File size: 2,974 Bytes
23d418f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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<Turn[]>([])
  const nextId = useRef(1)
  const controller = useRef<AbortController | null>(null)
  const latest = useRef<Turn[]>([]) // 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 }
}