import { useRef, useState } from "react"; import type { AssistantReply } from "../../services/AssistantService.tsx"; export interface Turn { question: string; reply?: AssistantReply; failed?: boolean; } export interface Conversation { id: number; subject: string; turns: Turn[]; draft: string; asking: boolean; showingTicket: boolean; } let lastId = 0; const fresh = (subject: string): Conversation => ({ id: ++lastId, subject, turns: [], draft: "", asking: false, showingTicket: false }); export interface AssistantConversation { conversation: Conversation; update: (change: (current: Conversation) => Partial, id?: number) => void; isLive: (id: number) => boolean; } // The path, query and hash, which carry any patient or encounter id the route names. export const assistantSubject = ({ pathname, search, hash }: { pathname: string; search: string; hash: string }) => pathname + search + hash; // A new subject replaces the conversation before it paints; a write for a replaced one is dropped. export const useAssistantConversation = (subject: string): AssistantConversation => { const [stored, setStored] = useState(() => fresh(subject)); let conversation = stored; if (stored.subject !== subject) { conversation = fresh(subject); setStored(conversation); } const live = useRef(conversation.id); live.current = conversation.id; const update: AssistantConversation["update"] = (change, id = conversation.id) => setStored((previous) => (previous.id === id ? { ...previous, ...change(previous) } : previous)); return { conversation, update, isLive: (id) => live.current === id }; };