-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAIChatPanel.tsx
More file actions
180 lines (168 loc) · 6.62 KB
/
AIChatPanel.tsx
File metadata and controls
180 lines (168 loc) · 6.62 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import { useState, useEffect } from "react";
import { Message, AIChatBox } from "./AIChatBox";
import { trpc } from "@/lib/trpc";
import { cn } from "@/lib/utils";
import { Button } from "./ui/button";
import { Sparkles, X, Mic, Volume2, VolumeX } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { useVoiceChat } from "@/hooks/useVoiceChat";
const AI_NAME = "Homegirl AI";
export function AIChatPanel() {
const [isOpen, setIsOpen] = useState(false);
const [messages, setMessages] = useState<Message[]>([]);
const { isSupported, isListening, transcript, isSpeaking, startListening, stopListening, speak, stopSpeaking, setTranscript } = useVoiceChat();
// Handle dictation input
useEffect(() => {
if (transcript) {
handleSendMessage(transcript);
setTranscript(''); // Clear transcript after sending
}
}, [transcript]);
// Handle AI speaking the response
useEffect(() => {
if (messages.length > 0) {
const lastMessage = messages[messages.length - 1];
if (lastMessage.role === 'assistant' && !isSpeaking) {
speak(lastMessage.content);
}
}
}, [messages, speak, isSpeaking]);
// 1. Fetch history and settings
const historyQuery = trpc.ai.history.useQuery(undefined, {
enabled: isOpen,
refetchOnWindowFocus: false,
onSuccess: (data) => {
// Filter out system messages and map to client Message type
const clientMessages: Message[] = data.map(h => ({
role: h.role as Message["role"],
content: h.content,
}));
setMessages(clientMessages);
}
});
const settingsQuery = trpc.ai.settings.useQuery(undefined, {
refetchOnWindowFocus: false,
});
// 2. Handle chat mutation
const chatMutation = trpc.ai.message.useMutation({
onMutate: (newMessage) => {
// Optimistically add user message
const userMessage: Message = { role: "user", content: newMessage.message };
setMessages(prev => [...prev, userMessage]);
},
onSuccess: (data) => {
// Add assistant response
const assistantMessage: Message = { role: "assistant", content: data.response };
setMessages(prev => [...prev, assistantMessage]);
},
onError: (error) => {
console.error("AI Chat Error:", error);
// Revert optimistic update and show error message
setMessages(prev => prev.slice(0, -1));
setMessages(prev => [...prev, {
role: "assistant",
content: `My bad, girl. Ran into a little drama: ${error.message}. Try again?`,
}]);
}
});
const handleSendMessage = (content: string) => {
if (isSpeaking) stopSpeaking();
chatMutation.mutate({ message: content });
};
// Suggested prompts based on the workflow-focused personality
const suggestedPrompts = [
"What's my schedule look like today?",
"Did any deposits come in?",
"Remind me to order more monomer.",
"What's my VIP score right now?",
"Give me the full system tutorial.",
];
// Determine chat box height based on screen size (for dark-mode aesthetic)
const chatBoxHeight = "70vh";
return (
<>
{/* Floating Bubble */}
<Button
onClick={() => setIsOpen(true)}
className={cn(
"fixed bottom-6 right-6 z-50 rounded-full shadow-lg transition-all duration-300",
isOpen && "scale-0 opacity-0 pointer-events-none"
)}
size="icon"
aria-label="Open AI Chat"
>
<Sparkles className="size-6" />
</Button>
{/* Collapsible Panel */}
<div
className={cn(
"fixed bottom-0 right-0 z-50 transition-all duration-300 ease-in-out",
"w-full sm:w-[400px] md:w-[450px] lg:w-[500px]",
isOpen ? "translate-x-0" : "translate-x-full"
)}
style={{ height: "100vh", maxHeight: "100vh" }}
>
<Card
className={cn(
"flex flex-col h-full rounded-none sm:rounded-tl-lg border-0 sm:border-l sm:border-t shadow-2xl",
"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60" // Maintain dark-mode aesthetic
)}
>
<CardHeader className="flex flex-row items-center justify-between space-y-0 p-4 border-b">
<CardTitle className="text-lg font-bold flex items-center gap-2">
<Sparkles className="size-5 text-primary" />
{AI_NAME}
</CardTitle>
<Button
variant="ghost"
size="icon"
onClick={() => setIsOpen(false)}
aria-label="Close AI Chat"
>
<X className="size-5" />
</Button>
</CardHeader>
<CardContent className="flex-1 p-0">
<AIChatBox
messages={messages}
onSendMessage={handleSendMessage}
isLoading={chatMutation.isPending || historyQuery.isLoading || isListening}
placeholder={`Ask ${AI_NAME} a question...`}
height={chatBoxHeight}
emptyStateMessage={`Hey girl! I'm ${AI_NAME}. I'm here to help you with your workflow. What's the plan for today?`}
suggestedPrompts={suggestedPrompts}
className="h-full border-0 rounded-none"
/>
{isSupported && (
<div className="flex justify-between items-center p-2 border-t">
<Button
variant="ghost"
size="sm"
onClick={isListening ? stopListening : startListening}
className={cn("text-sm", isListening ? "text-red-500 hover:text-red-600" : "text-gray-600 hover:text-pink-600")}
>
<Mic className="w-4 h-4 mr-2" />
{isListening ? "Listening..." : "Dictate"}
</Button>
<Button
variant="ghost"
size="sm"
onClick={isSpeaking ? stopSpeaking : () => {
// Re-speak the last AI message if available
const lastMessage = messages.findLast(m => m.role === 'assistant');
if (lastMessage) speak(lastMessage.content);
}}
className={cn("text-sm", isSpeaking ? "text-pink-600 hover:text-pink-700" : "text-gray-600 hover:text-pink-600")}
disabled={!messages.findLast(m => m.role === 'assistant')}
>
{isSpeaking ? <VolumeX className="w-4 h-4 mr-2" /> : <Volume2 className="w-4 h-4 mr-2" />}
{isSpeaking ? "Stop Voice" : "Read Last"}
</Button>
</div>
)}
</CardContent>
</Card>
</div>
</>
);
}