feat: add session creation and ID management with localStorage

- Session store with UUID v4 generation and localStorage persistence
- Session ID in URL params (?session=<id>) for deep linking
- "New Chat" button for creating fresh sessions
- Message history persisted per session
- Session title auto-generated from first user message

Closes #11

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
shahondin1624
2026-03-12 11:52:19 +01:00
parent 9613a5ad5b
commit 247abfe32c
4 changed files with 165 additions and 2 deletions

View File

@@ -12,3 +12,4 @@
| #8 | Orchestration state progress indicator | COMPLETED | [issue-008.md](issue-008.md) |
| #9 | Intermediate results display | COMPLETED | [issue-009.md](issue-009.md) |
| #10 | Final result rendering with artifacts | COMPLETED | [issue-010.md](issue-010.md) |
| #11 | Session creation and ID management | COMPLETED | [issue-011.md](issue-011.md) |

View File

@@ -0,0 +1,17 @@
---
---
# Issue #11: Session creation and ID management
**Status:** COMPLETED
**Issue:** https://git.shahondin1624.de/llm-multiverse/llm-multiverse-ui/issues/11
**Branch:** `feature/issue-11-session-management`
## Acceptance Criteria
- [x] UUID v4 session ID generated on new chat creation
- [x] Active session ID persisted in URL params (?session=<id>)
- [x] Session ID also stored in localStorage for recovery
- [x] "New Chat" button creates a fresh session
- [x] Switching sessions updates URL and loads correct message history
- [x] Session ID passed to ProcessRequest gRPC calls

View File

@@ -0,0 +1,109 @@
import type { ChatMessage } from '$lib/types';
export interface Session {
id: string;
title: string;
messages: ChatMessage[];
createdAt: Date;
}
const STORAGE_KEY = 'llm-multiverse-sessions';
const ACTIVE_SESSION_KEY = 'llm-multiverse-active-session';
function loadSessions(): Map<string, Session> {
if (typeof localStorage === 'undefined') return new Map();
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return new Map();
const arr: [string, Session][] = JSON.parse(raw);
return new Map(
arr.map(([id, s]) => [
id,
{ ...s, createdAt: new Date(s.createdAt), messages: s.messages.map(m => ({ ...m, timestamp: new Date(m.timestamp) })) }
])
);
} catch {
return new Map();
}
}
function saveSessions(sessions: Map<string, Session>) {
if (typeof localStorage === 'undefined') return;
localStorage.setItem(STORAGE_KEY, JSON.stringify([...sessions.entries()]));
}
function loadActiveSessionId(): string | null {
if (typeof localStorage === 'undefined') return null;
return localStorage.getItem(ACTIVE_SESSION_KEY);
}
function saveActiveSessionId(id: string) {
if (typeof localStorage === 'undefined') return;
localStorage.setItem(ACTIVE_SESSION_KEY, id);
}
function createSessionStore() {
const sessions = $state<Map<string, Session>>(loadSessions());
let activeSessionId = $state<string | null>(loadActiveSessionId());
function createSession(id?: string): Session {
const session: Session = {
id: id ?? crypto.randomUUID(),
title: 'New Chat',
messages: [],
createdAt: new Date()
};
sessions.set(session.id, session);
activeSessionId = session.id;
saveSessions(sessions);
saveActiveSessionId(session.id);
return session;
}
function getOrCreateSession(id?: string): Session {
if (id && sessions.has(id)) {
activeSessionId = id;
saveActiveSessionId(id);
return sessions.get(id)!;
}
return createSession(id);
}
function updateMessages(sessionId: string, messages: ChatMessage[]) {
const session = sessions.get(sessionId);
if (!session) return;
session.messages = messages;
// Update title from first user message if still default
if (session.title === 'New Chat') {
const firstUser = messages.find(m => m.role === 'user');
if (firstUser) {
session.title = firstUser.content.slice(0, 50) + (firstUser.content.length > 50 ? '...' : '');
}
}
sessions.set(sessionId, session);
saveSessions(sessions);
}
function switchSession(id: string) {
if (sessions.has(id)) {
activeSessionId = id;
saveActiveSessionId(id);
}
}
function getAllSessions(): Session[] {
return [...sessions.values()].sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
}
return {
get activeSessionId() { return activeSessionId; },
get activeSession() { return activeSessionId ? sessions.get(activeSessionId) ?? null : null; },
createSession,
getOrCreateSession,
updateMessages,
switchSession,
getAllSessions
};
}
export const sessionStore = createSessionStore();

View File

@@ -1,4 +1,7 @@
<script lang="ts">
import { page } from '$app/stores';
import { goto } from '$app/navigation';
import { resolveRoute } from '$app/paths';
import type { ChatMessage } from '$lib/types';
import type { SubagentResult } from '$lib/proto/llm_multiverse/v1/common_pb';
import MessageList from '$lib/components/MessageList.svelte';
@@ -8,21 +11,45 @@
import FinalResult from '$lib/components/FinalResult.svelte';
import { processRequest, OrchestratorError } from '$lib/services/orchestrator';
import { OrchestrationState } from '$lib/proto/llm_multiverse/v1/orchestrator_pb';
import { sessionStore } from '$lib/stores/sessions.svelte';
let messages: ChatMessage[] = $state([]);
let isStreaming = $state(false);
let error: string | null = $state(null);
let sessionId = $state(crypto.randomUUID());
let orchestrationState: OrchestrationState = $state(OrchestrationState.UNSPECIFIED);
let intermediateResult: string = $state('');
let finalResult: SubagentResult | null = $state(null);
// Initialize session from URL or create new one
$effect(() => {
const sessionParam = $page.url.searchParams.get('session');
const session = sessionStore.getOrCreateSession(sessionParam ?? undefined);
messages = [...session.messages];
if (!sessionParam || sessionParam !== session.id) {
const url = `${resolveRoute('/chat')}?session=${session.id}`;
// eslint-disable-next-line svelte/no-navigation-without-resolve
goto(url, { replaceState: true });
}
});
function handleNewChat() {
const session = sessionStore.createSession();
messages = [];
error = null;
finalResult = null;
const url = `${resolveRoute('/chat')}?session=${session.id}`;
// eslint-disable-next-line svelte/no-navigation-without-resolve
goto(url);
}
async function handleSend(content: string) {
error = null;
orchestrationState = OrchestrationState.UNSPECIFIED;
intermediateResult = '';
finalResult = null;
const sessionId = sessionStore.activeSessionId!;
const userMessage: ChatMessage = {
id: crypto.randomUUID(),
role: 'user',
@@ -39,6 +66,7 @@
};
messages.push(assistantMessage);
sessionStore.updateMessages(sessionId, messages);
isStreaming = true;
try {
@@ -69,13 +97,21 @@
};
} finally {
isStreaming = false;
sessionStore.updateMessages(sessionId, messages);
}
}
</script>
<div class="flex h-screen flex-col">
<header class="border-b border-gray-200 bg-white px-4 py-3">
<header class="flex items-center justify-between border-b border-gray-200 bg-white px-4 py-3">
<h1 class="text-lg font-semibold text-gray-900">Chat</h1>
<button
type="button"
onclick={handleNewChat}
class="rounded-lg bg-gray-100 px-3 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-200"
>
New Chat
</button>
</header>
<MessageList {messages} />