scaling-swarms / frontend /src /hooks /useEmbedChat.ts
tfrere's picture
tfrere HF Staff
Cursor
feat(frontend): browser-only live demo mode
6e392fe
Raw History Blame Contribute Delete
13.2 kB
import { useChat } from "@ai-sdk/react";
import {
DefaultChatTransport,
lastAssistantMessageIsCompleteWithToolCalls,
} from "ai";
import { useCallback, useEffect, useRef, useState } from "react";
import type { UIMessage } from "ai";
import type { EmbedStore } from "../editor/embeds/embed-store";
import type { EmbedDataStore } from "../editor/embeds/embed-data-store";
import type { EmbedVersionStore } from "../editor/embeds/embed-versions";
import {
entriesToMessages,
type EmbedChatStore,
} from "../editor/embeds/embed-history";
import { loadMessages, saveMessages } from "../utils/chat-persistence";
import {
embedStoreWorkspace,
runEmbedTool,
type EmbedMeta,
type EmbedWorkspace,
} from "../editor/embeds/embed-tool-exec";
import { DEMO_MODE } from "../demo/demo-mode";
import { createDemoChatTransport } from "../demo/demo-chat-transport";
export type { EmbedMeta, EmbedWorkspace };
interface UseEmbedChatOptions {
embedStore: EmbedStore | null;
/** Overrides the default embed-store workspace. */
workspace?: EmbedWorkspace | null;
dataStore?: EmbedDataStore | null;
versions?: EmbedVersionStore | null;
/**
* Shared conversation per chart (Yjs). When set, the thread is loaded
* from and saved to it instead of this browser's localStorage.
*/
chats?: EmbedChatStore | null;
/**
* Whether createEmbed({ filename }) may rename the chart. Only charts
* that are not in the article yet get renamed.
*/
allowRename?: boolean;
/** Current embed src key (filename) */
src: string;
modelRef: React.RefObject<string>;
userId: string;
/** Display name stamped on versions. */
authorName?: string;
/**
* Current preview theme (light/dark). Forwarded to the agent so it
* can sanity-check its colour choices and bake theme-aware CSS into
* generated charts (instead of hardcoding axis/text colours that
* only happen to look right under one theme).
*/
isDark?: boolean;
/**
* Called when the agent picks a descriptive filename via createEmbed.
* Parent is expected to update the htmlEmbed node's src attribute in
* the doc and lift the new src into its own state. The hook already
* moves the content and migrates persisted messages and versions.
*/
onRename?: (oldSrc: string, newSrc: string) => void;
/** Title / data source the agent gave the chart (createEmbed). */
onMeta?: (src: string, meta: EmbedMeta) => void;
/** Called after every successful write of the chart HTML. */
onWrite?: (src: string) => void;
}
const transport = DEMO_MODE ? createDemoChatTransport() : new DefaultChatTransport({ api: "/api/embed-chat" });
function scopeKey(src: string): string {
return `embed:${src}`;
}
function lastUserMessageId(messages: UIMessage[]): string | undefined {
for (let i = messages.length - 1; i >= 0; i--) {
if (messages[i].role === "user") return messages[i].id;
}
return undefined;
}
export function useEmbedChat({
embedStore,
workspace: workspaceOverride,
dataStore,
versions,
chats,
allowRename = true,
src,
modelRef,
userId,
authorName,
isDark,
onRename,
onMeta,
onWrite,
}: UseEmbedChatOptions) {
const [input, setInput] = useState("");
// srcRef is the source of truth for the active embed filename. It
// starts from the `src` prop but may change mid-session when the
// agent renames the chart via createEmbed({ filename }). We do NOT
// overwrite it from the prop on every render to avoid clobbering a
// freshly-chosen name before the parent has caught up.
const srcRef = useRef(src);
if (src !== srcRef.current) {
srcRef.current = src;
}
const userIdRef = useRef(userId);
userIdRef.current = userId;
const authorRef = useRef(authorName);
authorRef.current = authorName;
const callbacksRef = useRef({ onRename, onMeta, onWrite });
callbacksRef.current = { onRename, onMeta, onWrite };
const workspace: EmbedWorkspace | null =
workspaceOverride ?? (embedStore ? embedStoreWorkspace(embedStore) : null);
const workspaceRef = useRef(workspace);
workspaceRef.current = workspace;
const versionsRef = useRef(versions ?? null);
versionsRef.current = versions ?? null;
const chatsRef = useRef(chats ?? null);
chatsRef.current = chats ?? null;
const allowRenameRef = useRef(allowRename);
allowRenameRef.current = allowRename;
// Guard: only allow sendAutomaticallyWhen AFTER the user has sent at
// least one message in this session. Prevents auto-send on mount when
// restored messages end with completed tool calls.
const userHasSentRef = useRef(false);
// Track the current theme via ref so getEmbedContext always reads the
// latest value without forcing a callback identity churn on toggle.
const isDarkRef = useRef(!!isDark);
isDarkRef.current = !!isDark;
const messagesRef = useRef<UIMessage[]>([]);
const getEmbedContext = useCallback(() => {
const ws = workspaceRef.current;
if (!ws || !srcRef.current) return {};
const currentSrc = srcRef.current;
const embedHtml = ws.read(currentSrc);
const isBanner = currentSrc === "banner.html";
// A "scratch" file is a newly-created placeholder whose name is a
// hash-based auto-generated slug (see SlashMenu). When the chart is
// still empty under such a name, we explicitly ask the agent to
// pick a descriptive filename on the first createEmbed call.
const isScratch =
!isBanner && !embedHtml && /^d3-chart-[a-z0-9]+\.html$/i.test(currentSrc);
const dataFiles = dataStore
? dataStore.list().map((m) => ({
name: m.name,
ext: m.ext,
size: m.size,
rowCount: m.rowCount,
columns: m.columns,
}))
: [];
return {
embedHtml: embedHtml || undefined,
isBanner,
isScratch,
dataFiles,
theme: isDarkRef.current ? "dark" : "light",
};
}, [dataStore]);
const executeToolCall = useCallback(
(toolCall: { toolName: string; args: unknown; toolCallId: string }) => {
const ws = workspaceRef.current;
if (!ws) return "Embed store not available";
const currentSrc = srcRef.current;
const { output, renamedTo } = runEmbedTool(toolCall.toolName, toolCall.args, {
workspace: ws,
dataStore,
versions: versionsRef.current,
src: currentSrc,
author: authorRef.current,
turnId: lastUserMessageId(messagesRef.current),
allowRename: allowRenameRef.current,
onMeta: (target, meta) => callbacksRef.current.onMeta?.(target, meta),
onWrite: (target) => callbacksRef.current.onWrite?.(target),
});
if (renamedTo) {
chatsRef.current?.rename(currentSrc, renamedTo);
// Migrate persisted chat messages so the localStorage scope
// tracks the new file name.
try {
const uid = userIdRef.current;
const existing = loadMessages(uid, scopeKey(currentSrc));
if (existing && existing.length > 0) {
saveMessages(uid, scopeKey(renamedTo), existing);
}
saveMessages(uid, scopeKey(currentSrc), []);
} catch {
// Non-fatal: persistence is best-effort.
}
srcRef.current = renamedTo;
// Let the parent update the htmlEmbed node's src attribute
// in the ProseMirror doc and lift the new src into state.
callbacksRef.current.onRename?.(currentSrc, renamedTo);
}
return output;
},
[dataStore],
);
const { addToolOutput, setMessages: chatSetMessages, ...chat } = useChat({
transport,
// No initialMessages - we restore via setMessages below to match
// the proven pattern used by the global chat.
sendAutomaticallyWhen(ctx) {
if (!userHasSentRef.current) return false;
return lastAssistantMessageIsCompleteWithToolCalls(ctx);
},
async onToolCall({ toolCall }) {
if (toolCall.dynamic) return;
const result = executeToolCall({
toolName: toolCall.toolName as string,
args: toolCall.input,
toolCallId: toolCall.toolCallId,
});
(addToolOutput as (args: { tool: string; toolCallId: string; output: unknown }) => void)({
tool: toolCall.toolName as string,
toolCallId: toolCall.toolCallId,
output: result,
});
},
onError(error) {
console.error("[embed-chat] error:", error);
},
});
messagesRef.current = chat.messages as UIMessage[];
// --- Restore the conversation on mount ---------------------------------
// Shared thread first; a thread only this browser had (before threads
// were shared) is imported into it once.
const chatSetMessagesRef = useRef(chatSetMessages);
chatSetMessagesRef.current = chatSetMessages;
useEffect(() => {
const key = scopeKey(src);
const store = chatsRef.current;
const local = loadMessages(userId, key);
if (store) {
if (store.list(src).length === 0 && local && local.length > 0) {
store.sync(src, local, authorRef.current);
}
if (local) saveMessages(userId, key, []);
const entries = store.list(src);
if (entries.length > 0) chatSetMessagesRef.current(entriesToMessages(entries));
return;
}
if (local && local.length > 0) chatSetMessagesRef.current(local);
// Only run once on mount (src/userId are stable per keyed instance)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// --- Persistence ----------------------------------------------------------
const persist = useCallback(() => {
const msgs = messagesRef.current as UIMessage[];
const currentSrc = srcRef.current;
const store = chatsRef.current;
if (store) {
if (msgs.length > 0) store.sync(currentSrc, msgs, authorRef.current);
return;
}
saveMessages(userIdRef.current, scopeKey(currentSrc), msgs.length > 0 ? msgs : []);
}, []);
// Save after each completed round (streaming/submitted -> ready)
const prevStatusRef = useRef(chat.status);
useEffect(() => {
const prev = prevStatusRef.current;
const curr = chat.status;
prevStatusRef.current = curr;
const wasActive = prev === "streaming" || prev === "submitted";
if (wasActive && (curr === "ready" || curr === "error") && chat.messages.length > 0) {
persist();
}
}, [chat.status, chat.messages, persist]);
// Save on unmount (covers close-while-streaming)
useEffect(() => () => persist(), [persist]);
// Before the first agent write of a turn, keep the current state as a
// version so "Undo last change" can always go back to it.
const snapshotBaseline = useCallback(() => {
const ws = workspaceRef.current;
const store = versionsRef.current;
const currentSrc = srcRef.current;
if (!ws || !store || !currentSrc) return;
const html = ws.read(currentSrc);
if (!html) return;
const latest = store.latest(currentSrc);
if (!latest || latest.html !== html) {
store.record(currentSrc, html, {
kind: "initial",
author: authorRef.current,
note: latest ? "Edited outside the studio" : "Before the studio",
});
}
}, []);
const requestBody = useCallback(
() => ({ context: getEmbedContext(), model: modelRef.current }),
[getEmbedContext, modelRef],
);
const sendMessage = useCallback(
(content: string) => {
userHasSentRef.current = true;
snapshotBaseline();
chat.sendMessage({ text: content }, { body: requestBody() });
},
[chat, requestBody, snapshotBaseline],
);
/** Re-run the last request (after a network / credits / rate-limit error). */
const retry = useCallback(() => {
userHasSentRef.current = true;
chat.clearError();
const last = messagesRef.current[messagesRef.current.length - 1];
if (last?.role === "assistant") {
void chat.regenerate({ body: requestBody() });
} else if (last?.role === "user") {
// The request failed before any assistant output: resend it.
const text = last.parts
.map((p) => (p.type === "text" ? p.text : ""))
.join("")
.trim();
chatSetMessages(messagesRef.current.slice(0, -1));
if (text) chat.sendMessage({ text }, { body: requestBody() });
}
}, [chat, chatSetMessages, requestBody]);
const isLoading =
chat.status === "streaming" || chat.status === "submitted";
const clearMessages = useCallback(() => {
chatSetMessages([]);
chatsRef.current?.clear(srcRef.current);
saveMessages(userIdRef.current, scopeKey(srcRef.current), []);
}, [chatSetMessages]);
return {
messages: chat.messages as UIMessage[],
isLoading,
error: chat.error,
sendMessage,
retry,
clearMessages,
input,
setInput,
stop: chat.stop,
/** The chart's current file name (follows agent renames immediately). */
currentSrc: () => srcRef.current,
/**
* Imperative setter on the underlying chat. Exposed so dev-only demo
* scripts can inject a fake assistant reply (used to record the demo
* video without waiting for a real LLM round-trip). DO NOT use in
* production code paths.
*/
setMessages: chatSetMessages,
};
}