@gemina/elements 0.1.2 → 0.2.1
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 +24 -0
- package/dist/chat.cjs +79 -3
- package/dist/chat.cjs.map +1 -1
- package/dist/chat.js +1 -1
- package/dist/{chunk-DGY2IT73.js → chunk-ZN4GN5SU.js} +80 -4
- package/dist/chunk-ZN4GN5SU.js.map +1 -0
- package/dist/index.cjs +79 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-DGY2IT73.js.map +0 -1
package/README.md
CHANGED
|
@@ -165,6 +165,29 @@ treatment. Enter sends, Shift+Enter inserts a newline. The message list is
|
|
|
165
165
|
a `role="log"` live region with `aria-busy` while a reply is in flight, and
|
|
166
166
|
the input and send button are ARIA-labelled.
|
|
167
167
|
|
|
168
|
+
### Conversation memory
|
|
169
|
+
|
|
170
|
+
The widget keeps conversation memory automatically. The first message starts
|
|
171
|
+
a new server-side conversation; the response carries a `sessionId`, which the
|
|
172
|
+
component threads back into every following turn so the assistant can resolve
|
|
173
|
+
referents ("what about the total?", "and last year?") against what came
|
|
174
|
+
before. The id is held in memory for the life of the component — nothing is
|
|
175
|
+
persisted, and it's never surfaced as a prop or exposed to your app.
|
|
176
|
+
|
|
177
|
+
Once a conversation has any messages, a **New chat** button appears in the
|
|
178
|
+
widget header. Clicking it clears the transcript and forgets the current
|
|
179
|
+
`sessionId`, so the next message opens a fresh conversation; the previous
|
|
180
|
+
server-side session is deleted best-effort at the same time. The local reset
|
|
181
|
+
is authoritative — if the delete can't be reached, that session simply lapses
|
|
182
|
+
on its own idle TTL.
|
|
183
|
+
|
|
184
|
+
Server conversations expire after **24 hours of inactivity**. If you send a
|
|
185
|
+
message on a conversation the server has since forgotten (idle expiry, an
|
|
186
|
+
explicit reset, or end-user scope drift), the widget notices, drops the stale
|
|
187
|
+
id, and transparently retries as a new conversation — you just get your answer
|
|
188
|
+
back, with the prior memory gone. (A stale id that slips past this restart
|
|
189
|
+
falls back to the reset error below.)
|
|
190
|
+
|
|
168
191
|
### Error behavior
|
|
169
192
|
|
|
170
193
|
| API response | What the widget does |
|
|
@@ -172,6 +195,7 @@ the input and send button are ARIA-labelled.
|
|
|
172
195
|
| `401` | `tokenManager.invalidate()` + one automatic retry with a fresh token; if the retry also 401s → "Session expired — please reload the page or sign in again." |
|
|
173
196
|
| `429` | "You're sending messages too quickly — try again shortly." |
|
|
174
197
|
| `402` / `403` | "Document Intelligence isn't enabled on this plan." |
|
|
198
|
+
| `404` (a conversation the server forgot, past the transparent restart) | "This conversation is no longer available — send your message again to start a new one." with a **Retry** button. |
|
|
175
199
|
| anything else | Generic failure with a **Retry** button that resends the last message. |
|
|
176
200
|
|
|
177
201
|
### Theming
|
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.1
|
|
30
|
+
var VERSION = "0.2.1";
|
|
31
31
|
|
|
32
32
|
// src/chat.tsx
|
|
33
33
|
var import_jsx_runtime = require("react/jsx-runtime");
|
|
@@ -49,6 +49,7 @@ var ERR_CHAT_QUOTA_EXCEEDED = "CHAT_QUOTA_EXCEEDED";
|
|
|
49
49
|
var ERR_DI_NOT_IN_PLAN = "DOCUMENT_INTELLIGENCE_NOT_IN_PLAN";
|
|
50
50
|
var ERR_UNPROCESSABLE = "UNPROCESSABLE_ERROR";
|
|
51
51
|
var ERR_BAD_GATEWAY = "BAD_GATEWAY_ERROR";
|
|
52
|
+
var ERR_CHAT_SESSION_NOT_FOUND = "CHAT_SESSION_NOT_FOUND";
|
|
52
53
|
async function readChatError(error) {
|
|
53
54
|
const response = getResponseLike(error);
|
|
54
55
|
const info = {
|
|
@@ -89,6 +90,7 @@ async function readChatError(error) {
|
|
|
89
90
|
return info;
|
|
90
91
|
}
|
|
91
92
|
var SESSION_EXPIRED_TEXT = "Session expired \u2014 please reload the page or sign in again.";
|
|
93
|
+
var CONVERSATION_RESET_TEXT = "This conversation is no longer available \u2014 send your message again to start a new one.";
|
|
92
94
|
var RATE_LIMIT_TEXT = "You're sending messages too quickly \u2014 try again shortly.";
|
|
93
95
|
var PLAN_GATE_TEXT = "Chat isn't included in your plan.";
|
|
94
96
|
var UNANSWERABLE_TEXT = "We couldn't answer that. Try rephrasing your question.";
|
|
@@ -128,6 +130,12 @@ function describeChatError(info, originalText) {
|
|
|
128
130
|
if (status === 401) {
|
|
129
131
|
return { role: "error", text: SESSION_EXPIRED_TEXT };
|
|
130
132
|
}
|
|
133
|
+
if (errorCode === ERR_CHAT_SESSION_NOT_FOUND) {
|
|
134
|
+
return { role: "error", text: CONVERSATION_RESET_TEXT, retryText: originalText };
|
|
135
|
+
}
|
|
136
|
+
if (status === 404) {
|
|
137
|
+
return { role: "error", text: SERVICE_UNAVAILABLE_TEXT, retryText: originalText };
|
|
138
|
+
}
|
|
131
139
|
if (status === 422 || errorCode === ERR_UNPROCESSABLE) {
|
|
132
140
|
return { role: "error", text: UNANSWERABLE_TEXT };
|
|
133
141
|
}
|
|
@@ -199,6 +207,26 @@ var CHAT_CSS = `
|
|
|
199
207
|
@media (prefers-color-scheme: dark) {
|
|
200
208
|
.gemina-chat--auto { ${DARK_VARS} }
|
|
201
209
|
}
|
|
210
|
+
.gemina-chat__header {
|
|
211
|
+
display: flex;
|
|
212
|
+
justify-content: flex-end;
|
|
213
|
+
align-items: center;
|
|
214
|
+
flex: 0 0 auto;
|
|
215
|
+
padding: 6px 10px;
|
|
216
|
+
border-bottom: 1px solid var(--gemina-chat-border);
|
|
217
|
+
}
|
|
218
|
+
.gemina-chat__newchat {
|
|
219
|
+
font: inherit;
|
|
220
|
+
font-size: 12px;
|
|
221
|
+
padding: 3px 10px;
|
|
222
|
+
border-radius: var(--gemina-chat-radius);
|
|
223
|
+
border: 1px solid var(--gemina-chat-border);
|
|
224
|
+
background: transparent;
|
|
225
|
+
color: var(--gemina-chat-accent);
|
|
226
|
+
cursor: pointer;
|
|
227
|
+
}
|
|
228
|
+
.gemina-chat__newchat:hover:not(:disabled) { border-color: var(--gemina-chat-accent); }
|
|
229
|
+
.gemina-chat__newchat:disabled { opacity: 0.5; cursor: default; }
|
|
202
230
|
.gemina-chat__log {
|
|
203
231
|
flex: 1;
|
|
204
232
|
overflow-y: auto;
|
|
@@ -342,6 +370,7 @@ function GeminaChat(props) {
|
|
|
342
370
|
const nextIdRef = (0, import_react.useRef)(0);
|
|
343
371
|
const mountedRef = (0, import_react.useRef)(false);
|
|
344
372
|
const logRef = (0, import_react.useRef)(null);
|
|
373
|
+
const sessionIdRef = (0, import_react.useRef)(void 0);
|
|
345
374
|
(0, import_react.useEffect)(() => {
|
|
346
375
|
mountedRef.current = true;
|
|
347
376
|
ensureStylesInjected();
|
|
@@ -362,7 +391,12 @@ function GeminaChat(props) {
|
|
|
362
391
|
const chatOnce = (0, import_react.useCallback)(
|
|
363
392
|
(token, message) => {
|
|
364
393
|
const client = import_sdk.GeminaClient.withSessionToken(token, baseUrl);
|
|
365
|
-
|
|
394
|
+
const sessionId = sessionIdRef.current;
|
|
395
|
+
return client.chat.chatQuery({
|
|
396
|
+
// Thread the conversation id when we have one so follow-ups resolve
|
|
397
|
+
// referents ("what about the total?"); omit it to start a new one.
|
|
398
|
+
chatQueryInDTO: { message, endUserId, ...sessionId ? { sessionId } : {} }
|
|
399
|
+
});
|
|
366
400
|
},
|
|
367
401
|
[baseUrl, endUserId]
|
|
368
402
|
);
|
|
@@ -386,10 +420,22 @@ function GeminaChat(props) {
|
|
|
386
420
|
async (text) => {
|
|
387
421
|
setBusy(true);
|
|
388
422
|
try {
|
|
389
|
-
|
|
423
|
+
let result;
|
|
424
|
+
const hadSession = sessionIdRef.current !== void 0;
|
|
425
|
+
try {
|
|
426
|
+
result = await queryWithRetry(text);
|
|
427
|
+
} catch (error) {
|
|
428
|
+
if (hadSession && httpStatus(error) === 404) {
|
|
429
|
+
sessionIdRef.current = void 0;
|
|
430
|
+
result = await queryWithRetry(text);
|
|
431
|
+
} else {
|
|
432
|
+
throw error;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
390
435
|
if (!mountedRef.current) {
|
|
391
436
|
return;
|
|
392
437
|
}
|
|
438
|
+
sessionIdRef.current = result.sessionId ?? sessionIdRef.current;
|
|
393
439
|
appendMessage({
|
|
394
440
|
role: "assistant",
|
|
395
441
|
text: result.answer,
|
|
@@ -413,6 +459,26 @@ function GeminaChat(props) {
|
|
|
413
459
|
},
|
|
414
460
|
[queryWithRetry, appendMessage]
|
|
415
461
|
);
|
|
462
|
+
const startNewChat = (0, import_react.useCallback)(() => {
|
|
463
|
+
if (busy) {
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
const staleSession = sessionIdRef.current;
|
|
467
|
+
sessionIdRef.current = void 0;
|
|
468
|
+
setMessages([]);
|
|
469
|
+
setDraft("");
|
|
470
|
+
if (staleSession !== void 0) {
|
|
471
|
+
void (async () => {
|
|
472
|
+
try {
|
|
473
|
+
const token = await tokenManager.getToken();
|
|
474
|
+
await import_sdk.GeminaClient.withSessionToken(token, baseUrl).chat.deleteChatSession({
|
|
475
|
+
sessionId: staleSession
|
|
476
|
+
});
|
|
477
|
+
} catch {
|
|
478
|
+
}
|
|
479
|
+
})();
|
|
480
|
+
}
|
|
481
|
+
}, [busy, tokenManager, baseUrl]);
|
|
416
482
|
const submitDraft = (0, import_react.useCallback)(() => {
|
|
417
483
|
const text = draft.trim();
|
|
418
484
|
if (text.length === 0 || busy) {
|
|
@@ -471,6 +537,16 @@ function GeminaChat(props) {
|
|
|
471
537
|
className ?? ""
|
|
472
538
|
].filter((part) => part.length > 0).join(" ");
|
|
473
539
|
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
|
+
) }),
|
|
474
550
|
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
|
|
475
551
|
"div",
|
|
476
552
|
{
|
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\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 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 // 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__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\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 return client.chat.chatQuery({ chatQueryInDTO: { message, endUserId } });\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 const result = await queryWithRetry(text);\n if (!mountedRef.current) {\n return;\n }\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 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 <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.1.2';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAYA,mBAAyD;AAEzD,iBAA6B;;;ACbtB,IAAM,UAAU;;;AD+oBT;AA/jBd,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;AAkBxB,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,aAAa;AACpC,QAAI,OAAO,SAAS,O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K,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 /** 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.2.1';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAYA,mBAAyD;AAEzD,iBAA6B;;;ACbtB,IAAM,UAAU;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AU;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.js
CHANGED
|
@@ -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.1
|
|
6
|
+
var VERSION = "0.2.1";
|
|
7
7
|
|
|
8
8
|
// src/chat.tsx
|
|
9
9
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
@@ -25,6 +25,7 @@ var ERR_CHAT_QUOTA_EXCEEDED = "CHAT_QUOTA_EXCEEDED";
|
|
|
25
25
|
var ERR_DI_NOT_IN_PLAN = "DOCUMENT_INTELLIGENCE_NOT_IN_PLAN";
|
|
26
26
|
var ERR_UNPROCESSABLE = "UNPROCESSABLE_ERROR";
|
|
27
27
|
var ERR_BAD_GATEWAY = "BAD_GATEWAY_ERROR";
|
|
28
|
+
var ERR_CHAT_SESSION_NOT_FOUND = "CHAT_SESSION_NOT_FOUND";
|
|
28
29
|
async function readChatError(error) {
|
|
29
30
|
const response = getResponseLike(error);
|
|
30
31
|
const info = {
|
|
@@ -65,6 +66,7 @@ async function readChatError(error) {
|
|
|
65
66
|
return info;
|
|
66
67
|
}
|
|
67
68
|
var SESSION_EXPIRED_TEXT = "Session expired \u2014 please reload the page or sign in again.";
|
|
69
|
+
var CONVERSATION_RESET_TEXT = "This conversation is no longer available \u2014 send your message again to start a new one.";
|
|
68
70
|
var RATE_LIMIT_TEXT = "You're sending messages too quickly \u2014 try again shortly.";
|
|
69
71
|
var PLAN_GATE_TEXT = "Chat isn't included in your plan.";
|
|
70
72
|
var UNANSWERABLE_TEXT = "We couldn't answer that. Try rephrasing your question.";
|
|
@@ -104,6 +106,12 @@ function describeChatError(info, originalText) {
|
|
|
104
106
|
if (status === 401) {
|
|
105
107
|
return { role: "error", text: SESSION_EXPIRED_TEXT };
|
|
106
108
|
}
|
|
109
|
+
if (errorCode === ERR_CHAT_SESSION_NOT_FOUND) {
|
|
110
|
+
return { role: "error", text: CONVERSATION_RESET_TEXT, retryText: originalText };
|
|
111
|
+
}
|
|
112
|
+
if (status === 404) {
|
|
113
|
+
return { role: "error", text: SERVICE_UNAVAILABLE_TEXT, retryText: originalText };
|
|
114
|
+
}
|
|
107
115
|
if (status === 422 || errorCode === ERR_UNPROCESSABLE) {
|
|
108
116
|
return { role: "error", text: UNANSWERABLE_TEXT };
|
|
109
117
|
}
|
|
@@ -175,6 +183,26 @@ var CHAT_CSS = `
|
|
|
175
183
|
@media (prefers-color-scheme: dark) {
|
|
176
184
|
.gemina-chat--auto { ${DARK_VARS} }
|
|
177
185
|
}
|
|
186
|
+
.gemina-chat__header {
|
|
187
|
+
display: flex;
|
|
188
|
+
justify-content: flex-end;
|
|
189
|
+
align-items: center;
|
|
190
|
+
flex: 0 0 auto;
|
|
191
|
+
padding: 6px 10px;
|
|
192
|
+
border-bottom: 1px solid var(--gemina-chat-border);
|
|
193
|
+
}
|
|
194
|
+
.gemina-chat__newchat {
|
|
195
|
+
font: inherit;
|
|
196
|
+
font-size: 12px;
|
|
197
|
+
padding: 3px 10px;
|
|
198
|
+
border-radius: var(--gemina-chat-radius);
|
|
199
|
+
border: 1px solid var(--gemina-chat-border);
|
|
200
|
+
background: transparent;
|
|
201
|
+
color: var(--gemina-chat-accent);
|
|
202
|
+
cursor: pointer;
|
|
203
|
+
}
|
|
204
|
+
.gemina-chat__newchat:hover:not(:disabled) { border-color: var(--gemina-chat-accent); }
|
|
205
|
+
.gemina-chat__newchat:disabled { opacity: 0.5; cursor: default; }
|
|
178
206
|
.gemina-chat__log {
|
|
179
207
|
flex: 1;
|
|
180
208
|
overflow-y: auto;
|
|
@@ -318,6 +346,7 @@ function GeminaChat(props) {
|
|
|
318
346
|
const nextIdRef = useRef(0);
|
|
319
347
|
const mountedRef = useRef(false);
|
|
320
348
|
const logRef = useRef(null);
|
|
349
|
+
const sessionIdRef = useRef(void 0);
|
|
321
350
|
useEffect(() => {
|
|
322
351
|
mountedRef.current = true;
|
|
323
352
|
ensureStylesInjected();
|
|
@@ -338,7 +367,12 @@ function GeminaChat(props) {
|
|
|
338
367
|
const chatOnce = useCallback(
|
|
339
368
|
(token, message) => {
|
|
340
369
|
const client = GeminaClient.withSessionToken(token, baseUrl);
|
|
341
|
-
|
|
370
|
+
const sessionId = sessionIdRef.current;
|
|
371
|
+
return client.chat.chatQuery({
|
|
372
|
+
// Thread the conversation id when we have one so follow-ups resolve
|
|
373
|
+
// referents ("what about the total?"); omit it to start a new one.
|
|
374
|
+
chatQueryInDTO: { message, endUserId, ...sessionId ? { sessionId } : {} }
|
|
375
|
+
});
|
|
342
376
|
},
|
|
343
377
|
[baseUrl, endUserId]
|
|
344
378
|
);
|
|
@@ -362,10 +396,22 @@ function GeminaChat(props) {
|
|
|
362
396
|
async (text) => {
|
|
363
397
|
setBusy(true);
|
|
364
398
|
try {
|
|
365
|
-
|
|
399
|
+
let result;
|
|
400
|
+
const hadSession = sessionIdRef.current !== void 0;
|
|
401
|
+
try {
|
|
402
|
+
result = await queryWithRetry(text);
|
|
403
|
+
} catch (error) {
|
|
404
|
+
if (hadSession && httpStatus(error) === 404) {
|
|
405
|
+
sessionIdRef.current = void 0;
|
|
406
|
+
result = await queryWithRetry(text);
|
|
407
|
+
} else {
|
|
408
|
+
throw error;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
366
411
|
if (!mountedRef.current) {
|
|
367
412
|
return;
|
|
368
413
|
}
|
|
414
|
+
sessionIdRef.current = result.sessionId ?? sessionIdRef.current;
|
|
369
415
|
appendMessage({
|
|
370
416
|
role: "assistant",
|
|
371
417
|
text: result.answer,
|
|
@@ -389,6 +435,26 @@ function GeminaChat(props) {
|
|
|
389
435
|
},
|
|
390
436
|
[queryWithRetry, appendMessage]
|
|
391
437
|
);
|
|
438
|
+
const startNewChat = useCallback(() => {
|
|
439
|
+
if (busy) {
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
const staleSession = sessionIdRef.current;
|
|
443
|
+
sessionIdRef.current = void 0;
|
|
444
|
+
setMessages([]);
|
|
445
|
+
setDraft("");
|
|
446
|
+
if (staleSession !== void 0) {
|
|
447
|
+
void (async () => {
|
|
448
|
+
try {
|
|
449
|
+
const token = await tokenManager.getToken();
|
|
450
|
+
await GeminaClient.withSessionToken(token, baseUrl).chat.deleteChatSession({
|
|
451
|
+
sessionId: staleSession
|
|
452
|
+
});
|
|
453
|
+
} catch {
|
|
454
|
+
}
|
|
455
|
+
})();
|
|
456
|
+
}
|
|
457
|
+
}, [busy, tokenManager, baseUrl]);
|
|
392
458
|
const submitDraft = useCallback(() => {
|
|
393
459
|
const text = draft.trim();
|
|
394
460
|
if (text.length === 0 || busy) {
|
|
@@ -447,6 +513,16 @@ function GeminaChat(props) {
|
|
|
447
513
|
className ?? ""
|
|
448
514
|
].filter((part) => part.length > 0).join(" ");
|
|
449
515
|
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
|
+
) }),
|
|
450
526
|
/* @__PURE__ */ jsxs(
|
|
451
527
|
"div",
|
|
452
528
|
{
|
|
@@ -552,4 +628,4 @@ export {
|
|
|
552
628
|
VERSION,
|
|
553
629
|
GeminaChat
|
|
554
630
|
};
|
|
555
|
-
//# sourceMappingURL=chunk-
|
|
631
|
+
//# sourceMappingURL=chunk-ZN4GN5SU.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 /** 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.2.1';\n"],"mappings":";AAYA,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AAEzD,SAAS,oBAAoB;;;ACbtB,IAAM,UAAU;;;ADmuBb,cAiCI,YAjCJ;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,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H;AAAA;AAAA;AAAA,gBA1BG,QAAQ;AAAA,cA4Bf;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,QAAQ,oBAAC,SAAI,WAAU,uBAAsB,4BAAS;AAAA;AAAA;AAAA,IACzD;AAAA,IACA,qBAAC,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.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.1
|
|
167
|
+
var VERSION = "0.2.1";
|
|
168
168
|
|
|
169
169
|
// src/chat.tsx
|
|
170
170
|
var import_jsx_runtime = require("react/jsx-runtime");
|
|
@@ -186,6 +186,7 @@ var ERR_CHAT_QUOTA_EXCEEDED = "CHAT_QUOTA_EXCEEDED";
|
|
|
186
186
|
var ERR_DI_NOT_IN_PLAN = "DOCUMENT_INTELLIGENCE_NOT_IN_PLAN";
|
|
187
187
|
var ERR_UNPROCESSABLE = "UNPROCESSABLE_ERROR";
|
|
188
188
|
var ERR_BAD_GATEWAY = "BAD_GATEWAY_ERROR";
|
|
189
|
+
var ERR_CHAT_SESSION_NOT_FOUND = "CHAT_SESSION_NOT_FOUND";
|
|
189
190
|
async function readChatError(error) {
|
|
190
191
|
const response = getResponseLike(error);
|
|
191
192
|
const info = {
|
|
@@ -226,6 +227,7 @@ async function readChatError(error) {
|
|
|
226
227
|
return info;
|
|
227
228
|
}
|
|
228
229
|
var SESSION_EXPIRED_TEXT = "Session expired \u2014 please reload the page or sign in again.";
|
|
230
|
+
var CONVERSATION_RESET_TEXT = "This conversation is no longer available \u2014 send your message again to start a new one.";
|
|
229
231
|
var RATE_LIMIT_TEXT = "You're sending messages too quickly \u2014 try again shortly.";
|
|
230
232
|
var PLAN_GATE_TEXT = "Chat isn't included in your plan.";
|
|
231
233
|
var UNANSWERABLE_TEXT = "We couldn't answer that. Try rephrasing your question.";
|
|
@@ -265,6 +267,12 @@ function describeChatError(info, originalText) {
|
|
|
265
267
|
if (status === 401) {
|
|
266
268
|
return { role: "error", text: SESSION_EXPIRED_TEXT };
|
|
267
269
|
}
|
|
270
|
+
if (errorCode === ERR_CHAT_SESSION_NOT_FOUND) {
|
|
271
|
+
return { role: "error", text: CONVERSATION_RESET_TEXT, retryText: originalText };
|
|
272
|
+
}
|
|
273
|
+
if (status === 404) {
|
|
274
|
+
return { role: "error", text: SERVICE_UNAVAILABLE_TEXT, retryText: originalText };
|
|
275
|
+
}
|
|
268
276
|
if (status === 422 || errorCode === ERR_UNPROCESSABLE) {
|
|
269
277
|
return { role: "error", text: UNANSWERABLE_TEXT };
|
|
270
278
|
}
|
|
@@ -336,6 +344,26 @@ var CHAT_CSS = `
|
|
|
336
344
|
@media (prefers-color-scheme: dark) {
|
|
337
345
|
.gemina-chat--auto { ${DARK_VARS} }
|
|
338
346
|
}
|
|
347
|
+
.gemina-chat__header {
|
|
348
|
+
display: flex;
|
|
349
|
+
justify-content: flex-end;
|
|
350
|
+
align-items: center;
|
|
351
|
+
flex: 0 0 auto;
|
|
352
|
+
padding: 6px 10px;
|
|
353
|
+
border-bottom: 1px solid var(--gemina-chat-border);
|
|
354
|
+
}
|
|
355
|
+
.gemina-chat__newchat {
|
|
356
|
+
font: inherit;
|
|
357
|
+
font-size: 12px;
|
|
358
|
+
padding: 3px 10px;
|
|
359
|
+
border-radius: var(--gemina-chat-radius);
|
|
360
|
+
border: 1px solid var(--gemina-chat-border);
|
|
361
|
+
background: transparent;
|
|
362
|
+
color: var(--gemina-chat-accent);
|
|
363
|
+
cursor: pointer;
|
|
364
|
+
}
|
|
365
|
+
.gemina-chat__newchat:hover:not(:disabled) { border-color: var(--gemina-chat-accent); }
|
|
366
|
+
.gemina-chat__newchat:disabled { opacity: 0.5; cursor: default; }
|
|
339
367
|
.gemina-chat__log {
|
|
340
368
|
flex: 1;
|
|
341
369
|
overflow-y: auto;
|
|
@@ -479,6 +507,7 @@ function GeminaChat(props) {
|
|
|
479
507
|
const nextIdRef = (0, import_react.useRef)(0);
|
|
480
508
|
const mountedRef = (0, import_react.useRef)(false);
|
|
481
509
|
const logRef = (0, import_react.useRef)(null);
|
|
510
|
+
const sessionIdRef = (0, import_react.useRef)(void 0);
|
|
482
511
|
(0, import_react.useEffect)(() => {
|
|
483
512
|
mountedRef.current = true;
|
|
484
513
|
ensureStylesInjected();
|
|
@@ -499,7 +528,12 @@ function GeminaChat(props) {
|
|
|
499
528
|
const chatOnce = (0, import_react.useCallback)(
|
|
500
529
|
(token, message) => {
|
|
501
530
|
const client = import_sdk.GeminaClient.withSessionToken(token, baseUrl);
|
|
502
|
-
|
|
531
|
+
const sessionId = sessionIdRef.current;
|
|
532
|
+
return client.chat.chatQuery({
|
|
533
|
+
// Thread the conversation id when we have one so follow-ups resolve
|
|
534
|
+
// referents ("what about the total?"); omit it to start a new one.
|
|
535
|
+
chatQueryInDTO: { message, endUserId, ...sessionId ? { sessionId } : {} }
|
|
536
|
+
});
|
|
503
537
|
},
|
|
504
538
|
[baseUrl, endUserId]
|
|
505
539
|
);
|
|
@@ -523,10 +557,22 @@ function GeminaChat(props) {
|
|
|
523
557
|
async (text) => {
|
|
524
558
|
setBusy(true);
|
|
525
559
|
try {
|
|
526
|
-
|
|
560
|
+
let result;
|
|
561
|
+
const hadSession = sessionIdRef.current !== void 0;
|
|
562
|
+
try {
|
|
563
|
+
result = await queryWithRetry(text);
|
|
564
|
+
} catch (error) {
|
|
565
|
+
if (hadSession && httpStatus(error) === 404) {
|
|
566
|
+
sessionIdRef.current = void 0;
|
|
567
|
+
result = await queryWithRetry(text);
|
|
568
|
+
} else {
|
|
569
|
+
throw error;
|
|
570
|
+
}
|
|
571
|
+
}
|
|
527
572
|
if (!mountedRef.current) {
|
|
528
573
|
return;
|
|
529
574
|
}
|
|
575
|
+
sessionIdRef.current = result.sessionId ?? sessionIdRef.current;
|
|
530
576
|
appendMessage({
|
|
531
577
|
role: "assistant",
|
|
532
578
|
text: result.answer,
|
|
@@ -550,6 +596,26 @@ function GeminaChat(props) {
|
|
|
550
596
|
},
|
|
551
597
|
[queryWithRetry, appendMessage]
|
|
552
598
|
);
|
|
599
|
+
const startNewChat = (0, import_react.useCallback)(() => {
|
|
600
|
+
if (busy) {
|
|
601
|
+
return;
|
|
602
|
+
}
|
|
603
|
+
const staleSession = sessionIdRef.current;
|
|
604
|
+
sessionIdRef.current = void 0;
|
|
605
|
+
setMessages([]);
|
|
606
|
+
setDraft("");
|
|
607
|
+
if (staleSession !== void 0) {
|
|
608
|
+
void (async () => {
|
|
609
|
+
try {
|
|
610
|
+
const token = await tokenManager.getToken();
|
|
611
|
+
await import_sdk.GeminaClient.withSessionToken(token, baseUrl).chat.deleteChatSession({
|
|
612
|
+
sessionId: staleSession
|
|
613
|
+
});
|
|
614
|
+
} catch {
|
|
615
|
+
}
|
|
616
|
+
})();
|
|
617
|
+
}
|
|
618
|
+
}, [busy, tokenManager, baseUrl]);
|
|
553
619
|
const submitDraft = (0, import_react.useCallback)(() => {
|
|
554
620
|
const text = draft.trim();
|
|
555
621
|
if (text.length === 0 || busy) {
|
|
@@ -608,6 +674,16 @@ function GeminaChat(props) {
|
|
|
608
674
|
className ?? ""
|
|
609
675
|
].filter((part) => part.length > 0).join(" ");
|
|
610
676
|
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
|
+
) }),
|
|
611
687
|
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
|
|
612
688
|
"div",
|
|
613
689
|
{
|
package/dist/index.cjs.map
CHANGED
|
@@ -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\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 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 // 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__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\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 return client.chat.chatQuery({ chatQueryInDTO: { message, endUserId } });\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 const result = await queryWithRetry(text);\n if (!mountedRef.current) {\n return;\n }\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 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 <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>\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A,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/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.2.1';\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,QAAM,EAAE,OAAO,UAAU,IAAI;AAC7B,MAAI,OAAO,UAAU,YAAY,MAAM,WAAW,GAAG;AACnD,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AACA,MAAI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HANGED
package/dist/index.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gemina/elements",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.2.1",
|
|
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": {
|
|
@@ -55,7 +55,7 @@
|
|
|
55
55
|
"embeddable"
|
|
56
56
|
],
|
|
57
57
|
"dependencies": {
|
|
58
|
-
"@gemina/sdk": "^0.
|
|
58
|
+
"@gemina/sdk": "^0.2.0"
|
|
59
59
|
},
|
|
60
60
|
"peerDependencies": {
|
|
61
61
|
"react": ">=18",
|
|
@@ -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\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 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 // 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__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\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 return client.chat.chatQuery({ chatQueryInDTO: { message, endUserId } });\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 const result = await queryWithRetry(text);\n if (!mountedRef.current) {\n return;\n }\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 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 <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.1.2';\n"],"mappings":";AAYA,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AAEzD,SAAS,oBAAoB;;;ACbtB,IAAM,UAAU;;;AD+oBT,cAYA,YAZA;AA/jBd,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;AAkBxB,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;AA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