feat: wire chat UI to backend APIs
- Created API clients for LLM chat (/api/llm/chat) and Ideas (/api/ideas) - Implemented useChat hook for conversation state management - Connected Chat component to backend with full CRUD operations - Integrated ConversationSidebar with conversation fetching - Added automatic conversation persistence after each message - Integrated WebSocket for connection status - Used existing better-auth for authentication - All TypeScript strict mode compliant (no any types) Deliverables: ✅ Working chat interface at /chat route ✅ Conversations save to database via Ideas API ✅ Real-time WebSocket connection ✅ Clean TypeScript (no errors) ✅ Full conversation loading and persistence See CHAT_INTEGRATION_SUMMARY.md for detailed documentation.
This commit is contained in:
@@ -1,23 +1,19 @@
|
||||
"use client";
|
||||
|
||||
import { useState, forwardRef, useImperativeHandle } from "react";
|
||||
// import Link from "next/link";
|
||||
// NOTE: Import hooks when they're created (see issue #TBD)
|
||||
// import { useConversations, ConversationSummary } from "@/lib/hooks/useConversations";
|
||||
// import { useProjects } from "@/lib/hooks/useProjects";
|
||||
// import type { IsolationMode } from "@/lib/api";
|
||||
import { useState, useEffect, forwardRef, useImperativeHandle, useCallback } from "react";
|
||||
import { getConversations, type Idea } from "@/lib/api/ideas";
|
||||
import { useAuth } from "@/lib/auth/auth-context";
|
||||
|
||||
// Placeholder types
|
||||
type ConversationSummary = {
|
||||
id: string;
|
||||
title: string | null;
|
||||
project_id: string | null;
|
||||
updated_at: string;
|
||||
message_count: number;
|
||||
projectId: string | null;
|
||||
updatedAt: string;
|
||||
messageCount: number;
|
||||
};
|
||||
|
||||
export interface ConversationSidebarRef {
|
||||
refresh: () => void;
|
||||
refresh: () => Promise<void>;
|
||||
addConversation: (conversation: ConversationSummary) => void;
|
||||
}
|
||||
|
||||
@@ -25,7 +21,7 @@ interface ConversationSidebarProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
currentConversationId: string | null;
|
||||
onSelectConversation: (conversationId: string | null) => void;
|
||||
onSelectConversation: (conversationId: string | null) => Promise<void>;
|
||||
onNewConversation: (projectId?: string | null) => void;
|
||||
}
|
||||
|
||||
@@ -37,20 +33,75 @@ export const ConversationSidebar = forwardRef<ConversationSidebarRef, Conversati
|
||||
onNewConversation,
|
||||
}, ref) {
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
|
||||
// Placeholder data
|
||||
const conversations: ConversationSummary[] = [];
|
||||
const projects: Array<{ id: string; name: string }> = [];
|
||||
const [conversations, setConversations] = useState<ConversationSummary[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { user } = useAuth();
|
||||
|
||||
/**
|
||||
* Convert Idea to ConversationSummary
|
||||
*/
|
||||
const ideaToConversation = useCallback((idea: Idea): ConversationSummary => {
|
||||
// Count messages from the stored JSON content
|
||||
let messageCount = 0;
|
||||
try {
|
||||
const messages = JSON.parse(idea.content);
|
||||
messageCount = Array.isArray(messages) ? messages.length : 0;
|
||||
} catch {
|
||||
// If parsing fails, assume 0 messages
|
||||
messageCount = 0;
|
||||
}
|
||||
|
||||
return {
|
||||
id: idea.id,
|
||||
title: idea.title,
|
||||
projectId: idea.projectId,
|
||||
updatedAt: idea.updatedAt,
|
||||
messageCount,
|
||||
};
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Fetch conversations from backend
|
||||
*/
|
||||
const fetchConversations = useCallback(async (): Promise<void> => {
|
||||
if (!user) {
|
||||
setConversations([]);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
const response = await getConversations({
|
||||
limit: 50,
|
||||
page: 1,
|
||||
});
|
||||
|
||||
const summaries = response.data.map(ideaToConversation);
|
||||
setConversations(summaries);
|
||||
} catch (err) {
|
||||
const errorMsg = err instanceof Error ? err.message : "Failed to load conversations";
|
||||
setError(errorMsg);
|
||||
console.error("Error fetching conversations:", err);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [user, ideaToConversation]);
|
||||
|
||||
// Load conversations on mount and when user changes
|
||||
useEffect(() => {
|
||||
void fetchConversations();
|
||||
}, [fetchConversations]);
|
||||
|
||||
// Expose methods to parent via ref
|
||||
useImperativeHandle(ref, () => ({
|
||||
refresh: () => {
|
||||
// NOTE: Implement refresh logic (see issue #TBD)
|
||||
void 0; // Placeholder until implemented
|
||||
refresh: async () => {
|
||||
await fetchConversations();
|
||||
},
|
||||
addConversation: (conversation: ConversationSummary) => {
|
||||
// NOTE: Implement addConversation logic (see issue #TBD)
|
||||
void conversation; // Placeholder until implemented
|
||||
setConversations((prev) => [conversation, ...prev]);
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -60,7 +111,7 @@ export const ConversationSidebar = forwardRef<ConversationSidebarRef, Conversati
|
||||
return title.toLowerCase().includes(searchQuery.toLowerCase());
|
||||
});
|
||||
|
||||
const formatRelativeTime = (dateString: string) => {
|
||||
const formatRelativeTime = (dateString: string): string => {
|
||||
const date = new Date(dateString);
|
||||
const now = new Date();
|
||||
const diffMs = now.getTime() - date.getTime();
|
||||
@@ -75,7 +126,7 @@ export const ConversationSidebar = forwardRef<ConversationSidebarRef, Conversati
|
||||
return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
|
||||
};
|
||||
|
||||
const truncateTitle = (title: string | null, maxLength = 32) => {
|
||||
const truncateTitle = (title: string | null, maxLength = 32): string => {
|
||||
const displayTitle = title || "Untitled conversation";
|
||||
if (displayTitle.length <= maxLength) return displayTitle;
|
||||
return displayTitle.substring(0, maxLength - 1) + "…";
|
||||
@@ -106,15 +157,15 @@ export const ConversationSidebar = forwardRef<ConversationSidebarRef, Conversati
|
||||
}}
|
||||
aria-label="Conversation history"
|
||||
>
|
||||
{/* Collapsed view - NOTE: Implement (see issue #TBD) */}
|
||||
{/* Collapsed view */}
|
||||
{!isOpen && (
|
||||
<div className="hidden md:flex flex-col items-center py-3 h-full">
|
||||
<button
|
||||
onClick={() => onNewConversation()}
|
||||
className="p-3 rounded-lg transition-colors"
|
||||
className="p-3 rounded-lg transition-colors hover:bg-[rgb(var(--surface-1))]"
|
||||
title="New Conversation"
|
||||
>
|
||||
<svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<svg className="h-5 w-5" style={{ color: "rgb(var(--text-muted))" }} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path d="M12 4v16m8-8H4" />
|
||||
</svg>
|
||||
</button>
|
||||
@@ -196,16 +247,41 @@ export const ConversationSidebar = forwardRef<ConversationSidebarRef, Conversati
|
||||
|
||||
{/* Conversations List */}
|
||||
<div className="flex-1 overflow-y-auto px-3 pt-3 pb-3 space-y-1">
|
||||
{filteredConversations.length === 0 ? (
|
||||
{isLoading ? (
|
||||
<div className="text-center py-8" style={{ color: "rgb(var(--text-muted))" }}>
|
||||
<p className="text-sm">No conversations yet</p>
|
||||
<p className="text-xs mt-1">Start a new chat to begin</p>
|
||||
<div className="h-5 w-5 mx-auto animate-spin rounded-full border-2 border-t-transparent" style={{ borderColor: "rgb(var(--accent-primary))", borderTopColor: "transparent" }} />
|
||||
<p className="text-xs mt-2">Loading conversations...</p>
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="text-center py-8" style={{ color: "rgb(var(--semantic-error))" }}>
|
||||
<svg className="h-8 w-8 mx-auto mb-2" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<circle cx="12" cy="12" r="10" />
|
||||
<line x1="12" y1="8" x2="12" y2="12" />
|
||||
<line x1="12" y1="16" x2="12.01" y2="16" />
|
||||
</svg>
|
||||
<p className="text-xs">{error}</p>
|
||||
<button
|
||||
onClick={() => void fetchConversations()}
|
||||
className="text-xs mt-2 underline"
|
||||
style={{ color: "rgb(var(--accent-primary))" }}
|
||||
>
|
||||
Retry
|
||||
</button>
|
||||
</div>
|
||||
) : filteredConversations.length === 0 ? (
|
||||
<div className="text-center py-8" style={{ color: "rgb(var(--text-muted))" }}>
|
||||
<p className="text-sm">
|
||||
{searchQuery ? "No matching conversations" : "No conversations yet"}
|
||||
</p>
|
||||
<p className="text-xs mt-1">
|
||||
{searchQuery ? "Try a different search" : "Start a new chat to begin"}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
filteredConversations.map((conv) => (
|
||||
<button
|
||||
key={conv.id}
|
||||
onClick={() => onSelectConversation(conv.id)}
|
||||
onClick={() => void onSelectConversation(conv.id)}
|
||||
className={`w-full text-left px-3 py-2 rounded-lg transition-colors ${
|
||||
conv.id === currentConversationId
|
||||
? "bg-[rgb(var(--accent-primary-light))]"
|
||||
@@ -223,12 +299,12 @@ export const ConversationSidebar = forwardRef<ConversationSidebarRef, Conversati
|
||||
{truncateTitle(conv.title)}
|
||||
</p>
|
||||
<div className="flex items-center gap-2 mt-0.5" style={{ color: "rgb(var(--text-muted))" }}>
|
||||
<span className="text-xs">{formatRelativeTime(conv.updated_at)}</span>
|
||||
{conv.message_count > 0 && (
|
||||
<span className="text-xs">{formatRelativeTime(conv.updatedAt)}</span>
|
||||
{conv.messageCount > 0 && (
|
||||
<>
|
||||
<span className="text-xs">·</span>
|
||||
<span className="text-xs">
|
||||
{conv.message_count} msg{conv.message_count !== 1 ? "s" : ""}
|
||||
{conv.messageCount} msg{conv.messageCount !== 1 ? "s" : ""}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
|
||||
Reference in New Issue
Block a user