refactor: code review improvements — fix bugs, extract shared utilities, add README
- Fix reactivity bug: use SvelteMap instead of Map in sessions store - Fix theme listener memory leak: guard against double-init, return cleanup function - Fix transport singleton ignoring different endpoints - Fix form/button type mismatch in MessageInput - Add safer retry validation in chat page - Extract shared utilities: date formatting, session config check, result source config - Extract shared components: Backdrop, PageHeader - Extract orchestration composable from chat page (310→85 lines of script) - Consolidate AuditTimeline switch functions into config record - Move sample data to dedicated module - Add dark mode support for LineageTree SVG colors - Memoize leaf count computation in LineageTree - Update README with usage guide and project structure Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -3,7 +3,6 @@
|
||||
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 { OverrideLevel } from '$lib/proto/llm_multiverse/v1/common_pb';
|
||||
import type { SessionConfig } from '$lib/proto/llm_multiverse/v1/orchestrator_pb';
|
||||
import { SessionConfigSchema } from '$lib/proto/llm_multiverse/v1/orchestrator_pb';
|
||||
@@ -17,20 +16,11 @@
|
||||
import ConfigSidebar from '$lib/components/ConfigSidebar.svelte';
|
||||
import ThemeToggle from '$lib/components/ThemeToggle.svelte';
|
||||
import ConnectionStatus from '$lib/components/ConnectionStatus.svelte';
|
||||
import { processRequest, OrchestratorError, friendlyMessage } from '$lib/services/orchestrator';
|
||||
import { OrchestrationState } from '$lib/proto/llm_multiverse/v1/orchestrator_pb';
|
||||
import { sessionStore } from '$lib/stores/sessions.svelte';
|
||||
import { memoryStore } from '$lib/stores/memory.svelte';
|
||||
import { auditStore } from '$lib/stores/audit.svelte';
|
||||
import { toastStore } from '$lib/stores/toast.svelte';
|
||||
import { isNonDefaultConfig } from '$lib/utils/sessionConfig';
|
||||
import { createOrchestration } from '$lib/composables/useOrchestration.svelte';
|
||||
|
||||
let messages: ChatMessage[] = $state([]);
|
||||
let isStreaming = $state(false);
|
||||
let error: string | null = $state(null);
|
||||
let lastFailedContent: string | null = $state(null);
|
||||
let orchestrationState: OrchestrationState = $state(OrchestrationState.UNSPECIFIED);
|
||||
let intermediateResult: string = $state('');
|
||||
let finalResult: SubagentResult | null = $state(null);
|
||||
let sessionConfig: SessionConfig = $state(
|
||||
create(SessionConfigSchema, { overrideLevel: OverrideLevel.NONE })
|
||||
);
|
||||
@@ -40,11 +30,8 @@
|
||||
const memoryHref = resolveRoute('/memory');
|
||||
const auditHref = resolveRoute('/audit');
|
||||
|
||||
const isNonDefaultConfig = $derived(
|
||||
sessionConfig.overrideLevel !== OverrideLevel.NONE ||
|
||||
sessionConfig.disabledTools.length > 0 ||
|
||||
sessionConfig.grantedPermissions.length > 0
|
||||
);
|
||||
const orchestration = createOrchestration();
|
||||
const hasNonDefaultConfig = $derived(isNonDefaultConfig(sessionConfig));
|
||||
|
||||
function navigateToSession(sessionId: string, replace = false) {
|
||||
const url = `${resolveRoute('/chat')}?session=${sessionId}`;
|
||||
@@ -64,8 +51,7 @@
|
||||
function handleNewChat() {
|
||||
const session = sessionStore.createSession();
|
||||
messages = [];
|
||||
error = null;
|
||||
finalResult = null;
|
||||
orchestration.reset();
|
||||
navigateToSession(session.id);
|
||||
}
|
||||
|
||||
@@ -74,109 +60,20 @@
|
||||
const session = sessionStore.activeSession;
|
||||
if (session) {
|
||||
messages = [...session.messages];
|
||||
error = null;
|
||||
finalResult = null;
|
||||
orchestration.reset();
|
||||
navigateToSession(id);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSend(content: string) {
|
||||
error = null;
|
||||
lastFailedContent = null;
|
||||
orchestrationState = OrchestrationState.UNSPECIFIED;
|
||||
intermediateResult = '';
|
||||
finalResult = null;
|
||||
|
||||
const sessionId = sessionStore.activeSessionId!;
|
||||
let lastAuditState = OrchestrationState.UNSPECIFIED;
|
||||
|
||||
const userMessage: ChatMessage = {
|
||||
id: crypto.randomUUID(),
|
||||
role: 'user',
|
||||
content,
|
||||
timestamp: new Date()
|
||||
};
|
||||
messages.push(userMessage);
|
||||
|
||||
const assistantMessage: ChatMessage = {
|
||||
id: crypto.randomUUID(),
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
timestamp: new Date()
|
||||
};
|
||||
messages.push(assistantMessage);
|
||||
|
||||
sessionStore.updateMessages(sessionId, messages);
|
||||
isStreaming = true;
|
||||
|
||||
try {
|
||||
for await (const response of processRequest(sessionId, content, sessionConfig)) {
|
||||
orchestrationState = response.state;
|
||||
|
||||
// Capture state changes to the audit log
|
||||
if (response.state !== lastAuditState) {
|
||||
const stateLabel = OrchestrationState[response.state] ?? String(response.state);
|
||||
auditStore.addEvent(sessionId, {
|
||||
eventType: 'state_change',
|
||||
details: response.message || `State changed to ${stateLabel}`,
|
||||
state: stateLabel
|
||||
});
|
||||
lastAuditState = response.state;
|
||||
}
|
||||
|
||||
if (response.intermediateResult) {
|
||||
intermediateResult = response.intermediateResult;
|
||||
}
|
||||
if (response.finalResult) {
|
||||
finalResult = response.finalResult;
|
||||
if (response.finalResult.newMemoryCandidates.length > 0) {
|
||||
memoryStore.addCandidates(
|
||||
sessionId,
|
||||
response.finalResult.newMemoryCandidates.map((mc) => ({
|
||||
content: mc.content,
|
||||
source: mc.source,
|
||||
confidence: mc.confidence
|
||||
}))
|
||||
);
|
||||
}
|
||||
}
|
||||
const idx = messages.length - 1;
|
||||
messages[idx] = {
|
||||
...messages[idx],
|
||||
content: response.message
|
||||
};
|
||||
}
|
||||
} catch (err) {
|
||||
const friendlyMsg =
|
||||
err instanceof OrchestratorError
|
||||
? friendlyMessage(err.code)
|
||||
: 'An unexpected error occurred';
|
||||
error = friendlyMsg;
|
||||
lastFailedContent = content;
|
||||
toastStore.addToast({ message: friendlyMsg, type: 'error' });
|
||||
auditStore.addEvent(sessionId, {
|
||||
eventType: 'error',
|
||||
details: friendlyMsg
|
||||
});
|
||||
const idx = messages.length - 1;
|
||||
messages[idx] = {
|
||||
...messages[idx],
|
||||
content: `\u26A0 ${friendlyMsg}`
|
||||
};
|
||||
} finally {
|
||||
isStreaming = false;
|
||||
sessionStore.updateMessages(sessionId, messages);
|
||||
}
|
||||
messages = await orchestration.send(sessionId, content, sessionConfig, messages);
|
||||
}
|
||||
|
||||
function handleRetry() {
|
||||
if (!lastFailedContent) return;
|
||||
const content = lastFailedContent;
|
||||
// Remove the failed assistant message before retrying
|
||||
if (messages.length >= 2) {
|
||||
messages = messages.slice(0, -2);
|
||||
}
|
||||
handleSend(content);
|
||||
const sessionId = sessionStore.activeSessionId!;
|
||||
const result = orchestration.retry(sessionId, sessionConfig, messages);
|
||||
messages = result.messages;
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -240,7 +137,7 @@
|
||||
class="flex min-h-[44px] min-w-[44px] items-center justify-center gap-1 rounded-lg px-2.5 py-1.5 text-sm md:min-h-0 md:min-w-0
|
||||
{showConfig ? 'bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-300' : 'bg-gray-100 text-gray-700 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600'}"
|
||||
>
|
||||
{#if isNonDefaultConfig}
|
||||
{#if hasNonDefaultConfig}
|
||||
<span class="h-2 w-2 rounded-full bg-amber-500"></span>
|
||||
{/if}
|
||||
<span class="hidden sm:inline">Config</span>
|
||||
@@ -255,12 +152,12 @@
|
||||
|
||||
<MessageList {messages} />
|
||||
|
||||
{#if isStreaming}
|
||||
<OrchestrationProgress state={orchestrationState} />
|
||||
<ThinkingSection content={intermediateResult} />
|
||||
{#if orchestration.isStreaming}
|
||||
<OrchestrationProgress state={orchestration.orchestrationState} />
|
||||
<ThinkingSection content={orchestration.intermediateResult} />
|
||||
{/if}
|
||||
|
||||
{#if isStreaming && messages.length > 0 && messages[messages.length - 1].content === ''}
|
||||
{#if orchestration.isStreaming && messages.length > 0 && messages[messages.length - 1].content === ''}
|
||||
<div class="flex justify-start px-4 pb-2">
|
||||
<div class="flex items-center gap-1.5 rounded-2xl bg-gray-200 dark:bg-gray-700 px-4 py-2.5">
|
||||
<span class="h-2 w-2 animate-bounce rounded-full bg-gray-500 dark:bg-gray-400 [animation-delay:0ms]"
|
||||
@@ -275,18 +172,18 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if finalResult && !isStreaming}
|
||||
<FinalResult result={finalResult} />
|
||||
{#if orchestration.finalResult && !orchestration.isStreaming}
|
||||
<FinalResult result={orchestration.finalResult} />
|
||||
{/if}
|
||||
|
||||
{#if error}
|
||||
{#if orchestration.error}
|
||||
<div class="mx-4 mb-2 flex items-center justify-between gap-3 rounded-lg bg-red-50 dark:bg-red-900/30 px-4 py-2 text-sm text-red-600 dark:text-red-400">
|
||||
<span>{error}</span>
|
||||
{#if lastFailedContent}
|
||||
<span>{orchestration.error}</span>
|
||||
{#if orchestration.lastFailedContent}
|
||||
<button
|
||||
type="button"
|
||||
onclick={handleRetry}
|
||||
disabled={isStreaming}
|
||||
disabled={orchestration.isStreaming}
|
||||
class="shrink-0 rounded-md bg-red-100 px-3 py-1 text-xs font-medium text-red-700 hover:bg-red-200 dark:bg-red-800/50 dark:text-red-300 dark:hover:bg-red-800 disabled:opacity-50"
|
||||
>
|
||||
Retry
|
||||
@@ -295,7 +192,7 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<MessageInput onSend={handleSend} disabled={isStreaming} />
|
||||
<MessageInput onSend={handleSend} disabled={orchestration.isStreaming} />
|
||||
</div>
|
||||
|
||||
{#if showConfig}
|
||||
|
||||
Reference in New Issue
Block a user