(frontend): Add zustand library for managing loading state in the application

🔧 (frontend): Refactor navigation.tsx to improve code readability and maintainability
This commit is contained in:
cristhianzl 2025-09-09 21:40:35 -03:00
parent 7499c472fd
commit 2714f89c81
5 changed files with 370 additions and 242 deletions

View file

@ -1,143 +1,176 @@
"use client" "use client";
import Link from "next/link" import { useChat } from "@/contexts/chat-context";
import { usePathname } from "next/navigation" import { cn } from "@/lib/utils";
import { Library, MessageSquare, Settings2, Plus, FileText } from "lucide-react" import {
import { cn } from "@/lib/utils" FileText,
import { useState, useEffect, useRef, useCallback } from "react" Library,
import { useChat } from "@/contexts/chat-context" MessageSquare,
Plus,
Settings2,
} from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useCallback, useEffect, useRef, useState } from "react";
import { EndpointType } from "@/contexts/chat-context" import { EndpointType } from "@/contexts/chat-context";
import { useLoadingStore } from "@/stores/loadingStore";
interface RawConversation { interface RawConversation {
response_id: string response_id: string;
title: string title: string;
endpoint: string endpoint: string;
messages: Array<{ messages: Array<{
role: string role: string;
content: string content: string;
timestamp?: string timestamp?: string;
response_id?: string response_id?: string;
}> }>;
created_at?: string created_at?: string;
last_activity?: string last_activity?: string;
previous_response_id?: string previous_response_id?: string;
total_messages: number total_messages: number;
[key: string]: unknown [key: string]: unknown;
} }
interface ChatConversation { interface ChatConversation {
response_id: string response_id: string;
title: string title: string;
endpoint: EndpointType endpoint: EndpointType;
messages: Array<{ messages: Array<{
role: string role: string;
content: string content: string;
timestamp?: string timestamp?: string;
response_id?: string response_id?: string;
}> }>;
created_at?: string created_at?: string;
last_activity?: string last_activity?: string;
previous_response_id?: string previous_response_id?: string;
total_messages: number total_messages: number;
[key: string]: unknown [key: string]: unknown;
} }
export function Navigation() { export function Navigation() {
const pathname = usePathname() const pathname = usePathname();
const { endpoint, refreshTrigger, loadConversation, currentConversationId, setCurrentConversationId, startNewConversation, conversationDocs, addConversationDoc, refreshConversations, placeholderConversation, setPlaceholderConversation } = useChat() const {
const [conversations, setConversations] = useState<ChatConversation[]>([]) endpoint,
const [loadingConversations, setLoadingConversations] = useState(false) refreshTrigger,
const [previousConversationCount, setPreviousConversationCount] = useState(0) loadConversation,
const fileInputRef = useRef<HTMLInputElement>(null) currentConversationId,
setCurrentConversationId,
startNewConversation,
conversationDocs,
addConversationDoc,
refreshConversations,
placeholderConversation,
setPlaceholderConversation,
} = useChat();
const { loading } = useLoadingStore();
const [conversations, setConversations] = useState<ChatConversation[]>([]);
const [loadingConversations, setLoadingConversations] = useState(false);
const [loadingNewConversation, setLoadingNewConversation] = useState(false);
const [previousConversationCount, setPreviousConversationCount] = useState(0);
const fileInputRef = useRef<HTMLInputElement>(null);
const handleNewConversation = () => { const handleNewConversation = () => {
// Ensure current conversation appears in sidebar before starting a new one setLoadingNewConversation(true);
refreshConversations() refreshConversations();
// Use context helper to fully reset conversation state startNewConversation();
startNewConversation() if (typeof window !== "undefined") {
// Notify chat view even if state was already 'new' window.dispatchEvent(new CustomEvent("newConversation"));
if (typeof window !== 'undefined') {
window.dispatchEvent(new CustomEvent('newConversation'))
} }
} // Clear loading state after a short delay to show the new conversation is created
setTimeout(() => {
setLoadingNewConversation(false);
}, 300);
};
const handleFileUpload = async (file: File) => { const handleFileUpload = async (file: File) => {
console.log("Navigation file upload:", file.name) console.log("Navigation file upload:", file.name);
// Trigger loading start event for chat page // Trigger loading start event for chat page
window.dispatchEvent(new CustomEvent('fileUploadStart', { window.dispatchEvent(
detail: { filename: file.name } new CustomEvent("fileUploadStart", {
})) detail: { filename: file.name },
try {
const formData = new FormData()
formData.append('file', file)
formData.append('endpoint', endpoint)
const response = await fetch('/api/upload_context', {
method: 'POST',
body: formData,
}) })
);
try {
const formData = new FormData();
formData.append("file", file);
formData.append("endpoint", endpoint);
const response = await fetch("/api/upload_context", {
method: "POST",
body: formData,
});
if (!response.ok) { if (!response.ok) {
const errorText = await response.text() const errorText = await response.text();
console.error("Upload failed:", errorText) console.error("Upload failed:", errorText);
// Trigger error event for chat page to handle // Trigger error event for chat page to handle
window.dispatchEvent(new CustomEvent('fileUploadError', { window.dispatchEvent(
detail: { filename: file.name, error: 'Failed to process document' } new CustomEvent("fileUploadError", {
})) detail: {
filename: file.name,
error: "Failed to process document",
},
})
);
// Trigger loading end event // Trigger loading end event
window.dispatchEvent(new CustomEvent('fileUploadComplete')) window.dispatchEvent(new CustomEvent("fileUploadComplete"));
return return;
} }
const result = await response.json() const result = await response.json();
console.log("Upload result:", result) console.log("Upload result:", result);
// Add the file to conversation docs // Add the file to conversation docs
if (result.filename) { if (result.filename) {
addConversationDoc(result.filename) addConversationDoc(result.filename);
} }
// Trigger file upload event for chat page to handle // Trigger file upload event for chat page to handle
window.dispatchEvent(new CustomEvent('fileUploaded', { window.dispatchEvent(
detail: { file, result } new CustomEvent("fileUploaded", {
})) detail: { file, result },
})
);
// Trigger loading end event // Trigger loading end event
window.dispatchEvent(new CustomEvent('fileUploadComplete')) window.dispatchEvent(new CustomEvent("fileUploadComplete"));
} catch (error) { } catch (error) {
console.error('Upload failed:', error) console.error("Upload failed:", error);
// Trigger loading end event even on error // Trigger loading end event even on error
window.dispatchEvent(new CustomEvent('fileUploadComplete')) window.dispatchEvent(new CustomEvent("fileUploadComplete"));
// Trigger error event for chat page to handle // Trigger error event for chat page to handle
window.dispatchEvent(new CustomEvent('fileUploadError', { window.dispatchEvent(
detail: { filename: file.name, error: 'Failed to process document' } new CustomEvent("fileUploadError", {
})) detail: { filename: file.name, error: "Failed to process document" },
})
);
} }
} };
const handleFilePickerClick = () => { const handleFilePickerClick = () => {
fileInputRef.current?.click() fileInputRef.current?.click();
} };
const handleFilePickerChange = (e: React.ChangeEvent<HTMLInputElement>) => { const handleFilePickerChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.target.files const files = e.target.files;
if (files && files.length > 0) { if (files && files.length > 0) {
handleFileUpload(files[0]) handleFileUpload(files[0]);
} }
// Reset the input so the same file can be selected again // Reset the input so the same file can be selected again
if (fileInputRef.current) { if (fileInputRef.current) {
fileInputRef.current.value = '' fileInputRef.current.value = "";
} }
} };
const routes = [ const routes = [
{ {
@ -158,99 +191,123 @@ export function Navigation() {
href: "/settings", href: "/settings",
active: pathname === "/settings", active: pathname === "/settings",
}, },
] ];
const isOnChatPage = pathname === "/" || pathname === "/chat" const isOnChatPage = pathname === "/" || pathname === "/chat";
const createDefaultPlaceholder = useCallback(() => { const createDefaultPlaceholder = useCallback(() => {
return { return {
response_id: 'new-conversation-' + Date.now(), response_id: "new-conversation-" + Date.now(),
title: 'New conversation', title: "New conversation",
endpoint: endpoint, endpoint: endpoint,
messages: [{ messages: [
role: 'assistant', {
content: 'How can I assist?', role: "assistant",
timestamp: new Date().toISOString() content: "How can I assist?",
}], timestamp: new Date().toISOString(),
},
],
created_at: new Date().toISOString(), created_at: new Date().toISOString(),
last_activity: new Date().toISOString(), last_activity: new Date().toISOString(),
total_messages: 1 total_messages: 1,
} as ChatConversation } as ChatConversation;
}, [endpoint]) }, [endpoint]);
const fetchConversations = useCallback(async () => { const fetchConversations = useCallback(async () => {
setLoadingConversations(true) setLoadingConversations(true);
try { try {
// Fetch from the selected endpoint only // Fetch from the selected endpoint only
const apiEndpoint = endpoint === 'chat' ? '/api/chat/history' : '/api/langflow/history' const apiEndpoint =
endpoint === "chat" ? "/api/chat/history" : "/api/langflow/history";
const response = await fetch(apiEndpoint)
const response = await fetch(apiEndpoint);
if (response.ok) { if (response.ok) {
const history = await response.json() const history = await response.json();
const rawConversations = history.conversations || [] const rawConversations = history.conversations || [];
// Cast conversations to proper type and ensure endpoint is correct // Cast conversations to proper type and ensure endpoint is correct
const conversations: ChatConversation[] = rawConversations.map((conv: RawConversation) => ({ const conversations: ChatConversation[] = rawConversations.map(
...conv, (conv: RawConversation) => ({
endpoint: conv.endpoint as EndpointType ...conv,
})) endpoint: conv.endpoint as EndpointType,
})
);
// Sort conversations by last activity (most recent first) // Sort conversations by last activity (most recent first)
conversations.sort((a: ChatConversation, b: ChatConversation) => { conversations.sort((a: ChatConversation, b: ChatConversation) => {
const aTime = new Date(a.last_activity || a.created_at || 0).getTime() const aTime = new Date(
const bTime = new Date(b.last_activity || b.created_at || 0).getTime() a.last_activity || a.created_at || 0
return bTime - aTime ).getTime();
}) const bTime = new Date(
b.last_activity || b.created_at || 0
setConversations(conversations) ).getTime();
return bTime - aTime;
});
setConversations(conversations);
// If no conversations exist and no placeholder is shown, create a default placeholder // If no conversations exist and no placeholder is shown, create a default placeholder
if (conversations.length === 0 && !placeholderConversation) { if (conversations.length === 0 && !placeholderConversation) {
setPlaceholderConversation(createDefaultPlaceholder()) setPlaceholderConversation(createDefaultPlaceholder());
} }
} else { } else {
setConversations([]) setConversations([]);
// Also create placeholder when request fails and no conversations exist // Also create placeholder when request fails and no conversations exist
if (!placeholderConversation) { if (!placeholderConversation) {
setPlaceholderConversation(createDefaultPlaceholder()) setPlaceholderConversation(createDefaultPlaceholder());
} }
} }
// Conversation documents are now managed in chat context // Conversation documents are now managed in chat context
} catch (error) { } catch (error) {
console.error(`Failed to fetch ${endpoint} conversations:`, error) console.error(`Failed to fetch ${endpoint} conversations:`, error);
setConversations([]) setConversations([]);
} finally { } finally {
setLoadingConversations(false) setLoadingConversations(false);
} }
}, [endpoint, placeholderConversation, setPlaceholderConversation, createDefaultPlaceholder]) }, [
endpoint,
placeholderConversation,
setPlaceholderConversation,
createDefaultPlaceholder,
]);
// Fetch chat conversations when on chat page, endpoint changes, or refresh is triggered // Fetch chat conversations when on chat page, endpoint changes, or refresh is triggered
useEffect(() => { useEffect(() => {
if (isOnChatPage) { if (isOnChatPage) {
fetchConversations() fetchConversations();
} }
}, [isOnChatPage, endpoint, refreshTrigger, fetchConversations]) }, [isOnChatPage, endpoint, refreshTrigger, fetchConversations]);
// Clear placeholder when conversation count increases (new conversation was created) // Clear placeholder when conversation count increases (new conversation was created)
useEffect(() => { useEffect(() => {
const currentCount = conversations.length const currentCount = conversations.length;
// If we had a placeholder and the conversation count increased, clear the placeholder and highlight the new conversation // If we had a placeholder and the conversation count increased, clear the placeholder and highlight the new conversation
if (placeholderConversation && currentCount > previousConversationCount && conversations.length > 0) { if (
setPlaceholderConversation(null) placeholderConversation &&
currentCount > previousConversationCount &&
conversations.length > 0
) {
setPlaceholderConversation(null);
// Highlight the most recent conversation (first in sorted array) without loading its messages // Highlight the most recent conversation (first in sorted array) without loading its messages
const newestConversation = conversations[0] const newestConversation = conversations[0];
if (newestConversation) { if (newestConversation) {
setCurrentConversationId(newestConversation.response_id) setCurrentConversationId(newestConversation.response_id);
} }
} }
// Update the previous count // Update the previous count
setPreviousConversationCount(currentCount) setPreviousConversationCount(currentCount);
}, [conversations.length, placeholderConversation, setPlaceholderConversation, previousConversationCount, conversations, setCurrentConversationId]) }, [
conversations.length,
placeholderConversation,
setPlaceholderConversation,
previousConversationCount,
conversations,
setCurrentConversationId,
]);
return ( return (
<div className="space-y-4 py-4 flex flex-col h-full bg-background"> <div className="space-y-4 py-4 flex flex-col h-full bg-background">
@ -262,13 +319,20 @@ export function Navigation() {
href={route.href} href={route.href}
className={cn( className={cn(
"text-sm group flex p-3 w-full justify-start font-medium cursor-pointer hover:bg-accent hover:text-accent-foreground rounded-lg transition-all", "text-sm group flex p-3 w-full justify-start font-medium cursor-pointer hover:bg-accent hover:text-accent-foreground rounded-lg transition-all",
route.active route.active
? "bg-accent text-accent-foreground shadow-sm" ? "bg-accent text-accent-foreground shadow-sm"
: "text-foreground hover:text-accent-foreground", : "text-foreground hover:text-accent-foreground"
)} )}
> >
<div className="flex items-center flex-1"> <div className="flex items-center flex-1">
<route.icon className={cn("h-4 w-4 mr-3 shrink-0", route.active ? "text-accent-foreground" : "text-muted-foreground group-hover:text-foreground")} /> <route.icon
className={cn(
"h-4 w-4 mr-3 shrink-0",
route.active
? "text-accent-foreground"
: "text-muted-foreground group-hover:text-foreground"
)}
/>
{route.label} {route.label}
</div> </div>
</Link> </Link>
@ -286,22 +350,27 @@ export function Navigation() {
{/* Conversations Section */} {/* Conversations Section */}
<div className="px-3 flex-shrink-0"> <div className="px-3 flex-shrink-0">
<div className="flex items-center justify-between mb-3"> <div className="flex items-center justify-between mb-3">
<h3 className="text-sm font-medium text-muted-foreground">Conversations</h3> <h3 className="text-sm font-medium text-muted-foreground">
<button Conversations
</h3>
<button
className="p-1 hover:bg-accent rounded" className="p-1 hover:bg-accent rounded"
onClick={handleNewConversation} onClick={handleNewConversation}
title="Start new conversation" title="Start new conversation"
disabled={loading}
> >
<Plus className="h-4 w-4 text-muted-foreground" /> <Plus className="h-4 w-4 text-muted-foreground" />
</button> </button>
</div> </div>
</div> </div>
<div className="px-3 flex-1 min-h-0 flex flex-col"> <div className="px-3 flex-1 min-h-0 flex flex-col">
{/* Conversations List - grows naturally, doesn't fill all space */} {/* Conversations List - grows naturally, doesn't fill all space */}
<div className="flex-shrink-0 overflow-y-auto scrollbar-hide space-y-1 max-h-full"> <div className="flex-shrink-0 overflow-y-auto scrollbar-hide space-y-1 max-h-full">
{loadingConversations ? ( {loadingNewConversation ? (
<div className="text-sm text-muted-foreground p-2">Loading...</div> <div className="text-sm text-muted-foreground p-2">
Loading...
</div>
) : ( ) : (
<> <>
{/* Show placeholder conversation if it exists */} {/* Show placeholder conversation if it exists */}
@ -310,8 +379,8 @@ export function Navigation() {
className="p-2 rounded-lg bg-accent/50 border border-dashed border-accent cursor-pointer group" className="p-2 rounded-lg bg-accent/50 border border-dashed border-accent cursor-pointer group"
onClick={() => { onClick={() => {
// Don't load placeholder as a real conversation, just focus the input // Don't load placeholder as a real conversation, just focus the input
if (typeof window !== 'undefined') { if (typeof window !== "undefined") {
window.dispatchEvent(new CustomEvent('focusInput')) window.dispatchEvent(new CustomEvent("focusInput"));
} }
}} }}
> >
@ -323,19 +392,29 @@ export function Navigation() {
</div> </div>
</div> </div>
)} )}
{/* Show regular conversations */} {/* Show regular conversations */}
{conversations.length === 0 && !placeholderConversation ? ( {conversations.length === 0 && !placeholderConversation ? (
<div className="text-sm text-muted-foreground p-2">No conversations yet</div> <div className="text-sm text-muted-foreground p-2">
No conversations yet
</div>
) : ( ) : (
conversations.map((conversation) => ( conversations.map((conversation) => (
<div <div
key={conversation.response_id} key={conversation.response_id}
className={`p-2 rounded-lg hover:bg-accent cursor-pointer group ${ className={`p-2 rounded-lg group ${
currentConversationId === conversation.response_id ? 'bg-accent' : '' loading
? "opacity-50 cursor-not-allowed"
: "hover:bg-accent cursor-pointer"
} ${
currentConversationId === conversation.response_id
? "bg-accent"
: ""
}`} }`}
onClick={() => { onClick={() => {
loadConversation(conversation) if (loading) return;
loadConversation(conversation);
refreshConversations();
}} }}
> >
<div className="text-sm font-medium text-foreground mb-1 truncate"> <div className="text-sm font-medium text-foreground mb-1 truncate">
@ -346,7 +425,9 @@ export function Navigation() {
</div> </div>
{conversation.last_activity && ( {conversation.last_activity && (
<div className="text-xs text-muted-foreground"> <div className="text-xs text-muted-foreground">
{new Date(conversation.last_activity).toLocaleDateString()} {new Date(
conversation.last_activity
).toLocaleDateString()}
</div> </div>
)} )}
</div> </div>
@ -359,10 +440,13 @@ export function Navigation() {
{/* Conversation Knowledge Section - appears right after last conversation */} {/* Conversation Knowledge Section - appears right after last conversation */}
<div className="flex-shrink-0 mt-4"> <div className="flex-shrink-0 mt-4">
<div className="flex items-center justify-between mb-3"> <div className="flex items-center justify-between mb-3">
<h3 className="text-sm font-medium text-muted-foreground">Conversation knowledge</h3> <h3 className="text-sm font-medium text-muted-foreground">
<button Conversation knowledge
</h3>
<button
onClick={handleFilePickerClick} onClick={handleFilePickerClick}
className="p-1 hover:bg-accent rounded" className="p-1 hover:bg-accent rounded"
disabled={loading}
> >
<Plus className="h-4 w-4 text-muted-foreground" /> <Plus className="h-4 w-4 text-muted-foreground" />
</button> </button>
@ -376,7 +460,9 @@ export function Navigation() {
/> />
<div className="overflow-y-auto scrollbar-hide space-y-1 max-h-40"> <div className="overflow-y-auto scrollbar-hide space-y-1 max-h-40">
{conversationDocs.length === 0 ? ( {conversationDocs.length === 0 ? (
<div className="text-sm text-muted-foreground p-2">No documents yet</div> <div className="text-sm text-muted-foreground p-2">
No documents yet
</div>
) : ( ) : (
conversationDocs.map((doc, index) => ( conversationDocs.map((doc, index) => (
<div <div
@ -398,5 +484,5 @@ export function Navigation() {
</div> </div>
)} )}
</div> </div>
) );
} }

View file

@ -37,7 +37,8 @@
"react-icons": "^5.5.0", "react-icons": "^5.5.0",
"sonner": "^2.0.6", "sonner": "^2.0.6",
"tailwind-merge": "^3.3.1", "tailwind-merge": "^3.3.1",
"tailwindcss-animate": "^1.0.7" "tailwindcss-animate": "^1.0.7",
"zustand": "^5.0.8"
}, },
"devDependencies": { "devDependencies": {
"@eslint/eslintrc": "^3", "@eslint/eslintrc": "^3",
@ -8267,6 +8268,34 @@
"funding": { "funding": {
"url": "https://github.com/sponsors/sindresorhus" "url": "https://github.com/sponsors/sindresorhus"
} }
},
"node_modules/zustand": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.8.tgz",
"integrity": "sha512-gyPKpIaxY9XcO2vSMrLbiER7QMAMGOQZVRdJ6Zi782jkbzZygq5GI9nG8g+sMgitRtndwaBSl7uiqC49o1SSiw==",
"engines": {
"node": ">=12.20.0"
},
"peerDependencies": {
"@types/react": ">=18.0.0",
"immer": ">=9.0.6",
"react": ">=18.0.0",
"use-sync-external-store": ">=1.2.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"immer": {
"optional": true
},
"react": {
"optional": true
},
"use-sync-external-store": {
"optional": true
}
}
} }
} }
} }

View file

@ -38,7 +38,8 @@
"react-icons": "^5.5.0", "react-icons": "^5.5.0",
"sonner": "^2.0.6", "sonner": "^2.0.6",
"tailwind-merge": "^3.3.1", "tailwind-merge": "^3.3.1",
"tailwindcss-animate": "^1.0.7" "tailwindcss-animate": "^1.0.7",
"zustand": "^5.0.8"
}, },
"devDependencies": { "devDependencies": {
"@eslint/eslintrc": "^3", "@eslint/eslintrc": "^3",

View file

@ -1,5 +1,12 @@
"use client"; "use client";
import { ProtectedRoute } from "@/components/protected-route";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { useAuth } from "@/contexts/auth-context";
import { type EndpointType, useChat } from "@/contexts/chat-context";
import { useKnowledgeFilter } from "@/contexts/knowledge-filter-context";
import { useTask } from "@/contexts/task-context";
import { import {
AtSign, AtSign,
Bot, Bot,
@ -15,14 +22,8 @@ import {
Zap, Zap,
} from "lucide-react"; } from "lucide-react";
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import { ProtectedRoute } from "@/components/protected-route";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { useAuth } from "@/contexts/auth-context";
import { type EndpointType, useChat } from "@/contexts/chat-context";
import { useKnowledgeFilter } from "@/contexts/knowledge-filter-context";
import { useTask } from "@/contexts/task-context";
import { useGetNudgesQuery } from "../api/queries/useGetNudgesQuery"; import { useGetNudgesQuery } from "../api/queries/useGetNudgesQuery";
import { useLoadingStore } from "@/stores/loadingStore";
import Nudges from "./nudges"; import Nudges from "./nudges";
interface Message { interface Message {
@ -106,7 +107,7 @@ function ChatPage() {
}, },
]); ]);
const [input, setInput] = useState(""); const [input, setInput] = useState("");
const [loading, setLoading] = useState(false); const { loading, setLoading } = useLoadingStore();
const [asyncMode, setAsyncMode] = useState(true); const [asyncMode, setAsyncMode] = useState(true);
const [streamingMessage, setStreamingMessage] = useState<{ const [streamingMessage, setStreamingMessage] = useState<{
content: string; content: string;
@ -192,7 +193,7 @@ function ChatPage() {
"Upload failed with status:", "Upload failed with status:",
response.status, response.status,
"Response:", "Response:",
errorText, errorText
); );
throw new Error("Failed to process document"); throw new Error("Failed to process document");
} }
@ -446,7 +447,7 @@ function ChatPage() {
console.log( console.log(
"Loading conversation with", "Loading conversation with",
conversationData.messages.length, conversationData.messages.length,
"messages", "messages"
); );
// Convert backend message format to frontend Message interface // Convert backend message format to frontend Message interface
const convertedMessages: Message[] = conversationData.messages.map( const convertedMessages: Message[] = conversationData.messages.map(
@ -574,7 +575,7 @@ function ChatPage() {
) === "string" ) === "string"
? toolCall.function?.arguments || toolCall.arguments ? toolCall.function?.arguments || toolCall.arguments
: JSON.stringify( : JSON.stringify(
toolCall.function?.arguments || toolCall.arguments, toolCall.function?.arguments || toolCall.arguments
), ),
result: toolCall.result, result: toolCall.result,
status: "completed", status: "completed",
@ -593,7 +594,7 @@ function ChatPage() {
} }
return message; return message;
}, }
); );
setMessages(convertedMessages); setMessages(convertedMessages);
@ -682,7 +683,7 @@ function ChatPage() {
console.log( console.log(
"Chat page received file upload error event:", "Chat page received file upload error event:",
filename, filename,
error, error
); );
// Replace the last message with error message // Replace the last message with error message
@ -696,37 +697,37 @@ function ChatPage() {
window.addEventListener( window.addEventListener(
"fileUploadStart", "fileUploadStart",
handleFileUploadStart as EventListener, handleFileUploadStart as EventListener
); );
window.addEventListener( window.addEventListener(
"fileUploaded", "fileUploaded",
handleFileUploaded as EventListener, handleFileUploaded as EventListener
); );
window.addEventListener( window.addEventListener(
"fileUploadComplete", "fileUploadComplete",
handleFileUploadComplete as EventListener, handleFileUploadComplete as EventListener
); );
window.addEventListener( window.addEventListener(
"fileUploadError", "fileUploadError",
handleFileUploadError as EventListener, handleFileUploadError as EventListener
); );
return () => { return () => {
window.removeEventListener( window.removeEventListener(
"fileUploadStart", "fileUploadStart",
handleFileUploadStart as EventListener, handleFileUploadStart as EventListener
); );
window.removeEventListener( window.removeEventListener(
"fileUploaded", "fileUploaded",
handleFileUploaded as EventListener, handleFileUploaded as EventListener
); );
window.removeEventListener( window.removeEventListener(
"fileUploadComplete", "fileUploadComplete",
handleFileUploadComplete as EventListener, handleFileUploadComplete as EventListener
); );
window.removeEventListener( window.removeEventListener(
"fileUploadError", "fileUploadError",
handleFileUploadError as EventListener, handleFileUploadError as EventListener
); );
}; };
}, [endpoint, setPreviousResponseIds]); }, [endpoint, setPreviousResponseIds]);
@ -753,7 +754,7 @@ function ChatPage() {
}, [isFilterDropdownOpen]); }, [isFilterDropdownOpen]);
const { data: nudges = [], cancel: cancelNudges } = useGetNudgesQuery( const { data: nudges = [], cancel: cancelNudges } = useGetNudgesQuery(
previousResponseIds[endpoint], previousResponseIds[endpoint]
); );
const handleSSEStream = async (userMessage: Message) => { const handleSSEStream = async (userMessage: Message) => {
@ -858,7 +859,7 @@ function ChatPage() {
console.log( console.log(
"Received chunk:", "Received chunk:",
chunk.type || chunk.object, chunk.type || chunk.object,
chunk, chunk
); );
// Extract response ID if present // Extract response ID if present
@ -874,14 +875,14 @@ function ChatPage() {
if (chunk.delta.function_call) { if (chunk.delta.function_call) {
console.log( console.log(
"Function call in delta:", "Function call in delta:",
chunk.delta.function_call, chunk.delta.function_call
); );
// Check if this is a new function call // Check if this is a new function call
if (chunk.delta.function_call.name) { if (chunk.delta.function_call.name) {
console.log( console.log(
"New function call:", "New function call:",
chunk.delta.function_call.name, chunk.delta.function_call.name
); );
const functionCall: FunctionCall = { const functionCall: FunctionCall = {
name: chunk.delta.function_call.name, name: chunk.delta.function_call.name,
@ -897,7 +898,7 @@ function ChatPage() {
else if (chunk.delta.function_call.arguments) { else if (chunk.delta.function_call.arguments) {
console.log( console.log(
"Function call arguments delta:", "Function call arguments delta:",
chunk.delta.function_call.arguments, chunk.delta.function_call.arguments
); );
const lastFunctionCall = const lastFunctionCall =
currentFunctionCalls[currentFunctionCalls.length - 1]; currentFunctionCalls[currentFunctionCalls.length - 1];
@ -909,14 +910,14 @@ function ChatPage() {
chunk.delta.function_call.arguments; chunk.delta.function_call.arguments;
console.log( console.log(
"Accumulated arguments:", "Accumulated arguments:",
lastFunctionCall.argumentsString, lastFunctionCall.argumentsString
); );
// Try to parse arguments if they look complete // Try to parse arguments if they look complete
if (lastFunctionCall.argumentsString.includes("}")) { if (lastFunctionCall.argumentsString.includes("}")) {
try { try {
const parsed = JSON.parse( const parsed = JSON.parse(
lastFunctionCall.argumentsString, lastFunctionCall.argumentsString
); );
lastFunctionCall.arguments = parsed; lastFunctionCall.arguments = parsed;
lastFunctionCall.status = "completed"; lastFunctionCall.status = "completed";
@ -924,7 +925,7 @@ function ChatPage() {
} catch (e) { } catch (e) {
console.log( console.log(
"Arguments not yet complete or invalid JSON:", "Arguments not yet complete or invalid JSON:",
e, e
); );
} }
} }
@ -957,7 +958,7 @@ function ChatPage() {
else if (toolCall.function.arguments) { else if (toolCall.function.arguments) {
console.log( console.log(
"Tool call arguments delta:", "Tool call arguments delta:",
toolCall.function.arguments, toolCall.function.arguments
); );
const lastFunctionCall = const lastFunctionCall =
currentFunctionCalls[ currentFunctionCalls[
@ -971,7 +972,7 @@ function ChatPage() {
toolCall.function.arguments; toolCall.function.arguments;
console.log( console.log(
"Accumulated tool arguments:", "Accumulated tool arguments:",
lastFunctionCall.argumentsString, lastFunctionCall.argumentsString
); );
// Try to parse arguments if they look complete // Try to parse arguments if they look complete
@ -980,7 +981,7 @@ function ChatPage() {
) { ) {
try { try {
const parsed = JSON.parse( const parsed = JSON.parse(
lastFunctionCall.argumentsString, lastFunctionCall.argumentsString
); );
lastFunctionCall.arguments = parsed; lastFunctionCall.arguments = parsed;
lastFunctionCall.status = "completed"; lastFunctionCall.status = "completed";
@ -988,7 +989,7 @@ function ChatPage() {
} catch (e) { } catch (e) {
console.log( console.log(
"Tool arguments not yet complete or invalid JSON:", "Tool arguments not yet complete or invalid JSON:",
e, e
); );
} }
} }
@ -1020,7 +1021,7 @@ function ChatPage() {
console.log( console.log(
"Error parsing function call on finish:", "Error parsing function call on finish:",
fc, fc,
e, e
); );
} }
} }
@ -1036,12 +1037,12 @@ function ChatPage() {
console.log( console.log(
"🟢 CREATING function call (added):", "🟢 CREATING function call (added):",
chunk.item.id, chunk.item.id,
chunk.item.tool_name || chunk.item.name, chunk.item.tool_name || chunk.item.name
); );
// Try to find an existing pending call to update (created by earlier deltas) // Try to find an existing pending call to update (created by earlier deltas)
let existing = currentFunctionCalls.find( let existing = currentFunctionCalls.find(
(fc) => fc.id === chunk.item.id, (fc) => fc.id === chunk.item.id
); );
if (!existing) { if (!existing) {
existing = [...currentFunctionCalls] existing = [...currentFunctionCalls]
@ -1050,7 +1051,7 @@ function ChatPage() {
(fc) => (fc) =>
fc.status === "pending" && fc.status === "pending" &&
!fc.id && !fc.id &&
fc.name === (chunk.item.tool_name || chunk.item.name), fc.name === (chunk.item.tool_name || chunk.item.name)
); );
} }
@ -1063,7 +1064,7 @@ function ChatPage() {
chunk.item.inputs || existing.arguments; chunk.item.inputs || existing.arguments;
console.log( console.log(
"🟢 UPDATED existing pending function call with id:", "🟢 UPDATED existing pending function call with id:",
existing.id, existing.id
); );
} else { } else {
const functionCall: FunctionCall = { const functionCall: FunctionCall = {
@ -1081,7 +1082,7 @@ function ChatPage() {
currentFunctionCalls.map((fc) => ({ currentFunctionCalls.map((fc) => ({
id: fc.id, id: fc.id,
name: fc.name, name: fc.name,
})), }))
); );
} }
} }
@ -1092,7 +1093,7 @@ function ChatPage() {
) { ) {
console.log( console.log(
"Function args delta (Realtime API):", "Function args delta (Realtime API):",
chunk.delta, chunk.delta
); );
const lastFunctionCall = const lastFunctionCall =
currentFunctionCalls[currentFunctionCalls.length - 1]; currentFunctionCalls[currentFunctionCalls.length - 1];
@ -1103,7 +1104,7 @@ function ChatPage() {
lastFunctionCall.argumentsString += chunk.delta || ""; lastFunctionCall.argumentsString += chunk.delta || "";
console.log( console.log(
"Accumulated arguments (Realtime API):", "Accumulated arguments (Realtime API):",
lastFunctionCall.argumentsString, lastFunctionCall.argumentsString
); );
} }
} }
@ -1114,26 +1115,26 @@ function ChatPage() {
) { ) {
console.log( console.log(
"Function args done (Realtime API):", "Function args done (Realtime API):",
chunk.arguments, chunk.arguments
); );
const lastFunctionCall = const lastFunctionCall =
currentFunctionCalls[currentFunctionCalls.length - 1]; currentFunctionCalls[currentFunctionCalls.length - 1];
if (lastFunctionCall) { if (lastFunctionCall) {
try { try {
lastFunctionCall.arguments = JSON.parse( lastFunctionCall.arguments = JSON.parse(
chunk.arguments || "{}", chunk.arguments || "{}"
); );
lastFunctionCall.status = "completed"; lastFunctionCall.status = "completed";
console.log( console.log(
"Parsed function arguments (Realtime API):", "Parsed function arguments (Realtime API):",
lastFunctionCall.arguments, lastFunctionCall.arguments
); );
} catch (e) { } catch (e) {
lastFunctionCall.arguments = { raw: chunk.arguments }; lastFunctionCall.arguments = { raw: chunk.arguments };
lastFunctionCall.status = "error"; lastFunctionCall.status = "error";
console.log( console.log(
"Error parsing function arguments (Realtime API):", "Error parsing function arguments (Realtime API):",
e, e
); );
} }
} }
@ -1147,14 +1148,14 @@ function ChatPage() {
console.log( console.log(
"🔵 UPDATING function call (done):", "🔵 UPDATING function call (done):",
chunk.item.id, chunk.item.id,
chunk.item.tool_name || chunk.item.name, chunk.item.tool_name || chunk.item.name
); );
console.log( console.log(
"🔵 Looking for existing function calls:", "🔵 Looking for existing function calls:",
currentFunctionCalls.map((fc) => ({ currentFunctionCalls.map((fc) => ({
id: fc.id, id: fc.id,
name: fc.name, name: fc.name,
})), }))
); );
// Find existing function call by ID or name // Find existing function call by ID or name
@ -1162,14 +1163,14 @@ function ChatPage() {
(fc) => (fc) =>
fc.id === chunk.item.id || fc.id === chunk.item.id ||
fc.name === chunk.item.tool_name || fc.name === chunk.item.tool_name ||
fc.name === chunk.item.name, fc.name === chunk.item.name
); );
if (functionCall) { if (functionCall) {
console.log( console.log(
"🔵 FOUND existing function call, updating:", "🔵 FOUND existing function call, updating:",
functionCall.id, functionCall.id,
functionCall.name, functionCall.name
); );
// Update existing function call with completion data // Update existing function call with completion data
functionCall.status = functionCall.status =
@ -1192,7 +1193,7 @@ function ChatPage() {
"🔴 WARNING: Could not find existing function call to update:", "🔴 WARNING: Could not find existing function call to update:",
chunk.item.id, chunk.item.id,
chunk.item.tool_name, chunk.item.tool_name,
chunk.item.name, chunk.item.name
); );
} }
} }
@ -1213,7 +1214,7 @@ function ChatPage() {
fc.name === chunk.item.name || fc.name === chunk.item.name ||
fc.name === chunk.item.type || fc.name === chunk.item.type ||
fc.name.includes(chunk.item.type.replace("_call", "")) || fc.name.includes(chunk.item.type.replace("_call", "")) ||
chunk.item.type.includes(fc.name), chunk.item.type.includes(fc.name)
); );
if (functionCall) { if (functionCall) {
@ -1257,12 +1258,12 @@ function ChatPage() {
"🟡 CREATING tool call (added):", "🟡 CREATING tool call (added):",
chunk.item.id, chunk.item.id,
chunk.item.tool_name || chunk.item.name, chunk.item.tool_name || chunk.item.name,
chunk.item.type, chunk.item.type
); );
// Dedupe by id or pending with same name // Dedupe by id or pending with same name
let existing = currentFunctionCalls.find( let existing = currentFunctionCalls.find(
(fc) => fc.id === chunk.item.id, (fc) => fc.id === chunk.item.id
); );
if (!existing) { if (!existing) {
existing = [...currentFunctionCalls] existing = [...currentFunctionCalls]
@ -1274,7 +1275,7 @@ function ChatPage() {
fc.name === fc.name ===
(chunk.item.tool_name || (chunk.item.tool_name ||
chunk.item.name || chunk.item.name ||
chunk.item.type), chunk.item.type)
); );
} }
@ -1290,7 +1291,7 @@ function ChatPage() {
chunk.item.inputs || existing.arguments; chunk.item.inputs || existing.arguments;
console.log( console.log(
"🟡 UPDATED existing pending tool call with id:", "🟡 UPDATED existing pending tool call with id:",
existing.id, existing.id
); );
} else { } else {
const functionCall = { const functionCall = {
@ -1311,7 +1312,7 @@ function ChatPage() {
id: fc.id, id: fc.id,
name: fc.name, name: fc.name,
type: fc.type, type: fc.type,
})), }))
); );
} }
} }
@ -1589,7 +1590,7 @@ function ChatPage() {
const handleForkConversation = ( const handleForkConversation = (
messageIndex: number, messageIndex: number,
event?: React.MouseEvent, event?: React.MouseEvent
) => { ) => {
// Prevent any default behavior and stop event propagation // Prevent any default behavior and stop event propagation
if (event) { if (event) {
@ -1654,7 +1655,7 @@ function ChatPage() {
const renderFunctionCalls = ( const renderFunctionCalls = (
functionCalls: FunctionCall[], functionCalls: FunctionCall[],
messageIndex?: number, messageIndex?: number
) => { ) => {
if (!functionCalls || functionCalls.length === 0) return null; if (!functionCalls || functionCalls.length === 0) return null;
@ -2022,7 +2023,7 @@ function ChatPage() {
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
{renderFunctionCalls( {renderFunctionCalls(
message.functionCalls || [], message.functionCalls || [],
index, index
)} )}
<p className="text-foreground whitespace-pre-wrap break-words overflow-wrap-anywhere"> <p className="text-foreground whitespace-pre-wrap break-words overflow-wrap-anywhere">
{message.content} {message.content}
@ -2053,7 +2054,7 @@ function ChatPage() {
<div className="flex-1"> <div className="flex-1">
{renderFunctionCalls( {renderFunctionCalls(
streamingMessage.functionCalls, streamingMessage.functionCalls,
messages.length, messages.length
)} )}
<p className="text-foreground whitespace-pre-wrap break-words overflow-wrap-anywhere"> <p className="text-foreground whitespace-pre-wrap break-words overflow-wrap-anywhere">
{streamingMessage.content} {streamingMessage.content}
@ -2196,7 +2197,7 @@ function ChatPage() {
const filteredFilters = availableFilters.filter((filter) => const filteredFilters = availableFilters.filter((filter) =>
filter.name filter.name
.toLowerCase() .toLowerCase()
.includes(filterSearchTerm.toLowerCase()), .includes(filterSearchTerm.toLowerCase())
); );
if (e.key === "Escape") { if (e.key === "Escape") {
@ -2214,7 +2215,7 @@ function ChatPage() {
if (e.key === "ArrowDown") { if (e.key === "ArrowDown") {
e.preventDefault(); e.preventDefault();
setSelectedFilterIndex((prev) => setSelectedFilterIndex((prev) =>
prev < filteredFilters.length - 1 ? prev + 1 : 0, prev < filteredFilters.length - 1 ? prev + 1 : 0
); );
return; return;
} }
@ -2222,7 +2223,7 @@ function ChatPage() {
if (e.key === "ArrowUp") { if (e.key === "ArrowUp") {
e.preventDefault(); e.preventDefault();
setSelectedFilterIndex((prev) => setSelectedFilterIndex((prev) =>
prev > 0 ? prev - 1 : filteredFilters.length - 1, prev > 0 ? prev - 1 : filteredFilters.length - 1
); );
return; return;
} }
@ -2240,7 +2241,7 @@ function ChatPage() {
) { ) {
e.preventDefault(); e.preventDefault();
handleFilterSelect( handleFilterSelect(
filteredFilters[selectedFilterIndex], filteredFilters[selectedFilterIndex]
); );
return; return;
} }
@ -2259,7 +2260,7 @@ function ChatPage() {
) { ) {
e.preventDefault(); e.preventDefault();
handleFilterSelect( handleFilterSelect(
filteredFilters[selectedFilterIndex], filteredFilters[selectedFilterIndex]
); );
return; return;
} }
@ -2339,7 +2340,7 @@ function ChatPage() {
.filter((filter) => .filter((filter) =>
filter.name filter.name
.toLowerCase() .toLowerCase()
.includes(filterSearchTerm.toLowerCase()), .includes(filterSearchTerm.toLowerCase())
) )
.map((filter, index) => ( .map((filter, index) => (
<button <button
@ -2365,7 +2366,7 @@ function ChatPage() {
{availableFilters.filter((filter) => {availableFilters.filter((filter) =>
filter.name filter.name
.toLowerCase() .toLowerCase()
.includes(filterSearchTerm.toLowerCase()), .includes(filterSearchTerm.toLowerCase())
).length === 0 && ).length === 0 &&
filterSearchTerm && ( filterSearchTerm && (
<div className="px-2 py-3 text-sm text-muted-foreground"> <div className="px-2 py-3 text-sm text-muted-foreground">

View file

@ -0,0 +1,11 @@
import { create } from 'zustand'
interface LoadingState {
loading: boolean
setLoading: (loading: boolean) => void
}
export const useLoadingStore = create<LoadingState>((set) => ({
loading: false,
setLoading: (loading) => set({ loading }),
}))