feat: Adding session manager to UI using local storage

Signed-off-by: Francisco Javier Arceo <farceo@redhat.com>
This commit is contained in:
Francisco Javier Arceo 2025-08-19 12:18:30 -04:00
parent eb07a0f86a
commit e7be568d7e
4 changed files with 1558 additions and 78 deletions

View file

@ -1,6 +1,6 @@
"use client";
import { useState, useEffect } from "react";
import { useState, useEffect, useCallback, useRef } from "react";
import { flushSync } from "react-dom";
import { Button } from "@/components/ui/button";
import {
@ -15,9 +15,24 @@ import { type Message } from "@/components/chat-playground/chat-message";
import { useAuthClient } from "@/hooks/use-auth-client";
import type { CompletionCreateParams } from "llama-stack-client/resources/chat/completions";
import type { Model } from "llama-stack-client/resources/models";
import {
SessionManager,
SessionUtils,
} from "@/components/chat-playground/session-manager";
interface ChatSession {
id: string;
name: string;
messages: Message[];
selectedModel: string;
systemMessage: string;
createdAt: number;
updatedAt: number;
}
export default function ChatPlaygroundPage() {
const [messages, setMessages] = useState<Message[]>([]);
const [currentSession, setCurrentSession] = useState<ChatSession | null>(
null
);
const [input, setInput] = useState("");
const [isGenerating, setIsGenerating] = useState(false);
const [error, setError] = useState<string | null>(null);
@ -26,9 +41,52 @@ export default function ChatPlaygroundPage() {
const [modelsLoading, setModelsLoading] = useState(true);
const [modelsError, setModelsError] = useState<string | null>(null);
const client = useAuthClient();
const abortControllerRef = useRef<AbortController | null>(null);
const isModelsLoading = modelsLoading ?? true;
useEffect(() => {
const saved = SessionUtils.loadCurrentSession();
if (saved) {
setCurrentSession(saved);
} else {
const def = SessionUtils.createDefaultSession();
const defaultSession: ChatSession = {
...def,
selectedModel: "",
systemMessage: def.systemMessage || "You are a helpful assistant.",
};
setCurrentSession(defaultSession);
SessionUtils.saveCurrentSession(defaultSession);
}
}, []);
const handleModelChange = useCallback((newModel: string) => {
setSelectedModel(newModel);
setCurrentSession(prev =>
prev
? {
...prev,
selectedModel: newModel,
updatedAt: Date.now(),
}
: prev
);
}, []);
useEffect(() => {
if (currentSession) {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
setIsGenerating(false);
}
SessionUtils.saveCurrentSession(currentSession);
setSelectedModel(currentSession.selectedModel);
}
}, [currentSession]);
useEffect(() => {
const fetchModels = async () => {
try {
@ -38,7 +96,7 @@ export default function ChatPlaygroundPage() {
const llmModels = modelList.filter(model => model.model_type === "llm");
setModels(llmModels);
if (llmModels.length > 0) {
setSelectedModel(llmModels[0].identifier);
handleModelChange(llmModels[0].identifier);
}
} catch (err) {
console.error("Error fetching models:", err);
@ -49,7 +107,7 @@ export default function ChatPlaygroundPage() {
};
fetchModels();
}, [client]);
}, [client, handleModelChange]);
const extractTextContent = (content: unknown): string => {
if (typeof content === "string") {
@ -91,7 +149,6 @@ export default function ChatPlaygroundPage() {
event?.preventDefault?.();
if (!input.trim()) return;
// Add user message to chat
const userMessage: Message = {
id: Date.now().toString(),
role: "user",
@ -99,10 +156,17 @@ export default function ChatPlaygroundPage() {
createdAt: new Date(),
};
setMessages(prev => [...prev, userMessage]);
setCurrentSession(prev =>
prev
? {
...prev,
messages: [...prev.messages, userMessage],
updatedAt: Date.now(),
}
: prev
);
setInput("");
// Use the helper function with the content
await handleSubmitWithContent(userMessage.content);
};
@ -110,9 +174,19 @@ export default function ChatPlaygroundPage() {
setIsGenerating(true);
setError(null);
if (abortControllerRef.current) {
abortControllerRef.current.abort();
}
const abortController = new AbortController();
abortControllerRef.current = abortController;
try {
const messageParams: CompletionCreateParams["messages"] = [
...messages.map(msg => {
...(currentSession?.systemMessage
? [{ role: "system" as const, content: currentSession.systemMessage }]
: []),
...(currentSession?.messages || []).map(msg => {
const msgContent =
typeof msg.content === "string"
? msg.content
@ -128,11 +202,16 @@ export default function ChatPlaygroundPage() {
{ role: "user" as const, content },
];
const response = await client.chat.completions.create({
model: selectedModel,
const response = await client.chat.completions.create(
{
model: selectedModel || "",
messages: messageParams,
stream: true,
});
},
{
signal: abortController.signal,
} as { signal: AbortSignal }
);
const assistantMessage: Message = {
id: (Date.now() + 1).toString(),
@ -141,7 +220,15 @@ export default function ChatPlaygroundPage() {
createdAt: new Date(),
};
setMessages(prev => [...prev, assistantMessage]);
setCurrentSession(prev =>
prev
? {
...prev,
messages: [...prev.messages, assistantMessage],
updatedAt: Date.now(),
}
: null
);
let fullContent = "";
for await (const chunk of response) {
if (chunk.choices && chunk.choices[0]?.delta?.content) {
@ -149,23 +236,37 @@ export default function ChatPlaygroundPage() {
fullContent += deltaContent;
flushSync(() => {
setMessages(prev => {
const newMessages = [...prev];
const lastMessage = newMessages[newMessages.length - 1];
if (lastMessage.role === "assistant") {
lastMessage.content = fullContent;
}
return newMessages;
setCurrentSession(prev => {
if (!prev) return null;
const newMessages = [...prev.messages];
const last = newMessages[newMessages.length - 1];
if (last.role === "assistant") last.content = fullContent;
return { ...prev, messages: newMessages, updatedAt: Date.now() };
});
});
}
}
} catch (err) {
// don't show error if request was aborted
if (err instanceof Error && err.name === "AbortError") {
console.log("Request aborted");
return;
}
console.error("Error sending message:", err);
setError("Failed to send message. Please try again.");
setMessages(prev => prev.slice(0, -1));
setCurrentSession(prev =>
prev
? {
...prev,
messages: prev.messages.slice(0, -1),
updatedAt: Date.now(),
}
: prev
);
} finally {
setIsGenerating(false);
abortControllerRef.current = null;
}
};
const suggestions = [
@ -181,52 +282,142 @@ export default function ChatPlaygroundPage() {
content: message.content,
createdAt: new Date(),
};
setMessages(prev => [...prev, newMessage]);
setCurrentSession(prev =>
prev
? {
...prev,
messages: [...prev.messages, newMessage],
updatedAt: Date.now(),
}
: prev
);
handleSubmitWithContent(newMessage.content);
};
const clearChat = () => {
setMessages([]);
setCurrentSession(prev =>
prev ? { ...prev, messages: [], updatedAt: Date.now() } : prev
);
setError(null);
};
const handleSessionChange = (session: ChatSession) => {
setCurrentSession(session);
setError(null);
};
const handleNewSession = () => {
const defaultModel =
currentSession?.selectedModel ||
(models.length > 0 ? models[0].identifier : "");
const newSession: ChatSession = {
...SessionUtils.createDefaultSession(),
selectedModel: defaultModel,
systemMessage:
currentSession?.systemMessage || "You are a helpful assistant.",
messages: [],
updatedAt: Date.now(),
createdAt: Date.now(),
};
setCurrentSession(newSession);
SessionUtils.saveCurrentSession(newSession);
};
return (
<div className="flex flex-col h-full max-w-4xl mx-auto">
<div className="mb-4 flex justify-between items-center">
<h1 className="text-2xl font-bold">Chat Playground (Completions)</h1>
<div className="flex gap-2">
<div className="flex flex-col h-full w-full max-w-7xl mx-auto">
{/* Header */}
<div className="mb-6">
<div className="flex justify-between items-center mb-4">
<h1 className="text-3xl font-bold">Chat Playground</h1>
<div className="flex items-center gap-3">
<SessionManager
currentSession={currentSession}
onSessionChange={handleSessionChange}
onNewSession={handleNewSession}
/>
<Button
variant="outline"
onClick={clearChat}
disabled={isGenerating}
>
Clear Chat
</Button>
</div>
</div>
</div>
{/* Main Two-Column Layout */}
<div className="flex flex-1 gap-6 min-h-0 flex-col lg:flex-row">
{/* Left Column - Configuration Panel */}
<div className="w-full lg:w-80 lg:flex-shrink-0 space-y-6 p-4 border border-border rounded-lg bg-muted/30">
<h2 className="text-lg font-semibold border-b pb-2 text-left">
Settings
</h2>
{/* Model Configuration */}
<div className="space-y-4 text-left">
<h3 className="text-lg font-semibold border-b pb-2 text-left">
Model Configuration
</h3>
<div className="space-y-3">
<div>
<label className="text-sm font-medium block mb-2">Model</label>
<Select
value={selectedModel}
onValueChange={setSelectedModel}
onValueChange={handleModelChange}
disabled={isModelsLoading || isGenerating}
>
<SelectTrigger className="w-[180px]">
<SelectTrigger className="w-full">
<SelectValue
placeholder={
isModelsLoading ? "Loading models..." : "Select Model"
isModelsLoading ? "Loading..." : "Select Model"
}
/>
</SelectTrigger>
<SelectContent>
{models.map(model => (
<SelectItem key={model.identifier} value={model.identifier}>
<SelectItem
key={model.identifier}
value={model.identifier}
>
{model.identifier}
</SelectItem>
))}
</SelectContent>
</Select>
<Button variant="outline" onClick={clearChat} disabled={isGenerating}>
Clear Chat
</Button>
</div>
</div>
{modelsError && (
<div className="mb-4 p-3 bg-destructive/10 border border-destructive/20 rounded-md">
<p className="text-destructive text-sm">{modelsError}</p>
</div>
<p className="text-destructive text-xs mt-1">{modelsError}</p>
)}
</div>
<div>
<label className="text-sm font-medium block mb-2">
System Message
</label>
<textarea
value={currentSession?.systemMessage || ""}
onChange={e =>
setCurrentSession(prev =>
prev
? {
...prev,
systemMessage: e.target.value,
updatedAt: Date.now(),
}
: prev
)
}
placeholder="You are a helpful assistant."
disabled={isGenerating}
className="w-full h-24 px-3 py-2 text-sm border border-input rounded-md resize-none focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
/>
</div>
</div>
</div>
</div>
{/* Right Column - Chat Interface */}
<div className="flex-1 flex flex-col min-h-0 p-4 border border-border rounded-lg bg-background">
{error && (
<div className="mb-4 p-3 bg-destructive/10 border border-destructive/20 rounded-md">
<p className="text-destructive text-sm">{error}</p>
@ -235,15 +426,21 @@ export default function ChatPlaygroundPage() {
<Chat
className="flex-1"
messages={messages}
messages={currentSession?.messages || []}
handleSubmit={handleSubmit}
input={input}
handleInputChange={handleInputChange}
isGenerating={isGenerating}
append={append}
suggestions={suggestions}
setMessages={setMessages}
setMessages={messages =>
setCurrentSession(prev =>
prev ? { ...prev, messages, updatedAt: Date.now() } : prev
)
}
/>
</div>
</div>
</div>
);
}

View file

@ -161,10 +161,12 @@ export const ChatMessage: React.FC<ChatMessageProps> = ({
const isUser = role === "user";
const formattedTime = createdAt?.toLocaleTimeString("en-US", {
const formattedTime = createdAt
? new Date(createdAt).toLocaleTimeString("en-US", {
hour: "2-digit",
minute: "2-digit",
});
})
: undefined;
if (isUser) {
return (
@ -185,7 +187,7 @@ export const ChatMessage: React.FC<ChatMessageProps> = ({
{showTimeStamp && createdAt ? (
<time
dateTime={createdAt.toISOString()}
dateTime={new Date(createdAt).toISOString()}
className={cn(
"mt-1 block px-1 text-xs opacity-50",
animation !== "none" && "duration-500 animate-in fade-in-0"
@ -220,7 +222,7 @@ export const ChatMessage: React.FC<ChatMessageProps> = ({
{showTimeStamp && createdAt ? (
<time
dateTime={createdAt.toISOString()}
dateTime={new Date(createdAt).toISOString()}
className={cn(
"mt-1 block px-1 text-xs opacity-50",
animation !== "none" && "duration-500 animate-in fade-in-0"
@ -262,7 +264,7 @@ export const ChatMessage: React.FC<ChatMessageProps> = ({
{showTimeStamp && createdAt ? (
<time
dateTime={createdAt.toISOString()}
dateTime={new Date(createdAt).toISOString()}
className={cn(
"mt-1 block px-1 text-xs opacity-50",
animation !== "none" && "duration-500 animate-in fade-in-0"

View file

@ -0,0 +1,940 @@
import React from "react";
import {
render,
screen,
fireEvent,
waitFor,
act,
} from "@testing-library/react";
import "@testing-library/jest-dom";
import { SessionManager, SessionUtils } from "./session-manager";
import type { Message } from "@/components/chat-playground/chat-message";
interface ChatSession {
id: string;
name: string;
messages: Message[];
selectedModel: string;
selectedVectorDb: string;
systemMessage: string;
createdAt: number;
updatedAt: number;
}
const mockOnSessionChange = jest.fn();
const mockOnNewSession = jest.fn();
const localStorageMock = {
getItem: jest.fn(),
setItem: jest.fn(),
removeItem: jest.fn(),
clear: jest.fn(),
};
Object.defineProperty(window, "localStorage", {
value: localStorageMock,
writable: true,
});
// Mock crypto.randomUUID for test environment
let uuidCounter = 0;
Object.defineProperty(globalThis, "crypto", {
value: {
randomUUID: jest.fn(() => `test-uuid-${++uuidCounter}`),
},
writable: true,
});
describe("SessionManager", () => {
const mockSession: ChatSession = {
id: "session_123",
name: "Test Session",
messages: [
{
id: "msg_1",
role: "user",
content: "Hello",
timestamp: Date.now(),
},
],
selectedModel: "test-model",
selectedVectorDb: "test-vector-db",
systemMessage: "You are a helpful assistant.",
createdAt: 1710000000,
updatedAt: 1710001000,
};
const mockSessions: ChatSession[] = [
mockSession,
{
id: "session_456",
name: "Another Session",
messages: [],
selectedModel: "another-model",
selectedVectorDb: "another-vector-db",
systemMessage: "You are another assistant.",
createdAt: 1710002000,
updatedAt: 1710003000,
},
];
beforeEach(() => {
jest.clearAllMocks();
localStorageMock.getItem.mockReturnValue(null);
localStorageMock.setItem.mockImplementation(() => {});
uuidCounter = 0; // Reset UUID counter for consistent test behavior
});
describe("Component Rendering", () => {
test("renders session selector with placeholder when no session selected", async () => {
await act(async () => {
render(
<SessionManager
currentSession={null}
onSessionChange={mockOnSessionChange}
onNewSession={mockOnNewSession}
/>
);
});
expect(screen.getByText("Select Session")).toBeInTheDocument();
expect(screen.getByRole("button", { name: /New/ })).toBeInTheDocument();
});
test("renders current session name when session is selected", async () => {
localStorageMock.getItem.mockImplementation(key => {
if (key === "chat-playground-sessions") {
return JSON.stringify(mockSessions);
}
return null;
});
await act(async () => {
render(
<SessionManager
currentSession={mockSession}
onSessionChange={mockOnSessionChange}
onNewSession={mockOnNewSession}
/>
);
});
await waitFor(() => {
expect(screen.getByText("Test Session")).toBeInTheDocument();
});
});
test("shows session info when multiple sessions exist", async () => {
localStorageMock.getItem.mockImplementation(key => {
if (key === "chat-playground-sessions") {
return JSON.stringify(mockSessions);
}
return null;
});
await act(async () => {
render(
<SessionManager
currentSession={mockSession}
onSessionChange={mockOnSessionChange}
onNewSession={mockOnNewSession}
/>
);
});
await waitFor(() => {
expect(screen.getByText(/2 sessions/)).toBeInTheDocument();
expect(screen.getByText(/Current: Test Session/)).toBeInTheDocument();
expect(screen.getByText(/1 messages/)).toBeInTheDocument();
});
});
});
describe("Session Creation", () => {
test("shows create form when New button is clicked", async () => {
await act(async () => {
render(
<SessionManager
currentSession={mockSession}
onSessionChange={mockOnSessionChange}
onNewSession={mockOnNewSession}
/>
);
});
const newButton = screen.getByRole("button", { name: /New/ });
fireEvent.click(newButton);
expect(screen.getByText("Create New Session")).toBeInTheDocument();
expect(
screen.getByPlaceholderText("Session name (optional)")
).toBeInTheDocument();
expect(
screen.getByRole("button", { name: "Create" })
).toBeInTheDocument();
expect(
screen.getByRole("button", { name: "Cancel" })
).toBeInTheDocument();
});
test("creates session with custom name", async () => {
await act(async () => {
render(
<SessionManager
currentSession={mockSession}
onSessionChange={mockOnSessionChange}
onNewSession={mockOnNewSession}
/>
);
});
const newButton = screen.getByRole("button", { name: /New/ });
fireEvent.click(newButton);
const nameInput = screen.getByPlaceholderText("Session name (optional)");
fireEvent.change(nameInput, { target: { value: "Custom Session" } });
const createButton = screen.getByRole("button", { name: "Create" });
fireEvent.click(createButton);
expect(localStorageMock.setItem).toHaveBeenCalledWith(
"chat-playground-sessions",
expect.stringContaining("Custom Session")
);
expect(mockOnSessionChange).toHaveBeenCalled();
});
test("creates session with default name when no name provided", async () => {
localStorageMock.getItem.mockImplementation(key => {
if (key === "chat-playground-sessions") {
return JSON.stringify(mockSessions);
}
return null;
});
await act(async () => {
render(
<SessionManager
currentSession={mockSession}
onSessionChange={mockOnSessionChange}
onNewSession={mockOnNewSession}
/>
);
});
const newButton = screen.getByRole("button", { name: /New/ });
fireEvent.click(newButton);
const createButton = screen.getByRole("button", { name: "Create" });
fireEvent.click(createButton);
expect(localStorageMock.setItem).toHaveBeenCalledWith(
"chat-playground-sessions",
expect.stringContaining("Session 3")
);
});
test("cancels session creation", async () => {
await act(async () => {
render(
<SessionManager
currentSession={null}
onSessionChange={mockOnSessionChange}
onNewSession={mockOnNewSession}
/>
);
});
const newButton = screen.getByRole("button", { name: /New/ });
fireEvent.click(newButton);
const nameInput = screen.getByPlaceholderText("Session name (optional)");
fireEvent.change(nameInput, { target: { value: "Test Input" } });
localStorageMock.setItem.mockClear();
const cancelButton = screen.getByRole("button", { name: "Cancel" });
fireEvent.click(cancelButton);
expect(screen.queryByText("Create New Session")).not.toBeInTheDocument();
expect(localStorageMock.setItem).not.toHaveBeenCalled();
});
test("creates session on Enter key press", async () => {
await act(async () => {
render(
<SessionManager
currentSession={mockSession}
onSessionChange={mockOnSessionChange}
onNewSession={mockOnNewSession}
/>
);
});
const newButton = screen.getByRole("button", { name: /New/ });
fireEvent.click(newButton);
const nameInput = screen.getByPlaceholderText("Session name (optional)");
fireEvent.change(nameInput, { target: { value: "Enter Session" } });
fireEvent.keyDown(nameInput, { key: "Enter" });
expect(localStorageMock.setItem).toHaveBeenCalledWith(
"chat-playground-sessions",
expect.stringContaining("Enter Session")
);
});
test("cancels session creation on Escape key press", async () => {
await act(async () => {
render(
<SessionManager
currentSession={mockSession}
onSessionChange={mockOnSessionChange}
onNewSession={mockOnNewSession}
/>
);
});
const newButton = screen.getByRole("button", { name: /New/ });
fireEvent.click(newButton);
const nameInput = screen.getByPlaceholderText("Session name (optional)");
fireEvent.keyDown(nameInput, { key: "Escape" });
expect(screen.queryByText("Create New Session")).not.toBeInTheDocument();
});
});
describe("Session Switching", () => {
test("switches to selected session", async () => {
localStorageMock.getItem.mockImplementation(key => {
if (key === "chat-playground-sessions") {
return JSON.stringify(mockSessions);
}
return null;
});
await act(async () => {
render(
<SessionManager
currentSession={mockSession}
onSessionChange={mockOnSessionChange}
onNewSession={mockOnNewSession}
/>
);
});
await waitFor(() => {
expect(screen.getByText("Test Session")).toBeInTheDocument();
});
const selectTrigger = screen.getByRole("combobox");
fireEvent.click(selectTrigger);
await waitFor(() => {
const anotherSessionOption = screen.getByText("Another Session");
fireEvent.click(anotherSessionOption);
});
expect(localStorageMock.setItem).toHaveBeenCalledWith(
"chat-playground-current-session",
"session_456"
);
expect(mockOnSessionChange).toHaveBeenCalledWith(
expect.objectContaining({
id: "session_456",
name: "Another Session",
})
);
});
});
describe("LocalStorage Integration", () => {
test("loads sessions from localStorage on mount", async () => {
localStorageMock.getItem.mockImplementation(key => {
if (key === "chat-playground-sessions") {
return JSON.stringify(mockSessions);
}
return null;
});
await act(async () => {
render(
<SessionManager
currentSession={mockSession}
onSessionChange={mockOnSessionChange}
onNewSession={mockOnNewSession}
/>
);
});
await waitFor(() => {
expect(localStorageMock.getItem).toHaveBeenCalledWith(
"chat-playground-sessions"
);
});
});
test("handles corrupted localStorage data gracefully", async () => {
localStorageMock.getItem.mockReturnValue("invalid json");
const consoleSpy = jest.spyOn(console, "error").mockImplementation();
await act(async () => {
render(
<SessionManager
currentSession={mockSession}
onSessionChange={mockOnSessionChange}
onNewSession={mockOnNewSession}
/>
);
});
expect(consoleSpy).toHaveBeenCalledWith(
"Error parsing JSON:",
expect.any(Error)
);
consoleSpy.mockRestore();
});
test("updates localStorage when current session changes", async () => {
const updatedSession = {
...mockSession,
messages: [
...mockSession.messages,
{
id: "msg_2",
role: "assistant" as const,
content: "Hello back!",
timestamp: Date.now(),
},
],
updatedAt: Date.now(),
};
localStorageMock.getItem.mockImplementation(key => {
if (key === "chat-playground-sessions") {
return JSON.stringify([mockSession]);
}
return null;
});
const { rerender } = render(
<SessionManager
currentSession={mockSession}
onSessionChange={mockOnSessionChange}
onNewSession={mockOnNewSession}
/>
);
await act(async () => {
rerender(
<SessionManager
currentSession={updatedSession}
onSessionChange={mockOnSessionChange}
onNewSession={mockOnNewSession}
/>
);
});
await waitFor(() => {
expect(localStorageMock.setItem).toHaveBeenCalledWith(
"chat-playground-sessions",
expect.stringContaining(updatedSession.id)
);
});
});
});
describe("Session Deletion", () => {
test("shows delete button only when multiple sessions exist", async () => {
localStorageMock.getItem.mockImplementation(key => {
if (key === "chat-playground-sessions") {
return JSON.stringify([mockSession]);
}
return null;
});
await act(async () => {
render(
<SessionManager
currentSession={mockSession}
onSessionChange={mockOnSessionChange}
onNewSession={mockOnNewSession}
/>
);
});
expect(
screen.queryByTitle("Delete current session")
).not.toBeInTheDocument();
localStorageMock.getItem.mockImplementation(key => {
if (key === "chat-playground-sessions") {
return JSON.stringify(mockSessions);
}
return null;
});
const { rerender } = render(
<SessionManager
currentSession={mockSession}
onSessionChange={mockOnSessionChange}
onNewSession={mockOnNewSession}
/>
);
await act(async () => {
rerender(
<SessionManager
currentSession={mockSession}
onSessionChange={mockOnSessionChange}
onNewSession={mockOnNewSession}
/>
);
});
await waitFor(() => {
expect(screen.getByTitle("Delete current session")).toBeInTheDocument();
});
});
test("deletes current session after confirmation", async () => {
window.confirm = jest.fn().mockReturnValue(true);
localStorageMock.getItem.mockImplementation(key => {
if (key === "chat-playground-sessions") {
return JSON.stringify(mockSessions);
}
return null;
});
await act(async () => {
render(
<SessionManager
currentSession={mockSession}
onSessionChange={mockOnSessionChange}
onNewSession={mockOnNewSession}
/>
);
});
await waitFor(() => {
expect(screen.getByTitle("Delete current session")).toBeInTheDocument();
});
const deleteButton = screen.getByTitle("Delete current session");
fireEvent.click(deleteButton);
expect(window.confirm).toHaveBeenCalledWith(
"Are you sure you want to delete this session? This action cannot be undone."
);
expect(mockOnSessionChange).toHaveBeenCalled();
});
test("cancels deletion when user rejects confirmation", async () => {
window.confirm = jest.fn().mockReturnValue(false);
localStorageMock.getItem.mockImplementation(key => {
if (key === "chat-playground-sessions") {
return JSON.stringify(mockSessions);
}
return null;
});
await act(async () => {
render(
<SessionManager
currentSession={mockSession}
onSessionChange={mockOnSessionChange}
onNewSession={mockOnNewSession}
/>
);
});
await waitFor(() => {
expect(screen.getByTitle("Delete current session")).toBeInTheDocument();
});
const deleteButton = screen.getByTitle("Delete current session");
fireEvent.click(deleteButton);
expect(window.confirm).toHaveBeenCalled();
expect(mockOnSessionChange).not.toHaveBeenCalled();
});
test("prevents deletion of the last remaining session", async () => {
const singleSession = [mockSession];
localStorageMock.getItem.mockImplementation(key => {
if (key === "chat-playground-sessions") {
return JSON.stringify(singleSession);
}
return null;
});
await act(async () => {
render(
<SessionManager
currentSession={mockSession}
onSessionChange={mockOnSessionChange}
onNewSession={mockOnNewSession}
/>
);
});
expect(
screen.queryByTitle("Delete current session")
).not.toBeInTheDocument();
});
});
describe("Error Handling", () => {
test("component renders without crashing when localStorage is unavailable", async () => {
await act(async () => {
render(
<SessionManager
currentSession={mockSession}
onSessionChange={mockOnSessionChange}
onNewSession={mockOnNewSession}
/>
);
});
expect(screen.getByRole("button", { name: /New/ })).toBeInTheDocument();
expect(screen.getByText("Test Session")).toBeInTheDocument();
});
});
});
describe("SessionUtils", () => {
const mockSession: ChatSession = {
id: "utils_session_123",
name: "Utils Test Session",
messages: [],
selectedModel: "utils-model",
selectedVectorDb: "utils-vector-db",
systemMessage: "You are a utils assistant.",
createdAt: 1710000000,
updatedAt: 1710001000,
};
const mockSessions = [mockSession];
beforeEach(() => {
jest.clearAllMocks();
localStorageMock.getItem.mockReturnValue(null);
localStorageMock.setItem.mockImplementation(() => {});
});
describe("loadCurrentSession", () => {
test("returns null when no current session ID stored", () => {
const result = SessionUtils.loadCurrentSession();
expect(result).toBeNull();
});
test("returns null when no sessions stored", () => {
localStorageMock.getItem.mockImplementation(key => {
if (key === "chat-playground-current-session") {
return "session_123";
}
return null;
});
const result = SessionUtils.loadCurrentSession();
expect(result).toBeNull();
});
test("returns current session when found", () => {
localStorageMock.getItem.mockImplementation(key => {
if (key === "chat-playground-current-session") {
return "utils_session_123";
}
if (key === "chat-playground-sessions") {
return JSON.stringify(mockSessions);
}
return null;
});
const result = SessionUtils.loadCurrentSession();
expect(result).toEqual(mockSession);
});
test("returns null when current session ID not found in sessions", () => {
localStorageMock.getItem.mockImplementation(key => {
if (key === "chat-playground-current-session") {
return "nonexistent_session";
}
if (key === "chat-playground-sessions") {
return JSON.stringify(mockSessions);
}
return null;
});
const result = SessionUtils.loadCurrentSession();
expect(result).toBeNull();
});
test("handles corrupted sessions data gracefully", () => {
localStorageMock.getItem.mockImplementation(key => {
if (key === "chat-playground-current-session") {
return "session_123";
}
if (key === "chat-playground-sessions") {
return "invalid json";
}
return null;
});
const consoleSpy = jest.spyOn(console, "error").mockImplementation();
const result = SessionUtils.loadCurrentSession();
expect(result).toBeNull();
expect(consoleSpy).toHaveBeenCalledWith(
"Error parsing JSON:",
expect.any(Error)
);
consoleSpy.mockRestore();
});
});
describe("saveCurrentSession", () => {
test("saves new session to localStorage", () => {
localStorageMock.setItem.mockClear();
SessionUtils.saveCurrentSession(mockSession);
expect(localStorageMock.setItem).toHaveBeenCalledWith(
"chat-playground-sessions",
expect.stringContaining(mockSession.id)
);
expect(localStorageMock.setItem).toHaveBeenCalledWith(
"chat-playground-current-session",
mockSession.id
);
});
test("updates existing session in localStorage", () => {
localStorageMock.setItem.mockClear();
localStorageMock.getItem.mockImplementation(key => {
if (key === "chat-playground-sessions") {
return JSON.stringify(mockSessions);
}
return null;
});
const updatedSession = {
...mockSession,
name: "Updated Session Name",
messages: [
{
id: "msg_1",
role: "user" as const,
content: "Test message",
timestamp: Date.now(),
},
],
};
SessionUtils.saveCurrentSession(updatedSession);
expect(localStorageMock.setItem).toHaveBeenCalledWith(
"chat-playground-sessions",
expect.stringContaining("Updated Session Name")
);
expect(localStorageMock.setItem).toHaveBeenCalledWith(
"chat-playground-current-session",
updatedSession.id
);
});
test("handles corrupted sessions data gracefully", () => {
localStorageMock.setItem.mockClear();
localStorageMock.getItem.mockReturnValue("invalid json");
const consoleSpy = jest.spyOn(console, "error").mockImplementation();
SessionUtils.saveCurrentSession(mockSession);
expect(consoleSpy).toHaveBeenCalledWith(
"Error parsing JSON:",
expect.any(Error)
);
expect(localStorageMock.setItem).toHaveBeenCalledWith(
"chat-playground-sessions",
expect.stringContaining(mockSession.id)
);
consoleSpy.mockRestore();
});
test("updates timestamps correctly", () => {
localStorageMock.setItem.mockClear();
const originalNow = Date.now;
const mockTime = 1710005000;
Date.now = jest.fn(() => mockTime);
SessionUtils.saveCurrentSession(mockSession);
const savedSessionsCall = localStorageMock.setItem.mock.calls.find(
call => call[0] === "chat-playground-sessions"
);
const savedSessions = JSON.parse(savedSessionsCall[1]);
expect(savedSessions[0].updatedAt).toBe(mockTime);
Date.now = originalNow;
});
});
describe("createDefaultSession", () => {
test("creates default session with default values", () => {
const result = SessionUtils.createDefaultSession();
expect(result).toEqual(
expect.objectContaining({
name: "Default Session",
messages: [],
selectedModel: "",
selectedVectorDb: "",
systemMessage: "You are a helpful assistant.",
})
);
expect(result.id).toBeTruthy();
expect(result.createdAt).toBeTruthy();
expect(result.updatedAt).toBeTruthy();
});
test("creates default session with inherited model", () => {
const result = SessionUtils.createDefaultSession("inherited-model");
expect(result.selectedModel).toBe("inherited-model");
expect(result.selectedVectorDb).toBe("");
});
test("creates default session with inherited model and vector db", () => {
const result = SessionUtils.createDefaultSession(
"inherited-model",
"inherited-vector-db"
);
expect(result.selectedModel).toBe("inherited-model");
expect(result.selectedVectorDb).toBe("inherited-vector-db");
});
test("creates unique session IDs", () => {
const originalNow = Date.now;
let mockTime = 1710005000;
Date.now = jest.fn(() => ++mockTime);
const session1 = SessionUtils.createDefaultSession();
const session2 = SessionUtils.createDefaultSession();
expect(session1.id).not.toBe(session2.id);
Date.now = originalNow;
});
test("sets creation and update timestamps", () => {
const result = SessionUtils.createDefaultSession();
expect(result.createdAt).toBeTruthy();
expect(result.updatedAt).toBeTruthy();
expect(typeof result.createdAt).toBe("number");
expect(typeof result.updatedAt).toBe("number");
});
});
describe("deleteSession", () => {
test("deletes session and returns deleted session info", () => {
localStorageMock.setItem.mockClear();
localStorageMock.getItem.mockImplementation(key => {
if (key === "chat-playground-sessions") {
return JSON.stringify(mockSessions);
}
if (key === "chat-playground-current-session") {
return "utils_session_123";
}
return null;
});
const result = SessionUtils.deleteSession("utils_session_123");
expect(result.deletedSession).toEqual(mockSession);
expect(result.remainingSessions).toHaveLength(0);
expect(localStorageMock.setItem).toHaveBeenCalledWith(
"chat-playground-sessions",
"[]"
);
});
test("removes current session key when deleting current session", () => {
localStorageMock.getItem.mockImplementation(key => {
if (key === "chat-playground-sessions") {
return JSON.stringify(mockSessions);
}
if (key === "chat-playground-current-session") {
return "utils_session_123";
}
return null;
});
SessionUtils.deleteSession("utils_session_123");
expect(localStorageMock.removeItem).toHaveBeenCalledWith(
"chat-playground-current-session"
);
});
test("does not remove current session key when deleting different session", () => {
localStorageMock.getItem.mockImplementation(key => {
if (key === "chat-playground-sessions") {
return JSON.stringify([
mockSession,
{ ...mockSession, id: "other_session" },
]);
}
if (key === "chat-playground-current-session") {
return "utils_session_123";
}
return null;
});
SessionUtils.deleteSession("other_session");
expect(localStorageMock.removeItem).not.toHaveBeenCalledWith(
"chat-playground-current-session"
);
});
test("returns null for non-existent session", () => {
localStorageMock.getItem.mockImplementation(key => {
if (key === "chat-playground-sessions") {
return JSON.stringify(mockSessions);
}
return null;
});
const result = SessionUtils.deleteSession("non_existent");
expect(result.deletedSession).toBeNull();
expect(result.remainingSessions).toEqual(mockSessions);
});
test("handles corrupted sessions data gracefully", () => {
localStorageMock.getItem.mockReturnValue("invalid json");
const consoleSpy = jest.spyOn(console, "error").mockImplementation();
const result = SessionUtils.deleteSession("any_session");
expect(result.deletedSession).toBeNull();
expect(result.remainingSessions).toEqual([]);
expect(consoleSpy).toHaveBeenCalledWith(
"Error parsing JSON:",
expect.any(Error)
);
consoleSpy.mockRestore();
});
});
});

View file

@ -0,0 +1,341 @@
"use client";
import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Input } from "@/components/ui/input";
import { Card } from "@/components/ui/card";
import { Trash2 } from "lucide-react";
import type { Message } from "@/components/chat-playground/chat-message";
interface ChatSession {
id: string;
name: string;
messages: Message[];
selectedModel: string;
selectedVectorDb: string;
systemMessage: string;
createdAt: number;
updatedAt: number;
}
interface SessionManagerProps {
currentSession: ChatSession | null;
onSessionChange: (session: ChatSession) => void;
onNewSession: () => void;
}
const SESSIONS_STORAGE_KEY = "chat-playground-sessions";
const CURRENT_SESSION_KEY = "chat-playground-current-session";
// ensures this only happens client side
const safeLocalStorage = {
getItem: (key: string): string | null => {
if (typeof window === "undefined") return null;
try {
return localStorage.getItem(key);
} catch (err) {
console.error("Error accessing localStorage:", err);
return null;
}
},
setItem: (key: string, value: string): void => {
if (typeof window === "undefined") return;
try {
localStorage.setItem(key, value);
} catch (err) {
console.error("Error writing to localStorage:", err);
}
},
removeItem: (key: string): void => {
if (typeof window === "undefined") return;
try {
localStorage.removeItem(key);
} catch (err) {
console.error("Error removing from localStorage:", err);
}
},
};
function safeJsonParse<T>(jsonString: string | null, fallback: T): T {
if (!jsonString) return fallback;
try {
return JSON.parse(jsonString) as T;
} catch (err) {
console.error("Error parsing JSON:", err);
return fallback;
}
}
const generateSessionId = (): string => {
return globalThis.crypto.randomUUID();
};
export function SessionManager({
currentSession,
onSessionChange,
}: SessionManagerProps) {
const [sessions, setSessions] = useState<ChatSession[]>([]);
const [showCreateForm, setShowCreateForm] = useState(false);
const [newSessionName, setNewSessionName] = useState("");
useEffect(() => {
const savedSessions = safeLocalStorage.getItem(SESSIONS_STORAGE_KEY);
const sessions = safeJsonParse<ChatSession[]>(savedSessions, []);
setSessions(sessions);
}, []);
const saveSessions = (updatedSessions: ChatSession[]) => {
setSessions(updatedSessions);
safeLocalStorage.setItem(
SESSIONS_STORAGE_KEY,
JSON.stringify(updatedSessions)
);
};
const createNewSession = () => {
const sessionName =
newSessionName.trim() || `Session ${sessions.length + 1}`;
const newSession: ChatSession = {
id: generateSessionId(),
name: sessionName,
messages: [],
selectedModel: currentSession?.selectedModel || "",
selectedVectorDb: currentSession?.selectedVectorDb || "",
systemMessage:
currentSession?.systemMessage || "You are a helpful assistant.",
createdAt: Date.now(),
updatedAt: Date.now(),
};
const updatedSessions = [...sessions, newSession];
saveSessions(updatedSessions);
safeLocalStorage.setItem(CURRENT_SESSION_KEY, newSession.id);
onSessionChange(newSession);
setNewSessionName("");
setShowCreateForm(false);
};
const switchToSession = (sessionId: string) => {
const session = sessions.find(s => s.id === sessionId);
if (session) {
safeLocalStorage.setItem(CURRENT_SESSION_KEY, sessionId);
onSessionChange(session);
}
};
const deleteSession = (sessionId: string) => {
if (sessions.length <= 1) {
return;
}
if (
confirm(
"Are you sure you want to delete this session? This action cannot be undone."
)
) {
const updatedSessions = sessions.filter(s => s.id !== sessionId);
saveSessions(updatedSessions);
if (currentSession?.id === sessionId) {
const newCurrentSession = updatedSessions[0] || null;
if (newCurrentSession) {
safeLocalStorage.setItem(CURRENT_SESSION_KEY, newCurrentSession.id);
onSessionChange(newCurrentSession);
} else {
safeLocalStorage.removeItem(CURRENT_SESSION_KEY);
const defaultSession = SessionUtils.createDefaultSession();
saveSessions([defaultSession]);
safeLocalStorage.setItem(CURRENT_SESSION_KEY, defaultSession.id);
onSessionChange(defaultSession);
}
}
}
};
useEffect(() => {
if (currentSession) {
setSessions(prevSessions => {
const updatedSessions = prevSessions.map(session =>
session.id === currentSession.id ? currentSession : session
);
if (!prevSessions.find(s => s.id === currentSession.id)) {
updatedSessions.push(currentSession);
}
safeLocalStorage.setItem(
SESSIONS_STORAGE_KEY,
JSON.stringify(updatedSessions)
);
return updatedSessions;
});
}
}, [currentSession]);
return (
<div className="relative">
<div className="flex items-center gap-2">
<Select
value={currentSession?.id || ""}
onValueChange={switchToSession}
>
<SelectTrigger className="w-[200px]">
<SelectValue placeholder="Select Session" />
</SelectTrigger>
<SelectContent>
{sessions.map(session => (
<SelectItem key={session.id} value={session.id}>
{session.name}
</SelectItem>
))}
</SelectContent>
</Select>
<Button
onClick={() => setShowCreateForm(true)}
variant="outline"
size="sm"
>
+ New
</Button>
{currentSession && sessions.length > 1 && (
<Button
onClick={() => deleteSession(currentSession.id)}
variant="outline"
size="sm"
className="text-destructive hover:text-destructive hover:bg-destructive/10"
title="Delete current session"
>
<Trash2 className="h-3 w-3" />
</Button>
)}
</div>
{showCreateForm && (
<Card className="absolute top-full left-0 mt-2 p-4 space-y-3 w-80 z-50 bg-background border shadow-lg">
<h3 className="text-md font-semibold">Create New Session</h3>
<Input
value={newSessionName}
onChange={e => setNewSessionName(e.target.value)}
placeholder="Session name (optional)"
onKeyDown={e => {
if (e.key === "Enter") {
createNewSession();
} else if (e.key === "Escape") {
setShowCreateForm(false);
setNewSessionName("");
}
}}
/>
<div className="flex gap-2">
<Button onClick={createNewSession} className="flex-1">
Create
</Button>
<Button
variant="outline"
onClick={() => {
setShowCreateForm(false);
setNewSessionName("");
}}
className="flex-1"
>
Cancel
</Button>
</div>
</Card>
)}
{currentSession && sessions.length > 1 && (
<div className="absolute top-full left-0 mt-1 text-xs text-gray-500 whitespace-nowrap">
{sessions.length} sessions Current: {currentSession.name}
{currentSession.messages.length > 0 &&
`${currentSession.messages.length} messages`}
</div>
)}
</div>
);
}
export const SessionUtils = {
loadCurrentSession: (): ChatSession | null => {
const currentSessionId = safeLocalStorage.getItem(CURRENT_SESSION_KEY);
const savedSessions = safeLocalStorage.getItem(SESSIONS_STORAGE_KEY);
if (currentSessionId && savedSessions) {
const sessions = safeJsonParse<ChatSession[]>(savedSessions, []);
return sessions.find(s => s.id === currentSessionId) || null;
}
return null;
},
saveCurrentSession: (session: ChatSession) => {
const savedSessions = safeLocalStorage.getItem(SESSIONS_STORAGE_KEY);
const sessions = safeJsonParse<ChatSession[]>(savedSessions, []);
const existingIndex = sessions.findIndex(s => s.id === session.id);
if (existingIndex >= 0) {
sessions[existingIndex] = { ...session, updatedAt: Date.now() };
} else {
sessions.push({
...session,
createdAt: Date.now(),
updatedAt: Date.now(),
});
}
safeLocalStorage.setItem(SESSIONS_STORAGE_KEY, JSON.stringify(sessions));
safeLocalStorage.setItem(CURRENT_SESSION_KEY, session.id);
},
createDefaultSession: (
inheritModel?: string,
inheritVectorDb?: string
): ChatSession => ({
id: generateSessionId(),
name: "Default Session",
messages: [],
selectedModel: inheritModel || "",
selectedVectorDb: inheritVectorDb || "",
systemMessage: "You are a helpful assistant.",
createdAt: Date.now(),
updatedAt: Date.now(),
}),
deleteSession: (
sessionId: string
): {
deletedSession: ChatSession | null;
remainingSessions: ChatSession[];
} => {
const savedSessions = safeLocalStorage.getItem(SESSIONS_STORAGE_KEY);
const sessions = safeJsonParse<ChatSession[]>(savedSessions, []);
const sessionToDelete = sessions.find(s => s.id === sessionId);
const remainingSessions = sessions.filter(s => s.id !== sessionId);
safeLocalStorage.setItem(
SESSIONS_STORAGE_KEY,
JSON.stringify(remainingSessions)
);
const currentSessionId = safeLocalStorage.getItem(CURRENT_SESSION_KEY);
if (currentSessionId === sessionId) {
safeLocalStorage.removeItem(CURRENT_SESSION_KEY);
}
return { deletedSession: sessionToDelete || null, remainingSessions };
},
};