Files
CatoandClaude 9d5c25a26f feat(chat): run every in-page chat on chatkit's thread and composer (#328)
Seven hand-built chats (/demo, the professional demos, quick-create, /try,
/my-data documents, custom bots and the guided demo) now share one
EmbeddedChat panel: chatkit's ChatThread and Composer with the microphone,
Copy/Listen, Stop, Retry on a failed turn, starters and suggested replies.
Each surface keeps its own prompt, route and persistence through a small
useChatTurns hook.

Also fixes /demo and the /my-data document chat reading the answer from the
wrong level of the jsonSuccess envelope, which showed empty answers.


Claude-Session: https://claude.ai/code/session_019MDtmuMRAXYWNkfowAXVfi

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-15 18:48:44 +01:00

123 lines
3.8 KiB
TypeScript

'use client';
import { useCallback, useRef, useState } from 'react';
import type { EmbeddedChatMessage } from '@/components/chat/EmbeddedChat';
export interface ChatTurnAnswer {
content: string;
sources?: EmbeddedChatMessage['sources'];
/** Suggested next questions, shown as one-tap replies under the answer. */
replies?: readonly string[];
}
export interface ChatHistoryItem {
role: 'user' | 'assistant';
content: string;
}
/** Calls the surface's own route. Throw (or reject) for a failed turn. */
export type AskFn = (
text: string,
history: ChatHistoryItem[],
signal: AbortSignal,
) => Promise<ChatTurnAnswer>;
const newId = () =>
typeof crypto !== 'undefined' && 'randomUUID' in crypto
? crypto.randomUUID()
: `${Date.now()}-${Math.random().toString(36).slice(2)}`;
/**
* The turn loop every in-page chat shares: append the question, ask the
* surface's route, append the answer — or a failed turn chatkit shows with
* Retry. Stop aborts the request. `initial` seeds a welcome message, which is
* never sent back as history.
*/
export function useChatTurns(
ask: AskFn,
{ initial = [], failedText = "Sorry, I couldn't answer that. Please try again." } = {} as {
initial?: EmbeddedChatMessage[];
failedText?: string;
},
) {
const [messages, setMessages] = useState<EmbeddedChatMessage[]>(initial);
const [sending, setSending] = useState(false);
const abortRef = useRef<AbortController | null>(null);
const seedIds = useRef(new Set(initial.map((m) => m.id)));
const run = useCallback(
async (text: string, base: EmbeddedChatMessage[]) => {
const question: EmbeddedChatMessage = { id: newId(), role: 'user', content: text };
const history = base
.filter((m) => !seedIds.current.has(m.id) && !m.failed)
.map((m) => ({ role: m.role, content: m.content }));
setMessages([...base, question]);
setSending(true);
const controller = new AbortController();
abortRef.current = controller;
try {
const answer = await ask(text, history, controller.signal);
if (typeof answer?.content !== 'string' || !answer.content.trim()) {
throw new Error('Empty answer');
}
setMessages((prev) => [
...prev,
{
id: newId(),
role: 'assistant',
content: answer.content,
sources: answer.sources,
replies: answer.replies,
},
]);
} catch (error) {
if (controller.signal.aborted) return;
const message = error instanceof Error && error.message ? error.message : failedText;
setMessages((prev) => [
...prev,
{
id: newId(),
role: 'assistant',
content: failedText,
failed: true,
failure: { message },
},
]);
} finally {
if (abortRef.current === controller) abortRef.current = null;
setSending(false);
}
},
[ask, failedText],
);
const send = useCallback(
(text: string) => {
const trimmed = text.trim();
if (!trimmed || sending) return;
void run(trimmed, messages);
},
[messages, run, sending],
);
/** Re-asks the last question after a failed turn. */
const retry = useCallback(() => {
if (sending) return;
const lastUser = messages.map((m) => m.role).lastIndexOf('user');
if (lastUser < 0) return;
void run(messages[lastUser].content, messages.slice(0, lastUser));
}, [messages, run, sending]);
const stop = useCallback(() => {
abortRef.current?.abort();
}, []);
const reset = useCallback((next: EmbeddedChatMessage[] = []) => {
abortRef.current?.abort();
seedIds.current = new Set(next.map((m) => m.id));
setMessages(next);
}, []);
return { messages, sending, send, retry, stop, reset };
}