|
| 1 | +import React, { useState } from "react"; |
| 2 | +import { |
| 3 | + useExternalStoreRuntime, |
| 4 | + ThreadMessageLike, |
| 5 | + AppendMessage, |
| 6 | + AssistantRuntimeProvider, |
| 7 | + ExternalStoreThreadListAdapter, |
| 8 | +} from "@assistant-ui/react"; |
| 9 | +import { Thread } from "./assistant-ui/thread"; |
| 10 | +import { ThreadList } from "./assistant-ui/thread-list"; |
| 11 | +import { |
| 12 | + useChatContext, |
| 13 | + MyMessage, |
| 14 | + ThreadData, |
| 15 | + RegularThreadData, |
| 16 | + ArchivedThreadData |
| 17 | +} from "./context/ChatContext"; |
| 18 | +import styled from "styled-components"; |
| 19 | + |
| 20 | +const ChatContainer = styled.div` |
| 21 | + display: flex; |
| 22 | + height: 500px; |
| 23 | +
|
| 24 | + .aui-thread-list-root { |
| 25 | + width: 250px; |
| 26 | + background-color: #fff; |
| 27 | + padding: 10px; |
| 28 | + } |
| 29 | +
|
| 30 | + .aui-thread-root { |
| 31 | + flex: 1; |
| 32 | + background-color: #f9fafb; |
| 33 | + } |
| 34 | +
|
| 35 | + .aui-thread-list-item { |
| 36 | + cursor: pointer; |
| 37 | + transition: background-color 0.2s ease; |
| 38 | +
|
| 39 | + &[data-active="true"] { |
| 40 | + background-color: #dbeafe; |
| 41 | + border: 1px solid #bfdbfe; |
| 42 | + } |
| 43 | + } |
| 44 | +`; |
| 45 | + |
| 46 | +const generateId = () => Math.random().toString(36).substr(2, 9); |
| 47 | + |
| 48 | +const callYourAPI = async (text: string) => { |
| 49 | + // Simulate API delay |
| 50 | + await new Promise(resolve => setTimeout(resolve, 1500)); |
| 51 | + |
| 52 | + // Simple responses |
| 53 | + return { |
| 54 | + content: "This is a mock response from your backend. You typed: " + text |
| 55 | + }; |
| 56 | +}; |
| 57 | + |
| 58 | +export function ChatMain() { |
| 59 | + const { state, actions } = useChatContext(); |
| 60 | + const [isRunning, setIsRunning] = useState(false); |
| 61 | + |
| 62 | + console.log("STATE", state); |
| 63 | + |
| 64 | + // Get messages for current thread |
| 65 | + const currentMessages = actions.getCurrentMessages(); |
| 66 | + |
| 67 | + // Convert custom format to ThreadMessageLike |
| 68 | + const convertMessage = (message: MyMessage): ThreadMessageLike => ({ |
| 69 | + role: message.role, |
| 70 | + content: [{ type: "text", text: message.text }], |
| 71 | + id: message.id, |
| 72 | + createdAt: new Date(message.timestamp), |
| 73 | + }); |
| 74 | + |
| 75 | + const onNew = async (message: AppendMessage) => { |
| 76 | + // Extract text from AppendMessage content array |
| 77 | + if (message.content.length !== 1 || message.content[0]?.type !== "text") { |
| 78 | + throw new Error("Only text content is supported"); |
| 79 | + } |
| 80 | + |
| 81 | + // Add user message in custom format |
| 82 | + const userMessage: MyMessage = { |
| 83 | + id: generateId(), |
| 84 | + role: "user", |
| 85 | + text: message.content[0].text, |
| 86 | + timestamp: Date.now(), |
| 87 | + }; |
| 88 | + |
| 89 | + // Update current thread with new user message |
| 90 | + await actions.addMessage(state.currentThreadId, userMessage); |
| 91 | + setIsRunning(true); |
| 92 | + |
| 93 | + try { |
| 94 | + // Call mock API |
| 95 | + const response = await callYourAPI(userMessage.text); |
| 96 | + |
| 97 | + const assistantMessage: MyMessage = { |
| 98 | + id: generateId(), |
| 99 | + role: "assistant", |
| 100 | + text: response.content, |
| 101 | + timestamp: Date.now(), |
| 102 | + }; |
| 103 | + |
| 104 | + // Update current thread with assistant response |
| 105 | + await actions.addMessage(state.currentThreadId, assistantMessage); |
| 106 | + } catch (error) { |
| 107 | + // Handle errors gracefully |
| 108 | + const errorMessage: MyMessage = { |
| 109 | + id: generateId(), |
| 110 | + role: "assistant", |
| 111 | + text: `Sorry, I encountered an error: ${error instanceof Error ? error.message : 'Unknown error'}`, |
| 112 | + timestamp: Date.now(), |
| 113 | + }; |
| 114 | + |
| 115 | + await actions.addMessage(state.currentThreadId, errorMessage); |
| 116 | + } finally { |
| 117 | + setIsRunning(false); |
| 118 | + } |
| 119 | + }; |
| 120 | + |
| 121 | + // Add onEdit functionality |
| 122 | + const onEdit = async (message: AppendMessage) => { |
| 123 | + // Extract text from AppendMessage content array |
| 124 | + if (message.content.length !== 1 || message.content[0]?.type !== "text") { |
| 125 | + throw new Error("Only text content is supported"); |
| 126 | + } |
| 127 | + |
| 128 | + // Find the index where to insert the edited message |
| 129 | + const index = currentMessages.findIndex((m) => m.id === message.parentId) + 1; |
| 130 | + |
| 131 | + // Keep messages up to the parent |
| 132 | + const newMessages = [...currentMessages.slice(0, index)]; |
| 133 | + |
| 134 | + // Add the edited message in custom format |
| 135 | + const editedMessage: MyMessage = { |
| 136 | + id: generateId(), |
| 137 | + role: "user", |
| 138 | + text: message.content[0].text, |
| 139 | + timestamp: Date.now(), |
| 140 | + }; |
| 141 | + newMessages.push(editedMessage); |
| 142 | + |
| 143 | + // Update messages using the new context action |
| 144 | + await actions.updateMessages(state.currentThreadId, newMessages); |
| 145 | + setIsRunning(true); |
| 146 | + |
| 147 | + try { |
| 148 | + // Generate new response |
| 149 | + const response = await callYourAPI(editedMessage.text); |
| 150 | + |
| 151 | + const assistantMessage: MyMessage = { |
| 152 | + id: generateId(), |
| 153 | + role: "assistant", |
| 154 | + text: response.content, |
| 155 | + timestamp: Date.now(), |
| 156 | + }; |
| 157 | + |
| 158 | + newMessages.push(assistantMessage); |
| 159 | + await actions.updateMessages(state.currentThreadId, newMessages); |
| 160 | + } catch (error) { |
| 161 | + // Handle errors gracefully |
| 162 | + const errorMessage: MyMessage = { |
| 163 | + id: generateId(), |
| 164 | + role: "assistant", |
| 165 | + text: `Sorry, I encountered an error: ${error instanceof Error ? error.message : 'Unknown error'}`, |
| 166 | + timestamp: Date.now(), |
| 167 | + }; |
| 168 | + |
| 169 | + newMessages.push(errorMessage); |
| 170 | + await actions.updateMessages(state.currentThreadId, newMessages); |
| 171 | + } finally { |
| 172 | + setIsRunning(false); |
| 173 | + } |
| 174 | + }; |
| 175 | + |
| 176 | + // Thread list adapter for managing multiple threads |
| 177 | + const threadListAdapter: ExternalStoreThreadListAdapter = { |
| 178 | + threadId: state.currentThreadId, |
| 179 | + threads: state.threadList.filter((t): t is RegularThreadData => t.status === "regular"), |
| 180 | + archivedThreads: state.threadList.filter((t): t is ArchivedThreadData => t.status === "archived"), |
| 181 | + |
| 182 | + onSwitchToNewThread: async () => { |
| 183 | + const threadId = await actions.createThread("New Chat"); |
| 184 | + actions.setCurrentThread(threadId); |
| 185 | + }, |
| 186 | + |
| 187 | + onSwitchToThread: (threadId) => { |
| 188 | + actions.setCurrentThread(threadId); |
| 189 | + }, |
| 190 | + |
| 191 | + onRename: async (threadId, newTitle) => { |
| 192 | + await actions.updateThread(threadId, { title: newTitle }); |
| 193 | + }, |
| 194 | + |
| 195 | + onArchive: async (threadId) => { |
| 196 | + await actions.updateThread(threadId, { status: "archived" }); |
| 197 | + }, |
| 198 | + |
| 199 | + onDelete: async (threadId) => { |
| 200 | + await actions.deleteThread(threadId); |
| 201 | + }, |
| 202 | + }; |
| 203 | + |
| 204 | + const runtime = useExternalStoreRuntime({ |
| 205 | + messages: currentMessages, |
| 206 | + setMessages: (messages) => { |
| 207 | + actions.updateMessages(state.currentThreadId, messages); |
| 208 | + }, |
| 209 | + convertMessage, |
| 210 | + isRunning, |
| 211 | + onNew, |
| 212 | + onEdit, |
| 213 | + adapters: { |
| 214 | + threadList: threadListAdapter, |
| 215 | + }, |
| 216 | + }); |
| 217 | + |
| 218 | + if (!state.isInitialized) { |
| 219 | + return <div>Loading...</div>; |
| 220 | + } |
| 221 | + |
| 222 | + return ( |
| 223 | + <AssistantRuntimeProvider runtime={runtime}> |
| 224 | + <ChatContainer> |
| 225 | + <ThreadList /> |
| 226 | + <Thread /> |
| 227 | + </ChatContainer> |
| 228 | + </AssistantRuntimeProvider> |
| 229 | + ); |
| 230 | +} |
| 231 | + |
0 commit comments