import { useEffect, useSyncExternalStore } from 'react'; export interface AssistantSeed { id: number; prompt?: string; autoSend?: boolean; newChat?: boolean; classId?: string | null; documentIds?: string[]; } interface State { open: boolean; seed: AssistantSeed | null; /** What the user is currently looking at; supplied by pages. */ context: { classId: string | null; documentIds: string[]; label: string }; } let state: State = { open: false, seed: null, context: { classId: null, documentIds: [], label: '' } }; const listeners = new Set<() => void>(); const set = (patch: Partial) => { state = { ...state, ...patch }; listeners.forEach((fn) => fn()); }; let seedId = 0; /** The drawer's conversation, kept while the drawer is closed so reopening continues it. */ let drawerConversation: string | null = null; export const assistant = { /** Opens the assistant, optionally with a prepared prompt. */ open(seed: Omit = {}) { seedId += 1; set({ open: true, seed: { id: seedId, ...seed } }); }, close() { set({ open: false }); }, toggle() { set({ open: !state.open }); }, consumeSeed() { if (state.seed) set({ seed: null }); }, get drawerConversation() { return drawerConversation; }, rememberDrawerConversation(id: string | null) { drawerConversation = id; }, setContext(context: State['context']) { const cur = state.context; if (cur.classId === context.classId && cur.label === context.label && cur.documentIds.join() === context.documentIds.join()) return; set({ context }); }, }; export function useAssistantState(): State { return useSyncExternalStore( (fn) => { listeners.add(fn); return () => listeners.delete(fn); }, () => state, () => state, ); } /** Pages call this so the assistant knows which class or document "this" refers to. */ export function useAssistantContext(classId: string | null | undefined, label = '', documentIds: string[] = []): void { const key = documentIds.join(','); useEffect(() => { assistant.setContext({ classId: classId ?? null, documentIds: key ? key.split(',') : [], label }); return () => assistant.setContext({ classId: null, documentIds: [], label: '' }); }, [classId, label, key]); }