@gemina/elements 0.5.0 → 0.5.2

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.
package/README.md CHANGED
@@ -156,6 +156,7 @@ import { GeminaChat } from "@gemina/elements";
156
156
  | `theme` | `"light" \| "dark" \| "auto"` | `"auto"` | `"auto"` follows `prefers-color-scheme`. |
157
157
  | `dir` | `"ltr" \| "rtl" \| "auto"` | `"auto"` | `"auto"` flips the widget to RTL when the user's latest message contains Hebrew; bubbles also self-resolve via `dir="auto"`. |
158
158
  | `placeholder` | `string` | `"Ask about your documents…"` | Input placeholder. |
159
+ | `title` | `string` | — | Header text — your brand or assistant persona (`"Acme Invoices"`, `"Gemina's AI Rep"`). When set, the header is always visible. |
159
160
  | `onCitationClick` | `(documentId: string) => void` | — | Called when a citation chip is clicked. |
160
161
  | `className` | `string` | — | Extra class(es) on the root (handy for CSS-variable overrides). |
161
162
 
package/dist/chat.cjs CHANGED
@@ -27,7 +27,7 @@ var import_react = require("react");
27
27
  var import_sdk = require("@gemina/sdk");
28
28
 
29
29
  // src/version.ts
30
- var VERSION = "0.5.0";
30
+ var VERSION = "0.5.2";
31
31
 
32
32
  // src/chat.tsx
33
33
  var import_jsx_runtime = require("react/jsx-runtime");
@@ -215,6 +215,14 @@ var CHAT_CSS = `
215
215
  padding: 6px 10px;
216
216
  border-bottom: 1px solid var(--gemina-chat-border);
217
217
  }
218
+ .gemina-chat__title {
219
+ margin-inline-end: auto;
220
+ font-size: 13px;
221
+ font-weight: 600;
222
+ overflow: hidden;
223
+ text-overflow: ellipsis;
224
+ white-space: nowrap;
225
+ }
218
226
  .gemina-chat__newchat {
219
227
  font: inherit;
220
228
  font-size: 12px;
@@ -303,10 +311,35 @@ var CHAT_CSS = `
303
311
  }
304
312
  .gemina-chat__typing {
305
313
  align-self: flex-start;
314
+ display: flex;
315
+ align-items: center;
316
+ gap: 5px;
306
317
  color: var(--gemina-chat-muted);
307
318
  font-size: 12px;
308
319
  padding: 0 4px;
309
320
  }
321
+ .gemina-chat__typing-dots {
322
+ display: inline-flex;
323
+ align-items: center;
324
+ gap: 3px;
325
+ }
326
+ .gemina-chat__typing-dots span {
327
+ width: 4px;
328
+ height: 4px;
329
+ border-radius: 50%;
330
+ background: currentColor;
331
+ opacity: 0.25;
332
+ animation: gemina-chat-thinking 1.2s infinite ease-in-out;
333
+ }
334
+ .gemina-chat__typing-dots span:nth-child(2) { animation-delay: 0.2s; }
335
+ .gemina-chat__typing-dots span:nth-child(3) { animation-delay: 0.4s; }
336
+ @keyframes gemina-chat-thinking {
337
+ 0%, 60%, 100% { opacity: 0.25; transform: translateY(0); }
338
+ 30% { opacity: 1; transform: translateY(-2px); }
339
+ }
340
+ @media (prefers-reduced-motion: reduce) {
341
+ .gemina-chat__typing-dots span { animation: none; opacity: 0.6; }
342
+ }
310
343
  .gemina-chat__composer {
311
344
  display: flex;
312
345
  gap: 8px;
@@ -361,6 +394,7 @@ function GeminaChat(props) {
361
394
  theme = "auto",
362
395
  dir = "auto",
363
396
  placeholder = "Ask about your documents\u2026",
397
+ title,
364
398
  onCitationClick,
365
399
  className
366
400
  } = props;
@@ -537,16 +571,19 @@ function GeminaChat(props) {
537
571
  className ?? ""
538
572
  ].filter((part) => part.length > 0).join(" ");
539
573
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: rootClassName, dir: effectiveDir, children: [
540
- messages.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "gemina-chat__header", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
541
- "button",
542
- {
543
- type: "button",
544
- className: "gemina-chat__newchat",
545
- onClick: startNewChat,
546
- disabled: busy,
547
- children: "New chat"
548
- }
549
- ) }),
574
+ (title !== void 0 || messages.length > 0) && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "gemina-chat__header", children: [
575
+ title !== void 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "gemina-chat__title", dir: bubbleDir, children: title }),
576
+ messages.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
577
+ "button",
578
+ {
579
+ type: "button",
580
+ className: "gemina-chat__newchat",
581
+ onClick: startNewChat,
582
+ disabled: busy,
583
+ children: "New chat"
584
+ }
585
+ )
586
+ ] }),
550
587
  /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
551
588
  "div",
552
589
  {
@@ -616,7 +653,16 @@ function GeminaChat(props) {
616
653
  message.id
617
654
  );
618
655
  }),
619
- busy && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "gemina-chat__typing", children: "Thinking\u2026" })
656
+ busy && // The label alone is what the aria-live log announces; the dots are
657
+ // decoration (aria-hidden), and prefers-reduced-motion freezes them.
658
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "gemina-chat__typing", children: [
659
+ "Thinking",
660
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "gemina-chat__typing-dots", "aria-hidden": "true", children: [
661
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {}),
662
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {}),
663
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {})
664
+ ] })
665
+ ] })
620
666
  ]
621
667
  }
622
668
  ),
package/dist/chat.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/chat.tsx","../src/version.ts"],"sourcesContent":["/**\n * <GeminaChat> — drop-in chat UI over Gemina Document Intelligence.\n *\n * Auth flows exclusively through a {@link GeminaTokenManager}: the component\n * asks it for a short-lived session token per turn and calls\n * `POST /v1/chat/query` through `@gemina/sdk`. It never sees — and cannot\n * accept — a Gemina API key (the token manager throws on API-key-shaped\n * credentials).\n *\n * SSR-safe: no `window`/`document` access at import time; styles are\n * injected on mount.\n */\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type * as React from 'react';\nimport { GeminaClient } from '@gemina/sdk';\nimport type { ChatQueryOutDTO } from '@gemina/sdk';\nimport type { GeminaTokenManager } from './token-manager';\nimport { VERSION } from './version';\n\n/** Visual theme. `\"auto\"` follows `prefers-color-scheme`. */\nexport type GeminaChatTheme = 'light' | 'dark' | 'auto';\n\n/**\n * Text direction. `\"auto\"` flips the widget to RTL when the user's latest\n * message contains Hebrew, and lets each bubble resolve its own direction.\n */\nexport type GeminaChatDirection = 'ltr' | 'rtl' | 'auto';\n\nexport interface GeminaChatProps {\n /** Token source. Required — see {@link GeminaTokenManager}. */\n tokenManager: GeminaTokenManager;\n /** Gemina API base URL (default `https://api.gemina.co`). */\n baseUrl?: string;\n /**\n * Optional end-user id forwarded with each query. On the session-token\n * path the token's SIGNED scope always wins server-side — this is a\n * hint, not a security control.\n */\n endUserId?: string;\n /** Visual theme (default `\"auto\"`). */\n theme?: GeminaChatTheme;\n /** Text direction (default `\"auto\"`). */\n dir?: GeminaChatDirection;\n /** Input placeholder text. */\n placeholder?: string;\n /** Called with the cited `documentId` when a citation chip is clicked. */\n onCitationClick?: (documentId: string) => void;\n /** Extra class name(s) for the root element (e.g. to override CSS vars). */\n className?: string;\n}\n\ninterface UserMessage {\n id: number;\n role: 'user';\n text: string;\n}\n\ninterface AssistantMessage {\n id: number;\n role: 'assistant';\n text: string;\n citations: string[];\n confident: boolean;\n}\n\ninterface ErrorMessage {\n id: number;\n role: 'error';\n text: string;\n /** Present only when a retry is offered; holds the original user text. */\n retryText?: string;\n}\n\ntype ChatMessage = UserMessage | AssistantMessage | ErrorMessage;\n\n/** `Omit` that distributes over each member of a union. */\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\n\ntype ChatMessageInput = DistributiveOmit<ChatMessage, 'id'>;\n\n/** Hebrew Unicode block (U+0590–U+05FF). */\nconst HEBREW_RE = /[\\u0590-\\u05FF]/;\n\n/**\n * The response-like object carried by a thrown transport error. We pull it off\n * by shape rather than `instanceof ResponseError` — robust against duplicated\n * `@gemina/sdk` copies in a bundle (class identity is not shared across\n * copies). On the fetch transport this is the raw `Response`, so `status`,\n * `headers`, and the JSON body are all reachable from here.\n */\ninterface ResponseLike {\n status?: number;\n headers?: { get?: (name: string) => string | null };\n json?: () => Promise<unknown>;\n clone?: () => ResponseLike;\n}\n\nfunction getResponseLike(error: unknown): ResponseLike | undefined {\n if (error !== null && typeof error === 'object' && 'response' in error) {\n const response = (error as { response?: unknown }).response;\n if (response !== null && typeof response === 'object') {\n return response as ResponseLike;\n }\n }\n return undefined;\n}\n\n/** Extract an HTTP status from a thrown value, or `undefined`. */\nfunction httpStatus(error: unknown): number | undefined {\n const status = getResponseLike(error)?.status;\n return typeof status === 'number' ? status : undefined;\n}\n\n// Stable backend error codes. These survive production's `detail`-stripping\n// (see the chat-pricing handoff); we switch on HTTP status first and refine\n// with these where the same status can mean two different things.\nconst ERR_CHAT_QUOTA_EXCEEDED = 'CHAT_QUOTA_EXCEEDED';\nconst ERR_DI_NOT_IN_PLAN = 'DOCUMENT_INTELLIGENCE_NOT_IN_PLAN';\nconst ERR_UNPROCESSABLE = 'UNPROCESSABLE_ERROR';\nconst ERR_BAD_GATEWAY = 'BAD_GATEWAY_ERROR';\n// A conversation id that the server no longer knows (24h idle TTL, explicit\n// reset, or end-user scope drift). A turn that CARRIED a session and 404s is\n// this by construction — the chat/query handler raises 404 for nothing else —\n// so the component drops the id and restarts the conversation transparently.\nconst ERR_CHAT_SESSION_NOT_FOUND = 'CHAT_SESSION_NOT_FOUND';\n\ninterface ChatErrorInfo {\n status: number | undefined;\n errorCode: string | undefined;\n /** Human-readable server fallback (`errors[0].description`). */\n description: string | undefined;\n /** Whole seconds until reset, from the `Retry-After` header (429). */\n retryAfterSeconds: number | undefined;\n}\n\n/**\n * Read what the backend actually sent on an error. Only the HTTP status, the\n * stable `errors[0].error_code` / `description`, and the `Retry-After` header\n * are reliable across environments — production strips `errors[0].detail`, so\n * we never touch it. The fetch body can be read once, so we clone defensively;\n * if that fails (non-JSON, empty, or already consumed) the status still stands.\n */\nasync function readChatError(error: unknown): Promise<ChatErrorInfo> {\n const response = getResponseLike(error);\n const info: ChatErrorInfo = {\n status: typeof response?.status === 'number' ? response.status : undefined,\n errorCode: undefined,\n description: undefined,\n retryAfterSeconds: undefined,\n };\n if (response === undefined) {\n return info;\n }\n\n const rawRetryAfter = response.headers?.get?.('retry-after');\n if (rawRetryAfter !== null && rawRetryAfter !== undefined) {\n const seconds = Number(rawRetryAfter);\n if (Number.isFinite(seconds) && seconds > 0) {\n info.retryAfterSeconds = seconds;\n }\n }\n\n let body: unknown;\n try {\n const source = typeof response.clone === 'function' ? response.clone() : response;\n body = typeof source.json === 'function' ? await source.json() : undefined;\n } catch {\n body = undefined;\n }\n if (body !== null && typeof body === 'object') {\n const errors = (body as { errors?: unknown }).errors;\n if (\n Array.isArray(errors) &&\n errors.length > 0 &&\n errors[0] !== null &&\n typeof errors[0] === 'object'\n ) {\n const first = errors[0] as { error_code?: unknown; description?: unknown };\n if (typeof first.error_code === 'string') {\n info.errorCode = first.error_code;\n }\n if (typeof first.description === 'string') {\n info.description = first.description;\n }\n }\n }\n return info;\n}\n\nconst SESSION_EXPIRED_TEXT = 'Session expired — please reload the page or sign in again.';\nconst CONVERSATION_RESET_TEXT =\n 'This conversation is no longer available — send your message again to start a new one.';\nconst RATE_LIMIT_TEXT = \"You're sending messages too quickly — try again shortly.\";\nconst PLAN_GATE_TEXT = \"Chat isn't included in your plan.\";\nconst UNANSWERABLE_TEXT = \"We couldn't answer that. Try rephrasing your question.\";\nconst SERVICE_UNAVAILABLE_TEXT = 'The chat service is temporarily unavailable. Please try again.';\nconst GENERIC_ERROR_TEXT = \"Something went wrong and your message wasn't answered.\";\n\n/** Friendly \"resets in about N days/hours/minutes\" from Retry-After seconds. */\nfunction formatResetHint(seconds: number | undefined): string {\n if (seconds === undefined || !Number.isFinite(seconds) || seconds <= 0) {\n return 'at the next billing cycle';\n }\n const days = Math.round(seconds / 86400);\n if (days >= 1) {\n return `in about ${days} day${days === 1 ? '' : 's'}`;\n }\n const hours = Math.round(seconds / 3600);\n if (hours >= 1) {\n return `in about ${hours} hour${hours === 1 ? '' : 's'}`;\n }\n const minutes = Math.max(1, Math.round(seconds / 60));\n return `in about ${minutes} minute${minutes === 1 ? '' : 's'}`;\n}\n\n/**\n * Map a chat error to the bubble we render. Switches on HTTP status, refined by\n * the stable backend `error_code`. `retryText` is set only when resending the\n * same text could plausibly succeed — never for quota / plan / validation\n * outcomes, where an identical retry would just fail the same way.\n */\nfunction describeChatError(info: ChatErrorInfo, originalText: string): ChatMessageInput {\n const { status, errorCode } = info;\n\n // Over the included cap AND out of credits — the chat is blocked. Retrying\n // won't help; point at the reset time from the Retry-After header.\n if (status === 429 && errorCode === ERR_CHAT_QUOTA_EXCEEDED) {\n return {\n role: 'error',\n text: `You've used your included chats and are out of credits. Included chats reset ${formatResetHint(\n info.retryAfterSeconds,\n )}.`,\n };\n }\n // Any other 429 is a transient rate limit — a retry after a moment is fine.\n if (status === 429) {\n return { role: 'error', text: RATE_LIMIT_TEXT, retryText: originalText };\n }\n // Document Intelligence not in the plan/contract. NOT an auth failure.\n if (status === 402 || status === 403 || errorCode === ERR_DI_NOT_IN_PLAN) {\n return { role: 'error', text: PLAN_GATE_TEXT };\n }\n // Session expired — only surfaces after the 401-invalidate-retry-once path\n // has already failed a second time.\n if (status === 401) {\n return { role: 'error', text: SESSION_EXPIRED_TEXT };\n }\n // A stale conversation id that slipped past the transparent restart — only\n // the stable error_code reliably means \"the conversation is gone\". A bare 404\n // is a routing/gateway miss (e.g. the endpoint isn't deployed), which reads\n // better as a transient service error than a confusing \"conversation reset\".\n if (errorCode === ERR_CHAT_SESSION_NOT_FOUND) {\n return { role: 'error', text: CONVERSATION_RESET_TEXT, retryText: originalText };\n }\n if (status === 404) {\n return { role: 'error', text: SERVICE_UNAVAILABLE_TEXT, retryText: originalText };\n }\n // The question couldn't be answered (e.g. no searchable text). Expected, not\n // a server error — invite a rephrase rather than a blind retry.\n if (status === 422 || errorCode === ERR_UNPROCESSABLE) {\n return { role: 'error', text: UNANSWERABLE_TEXT };\n }\n // Chat backend timed out / unreachable — transient, offer retry.\n if (status === 502 || errorCode === ERR_BAD_GATEWAY) {\n return { role: 'error', text: SERVICE_UNAVAILABLE_TEXT, retryText: originalText };\n }\n // Anything else (incl. 500): prefer the server's description if it sent one.\n return {\n role: 'error',\n text: info.description ?? GENERIC_ERROR_TEXT,\n retryText: originalText,\n };\n}\n\n/**\n * The API reports citations as an array of `documentId` strings; normalize\n * defensively so `{ documentId }` objects also work if the shape evolves.\n */\nfunction normalizeCitations(citations: unknown): string[] {\n if (!Array.isArray(citations)) {\n return [];\n }\n const ids: string[] = [];\n for (const item of citations) {\n if (typeof item === 'string' && item.length > 0) {\n ids.push(item);\n } else if (\n item !== null &&\n typeof item === 'object' &&\n typeof (item as { documentId?: unknown }).documentId === 'string'\n ) {\n ids.push((item as { documentId: string }).documentId);\n }\n }\n return ids;\n}\n\n// --- Styles -----------------------------------------------------------------\n// Hand-rolled, no UI deps. Everything is scoped under .gemina-chat and driven\n// by CSS custom properties so host apps can re-theme without touching the DOM.\n\nconst DARK_VARS = `\n --gemina-chat-bg: #101418;\n --gemina-chat-fg: #e6e9ee;\n --gemina-chat-border: #2a323c;\n --gemina-chat-accent: #4c8dff;\n --gemina-chat-accent-fg: #ffffff;\n --gemina-chat-assistant-bg: #1c232b;\n --gemina-chat-assistant-fg: #e6e9ee;\n --gemina-chat-muted: #98a2b3;\n --gemina-chat-error: #f97066;\n --gemina-chat-low-confidence: #f7b27a;\n`;\n\nconst CHAT_CSS = `\n.gemina-chat {\n --gemina-chat-bg: #ffffff;\n --gemina-chat-fg: #1a1d21;\n --gemina-chat-border: #d9dce1;\n --gemina-chat-accent: #2f6fed;\n --gemina-chat-accent-fg: #ffffff;\n --gemina-chat-assistant-bg: #f2f4f7;\n --gemina-chat-assistant-fg: #1a1d21;\n --gemina-chat-muted: #667085;\n --gemina-chat-error: #b42318;\n --gemina-chat-low-confidence: #b54708;\n --gemina-chat-radius: 10px;\n --gemina-chat-font: system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif;\n\n box-sizing: border-box;\n display: flex;\n flex-direction: column;\n min-height: 320px;\n max-height: 600px;\n background: var(--gemina-chat-bg);\n color: var(--gemina-chat-fg);\n border: 1px solid var(--gemina-chat-border);\n border-radius: var(--gemina-chat-radius);\n font-family: var(--gemina-chat-font);\n font-size: 14px;\n line-height: 1.5;\n}\n.gemina-chat *, .gemina-chat *::before, .gemina-chat *::after { box-sizing: border-box; }\n.gemina-chat--dark { ${DARK_VARS} }\n@media (prefers-color-scheme: dark) {\n .gemina-chat--auto { ${DARK_VARS} }\n}\n.gemina-chat__header {\n display: flex;\n justify-content: flex-end;\n align-items: center;\n flex: 0 0 auto;\n padding: 6px 10px;\n border-bottom: 1px solid var(--gemina-chat-border);\n}\n.gemina-chat__newchat {\n font: inherit;\n font-size: 12px;\n padding: 3px 10px;\n border-radius: var(--gemina-chat-radius);\n border: 1px solid var(--gemina-chat-border);\n background: transparent;\n color: var(--gemina-chat-accent);\n cursor: pointer;\n}\n.gemina-chat__newchat:hover:not(:disabled) { border-color: var(--gemina-chat-accent); }\n.gemina-chat__newchat:disabled { opacity: 0.5; cursor: default; }\n.gemina-chat__log {\n flex: 1;\n overflow-y: auto;\n padding: 12px;\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n.gemina-chat__msg {\n max-width: 85%;\n padding: 8px 12px;\n border-radius: var(--gemina-chat-radius);\n white-space: pre-wrap;\n overflow-wrap: break-word;\n}\n.gemina-chat__msg--user {\n align-self: flex-end;\n background: var(--gemina-chat-accent);\n color: var(--gemina-chat-accent-fg);\n}\n.gemina-chat--rtl .gemina-chat__msg--user, .gemina-chat[dir=\"rtl\"] .gemina-chat__msg--user {\n align-self: flex-start;\n}\n.gemina-chat--rtl .gemina-chat__msg--assistant, .gemina-chat[dir=\"rtl\"] .gemina-chat__msg--assistant {\n align-self: flex-end;\n}\n.gemina-chat__msg--assistant {\n align-self: flex-start;\n background: var(--gemina-chat-assistant-bg);\n color: var(--gemina-chat-assistant-fg);\n}\n.gemina-chat__msg--low-confidence {\n border: 1px dashed var(--gemina-chat-low-confidence);\n}\n.gemina-chat__low-confidence-note {\n margin-top: 6px;\n font-size: 12px;\n color: var(--gemina-chat-low-confidence);\n}\n.gemina-chat__citations {\n display: flex;\n flex-wrap: wrap;\n gap: 4px;\n margin-top: 6px;\n}\n.gemina-chat__citation {\n font: inherit;\n font-size: 12px;\n padding: 2px 8px;\n border-radius: 999px;\n border: 1px solid var(--gemina-chat-border);\n background: transparent;\n color: var(--gemina-chat-accent);\n cursor: pointer;\n}\n.gemina-chat__citation:hover { border-color: var(--gemina-chat-accent); }\n.gemina-chat__msg--error {\n align-self: flex-start;\n background: transparent;\n border: 1px solid var(--gemina-chat-error);\n color: var(--gemina-chat-error);\n}\n.gemina-chat__retry {\n font: inherit;\n font-size: 12px;\n margin-top: 6px;\n display: block;\n padding: 2px 10px;\n border-radius: var(--gemina-chat-radius);\n border: 1px solid var(--gemina-chat-error);\n background: transparent;\n color: var(--gemina-chat-error);\n cursor: pointer;\n}\n.gemina-chat__typing {\n align-self: flex-start;\n color: var(--gemina-chat-muted);\n font-size: 12px;\n padding: 0 4px;\n}\n.gemina-chat__composer {\n display: flex;\n gap: 8px;\n padding: 10px;\n border-top: 1px solid var(--gemina-chat-border);\n}\n.gemina-chat__input {\n flex: 1;\n resize: none;\n font: inherit;\n color: inherit;\n background: transparent;\n border: 1px solid var(--gemina-chat-border);\n border-radius: var(--gemina-chat-radius);\n padding: 8px 10px;\n min-height: 38px;\n}\n.gemina-chat__input:focus {\n outline: 2px solid var(--gemina-chat-accent);\n outline-offset: -1px;\n}\n.gemina-chat__send {\n font: inherit;\n align-self: flex-end;\n border: none;\n border-radius: var(--gemina-chat-radius);\n background: var(--gemina-chat-accent);\n color: var(--gemina-chat-accent-fg);\n padding: 8px 16px;\n cursor: pointer;\n}\n.gemina-chat__send:disabled { opacity: 0.5; cursor: default; }\n`;\n\nconst STYLE_ATTR = 'data-gemina-chat';\n\n/**\n * Inject the widget stylesheet once per document (idempotent across\n * instances; intentionally not removed on unmount so sibling instances and\n * quick remounts never flash unstyled).\n */\nfunction ensureStylesInjected(): void {\n if (typeof document === 'undefined') {\n return;\n }\n if (document.head.querySelector(`style[${STYLE_ATTR}]`) !== null) {\n return;\n }\n const style = document.createElement('style');\n style.setAttribute(STYLE_ATTR, VERSION);\n style.textContent = CHAT_CSS;\n document.head.appendChild(style);\n}\n\n/**\n * Embeddable Gemina Document Intelligence chat.\n *\n * ```tsx\n * <GeminaChat\n * tokenManager={tokenManager}\n * onCitationClick={(documentId) => openDocument(documentId)}\n * />\n * ```\n */\nexport function GeminaChat(props: GeminaChatProps): React.JSX.Element {\n const {\n tokenManager,\n baseUrl,\n endUserId,\n theme = 'auto',\n dir = 'auto',\n placeholder = 'Ask about your documents…',\n onCitationClick,\n className,\n } = props;\n\n const [messages, setMessages] = useState<ChatMessage[]>([]);\n const [draft, setDraft] = useState('');\n const [busy, setBusy] = useState(false);\n const nextIdRef = useRef(0);\n const mountedRef = useRef(false);\n const logRef = useRef<HTMLDivElement | null>(null);\n // The conversation id (server-issued) that gives the chat memory across\n // turns. Held in a ref, not state: it changes per turn but must never\n // trigger a re-render, and the send flow reads its latest value directly.\n // Distinct from the auth session TOKEN the token manager holds.\n const sessionIdRef = useRef<string | undefined>(undefined);\n\n useEffect(() => {\n mountedRef.current = true;\n ensureStylesInjected();\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n // Keep the newest message in view.\n useEffect(() => {\n const log = logRef.current;\n if (log !== null) {\n log.scrollTop = log.scrollHeight;\n }\n }, [messages, busy]);\n\n const appendMessage = useCallback((message: ChatMessageInput) => {\n const id = nextIdRef.current++;\n setMessages((prev) => [...prev, { ...message, id }]);\n }, []);\n\n const chatOnce = useCallback(\n (token: string, message: string): Promise<ChatQueryOutDTO> => {\n const client = GeminaClient.withSessionToken(token, baseUrl);\n const sessionId = sessionIdRef.current;\n return client.chat.chatQuery({\n // Thread the conversation id when we have one so follow-ups resolve\n // referents (\"what about the total?\"); omit it to start a new one.\n chatQueryInDTO: { message, endUserId, ...(sessionId ? { sessionId } : {}) },\n });\n },\n [baseUrl, endUserId],\n );\n\n /** One turn, with the mandated 401-invalidate-retry-once behavior. */\n const queryWithRetry = useCallback(\n async (message: string): Promise<ChatQueryOutDTO> => {\n const token = await tokenManager.getToken();\n try {\n return await chatOnce(token, message);\n } catch (error) {\n if (httpStatus(error) !== 401) {\n throw error;\n }\n // Token likely expired mid-session: drop it, re-mint via the\n // tenant backend, retry exactly once. A second 401 propagates.\n tokenManager.invalidate();\n const freshToken = await tokenManager.getToken();\n return await chatOnce(freshToken, message);\n }\n },\n [tokenManager, chatOnce],\n );\n\n const performSend = useCallback(\n async (text: string) => {\n setBusy(true);\n try {\n let result: ChatQueryOutDTO;\n const hadSession = sessionIdRef.current !== undefined;\n try {\n result = await queryWithRetry(text);\n } catch (error) {\n // A turn that CARRIED a session and 404s means the conversation is\n // gone (24h idle TTL, an explicit reset, or end-user scope drift).\n // Drop the stale id and retry once as a fresh conversation, so the\n // expiry is transparent — the user just gets an answer, no memory.\n if (hadSession && httpStatus(error) === 404) {\n sessionIdRef.current = undefined;\n result = await queryWithRetry(text);\n } else {\n throw error;\n }\n }\n if (!mountedRef.current) {\n return;\n }\n // The response always returns the (possibly newly created) conversation\n // id — store it so the next turn continues this thread.\n sessionIdRef.current = result.sessionId ?? sessionIdRef.current;\n appendMessage({\n role: 'assistant',\n text: result.answer,\n citations: normalizeCitations(result.citations),\n confident: result.confident !== false,\n });\n } catch (error) {\n if (!mountedRef.current) {\n return;\n }\n // Reading the error body is async (fetch), so re-check mount after.\n const info = await readChatError(error);\n if (!mountedRef.current) {\n return;\n }\n appendMessage(describeChatError(info, text));\n } finally {\n if (mountedRef.current) {\n setBusy(false);\n }\n }\n },\n [queryWithRetry, appendMessage],\n );\n\n /**\n * Reset to a brand-new conversation: clear the transcript and forget the\n * session id so the next message starts fresh. The old session is deleted\n * server-side best-effort — the local reset is authoritative, and a failed\n * delete just leaves the session to lapse on its idle TTL.\n */\n const startNewChat = useCallback(() => {\n if (busy) {\n return;\n }\n const staleSession = sessionIdRef.current;\n sessionIdRef.current = undefined;\n setMessages([]);\n setDraft('');\n if (staleSession !== undefined) {\n void (async () => {\n try {\n const token = await tokenManager.getToken();\n await GeminaClient.withSessionToken(token, baseUrl).chat.deleteChatSession({\n sessionId: staleSession,\n });\n } catch {\n // Unreachable/expired session: nothing to clean up client-side.\n }\n })();\n }\n }, [busy, tokenManager, baseUrl]);\n\n const submitDraft = useCallback(() => {\n const text = draft.trim();\n if (text.length === 0 || busy) {\n return;\n }\n setDraft('');\n appendMessage({ role: 'user', text });\n void performSend(text);\n }, [draft, busy, appendMessage, performSend]);\n\n const retryMessage = useCallback(\n (failed: ErrorMessage) => {\n if (busy || failed.retryText === undefined) {\n return;\n }\n const text = failed.retryText;\n // Replace the error entry; the original user bubble is still there.\n setMessages((prev) => prev.filter((message) => message.id !== failed.id));\n void performSend(text);\n },\n [busy, performSend],\n );\n\n const handleKeyDown = useCallback(\n (event: React.KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.key === 'Enter' && !event.shiftKey) {\n event.preventDefault();\n submitDraft();\n }\n },\n [submitDraft],\n );\n\n const handleSubmit = useCallback(\n (event: React.FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n submitDraft();\n },\n [submitDraft],\n );\n\n // dir=\"auto\": follow the user's latest message (Hebrew → RTL); individual\n // bubbles additionally resolve their own direction via dir=\"auto\".\n let effectiveDir: 'ltr' | 'rtl';\n if (dir === 'auto') {\n let lastUserText = '';\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (message !== undefined && message.role === 'user') {\n lastUserText = message.text;\n break;\n }\n }\n effectiveDir = HEBREW_RE.test(lastUserText) ? 'rtl' : 'ltr';\n } else {\n effectiveDir = dir;\n }\n const bubbleDir = dir === 'auto' ? 'auto' : undefined;\n\n const rootClassName = [\n 'gemina-chat',\n `gemina-chat--${theme}`,\n effectiveDir === 'rtl' ? 'gemina-chat--rtl' : '',\n className ?? '',\n ]\n .filter((part) => part.length > 0)\n .join(' ');\n\n return (\n <div className={rootClassName} dir={effectiveDir}>\n {messages.length > 0 && (\n <div className=\"gemina-chat__header\">\n <button\n type=\"button\"\n className=\"gemina-chat__newchat\"\n onClick={startNewChat}\n disabled={busy}\n >\n New chat\n </button>\n </div>\n )}\n <div\n ref={logRef}\n role=\"log\"\n aria-live=\"polite\"\n aria-busy={busy}\n aria-label=\"Chat messages\"\n className=\"gemina-chat__log\"\n >\n {messages.map((message) => {\n if (message.role === 'user') {\n return (\n <div\n key={message.id}\n className=\"gemina-chat__msg gemina-chat__msg--user\"\n dir={bubbleDir}\n >\n {message.text}\n </div>\n );\n }\n if (message.role === 'assistant') {\n const lowConfidence = !message.confident;\n return (\n <div\n key={message.id}\n className={\n 'gemina-chat__msg gemina-chat__msg--assistant' +\n (lowConfidence ? ' gemina-chat__msg--low-confidence' : '')\n }\n dir={bubbleDir}\n >\n {message.text}\n {lowConfidence && (\n <div className=\"gemina-chat__low-confidence-note\">\n Low confidence — please verify against the cited documents.\n </div>\n )}\n {message.citations.length > 0 && (\n <div className=\"gemina-chat__citations\">\n {message.citations.map((documentId, index) => (\n <button\n key={`${documentId}-${index}`}\n type=\"button\"\n className=\"gemina-chat__citation\"\n title={`Open document ${documentId}`}\n onClick={() => onCitationClick?.(documentId)}\n >\n {documentId}\n </button>\n ))}\n </div>\n )}\n </div>\n );\n }\n return (\n <div\n key={message.id}\n role=\"alert\"\n className=\"gemina-chat__msg gemina-chat__msg--error\"\n >\n {message.text}\n {message.retryText !== undefined && (\n <button\n type=\"button\"\n className=\"gemina-chat__retry\"\n onClick={() => retryMessage(message)}\n >\n Retry\n </button>\n )}\n </div>\n );\n })}\n {busy && <div className=\"gemina-chat__typing\">Thinking…</div>}\n </div>\n <form className=\"gemina-chat__composer\" onSubmit={handleSubmit}>\n <textarea\n className=\"gemina-chat__input\"\n aria-label=\"Chat message\"\n rows={1}\n value={draft}\n placeholder={placeholder}\n dir={bubbleDir}\n onChange={(event) => setDraft(event.target.value)}\n onKeyDown={handleKeyDown}\n />\n <button\n type=\"submit\"\n className=\"gemina-chat__send\"\n aria-label=\"Send message\"\n disabled={busy || draft.trim().length === 0}\n >\n Send\n </button>\n </form>\n </div>\n );\n}\n","/** Package version. Keep in sync with package.json. */\nexport const VERSION = '0.5.0';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAYA,mBAAyD;AAEzD,iBAA6B;;;ACbtB,IAAM,UAAU;;;ADmuBb;AAnpBV,IAAM,YAAY;AAgBlB,SAAS,gBAAgB,OAA0C;AACjE,MAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,cAAc,OAAO;AACtE,UAAM,WAAY,MAAiC;AACnD,QAAI,aAAa,QAAQ,OAAO,aAAa,UAAU;AACrD,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;AAGA,SAAS,WAAW,OAAoC;AACtD,QAAM,SAAS,gBAAgB,KAAK,GAAG;AACvC,SAAO,OAAO,WAAW,WAAW,SAAS;AAC/C;AAKA,IAAM,0BAA0B;AAChC,IAAM,qBAAqB;AAC3B,IAAM,oBAAoB;AAC1B,IAAM,kBAAkB;AAKxB,IAAM,6BAA6B;AAkBnC,eAAe,cAAc,OAAwC;AACnE,QAAM,WAAW,gBAAgB,KAAK;AACtC,QAAM,OAAsB;AAAA,IAC1B,QAAQ,OAAO,UAAU,WAAW,WAAW,SAAS,SAAS;AAAA,IACjE,WAAW;AAAA,IACX,aAAa;AAAA,IACb,mBAAmB;AAAA,EACrB;AACA,MAAI,aAAa,QAAW;AAC1B,WAAO;AAAA,EACT;AAEA,QAAM,gBAAgB,SAAS,SAAS,MAAM,aAAa;AAC3D,MAAI,kBAAkB,QAAQ,kBAAkB,QAAW;AACzD,UAAM,UAAU,OAAO,aAA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,YAcf;AAAA,UAEJ,CAAC;AAAA,UACA,QAAQ,4CAAC,SAAI,WAAU,uBAAsB,4BAAS;AAAA;AAAA;AAAA,IACzD;AAAA,IACA,6CAAC,UAAK,WAAU,yBAAwB,UAAU,cAChD;AAAA;AAAA,QAAC;AAAA;AAAA,UACC,WAAU;AAAA,UACV,cAAW;AAAA,UACX,MAAM;AAAA,UACN,OAAO;AAAA,UACP;AAAA,UACA,KAAK;AAAA,UACL,UAAU,CAAC,UAAU,SAAS,MAAM,OAAO,KAAK;AAAA,UAChD,WAAW;AAAA;AAAA,MACb;AAAA,MACA;AAAA,QAAC;AAAA;AAAA,UACC,MAAK;AAAA,UACL,WAAU;AAAA,UACV,cAAW;AAAA,UACX,UAAU,QAAQ,MAAM,KAAK,EAAE,WAAW;AAAA,UAC3C;AAAA;AAAA,MAED;AAAA,OACF;AAAA,KACF;AAEJ;","names":[]}
1
+ {"version":3,"sources":["../src/chat.tsx","../src/version.ts"],"sourcesContent":["/**\n * <GeminaChat> — drop-in chat UI over Gemina Document Intelligence.\n *\n * Auth flows exclusively through a {@link GeminaTokenManager}: the component\n * asks it for a short-lived session token per turn and calls\n * `POST /v1/chat/query` through `@gemina/sdk`. It never sees — and cannot\n * accept — a Gemina API key (the token manager throws on API-key-shaped\n * credentials).\n *\n * SSR-safe: no `window`/`document` access at import time; styles are\n * injected on mount.\n */\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type * as React from 'react';\nimport { GeminaClient } from '@gemina/sdk';\nimport type { ChatQueryOutDTO } from '@gemina/sdk';\nimport type { GeminaTokenManager } from './token-manager';\nimport { VERSION } from './version';\n\n/** Visual theme. `\"auto\"` follows `prefers-color-scheme`. */\nexport type GeminaChatTheme = 'light' | 'dark' | 'auto';\n\n/**\n * Text direction. `\"auto\"` flips the widget to RTL when the user's latest\n * message contains Hebrew, and lets each bubble resolve its own direction.\n */\nexport type GeminaChatDirection = 'ltr' | 'rtl' | 'auto';\n\nexport interface GeminaChatProps {\n /** Token source. Required — see {@link GeminaTokenManager}. */\n tokenManager: GeminaTokenManager;\n /** Gemina API base URL (default `https://api.gemina.co`). */\n baseUrl?: string;\n /**\n * Optional end-user id forwarded with each query. On the session-token\n * path the token's SIGNED scope always wins server-side — this is a\n * hint, not a security control.\n */\n endUserId?: string;\n /** Visual theme (default `\"auto\"`). */\n theme?: GeminaChatTheme;\n /** Text direction (default `\"auto\"`). */\n dir?: GeminaChatDirection;\n /** Input placeholder text. */\n placeholder?: string;\n /**\n * Header text — whatever identity the embedding platform wants the chat\n * to carry: a brand (\"Acme Invoices\"), an assistant persona (\"Gemina's\n * AI Rep\"), anything. Text only, rendered verbatim. When set, the header\n * is always visible; without it the header appears only once a\n * conversation has started (to host \"New chat\"). Colors and fonts are\n * themeable separately via the `--gemina-chat-*` CSS variables.\n */\n title?: string;\n /** Called with the cited `documentId` when a citation chip is clicked. */\n onCitationClick?: (documentId: string) => void;\n /** Extra class name(s) for the root element (e.g. to override CSS vars). */\n className?: string;\n}\n\ninterface UserMessage {\n id: number;\n role: 'user';\n text: string;\n}\n\ninterface AssistantMessage {\n id: number;\n role: 'assistant';\n text: string;\n citations: string[];\n confident: boolean;\n}\n\ninterface ErrorMessage {\n id: number;\n role: 'error';\n text: string;\n /** Present only when a retry is offered; holds the original user text. */\n retryText?: string;\n}\n\ntype ChatMessage = UserMessage | AssistantMessage | ErrorMessage;\n\n/** `Omit` that distributes over each member of a union. */\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\n\ntype ChatMessageInput = DistributiveOmit<ChatMessage, 'id'>;\n\n/** Hebrew Unicode block (U+0590–U+05FF). */\nconst HEBREW_RE = /[\\u0590-\\u05FF]/;\n\n/**\n * The response-like object carried by a thrown transport error. We pull it off\n * by shape rather than `instanceof ResponseError` — robust against duplicated\n * `@gemina/sdk` copies in a bundle (class identity is not shared across\n * copies). On the fetch transport this is the raw `Response`, so `status`,\n * `headers`, and the JSON body are all reachable from here.\n */\ninterface ResponseLike {\n status?: number;\n headers?: { get?: (name: string) => string | null };\n json?: () => Promise<unknown>;\n clone?: () => ResponseLike;\n}\n\nfunction getResponseLike(error: unknown): ResponseLike | undefined {\n if (error !== null && typeof error === 'object' && 'response' in error) {\n const response = (error as { response?: unknown }).response;\n if (response !== null && typeof response === 'object') {\n return response as ResponseLike;\n }\n }\n return undefined;\n}\n\n/** Extract an HTTP status from a thrown value, or `undefined`. */\nfunction httpStatus(error: unknown): number | undefined {\n const status = getResponseLike(error)?.status;\n return typeof status === 'number' ? status : undefined;\n}\n\n// Stable backend error codes. These survive production's `detail`-stripping\n// (see the chat-pricing handoff); we switch on HTTP status first and refine\n// with these where the same status can mean two different things.\nconst ERR_CHAT_QUOTA_EXCEEDED = 'CHAT_QUOTA_EXCEEDED';\nconst ERR_DI_NOT_IN_PLAN = 'DOCUMENT_INTELLIGENCE_NOT_IN_PLAN';\nconst ERR_UNPROCESSABLE = 'UNPROCESSABLE_ERROR';\nconst ERR_BAD_GATEWAY = 'BAD_GATEWAY_ERROR';\n// A conversation id that the server no longer knows (24h idle TTL, explicit\n// reset, or end-user scope drift). A turn that CARRIED a session and 404s is\n// this by construction — the chat/query handler raises 404 for nothing else —\n// so the component drops the id and restarts the conversation transparently.\nconst ERR_CHAT_SESSION_NOT_FOUND = 'CHAT_SESSION_NOT_FOUND';\n\ninterface ChatErrorInfo {\n status: number | undefined;\n errorCode: string | undefined;\n /** Human-readable server fallback (`errors[0].description`). */\n description: string | undefined;\n /** Whole seconds until reset, from the `Retry-After` header (429). */\n retryAfterSeconds: number | undefined;\n}\n\n/**\n * Read what the backend actually sent on an error. Only the HTTP status, the\n * stable `errors[0].error_code` / `description`, and the `Retry-After` header\n * are reliable across environments — production strips `errors[0].detail`, so\n * we never touch it. The fetch body can be read once, so we clone defensively;\n * if that fails (non-JSON, empty, or already consumed) the status still stands.\n */\nasync function readChatError(error: unknown): Promise<ChatErrorInfo> {\n const response = getResponseLike(error);\n const info: ChatErrorInfo = {\n status: typeof response?.status === 'number' ? response.status : undefined,\n errorCode: undefined,\n description: undefined,\n retryAfterSeconds: undefined,\n };\n if (response === undefined) {\n return info;\n }\n\n const rawRetryAfter = response.headers?.get?.('retry-after');\n if (rawRetryAfter !== null && rawRetryAfter !== undefined) {\n const seconds = Number(rawRetryAfter);\n if (Number.isFinite(seconds) && seconds > 0) {\n info.retryAfterSeconds = seconds;\n }\n }\n\n let body: unknown;\n try {\n const source = typeof response.clone === 'function' ? response.clone() : response;\n body = typeof source.json === 'function' ? await source.json() : undefined;\n } catch {\n body = undefined;\n }\n if (body !== null && typeof body === 'object') {\n const errors = (body as { errors?: unknown }).errors;\n if (\n Array.isArray(errors) &&\n errors.length > 0 &&\n errors[0] !== null &&\n typeof errors[0] === 'object'\n ) {\n const first = errors[0] as { error_code?: unknown; description?: unknown };\n if (typeof first.error_code === 'string') {\n info.errorCode = first.error_code;\n }\n if (typeof first.description === 'string') {\n info.description = first.description;\n }\n }\n }\n return info;\n}\n\nconst SESSION_EXPIRED_TEXT = 'Session expired — please reload the page or sign in again.';\nconst CONVERSATION_RESET_TEXT =\n 'This conversation is no longer available — send your message again to start a new one.';\nconst RATE_LIMIT_TEXT = \"You're sending messages too quickly — try again shortly.\";\nconst PLAN_GATE_TEXT = \"Chat isn't included in your plan.\";\nconst UNANSWERABLE_TEXT = \"We couldn't answer that. Try rephrasing your question.\";\nconst SERVICE_UNAVAILABLE_TEXT = 'The chat service is temporarily unavailable. Please try again.';\nconst GENERIC_ERROR_TEXT = \"Something went wrong and your message wasn't answered.\";\n\n/** Friendly \"resets in about N days/hours/minutes\" from Retry-After seconds. */\nfunction formatResetHint(seconds: number | undefined): string {\n if (seconds === undefined || !Number.isFinite(seconds) || seconds <= 0) {\n return 'at the next billing cycle';\n }\n const days = Math.round(seconds / 86400);\n if (days >= 1) {\n return `in about ${days} day${days === 1 ? '' : 's'}`;\n }\n const hours = Math.round(seconds / 3600);\n if (hours >= 1) {\n return `in about ${hours} hour${hours === 1 ? '' : 's'}`;\n }\n const minutes = Math.max(1, Math.round(seconds / 60));\n return `in about ${minutes} minute${minutes === 1 ? '' : 's'}`;\n}\n\n/**\n * Map a chat error to the bubble we render. Switches on HTTP status, refined by\n * the stable backend `error_code`. `retryText` is set only when resending the\n * same text could plausibly succeed — never for quota / plan / validation\n * outcomes, where an identical retry would just fail the same way.\n */\nfunction describeChatError(info: ChatErrorInfo, originalText: string): ChatMessageInput {\n const { status, errorCode } = info;\n\n // Over the included cap AND out of credits — the chat is blocked. Retrying\n // won't help; point at the reset time from the Retry-After header.\n if (status === 429 && errorCode === ERR_CHAT_QUOTA_EXCEEDED) {\n return {\n role: 'error',\n text: `You've used your included chats and are out of credits. Included chats reset ${formatResetHint(\n info.retryAfterSeconds,\n )}.`,\n };\n }\n // Any other 429 is a transient rate limit — a retry after a moment is fine.\n if (status === 429) {\n return { role: 'error', text: RATE_LIMIT_TEXT, retryText: originalText };\n }\n // Document Intelligence not in the plan/contract. NOT an auth failure.\n if (status === 402 || status === 403 || errorCode === ERR_DI_NOT_IN_PLAN) {\n return { role: 'error', text: PLAN_GATE_TEXT };\n }\n // Session expired — only surfaces after the 401-invalidate-retry-once path\n // has already failed a second time.\n if (status === 401) {\n return { role: 'error', text: SESSION_EXPIRED_TEXT };\n }\n // A stale conversation id that slipped past the transparent restart — only\n // the stable error_code reliably means \"the conversation is gone\". A bare 404\n // is a routing/gateway miss (e.g. the endpoint isn't deployed), which reads\n // better as a transient service error than a confusing \"conversation reset\".\n if (errorCode === ERR_CHAT_SESSION_NOT_FOUND) {\n return { role: 'error', text: CONVERSATION_RESET_TEXT, retryText: originalText };\n }\n if (status === 404) {\n return { role: 'error', text: SERVICE_UNAVAILABLE_TEXT, retryText: originalText };\n }\n // The question couldn't be answered (e.g. no searchable text). Expected, not\n // a server error — invite a rephrase rather than a blind retry.\n if (status === 422 || errorCode === ERR_UNPROCESSABLE) {\n return { role: 'error', text: UNANSWERABLE_TEXT };\n }\n // Chat backend timed out / unreachable — transient, offer retry.\n if (status === 502 || errorCode === ERR_BAD_GATEWAY) {\n return { role: 'error', text: SERVICE_UNAVAILABLE_TEXT, retryText: originalText };\n }\n // Anything else (incl. 500): prefer the server's description if it sent one.\n return {\n role: 'error',\n text: info.description ?? GENERIC_ERROR_TEXT,\n retryText: originalText,\n };\n}\n\n/**\n * The API reports citations as an array of `documentId` strings; normalize\n * defensively so `{ documentId }` objects also work if the shape evolves.\n */\nfunction normalizeCitations(citations: unknown): string[] {\n if (!Array.isArray(citations)) {\n return [];\n }\n const ids: string[] = [];\n for (const item of citations) {\n if (typeof item === 'string' && item.length > 0) {\n ids.push(item);\n } else if (\n item !== null &&\n typeof item === 'object' &&\n typeof (item as { documentId?: unknown }).documentId === 'string'\n ) {\n ids.push((item as { documentId: string }).documentId);\n }\n }\n return ids;\n}\n\n// --- Styles -----------------------------------------------------------------\n// Hand-rolled, no UI deps. Everything is scoped under .gemina-chat and driven\n// by CSS custom properties so host apps can re-theme without touching the DOM.\n\nconst DARK_VARS = `\n --gemina-chat-bg: #101418;\n --gemina-chat-fg: #e6e9ee;\n --gemina-chat-border: #2a323c;\n --gemina-chat-accent: #4c8dff;\n --gemina-chat-accent-fg: #ffffff;\n --gemina-chat-assistant-bg: #1c232b;\n --gemina-chat-assistant-fg: #e6e9ee;\n --gemina-chat-muted: #98a2b3;\n --gemina-chat-error: #f97066;\n --gemina-chat-low-confidence: #f7b27a;\n`;\n\nconst CHAT_CSS = `\n.gemina-chat {\n --gemina-chat-bg: #ffffff;\n --gemina-chat-fg: #1a1d21;\n --gemina-chat-border: #d9dce1;\n --gemina-chat-accent: #2f6fed;\n --gemina-chat-accent-fg: #ffffff;\n --gemina-chat-assistant-bg: #f2f4f7;\n --gemina-chat-assistant-fg: #1a1d21;\n --gemina-chat-muted: #667085;\n --gemina-chat-error: #b42318;\n --gemina-chat-low-confidence: #b54708;\n --gemina-chat-radius: 10px;\n --gemina-chat-font: system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif;\n\n box-sizing: border-box;\n display: flex;\n flex-direction: column;\n min-height: 320px;\n max-height: 600px;\n background: var(--gemina-chat-bg);\n color: var(--gemina-chat-fg);\n border: 1px solid var(--gemina-chat-border);\n border-radius: var(--gemina-chat-radius);\n font-family: var(--gemina-chat-font);\n font-size: 14px;\n line-height: 1.5;\n}\n.gemina-chat *, .gemina-chat *::before, .gemina-chat *::after { box-sizing: border-box; }\n.gemina-chat--dark { ${DARK_VARS} }\n@media (prefers-color-scheme: dark) {\n .gemina-chat--auto { ${DARK_VARS} }\n}\n.gemina-chat__header {\n display: flex;\n justify-content: flex-end;\n align-items: center;\n flex: 0 0 auto;\n padding: 6px 10px;\n border-bottom: 1px solid var(--gemina-chat-border);\n}\n.gemina-chat__title {\n margin-inline-end: auto;\n font-size: 13px;\n font-weight: 600;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n.gemina-chat__newchat {\n font: inherit;\n font-size: 12px;\n padding: 3px 10px;\n border-radius: var(--gemina-chat-radius);\n border: 1px solid var(--gemina-chat-border);\n background: transparent;\n color: var(--gemina-chat-accent);\n cursor: pointer;\n}\n.gemina-chat__newchat:hover:not(:disabled) { border-color: var(--gemina-chat-accent); }\n.gemina-chat__newchat:disabled { opacity: 0.5; cursor: default; }\n.gemina-chat__log {\n flex: 1;\n overflow-y: auto;\n padding: 12px;\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n.gemina-chat__msg {\n max-width: 85%;\n padding: 8px 12px;\n border-radius: var(--gemina-chat-radius);\n white-space: pre-wrap;\n overflow-wrap: break-word;\n}\n.gemina-chat__msg--user {\n align-self: flex-end;\n background: var(--gemina-chat-accent);\n color: var(--gemina-chat-accent-fg);\n}\n.gemina-chat--rtl .gemina-chat__msg--user, .gemina-chat[dir=\"rtl\"] .gemina-chat__msg--user {\n align-self: flex-start;\n}\n.gemina-chat--rtl .gemina-chat__msg--assistant, .gemina-chat[dir=\"rtl\"] .gemina-chat__msg--assistant {\n align-self: flex-end;\n}\n.gemina-chat__msg--assistant {\n align-self: flex-start;\n background: var(--gemina-chat-assistant-bg);\n color: var(--gemina-chat-assistant-fg);\n}\n.gemina-chat__msg--low-confidence {\n border: 1px dashed var(--gemina-chat-low-confidence);\n}\n.gemina-chat__low-confidence-note {\n margin-top: 6px;\n font-size: 12px;\n color: var(--gemina-chat-low-confidence);\n}\n.gemina-chat__citations {\n display: flex;\n flex-wrap: wrap;\n gap: 4px;\n margin-top: 6px;\n}\n.gemina-chat__citation {\n font: inherit;\n font-size: 12px;\n padding: 2px 8px;\n border-radius: 999px;\n border: 1px solid var(--gemina-chat-border);\n background: transparent;\n color: var(--gemina-chat-accent);\n cursor: pointer;\n}\n.gemina-chat__citation:hover { border-color: var(--gemina-chat-accent); }\n.gemina-chat__msg--error {\n align-self: flex-start;\n background: transparent;\n border: 1px solid var(--gemina-chat-error);\n color: var(--gemina-chat-error);\n}\n.gemina-chat__retry {\n font: inherit;\n font-size: 12px;\n margin-top: 6px;\n display: block;\n padding: 2px 10px;\n border-radius: var(--gemina-chat-radius);\n border: 1px solid var(--gemina-chat-error);\n background: transparent;\n color: var(--gemina-chat-error);\n cursor: pointer;\n}\n.gemina-chat__typing {\n align-self: flex-start;\n display: flex;\n align-items: center;\n gap: 5px;\n color: var(--gemina-chat-muted);\n font-size: 12px;\n padding: 0 4px;\n}\n.gemina-chat__typing-dots {\n display: inline-flex;\n align-items: center;\n gap: 3px;\n}\n.gemina-chat__typing-dots span {\n width: 4px;\n height: 4px;\n border-radius: 50%;\n background: currentColor;\n opacity: 0.25;\n animation: gemina-chat-thinking 1.2s infinite ease-in-out;\n}\n.gemina-chat__typing-dots span:nth-child(2) { animation-delay: 0.2s; }\n.gemina-chat__typing-dots span:nth-child(3) { animation-delay: 0.4s; }\n@keyframes gemina-chat-thinking {\n 0%, 60%, 100% { opacity: 0.25; transform: translateY(0); }\n 30% { opacity: 1; transform: translateY(-2px); }\n}\n@media (prefers-reduced-motion: reduce) {\n .gemina-chat__typing-dots span { animation: none; opacity: 0.6; }\n}\n.gemina-chat__composer {\n display: flex;\n gap: 8px;\n padding: 10px;\n border-top: 1px solid var(--gemina-chat-border);\n}\n.gemina-chat__input {\n flex: 1;\n resize: none;\n font: inherit;\n color: inherit;\n background: transparent;\n border: 1px solid var(--gemina-chat-border);\n border-radius: var(--gemina-chat-radius);\n padding: 8px 10px;\n min-height: 38px;\n}\n.gemina-chat__input:focus {\n outline: 2px solid var(--gemina-chat-accent);\n outline-offset: -1px;\n}\n.gemina-chat__send {\n font: inherit;\n align-self: flex-end;\n border: none;\n border-radius: var(--gemina-chat-radius);\n background: var(--gemina-chat-accent);\n color: var(--gemina-chat-accent-fg);\n padding: 8px 16px;\n cursor: pointer;\n}\n.gemina-chat__send:disabled { opacity: 0.5; cursor: default; }\n`;\n\nconst STYLE_ATTR = 'data-gemina-chat';\n\n/**\n * Inject the widget stylesheet once per document (idempotent across\n * instances; intentionally not removed on unmount so sibling instances and\n * quick remounts never flash unstyled).\n */\nfunction ensureStylesInjected(): void {\n if (typeof document === 'undefined') {\n return;\n }\n if (document.head.querySelector(`style[${STYLE_ATTR}]`) !== null) {\n return;\n }\n const style = document.createElement('style');\n style.setAttribute(STYLE_ATTR, VERSION);\n style.textContent = CHAT_CSS;\n document.head.appendChild(style);\n}\n\n/**\n * Embeddable Gemina Document Intelligence chat.\n *\n * ```tsx\n * <GeminaChat\n * tokenManager={tokenManager}\n * onCitationClick={(documentId) => openDocument(documentId)}\n * />\n * ```\n */\nexport function GeminaChat(props: GeminaChatProps): React.JSX.Element {\n const {\n tokenManager,\n baseUrl,\n endUserId,\n theme = 'auto',\n dir = 'auto',\n placeholder = 'Ask about your documents…',\n title,\n onCitationClick,\n className,\n } = props;\n\n const [messages, setMessages] = useState<ChatMessage[]>([]);\n const [draft, setDraft] = useState('');\n const [busy, setBusy] = useState(false);\n const nextIdRef = useRef(0);\n const mountedRef = useRef(false);\n const logRef = useRef<HTMLDivElement | null>(null);\n // The conversation id (server-issued) that gives the chat memory across\n // turns. Held in a ref, not state: it changes per turn but must never\n // trigger a re-render, and the send flow reads its latest value directly.\n // Distinct from the auth session TOKEN the token manager holds.\n const sessionIdRef = useRef<string | undefined>(undefined);\n\n useEffect(() => {\n mountedRef.current = true;\n ensureStylesInjected();\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n // Keep the newest message in view.\n useEffect(() => {\n const log = logRef.current;\n if (log !== null) {\n log.scrollTop = log.scrollHeight;\n }\n }, [messages, busy]);\n\n const appendMessage = useCallback((message: ChatMessageInput) => {\n const id = nextIdRef.current++;\n setMessages((prev) => [...prev, { ...message, id }]);\n }, []);\n\n const chatOnce = useCallback(\n (token: string, message: string): Promise<ChatQueryOutDTO> => {\n const client = GeminaClient.withSessionToken(token, baseUrl);\n const sessionId = sessionIdRef.current;\n return client.chat.chatQuery({\n // Thread the conversation id when we have one so follow-ups resolve\n // referents (\"what about the total?\"); omit it to start a new one.\n chatQueryInDTO: { message, endUserId, ...(sessionId ? { sessionId } : {}) },\n });\n },\n [baseUrl, endUserId],\n );\n\n /** One turn, with the mandated 401-invalidate-retry-once behavior. */\n const queryWithRetry = useCallback(\n async (message: string): Promise<ChatQueryOutDTO> => {\n const token = await tokenManager.getToken();\n try {\n return await chatOnce(token, message);\n } catch (error) {\n if (httpStatus(error) !== 401) {\n throw error;\n }\n // Token likely expired mid-session: drop it, re-mint via the\n // tenant backend, retry exactly once. A second 401 propagates.\n tokenManager.invalidate();\n const freshToken = await tokenManager.getToken();\n return await chatOnce(freshToken, message);\n }\n },\n [tokenManager, chatOnce],\n );\n\n const performSend = useCallback(\n async (text: string) => {\n setBusy(true);\n try {\n let result: ChatQueryOutDTO;\n const hadSession = sessionIdRef.current !== undefined;\n try {\n result = await queryWithRetry(text);\n } catch (error) {\n // A turn that CARRIED a session and 404s means the conversation is\n // gone (24h idle TTL, an explicit reset, or end-user scope drift).\n // Drop the stale id and retry once as a fresh conversation, so the\n // expiry is transparent — the user just gets an answer, no memory.\n if (hadSession && httpStatus(error) === 404) {\n sessionIdRef.current = undefined;\n result = await queryWithRetry(text);\n } else {\n throw error;\n }\n }\n if (!mountedRef.current) {\n return;\n }\n // The response always returns the (possibly newly created) conversation\n // id — store it so the next turn continues this thread.\n sessionIdRef.current = result.sessionId ?? sessionIdRef.current;\n appendMessage({\n role: 'assistant',\n text: result.answer,\n citations: normalizeCitations(result.citations),\n confident: result.confident !== false,\n });\n } catch (error) {\n if (!mountedRef.current) {\n return;\n }\n // Reading the error body is async (fetch), so re-check mount after.\n const info = await readChatError(error);\n if (!mountedRef.current) {\n return;\n }\n appendMessage(describeChatError(info, text));\n } finally {\n if (mountedRef.current) {\n setBusy(false);\n }\n }\n },\n [queryWithRetry, appendMessage],\n );\n\n /**\n * Reset to a brand-new conversation: clear the transcript and forget the\n * session id so the next message starts fresh. The old session is deleted\n * server-side best-effort — the local reset is authoritative, and a failed\n * delete just leaves the session to lapse on its idle TTL.\n */\n const startNewChat = useCallback(() => {\n if (busy) {\n return;\n }\n const staleSession = sessionIdRef.current;\n sessionIdRef.current = undefined;\n setMessages([]);\n setDraft('');\n if (staleSession !== undefined) {\n void (async () => {\n try {\n const token = await tokenManager.getToken();\n await GeminaClient.withSessionToken(token, baseUrl).chat.deleteChatSession({\n sessionId: staleSession,\n });\n } catch {\n // Unreachable/expired session: nothing to clean up client-side.\n }\n })();\n }\n }, [busy, tokenManager, baseUrl]);\n\n const submitDraft = useCallback(() => {\n const text = draft.trim();\n if (text.length === 0 || busy) {\n return;\n }\n setDraft('');\n appendMessage({ role: 'user', text });\n void performSend(text);\n }, [draft, busy, appendMessage, performSend]);\n\n const retryMessage = useCallback(\n (failed: ErrorMessage) => {\n if (busy || failed.retryText === undefined) {\n return;\n }\n const text = failed.retryText;\n // Replace the error entry; the original user bubble is still there.\n setMessages((prev) => prev.filter((message) => message.id !== failed.id));\n void performSend(text);\n },\n [busy, performSend],\n );\n\n const handleKeyDown = useCallback(\n (event: React.KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.key === 'Enter' && !event.shiftKey) {\n event.preventDefault();\n submitDraft();\n }\n },\n [submitDraft],\n );\n\n const handleSubmit = useCallback(\n (event: React.FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n submitDraft();\n },\n [submitDraft],\n );\n\n // dir=\"auto\": follow the user's latest message (Hebrew → RTL); individual\n // bubbles additionally resolve their own direction via dir=\"auto\".\n let effectiveDir: 'ltr' | 'rtl';\n if (dir === 'auto') {\n let lastUserText = '';\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (message !== undefined && message.role === 'user') {\n lastUserText = message.text;\n break;\n }\n }\n effectiveDir = HEBREW_RE.test(lastUserText) ? 'rtl' : 'ltr';\n } else {\n effectiveDir = dir;\n }\n const bubbleDir = dir === 'auto' ? 'auto' : undefined;\n\n const rootClassName = [\n 'gemina-chat',\n `gemina-chat--${theme}`,\n effectiveDir === 'rtl' ? 'gemina-chat--rtl' : '',\n className ?? '',\n ]\n .filter((part) => part.length > 0)\n .join(' ');\n\n return (\n <div className={rootClassName} dir={effectiveDir}>\n {(title !== undefined || messages.length > 0) && (\n <div className=\"gemina-chat__header\">\n {title !== undefined && (\n <div className=\"gemina-chat__title\" dir={bubbleDir}>\n {title}\n </div>\n )}\n {messages.length > 0 && (\n <button\n type=\"button\"\n className=\"gemina-chat__newchat\"\n onClick={startNewChat}\n disabled={busy}\n >\n New chat\n </button>\n )}\n </div>\n )}\n <div\n ref={logRef}\n role=\"log\"\n aria-live=\"polite\"\n aria-busy={busy}\n aria-label=\"Chat messages\"\n className=\"gemina-chat__log\"\n >\n {messages.map((message) => {\n if (message.role === 'user') {\n return (\n <div\n key={message.id}\n className=\"gemina-chat__msg gemina-chat__msg--user\"\n dir={bubbleDir}\n >\n {message.text}\n </div>\n );\n }\n if (message.role === 'assistant') {\n const lowConfidence = !message.confident;\n return (\n <div\n key={message.id}\n className={\n 'gemina-chat__msg gemina-chat__msg--assistant' +\n (lowConfidence ? ' gemina-chat__msg--low-confidence' : '')\n }\n dir={bubbleDir}\n >\n {message.text}\n {lowConfidence && (\n <div className=\"gemina-chat__low-confidence-note\">\n Low confidence — please verify against the cited documents.\n </div>\n )}\n {message.citations.length > 0 && (\n <div className=\"gemina-chat__citations\">\n {message.citations.map((documentId, index) => (\n <button\n key={`${documentId}-${index}`}\n type=\"button\"\n className=\"gemina-chat__citation\"\n title={`Open document ${documentId}`}\n onClick={() => onCitationClick?.(documentId)}\n >\n {documentId}\n </button>\n ))}\n </div>\n )}\n </div>\n );\n }\n return (\n <div\n key={message.id}\n role=\"alert\"\n className=\"gemina-chat__msg gemina-chat__msg--error\"\n >\n {message.text}\n {message.retryText !== undefined && (\n <button\n type=\"button\"\n className=\"gemina-chat__retry\"\n onClick={() => retryMessage(message)}\n >\n Retry\n </button>\n )}\n </div>\n );\n })}\n {busy && (\n // The label alone is what the aria-live log announces; the dots are\n // decoration (aria-hidden), and prefers-reduced-motion freezes them.\n <div className=\"gemina-chat__typing\">\n Thinking\n <span className=\"gemina-chat__typing-dots\" aria-hidden=\"true\">\n <span />\n <span />\n <span />\n </span>\n </div>\n )}\n </div>\n <form className=\"gemina-chat__composer\" onSubmit={handleSubmit}>\n <textarea\n className=\"gemina-chat__input\"\n aria-label=\"Chat message\"\n rows={1}\n value={draft}\n placeholder={placeholder}\n dir={bubbleDir}\n onChange={(event) => setDraft(event.target.value)}\n onKeyDown={handleKeyDown}\n />\n <button\n type=\"submit\"\n className=\"gemina-chat__send\"\n aria-label=\"Send message\"\n disabled={busy || draft.trim().length === 0}\n >\n Send\n </button>\n </form>\n </div>\n );\n}\n","/** Package version. Keep in sync with package.json. */\nexport const VERSION = '0.5.2';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAYA,mBAAyD;AAEzD,iBAA6B;;;ACbtB,IAAM,UAAU;;;AD6wBf;AAprBR,IAAM,YAAY;AAgBlB,SAAS,gBAAgB,OAA0C;AACjE,MAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,cAAc,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K;AAAA,eACR;AAAA,aACF;AAAA;AAAA;AAAA,IAEJ;AAAA,IACA,6CAAC,UAAK,WAAU,yBAAwB,UAAU,cAChD;AAAA;AAAA,QAAC;AAAA;AAAA,UACC,WAAU;AAAA,UACV,cAAW;AAAA,UACX,MAAM;AAAA,UACN,OAAO;AAAA,UACP;AAAA,UACA,KAAK;AAAA,UACL,UAAU,CAAC,UAAU,SAAS,MAAM,OAAO,KAAK;AAAA,UAChD,WAAW;AAAA;AAAA,MACb;AAAA,MACA;AAAA,QAAC;AAAA;AAAA,UACC,MAAK;AAAA,UACL,WAAU;AAAA,UACV,cAAW;AAAA,UACX,UAAU,QAAQ,MAAM,KAAK,EAAE,WAAW;AAAA,UAC3C;AAAA;AAAA,MAED;AAAA,OACF;AAAA,KACF;AAEJ;","names":[]}
package/dist/chat.d.cts CHANGED
@@ -25,6 +25,15 @@ interface GeminaChatProps {
25
25
  dir?: GeminaChatDirection;
26
26
  /** Input placeholder text. */
27
27
  placeholder?: string;
28
+ /**
29
+ * Header text — whatever identity the embedding platform wants the chat
30
+ * to carry: a brand ("Acme Invoices"), an assistant persona ("Gemina's
31
+ * AI Rep"), anything. Text only, rendered verbatim. When set, the header
32
+ * is always visible; without it the header appears only once a
33
+ * conversation has started (to host "New chat"). Colors and fonts are
34
+ * themeable separately via the `--gemina-chat-*` CSS variables.
35
+ */
36
+ title?: string;
28
37
  /** Called with the cited `documentId` when a citation chip is clicked. */
29
38
  onCitationClick?: (documentId: string) => void;
30
39
  /** Extra class name(s) for the root element (e.g. to override CSS vars). */
package/dist/chat.d.ts CHANGED
@@ -25,6 +25,15 @@ interface GeminaChatProps {
25
25
  dir?: GeminaChatDirection;
26
26
  /** Input placeholder text. */
27
27
  placeholder?: string;
28
+ /**
29
+ * Header text — whatever identity the embedding platform wants the chat
30
+ * to carry: a brand ("Acme Invoices"), an assistant persona ("Gemina's
31
+ * AI Rep"), anything. Text only, rendered verbatim. When set, the header
32
+ * is always visible; without it the header appears only once a
33
+ * conversation has started (to host "New chat"). Colors and fonts are
34
+ * themeable separately via the `--gemina-chat-*` CSS variables.
35
+ */
36
+ title?: string;
28
37
  /** Called with the cited `documentId` when a citation chip is clicked. */
29
38
  onCitationClick?: (documentId: string) => void;
30
39
  /** Extra class name(s) for the root element (e.g. to override CSS vars). */
package/dist/chat.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  GeminaChat
3
- } from "./chunk-7MGELCGG.js";
3
+ } from "./chunk-KCOWRC34.js";
4
4
  export {
5
5
  GeminaChat
6
6
  };
@@ -3,7 +3,7 @@ import { useCallback, useEffect, useRef, useState } from "react";
3
3
  import { GeminaClient } from "@gemina/sdk";
4
4
 
5
5
  // src/version.ts
6
- var VERSION = "0.5.0";
6
+ var VERSION = "0.5.2";
7
7
 
8
8
  // src/chat.tsx
9
9
  import { jsx, jsxs } from "react/jsx-runtime";
@@ -191,6 +191,14 @@ var CHAT_CSS = `
191
191
  padding: 6px 10px;
192
192
  border-bottom: 1px solid var(--gemina-chat-border);
193
193
  }
194
+ .gemina-chat__title {
195
+ margin-inline-end: auto;
196
+ font-size: 13px;
197
+ font-weight: 600;
198
+ overflow: hidden;
199
+ text-overflow: ellipsis;
200
+ white-space: nowrap;
201
+ }
194
202
  .gemina-chat__newchat {
195
203
  font: inherit;
196
204
  font-size: 12px;
@@ -279,10 +287,35 @@ var CHAT_CSS = `
279
287
  }
280
288
  .gemina-chat__typing {
281
289
  align-self: flex-start;
290
+ display: flex;
291
+ align-items: center;
292
+ gap: 5px;
282
293
  color: var(--gemina-chat-muted);
283
294
  font-size: 12px;
284
295
  padding: 0 4px;
285
296
  }
297
+ .gemina-chat__typing-dots {
298
+ display: inline-flex;
299
+ align-items: center;
300
+ gap: 3px;
301
+ }
302
+ .gemina-chat__typing-dots span {
303
+ width: 4px;
304
+ height: 4px;
305
+ border-radius: 50%;
306
+ background: currentColor;
307
+ opacity: 0.25;
308
+ animation: gemina-chat-thinking 1.2s infinite ease-in-out;
309
+ }
310
+ .gemina-chat__typing-dots span:nth-child(2) { animation-delay: 0.2s; }
311
+ .gemina-chat__typing-dots span:nth-child(3) { animation-delay: 0.4s; }
312
+ @keyframes gemina-chat-thinking {
313
+ 0%, 60%, 100% { opacity: 0.25; transform: translateY(0); }
314
+ 30% { opacity: 1; transform: translateY(-2px); }
315
+ }
316
+ @media (prefers-reduced-motion: reduce) {
317
+ .gemina-chat__typing-dots span { animation: none; opacity: 0.6; }
318
+ }
286
319
  .gemina-chat__composer {
287
320
  display: flex;
288
321
  gap: 8px;
@@ -337,6 +370,7 @@ function GeminaChat(props) {
337
370
  theme = "auto",
338
371
  dir = "auto",
339
372
  placeholder = "Ask about your documents\u2026",
373
+ title,
340
374
  onCitationClick,
341
375
  className
342
376
  } = props;
@@ -513,16 +547,19 @@ function GeminaChat(props) {
513
547
  className ?? ""
514
548
  ].filter((part) => part.length > 0).join(" ");
515
549
  return /* @__PURE__ */ jsxs("div", { className: rootClassName, dir: effectiveDir, children: [
516
- messages.length > 0 && /* @__PURE__ */ jsx("div", { className: "gemina-chat__header", children: /* @__PURE__ */ jsx(
517
- "button",
518
- {
519
- type: "button",
520
- className: "gemina-chat__newchat",
521
- onClick: startNewChat,
522
- disabled: busy,
523
- children: "New chat"
524
- }
525
- ) }),
550
+ (title !== void 0 || messages.length > 0) && /* @__PURE__ */ jsxs("div", { className: "gemina-chat__header", children: [
551
+ title !== void 0 && /* @__PURE__ */ jsx("div", { className: "gemina-chat__title", dir: bubbleDir, children: title }),
552
+ messages.length > 0 && /* @__PURE__ */ jsx(
553
+ "button",
554
+ {
555
+ type: "button",
556
+ className: "gemina-chat__newchat",
557
+ onClick: startNewChat,
558
+ disabled: busy,
559
+ children: "New chat"
560
+ }
561
+ )
562
+ ] }),
526
563
  /* @__PURE__ */ jsxs(
527
564
  "div",
528
565
  {
@@ -592,7 +629,16 @@ function GeminaChat(props) {
592
629
  message.id
593
630
  );
594
631
  }),
595
- busy && /* @__PURE__ */ jsx("div", { className: "gemina-chat__typing", children: "Thinking\u2026" })
632
+ busy && // The label alone is what the aria-live log announces; the dots are
633
+ // decoration (aria-hidden), and prefers-reduced-motion freezes them.
634
+ /* @__PURE__ */ jsxs("div", { className: "gemina-chat__typing", children: [
635
+ "Thinking",
636
+ /* @__PURE__ */ jsxs("span", { className: "gemina-chat__typing-dots", "aria-hidden": "true", children: [
637
+ /* @__PURE__ */ jsx("span", {}),
638
+ /* @__PURE__ */ jsx("span", {}),
639
+ /* @__PURE__ */ jsx("span", {})
640
+ ] })
641
+ ] })
596
642
  ]
597
643
  }
598
644
  ),
@@ -628,4 +674,4 @@ export {
628
674
  VERSION,
629
675
  GeminaChat
630
676
  };
631
- //# sourceMappingURL=chunk-7MGELCGG.js.map
677
+ //# sourceMappingURL=chunk-KCOWRC34.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/chat.tsx","../src/version.ts"],"sourcesContent":["/**\n * <GeminaChat> — drop-in chat UI over Gemina Document Intelligence.\n *\n * Auth flows exclusively through a {@link GeminaTokenManager}: the component\n * asks it for a short-lived session token per turn and calls\n * `POST /v1/chat/query` through `@gemina/sdk`. It never sees — and cannot\n * accept — a Gemina API key (the token manager throws on API-key-shaped\n * credentials).\n *\n * SSR-safe: no `window`/`document` access at import time; styles are\n * injected on mount.\n */\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type * as React from 'react';\nimport { GeminaClient } from '@gemina/sdk';\nimport type { ChatQueryOutDTO } from '@gemina/sdk';\nimport type { GeminaTokenManager } from './token-manager';\nimport { VERSION } from './version';\n\n/** Visual theme. `\"auto\"` follows `prefers-color-scheme`. */\nexport type GeminaChatTheme = 'light' | 'dark' | 'auto';\n\n/**\n * Text direction. `\"auto\"` flips the widget to RTL when the user's latest\n * message contains Hebrew, and lets each bubble resolve its own direction.\n */\nexport type GeminaChatDirection = 'ltr' | 'rtl' | 'auto';\n\nexport interface GeminaChatProps {\n /** Token source. Required — see {@link GeminaTokenManager}. */\n tokenManager: GeminaTokenManager;\n /** Gemina API base URL (default `https://api.gemina.co`). */\n baseUrl?: string;\n /**\n * Optional end-user id forwarded with each query. On the session-token\n * path the token's SIGNED scope always wins server-side — this is a\n * hint, not a security control.\n */\n endUserId?: string;\n /** Visual theme (default `\"auto\"`). */\n theme?: GeminaChatTheme;\n /** Text direction (default `\"auto\"`). */\n dir?: GeminaChatDirection;\n /** Input placeholder text. */\n placeholder?: string;\n /**\n * Header text — whatever identity the embedding platform wants the chat\n * to carry: a brand (\"Acme Invoices\"), an assistant persona (\"Gemina's\n * AI Rep\"), anything. Text only, rendered verbatim. When set, the header\n * is always visible; without it the header appears only once a\n * conversation has started (to host \"New chat\"). Colors and fonts are\n * themeable separately via the `--gemina-chat-*` CSS variables.\n */\n title?: string;\n /** Called with the cited `documentId` when a citation chip is clicked. */\n onCitationClick?: (documentId: string) => void;\n /** Extra class name(s) for the root element (e.g. to override CSS vars). */\n className?: string;\n}\n\ninterface UserMessage {\n id: number;\n role: 'user';\n text: string;\n}\n\ninterface AssistantMessage {\n id: number;\n role: 'assistant';\n text: string;\n citations: string[];\n confident: boolean;\n}\n\ninterface ErrorMessage {\n id: number;\n role: 'error';\n text: string;\n /** Present only when a retry is offered; holds the original user text. */\n retryText?: string;\n}\n\ntype ChatMessage = UserMessage | AssistantMessage | ErrorMessage;\n\n/** `Omit` that distributes over each member of a union. */\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\n\ntype ChatMessageInput = DistributiveOmit<ChatMessage, 'id'>;\n\n/** Hebrew Unicode block (U+0590–U+05FF). */\nconst HEBREW_RE = /[\\u0590-\\u05FF]/;\n\n/**\n * The response-like object carried by a thrown transport error. We pull it off\n * by shape rather than `instanceof ResponseError` — robust against duplicated\n * `@gemina/sdk` copies in a bundle (class identity is not shared across\n * copies). On the fetch transport this is the raw `Response`, so `status`,\n * `headers`, and the JSON body are all reachable from here.\n */\ninterface ResponseLike {\n status?: number;\n headers?: { get?: (name: string) => string | null };\n json?: () => Promise<unknown>;\n clone?: () => ResponseLike;\n}\n\nfunction getResponseLike(error: unknown): ResponseLike | undefined {\n if (error !== null && typeof error === 'object' && 'response' in error) {\n const response = (error as { response?: unknown }).response;\n if (response !== null && typeof response === 'object') {\n return response as ResponseLike;\n }\n }\n return undefined;\n}\n\n/** Extract an HTTP status from a thrown value, or `undefined`. */\nfunction httpStatus(error: unknown): number | undefined {\n const status = getResponseLike(error)?.status;\n return typeof status === 'number' ? status : undefined;\n}\n\n// Stable backend error codes. These survive production's `detail`-stripping\n// (see the chat-pricing handoff); we switch on HTTP status first and refine\n// with these where the same status can mean two different things.\nconst ERR_CHAT_QUOTA_EXCEEDED = 'CHAT_QUOTA_EXCEEDED';\nconst ERR_DI_NOT_IN_PLAN = 'DOCUMENT_INTELLIGENCE_NOT_IN_PLAN';\nconst ERR_UNPROCESSABLE = 'UNPROCESSABLE_ERROR';\nconst ERR_BAD_GATEWAY = 'BAD_GATEWAY_ERROR';\n// A conversation id that the server no longer knows (24h idle TTL, explicit\n// reset, or end-user scope drift). A turn that CARRIED a session and 404s is\n// this by construction — the chat/query handler raises 404 for nothing else —\n// so the component drops the id and restarts the conversation transparently.\nconst ERR_CHAT_SESSION_NOT_FOUND = 'CHAT_SESSION_NOT_FOUND';\n\ninterface ChatErrorInfo {\n status: number | undefined;\n errorCode: string | undefined;\n /** Human-readable server fallback (`errors[0].description`). */\n description: string | undefined;\n /** Whole seconds until reset, from the `Retry-After` header (429). */\n retryAfterSeconds: number | undefined;\n}\n\n/**\n * Read what the backend actually sent on an error. Only the HTTP status, the\n * stable `errors[0].error_code` / `description`, and the `Retry-After` header\n * are reliable across environments — production strips `errors[0].detail`, so\n * we never touch it. The fetch body can be read once, so we clone defensively;\n * if that fails (non-JSON, empty, or already consumed) the status still stands.\n */\nasync function readChatError(error: unknown): Promise<ChatErrorInfo> {\n const response = getResponseLike(error);\n const info: ChatErrorInfo = {\n status: typeof response?.status === 'number' ? response.status : undefined,\n errorCode: undefined,\n description: undefined,\n retryAfterSeconds: undefined,\n };\n if (response === undefined) {\n return info;\n }\n\n const rawRetryAfter = response.headers?.get?.('retry-after');\n if (rawRetryAfter !== null && rawRetryAfter !== undefined) {\n const seconds = Number(rawRetryAfter);\n if (Number.isFinite(seconds) && seconds > 0) {\n info.retryAfterSeconds = seconds;\n }\n }\n\n let body: unknown;\n try {\n const source = typeof response.clone === 'function' ? response.clone() : response;\n body = typeof source.json === 'function' ? await source.json() : undefined;\n } catch {\n body = undefined;\n }\n if (body !== null && typeof body === 'object') {\n const errors = (body as { errors?: unknown }).errors;\n if (\n Array.isArray(errors) &&\n errors.length > 0 &&\n errors[0] !== null &&\n typeof errors[0] === 'object'\n ) {\n const first = errors[0] as { error_code?: unknown; description?: unknown };\n if (typeof first.error_code === 'string') {\n info.errorCode = first.error_code;\n }\n if (typeof first.description === 'string') {\n info.description = first.description;\n }\n }\n }\n return info;\n}\n\nconst SESSION_EXPIRED_TEXT = 'Session expired — please reload the page or sign in again.';\nconst CONVERSATION_RESET_TEXT =\n 'This conversation is no longer available — send your message again to start a new one.';\nconst RATE_LIMIT_TEXT = \"You're sending messages too quickly — try again shortly.\";\nconst PLAN_GATE_TEXT = \"Chat isn't included in your plan.\";\nconst UNANSWERABLE_TEXT = \"We couldn't answer that. Try rephrasing your question.\";\nconst SERVICE_UNAVAILABLE_TEXT = 'The chat service is temporarily unavailable. Please try again.';\nconst GENERIC_ERROR_TEXT = \"Something went wrong and your message wasn't answered.\";\n\n/** Friendly \"resets in about N days/hours/minutes\" from Retry-After seconds. */\nfunction formatResetHint(seconds: number | undefined): string {\n if (seconds === undefined || !Number.isFinite(seconds) || seconds <= 0) {\n return 'at the next billing cycle';\n }\n const days = Math.round(seconds / 86400);\n if (days >= 1) {\n return `in about ${days} day${days === 1 ? '' : 's'}`;\n }\n const hours = Math.round(seconds / 3600);\n if (hours >= 1) {\n return `in about ${hours} hour${hours === 1 ? '' : 's'}`;\n }\n const minutes = Math.max(1, Math.round(seconds / 60));\n return `in about ${minutes} minute${minutes === 1 ? '' : 's'}`;\n}\n\n/**\n * Map a chat error to the bubble we render. Switches on HTTP status, refined by\n * the stable backend `error_code`. `retryText` is set only when resending the\n * same text could plausibly succeed — never for quota / plan / validation\n * outcomes, where an identical retry would just fail the same way.\n */\nfunction describeChatError(info: ChatErrorInfo, originalText: string): ChatMessageInput {\n const { status, errorCode } = info;\n\n // Over the included cap AND out of credits — the chat is blocked. Retrying\n // won't help; point at the reset time from the Retry-After header.\n if (status === 429 && errorCode === ERR_CHAT_QUOTA_EXCEEDED) {\n return {\n role: 'error',\n text: `You've used your included chats and are out of credits. Included chats reset ${formatResetHint(\n info.retryAfterSeconds,\n )}.`,\n };\n }\n // Any other 429 is a transient rate limit — a retry after a moment is fine.\n if (status === 429) {\n return { role: 'error', text: RATE_LIMIT_TEXT, retryText: originalText };\n }\n // Document Intelligence not in the plan/contract. NOT an auth failure.\n if (status === 402 || status === 403 || errorCode === ERR_DI_NOT_IN_PLAN) {\n return { role: 'error', text: PLAN_GATE_TEXT };\n }\n // Session expired — only surfaces after the 401-invalidate-retry-once path\n // has already failed a second time.\n if (status === 401) {\n return { role: 'error', text: SESSION_EXPIRED_TEXT };\n }\n // A stale conversation id that slipped past the transparent restart — only\n // the stable error_code reliably means \"the conversation is gone\". A bare 404\n // is a routing/gateway miss (e.g. the endpoint isn't deployed), which reads\n // better as a transient service error than a confusing \"conversation reset\".\n if (errorCode === ERR_CHAT_SESSION_NOT_FOUND) {\n return { role: 'error', text: CONVERSATION_RESET_TEXT, retryText: originalText };\n }\n if (status === 404) {\n return { role: 'error', text: SERVICE_UNAVAILABLE_TEXT, retryText: originalText };\n }\n // The question couldn't be answered (e.g. no searchable text). Expected, not\n // a server error — invite a rephrase rather than a blind retry.\n if (status === 422 || errorCode === ERR_UNPROCESSABLE) {\n return { role: 'error', text: UNANSWERABLE_TEXT };\n }\n // Chat backend timed out / unreachable — transient, offer retry.\n if (status === 502 || errorCode === ERR_BAD_GATEWAY) {\n return { role: 'error', text: SERVICE_UNAVAILABLE_TEXT, retryText: originalText };\n }\n // Anything else (incl. 500): prefer the server's description if it sent one.\n return {\n role: 'error',\n text: info.description ?? GENERIC_ERROR_TEXT,\n retryText: originalText,\n };\n}\n\n/**\n * The API reports citations as an array of `documentId` strings; normalize\n * defensively so `{ documentId }` objects also work if the shape evolves.\n */\nfunction normalizeCitations(citations: unknown): string[] {\n if (!Array.isArray(citations)) {\n return [];\n }\n const ids: string[] = [];\n for (const item of citations) {\n if (typeof item === 'string' && item.length > 0) {\n ids.push(item);\n } else if (\n item !== null &&\n typeof item === 'object' &&\n typeof (item as { documentId?: unknown }).documentId === 'string'\n ) {\n ids.push((item as { documentId: string }).documentId);\n }\n }\n return ids;\n}\n\n// --- Styles -----------------------------------------------------------------\n// Hand-rolled, no UI deps. Everything is scoped under .gemina-chat and driven\n// by CSS custom properties so host apps can re-theme without touching the DOM.\n\nconst DARK_VARS = `\n --gemina-chat-bg: #101418;\n --gemina-chat-fg: #e6e9ee;\n --gemina-chat-border: #2a323c;\n --gemina-chat-accent: #4c8dff;\n --gemina-chat-accent-fg: #ffffff;\n --gemina-chat-assistant-bg: #1c232b;\n --gemina-chat-assistant-fg: #e6e9ee;\n --gemina-chat-muted: #98a2b3;\n --gemina-chat-error: #f97066;\n --gemina-chat-low-confidence: #f7b27a;\n`;\n\nconst CHAT_CSS = `\n.gemina-chat {\n --gemina-chat-bg: #ffffff;\n --gemina-chat-fg: #1a1d21;\n --gemina-chat-border: #d9dce1;\n --gemina-chat-accent: #2f6fed;\n --gemina-chat-accent-fg: #ffffff;\n --gemina-chat-assistant-bg: #f2f4f7;\n --gemina-chat-assistant-fg: #1a1d21;\n --gemina-chat-muted: #667085;\n --gemina-chat-error: #b42318;\n --gemina-chat-low-confidence: #b54708;\n --gemina-chat-radius: 10px;\n --gemina-chat-font: system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif;\n\n box-sizing: border-box;\n display: flex;\n flex-direction: column;\n min-height: 320px;\n max-height: 600px;\n background: var(--gemina-chat-bg);\n color: var(--gemina-chat-fg);\n border: 1px solid var(--gemina-chat-border);\n border-radius: var(--gemina-chat-radius);\n font-family: var(--gemina-chat-font);\n font-size: 14px;\n line-height: 1.5;\n}\n.gemina-chat *, .gemina-chat *::before, .gemina-chat *::after { box-sizing: border-box; }\n.gemina-chat--dark { ${DARK_VARS} }\n@media (prefers-color-scheme: dark) {\n .gemina-chat--auto { ${DARK_VARS} }\n}\n.gemina-chat__header {\n display: flex;\n justify-content: flex-end;\n align-items: center;\n flex: 0 0 auto;\n padding: 6px 10px;\n border-bottom: 1px solid var(--gemina-chat-border);\n}\n.gemina-chat__title {\n margin-inline-end: auto;\n font-size: 13px;\n font-weight: 600;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n.gemina-chat__newchat {\n font: inherit;\n font-size: 12px;\n padding: 3px 10px;\n border-radius: var(--gemina-chat-radius);\n border: 1px solid var(--gemina-chat-border);\n background: transparent;\n color: var(--gemina-chat-accent);\n cursor: pointer;\n}\n.gemina-chat__newchat:hover:not(:disabled) { border-color: var(--gemina-chat-accent); }\n.gemina-chat__newchat:disabled { opacity: 0.5; cursor: default; }\n.gemina-chat__log {\n flex: 1;\n overflow-y: auto;\n padding: 12px;\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n.gemina-chat__msg {\n max-width: 85%;\n padding: 8px 12px;\n border-radius: var(--gemina-chat-radius);\n white-space: pre-wrap;\n overflow-wrap: break-word;\n}\n.gemina-chat__msg--user {\n align-self: flex-end;\n background: var(--gemina-chat-accent);\n color: var(--gemina-chat-accent-fg);\n}\n.gemina-chat--rtl .gemina-chat__msg--user, .gemina-chat[dir=\"rtl\"] .gemina-chat__msg--user {\n align-self: flex-start;\n}\n.gemina-chat--rtl .gemina-chat__msg--assistant, .gemina-chat[dir=\"rtl\"] .gemina-chat__msg--assistant {\n align-self: flex-end;\n}\n.gemina-chat__msg--assistant {\n align-self: flex-start;\n background: var(--gemina-chat-assistant-bg);\n color: var(--gemina-chat-assistant-fg);\n}\n.gemina-chat__msg--low-confidence {\n border: 1px dashed var(--gemina-chat-low-confidence);\n}\n.gemina-chat__low-confidence-note {\n margin-top: 6px;\n font-size: 12px;\n color: var(--gemina-chat-low-confidence);\n}\n.gemina-chat__citations {\n display: flex;\n flex-wrap: wrap;\n gap: 4px;\n margin-top: 6px;\n}\n.gemina-chat__citation {\n font: inherit;\n font-size: 12px;\n padding: 2px 8px;\n border-radius: 999px;\n border: 1px solid var(--gemina-chat-border);\n background: transparent;\n color: var(--gemina-chat-accent);\n cursor: pointer;\n}\n.gemina-chat__citation:hover { border-color: var(--gemina-chat-accent); }\n.gemina-chat__msg--error {\n align-self: flex-start;\n background: transparent;\n border: 1px solid var(--gemina-chat-error);\n color: var(--gemina-chat-error);\n}\n.gemina-chat__retry {\n font: inherit;\n font-size: 12px;\n margin-top: 6px;\n display: block;\n padding: 2px 10px;\n border-radius: var(--gemina-chat-radius);\n border: 1px solid var(--gemina-chat-error);\n background: transparent;\n color: var(--gemina-chat-error);\n cursor: pointer;\n}\n.gemina-chat__typing {\n align-self: flex-start;\n display: flex;\n align-items: center;\n gap: 5px;\n color: var(--gemina-chat-muted);\n font-size: 12px;\n padding: 0 4px;\n}\n.gemina-chat__typing-dots {\n display: inline-flex;\n align-items: center;\n gap: 3px;\n}\n.gemina-chat__typing-dots span {\n width: 4px;\n height: 4px;\n border-radius: 50%;\n background: currentColor;\n opacity: 0.25;\n animation: gemina-chat-thinking 1.2s infinite ease-in-out;\n}\n.gemina-chat__typing-dots span:nth-child(2) { animation-delay: 0.2s; }\n.gemina-chat__typing-dots span:nth-child(3) { animation-delay: 0.4s; }\n@keyframes gemina-chat-thinking {\n 0%, 60%, 100% { opacity: 0.25; transform: translateY(0); }\n 30% { opacity: 1; transform: translateY(-2px); }\n}\n@media (prefers-reduced-motion: reduce) {\n .gemina-chat__typing-dots span { animation: none; opacity: 0.6; }\n}\n.gemina-chat__composer {\n display: flex;\n gap: 8px;\n padding: 10px;\n border-top: 1px solid var(--gemina-chat-border);\n}\n.gemina-chat__input {\n flex: 1;\n resize: none;\n font: inherit;\n color: inherit;\n background: transparent;\n border: 1px solid var(--gemina-chat-border);\n border-radius: var(--gemina-chat-radius);\n padding: 8px 10px;\n min-height: 38px;\n}\n.gemina-chat__input:focus {\n outline: 2px solid var(--gemina-chat-accent);\n outline-offset: -1px;\n}\n.gemina-chat__send {\n font: inherit;\n align-self: flex-end;\n border: none;\n border-radius: var(--gemina-chat-radius);\n background: var(--gemina-chat-accent);\n color: var(--gemina-chat-accent-fg);\n padding: 8px 16px;\n cursor: pointer;\n}\n.gemina-chat__send:disabled { opacity: 0.5; cursor: default; }\n`;\n\nconst STYLE_ATTR = 'data-gemina-chat';\n\n/**\n * Inject the widget stylesheet once per document (idempotent across\n * instances; intentionally not removed on unmount so sibling instances and\n * quick remounts never flash unstyled).\n */\nfunction ensureStylesInjected(): void {\n if (typeof document === 'undefined') {\n return;\n }\n if (document.head.querySelector(`style[${STYLE_ATTR}]`) !== null) {\n return;\n }\n const style = document.createElement('style');\n style.setAttribute(STYLE_ATTR, VERSION);\n style.textContent = CHAT_CSS;\n document.head.appendChild(style);\n}\n\n/**\n * Embeddable Gemina Document Intelligence chat.\n *\n * ```tsx\n * <GeminaChat\n * tokenManager={tokenManager}\n * onCitationClick={(documentId) => openDocument(documentId)}\n * />\n * ```\n */\nexport function GeminaChat(props: GeminaChatProps): React.JSX.Element {\n const {\n tokenManager,\n baseUrl,\n endUserId,\n theme = 'auto',\n dir = 'auto',\n placeholder = 'Ask about your documents…',\n title,\n onCitationClick,\n className,\n } = props;\n\n const [messages, setMessages] = useState<ChatMessage[]>([]);\n const [draft, setDraft] = useState('');\n const [busy, setBusy] = useState(false);\n const nextIdRef = useRef(0);\n const mountedRef = useRef(false);\n const logRef = useRef<HTMLDivElement | null>(null);\n // The conversation id (server-issued) that gives the chat memory across\n // turns. Held in a ref, not state: it changes per turn but must never\n // trigger a re-render, and the send flow reads its latest value directly.\n // Distinct from the auth session TOKEN the token manager holds.\n const sessionIdRef = useRef<string | undefined>(undefined);\n\n useEffect(() => {\n mountedRef.current = true;\n ensureStylesInjected();\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n // Keep the newest message in view.\n useEffect(() => {\n const log = logRef.current;\n if (log !== null) {\n log.scrollTop = log.scrollHeight;\n }\n }, [messages, busy]);\n\n const appendMessage = useCallback((message: ChatMessageInput) => {\n const id = nextIdRef.current++;\n setMessages((prev) => [...prev, { ...message, id }]);\n }, []);\n\n const chatOnce = useCallback(\n (token: string, message: string): Promise<ChatQueryOutDTO> => {\n const client = GeminaClient.withSessionToken(token, baseUrl);\n const sessionId = sessionIdRef.current;\n return client.chat.chatQuery({\n // Thread the conversation id when we have one so follow-ups resolve\n // referents (\"what about the total?\"); omit it to start a new one.\n chatQueryInDTO: { message, endUserId, ...(sessionId ? { sessionId } : {}) },\n });\n },\n [baseUrl, endUserId],\n );\n\n /** One turn, with the mandated 401-invalidate-retry-once behavior. */\n const queryWithRetry = useCallback(\n async (message: string): Promise<ChatQueryOutDTO> => {\n const token = await tokenManager.getToken();\n try {\n return await chatOnce(token, message);\n } catch (error) {\n if (httpStatus(error) !== 401) {\n throw error;\n }\n // Token likely expired mid-session: drop it, re-mint via the\n // tenant backend, retry exactly once. A second 401 propagates.\n tokenManager.invalidate();\n const freshToken = await tokenManager.getToken();\n return await chatOnce(freshToken, message);\n }\n },\n [tokenManager, chatOnce],\n );\n\n const performSend = useCallback(\n async (text: string) => {\n setBusy(true);\n try {\n let result: ChatQueryOutDTO;\n const hadSession = sessionIdRef.current !== undefined;\n try {\n result = await queryWithRetry(text);\n } catch (error) {\n // A turn that CARRIED a session and 404s means the conversation is\n // gone (24h idle TTL, an explicit reset, or end-user scope drift).\n // Drop the stale id and retry once as a fresh conversation, so the\n // expiry is transparent — the user just gets an answer, no memory.\n if (hadSession && httpStatus(error) === 404) {\n sessionIdRef.current = undefined;\n result = await queryWithRetry(text);\n } else {\n throw error;\n }\n }\n if (!mountedRef.current) {\n return;\n }\n // The response always returns the (possibly newly created) conversation\n // id — store it so the next turn continues this thread.\n sessionIdRef.current = result.sessionId ?? sessionIdRef.current;\n appendMessage({\n role: 'assistant',\n text: result.answer,\n citations: normalizeCitations(result.citations),\n confident: result.confident !== false,\n });\n } catch (error) {\n if (!mountedRef.current) {\n return;\n }\n // Reading the error body is async (fetch), so re-check mount after.\n const info = await readChatError(error);\n if (!mountedRef.current) {\n return;\n }\n appendMessage(describeChatError(info, text));\n } finally {\n if (mountedRef.current) {\n setBusy(false);\n }\n }\n },\n [queryWithRetry, appendMessage],\n );\n\n /**\n * Reset to a brand-new conversation: clear the transcript and forget the\n * session id so the next message starts fresh. The old session is deleted\n * server-side best-effort — the local reset is authoritative, and a failed\n * delete just leaves the session to lapse on its idle TTL.\n */\n const startNewChat = useCallback(() => {\n if (busy) {\n return;\n }\n const staleSession = sessionIdRef.current;\n sessionIdRef.current = undefined;\n setMessages([]);\n setDraft('');\n if (staleSession !== undefined) {\n void (async () => {\n try {\n const token = await tokenManager.getToken();\n await GeminaClient.withSessionToken(token, baseUrl).chat.deleteChatSession({\n sessionId: staleSession,\n });\n } catch {\n // Unreachable/expired session: nothing to clean up client-side.\n }\n })();\n }\n }, [busy, tokenManager, baseUrl]);\n\n const submitDraft = useCallback(() => {\n const text = draft.trim();\n if (text.length === 0 || busy) {\n return;\n }\n setDraft('');\n appendMessage({ role: 'user', text });\n void performSend(text);\n }, [draft, busy, appendMessage, performSend]);\n\n const retryMessage = useCallback(\n (failed: ErrorMessage) => {\n if (busy || failed.retryText === undefined) {\n return;\n }\n const text = failed.retryText;\n // Replace the error entry; the original user bubble is still there.\n setMessages((prev) => prev.filter((message) => message.id !== failed.id));\n void performSend(text);\n },\n [busy, performSend],\n );\n\n const handleKeyDown = useCallback(\n (event: React.KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.key === 'Enter' && !event.shiftKey) {\n event.preventDefault();\n submitDraft();\n }\n },\n [submitDraft],\n );\n\n const handleSubmit = useCallback(\n (event: React.FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n submitDraft();\n },\n [submitDraft],\n );\n\n // dir=\"auto\": follow the user's latest message (Hebrew → RTL); individual\n // bubbles additionally resolve their own direction via dir=\"auto\".\n let effectiveDir: 'ltr' | 'rtl';\n if (dir === 'auto') {\n let lastUserText = '';\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (message !== undefined && message.role === 'user') {\n lastUserText = message.text;\n break;\n }\n }\n effectiveDir = HEBREW_RE.test(lastUserText) ? 'rtl' : 'ltr';\n } else {\n effectiveDir = dir;\n }\n const bubbleDir = dir === 'auto' ? 'auto' : undefined;\n\n const rootClassName = [\n 'gemina-chat',\n `gemina-chat--${theme}`,\n effectiveDir === 'rtl' ? 'gemina-chat--rtl' : '',\n className ?? '',\n ]\n .filter((part) => part.length > 0)\n .join(' ');\n\n return (\n <div className={rootClassName} dir={effectiveDir}>\n {(title !== undefined || messages.length > 0) && (\n <div className=\"gemina-chat__header\">\n {title !== undefined && (\n <div className=\"gemina-chat__title\" dir={bubbleDir}>\n {title}\n </div>\n )}\n {messages.length > 0 && (\n <button\n type=\"button\"\n className=\"gemina-chat__newchat\"\n onClick={startNewChat}\n disabled={busy}\n >\n New chat\n </button>\n )}\n </div>\n )}\n <div\n ref={logRef}\n role=\"log\"\n aria-live=\"polite\"\n aria-busy={busy}\n aria-label=\"Chat messages\"\n className=\"gemina-chat__log\"\n >\n {messages.map((message) => {\n if (message.role === 'user') {\n return (\n <div\n key={message.id}\n className=\"gemina-chat__msg gemina-chat__msg--user\"\n dir={bubbleDir}\n >\n {message.text}\n </div>\n );\n }\n if (message.role === 'assistant') {\n const lowConfidence = !message.confident;\n return (\n <div\n key={message.id}\n className={\n 'gemina-chat__msg gemina-chat__msg--assistant' +\n (lowConfidence ? ' gemina-chat__msg--low-confidence' : '')\n }\n dir={bubbleDir}\n >\n {message.text}\n {lowConfidence && (\n <div className=\"gemina-chat__low-confidence-note\">\n Low confidence — please verify against the cited documents.\n </div>\n )}\n {message.citations.length > 0 && (\n <div className=\"gemina-chat__citations\">\n {message.citations.map((documentId, index) => (\n <button\n key={`${documentId}-${index}`}\n type=\"button\"\n className=\"gemina-chat__citation\"\n title={`Open document ${documentId}`}\n onClick={() => onCitationClick?.(documentId)}\n >\n {documentId}\n </button>\n ))}\n </div>\n )}\n </div>\n );\n }\n return (\n <div\n key={message.id}\n role=\"alert\"\n className=\"gemina-chat__msg gemina-chat__msg--error\"\n >\n {message.text}\n {message.retryText !== undefined && (\n <button\n type=\"button\"\n className=\"gemina-chat__retry\"\n onClick={() => retryMessage(message)}\n >\n Retry\n </button>\n )}\n </div>\n );\n })}\n {busy && (\n // The label alone is what the aria-live log announces; the dots are\n // decoration (aria-hidden), and prefers-reduced-motion freezes them.\n <div className=\"gemina-chat__typing\">\n Thinking\n <span className=\"gemina-chat__typing-dots\" aria-hidden=\"true\">\n <span />\n <span />\n <span />\n </span>\n </div>\n )}\n </div>\n <form className=\"gemina-chat__composer\" onSubmit={handleSubmit}>\n <textarea\n className=\"gemina-chat__input\"\n aria-label=\"Chat message\"\n rows={1}\n value={draft}\n placeholder={placeholder}\n dir={bubbleDir}\n onChange={(event) => setDraft(event.target.value)}\n onKeyDown={handleKeyDown}\n />\n <button\n type=\"submit\"\n className=\"gemina-chat__send\"\n aria-label=\"Send message\"\n disabled={busy || draft.trim().length === 0}\n >\n Send\n </button>\n </form>\n </div>\n );\n}\n","/** Package version. Keep in sync with package.json. */\nexport const VERSION = '0.5.2';\n"],"mappings":";AAYA,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AAEzD,SAAS,oBAAoB;;;ACbtB,IAAM,UAAU;;;AD6wBf,SAEI,KAFJ;AAprBR,IAAM,YAAY;AAgBlB,SAAS,gBAAgB,OAA0C;AACjE,MAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,cAAc,OAAO;AACtE,UAAM,WAAY,MAAiC;AACnD,QAAI,aAAa,QAAQ,OA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B,UAAU,cAChD;AAAA;AAAA,QAAC;AAAA;AAAA,UACC,WAAU;AAAA,UACV,cAAW;AAAA,UACX,MAAM;AAAA,UACN,OAAO;AAAA,UACP;AAAA,UACA,KAAK;AAAA,UACL,UAAU,CAAC,UAAU,SAAS,MAAM,OAAO,KAAK;AAAA,UAChD,WAAW;AAAA;AAAA,MACb;AAAA,MACA;AAAA,QAAC;AAAA;AAAA,UACC,MAAK;AAAA,UACL,WAAU;AAAA,UACV,cAAW;AAAA,UACX,UAAU,QAAQ,MAAM,KAAK,EAAE,WAAW;AAAA,UAC3C;AAAA;AAAA,MAED;AAAA,OACF;AAAA,KACF;AAEJ;","names":[]}
package/dist/index.cjs CHANGED
@@ -164,7 +164,7 @@ var import_react = require("react");
164
164
  var import_sdk = require("@gemina/sdk");
165
165
 
166
166
  // src/version.ts
167
- var VERSION = "0.5.0";
167
+ var VERSION = "0.5.2";
168
168
 
169
169
  // src/chat.tsx
170
170
  var import_jsx_runtime = require("react/jsx-runtime");
@@ -352,6 +352,14 @@ var CHAT_CSS = `
352
352
  padding: 6px 10px;
353
353
  border-bottom: 1px solid var(--gemina-chat-border);
354
354
  }
355
+ .gemina-chat__title {
356
+ margin-inline-end: auto;
357
+ font-size: 13px;
358
+ font-weight: 600;
359
+ overflow: hidden;
360
+ text-overflow: ellipsis;
361
+ white-space: nowrap;
362
+ }
355
363
  .gemina-chat__newchat {
356
364
  font: inherit;
357
365
  font-size: 12px;
@@ -440,10 +448,35 @@ var CHAT_CSS = `
440
448
  }
441
449
  .gemina-chat__typing {
442
450
  align-self: flex-start;
451
+ display: flex;
452
+ align-items: center;
453
+ gap: 5px;
443
454
  color: var(--gemina-chat-muted);
444
455
  font-size: 12px;
445
456
  padding: 0 4px;
446
457
  }
458
+ .gemina-chat__typing-dots {
459
+ display: inline-flex;
460
+ align-items: center;
461
+ gap: 3px;
462
+ }
463
+ .gemina-chat__typing-dots span {
464
+ width: 4px;
465
+ height: 4px;
466
+ border-radius: 50%;
467
+ background: currentColor;
468
+ opacity: 0.25;
469
+ animation: gemina-chat-thinking 1.2s infinite ease-in-out;
470
+ }
471
+ .gemina-chat__typing-dots span:nth-child(2) { animation-delay: 0.2s; }
472
+ .gemina-chat__typing-dots span:nth-child(3) { animation-delay: 0.4s; }
473
+ @keyframes gemina-chat-thinking {
474
+ 0%, 60%, 100% { opacity: 0.25; transform: translateY(0); }
475
+ 30% { opacity: 1; transform: translateY(-2px); }
476
+ }
477
+ @media (prefers-reduced-motion: reduce) {
478
+ .gemina-chat__typing-dots span { animation: none; opacity: 0.6; }
479
+ }
447
480
  .gemina-chat__composer {
448
481
  display: flex;
449
482
  gap: 8px;
@@ -498,6 +531,7 @@ function GeminaChat(props) {
498
531
  theme = "auto",
499
532
  dir = "auto",
500
533
  placeholder = "Ask about your documents\u2026",
534
+ title,
501
535
  onCitationClick,
502
536
  className
503
537
  } = props;
@@ -674,16 +708,19 @@ function GeminaChat(props) {
674
708
  className ?? ""
675
709
  ].filter((part) => part.length > 0).join(" ");
676
710
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: rootClassName, dir: effectiveDir, children: [
677
- messages.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "gemina-chat__header", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
678
- "button",
679
- {
680
- type: "button",
681
- className: "gemina-chat__newchat",
682
- onClick: startNewChat,
683
- disabled: busy,
684
- children: "New chat"
685
- }
686
- ) }),
711
+ (title !== void 0 || messages.length > 0) && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "gemina-chat__header", children: [
712
+ title !== void 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "gemina-chat__title", dir: bubbleDir, children: title }),
713
+ messages.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
714
+ "button",
715
+ {
716
+ type: "button",
717
+ className: "gemina-chat__newchat",
718
+ onClick: startNewChat,
719
+ disabled: busy,
720
+ children: "New chat"
721
+ }
722
+ )
723
+ ] }),
687
724
  /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
688
725
  "div",
689
726
  {
@@ -753,7 +790,16 @@ function GeminaChat(props) {
753
790
  message.id
754
791
  );
755
792
  }),
756
- busy && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "gemina-chat__typing", children: "Thinking\u2026" })
793
+ busy && // The label alone is what the aria-live log announces; the dots are
794
+ // decoration (aria-hidden), and prefers-reduced-motion freezes them.
795
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "gemina-chat__typing", children: [
796
+ "Thinking",
797
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "gemina-chat__typing-dots", "aria-hidden": "true", children: [
798
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {}),
799
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {}),
800
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {})
801
+ ] })
802
+ ] })
757
803
  ]
758
804
  }
759
805
  ),
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/token-manager.ts","../src/chat.tsx","../src/version.ts"],"sourcesContent":["// Token management (no React required — also available as\n// `@gemina/elements/token-manager`).\nexport { GeminaTokenManager } from './token-manager';\nexport type { FetchTokenResult, GeminaTokenManagerOptions } from './token-manager';\n\n// Chat UI (React — also available as `@gemina/elements/chat`).\nexport { GeminaChat } from './chat';\nexport type { GeminaChatProps, GeminaChatTheme, GeminaChatDirection } from './chat';\n\nexport { VERSION } from './version';\n","/**\n * GeminaTokenManager — in-memory holder for short-lived Gemina session\n * tokens, per the Document Intelligence token spec (PRD §6.11.1).\n *\n * Security model (the five footguns this file designs out):\n *\n * 1. **The API key never enters the browser.** The constructor throws if it\n * is handed a raw string instead of a `fetchToken` callback, and\n * `getToken()` rejects if the callback ever resolves with an\n * API-key-shaped string (32 alphanumerics, no dots).\n * 2. **The token is never persisted.** No `localStorage`, `sessionStorage`,\n * cookies, or IndexedDB anywhere in this package — the token lives only\n * in memory, inside state that is not an own property of the instance.\n * 3. **The browser never asserts its own scope.** This manager carries no\n * scope parameters at all; scope is signed into the token server-side.\n * 4. **No refresh token is held in the browser.** Renewal always goes back\n * through the tenant's own authenticated backend via `fetchToken`.\n * 5. **The SDK cannot mint or widen TTL/scope.** This class only *stores*\n * what the tenant backend minted; it has no code path to\n * `POST /v1/sessions/token`.\n *\n * Storage choice: internal state (including the token) lives in a\n * module-scoped `WeakMap` keyed by the instance rather than in an ordinary\n * class field. An ordinary field — even a `#private` one via devtools — is\n * trivially discoverable by enumerating the instance; the WeakMap keeps the\n * token out of `Object.keys`, `JSON.stringify`, spread copies, and casual\n * inspection, and it is unreachable without a reference to both the WeakMap\n * (module-private) and the instance. This is hardening against accidental\n * exposure/serialization, not encryption: code running in the same realm\n * with a debugger can still read process memory. The upgrade path for\n * stronger isolation is a Web Worker (see PRD §6.11.1).\n *\n * SSR-safe: this module touches no `window`/`document` at import time and\n * starts no timers — refresh happens lazily inside `getToken()`, so an idle\n * manager consumes nothing and never keeps a Node process alive.\n */\n\n/** What `fetchToken` must resolve with (mirror of the mint response). */\nexport interface FetchTokenResult {\n /** The raw session token (a JWT). Pass it WITHOUT a \"Bearer \" prefix. */\n token: string;\n /** Token lifetime in seconds, as returned by the mint endpoint. */\n expiresIn: number;\n}\n\n/** Constructor options for {@link GeminaTokenManager}. */\nexport interface GeminaTokenManagerOptions {\n /**\n * Callback that obtains a fresh session token from the TENANT'S OWN\n * backend (which in turn calls Gemina's `POST /v1/sessions/token` with\n * the API key, server-side). It must resolve with\n * `{ token, expiresIn }`. It must NEVER return a Gemina API key.\n */\n fetchToken: () => Promise<FetchTokenResult>;\n /**\n * How many seconds before the token's expiry `getToken()` starts\n * refreshing. Default 60 (the PRD's `exp − 60s` refresh point).\n */\n refreshSkewSeconds?: number;\n}\n\n/** Gemina API keys are exactly 32 alphanumerics with no prefix. */\nconst API_KEY_SHAPE = /^[A-Za-z0-9]{32}$/;\n\nconst API_KEY_ERROR =\n 'GeminaTokenManager received an API-key-shaped credential (32 alphanumeric ' +\n 'characters). Gemina API keys are master keys and must NEVER enter the ' +\n 'browser: mint a short-lived session token on YOUR backend via ' +\n 'POST /v1/sessions/token (sessions.mintRetrievalToken in @gemina/sdk) and ' +\n 'return { token, expiresIn } from fetchToken instead.';\n\ninterface TokenState {\n fetchToken: () => Promise<FetchTokenResult>;\n refreshSkewMs: number;\n /** The cached raw token, or null when absent/invalidated. */\n token: string | null;\n /** Epoch ms after which the cached token is considered expired. */\n expiresAtMs: number;\n /** Shared in-flight refresh, so concurrent callers never stampede. */\n inFlight: Promise<string> | null;\n /** Bumped by invalidate(); stale refreshes must not repopulate the cache. */\n epoch: number;\n}\n\n// Module-private state store — see the header comment for why the token is\n// deliberately NOT an own property of the instance.\nconst STATES = new WeakMap<GeminaTokenManager, TokenState>();\n\nfunction getState(manager: GeminaTokenManager): TokenState {\n const state = STATES.get(manager);\n if (state === undefined) {\n throw new Error(\n 'GeminaTokenManager state missing — was the instance constructed normally? ' +\n '(Object.create/deserialization is not supported.)',\n );\n }\n return state;\n}\n\n/**\n * Validate what `fetchToken` resolved with and return the raw token.\n * Rejects API-key-shaped strings and anything that is not JWT-shaped.\n */\nfunction validateFetchedToken(result: FetchTokenResult): string {\n if (result === null || typeof result !== 'object') {\n throw new Error(\n 'GeminaTokenManager: fetchToken must resolve with { token, expiresIn } ' +\n `(got ${result === null ? 'null' : typeof result}).`,\n );\n }\n const { token, expiresIn } = result;\n if (typeof token !== 'string' || token.length === 0) {\n throw new Error(\n 'GeminaTokenManager: fetchToken resolved without a token string. ' +\n 'Return { token, expiresIn } from the mint response.',\n );\n }\n if (API_KEY_SHAPE.test(token)) {\n throw new Error(API_KEY_ERROR);\n }\n // Session tokens are JWTs: exactly three non-empty dot-separated segments.\n const segments = token.split('.');\n if (segments.length !== 3 || segments.some((segment) => segment.length === 0)) {\n throw new Error(\n 'GeminaTokenManager: fetchToken resolved with a value that is not a ' +\n 'session token. Gemina session tokens are JWTs (three dot-separated ' +\n 'segments); return the `token` field from POST /v1/sessions/token.',\n );\n }\n if (typeof expiresIn !== 'number' || !Number.isFinite(expiresIn) || expiresIn <= 0) {\n throw new Error(\n 'GeminaTokenManager: fetchToken resolved with an invalid expiresIn ' +\n `(${String(expiresIn)}). Return the mint response's expiresIn (seconds > 0).`,\n );\n }\n return token;\n}\n\n/**\n * Holds a short-lived Gemina session token in memory and keeps it fresh.\n *\n * ```ts\n * const tokenManager = new GeminaTokenManager({\n * // YOUR backend endpoint — it holds the API key and mints the token.\n * fetchToken: async () => {\n * const res = await fetch(\"/api/gemina-session\", { method: \"POST\" });\n * if (!res.ok) throw new Error(\"Failed to mint Gemina session token\");\n * return res.json(); // { token, expiresIn }\n * },\n * });\n * ```\n *\n * - `getToken()` fetches lazily on first use, then auto-refreshes when the\n * cached token is within `refreshSkewSeconds` of expiry. Concurrent\n * callers share a single in-flight fetch.\n * - `invalidate()` drops the cache so the next `getToken()` refetches\n * (use after a 401).\n * - No timers run while idle; nothing is ever written to storage.\n */\nexport class GeminaTokenManager {\n constructor(options: GeminaTokenManagerOptions) {\n if (typeof options === 'string') {\n // Someone did `new GeminaTokenManager(\"<api key or token>\")`.\n throw new Error(\n API_KEY_SHAPE.test(options)\n ? API_KEY_ERROR\n : 'GeminaTokenManager takes { fetchToken } — a callback that asks ' +\n 'YOUR backend for a fresh session token — not a raw string. ' +\n 'Never pass a Gemina API key to browser code.',\n );\n }\n if (options === null || typeof options !== 'object') {\n throw new Error(\n 'GeminaTokenManager requires an options object: new GeminaTokenManager({ fetchToken }).',\n );\n }\n const { fetchToken, refreshSkewSeconds = 60 } = options;\n if (typeof fetchToken === 'string') {\n throw new Error(\n (API_KEY_SHAPE.test(fetchToken) ? `${API_KEY_ERROR} ` : '') +\n 'GeminaTokenManager: fetchToken must be a function returning ' +\n 'Promise<{ token, expiresIn }>, not a string.',\n );\n }\n if (typeof fetchToken !== 'function') {\n throw new Error(\n 'GeminaTokenManager: fetchToken is required and must be a function ' +\n 'returning Promise<{ token, expiresIn }>.',\n );\n }\n if (\n typeof refreshSkewSeconds !== 'number' ||\n !Number.isFinite(refreshSkewSeconds) ||\n refreshSkewSeconds < 0\n ) {\n throw new Error(\n `GeminaTokenManager: refreshSkewSeconds must be a non-negative number (got ${String(\n refreshSkewSeconds,\n )}).`,\n );\n }\n\n STATES.set(this, {\n fetchToken,\n refreshSkewMs: refreshSkewSeconds * 1000,\n token: null,\n expiresAtMs: 0,\n inFlight: null,\n epoch: 0,\n });\n }\n\n /**\n * Return a valid session token, fetching or refreshing as needed.\n *\n * A cached token is reused until `now >= expiry - refreshSkewSeconds`\n * (expiry computed as `Date.now() + expiresIn * 1000` at fetch time).\n * All concurrent callers during a refresh share ONE in-flight fetch.\n * A failed fetch is not cached — the next call retries.\n */\n getToken(): Promise<string> {\n const state = getState(this);\n\n if (state.token !== null && Date.now() < state.expiresAtMs - state.refreshSkewMs) {\n return Promise.resolve(state.token);\n }\n\n if (state.inFlight !== null) {\n return state.inFlight;\n }\n\n const epoch = state.epoch;\n const fetchStartedAtMs = Date.now();\n // Start the user callback immediately (getToken() should fire the mint\n // request right away), but convert a synchronous throw into a rejection\n // so the in-flight bookkeeping below stays consistent.\n let fetched: Promise<FetchTokenResult>;\n try {\n fetched = Promise.resolve(state.fetchToken());\n } catch (error) {\n fetched = Promise.reject(error);\n }\n const inFlight: Promise<string> = fetched\n .then((result) => {\n const token = validateFetchedToken(result);\n if (state.epoch === epoch) {\n state.token = token;\n state.expiresAtMs = fetchStartedAtMs + result.expiresIn * 1000;\n }\n // If invalidate() ran mid-flight, still hand this (already-minted)\n // token to the callers who asked before the invalidation — but do\n // not cache it; the next getToken() fetches fresh.\n return token;\n })\n .finally(() => {\n if (state.inFlight === inFlight) {\n state.inFlight = null;\n }\n });\n\n state.inFlight = inFlight;\n return inFlight;\n }\n\n /**\n * Drop the cached token (and detach any in-flight refresh) so the next\n * `getToken()` fetches a fresh one. Call this when the API answers 401,\n * then retry the request once with a new `getToken()`.\n */\n invalidate(): void {\n const state = getState(this);\n state.token = null;\n state.expiresAtMs = 0;\n state.inFlight = null;\n state.epoch += 1;\n }\n}\n","/**\n * <GeminaChat> — drop-in chat UI over Gemina Document Intelligence.\n *\n * Auth flows exclusively through a {@link GeminaTokenManager}: the component\n * asks it for a short-lived session token per turn and calls\n * `POST /v1/chat/query` through `@gemina/sdk`. It never sees — and cannot\n * accept — a Gemina API key (the token manager throws on API-key-shaped\n * credentials).\n *\n * SSR-safe: no `window`/`document` access at import time; styles are\n * injected on mount.\n */\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type * as React from 'react';\nimport { GeminaClient } from '@gemina/sdk';\nimport type { ChatQueryOutDTO } from '@gemina/sdk';\nimport type { GeminaTokenManager } from './token-manager';\nimport { VERSION } from './version';\n\n/** Visual theme. `\"auto\"` follows `prefers-color-scheme`. */\nexport type GeminaChatTheme = 'light' | 'dark' | 'auto';\n\n/**\n * Text direction. `\"auto\"` flips the widget to RTL when the user's latest\n * message contains Hebrew, and lets each bubble resolve its own direction.\n */\nexport type GeminaChatDirection = 'ltr' | 'rtl' | 'auto';\n\nexport interface GeminaChatProps {\n /** Token source. Required — see {@link GeminaTokenManager}. */\n tokenManager: GeminaTokenManager;\n /** Gemina API base URL (default `https://api.gemina.co`). */\n baseUrl?: string;\n /**\n * Optional end-user id forwarded with each query. On the session-token\n * path the token's SIGNED scope always wins server-side — this is a\n * hint, not a security control.\n */\n endUserId?: string;\n /** Visual theme (default `\"auto\"`). */\n theme?: GeminaChatTheme;\n /** Text direction (default `\"auto\"`). */\n dir?: GeminaChatDirection;\n /** Input placeholder text. */\n placeholder?: string;\n /** Called with the cited `documentId` when a citation chip is clicked. */\n onCitationClick?: (documentId: string) => void;\n /** Extra class name(s) for the root element (e.g. to override CSS vars). */\n className?: string;\n}\n\ninterface UserMessage {\n id: number;\n role: 'user';\n text: string;\n}\n\ninterface AssistantMessage {\n id: number;\n role: 'assistant';\n text: string;\n citations: string[];\n confident: boolean;\n}\n\ninterface ErrorMessage {\n id: number;\n role: 'error';\n text: string;\n /** Present only when a retry is offered; holds the original user text. */\n retryText?: string;\n}\n\ntype ChatMessage = UserMessage | AssistantMessage | ErrorMessage;\n\n/** `Omit` that distributes over each member of a union. */\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\n\ntype ChatMessageInput = DistributiveOmit<ChatMessage, 'id'>;\n\n/** Hebrew Unicode block (U+0590–U+05FF). */\nconst HEBREW_RE = /[\\u0590-\\u05FF]/;\n\n/**\n * The response-like object carried by a thrown transport error. We pull it off\n * by shape rather than `instanceof ResponseError` — robust against duplicated\n * `@gemina/sdk` copies in a bundle (class identity is not shared across\n * copies). On the fetch transport this is the raw `Response`, so `status`,\n * `headers`, and the JSON body are all reachable from here.\n */\ninterface ResponseLike {\n status?: number;\n headers?: { get?: (name: string) => string | null };\n json?: () => Promise<unknown>;\n clone?: () => ResponseLike;\n}\n\nfunction getResponseLike(error: unknown): ResponseLike | undefined {\n if (error !== null && typeof error === 'object' && 'response' in error) {\n const response = (error as { response?: unknown }).response;\n if (response !== null && typeof response === 'object') {\n return response as ResponseLike;\n }\n }\n return undefined;\n}\n\n/** Extract an HTTP status from a thrown value, or `undefined`. */\nfunction httpStatus(error: unknown): number | undefined {\n const status = getResponseLike(error)?.status;\n return typeof status === 'number' ? status : undefined;\n}\n\n// Stable backend error codes. These survive production's `detail`-stripping\n// (see the chat-pricing handoff); we switch on HTTP status first and refine\n// with these where the same status can mean two different things.\nconst ERR_CHAT_QUOTA_EXCEEDED = 'CHAT_QUOTA_EXCEEDED';\nconst ERR_DI_NOT_IN_PLAN = 'DOCUMENT_INTELLIGENCE_NOT_IN_PLAN';\nconst ERR_UNPROCESSABLE = 'UNPROCESSABLE_ERROR';\nconst ERR_BAD_GATEWAY = 'BAD_GATEWAY_ERROR';\n// A conversation id that the server no longer knows (24h idle TTL, explicit\n// reset, or end-user scope drift). A turn that CARRIED a session and 404s is\n// this by construction — the chat/query handler raises 404 for nothing else —\n// so the component drops the id and restarts the conversation transparently.\nconst ERR_CHAT_SESSION_NOT_FOUND = 'CHAT_SESSION_NOT_FOUND';\n\ninterface ChatErrorInfo {\n status: number | undefined;\n errorCode: string | undefined;\n /** Human-readable server fallback (`errors[0].description`). */\n description: string | undefined;\n /** Whole seconds until reset, from the `Retry-After` header (429). */\n retryAfterSeconds: number | undefined;\n}\n\n/**\n * Read what the backend actually sent on an error. Only the HTTP status, the\n * stable `errors[0].error_code` / `description`, and the `Retry-After` header\n * are reliable across environments — production strips `errors[0].detail`, so\n * we never touch it. The fetch body can be read once, so we clone defensively;\n * if that fails (non-JSON, empty, or already consumed) the status still stands.\n */\nasync function readChatError(error: unknown): Promise<ChatErrorInfo> {\n const response = getResponseLike(error);\n const info: ChatErrorInfo = {\n status: typeof response?.status === 'number' ? response.status : undefined,\n errorCode: undefined,\n description: undefined,\n retryAfterSeconds: undefined,\n };\n if (response === undefined) {\n return info;\n }\n\n const rawRetryAfter = response.headers?.get?.('retry-after');\n if (rawRetryAfter !== null && rawRetryAfter !== undefined) {\n const seconds = Number(rawRetryAfter);\n if (Number.isFinite(seconds) && seconds > 0) {\n info.retryAfterSeconds = seconds;\n }\n }\n\n let body: unknown;\n try {\n const source = typeof response.clone === 'function' ? response.clone() : response;\n body = typeof source.json === 'function' ? await source.json() : undefined;\n } catch {\n body = undefined;\n }\n if (body !== null && typeof body === 'object') {\n const errors = (body as { errors?: unknown }).errors;\n if (\n Array.isArray(errors) &&\n errors.length > 0 &&\n errors[0] !== null &&\n typeof errors[0] === 'object'\n ) {\n const first = errors[0] as { error_code?: unknown; description?: unknown };\n if (typeof first.error_code === 'string') {\n info.errorCode = first.error_code;\n }\n if (typeof first.description === 'string') {\n info.description = first.description;\n }\n }\n }\n return info;\n}\n\nconst SESSION_EXPIRED_TEXT = 'Session expired — please reload the page or sign in again.';\nconst CONVERSATION_RESET_TEXT =\n 'This conversation is no longer available — send your message again to start a new one.';\nconst RATE_LIMIT_TEXT = \"You're sending messages too quickly — try again shortly.\";\nconst PLAN_GATE_TEXT = \"Chat isn't included in your plan.\";\nconst UNANSWERABLE_TEXT = \"We couldn't answer that. Try rephrasing your question.\";\nconst SERVICE_UNAVAILABLE_TEXT = 'The chat service is temporarily unavailable. Please try again.';\nconst GENERIC_ERROR_TEXT = \"Something went wrong and your message wasn't answered.\";\n\n/** Friendly \"resets in about N days/hours/minutes\" from Retry-After seconds. */\nfunction formatResetHint(seconds: number | undefined): string {\n if (seconds === undefined || !Number.isFinite(seconds) || seconds <= 0) {\n return 'at the next billing cycle';\n }\n const days = Math.round(seconds / 86400);\n if (days >= 1) {\n return `in about ${days} day${days === 1 ? '' : 's'}`;\n }\n const hours = Math.round(seconds / 3600);\n if (hours >= 1) {\n return `in about ${hours} hour${hours === 1 ? '' : 's'}`;\n }\n const minutes = Math.max(1, Math.round(seconds / 60));\n return `in about ${minutes} minute${minutes === 1 ? '' : 's'}`;\n}\n\n/**\n * Map a chat error to the bubble we render. Switches on HTTP status, refined by\n * the stable backend `error_code`. `retryText` is set only when resending the\n * same text could plausibly succeed — never for quota / plan / validation\n * outcomes, where an identical retry would just fail the same way.\n */\nfunction describeChatError(info: ChatErrorInfo, originalText: string): ChatMessageInput {\n const { status, errorCode } = info;\n\n // Over the included cap AND out of credits — the chat is blocked. Retrying\n // won't help; point at the reset time from the Retry-After header.\n if (status === 429 && errorCode === ERR_CHAT_QUOTA_EXCEEDED) {\n return {\n role: 'error',\n text: `You've used your included chats and are out of credits. Included chats reset ${formatResetHint(\n info.retryAfterSeconds,\n )}.`,\n };\n }\n // Any other 429 is a transient rate limit — a retry after a moment is fine.\n if (status === 429) {\n return { role: 'error', text: RATE_LIMIT_TEXT, retryText: originalText };\n }\n // Document Intelligence not in the plan/contract. NOT an auth failure.\n if (status === 402 || status === 403 || errorCode === ERR_DI_NOT_IN_PLAN) {\n return { role: 'error', text: PLAN_GATE_TEXT };\n }\n // Session expired — only surfaces after the 401-invalidate-retry-once path\n // has already failed a second time.\n if (status === 401) {\n return { role: 'error', text: SESSION_EXPIRED_TEXT };\n }\n // A stale conversation id that slipped past the transparent restart — only\n // the stable error_code reliably means \"the conversation is gone\". A bare 404\n // is a routing/gateway miss (e.g. the endpoint isn't deployed), which reads\n // better as a transient service error than a confusing \"conversation reset\".\n if (errorCode === ERR_CHAT_SESSION_NOT_FOUND) {\n return { role: 'error', text: CONVERSATION_RESET_TEXT, retryText: originalText };\n }\n if (status === 404) {\n return { role: 'error', text: SERVICE_UNAVAILABLE_TEXT, retryText: originalText };\n }\n // The question couldn't be answered (e.g. no searchable text). Expected, not\n // a server error — invite a rephrase rather than a blind retry.\n if (status === 422 || errorCode === ERR_UNPROCESSABLE) {\n return { role: 'error', text: UNANSWERABLE_TEXT };\n }\n // Chat backend timed out / unreachable — transient, offer retry.\n if (status === 502 || errorCode === ERR_BAD_GATEWAY) {\n return { role: 'error', text: SERVICE_UNAVAILABLE_TEXT, retryText: originalText };\n }\n // Anything else (incl. 500): prefer the server's description if it sent one.\n return {\n role: 'error',\n text: info.description ?? GENERIC_ERROR_TEXT,\n retryText: originalText,\n };\n}\n\n/**\n * The API reports citations as an array of `documentId` strings; normalize\n * defensively so `{ documentId }` objects also work if the shape evolves.\n */\nfunction normalizeCitations(citations: unknown): string[] {\n if (!Array.isArray(citations)) {\n return [];\n }\n const ids: string[] = [];\n for (const item of citations) {\n if (typeof item === 'string' && item.length > 0) {\n ids.push(item);\n } else if (\n item !== null &&\n typeof item === 'object' &&\n typeof (item as { documentId?: unknown }).documentId === 'string'\n ) {\n ids.push((item as { documentId: string }).documentId);\n }\n }\n return ids;\n}\n\n// --- Styles -----------------------------------------------------------------\n// Hand-rolled, no UI deps. Everything is scoped under .gemina-chat and driven\n// by CSS custom properties so host apps can re-theme without touching the DOM.\n\nconst DARK_VARS = `\n --gemina-chat-bg: #101418;\n --gemina-chat-fg: #e6e9ee;\n --gemina-chat-border: #2a323c;\n --gemina-chat-accent: #4c8dff;\n --gemina-chat-accent-fg: #ffffff;\n --gemina-chat-assistant-bg: #1c232b;\n --gemina-chat-assistant-fg: #e6e9ee;\n --gemina-chat-muted: #98a2b3;\n --gemina-chat-error: #f97066;\n --gemina-chat-low-confidence: #f7b27a;\n`;\n\nconst CHAT_CSS = `\n.gemina-chat {\n --gemina-chat-bg: #ffffff;\n --gemina-chat-fg: #1a1d21;\n --gemina-chat-border: #d9dce1;\n --gemina-chat-accent: #2f6fed;\n --gemina-chat-accent-fg: #ffffff;\n --gemina-chat-assistant-bg: #f2f4f7;\n --gemina-chat-assistant-fg: #1a1d21;\n --gemina-chat-muted: #667085;\n --gemina-chat-error: #b42318;\n --gemina-chat-low-confidence: #b54708;\n --gemina-chat-radius: 10px;\n --gemina-chat-font: system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif;\n\n box-sizing: border-box;\n display: flex;\n flex-direction: column;\n min-height: 320px;\n max-height: 600px;\n background: var(--gemina-chat-bg);\n color: var(--gemina-chat-fg);\n border: 1px solid var(--gemina-chat-border);\n border-radius: var(--gemina-chat-radius);\n font-family: var(--gemina-chat-font);\n font-size: 14px;\n line-height: 1.5;\n}\n.gemina-chat *, .gemina-chat *::before, .gemina-chat *::after { box-sizing: border-box; }\n.gemina-chat--dark { ${DARK_VARS} }\n@media (prefers-color-scheme: dark) {\n .gemina-chat--auto { ${DARK_VARS} }\n}\n.gemina-chat__header {\n display: flex;\n justify-content: flex-end;\n align-items: center;\n flex: 0 0 auto;\n padding: 6px 10px;\n border-bottom: 1px solid var(--gemina-chat-border);\n}\n.gemina-chat__newchat {\n font: inherit;\n font-size: 12px;\n padding: 3px 10px;\n border-radius: var(--gemina-chat-radius);\n border: 1px solid var(--gemina-chat-border);\n background: transparent;\n color: var(--gemina-chat-accent);\n cursor: pointer;\n}\n.gemina-chat__newchat:hover:not(:disabled) { border-color: var(--gemina-chat-accent); }\n.gemina-chat__newchat:disabled { opacity: 0.5; cursor: default; }\n.gemina-chat__log {\n flex: 1;\n overflow-y: auto;\n padding: 12px;\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n.gemina-chat__msg {\n max-width: 85%;\n padding: 8px 12px;\n border-radius: var(--gemina-chat-radius);\n white-space: pre-wrap;\n overflow-wrap: break-word;\n}\n.gemina-chat__msg--user {\n align-self: flex-end;\n background: var(--gemina-chat-accent);\n color: var(--gemina-chat-accent-fg);\n}\n.gemina-chat--rtl .gemina-chat__msg--user, .gemina-chat[dir=\"rtl\"] .gemina-chat__msg--user {\n align-self: flex-start;\n}\n.gemina-chat--rtl .gemina-chat__msg--assistant, .gemina-chat[dir=\"rtl\"] .gemina-chat__msg--assistant {\n align-self: flex-end;\n}\n.gemina-chat__msg--assistant {\n align-self: flex-start;\n background: var(--gemina-chat-assistant-bg);\n color: var(--gemina-chat-assistant-fg);\n}\n.gemina-chat__msg--low-confidence {\n border: 1px dashed var(--gemina-chat-low-confidence);\n}\n.gemina-chat__low-confidence-note {\n margin-top: 6px;\n font-size: 12px;\n color: var(--gemina-chat-low-confidence);\n}\n.gemina-chat__citations {\n display: flex;\n flex-wrap: wrap;\n gap: 4px;\n margin-top: 6px;\n}\n.gemina-chat__citation {\n font: inherit;\n font-size: 12px;\n padding: 2px 8px;\n border-radius: 999px;\n border: 1px solid var(--gemina-chat-border);\n background: transparent;\n color: var(--gemina-chat-accent);\n cursor: pointer;\n}\n.gemina-chat__citation:hover { border-color: var(--gemina-chat-accent); }\n.gemina-chat__msg--error {\n align-self: flex-start;\n background: transparent;\n border: 1px solid var(--gemina-chat-error);\n color: var(--gemina-chat-error);\n}\n.gemina-chat__retry {\n font: inherit;\n font-size: 12px;\n margin-top: 6px;\n display: block;\n padding: 2px 10px;\n border-radius: var(--gemina-chat-radius);\n border: 1px solid var(--gemina-chat-error);\n background: transparent;\n color: var(--gemina-chat-error);\n cursor: pointer;\n}\n.gemina-chat__typing {\n align-self: flex-start;\n color: var(--gemina-chat-muted);\n font-size: 12px;\n padding: 0 4px;\n}\n.gemina-chat__composer {\n display: flex;\n gap: 8px;\n padding: 10px;\n border-top: 1px solid var(--gemina-chat-border);\n}\n.gemina-chat__input {\n flex: 1;\n resize: none;\n font: inherit;\n color: inherit;\n background: transparent;\n border: 1px solid var(--gemina-chat-border);\n border-radius: var(--gemina-chat-radius);\n padding: 8px 10px;\n min-height: 38px;\n}\n.gemina-chat__input:focus {\n outline: 2px solid var(--gemina-chat-accent);\n outline-offset: -1px;\n}\n.gemina-chat__send {\n font: inherit;\n align-self: flex-end;\n border: none;\n border-radius: var(--gemina-chat-radius);\n background: var(--gemina-chat-accent);\n color: var(--gemina-chat-accent-fg);\n padding: 8px 16px;\n cursor: pointer;\n}\n.gemina-chat__send:disabled { opacity: 0.5; cursor: default; }\n`;\n\nconst STYLE_ATTR = 'data-gemina-chat';\n\n/**\n * Inject the widget stylesheet once per document (idempotent across\n * instances; intentionally not removed on unmount so sibling instances and\n * quick remounts never flash unstyled).\n */\nfunction ensureStylesInjected(): void {\n if (typeof document === 'undefined') {\n return;\n }\n if (document.head.querySelector(`style[${STYLE_ATTR}]`) !== null) {\n return;\n }\n const style = document.createElement('style');\n style.setAttribute(STYLE_ATTR, VERSION);\n style.textContent = CHAT_CSS;\n document.head.appendChild(style);\n}\n\n/**\n * Embeddable Gemina Document Intelligence chat.\n *\n * ```tsx\n * <GeminaChat\n * tokenManager={tokenManager}\n * onCitationClick={(documentId) => openDocument(documentId)}\n * />\n * ```\n */\nexport function GeminaChat(props: GeminaChatProps): React.JSX.Element {\n const {\n tokenManager,\n baseUrl,\n endUserId,\n theme = 'auto',\n dir = 'auto',\n placeholder = 'Ask about your documents…',\n onCitationClick,\n className,\n } = props;\n\n const [messages, setMessages] = useState<ChatMessage[]>([]);\n const [draft, setDraft] = useState('');\n const [busy, setBusy] = useState(false);\n const nextIdRef = useRef(0);\n const mountedRef = useRef(false);\n const logRef = useRef<HTMLDivElement | null>(null);\n // The conversation id (server-issued) that gives the chat memory across\n // turns. Held in a ref, not state: it changes per turn but must never\n // trigger a re-render, and the send flow reads its latest value directly.\n // Distinct from the auth session TOKEN the token manager holds.\n const sessionIdRef = useRef<string | undefined>(undefined);\n\n useEffect(() => {\n mountedRef.current = true;\n ensureStylesInjected();\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n // Keep the newest message in view.\n useEffect(() => {\n const log = logRef.current;\n if (log !== null) {\n log.scrollTop = log.scrollHeight;\n }\n }, [messages, busy]);\n\n const appendMessage = useCallback((message: ChatMessageInput) => {\n const id = nextIdRef.current++;\n setMessages((prev) => [...prev, { ...message, id }]);\n }, []);\n\n const chatOnce = useCallback(\n (token: string, message: string): Promise<ChatQueryOutDTO> => {\n const client = GeminaClient.withSessionToken(token, baseUrl);\n const sessionId = sessionIdRef.current;\n return client.chat.chatQuery({\n // Thread the conversation id when we have one so follow-ups resolve\n // referents (\"what about the total?\"); omit it to start a new one.\n chatQueryInDTO: { message, endUserId, ...(sessionId ? { sessionId } : {}) },\n });\n },\n [baseUrl, endUserId],\n );\n\n /** One turn, with the mandated 401-invalidate-retry-once behavior. */\n const queryWithRetry = useCallback(\n async (message: string): Promise<ChatQueryOutDTO> => {\n const token = await tokenManager.getToken();\n try {\n return await chatOnce(token, message);\n } catch (error) {\n if (httpStatus(error) !== 401) {\n throw error;\n }\n // Token likely expired mid-session: drop it, re-mint via the\n // tenant backend, retry exactly once. A second 401 propagates.\n tokenManager.invalidate();\n const freshToken = await tokenManager.getToken();\n return await chatOnce(freshToken, message);\n }\n },\n [tokenManager, chatOnce],\n );\n\n const performSend = useCallback(\n async (text: string) => {\n setBusy(true);\n try {\n let result: ChatQueryOutDTO;\n const hadSession = sessionIdRef.current !== undefined;\n try {\n result = await queryWithRetry(text);\n } catch (error) {\n // A turn that CARRIED a session and 404s means the conversation is\n // gone (24h idle TTL, an explicit reset, or end-user scope drift).\n // Drop the stale id and retry once as a fresh conversation, so the\n // expiry is transparent — the user just gets an answer, no memory.\n if (hadSession && httpStatus(error) === 404) {\n sessionIdRef.current = undefined;\n result = await queryWithRetry(text);\n } else {\n throw error;\n }\n }\n if (!mountedRef.current) {\n return;\n }\n // The response always returns the (possibly newly created) conversation\n // id — store it so the next turn continues this thread.\n sessionIdRef.current = result.sessionId ?? sessionIdRef.current;\n appendMessage({\n role: 'assistant',\n text: result.answer,\n citations: normalizeCitations(result.citations),\n confident: result.confident !== false,\n });\n } catch (error) {\n if (!mountedRef.current) {\n return;\n }\n // Reading the error body is async (fetch), so re-check mount after.\n const info = await readChatError(error);\n if (!mountedRef.current) {\n return;\n }\n appendMessage(describeChatError(info, text));\n } finally {\n if (mountedRef.current) {\n setBusy(false);\n }\n }\n },\n [queryWithRetry, appendMessage],\n );\n\n /**\n * Reset to a brand-new conversation: clear the transcript and forget the\n * session id so the next message starts fresh. The old session is deleted\n * server-side best-effort — the local reset is authoritative, and a failed\n * delete just leaves the session to lapse on its idle TTL.\n */\n const startNewChat = useCallback(() => {\n if (busy) {\n return;\n }\n const staleSession = sessionIdRef.current;\n sessionIdRef.current = undefined;\n setMessages([]);\n setDraft('');\n if (staleSession !== undefined) {\n void (async () => {\n try {\n const token = await tokenManager.getToken();\n await GeminaClient.withSessionToken(token, baseUrl).chat.deleteChatSession({\n sessionId: staleSession,\n });\n } catch {\n // Unreachable/expired session: nothing to clean up client-side.\n }\n })();\n }\n }, [busy, tokenManager, baseUrl]);\n\n const submitDraft = useCallback(() => {\n const text = draft.trim();\n if (text.length === 0 || busy) {\n return;\n }\n setDraft('');\n appendMessage({ role: 'user', text });\n void performSend(text);\n }, [draft, busy, appendMessage, performSend]);\n\n const retryMessage = useCallback(\n (failed: ErrorMessage) => {\n if (busy || failed.retryText === undefined) {\n return;\n }\n const text = failed.retryText;\n // Replace the error entry; the original user bubble is still there.\n setMessages((prev) => prev.filter((message) => message.id !== failed.id));\n void performSend(text);\n },\n [busy, performSend],\n );\n\n const handleKeyDown = useCallback(\n (event: React.KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.key === 'Enter' && !event.shiftKey) {\n event.preventDefault();\n submitDraft();\n }\n },\n [submitDraft],\n );\n\n const handleSubmit = useCallback(\n (event: React.FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n submitDraft();\n },\n [submitDraft],\n );\n\n // dir=\"auto\": follow the user's latest message (Hebrew → RTL); individual\n // bubbles additionally resolve their own direction via dir=\"auto\".\n let effectiveDir: 'ltr' | 'rtl';\n if (dir === 'auto') {\n let lastUserText = '';\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (message !== undefined && message.role === 'user') {\n lastUserText = message.text;\n break;\n }\n }\n effectiveDir = HEBREW_RE.test(lastUserText) ? 'rtl' : 'ltr';\n } else {\n effectiveDir = dir;\n }\n const bubbleDir = dir === 'auto' ? 'auto' : undefined;\n\n const rootClassName = [\n 'gemina-chat',\n `gemina-chat--${theme}`,\n effectiveDir === 'rtl' ? 'gemina-chat--rtl' : '',\n className ?? '',\n ]\n .filter((part) => part.length > 0)\n .join(' ');\n\n return (\n <div className={rootClassName} dir={effectiveDir}>\n {messages.length > 0 && (\n <div className=\"gemina-chat__header\">\n <button\n type=\"button\"\n className=\"gemina-chat__newchat\"\n onClick={startNewChat}\n disabled={busy}\n >\n New chat\n </button>\n </div>\n )}\n <div\n ref={logRef}\n role=\"log\"\n aria-live=\"polite\"\n aria-busy={busy}\n aria-label=\"Chat messages\"\n className=\"gemina-chat__log\"\n >\n {messages.map((message) => {\n if (message.role === 'user') {\n return (\n <div\n key={message.id}\n className=\"gemina-chat__msg gemina-chat__msg--user\"\n dir={bubbleDir}\n >\n {message.text}\n </div>\n );\n }\n if (message.role === 'assistant') {\n const lowConfidence = !message.confident;\n return (\n <div\n key={message.id}\n className={\n 'gemina-chat__msg gemina-chat__msg--assistant' +\n (lowConfidence ? ' gemina-chat__msg--low-confidence' : '')\n }\n dir={bubbleDir}\n >\n {message.text}\n {lowConfidence && (\n <div className=\"gemina-chat__low-confidence-note\">\n Low confidence — please verify against the cited documents.\n </div>\n )}\n {message.citations.length > 0 && (\n <div className=\"gemina-chat__citations\">\n {message.citations.map((documentId, index) => (\n <button\n key={`${documentId}-${index}`}\n type=\"button\"\n className=\"gemina-chat__citation\"\n title={`Open document ${documentId}`}\n onClick={() => onCitationClick?.(documentId)}\n >\n {documentId}\n </button>\n ))}\n </div>\n )}\n </div>\n );\n }\n return (\n <div\n key={message.id}\n role=\"alert\"\n className=\"gemina-chat__msg gemina-chat__msg--error\"\n >\n {message.text}\n {message.retryText !== undefined && (\n <button\n type=\"button\"\n className=\"gemina-chat__retry\"\n onClick={() => retryMessage(message)}\n >\n Retry\n </button>\n )}\n </div>\n );\n })}\n {busy && <div className=\"gemina-chat__typing\">Thinking…</div>}\n </div>\n <form className=\"gemina-chat__composer\" onSubmit={handleSubmit}>\n <textarea\n className=\"gemina-chat__input\"\n aria-label=\"Chat message\"\n rows={1}\n value={draft}\n placeholder={placeholder}\n dir={bubbleDir}\n onChange={(event) => setDraft(event.target.value)}\n onKeyDown={handleKeyDown}\n />\n <button\n type=\"submit\"\n className=\"gemina-chat__send\"\n aria-label=\"Send message\"\n disabled={busy || draft.trim().length === 0}\n >\n Send\n </button>\n </form>\n </div>\n );\n}\n","/** Package version. Keep in sync with package.json. */\nexport const VERSION = '0.5.0';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC8DA,IAAM,gBAAgB;AAEtB,IAAM,gBACJ;AAqBF,IAAM,SAAS,oBAAI,QAAwC;AAE3D,SAAS,SAAS,SAAyC;AACzD,QAAM,QAAQ,OAAO,IAAI,OAAO;AAChC,MAAI,UAAU,QAAW;AACvB,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AACA,SAAO;AACT;AAMA,SAAS,qBAAqB,QAAkC;AAC9D,MAAI,WAAW,QAAQ,OAAO,WAAW,UAAU;AACjD,UAAM,IAAI;AAAA,MACR,8EACU,WAAW,OAAO,SAAS,OAAO,MAAM;AAAA,IACpD;AAAA,EACF;AACA,QAA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AAQ,MAAM,KAAK,EAAE,WAAW;AAAA,UAC3C;AAAA;AAAA,MAED;AAAA,OACF;AAAA,KACF;AAEJ;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts","../src/token-manager.ts","../src/chat.tsx","../src/version.ts"],"sourcesContent":["// Token management (no React required — also available as\n// `@gemina/elements/token-manager`).\nexport { GeminaTokenManager } from './token-manager';\nexport type { FetchTokenResult, GeminaTokenManagerOptions } from './token-manager';\n\n// Chat UI (React — also available as `@gemina/elements/chat`).\nexport { GeminaChat } from './chat';\nexport type { GeminaChatProps, GeminaChatTheme, GeminaChatDirection } from './chat';\n\nexport { VERSION } from './version';\n","/**\n * GeminaTokenManager — in-memory holder for short-lived Gemina session\n * tokens, per the Document Intelligence token spec (PRD §6.11.1).\n *\n * Security model (the five footguns this file designs out):\n *\n * 1. **The API key never enters the browser.** The constructor throws if it\n * is handed a raw string instead of a `fetchToken` callback, and\n * `getToken()` rejects if the callback ever resolves with an\n * API-key-shaped string (32 alphanumerics, no dots).\n * 2. **The token is never persisted.** No `localStorage`, `sessionStorage`,\n * cookies, or IndexedDB anywhere in this package — the token lives only\n * in memory, inside state that is not an own property of the instance.\n * 3. **The browser never asserts its own scope.** This manager carries no\n * scope parameters at all; scope is signed into the token server-side.\n * 4. **No refresh token is held in the browser.** Renewal always goes back\n * through the tenant's own authenticated backend via `fetchToken`.\n * 5. **The SDK cannot mint or widen TTL/scope.** This class only *stores*\n * what the tenant backend minted; it has no code path to\n * `POST /v1/sessions/token`.\n *\n * Storage choice: internal state (including the token) lives in a\n * module-scoped `WeakMap` keyed by the instance rather than in an ordinary\n * class field. An ordinary field — even a `#private` one via devtools — is\n * trivially discoverable by enumerating the instance; the WeakMap keeps the\n * token out of `Object.keys`, `JSON.stringify`, spread copies, and casual\n * inspection, and it is unreachable without a reference to both the WeakMap\n * (module-private) and the instance. This is hardening against accidental\n * exposure/serialization, not encryption: code running in the same realm\n * with a debugger can still read process memory. The upgrade path for\n * stronger isolation is a Web Worker (see PRD §6.11.1).\n *\n * SSR-safe: this module touches no `window`/`document` at import time and\n * starts no timers — refresh happens lazily inside `getToken()`, so an idle\n * manager consumes nothing and never keeps a Node process alive.\n */\n\n/** What `fetchToken` must resolve with (mirror of the mint response). */\nexport interface FetchTokenResult {\n /** The raw session token (a JWT). Pass it WITHOUT a \"Bearer \" prefix. */\n token: string;\n /** Token lifetime in seconds, as returned by the mint endpoint. */\n expiresIn: number;\n}\n\n/** Constructor options for {@link GeminaTokenManager}. */\nexport interface GeminaTokenManagerOptions {\n /**\n * Callback that obtains a fresh session token from the TENANT'S OWN\n * backend (which in turn calls Gemina's `POST /v1/sessions/token` with\n * the API key, server-side). It must resolve with\n * `{ token, expiresIn }`. It must NEVER return a Gemina API key.\n */\n fetchToken: () => Promise<FetchTokenResult>;\n /**\n * How many seconds before the token's expiry `getToken()` starts\n * refreshing. Default 60 (the PRD's `exp − 60s` refresh point).\n */\n refreshSkewSeconds?: number;\n}\n\n/** Gemina API keys are exactly 32 alphanumerics with no prefix. */\nconst API_KEY_SHAPE = /^[A-Za-z0-9]{32}$/;\n\nconst API_KEY_ERROR =\n 'GeminaTokenManager received an API-key-shaped credential (32 alphanumeric ' +\n 'characters). Gemina API keys are master keys and must NEVER enter the ' +\n 'browser: mint a short-lived session token on YOUR backend via ' +\n 'POST /v1/sessions/token (sessions.mintRetrievalToken in @gemina/sdk) and ' +\n 'return { token, expiresIn } from fetchToken instead.';\n\ninterface TokenState {\n fetchToken: () => Promise<FetchTokenResult>;\n refreshSkewMs: number;\n /** The cached raw token, or null when absent/invalidated. */\n token: string | null;\n /** Epoch ms after which the cached token is considered expired. */\n expiresAtMs: number;\n /** Shared in-flight refresh, so concurrent callers never stampede. */\n inFlight: Promise<string> | null;\n /** Bumped by invalidate(); stale refreshes must not repopulate the cache. */\n epoch: number;\n}\n\n// Module-private state store — see the header comment for why the token is\n// deliberately NOT an own property of the instance.\nconst STATES = new WeakMap<GeminaTokenManager, TokenState>();\n\nfunction getState(manager: GeminaTokenManager): TokenState {\n const state = STATES.get(manager);\n if (state === undefined) {\n throw new Error(\n 'GeminaTokenManager state missing — was the instance constructed normally? ' +\n '(Object.create/deserialization is not supported.)',\n );\n }\n return state;\n}\n\n/**\n * Validate what `fetchToken` resolved with and return the raw token.\n * Rejects API-key-shaped strings and anything that is not JWT-shaped.\n */\nfunction validateFetchedToken(result: FetchTokenResult): string {\n if (result === null || typeof result !== 'object') {\n throw new Error(\n 'GeminaTokenManager: fetchToken must resolve with { token, expiresIn } ' +\n `(got ${result === null ? 'null' : typeof result}).`,\n );\n }\n const { token, expiresIn } = result;\n if (typeof token !== 'string' || token.length === 0) {\n throw new Error(\n 'GeminaTokenManager: fetchToken resolved without a token string. ' +\n 'Return { token, expiresIn } from the mint response.',\n );\n }\n if (API_KEY_SHAPE.test(token)) {\n throw new Error(API_KEY_ERROR);\n }\n // Session tokens are JWTs: exactly three non-empty dot-separated segments.\n const segments = token.split('.');\n if (segments.length !== 3 || segments.some((segment) => segment.length === 0)) {\n throw new Error(\n 'GeminaTokenManager: fetchToken resolved with a value that is not a ' +\n 'session token. Gemina session tokens are JWTs (three dot-separated ' +\n 'segments); return the `token` field from POST /v1/sessions/token.',\n );\n }\n if (typeof expiresIn !== 'number' || !Number.isFinite(expiresIn) || expiresIn <= 0) {\n throw new Error(\n 'GeminaTokenManager: fetchToken resolved with an invalid expiresIn ' +\n `(${String(expiresIn)}). Return the mint response's expiresIn (seconds > 0).`,\n );\n }\n return token;\n}\n\n/**\n * Holds a short-lived Gemina session token in memory and keeps it fresh.\n *\n * ```ts\n * const tokenManager = new GeminaTokenManager({\n * // YOUR backend endpoint — it holds the API key and mints the token.\n * fetchToken: async () => {\n * const res = await fetch(\"/api/gemina-session\", { method: \"POST\" });\n * if (!res.ok) throw new Error(\"Failed to mint Gemina session token\");\n * return res.json(); // { token, expiresIn }\n * },\n * });\n * ```\n *\n * - `getToken()` fetches lazily on first use, then auto-refreshes when the\n * cached token is within `refreshSkewSeconds` of expiry. Concurrent\n * callers share a single in-flight fetch.\n * - `invalidate()` drops the cache so the next `getToken()` refetches\n * (use after a 401).\n * - No timers run while idle; nothing is ever written to storage.\n */\nexport class GeminaTokenManager {\n constructor(options: GeminaTokenManagerOptions) {\n if (typeof options === 'string') {\n // Someone did `new GeminaTokenManager(\"<api key or token>\")`.\n throw new Error(\n API_KEY_SHAPE.test(options)\n ? API_KEY_ERROR\n : 'GeminaTokenManager takes { fetchToken } — a callback that asks ' +\n 'YOUR backend for a fresh session token — not a raw string. ' +\n 'Never pass a Gemina API key to browser code.',\n );\n }\n if (options === null || typeof options !== 'object') {\n throw new Error(\n 'GeminaTokenManager requires an options object: new GeminaTokenManager({ fetchToken }).',\n );\n }\n const { fetchToken, refreshSkewSeconds = 60 } = options;\n if (typeof fetchToken === 'string') {\n throw new Error(\n (API_KEY_SHAPE.test(fetchToken) ? `${API_KEY_ERROR} ` : '') +\n 'GeminaTokenManager: fetchToken must be a function returning ' +\n 'Promise<{ token, expiresIn }>, not a string.',\n );\n }\n if (typeof fetchToken !== 'function') {\n throw new Error(\n 'GeminaTokenManager: fetchToken is required and must be a function ' +\n 'returning Promise<{ token, expiresIn }>.',\n );\n }\n if (\n typeof refreshSkewSeconds !== 'number' ||\n !Number.isFinite(refreshSkewSeconds) ||\n refreshSkewSeconds < 0\n ) {\n throw new Error(\n `GeminaTokenManager: refreshSkewSeconds must be a non-negative number (got ${String(\n refreshSkewSeconds,\n )}).`,\n );\n }\n\n STATES.set(this, {\n fetchToken,\n refreshSkewMs: refreshSkewSeconds * 1000,\n token: null,\n expiresAtMs: 0,\n inFlight: null,\n epoch: 0,\n });\n }\n\n /**\n * Return a valid session token, fetching or refreshing as needed.\n *\n * A cached token is reused until `now >= expiry - refreshSkewSeconds`\n * (expiry computed as `Date.now() + expiresIn * 1000` at fetch time).\n * All concurrent callers during a refresh share ONE in-flight fetch.\n * A failed fetch is not cached — the next call retries.\n */\n getToken(): Promise<string> {\n const state = getState(this);\n\n if (state.token !== null && Date.now() < state.expiresAtMs - state.refreshSkewMs) {\n return Promise.resolve(state.token);\n }\n\n if (state.inFlight !== null) {\n return state.inFlight;\n }\n\n const epoch = state.epoch;\n const fetchStartedAtMs = Date.now();\n // Start the user callback immediately (getToken() should fire the mint\n // request right away), but convert a synchronous throw into a rejection\n // so the in-flight bookkeeping below stays consistent.\n let fetched: Promise<FetchTokenResult>;\n try {\n fetched = Promise.resolve(state.fetchToken());\n } catch (error) {\n fetched = Promise.reject(error);\n }\n const inFlight: Promise<string> = fetched\n .then((result) => {\n const token = validateFetchedToken(result);\n if (state.epoch === epoch) {\n state.token = token;\n state.expiresAtMs = fetchStartedAtMs + result.expiresIn * 1000;\n }\n // If invalidate() ran mid-flight, still hand this (already-minted)\n // token to the callers who asked before the invalidation — but do\n // not cache it; the next getToken() fetches fresh.\n return token;\n })\n .finally(() => {\n if (state.inFlight === inFlight) {\n state.inFlight = null;\n }\n });\n\n state.inFlight = inFlight;\n return inFlight;\n }\n\n /**\n * Drop the cached token (and detach any in-flight refresh) so the next\n * `getToken()` fetches a fresh one. Call this when the API answers 401,\n * then retry the request once with a new `getToken()`.\n */\n invalidate(): void {\n const state = getState(this);\n state.token = null;\n state.expiresAtMs = 0;\n state.inFlight = null;\n state.epoch += 1;\n }\n}\n","/**\n * <GeminaChat> — drop-in chat UI over Gemina Document Intelligence.\n *\n * Auth flows exclusively through a {@link GeminaTokenManager}: the component\n * asks it for a short-lived session token per turn and calls\n * `POST /v1/chat/query` through `@gemina/sdk`. It never sees — and cannot\n * accept — a Gemina API key (the token manager throws on API-key-shaped\n * credentials).\n *\n * SSR-safe: no `window`/`document` access at import time; styles are\n * injected on mount.\n */\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type * as React from 'react';\nimport { GeminaClient } from '@gemina/sdk';\nimport type { ChatQueryOutDTO } from '@gemina/sdk';\nimport type { GeminaTokenManager } from './token-manager';\nimport { VERSION } from './version';\n\n/** Visual theme. `\"auto\"` follows `prefers-color-scheme`. */\nexport type GeminaChatTheme = 'light' | 'dark' | 'auto';\n\n/**\n * Text direction. `\"auto\"` flips the widget to RTL when the user's latest\n * message contains Hebrew, and lets each bubble resolve its own direction.\n */\nexport type GeminaChatDirection = 'ltr' | 'rtl' | 'auto';\n\nexport interface GeminaChatProps {\n /** Token source. Required — see {@link GeminaTokenManager}. */\n tokenManager: GeminaTokenManager;\n /** Gemina API base URL (default `https://api.gemina.co`). */\n baseUrl?: string;\n /**\n * Optional end-user id forwarded with each query. On the session-token\n * path the token's SIGNED scope always wins server-side — this is a\n * hint, not a security control.\n */\n endUserId?: string;\n /** Visual theme (default `\"auto\"`). */\n theme?: GeminaChatTheme;\n /** Text direction (default `\"auto\"`). */\n dir?: GeminaChatDirection;\n /** Input placeholder text. */\n placeholder?: string;\n /**\n * Header text — whatever identity the embedding platform wants the chat\n * to carry: a brand (\"Acme Invoices\"), an assistant persona (\"Gemina's\n * AI Rep\"), anything. Text only, rendered verbatim. When set, the header\n * is always visible; without it the header appears only once a\n * conversation has started (to host \"New chat\"). Colors and fonts are\n * themeable separately via the `--gemina-chat-*` CSS variables.\n */\n title?: string;\n /** Called with the cited `documentId` when a citation chip is clicked. */\n onCitationClick?: (documentId: string) => void;\n /** Extra class name(s) for the root element (e.g. to override CSS vars). */\n className?: string;\n}\n\ninterface UserMessage {\n id: number;\n role: 'user';\n text: string;\n}\n\ninterface AssistantMessage {\n id: number;\n role: 'assistant';\n text: string;\n citations: string[];\n confident: boolean;\n}\n\ninterface ErrorMessage {\n id: number;\n role: 'error';\n text: string;\n /** Present only when a retry is offered; holds the original user text. */\n retryText?: string;\n}\n\ntype ChatMessage = UserMessage | AssistantMessage | ErrorMessage;\n\n/** `Omit` that distributes over each member of a union. */\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\n\ntype ChatMessageInput = DistributiveOmit<ChatMessage, 'id'>;\n\n/** Hebrew Unicode block (U+0590–U+05FF). */\nconst HEBREW_RE = /[\\u0590-\\u05FF]/;\n\n/**\n * The response-like object carried by a thrown transport error. We pull it off\n * by shape rather than `instanceof ResponseError` — robust against duplicated\n * `@gemina/sdk` copies in a bundle (class identity is not shared across\n * copies). On the fetch transport this is the raw `Response`, so `status`,\n * `headers`, and the JSON body are all reachable from here.\n */\ninterface ResponseLike {\n status?: number;\n headers?: { get?: (name: string) => string | null };\n json?: () => Promise<unknown>;\n clone?: () => ResponseLike;\n}\n\nfunction getResponseLike(error: unknown): ResponseLike | undefined {\n if (error !== null && typeof error === 'object' && 'response' in error) {\n const response = (error as { response?: unknown }).response;\n if (response !== null && typeof response === 'object') {\n return response as ResponseLike;\n }\n }\n return undefined;\n}\n\n/** Extract an HTTP status from a thrown value, or `undefined`. */\nfunction httpStatus(error: unknown): number | undefined {\n const status = getResponseLike(error)?.status;\n return typeof status === 'number' ? status : undefined;\n}\n\n// Stable backend error codes. These survive production's `detail`-stripping\n// (see the chat-pricing handoff); we switch on HTTP status first and refine\n// with these where the same status can mean two different things.\nconst ERR_CHAT_QUOTA_EXCEEDED = 'CHAT_QUOTA_EXCEEDED';\nconst ERR_DI_NOT_IN_PLAN = 'DOCUMENT_INTELLIGENCE_NOT_IN_PLAN';\nconst ERR_UNPROCESSABLE = 'UNPROCESSABLE_ERROR';\nconst ERR_BAD_GATEWAY = 'BAD_GATEWAY_ERROR';\n// A conversation id that the server no longer knows (24h idle TTL, explicit\n// reset, or end-user scope drift). A turn that CARRIED a session and 404s is\n// this by construction — the chat/query handler raises 404 for nothing else —\n// so the component drops the id and restarts the conversation transparently.\nconst ERR_CHAT_SESSION_NOT_FOUND = 'CHAT_SESSION_NOT_FOUND';\n\ninterface ChatErrorInfo {\n status: number | undefined;\n errorCode: string | undefined;\n /** Human-readable server fallback (`errors[0].description`). */\n description: string | undefined;\n /** Whole seconds until reset, from the `Retry-After` header (429). */\n retryAfterSeconds: number | undefined;\n}\n\n/**\n * Read what the backend actually sent on an error. Only the HTTP status, the\n * stable `errors[0].error_code` / `description`, and the `Retry-After` header\n * are reliable across environments — production strips `errors[0].detail`, so\n * we never touch it. The fetch body can be read once, so we clone defensively;\n * if that fails (non-JSON, empty, or already consumed) the status still stands.\n */\nasync function readChatError(error: unknown): Promise<ChatErrorInfo> {\n const response = getResponseLike(error);\n const info: ChatErrorInfo = {\n status: typeof response?.status === 'number' ? response.status : undefined,\n errorCode: undefined,\n description: undefined,\n retryAfterSeconds: undefined,\n };\n if (response === undefined) {\n return info;\n }\n\n const rawRetryAfter = response.headers?.get?.('retry-after');\n if (rawRetryAfter !== null && rawRetryAfter !== undefined) {\n const seconds = Number(rawRetryAfter);\n if (Number.isFinite(seconds) && seconds > 0) {\n info.retryAfterSeconds = seconds;\n }\n }\n\n let body: unknown;\n try {\n const source = typeof response.clone === 'function' ? response.clone() : response;\n body = typeof source.json === 'function' ? await source.json() : undefined;\n } catch {\n body = undefined;\n }\n if (body !== null && typeof body === 'object') {\n const errors = (body as { errors?: unknown }).errors;\n if (\n Array.isArray(errors) &&\n errors.length > 0 &&\n errors[0] !== null &&\n typeof errors[0] === 'object'\n ) {\n const first = errors[0] as { error_code?: unknown; description?: unknown };\n if (typeof first.error_code === 'string') {\n info.errorCode = first.error_code;\n }\n if (typeof first.description === 'string') {\n info.description = first.description;\n }\n }\n }\n return info;\n}\n\nconst SESSION_EXPIRED_TEXT = 'Session expired — please reload the page or sign in again.';\nconst CONVERSATION_RESET_TEXT =\n 'This conversation is no longer available — send your message again to start a new one.';\nconst RATE_LIMIT_TEXT = \"You're sending messages too quickly — try again shortly.\";\nconst PLAN_GATE_TEXT = \"Chat isn't included in your plan.\";\nconst UNANSWERABLE_TEXT = \"We couldn't answer that. Try rephrasing your question.\";\nconst SERVICE_UNAVAILABLE_TEXT = 'The chat service is temporarily unavailable. Please try again.';\nconst GENERIC_ERROR_TEXT = \"Something went wrong and your message wasn't answered.\";\n\n/** Friendly \"resets in about N days/hours/minutes\" from Retry-After seconds. */\nfunction formatResetHint(seconds: number | undefined): string {\n if (seconds === undefined || !Number.isFinite(seconds) || seconds <= 0) {\n return 'at the next billing cycle';\n }\n const days = Math.round(seconds / 86400);\n if (days >= 1) {\n return `in about ${days} day${days === 1 ? '' : 's'}`;\n }\n const hours = Math.round(seconds / 3600);\n if (hours >= 1) {\n return `in about ${hours} hour${hours === 1 ? '' : 's'}`;\n }\n const minutes = Math.max(1, Math.round(seconds / 60));\n return `in about ${minutes} minute${minutes === 1 ? '' : 's'}`;\n}\n\n/**\n * Map a chat error to the bubble we render. Switches on HTTP status, refined by\n * the stable backend `error_code`. `retryText` is set only when resending the\n * same text could plausibly succeed — never for quota / plan / validation\n * outcomes, where an identical retry would just fail the same way.\n */\nfunction describeChatError(info: ChatErrorInfo, originalText: string): ChatMessageInput {\n const { status, errorCode } = info;\n\n // Over the included cap AND out of credits — the chat is blocked. Retrying\n // won't help; point at the reset time from the Retry-After header.\n if (status === 429 && errorCode === ERR_CHAT_QUOTA_EXCEEDED) {\n return {\n role: 'error',\n text: `You've used your included chats and are out of credits. Included chats reset ${formatResetHint(\n info.retryAfterSeconds,\n )}.`,\n };\n }\n // Any other 429 is a transient rate limit — a retry after a moment is fine.\n if (status === 429) {\n return { role: 'error', text: RATE_LIMIT_TEXT, retryText: originalText };\n }\n // Document Intelligence not in the plan/contract. NOT an auth failure.\n if (status === 402 || status === 403 || errorCode === ERR_DI_NOT_IN_PLAN) {\n return { role: 'error', text: PLAN_GATE_TEXT };\n }\n // Session expired — only surfaces after the 401-invalidate-retry-once path\n // has already failed a second time.\n if (status === 401) {\n return { role: 'error', text: SESSION_EXPIRED_TEXT };\n }\n // A stale conversation id that slipped past the transparent restart — only\n // the stable error_code reliably means \"the conversation is gone\". A bare 404\n // is a routing/gateway miss (e.g. the endpoint isn't deployed), which reads\n // better as a transient service error than a confusing \"conversation reset\".\n if (errorCode === ERR_CHAT_SESSION_NOT_FOUND) {\n return { role: 'error', text: CONVERSATION_RESET_TEXT, retryText: originalText };\n }\n if (status === 404) {\n return { role: 'error', text: SERVICE_UNAVAILABLE_TEXT, retryText: originalText };\n }\n // The question couldn't be answered (e.g. no searchable text). Expected, not\n // a server error — invite a rephrase rather than a blind retry.\n if (status === 422 || errorCode === ERR_UNPROCESSABLE) {\n return { role: 'error', text: UNANSWERABLE_TEXT };\n }\n // Chat backend timed out / unreachable — transient, offer retry.\n if (status === 502 || errorCode === ERR_BAD_GATEWAY) {\n return { role: 'error', text: SERVICE_UNAVAILABLE_TEXT, retryText: originalText };\n }\n // Anything else (incl. 500): prefer the server's description if it sent one.\n return {\n role: 'error',\n text: info.description ?? GENERIC_ERROR_TEXT,\n retryText: originalText,\n };\n}\n\n/**\n * The API reports citations as an array of `documentId` strings; normalize\n * defensively so `{ documentId }` objects also work if the shape evolves.\n */\nfunction normalizeCitations(citations: unknown): string[] {\n if (!Array.isArray(citations)) {\n return [];\n }\n const ids: string[] = [];\n for (const item of citations) {\n if (typeof item === 'string' && item.length > 0) {\n ids.push(item);\n } else if (\n item !== null &&\n typeof item === 'object' &&\n typeof (item as { documentId?: unknown }).documentId === 'string'\n ) {\n ids.push((item as { documentId: string }).documentId);\n }\n }\n return ids;\n}\n\n// --- Styles -----------------------------------------------------------------\n// Hand-rolled, no UI deps. Everything is scoped under .gemina-chat and driven\n// by CSS custom properties so host apps can re-theme without touching the DOM.\n\nconst DARK_VARS = `\n --gemina-chat-bg: #101418;\n --gemina-chat-fg: #e6e9ee;\n --gemina-chat-border: #2a323c;\n --gemina-chat-accent: #4c8dff;\n --gemina-chat-accent-fg: #ffffff;\n --gemina-chat-assistant-bg: #1c232b;\n --gemina-chat-assistant-fg: #e6e9ee;\n --gemina-chat-muted: #98a2b3;\n --gemina-chat-error: #f97066;\n --gemina-chat-low-confidence: #f7b27a;\n`;\n\nconst CHAT_CSS = `\n.gemina-chat {\n --gemina-chat-bg: #ffffff;\n --gemina-chat-fg: #1a1d21;\n --gemina-chat-border: #d9dce1;\n --gemina-chat-accent: #2f6fed;\n --gemina-chat-accent-fg: #ffffff;\n --gemina-chat-assistant-bg: #f2f4f7;\n --gemina-chat-assistant-fg: #1a1d21;\n --gemina-chat-muted: #667085;\n --gemina-chat-error: #b42318;\n --gemina-chat-low-confidence: #b54708;\n --gemina-chat-radius: 10px;\n --gemina-chat-font: system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif;\n\n box-sizing: border-box;\n display: flex;\n flex-direction: column;\n min-height: 320px;\n max-height: 600px;\n background: var(--gemina-chat-bg);\n color: var(--gemina-chat-fg);\n border: 1px solid var(--gemina-chat-border);\n border-radius: var(--gemina-chat-radius);\n font-family: var(--gemina-chat-font);\n font-size: 14px;\n line-height: 1.5;\n}\n.gemina-chat *, .gemina-chat *::before, .gemina-chat *::after { box-sizing: border-box; }\n.gemina-chat--dark { ${DARK_VARS} }\n@media (prefers-color-scheme: dark) {\n .gemina-chat--auto { ${DARK_VARS} }\n}\n.gemina-chat__header {\n display: flex;\n justify-content: flex-end;\n align-items: center;\n flex: 0 0 auto;\n padding: 6px 10px;\n border-bottom: 1px solid var(--gemina-chat-border);\n}\n.gemina-chat__title {\n margin-inline-end: auto;\n font-size: 13px;\n font-weight: 600;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n.gemina-chat__newchat {\n font: inherit;\n font-size: 12px;\n padding: 3px 10px;\n border-radius: var(--gemina-chat-radius);\n border: 1px solid var(--gemina-chat-border);\n background: transparent;\n color: var(--gemina-chat-accent);\n cursor: pointer;\n}\n.gemina-chat__newchat:hover:not(:disabled) { border-color: var(--gemina-chat-accent); }\n.gemina-chat__newchat:disabled { opacity: 0.5; cursor: default; }\n.gemina-chat__log {\n flex: 1;\n overflow-y: auto;\n padding: 12px;\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n.gemina-chat__msg {\n max-width: 85%;\n padding: 8px 12px;\n border-radius: var(--gemina-chat-radius);\n white-space: pre-wrap;\n overflow-wrap: break-word;\n}\n.gemina-chat__msg--user {\n align-self: flex-end;\n background: var(--gemina-chat-accent);\n color: var(--gemina-chat-accent-fg);\n}\n.gemina-chat--rtl .gemina-chat__msg--user, .gemina-chat[dir=\"rtl\"] .gemina-chat__msg--user {\n align-self: flex-start;\n}\n.gemina-chat--rtl .gemina-chat__msg--assistant, .gemina-chat[dir=\"rtl\"] .gemina-chat__msg--assistant {\n align-self: flex-end;\n}\n.gemina-chat__msg--assistant {\n align-self: flex-start;\n background: var(--gemina-chat-assistant-bg);\n color: var(--gemina-chat-assistant-fg);\n}\n.gemina-chat__msg--low-confidence {\n border: 1px dashed var(--gemina-chat-low-confidence);\n}\n.gemina-chat__low-confidence-note {\n margin-top: 6px;\n font-size: 12px;\n color: var(--gemina-chat-low-confidence);\n}\n.gemina-chat__citations {\n display: flex;\n flex-wrap: wrap;\n gap: 4px;\n margin-top: 6px;\n}\n.gemina-chat__citation {\n font: inherit;\n font-size: 12px;\n padding: 2px 8px;\n border-radius: 999px;\n border: 1px solid var(--gemina-chat-border);\n background: transparent;\n color: var(--gemina-chat-accent);\n cursor: pointer;\n}\n.gemina-chat__citation:hover { border-color: var(--gemina-chat-accent); }\n.gemina-chat__msg--error {\n align-self: flex-start;\n background: transparent;\n border: 1px solid var(--gemina-chat-error);\n color: var(--gemina-chat-error);\n}\n.gemina-chat__retry {\n font: inherit;\n font-size: 12px;\n margin-top: 6px;\n display: block;\n padding: 2px 10px;\n border-radius: var(--gemina-chat-radius);\n border: 1px solid var(--gemina-chat-error);\n background: transparent;\n color: var(--gemina-chat-error);\n cursor: pointer;\n}\n.gemina-chat__typing {\n align-self: flex-start;\n display: flex;\n align-items: center;\n gap: 5px;\n color: var(--gemina-chat-muted);\n font-size: 12px;\n padding: 0 4px;\n}\n.gemina-chat__typing-dots {\n display: inline-flex;\n align-items: center;\n gap: 3px;\n}\n.gemina-chat__typing-dots span {\n width: 4px;\n height: 4px;\n border-radius: 50%;\n background: currentColor;\n opacity: 0.25;\n animation: gemina-chat-thinking 1.2s infinite ease-in-out;\n}\n.gemina-chat__typing-dots span:nth-child(2) { animation-delay: 0.2s; }\n.gemina-chat__typing-dots span:nth-child(3) { animation-delay: 0.4s; }\n@keyframes gemina-chat-thinking {\n 0%, 60%, 100% { opacity: 0.25; transform: translateY(0); }\n 30% { opacity: 1; transform: translateY(-2px); }\n}\n@media (prefers-reduced-motion: reduce) {\n .gemina-chat__typing-dots span { animation: none; opacity: 0.6; }\n}\n.gemina-chat__composer {\n display: flex;\n gap: 8px;\n padding: 10px;\n border-top: 1px solid var(--gemina-chat-border);\n}\n.gemina-chat__input {\n flex: 1;\n resize: none;\n font: inherit;\n color: inherit;\n background: transparent;\n border: 1px solid var(--gemina-chat-border);\n border-radius: var(--gemina-chat-radius);\n padding: 8px 10px;\n min-height: 38px;\n}\n.gemina-chat__input:focus {\n outline: 2px solid var(--gemina-chat-accent);\n outline-offset: -1px;\n}\n.gemina-chat__send {\n font: inherit;\n align-self: flex-end;\n border: none;\n border-radius: var(--gemina-chat-radius);\n background: var(--gemina-chat-accent);\n color: var(--gemina-chat-accent-fg);\n padding: 8px 16px;\n cursor: pointer;\n}\n.gemina-chat__send:disabled { opacity: 0.5; cursor: default; }\n`;\n\nconst STYLE_ATTR = 'data-gemina-chat';\n\n/**\n * Inject the widget stylesheet once per document (idempotent across\n * instances; intentionally not removed on unmount so sibling instances and\n * quick remounts never flash unstyled).\n */\nfunction ensureStylesInjected(): void {\n if (typeof document === 'undefined') {\n return;\n }\n if (document.head.querySelector(`style[${STYLE_ATTR}]`) !== null) {\n return;\n }\n const style = document.createElement('style');\n style.setAttribute(STYLE_ATTR, VERSION);\n style.textContent = CHAT_CSS;\n document.head.appendChild(style);\n}\n\n/**\n * Embeddable Gemina Document Intelligence chat.\n *\n * ```tsx\n * <GeminaChat\n * tokenManager={tokenManager}\n * onCitationClick={(documentId) => openDocument(documentId)}\n * />\n * ```\n */\nexport function GeminaChat(props: GeminaChatProps): React.JSX.Element {\n const {\n tokenManager,\n baseUrl,\n endUserId,\n theme = 'auto',\n dir = 'auto',\n placeholder = 'Ask about your documents…',\n title,\n onCitationClick,\n className,\n } = props;\n\n const [messages, setMessages] = useState<ChatMessage[]>([]);\n const [draft, setDraft] = useState('');\n const [busy, setBusy] = useState(false);\n const nextIdRef = useRef(0);\n const mountedRef = useRef(false);\n const logRef = useRef<HTMLDivElement | null>(null);\n // The conversation id (server-issued) that gives the chat memory across\n // turns. Held in a ref, not state: it changes per turn but must never\n // trigger a re-render, and the send flow reads its latest value directly.\n // Distinct from the auth session TOKEN the token manager holds.\n const sessionIdRef = useRef<string | undefined>(undefined);\n\n useEffect(() => {\n mountedRef.current = true;\n ensureStylesInjected();\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n // Keep the newest message in view.\n useEffect(() => {\n const log = logRef.current;\n if (log !== null) {\n log.scrollTop = log.scrollHeight;\n }\n }, [messages, busy]);\n\n const appendMessage = useCallback((message: ChatMessageInput) => {\n const id = nextIdRef.current++;\n setMessages((prev) => [...prev, { ...message, id }]);\n }, []);\n\n const chatOnce = useCallback(\n (token: string, message: string): Promise<ChatQueryOutDTO> => {\n const client = GeminaClient.withSessionToken(token, baseUrl);\n const sessionId = sessionIdRef.current;\n return client.chat.chatQuery({\n // Thread the conversation id when we have one so follow-ups resolve\n // referents (\"what about the total?\"); omit it to start a new one.\n chatQueryInDTO: { message, endUserId, ...(sessionId ? { sessionId } : {}) },\n });\n },\n [baseUrl, endUserId],\n );\n\n /** One turn, with the mandated 401-invalidate-retry-once behavior. */\n const queryWithRetry = useCallback(\n async (message: string): Promise<ChatQueryOutDTO> => {\n const token = await tokenManager.getToken();\n try {\n return await chatOnce(token, message);\n } catch (error) {\n if (httpStatus(error) !== 401) {\n throw error;\n }\n // Token likely expired mid-session: drop it, re-mint via the\n // tenant backend, retry exactly once. A second 401 propagates.\n tokenManager.invalidate();\n const freshToken = await tokenManager.getToken();\n return await chatOnce(freshToken, message);\n }\n },\n [tokenManager, chatOnce],\n );\n\n const performSend = useCallback(\n async (text: string) => {\n setBusy(true);\n try {\n let result: ChatQueryOutDTO;\n const hadSession = sessionIdRef.current !== undefined;\n try {\n result = await queryWithRetry(text);\n } catch (error) {\n // A turn that CARRIED a session and 404s means the conversation is\n // gone (24h idle TTL, an explicit reset, or end-user scope drift).\n // Drop the stale id and retry once as a fresh conversation, so the\n // expiry is transparent — the user just gets an answer, no memory.\n if (hadSession && httpStatus(error) === 404) {\n sessionIdRef.current = undefined;\n result = await queryWithRetry(text);\n } else {\n throw error;\n }\n }\n if (!mountedRef.current) {\n return;\n }\n // The response always returns the (possibly newly created) conversation\n // id — store it so the next turn continues this thread.\n sessionIdRef.current = result.sessionId ?? sessionIdRef.current;\n appendMessage({\n role: 'assistant',\n text: result.answer,\n citations: normalizeCitations(result.citations),\n confident: result.confident !== false,\n });\n } catch (error) {\n if (!mountedRef.current) {\n return;\n }\n // Reading the error body is async (fetch), so re-check mount after.\n const info = await readChatError(error);\n if (!mountedRef.current) {\n return;\n }\n appendMessage(describeChatError(info, text));\n } finally {\n if (mountedRef.current) {\n setBusy(false);\n }\n }\n },\n [queryWithRetry, appendMessage],\n );\n\n /**\n * Reset to a brand-new conversation: clear the transcript and forget the\n * session id so the next message starts fresh. The old session is deleted\n * server-side best-effort — the local reset is authoritative, and a failed\n * delete just leaves the session to lapse on its idle TTL.\n */\n const startNewChat = useCallback(() => {\n if (busy) {\n return;\n }\n const staleSession = sessionIdRef.current;\n sessionIdRef.current = undefined;\n setMessages([]);\n setDraft('');\n if (staleSession !== undefined) {\n void (async () => {\n try {\n const token = await tokenManager.getToken();\n await GeminaClient.withSessionToken(token, baseUrl).chat.deleteChatSession({\n sessionId: staleSession,\n });\n } catch {\n // Unreachable/expired session: nothing to clean up client-side.\n }\n })();\n }\n }, [busy, tokenManager, baseUrl]);\n\n const submitDraft = useCallback(() => {\n const text = draft.trim();\n if (text.length === 0 || busy) {\n return;\n }\n setDraft('');\n appendMessage({ role: 'user', text });\n void performSend(text);\n }, [draft, busy, appendMessage, performSend]);\n\n const retryMessage = useCallback(\n (failed: ErrorMessage) => {\n if (busy || failed.retryText === undefined) {\n return;\n }\n const text = failed.retryText;\n // Replace the error entry; the original user bubble is still there.\n setMessages((prev) => prev.filter((message) => message.id !== failed.id));\n void performSend(text);\n },\n [busy, performSend],\n );\n\n const handleKeyDown = useCallback(\n (event: React.KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.key === 'Enter' && !event.shiftKey) {\n event.preventDefault();\n submitDraft();\n }\n },\n [submitDraft],\n );\n\n const handleSubmit = useCallback(\n (event: React.FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n submitDraft();\n },\n [submitDraft],\n );\n\n // dir=\"auto\": follow the user's latest message (Hebrew → RTL); individual\n // bubbles additionally resolve their own direction via dir=\"auto\".\n let effectiveDir: 'ltr' | 'rtl';\n if (dir === 'auto') {\n let lastUserText = '';\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (message !== undefined && message.role === 'user') {\n lastUserText = message.text;\n break;\n }\n }\n effectiveDir = HEBREW_RE.test(lastUserText) ? 'rtl' : 'ltr';\n } else {\n effectiveDir = dir;\n }\n const bubbleDir = dir === 'auto' ? 'auto' : undefined;\n\n const rootClassName = [\n 'gemina-chat',\n `gemina-chat--${theme}`,\n effectiveDir === 'rtl' ? 'gemina-chat--rtl' : '',\n className ?? '',\n ]\n .filter((part) => part.length > 0)\n .join(' ');\n\n return (\n <div className={rootClassName} dir={effectiveDir}>\n {(title !== undefined || messages.length > 0) && (\n <div className=\"gemina-chat__header\">\n {title !== undefined && (\n <div className=\"gemina-chat__title\" dir={bubbleDir}>\n {title}\n </div>\n )}\n {messages.length > 0 && (\n <button\n type=\"button\"\n className=\"gemina-chat__newchat\"\n onClick={startNewChat}\n disabled={busy}\n >\n New chat\n </button>\n )}\n </div>\n )}\n <div\n ref={logRef}\n role=\"log\"\n aria-live=\"polite\"\n aria-busy={busy}\n aria-label=\"Chat messages\"\n className=\"gemina-chat__log\"\n >\n {messages.map((message) => {\n if (message.role === 'user') {\n return (\n <div\n key={message.id}\n className=\"gemina-chat__msg gemina-chat__msg--user\"\n dir={bubbleDir}\n >\n {message.text}\n </div>\n );\n }\n if (message.role === 'assistant') {\n const lowConfidence = !message.confident;\n return (\n <div\n key={message.id}\n className={\n 'gemina-chat__msg gemina-chat__msg--assistant' +\n (lowConfidence ? ' gemina-chat__msg--low-confidence' : '')\n }\n dir={bubbleDir}\n >\n {message.text}\n {lowConfidence && (\n <div className=\"gemina-chat__low-confidence-note\">\n Low confidence — please verify against the cited documents.\n </div>\n )}\n {message.citations.length > 0 && (\n <div className=\"gemina-chat__citations\">\n {message.citations.map((documentId, index) => (\n <button\n key={`${documentId}-${index}`}\n type=\"button\"\n className=\"gemina-chat__citation\"\n title={`Open document ${documentId}`}\n onClick={() => onCitationClick?.(documentId)}\n >\n {documentId}\n </button>\n ))}\n </div>\n )}\n </div>\n );\n }\n return (\n <div\n key={message.id}\n role=\"alert\"\n className=\"gemina-chat__msg gemina-chat__msg--error\"\n >\n {message.text}\n {message.retryText !== undefined && (\n <button\n type=\"button\"\n className=\"gemina-chat__retry\"\n onClick={() => retryMessage(message)}\n >\n Retry\n </button>\n )}\n </div>\n );\n })}\n {busy && (\n // The label alone is what the aria-live log announces; the dots are\n // decoration (aria-hidden), and prefers-reduced-motion freezes them.\n <div className=\"gemina-chat__typing\">\n Thinking\n <span className=\"gemina-chat__typing-dots\" aria-hidden=\"true\">\n <span />\n <span />\n <span />\n </span>\n </div>\n )}\n </div>\n <form className=\"gemina-chat__composer\" onSubmit={handleSubmit}>\n <textarea\n className=\"gemina-chat__input\"\n aria-label=\"Chat message\"\n rows={1}\n value={draft}\n placeholder={placeholder}\n dir={bubbleDir}\n onChange={(event) => setDraft(event.target.value)}\n onKeyDown={handleKeyDown}\n />\n <button\n type=\"submit\"\n className=\"gemina-chat__send\"\n aria-label=\"Send message\"\n disabled={busy || draft.trim().length === 0}\n >\n Send\n </button>\n </form>\n </div>\n );\n}\n","/** Package version. Keep in sync with package.json. */\nexport const VERSION = '0.5.2';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;A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Bf;AAAA,YAEJ;AACA,mBACE;AAAA,cAAC;AAAA;AAAA,gBAEC,MAAK;AAAA,gBACL,WAAU;AAAA,gBAET;AAAA,0BAAQ;AAAA,kBACR,QAAQ,cAAc,UACrB;AAAA,oBAAC;AAAA;AAAA,sBACC,MAAK;AAAA,sBACL,WAAU;AAAA,sBACV,SAAS,MAAM,aAAa,OAAO;AAAA,sBACpC;AAAA;AAAA,kBAED;AAAA;AAAA;AAAA,cAZG,QAAQ;AAAA,YAcf;AAAA,UAEJ,CAAC;AAAA,UACA;AAAA;AAAA,UAGC,6CAAC,SAAI,WAAU,uBAAsB;AAAA;AAAA,YAEnC,6CAAC,UAAK,WAAU,4BAA2B,eAAY,QACrD;AAAA,0DAAC,UAAK;AAAA,cACN,4CAAC,UAAK;AAAA,cACN,4CAAC,UAAK;AAAA,eACR;AAAA,aACF;AAAA;AAAA;AAAA,IAEJ;AAAA,IACA,6CAAC,UAAK,WAAU,yBAAwB,UAAU,cAChD;AAAA;AAAA,QAAC;AAAA;AAAA,UACC,WAAU;AAAA,UACV,cAAW;AAAA,UACX,MAAM;AAAA,UACN,OAAO;AAAA,UACP;AAAA,UACA,KAAK;AAAA,UACL,UAAU,CAAC,UAAU,SAAS,MAAM,OAAO,KAAK;AAAA,UAChD,WAAW;AAAA;AAAA,MACb;AAAA,MACA;AAAA,QAAC;AAAA;AAAA,UACC,MAAK;AAAA,UACL,WAAU;AAAA,UACV,cAAW;AAAA,UACX,UAAU,QAAQ,MAAM,KAAK,EAAE,WAAW;AAAA,UAC3C;AAAA;AAAA,MAED;AAAA,OACF;AAAA,KACF;AAEJ;","names":[]}
package/dist/index.d.cts CHANGED
@@ -3,6 +3,6 @@ export { GeminaChat, GeminaChatDirection, GeminaChatProps, GeminaChatTheme } fro
3
3
  import 'react';
4
4
 
5
5
  /** Package version. Keep in sync with package.json. */
6
- declare const VERSION = "0.5.0";
6
+ declare const VERSION = "0.5.2";
7
7
 
8
8
  export { VERSION };
package/dist/index.d.ts CHANGED
@@ -3,6 +3,6 @@ export { GeminaChat, GeminaChatDirection, GeminaChatProps, GeminaChatTheme } fro
3
3
  import 'react';
4
4
 
5
5
  /** Package version. Keep in sync with package.json. */
6
- declare const VERSION = "0.5.0";
6
+ declare const VERSION = "0.5.2";
7
7
 
8
8
  export { VERSION };
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  import {
5
5
  GeminaChat,
6
6
  VERSION
7
- } from "./chunk-7MGELCGG.js";
7
+ } from "./chunk-KCOWRC34.js";
8
8
  export {
9
9
  GeminaChat,
10
10
  GeminaTokenManager,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gemina/elements",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "Embeddable browser UI for Gemina Document Intelligence — a drop-in React chat component plus a security-hardened session-token manager. The API key never enters the browser.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/chat.tsx","../src/version.ts"],"sourcesContent":["/**\n * <GeminaChat> — drop-in chat UI over Gemina Document Intelligence.\n *\n * Auth flows exclusively through a {@link GeminaTokenManager}: the component\n * asks it for a short-lived session token per turn and calls\n * `POST /v1/chat/query` through `@gemina/sdk`. It never sees — and cannot\n * accept — a Gemina API key (the token manager throws on API-key-shaped\n * credentials).\n *\n * SSR-safe: no `window`/`document` access at import time; styles are\n * injected on mount.\n */\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type * as React from 'react';\nimport { GeminaClient } from '@gemina/sdk';\nimport type { ChatQueryOutDTO } from '@gemina/sdk';\nimport type { GeminaTokenManager } from './token-manager';\nimport { VERSION } from './version';\n\n/** Visual theme. `\"auto\"` follows `prefers-color-scheme`. */\nexport type GeminaChatTheme = 'light' | 'dark' | 'auto';\n\n/**\n * Text direction. `\"auto\"` flips the widget to RTL when the user's latest\n * message contains Hebrew, and lets each bubble resolve its own direction.\n */\nexport type GeminaChatDirection = 'ltr' | 'rtl' | 'auto';\n\nexport interface GeminaChatProps {\n /** Token source. Required — see {@link GeminaTokenManager}. */\n tokenManager: GeminaTokenManager;\n /** Gemina API base URL (default `https://api.gemina.co`). */\n baseUrl?: string;\n /**\n * Optional end-user id forwarded with each query. On the session-token\n * path the token's SIGNED scope always wins server-side — this is a\n * hint, not a security control.\n */\n endUserId?: string;\n /** Visual theme (default `\"auto\"`). */\n theme?: GeminaChatTheme;\n /** Text direction (default `\"auto\"`). */\n dir?: GeminaChatDirection;\n /** Input placeholder text. */\n placeholder?: string;\n /** Called with the cited `documentId` when a citation chip is clicked. */\n onCitationClick?: (documentId: string) => void;\n /** Extra class name(s) for the root element (e.g. to override CSS vars). */\n className?: string;\n}\n\ninterface UserMessage {\n id: number;\n role: 'user';\n text: string;\n}\n\ninterface AssistantMessage {\n id: number;\n role: 'assistant';\n text: string;\n citations: string[];\n confident: boolean;\n}\n\ninterface ErrorMessage {\n id: number;\n role: 'error';\n text: string;\n /** Present only when a retry is offered; holds the original user text. */\n retryText?: string;\n}\n\ntype ChatMessage = UserMessage | AssistantMessage | ErrorMessage;\n\n/** `Omit` that distributes over each member of a union. */\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\n\ntype ChatMessageInput = DistributiveOmit<ChatMessage, 'id'>;\n\n/** Hebrew Unicode block (U+0590–U+05FF). */\nconst HEBREW_RE = /[\\u0590-\\u05FF]/;\n\n/**\n * The response-like object carried by a thrown transport error. We pull it off\n * by shape rather than `instanceof ResponseError` — robust against duplicated\n * `@gemina/sdk` copies in a bundle (class identity is not shared across\n * copies). On the fetch transport this is the raw `Response`, so `status`,\n * `headers`, and the JSON body are all reachable from here.\n */\ninterface ResponseLike {\n status?: number;\n headers?: { get?: (name: string) => string | null };\n json?: () => Promise<unknown>;\n clone?: () => ResponseLike;\n}\n\nfunction getResponseLike(error: unknown): ResponseLike | undefined {\n if (error !== null && typeof error === 'object' && 'response' in error) {\n const response = (error as { response?: unknown }).response;\n if (response !== null && typeof response === 'object') {\n return response as ResponseLike;\n }\n }\n return undefined;\n}\n\n/** Extract an HTTP status from a thrown value, or `undefined`. */\nfunction httpStatus(error: unknown): number | undefined {\n const status = getResponseLike(error)?.status;\n return typeof status === 'number' ? status : undefined;\n}\n\n// Stable backend error codes. These survive production's `detail`-stripping\n// (see the chat-pricing handoff); we switch on HTTP status first and refine\n// with these where the same status can mean two different things.\nconst ERR_CHAT_QUOTA_EXCEEDED = 'CHAT_QUOTA_EXCEEDED';\nconst ERR_DI_NOT_IN_PLAN = 'DOCUMENT_INTELLIGENCE_NOT_IN_PLAN';\nconst ERR_UNPROCESSABLE = 'UNPROCESSABLE_ERROR';\nconst ERR_BAD_GATEWAY = 'BAD_GATEWAY_ERROR';\n// A conversation id that the server no longer knows (24h idle TTL, explicit\n// reset, or end-user scope drift). A turn that CARRIED a session and 404s is\n// this by construction — the chat/query handler raises 404 for nothing else —\n// so the component drops the id and restarts the conversation transparently.\nconst ERR_CHAT_SESSION_NOT_FOUND = 'CHAT_SESSION_NOT_FOUND';\n\ninterface ChatErrorInfo {\n status: number | undefined;\n errorCode: string | undefined;\n /** Human-readable server fallback (`errors[0].description`). */\n description: string | undefined;\n /** Whole seconds until reset, from the `Retry-After` header (429). */\n retryAfterSeconds: number | undefined;\n}\n\n/**\n * Read what the backend actually sent on an error. Only the HTTP status, the\n * stable `errors[0].error_code` / `description`, and the `Retry-After` header\n * are reliable across environments — production strips `errors[0].detail`, so\n * we never touch it. The fetch body can be read once, so we clone defensively;\n * if that fails (non-JSON, empty, or already consumed) the status still stands.\n */\nasync function readChatError(error: unknown): Promise<ChatErrorInfo> {\n const response = getResponseLike(error);\n const info: ChatErrorInfo = {\n status: typeof response?.status === 'number' ? response.status : undefined,\n errorCode: undefined,\n description: undefined,\n retryAfterSeconds: undefined,\n };\n if (response === undefined) {\n return info;\n }\n\n const rawRetryAfter = response.headers?.get?.('retry-after');\n if (rawRetryAfter !== null && rawRetryAfter !== undefined) {\n const seconds = Number(rawRetryAfter);\n if (Number.isFinite(seconds) && seconds > 0) {\n info.retryAfterSeconds = seconds;\n }\n }\n\n let body: unknown;\n try {\n const source = typeof response.clone === 'function' ? response.clone() : response;\n body = typeof source.json === 'function' ? await source.json() : undefined;\n } catch {\n body = undefined;\n }\n if (body !== null && typeof body === 'object') {\n const errors = (body as { errors?: unknown }).errors;\n if (\n Array.isArray(errors) &&\n errors.length > 0 &&\n errors[0] !== null &&\n typeof errors[0] === 'object'\n ) {\n const first = errors[0] as { error_code?: unknown; description?: unknown };\n if (typeof first.error_code === 'string') {\n info.errorCode = first.error_code;\n }\n if (typeof first.description === 'string') {\n info.description = first.description;\n }\n }\n }\n return info;\n}\n\nconst SESSION_EXPIRED_TEXT = 'Session expired — please reload the page or sign in again.';\nconst CONVERSATION_RESET_TEXT =\n 'This conversation is no longer available — send your message again to start a new one.';\nconst RATE_LIMIT_TEXT = \"You're sending messages too quickly — try again shortly.\";\nconst PLAN_GATE_TEXT = \"Chat isn't included in your plan.\";\nconst UNANSWERABLE_TEXT = \"We couldn't answer that. Try rephrasing your question.\";\nconst SERVICE_UNAVAILABLE_TEXT = 'The chat service is temporarily unavailable. Please try again.';\nconst GENERIC_ERROR_TEXT = \"Something went wrong and your message wasn't answered.\";\n\n/** Friendly \"resets in about N days/hours/minutes\" from Retry-After seconds. */\nfunction formatResetHint(seconds: number | undefined): string {\n if (seconds === undefined || !Number.isFinite(seconds) || seconds <= 0) {\n return 'at the next billing cycle';\n }\n const days = Math.round(seconds / 86400);\n if (days >= 1) {\n return `in about ${days} day${days === 1 ? '' : 's'}`;\n }\n const hours = Math.round(seconds / 3600);\n if (hours >= 1) {\n return `in about ${hours} hour${hours === 1 ? '' : 's'}`;\n }\n const minutes = Math.max(1, Math.round(seconds / 60));\n return `in about ${minutes} minute${minutes === 1 ? '' : 's'}`;\n}\n\n/**\n * Map a chat error to the bubble we render. Switches on HTTP status, refined by\n * the stable backend `error_code`. `retryText` is set only when resending the\n * same text could plausibly succeed — never for quota / plan / validation\n * outcomes, where an identical retry would just fail the same way.\n */\nfunction describeChatError(info: ChatErrorInfo, originalText: string): ChatMessageInput {\n const { status, errorCode } = info;\n\n // Over the included cap AND out of credits — the chat is blocked. Retrying\n // won't help; point at the reset time from the Retry-After header.\n if (status === 429 && errorCode === ERR_CHAT_QUOTA_EXCEEDED) {\n return {\n role: 'error',\n text: `You've used your included chats and are out of credits. Included chats reset ${formatResetHint(\n info.retryAfterSeconds,\n )}.`,\n };\n }\n // Any other 429 is a transient rate limit — a retry after a moment is fine.\n if (status === 429) {\n return { role: 'error', text: RATE_LIMIT_TEXT, retryText: originalText };\n }\n // Document Intelligence not in the plan/contract. NOT an auth failure.\n if (status === 402 || status === 403 || errorCode === ERR_DI_NOT_IN_PLAN) {\n return { role: 'error', text: PLAN_GATE_TEXT };\n }\n // Session expired — only surfaces after the 401-invalidate-retry-once path\n // has already failed a second time.\n if (status === 401) {\n return { role: 'error', text: SESSION_EXPIRED_TEXT };\n }\n // A stale conversation id that slipped past the transparent restart — only\n // the stable error_code reliably means \"the conversation is gone\". A bare 404\n // is a routing/gateway miss (e.g. the endpoint isn't deployed), which reads\n // better as a transient service error than a confusing \"conversation reset\".\n if (errorCode === ERR_CHAT_SESSION_NOT_FOUND) {\n return { role: 'error', text: CONVERSATION_RESET_TEXT, retryText: originalText };\n }\n if (status === 404) {\n return { role: 'error', text: SERVICE_UNAVAILABLE_TEXT, retryText: originalText };\n }\n // The question couldn't be answered (e.g. no searchable text). Expected, not\n // a server error — invite a rephrase rather than a blind retry.\n if (status === 422 || errorCode === ERR_UNPROCESSABLE) {\n return { role: 'error', text: UNANSWERABLE_TEXT };\n }\n // Chat backend timed out / unreachable — transient, offer retry.\n if (status === 502 || errorCode === ERR_BAD_GATEWAY) {\n return { role: 'error', text: SERVICE_UNAVAILABLE_TEXT, retryText: originalText };\n }\n // Anything else (incl. 500): prefer the server's description if it sent one.\n return {\n role: 'error',\n text: info.description ?? GENERIC_ERROR_TEXT,\n retryText: originalText,\n };\n}\n\n/**\n * The API reports citations as an array of `documentId` strings; normalize\n * defensively so `{ documentId }` objects also work if the shape evolves.\n */\nfunction normalizeCitations(citations: unknown): string[] {\n if (!Array.isArray(citations)) {\n return [];\n }\n const ids: string[] = [];\n for (const item of citations) {\n if (typeof item === 'string' && item.length > 0) {\n ids.push(item);\n } else if (\n item !== null &&\n typeof item === 'object' &&\n typeof (item as { documentId?: unknown }).documentId === 'string'\n ) {\n ids.push((item as { documentId: string }).documentId);\n }\n }\n return ids;\n}\n\n// --- Styles -----------------------------------------------------------------\n// Hand-rolled, no UI deps. Everything is scoped under .gemina-chat and driven\n// by CSS custom properties so host apps can re-theme without touching the DOM.\n\nconst DARK_VARS = `\n --gemina-chat-bg: #101418;\n --gemina-chat-fg: #e6e9ee;\n --gemina-chat-border: #2a323c;\n --gemina-chat-accent: #4c8dff;\n --gemina-chat-accent-fg: #ffffff;\n --gemina-chat-assistant-bg: #1c232b;\n --gemina-chat-assistant-fg: #e6e9ee;\n --gemina-chat-muted: #98a2b3;\n --gemina-chat-error: #f97066;\n --gemina-chat-low-confidence: #f7b27a;\n`;\n\nconst CHAT_CSS = `\n.gemina-chat {\n --gemina-chat-bg: #ffffff;\n --gemina-chat-fg: #1a1d21;\n --gemina-chat-border: #d9dce1;\n --gemina-chat-accent: #2f6fed;\n --gemina-chat-accent-fg: #ffffff;\n --gemina-chat-assistant-bg: #f2f4f7;\n --gemina-chat-assistant-fg: #1a1d21;\n --gemina-chat-muted: #667085;\n --gemina-chat-error: #b42318;\n --gemina-chat-low-confidence: #b54708;\n --gemina-chat-radius: 10px;\n --gemina-chat-font: system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif;\n\n box-sizing: border-box;\n display: flex;\n flex-direction: column;\n min-height: 320px;\n max-height: 600px;\n background: var(--gemina-chat-bg);\n color: var(--gemina-chat-fg);\n border: 1px solid var(--gemina-chat-border);\n border-radius: var(--gemina-chat-radius);\n font-family: var(--gemina-chat-font);\n font-size: 14px;\n line-height: 1.5;\n}\n.gemina-chat *, .gemina-chat *::before, .gemina-chat *::after { box-sizing: border-box; }\n.gemina-chat--dark { ${DARK_VARS} }\n@media (prefers-color-scheme: dark) {\n .gemina-chat--auto { ${DARK_VARS} }\n}\n.gemina-chat__header {\n display: flex;\n justify-content: flex-end;\n align-items: center;\n flex: 0 0 auto;\n padding: 6px 10px;\n border-bottom: 1px solid var(--gemina-chat-border);\n}\n.gemina-chat__newchat {\n font: inherit;\n font-size: 12px;\n padding: 3px 10px;\n border-radius: var(--gemina-chat-radius);\n border: 1px solid var(--gemina-chat-border);\n background: transparent;\n color: var(--gemina-chat-accent);\n cursor: pointer;\n}\n.gemina-chat__newchat:hover:not(:disabled) { border-color: var(--gemina-chat-accent); }\n.gemina-chat__newchat:disabled { opacity: 0.5; cursor: default; }\n.gemina-chat__log {\n flex: 1;\n overflow-y: auto;\n padding: 12px;\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n.gemina-chat__msg {\n max-width: 85%;\n padding: 8px 12px;\n border-radius: var(--gemina-chat-radius);\n white-space: pre-wrap;\n overflow-wrap: break-word;\n}\n.gemina-chat__msg--user {\n align-self: flex-end;\n background: var(--gemina-chat-accent);\n color: var(--gemina-chat-accent-fg);\n}\n.gemina-chat--rtl .gemina-chat__msg--user, .gemina-chat[dir=\"rtl\"] .gemina-chat__msg--user {\n align-self: flex-start;\n}\n.gemina-chat--rtl .gemina-chat__msg--assistant, .gemina-chat[dir=\"rtl\"] .gemina-chat__msg--assistant {\n align-self: flex-end;\n}\n.gemina-chat__msg--assistant {\n align-self: flex-start;\n background: var(--gemina-chat-assistant-bg);\n color: var(--gemina-chat-assistant-fg);\n}\n.gemina-chat__msg--low-confidence {\n border: 1px dashed var(--gemina-chat-low-confidence);\n}\n.gemina-chat__low-confidence-note {\n margin-top: 6px;\n font-size: 12px;\n color: var(--gemina-chat-low-confidence);\n}\n.gemina-chat__citations {\n display: flex;\n flex-wrap: wrap;\n gap: 4px;\n margin-top: 6px;\n}\n.gemina-chat__citation {\n font: inherit;\n font-size: 12px;\n padding: 2px 8px;\n border-radius: 999px;\n border: 1px solid var(--gemina-chat-border);\n background: transparent;\n color: var(--gemina-chat-accent);\n cursor: pointer;\n}\n.gemina-chat__citation:hover { border-color: var(--gemina-chat-accent); }\n.gemina-chat__msg--error {\n align-self: flex-start;\n background: transparent;\n border: 1px solid var(--gemina-chat-error);\n color: var(--gemina-chat-error);\n}\n.gemina-chat__retry {\n font: inherit;\n font-size: 12px;\n margin-top: 6px;\n display: block;\n padding: 2px 10px;\n border-radius: var(--gemina-chat-radius);\n border: 1px solid var(--gemina-chat-error);\n background: transparent;\n color: var(--gemina-chat-error);\n cursor: pointer;\n}\n.gemina-chat__typing {\n align-self: flex-start;\n color: var(--gemina-chat-muted);\n font-size: 12px;\n padding: 0 4px;\n}\n.gemina-chat__composer {\n display: flex;\n gap: 8px;\n padding: 10px;\n border-top: 1px solid var(--gemina-chat-border);\n}\n.gemina-chat__input {\n flex: 1;\n resize: none;\n font: inherit;\n color: inherit;\n background: transparent;\n border: 1px solid var(--gemina-chat-border);\n border-radius: var(--gemina-chat-radius);\n padding: 8px 10px;\n min-height: 38px;\n}\n.gemina-chat__input:focus {\n outline: 2px solid var(--gemina-chat-accent);\n outline-offset: -1px;\n}\n.gemina-chat__send {\n font: inherit;\n align-self: flex-end;\n border: none;\n border-radius: var(--gemina-chat-radius);\n background: var(--gemina-chat-accent);\n color: var(--gemina-chat-accent-fg);\n padding: 8px 16px;\n cursor: pointer;\n}\n.gemina-chat__send:disabled { opacity: 0.5; cursor: default; }\n`;\n\nconst STYLE_ATTR = 'data-gemina-chat';\n\n/**\n * Inject the widget stylesheet once per document (idempotent across\n * instances; intentionally not removed on unmount so sibling instances and\n * quick remounts never flash unstyled).\n */\nfunction ensureStylesInjected(): void {\n if (typeof document === 'undefined') {\n return;\n }\n if (document.head.querySelector(`style[${STYLE_ATTR}]`) !== null) {\n return;\n }\n const style = document.createElement('style');\n style.setAttribute(STYLE_ATTR, VERSION);\n style.textContent = CHAT_CSS;\n document.head.appendChild(style);\n}\n\n/**\n * Embeddable Gemina Document Intelligence chat.\n *\n * ```tsx\n * <GeminaChat\n * tokenManager={tokenManager}\n * onCitationClick={(documentId) => openDocument(documentId)}\n * />\n * ```\n */\nexport function GeminaChat(props: GeminaChatProps): React.JSX.Element {\n const {\n tokenManager,\n baseUrl,\n endUserId,\n theme = 'auto',\n dir = 'auto',\n placeholder = 'Ask about your documents…',\n onCitationClick,\n className,\n } = props;\n\n const [messages, setMessages] = useState<ChatMessage[]>([]);\n const [draft, setDraft] = useState('');\n const [busy, setBusy] = useState(false);\n const nextIdRef = useRef(0);\n const mountedRef = useRef(false);\n const logRef = useRef<HTMLDivElement | null>(null);\n // The conversation id (server-issued) that gives the chat memory across\n // turns. Held in a ref, not state: it changes per turn but must never\n // trigger a re-render, and the send flow reads its latest value directly.\n // Distinct from the auth session TOKEN the token manager holds.\n const sessionIdRef = useRef<string | undefined>(undefined);\n\n useEffect(() => {\n mountedRef.current = true;\n ensureStylesInjected();\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n // Keep the newest message in view.\n useEffect(() => {\n const log = logRef.current;\n if (log !== null) {\n log.scrollTop = log.scrollHeight;\n }\n }, [messages, busy]);\n\n const appendMessage = useCallback((message: ChatMessageInput) => {\n const id = nextIdRef.current++;\n setMessages((prev) => [...prev, { ...message, id }]);\n }, []);\n\n const chatOnce = useCallback(\n (token: string, message: string): Promise<ChatQueryOutDTO> => {\n const client = GeminaClient.withSessionToken(token, baseUrl);\n const sessionId = sessionIdRef.current;\n return client.chat.chatQuery({\n // Thread the conversation id when we have one so follow-ups resolve\n // referents (\"what about the total?\"); omit it to start a new one.\n chatQueryInDTO: { message, endUserId, ...(sessionId ? { sessionId } : {}) },\n });\n },\n [baseUrl, endUserId],\n );\n\n /** One turn, with the mandated 401-invalidate-retry-once behavior. */\n const queryWithRetry = useCallback(\n async (message: string): Promise<ChatQueryOutDTO> => {\n const token = await tokenManager.getToken();\n try {\n return await chatOnce(token, message);\n } catch (error) {\n if (httpStatus(error) !== 401) {\n throw error;\n }\n // Token likely expired mid-session: drop it, re-mint via the\n // tenant backend, retry exactly once. A second 401 propagates.\n tokenManager.invalidate();\n const freshToken = await tokenManager.getToken();\n return await chatOnce(freshToken, message);\n }\n },\n [tokenManager, chatOnce],\n );\n\n const performSend = useCallback(\n async (text: string) => {\n setBusy(true);\n try {\n let result: ChatQueryOutDTO;\n const hadSession = sessionIdRef.current !== undefined;\n try {\n result = await queryWithRetry(text);\n } catch (error) {\n // A turn that CARRIED a session and 404s means the conversation is\n // gone (24h idle TTL, an explicit reset, or end-user scope drift).\n // Drop the stale id and retry once as a fresh conversation, so the\n // expiry is transparent — the user just gets an answer, no memory.\n if (hadSession && httpStatus(error) === 404) {\n sessionIdRef.current = undefined;\n result = await queryWithRetry(text);\n } else {\n throw error;\n }\n }\n if (!mountedRef.current) {\n return;\n }\n // The response always returns the (possibly newly created) conversation\n // id — store it so the next turn continues this thread.\n sessionIdRef.current = result.sessionId ?? sessionIdRef.current;\n appendMessage({\n role: 'assistant',\n text: result.answer,\n citations: normalizeCitations(result.citations),\n confident: result.confident !== false,\n });\n } catch (error) {\n if (!mountedRef.current) {\n return;\n }\n // Reading the error body is async (fetch), so re-check mount after.\n const info = await readChatError(error);\n if (!mountedRef.current) {\n return;\n }\n appendMessage(describeChatError(info, text));\n } finally {\n if (mountedRef.current) {\n setBusy(false);\n }\n }\n },\n [queryWithRetry, appendMessage],\n );\n\n /**\n * Reset to a brand-new conversation: clear the transcript and forget the\n * session id so the next message starts fresh. The old session is deleted\n * server-side best-effort — the local reset is authoritative, and a failed\n * delete just leaves the session to lapse on its idle TTL.\n */\n const startNewChat = useCallback(() => {\n if (busy) {\n return;\n }\n const staleSession = sessionIdRef.current;\n sessionIdRef.current = undefined;\n setMessages([]);\n setDraft('');\n if (staleSession !== undefined) {\n void (async () => {\n try {\n const token = await tokenManager.getToken();\n await GeminaClient.withSessionToken(token, baseUrl).chat.deleteChatSession({\n sessionId: staleSession,\n });\n } catch {\n // Unreachable/expired session: nothing to clean up client-side.\n }\n })();\n }\n }, [busy, tokenManager, baseUrl]);\n\n const submitDraft = useCallback(() => {\n const text = draft.trim();\n if (text.length === 0 || busy) {\n return;\n }\n setDraft('');\n appendMessage({ role: 'user', text });\n void performSend(text);\n }, [draft, busy, appendMessage, performSend]);\n\n const retryMessage = useCallback(\n (failed: ErrorMessage) => {\n if (busy || failed.retryText === undefined) {\n return;\n }\n const text = failed.retryText;\n // Replace the error entry; the original user bubble is still there.\n setMessages((prev) => prev.filter((message) => message.id !== failed.id));\n void performSend(text);\n },\n [busy, performSend],\n );\n\n const handleKeyDown = useCallback(\n (event: React.KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.key === 'Enter' && !event.shiftKey) {\n event.preventDefault();\n submitDraft();\n }\n },\n [submitDraft],\n );\n\n const handleSubmit = useCallback(\n (event: React.FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n submitDraft();\n },\n [submitDraft],\n );\n\n // dir=\"auto\": follow the user's latest message (Hebrew → RTL); individual\n // bubbles additionally resolve their own direction via dir=\"auto\".\n let effectiveDir: 'ltr' | 'rtl';\n if (dir === 'auto') {\n let lastUserText = '';\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (message !== undefined && message.role === 'user') {\n lastUserText = message.text;\n break;\n }\n }\n effectiveDir = HEBREW_RE.test(lastUserText) ? 'rtl' : 'ltr';\n } else {\n effectiveDir = dir;\n }\n const bubbleDir = dir === 'auto' ? 'auto' : undefined;\n\n const rootClassName = [\n 'gemina-chat',\n `gemina-chat--${theme}`,\n effectiveDir === 'rtl' ? 'gemina-chat--rtl' : '',\n className ?? '',\n ]\n .filter((part) => part.length > 0)\n .join(' ');\n\n return (\n <div className={rootClassName} dir={effectiveDir}>\n {messages.length > 0 && (\n <div className=\"gemina-chat__header\">\n <button\n type=\"button\"\n className=\"gemina-chat__newchat\"\n onClick={startNewChat}\n disabled={busy}\n >\n New chat\n </button>\n </div>\n )}\n <div\n ref={logRef}\n role=\"log\"\n aria-live=\"polite\"\n aria-busy={busy}\n aria-label=\"Chat messages\"\n className=\"gemina-chat__log\"\n >\n {messages.map((message) => {\n if (message.role === 'user') {\n return (\n <div\n key={message.id}\n className=\"gemina-chat__msg gemina-chat__msg--user\"\n dir={bubbleDir}\n >\n {message.text}\n </div>\n );\n }\n if (message.role === 'assistant') {\n const lowConfidence = !message.confident;\n return (\n <div\n key={message.id}\n className={\n 'gemina-chat__msg gemina-chat__msg--assistant' +\n (lowConfidence ? ' gemina-chat__msg--low-confidence' : '')\n }\n dir={bubbleDir}\n >\n {message.text}\n {lowConfidence && (\n <div className=\"gemina-chat__low-confidence-note\">\n Low confidence — please verify against the cited documents.\n </div>\n )}\n {message.citations.length > 0 && (\n <div className=\"gemina-chat__citations\">\n {message.citations.map((documentId, index) => (\n <button\n key={`${documentId}-${index}`}\n type=\"button\"\n className=\"gemina-chat__citation\"\n title={`Open document ${documentId}`}\n onClick={() => onCitationClick?.(documentId)}\n >\n {documentId}\n </button>\n ))}\n </div>\n )}\n </div>\n );\n }\n return (\n <div\n key={message.id}\n role=\"alert\"\n className=\"gemina-chat__msg gemina-chat__msg--error\"\n >\n {message.text}\n {message.retryText !== undefined && (\n <button\n type=\"button\"\n className=\"gemina-chat__retry\"\n onClick={() => retryMessage(message)}\n >\n Retry\n </button>\n )}\n </div>\n );\n })}\n {busy && <div className=\"gemina-chat__typing\">Thinking…</div>}\n </div>\n <form className=\"gemina-chat__composer\" onSubmit={handleSubmit}>\n <textarea\n className=\"gemina-chat__input\"\n aria-label=\"Chat message\"\n rows={1}\n value={draft}\n placeholder={placeholder}\n dir={bubbleDir}\n onChange={(event) => setDraft(event.target.value)}\n onKeyDown={handleKeyDown}\n />\n <button\n type=\"submit\"\n className=\"gemina-chat__send\"\n aria-label=\"Send message\"\n disabled={busy || draft.trim().length === 0}\n >\n Send\n </button>\n </form>\n </div>\n );\n}\n","/** Package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