File size: 1,736 Bytes
2d93ee9
03e545a
 
2d93ee9
 
03e545a
2d93ee9
03e545a
 
 
2d93ee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03e545a
 
 
 
 
2d93ee9
03e545a
 
 
 
 
 
2d93ee9
 
 
 
 
 
03e545a
 
 
 
2d93ee9
 
 
 
 
 
 
 
 
03e545a
 
 
 
 
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
import { useEffect, useState } from 'react'
import MessageList from './MessageList'
import InputBar from './InputBar'
import SessionList from './SessionList'
import UsernameForm from './UsernameForm'
import '../styles/chat.css'
import { fetchStream, fetchSessions } from '../api'

function ChatWindow() {
  const [messages, setMessages] = useState([])
  const [sessionName] = useState(() => crypto.randomUUID())
  const [sessions, setSessions] = useState([])
  const [username, setUsername] = useState(() =>
    localStorage.getItem('username') || ''
  )

  useEffect(() => {
    if (username) {
      fetchSessions(username).then(setSessions)
    }
  }, [username])

  const refreshSessions = () => {
    if (username) {
      fetchSessions(username).then(setSessions)
    }
  }

  const sendMessage = async (text) => {
    const userMsg = { role: 'user', content: text }
    setMessages((prev) => [...prev, userMsg, { role: 'assistant', content: '' }])
    const index = messages.length + 1
    await fetchStream(username, sessionName, text, (chunk) => {
      setMessages((prev) => {
        const copy = [...prev]
        copy[index] = { ...copy[index], content: copy[index].content + chunk }
        return copy
      })
    })
    refreshSessions()
  }

  const handleUsernameSet = (name) => {
    localStorage.setItem('username', name)
    setUsername(name)
  }

  return (
    <div className="chat-container">
      {!username ? (
        <UsernameForm onSet={handleUsernameSet} />
      ) : (
        <>
          <SessionList sessions={sessions} current={sessionName} />
          <MessageList messages={messages} />
          <InputBar onSend={sendMessage} />
        </>
      )}
    </div>
  )
}

export default ChatWindow