import { useCallback, useEffect, useRef, useState } from 'react' import { ended, reduce, type RunState, starting } from '@/lib/run' import { historyOf } from '@/lib/history' import { ask, AskRefused } from '@/lib/sse' import type { AskEvent, SystemId } from '@/lib/types' /** One question and its answer. A follow-up carries the earlier turns: the server * rewrites it into a standalone question, which the (frozen) system answers. */ export type Turn = { id: number question: string system: SystemId day: string | null // the policy date asked for (null = today) run: RunState lastEventAt: number // for the running step's timer } /** The conversation: send a question (it streams into its own turn), stop the one * running. Events of a turn only ever update that turn, so a stopped or older stream * can never write into the newest answer. */ export function useChat() { const [turns, setTurns] = useState([]) const nextId = useRef(1) const controller = useRef(null) const latest = useRef([]) // the turns as last rendered, for the next history useEffect(() => { latest.current = turns }, [turns]) const update = useCallback((id: number, change: (run: RunState) => RunState) => { setTurns((all) => all.map((t) => (t.id === id ? { ...t, run: change(t.run), lastEventAt: Date.now() } : t))) }, []) const send = useCallback( async (question: string, system: SystemId, day: string | null) => { controller.current?.abort() // one question at a time const history = historyOf(latest.current) // earlier answered turns: follow-ups const id = nextId.current++ const turn: Turn = { id, question, system, day, run: starting(system), lastEventAt: Date.now() } setTurns((all) => [...all, turn]) const c = new AbortController() controller.current = c const onEvent = (event: AskEvent) => update(id, (run) => reduce(run, event)) try { await ask({ question, system, day: day ?? undefined, history }, onEvent, c.signal) update(id, ended) // closed without an answer or error: say so, never spin } catch (error) { const [kind, message] = c.signal.aborted ? ['stopped', 'Stopped.'] : error instanceof AskRefused ? ['refused', error.message] : ['network', 'The connection to the server was lost. Please try again.'] update(id, (run) => reduce(run, { type: 'error', kind, message })) } }, [update], ) const stop = useCallback(() => controller.current?.abort(), []) /** Start over: stop what runs and clear the conversation. */ const clear = useCallback(() => { controller.current?.abort() setTurns([]) }, []) useEffect(() => () => controller.current?.abort(), []) // leaving the page stops the stream const busy = turns.length > 0 && turns[turns.length - 1].run.phase === 'running' return { turns, busy, send, stop, clear } }