doccupine 0.0.147 → 0.0.148

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.
@@ -1,488 +1,269 @@
1
1
  export const chatTemplate = `"use client";
2
- import React, {
3
- createContext,
4
- useCallback,
5
- useContext,
6
- useEffect,
7
- useLayoutEffect,
8
- useRef,
9
- useState,
10
- useSyncExternalStore,
11
- } from "react";
12
- import { IconButton } from "cherry-styled-components";
13
- import { ArrowUp, LoaderPinwheel, RotateCcw, Sparkles, X } from "lucide-react";
2
+ import React, { createContext, useMemo } from "react";
3
+ import { useRouter } from "next/navigation";
4
+ import {
5
+ ChatInput,
6
+ ChatMessage,
7
+ ChatMessageList,
8
+ ChatPanel,
9
+ ChatProvider,
10
+ ChatSource,
11
+ ChatSources,
12
+ ChatTyping,
13
+ IconButton,
14
+ Prose,
15
+ useBelowBreakpoint,
16
+ useChat,
17
+ type ChatSendContext,
18
+ type ChatSourceData,
19
+ } from "cherry-styled-components";
20
+ import { RotateCcw } from "lucide-react";
14
21
  import remarkGfm from "remark-gfm";
15
22
  import rehypeHighlight from "rehype-highlight";
16
23
  import { MDXRemote, MDXRemoteSerializeResult } from "next-mdx-remote";
17
24
  import { serialize } from "next-mdx-remote/serialize";
18
- import { theme } from "@/app/theme";
19
- import {
20
- StyledAnswer,
21
- StyledChat,
22
- StyledChatForm,
23
- StyledChatSurface,
24
- StyledChatTitle,
25
- StyledChatTitleIconWrapper,
26
- StyledError,
27
- StyledGlowSmallButton,
28
- StyledLoading,
29
- StyledRainbowButton,
30
- StyledRainbowInput,
31
- StyledRainbowInputWrapper,
32
- StyledSourceLink,
33
- StyledSources,
34
- StyledSparkle,
35
- StyledSparkleContainer,
36
- } from "@/components/ChatStyles";
37
25
  import { Callout } from "@/components/layout/Callout";
38
- import { useLockBodyScroll } from "@/components/LockBodyScroll";
39
26
  import { useMDXComponents as getMDXComponents } from "@/components/MDXComponents";
40
27
 
41
28
  const mdxComponents = getMDXComponents({});
42
29
 
43
- const MOBILE_CHAT_QUERY = \`(max-width: \${theme.breakpoints.lg - 1}px)\`;
44
-
45
- function subscribeToMobileChat(callback: () => void) {
46
- const mediaQuery = window.matchMedia(MOBILE_CHAT_QUERY);
47
- mediaQuery.addEventListener("change", callback);
48
- return () => mediaQuery.removeEventListener("change", callback);
49
- }
50
-
51
- function getMobileChatSnapshot() {
52
- return window.matchMedia(MOBILE_CHAT_QUERY).matches;
53
- }
54
-
55
- function useIsMobileChat() {
56
- return useSyncExternalStore(
57
- subscribeToMobileChat,
58
- getMobileChatSnapshot,
59
- () => false,
60
- );
61
- }
62
-
63
- type Source = {
30
+ type RagSource = {
64
31
  id: string;
65
32
  path: string;
66
33
  uri: string;
67
34
  score: number;
68
35
  };
69
36
 
70
- type Answer = {
71
- text: string;
72
- answer?: boolean;
73
- mdx?: MDXRemoteSerializeResult;
74
- sources?: Source[];
75
- };
37
+ // Map a retrieval hit onto the chip the transcript renders: docs://<slug>
38
+ // becomes an app-relative href, and the slug's last segment becomes a
39
+ // title-cased label.
40
+ function toSourceChip(src: RagSource): ChatSourceData {
41
+ const slug = src.uri.replace("docs://", "").replace(/^\\/+/, "");
42
+ const href = slug ? \`/\${slug}/\` : "/";
43
+ const label = slug
44
+ ? slug
45
+ .split("/")
46
+ .pop()!
47
+ .replace(/-/g, " ")
48
+ .replace(/\\b\\w/g, (c: string) => c.toUpperCase())
49
+ : "Home";
50
+ return { id: src.id, label, href };
51
+ }
76
52
 
77
- const SPARKLE_COLORS = [
78
- "#ff6b6b",
79
- "#feca57",
80
- "#48dbfb",
81
- "#ff9ff3",
82
- "#54a0ff",
83
- "#5f27cd",
84
- ];
53
+ // Cherry's ChatProvider owns the transcript, panel state, and streaming
54
+ // bookkeeping; this handler owns the transport: POST the question to
55
+ // /api/rag, stream the SSE frames, and patch the assistant bubble as tokens
56
+ // arrive. The provider bounds \`history\` to the RAG contract (20 entries,
57
+ // 4000 chars each), swallows aborts, and surfaces thrown errors as \`error\`.
58
+ async function sendToAssistant(
59
+ question: string,
60
+ { signal, history, setAssistant }: ChatSendContext,
61
+ ) {
62
+ const res = await fetch("/api/rag", {
63
+ method: "POST",
64
+ headers: { "Content-Type": "application/json" },
65
+ body: JSON.stringify({ question, history }),
66
+ signal,
67
+ });
68
+
69
+ if (!res.ok) {
70
+ // The body may be a proxy/gateway HTML error page (e.g. Cloudflare
71
+ // 524), not our JSON - never blindly JSON.parse it.
72
+ const contentType = res.headers.get("content-type") || "";
73
+ let message = "Request failed";
74
+ if (contentType.includes("application/json")) {
75
+ try {
76
+ const errorData = await res.json();
77
+ message = errorData.error || message;
78
+ } catch {
79
+ // Non-JSON despite the header - fall through to the default.
80
+ }
81
+ } else if ([502, 503, 504, 524].includes(res.status)) {
82
+ message = "The assistant took too long to respond. Please try again.";
83
+ }
84
+ throw new Error(message);
85
+ }
85
86
 
86
- // Deterministic sparkle positions to avoid hydration mismatch
87
- const SPARKLE_POSITIONS = [
88
- { left: 8, top: 35 },
89
- { left: 17, top: 55 },
90
- { left: 26, top: 28 },
91
- { left: 35, top: 68 },
92
- { left: 44, top: 42 },
93
- { left: 53, top: 75 },
94
- { left: 62, top: 32 },
95
- { left: 71, top: 58 },
96
- { left: 80, top: 45 },
97
- { left: 89, top: 65 },
98
- ];
87
+ const reader = res.body?.getReader();
88
+ if (!reader) {
89
+ throw new Error("Failed to get response reader");
90
+ }
99
91
 
100
- interface RainbowInputProps {
101
- id?: string;
102
- value: string;
103
- onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
104
- placeholder?: string;
105
- autoComplete?: string;
106
- "aria-label"?: string;
107
- inputRef?: React.Ref<HTMLInputElement>;
108
- }
92
+ const decoder = new TextDecoder();
93
+ const contentParts: string[] = [];
94
+ let sources: ChatSourceData[] = [];
95
+ let buffer = "";
96
+
97
+ while (true) {
98
+ const { done, value } = await reader.read();
99
+ if (done) break;
100
+
101
+ buffer += decoder.decode(value, { stream: true });
102
+ const parts = buffer.split("\\n");
103
+ buffer = parts.pop() ?? "";
104
+
105
+ for (const line of parts) {
106
+ if (!line.startsWith("data: ")) continue;
107
+
108
+ // Guard only the parse: a malformed frame is skipped, while the
109
+ // server's error event below must throw past this loop so it lands
110
+ // in the provider's error state instead of dying in a parse-error
111
+ // log.
112
+ let data;
113
+ try {
114
+ data = JSON.parse(line.slice(6));
115
+ } catch {
116
+ console.error("Failed to parse SSE data:", line);
117
+ continue;
118
+ }
109
119
 
110
- function RainbowInput({
111
- id,
112
- value,
113
- onChange,
114
- placeholder,
115
- autoComplete,
116
- "aria-label": ariaLabel,
117
- inputRef,
118
- }: RainbowInputProps) {
119
- const [isFocused, setIsFocused] = useState(false);
120
- const [isHovered, setIsHovered] = useState(false);
121
- const isActive = isFocused || isHovered;
120
+ if (data.type === "metadata") {
121
+ const allSources: RagSource[] = data.data?.sources ?? [];
122
+ const seen = new Set<string>();
123
+ sources = allSources
124
+ .filter((s) => {
125
+ if (s.score < 0.4 || seen.has(s.uri)) return false;
126
+ seen.add(s.uri);
127
+ return true;
128
+ })
129
+ .map(toSourceChip);
130
+ } else if (data.type === "content") {
131
+ contentParts.push(data.data);
132
+ const streamedContent = contentParts.join("");
133
+ setAssistant(streamedContent, { text: streamedContent, sources });
134
+ } else if (data.type === "error") {
135
+ throw new Error(data.data);
136
+ } else if (data.type === "done") {
137
+ const streamedContent = contentParts.join("");
138
+ let mdxSource: MDXRemoteSerializeResult | null = null;
139
+ try {
140
+ mdxSource = await serialize(streamedContent, {
141
+ parseFrontmatter: false,
142
+ mdxOptions: {
143
+ remarkPlugins: [remarkGfm],
144
+ rehypePlugins: [rehypeHighlight],
145
+ format: "md",
146
+ development: false,
147
+ },
148
+ });
149
+ } catch (mdxError: unknown) {
150
+ console.error("MDX serialization error:", mdxError);
151
+ }
152
+
153
+ setAssistant(
154
+ mdxSource ? (
155
+ <MDXRemote {...mdxSource} components={mdxComponents} />
156
+ ) : (
157
+ streamedContent
158
+ ),
159
+ { text: streamedContent, sources },
160
+ );
161
+ }
162
+ }
163
+ }
164
+ }
122
165
 
123
- const sparkles = SPARKLE_POSITIONS.map((pos, i) => ({
124
- color: SPARKLE_COLORS[i % SPARKLE_COLORS.length],
125
- left: pos.left,
126
- top: pos.top,
127
- delay: i * 0.12,
128
- }));
166
+ function ChatSourceLink({ source }: { source: ChatSourceData }) {
167
+ const { close } = useChat();
168
+ const isMobileChat = useBelowBreakpoint("lg");
169
+ const router = useRouter();
129
170
 
130
171
  return (
131
- <StyledRainbowInputWrapper
132
- $isActive={isActive}
133
- onMouseEnter={() => setIsHovered(true)}
134
- onMouseLeave={() => setIsHovered(false)}
172
+ <ChatSource
173
+ href={source.href}
174
+ onClick={(event) => {
175
+ if (
176
+ event.defaultPrevented ||
177
+ event.button !== 0 ||
178
+ event.metaKey ||
179
+ event.ctrlKey ||
180
+ event.shiftKey ||
181
+ event.altKey
182
+ ) {
183
+ return;
184
+ }
185
+ // ChatSource renders a plain anchor, so route unmodified left clicks
186
+ // client-side to keep the transcript alive; below lg the panel is a
187
+ // fullscreen dialog, so close it to reveal the navigated page.
188
+ event.preventDefault();
189
+ if (isMobileChat) close();
190
+ router.push(source.href);
191
+ }}
135
192
  >
136
- <StyledSparkleContainer $isActive={isActive}>
137
- {sparkles.map((sparkle, i) => (
138
- <StyledSparkle
139
- key={i}
140
- $color={sparkle.color}
141
- $left={sparkle.left}
142
- $top={sparkle.top}
143
- $delay={sparkle.delay}
144
- />
145
- ))}
146
- </StyledSparkleContainer>
147
- <StyledRainbowInput
148
- ref={inputRef}
149
- id={id}
150
- value={value}
151
- onChange={onChange}
152
- placeholder={placeholder}
153
- autoComplete={autoComplete}
154
- aria-label={ariaLabel}
155
- onFocus={() => setIsFocused(true)}
156
- onBlur={() => setIsFocused(false)}
157
- />
158
- </StyledRainbowInputWrapper>
193
+ {source.label}
194
+ </ChatSource>
159
195
  );
160
196
  }
161
197
 
162
- function ChatButtonCTA() {
163
- const { toggleChat, isOpen } = useContext(ChatContext);
198
+ function ChatTranscript() {
199
+ const { messages, loading, error } = useChat();
200
+ const lastMessage = messages[messages.length - 1];
164
201
 
165
202
  return (
166
- <StyledGlowSmallButton
167
- onClick={toggleChat}
168
- aria-label="Ask AI Assistant"
169
- $hasContent={isOpen}
170
- type="button"
171
- >
172
- <span>
173
- <Sparkles size={16} />
174
- Ask AI
175
- </span>
176
- </StyledGlowSmallButton>
203
+ <ChatMessageList>
204
+ {messages.map((message) => (
205
+ <ChatMessage key={message.id} $role={message.role}>
206
+ {message.role === "assistant" ? (
207
+ // The docs' typographic context lives on the docs page wrapper,
208
+ // so a rendered MDX answer would arrive margin-less here. Prose
209
+ // $compact is Cherry's document styling for chat replies: a 10px
210
+ // rhythm between elements, inline-code chips, lists, and tables.
211
+ <Prose $compact>{message.content}</Prose>
212
+ ) : (
213
+ message.content
214
+ )}
215
+ {message.role === "assistant" &&
216
+ message.sources &&
217
+ message.sources.length > 0 && (
218
+ <ChatSources>
219
+ {message.sources.map((source) => (
220
+ <ChatSourceLink key={source.id} source={source} />
221
+ ))}
222
+ </ChatSources>
223
+ )}
224
+ </ChatMessage>
225
+ ))}
226
+ {loading && lastMessage?.role !== "assistant" && <ChatTyping />}
227
+ {error && (
228
+ <Callout type="danger">
229
+ <p>
230
+ <strong>Error:</strong> {error}
231
+ </p>
232
+ </Callout>
233
+ )}
234
+ </ChatMessageList>
177
235
  );
178
236
  }
179
237
 
180
- function Chat() {
181
- const {
182
- isOpen,
183
- question,
184
- setQuestion,
185
- loading,
186
- error,
187
- answer,
188
- ask,
189
- closeChat,
190
- resetChat,
191
- chatInputRef,
192
- } = useContext(ChatContext);
193
- const chatSurfaceRef = useRef<HTMLDivElement | null>(null);
194
- const chatScrollRef = useRef<HTMLDivElement | null>(null);
195
- const scrollFrameRef = useRef<number | null>(null);
196
- const shouldAutoScrollRef = useRef(true);
197
- const loadingRef = useRef(loading);
198
- const isMobileChat = useIsMobileChat();
199
- const isMobileModal = isOpen && isMobileChat;
200
-
201
- useLockBodyScroll(isOpen);
202
-
203
- useEffect(() => {
204
- loadingRef.current = loading;
205
- }, [loading]);
206
-
207
- useLayoutEffect(() => {
208
- if (isOpen) {
209
- shouldAutoScrollRef.current = true;
210
- return;
211
- }
212
-
213
- if (scrollFrameRef.current !== null) {
214
- cancelAnimationFrame(scrollFrameRef.current);
215
- scrollFrameRef.current = null;
216
- }
217
- }, [isOpen]);
218
-
219
- useEffect(() => {
220
- if (!isOpen || !shouldAutoScrollRef.current) return;
221
- if (scrollFrameRef.current !== null) return;
222
-
223
- scrollFrameRef.current = requestAnimationFrame(() => {
224
- scrollFrameRef.current = null;
225
- const scrollContainer = chatScrollRef.current;
226
- if (!scrollContainer || !shouldAutoScrollRef.current) return;
227
- const reduceMotion = window.matchMedia(
228
- "(prefers-reduced-motion: reduce)",
229
- ).matches;
230
- scrollContainer.scrollTo({
231
- top: scrollContainer.scrollHeight,
232
- behavior: reduceMotion || loadingRef.current ? "auto" : "smooth",
233
- });
234
- });
235
- }, [answer, isOpen, loading]);
236
-
237
- useEffect(() => {
238
- return () => {
239
- if (scrollFrameRef.current !== null) {
240
- cancelAnimationFrame(scrollFrameRef.current);
241
- }
242
- };
243
- }, []);
244
-
245
- useEffect(() => {
246
- if (!isMobileModal || !chatSurfaceRef.current) return;
247
-
248
- const surface = chatSurfaceRef.current;
249
- const inertSiblings: Array<{
250
- element: HTMLElement;
251
- wasInert: boolean;
252
- }> = [];
253
- let current: HTMLElement = surface;
254
-
255
- while (current.parentElement) {
256
- const parent = current.parentElement;
257
- for (const sibling of Array.from(parent.children)) {
258
- if (sibling === current || !(sibling instanceof HTMLElement)) continue;
259
- inertSiblings.push({ element: sibling, wasInert: sibling.inert });
260
- sibling.inert = true;
261
- }
262
- if (parent === document.body) break;
263
- current = parent;
264
- }
265
-
266
- const containFocus = (event: FocusEvent) => {
267
- if (event.target instanceof Node && !surface.contains(event.target)) {
268
- chatInputRef.current?.focus();
269
- }
270
- };
271
-
272
- document.addEventListener("focusin", containFocus);
273
- chatInputRef.current?.focus();
274
-
275
- return () => {
276
- document.removeEventListener("focusin", containFocus);
277
- for (const { element, wasInert } of inertSiblings) {
278
- element.inert = wasInert;
279
- }
280
- };
281
- }, [chatInputRef, isMobileModal]);
282
-
283
- const handleChatScroll = () => {
284
- const scrollContainer = chatScrollRef.current;
285
- if (!scrollContainer) return;
286
- const distanceFromBottom =
287
- scrollContainer.scrollHeight -
288
- scrollContainer.scrollTop -
289
- scrollContainer.clientHeight;
290
- shouldAutoScrollRef.current =
291
- distanceFromBottom <= scrollContainer.clientHeight * 0.15;
292
- };
293
-
294
- const handleSurfaceKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
295
- if (event.key === "Escape" && isMobileModal) {
296
- event.preventDefault();
297
- event.stopPropagation();
298
- closeChat();
299
- return;
300
- }
301
-
302
- if (event.key !== "Tab" || !isMobileModal) return;
303
- const focusable = Array.from(
304
- chatSurfaceRef.current?.querySelectorAll<HTMLElement>(
305
- 'a[href], button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])',
306
- ) ?? [],
307
- ).filter(
308
- (element) =>
309
- element.offsetParent !== null &&
310
- element.getAttribute("aria-hidden") !== "true",
311
- );
312
- if (focusable.length === 0) {
313
- event.preventDefault();
314
- return;
315
- }
316
- const first = focusable[0];
317
- const last = focusable[focusable.length - 1];
318
- if (event.shiftKey && document.activeElement === first) {
319
- event.preventDefault();
320
- last.focus();
321
- } else if (!event.shiftKey && document.activeElement === last) {
322
- event.preventDefault();
323
- first.focus();
324
- }
325
- };
238
+ function ChatActions() {
239
+ const { reset } = useChat();
326
240
 
327
241
  return (
328
- <StyledChatSurface
329
- ref={chatSurfaceRef}
330
- $isVisible={isOpen}
331
- inert={!isOpen}
332
- aria-hidden={!isOpen}
333
- role={isMobileModal ? "dialog" : "complementary"}
334
- aria-modal={isMobileModal ? "true" : undefined}
335
- aria-label="AI Assistant"
336
- data-chat-surface
337
- data-markdown-ignore
338
- onKeyDownCapture={handleSurfaceKeyDown}
242
+ <IconButton
243
+ onClick={reset}
244
+ aria-label="Reset chat history"
245
+ title="Reset chat history"
339
246
  >
340
- <StyledChat
341
- ref={chatScrollRef}
342
- $isVisible={isOpen}
343
- onScroll={handleChatScroll}
344
- >
345
- <StyledChatTitle>
346
- <StyledChatTitleIconWrapper>
347
- <Sparkles />
348
- <h3>AI Assistant</h3>
349
- </StyledChatTitleIconWrapper>
350
- <StyledChatTitleIconWrapper>
351
- <IconButton
352
- onClick={resetChat}
353
- aria-label="Reset chat history"
354
- title="Reset chat history"
355
- >
356
- <RotateCcw />
357
- </IconButton>
358
- <IconButton
359
- onClick={() => closeChat()}
360
- aria-label="Close chat"
361
- title="Close chat"
362
- >
363
- <X />
364
- </IconButton>
365
- </StyledChatTitleIconWrapper>
366
- </StyledChatTitle>
367
- {answer &&
368
- answer.map((a, i) => (
369
- <React.Fragment key={i}>
370
- <StyledAnswer $isAnswer={a.answer ?? false}>
371
- {a.answer && a.mdx ? (
372
- <MDXRemote {...a.mdx} components={mdxComponents} />
373
- ) : (
374
- a.text
375
- )}
376
- </StyledAnswer>
377
- {a.answer && a.sources && a.sources.length > 0 && (
378
- <StyledSources>
379
- {a.sources.map((src) => {
380
- const slug = src.uri
381
- .replace("docs://", "")
382
- .replace(/^\\/+/, "");
383
- const href = slug ? \`/\${slug}/\` : "/";
384
- const label = slug
385
- ? slug
386
- .split("/")
387
- .pop()!
388
- .replace(/-/g, " ")
389
- .replace(/\\b\\w/g, (c: string) => c.toUpperCase())
390
- : "Home";
391
- return (
392
- <StyledSourceLink
393
- key={src.id}
394
- href={href}
395
- onClick={() => {
396
- if (window.innerWidth <= 992) {
397
- closeChat();
398
- }
399
- }}
400
- >
401
- {label}
402
- </StyledSourceLink>
403
- );
404
- })}
405
- </StyledSources>
406
- )}
407
- </React.Fragment>
408
- ))}
409
- {loading && !answer[answer.length - 1]?.answer && (
410
- <StyledLoading>
411
- Answering<span>.</span>
412
- <span>.</span>
413
- <span>.</span>
414
- </StyledLoading>
415
- )}
416
- {error && (
417
- <StyledError>
418
- <Callout type="danger">
419
- <p>
420
- <strong>Error:</strong> {error}
421
- </p>
422
- </Callout>
423
- </StyledError>
424
- )}
425
- </StyledChat>
247
+ <RotateCcw />
248
+ </IconButton>
249
+ );
250
+ }
426
251
 
427
- <StyledChatForm onSubmit={ask} $isVisible={isOpen} data-markdown-ignore>
428
- <RainbowInput
429
- id="chat-bottom-input"
430
- inputRef={chatInputRef}
431
- value={question}
432
- onChange={(e) => setQuestion(e.target.value)}
433
- placeholder="Ask AI Assistant..."
434
- autoComplete="off"
435
- aria-label="Ask a follow-up question"
436
- />
437
- <StyledRainbowButton
438
- type="submit"
439
- disabled={loading || question.trim() === ""}
440
- $hasContent={question.trim().length > 0}
441
- aria-label={loading ? "Loading response" : "Submit question"}
442
- >
443
- {loading ? <LoaderPinwheel className="loading" /> : <ArrowUp />}
444
- </StyledRainbowButton>
445
- </StyledChatForm>
446
- </StyledChatSurface>
252
+ function Chat() {
253
+ return (
254
+ <ChatPanel $title="AI Assistant" $actions={<ChatActions />}>
255
+ <ChatTranscript />
256
+ <ChatInput $glow />
257
+ </ChatPanel>
447
258
  );
448
259
  }
449
260
 
450
- const ChatContext = createContext<{
451
- isOpen: boolean;
452
- setIsOpen: (isOpen: boolean) => void;
453
- toggleChat: () => void;
454
- isChatActive: boolean;
455
- question: string;
456
- setQuestion: (q: string) => void;
457
- loading: boolean;
458
- error: string | null;
459
- answer: Answer[];
460
- setAnswer: (answers: Answer[]) => void;
461
- ask: (e: React.FormEvent) => void;
462
- askAssistant: (question: string, returnFocusTo?: HTMLElement | null) => void;
463
- closeChat: (restoreFocus?: boolean) => HTMLElement | null;
464
- registerSearchClose: (
465
- closeSearch: (restoreFocus?: boolean) => HTMLElement | null,
466
- ) => () => void;
467
- resetChat: () => void;
468
- chatInputRef: React.RefObject<HTMLInputElement | null>;
469
- }>({
470
- isOpen: false,
471
- setIsOpen: () => {},
472
- toggleChat: () => {},
261
+ // App-level chat context: only whether the AI assistant is enabled (an LLM
262
+ // provider is configured). Panel state, the transcript, and streaming all
263
+ // live in Cherry's ChatProvider - read those with useChat() from
264
+ // "cherry-styled-components".
265
+ const ChatContext = createContext<{ isChatActive: boolean }>({
473
266
  isChatActive: false,
474
- question: "",
475
- setQuestion: () => {},
476
- loading: false,
477
- error: null,
478
- answer: [],
479
- setAnswer: () => {},
480
- ask: () => {},
481
- askAssistant: () => {},
482
- closeChat: () => null,
483
- registerSearchClose: () => () => {},
484
- resetChat: () => {},
485
- chatInputRef: { current: null },
486
267
  });
487
268
 
488
269
  interface ChatContextProviderProps {
@@ -490,361 +271,20 @@ interface ChatContextProviderProps {
490
271
  isChatActive: boolean;
491
272
  }
492
273
 
493
- const INITIAL_GREETING = "Hey there, how can I assist you?";
494
-
495
274
  const ChtProvider = ({ children, isChatActive }: ChatContextProviderProps) => {
496
- const [isOpen, setIsOpen] = useState(false);
497
- const [question, setQuestion] = useState("");
498
- const [loading, setLoading] = useState(false);
499
- const [error, setError] = useState<string | null>(null);
500
- const [answer, setAnswer] = useState<Answer[]>([]);
501
- const abortRef = useRef<AbortController | null>(null);
502
- const chatInputRef = useRef<HTMLInputElement | null>(null);
503
- const focusTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
504
- const restoreFocusTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(
505
- null,
506
- );
507
- const pendingRestoreFocusRef = useRef<HTMLElement | null>(null);
508
- const openerRef = useRef<HTMLElement | null>(null);
509
- const closeSearchRef = useRef<
510
- ((restoreFocus?: boolean) => HTMLElement | null) | null
511
- >(null);
512
- const isOpenRef = useRef(isOpen);
513
-
514
- useEffect(() => {
515
- isOpenRef.current = isOpen;
516
- }, [isOpen]);
517
-
518
- const showChat = useCallback((returnFocusTo?: HTMLElement | null) => {
519
- const previousOverlayOpener = closeSearchRef.current?.(false) ?? null;
520
- const pendingChatOpener = pendingRestoreFocusRef.current;
521
- if (restoreFocusTimeoutRef.current) {
522
- clearTimeout(restoreFocusTimeoutRef.current);
523
- restoreFocusTimeoutRef.current = null;
524
- }
525
- pendingRestoreFocusRef.current = null;
526
- if (!isOpenRef.current) {
527
- const activeElement = document.activeElement;
528
- openerRef.current =
529
- returnFocusTo?.isConnected === true
530
- ? returnFocusTo
531
- : previousOverlayOpener?.isConnected === true
532
- ? previousOverlayOpener
533
- : pendingChatOpener?.isConnected === true
534
- ? pendingChatOpener
535
- : activeElement instanceof HTMLElement &&
536
- activeElement !== document.body
537
- ? activeElement
538
- : null;
539
- }
540
- isOpenRef.current = true;
541
- setIsOpen(true);
542
- if (focusTimeoutRef.current) clearTimeout(focusTimeoutRef.current);
543
- focusTimeoutRef.current = setTimeout(() => {
544
- focusTimeoutRef.current = null;
545
- chatInputRef.current?.focus();
546
- }, 0);
547
- }, []);
548
-
549
- // Open the assistant and seed its greeting on the first visit. The opener is
550
- // captured before the mobile dialog makes the rest of the page inert.
551
- const openChat = useCallback(() => {
552
- showChat();
553
- setAnswer((prev) =>
554
- prev.length === 0 ? [{ text: INITIAL_GREETING, answer: true }] : prev,
555
- );
556
- }, [showChat]);
557
-
558
- const closeChat = useCallback((restoreFocus = true) => {
559
- const pendingOpener = pendingRestoreFocusRef.current;
560
- if (!restoreFocus && restoreFocusTimeoutRef.current) {
561
- clearTimeout(restoreFocusTimeoutRef.current);
562
- restoreFocusTimeoutRef.current = null;
563
- pendingRestoreFocusRef.current = null;
564
- }
565
- if (!isOpenRef.current) return pendingOpener;
566
- if (focusTimeoutRef.current) {
567
- clearTimeout(focusTimeoutRef.current);
568
- focusTimeoutRef.current = null;
569
- }
570
- const activeElement = document.activeElement;
571
- if (
572
- activeElement instanceof HTMLElement &&
573
- activeElement.closest("[data-chat-surface]")
574
- ) {
575
- activeElement.blur();
576
- }
577
- const opener = openerRef.current;
578
- openerRef.current = null;
579
- isOpenRef.current = false;
580
- setIsOpen(false);
581
- if (restoreFocusTimeoutRef.current) {
582
- clearTimeout(restoreFocusTimeoutRef.current);
583
- }
584
- if (restoreFocus) {
585
- pendingRestoreFocusRef.current = opener;
586
- restoreFocusTimeoutRef.current = setTimeout(() => {
587
- const focusTarget = pendingRestoreFocusRef.current;
588
- restoreFocusTimeoutRef.current = null;
589
- pendingRestoreFocusRef.current = null;
590
- if (focusTarget?.isConnected) focusTarget.focus();
591
- }, 0);
592
- } else {
593
- pendingRestoreFocusRef.current = null;
594
- }
595
- return opener;
596
- }, []);
597
-
598
- const registerSearchClose = useCallback(
599
- (closeSearch: (restoreFocus?: boolean) => HTMLElement | null) => {
600
- closeSearchRef.current = closeSearch;
601
- return () => {
602
- if (closeSearchRef.current === closeSearch) {
603
- closeSearchRef.current = null;
604
- }
605
- };
606
- },
607
- [],
608
- );
609
-
610
- const toggleChat = useCallback(() => {
611
- if (isOpenRef.current) {
612
- closeChat();
613
- } else {
614
- openChat();
615
- }
616
- }, [closeChat, openChat]);
617
-
618
- useEffect(() => {
619
- return () => {
620
- if (focusTimeoutRef.current) clearTimeout(focusTimeoutRef.current);
621
- if (restoreFocusTimeoutRef.current) {
622
- clearTimeout(restoreFocusTimeoutRef.current);
623
- }
624
- };
625
- }, []);
626
-
627
- // Global Cmd/Ctrl+I toggles the assistant, but only when chat is enabled.
628
- useEffect(() => {
629
- if (!isChatActive) return;
630
- function handleKeyDown(e: KeyboardEvent) {
631
- if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "i") {
632
- e.preventDefault();
633
- toggleChat();
634
- }
635
- }
636
- document.addEventListener("keydown", handleKeyDown);
637
- return () => document.removeEventListener("keydown", handleKeyDown);
638
- }, [isChatActive, toggleChat]);
639
-
640
- async function runQuestion(
641
- currentQuestion: string,
642
- returnFocusTo?: HTMLElement | null,
643
- ) {
644
- setQuestion("");
645
- showChat(returnFocusTo);
646
- setLoading(true);
647
- setError(null);
648
-
649
- const base =
650
- answer.length > 0 ? answer : [{ text: INITIAL_GREETING, answer: true }];
651
- const mergedQuestions = [...base, { text: currentQuestion, answer: false }];
652
-
653
- setAnswer(mergedQuestions);
654
-
655
- const controller = new AbortController();
656
- abortRef.current = controller;
657
-
658
- try {
659
- const history = answer
660
- .filter((a) => a.text.trim() !== "")
661
- .slice(-20)
662
- .map((a) => ({
663
- role: a.answer ? ("assistant" as const) : ("user" as const),
664
- content: a.text.slice(0, 4000),
665
- }));
666
-
667
- const res = await fetch("/api/rag", {
668
- method: "POST",
669
- headers: { "Content-Type": "application/json" },
670
- body: JSON.stringify({ question: currentQuestion, history }),
671
- signal: controller.signal,
672
- });
673
-
674
- if (!res.ok) {
675
- // The body may be a proxy/gateway HTML error page (e.g. Cloudflare
676
- // 524), not our JSON - never blindly JSON.parse it.
677
- const contentType = res.headers.get("content-type") || "";
678
- let message = "Request failed";
679
- if (contentType.includes("application/json")) {
680
- try {
681
- const errorData = await res.json();
682
- message = errorData.error || message;
683
- } catch {
684
- // Non-JSON despite the header - fall through to the default.
685
- }
686
- } else if ([502, 503, 504, 524].includes(res.status)) {
687
- message = "The assistant took too long to respond. Please try again.";
688
- }
689
- throw new Error(message);
690
- }
691
-
692
- const reader = res.body?.getReader();
693
- const decoder = new TextDecoder();
694
- const contentParts: string[] = [];
695
- let sources: Source[] = [];
696
- if (!reader) {
697
- throw new Error("Failed to get response reader");
698
- }
699
-
700
- // Don't insert the answer bubble yet - an empty bubble renders a blank
701
- // gap above the "Answering..." loader. The bubble is created on the first
702
- // streamed token (or the done event) instead, so the loader stays put
703
- // until real text appears.
704
- const streamingAnswerIndex = mergedQuestions.length;
705
-
706
- let buffer = "";
707
- while (true) {
708
- const { done, value } = await reader.read();
709
- if (done) break;
710
-
711
- buffer += decoder.decode(value, { stream: true });
712
- const parts = buffer.split("\\n");
713
- buffer = parts.pop() ?? "";
714
-
715
- for (const line of parts) {
716
- if (!line.startsWith("data: ")) continue;
717
-
718
- // Guard only the parse: a malformed frame is skipped, while the
719
- // server's error event below must throw past this loop to the
720
- // outer catch so it renders in the chat's error callout instead
721
- // of dying in a parse-error log.
722
- let data;
723
- try {
724
- data = JSON.parse(line.slice(6));
725
- } catch {
726
- console.error("Failed to parse SSE data:", line);
727
- continue;
728
- }
729
-
730
- if (data.type === "metadata") {
731
- const allSources: Source[] = data.data?.sources ?? [];
732
- const seen = new Set<string>();
733
- sources = allSources.filter((s: Source) => {
734
- if (s.score < 0.4 || seen.has(s.uri)) return false;
735
- seen.add(s.uri);
736
- return true;
737
- });
738
- } else if (data.type === "content") {
739
- contentParts.push(data.data);
740
- const streamedContent = contentParts.join("");
741
-
742
- setAnswer((prev) => {
743
- const newAnswers = [...prev];
744
- newAnswers[streamingAnswerIndex] = {
745
- text: streamedContent,
746
- answer: true,
747
- sources,
748
- };
749
- return newAnswers;
750
- });
751
- } else if (data.type === "error") {
752
- throw new Error(data.data);
753
- } else if (data.type === "done") {
754
- const streamedContent = contentParts.join("");
755
- let mdxSource: MDXRemoteSerializeResult | null = null;
756
- try {
757
- mdxSource = await serialize(streamedContent, {
758
- parseFrontmatter: false,
759
- mdxOptions: {
760
- remarkPlugins: [remarkGfm],
761
- rehypePlugins: [rehypeHighlight],
762
- format: "md",
763
- development: false,
764
- },
765
- });
766
- } catch (mdxError: unknown) {
767
- console.error("MDX serialization error:", mdxError);
768
- }
769
-
770
- setAnswer((prev) => {
771
- const newAnswers = [...prev];
772
- newAnswers[streamingAnswerIndex] = {
773
- text: streamedContent,
774
- answer: true,
775
- mdx: mdxSource || undefined,
776
- sources,
777
- };
778
- return newAnswers;
779
- });
780
- }
781
- }
782
- }
783
- } catch (err: unknown) {
784
- if (err instanceof DOMException && err.name === "AbortError") return;
785
- setError(err instanceof Error ? err.message : "Unknown error");
786
- } finally {
787
- abortRef.current = null;
788
- setLoading(false);
789
- }
790
- }
791
-
792
- async function ask(e: React.FormEvent) {
793
- e.preventDefault();
794
- if (loading || question.trim() === "") return;
795
- await runQuestion(question);
796
- }
797
-
798
- // Bridge from the search modal: hand the typed query to the assistant. If a
799
- // response is already streaming (loading), we can't submit yet - open the
800
- // panel and pre-fill the input so the user can send it the moment the
801
- // current answer finishes. Otherwise submit it right away.
802
- function askAssistant(
803
- rawQuestion: string,
804
- returnFocusTo?: HTMLElement | null,
805
- ) {
806
- const trimmed = rawQuestion.trim();
807
- if (trimmed === "") return;
808
- if (loading) {
809
- showChat(returnFocusTo);
810
- setQuestion(trimmed);
811
- } else {
812
- void runQuestion(trimmed, returnFocusTo);
813
- }
814
- }
815
-
816
- function resetChat() {
817
- abortRef.current?.abort();
818
- setLoading(false);
819
- setError(null);
820
- setAnswer([{ text: INITIAL_GREETING, answer: true }]);
821
- }
275
+ const value = useMemo(() => ({ isChatActive }), [isChatActive]);
822
276
 
823
277
  return (
824
- <ChatContext.Provider
825
- value={{
826
- isOpen,
827
- setIsOpen,
828
- toggleChat,
829
- isChatActive,
830
- question,
831
- setQuestion,
832
- loading,
833
- error,
834
- answer,
835
- setAnswer,
836
- ask,
837
- askAssistant,
838
- closeChat,
839
- registerSearchClose,
840
- resetChat,
841
- chatInputRef,
842
- }}
843
- >
844
- {children}
278
+ <ChatContext.Provider value={value}>
279
+ <ChatProvider
280
+ onSend={sendToAssistant}
281
+ shortcut={isChatActive ? "i" : null}
282
+ >
283
+ {children}
284
+ </ChatProvider>
845
285
  </ChatContext.Provider>
846
286
  );
847
287
  };
848
288
 
849
- export { Chat, ChtProvider, ChatContext, ChatButtonCTA };
289
+ export { Chat, ChtProvider, ChatContext };
850
290
  `;