Compare commits

...

10 Commits

Author SHA1 Message Date
6f83311d94 Merge pull request 'feat: display inference statistics in chat UI' (#45) from feature/issue-43-inference-stats into main
Merge pull request 'feat: display inference statistics in chat UI' (#45)
2026-03-13 14:50:35 +01:00
shahondin1624
36731aac1d chore: mark issue #43 plan as COMPLETED
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 14:46:47 +01:00
shahondin1624
3d85cc6b8c feat: add aria attributes to context utilization progress bar
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 14:46:35 +01:00
shahondin1624
52eaf661c4 feat: display inference statistics in chat UI
Add InferenceStats proto message and InferenceStatsPanel component that
displays token counts, throughput, and context window utilization as a
collapsible panel below assistant messages after orchestration completes.

Closes #43

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 14:44:12 +01:00
e93158f670 Merge pull request 'feat: structured artifact rendering, UX improvements' (#44) from feat/structured-artifact-passthrough into main 2026-03-12 23:14:28 +01:00
shahondin1624
2c6c961e08 feat: structured artifact rendering, UX improvements
- Render structured artifacts from agent results with type-aware
  formatting: code blocks with syntax highlighting and copy button,
  terminal-style command output, search result cards, and text findings
- Make FinalResult panel collapsible (default collapsed) with scrollable
  content (max-h-96) to prevent dominating the chat view
- Add clickable URL detection in summaries and artifact content
- Fix code block contrast for both light and dark mode
- Animate progress bar with pulse ring on active step and gradient
  shimmer on connecting lines
- Fix tab-switching bug: use module-level orchestrationStore singleton
  so orchestration state survives route navigation
- Remove sample/demo data seeding and clean up persisted localStorage
  entries from previous sample sessions
- Remove showSampleBadge prop from PageHeader
- Regenerate proto types for new Artifact message and ArtifactType enum
- Update README project structure (remove deleted data/ directory)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 23:13:33 +01:00
cfd338028a Merge pull request 'fix: prevent session creation loop without backend' (#42) from fix/session-creation-loop into main 2026-03-12 16:41:41 +01:00
shahondin1624
a5bc38cb65 fix: prevent session creation loop when running without backend
Make getOrCreateSession idempotent by returning the existing active
session when called with no ID, instead of always creating a new one.
Use untrack() in the $effect to sever SvelteMap dependency so it only
re-runs on $page changes. Disable SSR on client-only routes, reduce
preload aggressiveness, and skip retries when already disconnected.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 16:41:08 +01:00
d7d1d9fd57 Merge pull request 'refactor: code review improvements' (#41) from refactor/code-review-improvements into main 2026-03-12 13:48:57 +01:00
shahondin1624
38f5f31b92 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>
2026-03-12 13:48:06 +01:00
36 changed files with 1227 additions and 692 deletions

View File

@@ -1,3 +1,97 @@
# llm-multiverse-ui # llm-multiverse-ui
Web frontend for the llm-multiverse orchestration system Web frontend for the **llm-multiverse** orchestration system. Built with SvelteKit 5, TypeScript, Tailwind CSS v4, and gRPC-Web (Connect).
## Prerequisites
- Node.js 20+
- A running llm-multiverse gRPC backend (the UI proxies requests through Vite/your production reverse proxy)
## Getting Started
```bash
# Install dependencies
npm install
# Generate protobuf TypeScript definitions (only needed after .proto changes)
npm run generate
# Start the dev server
npm run dev
```
The app starts at `http://localhost:5173` by default.
## Scripts
| Command | Description |
| ------------------- | ------------------------------------------------ |
| `npm run dev` | Start Vite dev server with HMR |
| `npm run build` | Production build |
| `npm run preview` | Preview the production build locally |
| `npm run check` | Run svelte-check for TypeScript/Svelte errors |
| `npm run lint` | Run ESLint |
| `npm run format` | Format code with Prettier |
| `npm run generate` | Regenerate protobuf TypeScript from `.proto` files |
## Using the UI
### Landing Page
The root page (`/`) links to every section of the app.
### Chat (`/chat`)
The main interface for interacting with the orchestrator.
- **Sessions** are listed in the left sidebar. Click **+ New Chat** to start a session, or select an existing one. On mobile, tap the hamburger menu to open the sidebar.
- Type a message and press **Enter** (or the **Send** button) to send it. While the orchestrator is processing, a progress indicator and thinking section show the current state.
- **Session Config** (gear icon / "Config" button) opens a right sidebar where you can adjust the override level, disable specific tools, grant permissions, and save/load presets.
- If a request fails, an error banner appears with a **Retry** button.
- Navigation links to Lineage, Memory, and Audit are in the header (hidden on small screens).
### Agent Lineage (`/lineage`)
Visualizes the agent spawn tree as an interactive SVG diagram.
- Click a node to view agent details (ID, type, depth, children) in a side panel.
- A legend at the bottom shows agent type colors.
- Supports dark mode with theme-aware SVG colors.
### Memory Candidates (`/memory`)
Lists memory candidates captured during orchestration, grouped by session.
- **Source filter** — filter by Tool Output, Model Knowledge, or Web.
- **Confidence slider** — set a minimum confidence threshold.
- Each card shows the candidate content, source badge, and a confidence bar.
### Audit Log (`/audit`)
Timeline view of orchestration events for each session.
- Select a session from the dropdown, then optionally filter by event type (State Change, Tool, Error, Message).
- Events are displayed chronologically with date separators and color-coded badges.
### Theme
Use the theme toggle (sun/moon icon in any header) to cycle between **System**, **Light**, and **Dark** modes. The preference is persisted in localStorage.
## Project Structure
```
src/
lib/
components/ Svelte components (Backdrop, PageHeader, MessageInput, ...)
composables/ Reactive composables (useOrchestration)
proto/ Generated protobuf TypeScript
services/ gRPC client (orchestrator)
stores/ Svelte 5 reactive stores (sessions, audit, memory, theme, ...)
types/ TypeScript types and helpers (lineage, resultSource)
utils/ Shared utilities (date formatting, session config)
routes/
chat/ Chat page
lineage/ Agent lineage visualization
memory/ Memory candidates browser
audit/ Audit log timeline
```

View File

@@ -22,3 +22,4 @@
| #18 | Dark/light theme toggle | COMPLETED | [issue-018.md](issue-018.md) | | #18 | Dark/light theme toggle | COMPLETED | [issue-018.md](issue-018.md) |
| #19 | Responsive layout and mobile support | COMPLETED | [issue-019.md](issue-019.md) | | #19 | Responsive layout and mobile support | COMPLETED | [issue-019.md](issue-019.md) |
| #20 | Error handling and connection status | COMPLETED | [issue-020.md](issue-020.md) | | #20 | Error handling and connection status | COMPLETED | [issue-020.md](issue-020.md) |
| #43 | Display inference statistics in chat UI | COMPLETED | [issue-043.md](issue-043.md) |

View File

@@ -0,0 +1,60 @@
# Issue #43: Display Inference Statistics in Chat UI
**Status:** COMPLETED
**Issue:** [#43](https://git.shahondin1624.de/llm-multiverse/llm-multiverse-ui/issues/43)
**Branch:** `feature/issue-43-inference-stats`
## Overview
Add a collapsible UI panel that displays LLM inference statistics (token counts, context window utilization, throughput) below assistant messages after orchestration completes.
## Phases
### Phase 1: Proto Types
**Files:**
- `proto/upstream/proto/llm_multiverse/v1/common.proto` — Add `InferenceStats` message
- `proto/upstream/proto/llm_multiverse/v1/orchestrator.proto` — Add optional `inference_stats` field to `ProcessRequestResponse`
**InferenceStats message fields:**
- `prompt_tokens` (uint32) — tokens in the prompt
- `completion_tokens` (uint32) — tokens generated
- `total_tokens` (uint32) — sum of prompt + completion
- `context_window_size` (uint32) — model's maximum context length
- `tokens_per_second` (float) — generation throughput
**Then regenerate types:** `npm run generate`
### Phase 2: Orchestration State
**Files:**
- `src/lib/composables/useOrchestration.svelte.ts` — Extract `inferenceStats` from response, expose via store getter
### Phase 3: InferenceStatsPanel Component
**Files:**
- `src/lib/components/InferenceStatsPanel.svelte` — New component
**Design:**
- Follow `<details>` pattern from FinalResult.svelte
- Collapsed by default
- Summary line shows key stat (e.g., total tokens + tokens/sec)
- Expanded content shows all stats in a grid layout
- Context utilization shown as a progress bar
- Blue/indigo color scheme (neutral, info-like)
- Full dark mode support
### Phase 4: Chat Page Integration
**Files:**
- `src/routes/chat/+page.svelte` — Render `InferenceStatsPanel` after `FinalResult` when stats available
## Acceptance Criteria
- [x] InferenceStats proto message defined and TypeScript types generated
- [x] InferenceStatsPanel displays all required metrics
- [x] Panel is collapsible, collapsed by default
- [x] Context utilization shows visual progress bar
- [x] Integrates cleanly into chat page below assistant message
- [x] Dark mode support
- [x] Build, lint, typecheck pass

View File

@@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head% %sveltekit.head%
</head> </head>
<body data-sveltekit-preload-data="hover"> <body data-sveltekit-preload-data="tap">
<div style="display: contents">%sveltekit.body%</div> <div style="display: contents">%sveltekit.body%</div>
</body> </body>
</html> </html>

View File

@@ -1,5 +1,6 @@
<script lang="ts"> <script lang="ts">
import type { AuditEvent } from '$lib/stores/audit.svelte'; import type { AuditEvent, AuditEventType } from '$lib/stores/audit.svelte';
import { formatShortDate } from '$lib/utils/date';
let { events }: { events: AuditEvent[] } = $props(); let { events }: { events: AuditEvent[] } = $props();
@@ -7,53 +8,33 @@
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }); return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
} }
function formatDate(date: Date): string { const eventTypeConfig: Record<AuditEventType, { badge: string; dot: string; label: string }> = {
return date.toLocaleDateString([], { month: 'short', day: 'numeric', year: 'numeric' }); state_change: {
badge: 'bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300',
dot: 'bg-blue-500',
label: 'State Change'
},
tool_invocation: {
badge: 'bg-green-100 dark:bg-green-900/40 text-green-700 dark:text-green-300',
dot: 'bg-green-500',
label: 'Tool'
},
error: {
badge: 'bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300',
dot: 'bg-red-500',
label: 'Error'
},
message: {
badge: 'bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400',
dot: 'bg-gray-400',
label: 'Message'
} }
};
function typeBadgeClasses(eventType: string): string { const defaultEventConfig = { badge: 'bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400', dot: 'bg-gray-400', label: 'Unknown' };
switch (eventType) {
case 'state_change':
return 'bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300';
case 'tool_invocation':
return 'bg-green-100 dark:bg-green-900/40 text-green-700 dark:text-green-300';
case 'error':
return 'bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300';
case 'message':
return 'bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400';
default:
return 'bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400';
}
}
function typeDotClasses(eventType: string): string { function getEventConfig(eventType: string) {
switch (eventType) { return eventTypeConfig[eventType as AuditEventType] ?? defaultEventConfig;
case 'state_change':
return 'bg-blue-500';
case 'tool_invocation':
return 'bg-green-500';
case 'error':
return 'bg-red-500';
case 'message':
return 'bg-gray-400';
default:
return 'bg-gray-400';
}
}
function typeLabel(eventType: string): string {
switch (eventType) {
case 'state_change':
return 'State Change';
case 'tool_invocation':
return 'Tool';
case 'error':
return 'Error';
case 'message':
return 'Message';
default:
return eventType;
}
} }
</script> </script>
@@ -70,18 +51,19 @@
<ol class="space-y-4"> <ol class="space-y-4">
{#each events as event, i (event.id)} {#each events as event, i (event.id)}
{@const showDate = i === 0 || formatDate(event.timestamp) !== formatDate(events[i - 1].timestamp)} {@const showDate = i === 0 || formatShortDate(event.timestamp) !== formatShortDate(events[i - 1].timestamp)}
{@const config = getEventConfig(event.eventType)}
{#if showDate} {#if showDate}
<li class="relative pl-10 pt-2"> <li class="relative pl-10 pt-2">
<span class="text-xs font-medium text-gray-400 dark:text-gray-500">{formatDate(event.timestamp)}</span> <span class="text-xs font-medium text-gray-400 dark:text-gray-500">{formatShortDate(event.timestamp)}</span>
</li> </li>
{/if} {/if}
<li class="group relative flex items-start pl-10"> <li class="group relative flex items-start pl-10">
<!-- Dot on the timeline --> <!-- Dot on the timeline -->
<div <div
class="absolute left-1.5 top-1.5 h-3 w-3 rounded-full ring-2 ring-white dark:ring-gray-900 {typeDotClasses(event.eventType)}" class="absolute left-1.5 top-1.5 h-3 w-3 rounded-full ring-2 ring-white dark:ring-gray-900 {config.dot}"
></div> ></div>
<!-- Event card --> <!-- Event card -->
@@ -91,9 +73,9 @@
<div class="flex flex-wrap items-center gap-2"> <div class="flex flex-wrap items-center gap-2">
<span class="text-xs text-gray-400 dark:text-gray-500">{formatTimestamp(event.timestamp)}</span> <span class="text-xs text-gray-400 dark:text-gray-500">{formatTimestamp(event.timestamp)}</span>
<span <span
class="inline-flex rounded-full px-2 py-0.5 text-xs font-medium {typeBadgeClasses(event.eventType)}" class="inline-flex rounded-full px-2 py-0.5 text-xs font-medium {config.badge}"
> >
{typeLabel(event.eventType)} {config.label}
</span> </span>
{#if event.state} {#if event.state}
<span class="rounded-md bg-blue-50 dark:bg-blue-900/30 px-1.5 py-0.5 text-xs font-mono text-blue-600 dark:text-blue-400"> <span class="rounded-md bg-blue-50 dark:bg-blue-900/30 px-1.5 py-0.5 text-xs font-mono text-blue-600 dark:text-blue-400">

View File

@@ -0,0 +1,12 @@
<script lang="ts">
let { onClose }: { onClose: () => void } = $props();
</script>
<div
class="fixed inset-0 z-40 bg-black/50 md:hidden"
role="button"
tabindex="-1"
onclick={onClose}
onkeydown={(e) => { if (e.key === 'Escape') onClose(); }}
aria-label="Close overlay"
></div>

View File

@@ -4,6 +4,8 @@
import { SessionConfigSchema } from '$lib/proto/llm_multiverse/v1/orchestrator_pb'; import { SessionConfigSchema } from '$lib/proto/llm_multiverse/v1/orchestrator_pb';
import { create } from '@bufbuild/protobuf'; import { create } from '@bufbuild/protobuf';
import { presetStore } from '$lib/stores/presets.svelte'; import { presetStore } from '$lib/stores/presets.svelte';
import { isNonDefaultConfig } from '$lib/utils/sessionConfig';
import Backdrop from '$lib/components/Backdrop.svelte';
let { let {
config, config,
@@ -37,11 +39,7 @@
{ value: OverrideLevel.ALL, label: 'All', description: 'No enforcement' } { value: OverrideLevel.ALL, label: 'All', description: 'No enforcement' }
]; ];
const isNonDefault = $derived( const isNonDefault = $derived(isNonDefaultConfig(config));
config.overrideLevel !== OverrideLevel.NONE ||
config.disabledTools.length > 0 ||
config.grantedPermissions.length > 0
);
function setOverrideLevel(level: OverrideLevel) { function setOverrideLevel(level: OverrideLevel) {
const updated = create(SessionConfigSchema, { const updated = create(SessionConfigSchema, {
@@ -120,16 +118,8 @@
} }
</script> </script>
<!-- Mobile overlay backdrop -->
{#if onClose} {#if onClose}
<div <Backdrop onClose={onClose} />
class="fixed inset-0 z-40 bg-black/50 md:hidden"
role="button"
tabindex="-1"
onclick={onClose}
onkeydown={(e) => { if (e.key === 'Escape') onClose?.(); }}
aria-label="Close config sidebar"
></div>
{/if} {/if}
<aside <aside

View File

@@ -1,6 +1,7 @@
<script lang="ts"> <script lang="ts">
import type { SubagentResult } from '$lib/proto/llm_multiverse/v1/common_pb'; import type { SubagentResult } from '$lib/proto/llm_multiverse/v1/common_pb';
import { ResultStatus, ResultQuality, ResultSource } from '$lib/proto/llm_multiverse/v1/common_pb'; import { ResultStatus, ResultQuality, ArtifactType } from '$lib/proto/llm_multiverse/v1/common_pb';
import { resultSourceConfig } from '$lib/types/resultSource';
let { result }: { result: SubagentResult } = $props(); let { result }: { result: SubagentResult } = $props();
@@ -26,18 +27,34 @@
} }
}); });
const sourceLabel = $derived.by(() => { const sourceBadge = $derived(resultSourceConfig(result.source));
switch (result.source) {
case ResultSource.TOOL_OUTPUT: return 'Tool Output'; const LINE_COLLAPSE_THRESHOLD = 20;
case ResultSource.MODEL_KNOWLEDGE: return 'Model Knowledge';
case ResultSource.WEB: return 'Web'; function contentLineCount(content: string): number {
default: return ''; return content.split('\n').length;
}
const URL_RE = /(https?:\/\/[^\s<>"')\]]+)/g;
function linkify(text: string): string {
return text.replace(URL_RE, '<a href="$1" target="_blank" rel="noopener noreferrer" class="text-blue-600 dark:text-blue-400 underline hover:text-blue-800 dark:hover:text-blue-300 break-all">$1</a>');
}
let copiedIndex: number | null = $state(null);
async function copyToClipboard(content: string, index: number) {
await navigator.clipboard.writeText(content);
copiedIndex = index;
setTimeout(() => {
if (copiedIndex === index) copiedIndex = null;
}, 2000);
} }
});
</script> </script>
<div class="mx-4 mb-3 rounded-xl border {statusConfig.border} {statusConfig.bg} p-4"> <details class="mx-4 mb-3 rounded-xl border {statusConfig.border} {statusConfig.bg}">
<div class="mb-2 flex items-center gap-2"> <summary class="flex cursor-pointer items-center gap-2 px-4 py-2.5 select-none">
<svg class="chevron h-4 w-4 shrink-0 text-gray-500 dark:text-gray-400 transition-transform" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" /></svg>
<span class="rounded-full px-2.5 py-0.5 text-xs font-medium {statusConfig.bg} {statusConfig.text}"> <span class="rounded-full px-2.5 py-0.5 text-xs font-medium {statusConfig.bg} {statusConfig.text}">
{statusConfig.label} {statusConfig.label}
</span> </span>
@@ -46,15 +63,19 @@
{qualityLabel} {qualityLabel}
</span> </span>
{/if} {/if}
{#if sourceLabel} {#if sourceBadge.label !== 'Unspecified'}
<span class="rounded-full bg-purple-100 dark:bg-purple-900/40 px-2.5 py-0.5 text-xs font-medium text-purple-800 dark:text-purple-300"> <span class="rounded-full {sourceBadge.bg} px-2.5 py-0.5 text-xs font-medium {sourceBadge.text}">
{sourceLabel} {sourceBadge.label}
</span> </span>
{/if} {/if}
</div>
{#if result.summary} {#if result.summary}
<p class="text-sm {statusConfig.text}">{result.summary}</p> <span class="ml-1 truncate text-xs {statusConfig.text}">{result.summary}</span>
{/if}
</summary>
<div class="max-h-96 overflow-y-auto border-t {statusConfig.border} px-4 pb-4 pt-3">
{#if result.summary}
<p class="text-sm {statusConfig.text}">{@html linkify(result.summary)}</p>
{/if} {/if}
{#if result.failureReason} {#if result.failureReason}
@@ -64,14 +85,98 @@
{#if result.artifacts.length > 0} {#if result.artifacts.length > 0}
<div class="mt-3 border-t {statusConfig.border} pt-3"> <div class="mt-3 border-t {statusConfig.border} pt-3">
<p class="mb-1.5 text-xs font-medium text-gray-600 dark:text-gray-400">Artifacts</p> <p class="mb-1.5 text-xs font-medium text-gray-600 dark:text-gray-400">Artifacts</p>
<ul class="space-y-1"> <div class="space-y-3">
{#each result.artifacts as artifact (artifact)} {#each result.artifacts as artifact, i (artifact.label + i)}
<li class="flex items-center gap-2 text-sm"> {#if artifact.artifactType === ArtifactType.CODE}
<span class="text-gray-400 dark:text-gray-500">&#128196;</span> <!-- Code artifact: syntax-highlighted block with filename header -->
<span class="font-mono text-xs text-gray-700 dark:text-gray-300">{artifact}</span> <div class="rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
</li> <div class="flex items-center gap-2 bg-gray-100 dark:bg-gray-800 px-3 py-1.5 text-xs">
<span class="text-blue-600 dark:text-blue-400">&#128196;</span>
<span class="font-mono font-medium text-gray-700 dark:text-gray-300">{artifact.label}</span>
<div class="ml-auto flex items-center gap-1.5">
{#if artifact.metadata?.language}
<span class="rounded bg-gray-200 dark:bg-gray-700 px-1.5 py-0.5 text-[10px] text-gray-500 dark:text-gray-400">{artifact.metadata.language}</span>
{/if}
<button
type="button"
onclick={() => copyToClipboard(artifact.content, i)}
class="rounded p-0.5 text-gray-400 hover:bg-gray-200 hover:text-gray-600 dark:text-gray-500 dark:hover:bg-gray-700 dark:hover:text-gray-300 transition-colors"
title="Copy code"
>
{#if copiedIndex === i}
<svg class="h-3.5 w-3.5 text-green-500" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5" /></svg>
{:else}
<svg class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M15.666 3.888A2.25 2.25 0 0 0 13.5 2.25h-3c-1.03 0-1.9.693-2.166 1.638m7.332 0c.055.194.084.4.084.612v0a.75.75 0 0 1-.75.75H9.75a.75.75 0 0 1-.75-.75v0c0-.212.03-.418.084-.612m7.332 0c.646.049 1.288.11 1.927.184 1.1.128 1.907 1.077 1.907 2.185V19.5a2.25 2.25 0 0 1-2.25 2.25H6.75A2.25 2.25 0 0 1 4.5 19.5V6.257c0-1.108.806-2.057 1.907-2.185a48.208 48.208 0 0 1 1.927-.184" /></svg>
{/if}
</button>
</div>
</div>
{#if contentLineCount(artifact.content) > LINE_COLLAPSE_THRESHOLD}
<details>
<summary class="cursor-pointer bg-gray-50 dark:bg-gray-900 px-3 py-1 text-xs text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300">
Show {contentLineCount(artifact.content)} lines
</summary>
<pre class="overflow-x-auto bg-gray-50 dark:bg-gray-900 p-3 text-xs leading-relaxed text-gray-800 dark:text-gray-200"><code class="language-{artifact.metadata?.language ?? ''}">{artifact.content}</code></pre>
</details>
{:else}
<pre class="overflow-x-auto bg-gray-50 dark:bg-gray-900 p-3 text-xs leading-relaxed text-gray-800 dark:text-gray-200"><code class="language-{artifact.metadata?.language ?? ''}">{artifact.content}</code></pre>
{/if}
</div>
{:else if artifact.artifactType === ArtifactType.COMMAND_OUTPUT}
<!-- Command output: terminal-style block -->
<div class="rounded-lg border border-gray-700 dark:border-gray-600 overflow-hidden">
<div class="flex items-center gap-2 bg-gray-800 dark:bg-gray-900 px-3 py-1.5 text-xs">
<span class="text-green-400">&#9654;</span>
<span class="font-mono text-gray-300">{artifact.label}</span>
</div>
{#if contentLineCount(artifact.content) > LINE_COLLAPSE_THRESHOLD}
<details>
<summary class="cursor-pointer bg-gray-900 dark:bg-black px-3 py-1 text-xs text-gray-400 hover:text-gray-200">
Show {contentLineCount(artifact.content)} lines
</summary>
<pre class="overflow-x-auto bg-gray-900 dark:bg-black p-3 font-mono text-xs leading-relaxed text-green-300 dark:text-green-400">{artifact.content}</pre>
</details>
{:else}
<pre class="overflow-x-auto bg-gray-900 dark:bg-black p-3 font-mono text-xs leading-relaxed text-green-300 dark:text-green-400">{artifact.content}</pre>
{/if}
</div>
{:else if artifact.artifactType === ArtifactType.SEARCH_RESULT}
<!-- Search result: card with query title -->
<div class="rounded-lg border border-purple-200 dark:border-purple-800 bg-purple-50 dark:bg-purple-900/20 p-3">
<div class="mb-1 flex items-center gap-2 text-xs">
<span class="text-purple-500">&#128269;</span>
<span class="font-medium text-purple-700 dark:text-purple-300">{artifact.label}</span>
</div>
{#if contentLineCount(artifact.content) > LINE_COLLAPSE_THRESHOLD}
<details>
<summary class="cursor-pointer text-xs text-purple-500 dark:text-purple-400 hover:text-purple-700 dark:hover:text-purple-300">
Show full results
</summary>
<p class="mt-1 whitespace-pre-wrap text-xs text-gray-700 dark:text-gray-300">{@html linkify(artifact.content)}</p>
</details>
{:else}
<p class="whitespace-pre-wrap text-xs text-gray-700 dark:text-gray-300">{@html linkify(artifact.content)}</p>
{/if}
</div>
{:else}
<!-- Text / finding artifact: plain text -->
<div class="flex items-start gap-2 text-sm">
<span class="mt-0.5 text-gray-400 dark:text-gray-500">&#128196;</span>
<span class="text-xs text-gray-700 dark:text-gray-300">{@html linkify(artifact.content)}</span>
</div>
{/if}
{/each} {/each}
</ul> </div>
</div> </div>
{/if} {/if}
</div> </div>
</details>
<style>
details[open] > summary .chevron {
transform: rotate(90deg);
}
</style>

View File

@@ -0,0 +1,94 @@
<script lang="ts">
import type { InferenceStats } from '$lib/proto/llm_multiverse/v1/common_pb';
let { stats }: { stats: InferenceStats } = $props();
const utilizationPct = $derived(
stats.contextWindowSize > 0
? Math.min(100, (stats.totalTokens / stats.contextWindowSize) * 100)
: 0
);
const utilizationColor = $derived.by(() => {
if (utilizationPct >= 90) return { bar: 'bg-red-500', text: 'text-red-700 dark:text-red-400' };
if (utilizationPct >= 70) return { bar: 'bg-amber-500', text: 'text-amber-700 dark:text-amber-400' };
return { bar: 'bg-blue-500', text: 'text-blue-700 dark:text-blue-400' };
});
function formatNumber(n: number): string {
return n.toLocaleString();
}
</script>
<details class="mx-4 mb-3 rounded-xl border border-indigo-200 dark:border-indigo-800 bg-indigo-50 dark:bg-indigo-900/20">
<summary class="flex cursor-pointer items-center gap-2 px-4 py-2.5 select-none">
<svg class="chevron h-4 w-4 shrink-0 text-gray-500 dark:text-gray-400 transition-transform" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" /></svg>
<span class="rounded-full bg-indigo-100 dark:bg-indigo-900/40 px-2.5 py-0.5 text-xs font-medium text-indigo-800 dark:text-indigo-300">
Stats
</span>
<span class="truncate text-xs text-indigo-700 dark:text-indigo-400">
{formatNumber(stats.totalTokens)} tokens
{#if stats.tokensPerSecond > 0}
&middot; {stats.tokensPerSecond.toFixed(1)} tok/s
{/if}
{#if stats.contextWindowSize > 0}
&middot; {utilizationPct.toFixed(0)}% context
{/if}
</span>
</summary>
<div class="border-t border-indigo-200 dark:border-indigo-800 px-4 pb-4 pt-3">
<div class="grid grid-cols-2 gap-x-6 gap-y-3 sm:grid-cols-3">
<div>
<p class="text-[10px] font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">Prompt</p>
<p class="text-sm font-semibold text-gray-900 dark:text-gray-100">{formatNumber(stats.promptTokens)}</p>
</div>
<div>
<p class="text-[10px] font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">Completion</p>
<p class="text-sm font-semibold text-gray-900 dark:text-gray-100">{formatNumber(stats.completionTokens)}</p>
</div>
<div>
<p class="text-[10px] font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">Total</p>
<p class="text-sm font-semibold text-gray-900 dark:text-gray-100">{formatNumber(stats.totalTokens)}</p>
</div>
{#if stats.tokensPerSecond > 0}
<div>
<p class="text-[10px] font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">Throughput</p>
<p class="text-sm font-semibold text-gray-900 dark:text-gray-100">{stats.tokensPerSecond.toFixed(1)} tok/s</p>
</div>
{/if}
{#if stats.contextWindowSize > 0}
<div class="col-span-2">
<p class="text-[10px] font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">Context Window</p>
<p class="text-sm font-semibold text-gray-900 dark:text-gray-100">{formatNumber(stats.contextWindowSize)}</p>
</div>
{/if}
</div>
{#if stats.contextWindowSize > 0}
<div class="mt-3 border-t border-indigo-200 dark:border-indigo-800 pt-3">
<div class="flex items-center justify-between text-xs">
<span class="font-medium text-gray-600 dark:text-gray-400">Context Utilization</span>
<span class="font-semibold {utilizationColor.text}">{utilizationPct.toFixed(1)}%</span>
</div>
<div class="mt-1.5 h-2 w-full overflow-hidden rounded-full bg-gray-200 dark:bg-gray-700">
<div
class="h-full rounded-full transition-all duration-300 {utilizationColor.bar}"
style="width: {utilizationPct}%"
role="progressbar"
aria-valuenow={utilizationPct}
aria-valuemin={0}
aria-valuemax={100}
aria-label="Context window utilization"
></div>
</div>
</div>
{/if}
</div>
</details>
<style>
details[open] > summary .chevron {
transform: rotate(90deg);
}
</style>

View File

@@ -40,12 +40,23 @@
} }
/** /**
* Recursively counts the total number of leaf nodes in a subtree. * Computes leaf counts for every node in a single bottom-up pass.
* A leaf is a node with no children; it counts as 1 vertical slot. * Stores results in a map keyed by node identity.
*/ */
function countLeaves(node: LineageNode): number { function computeLeafCounts(roots: LineageNode[]): Map<LineageNode, number> {
if (node.children.length === 0) return 1; // eslint-disable-next-line svelte/prefer-svelte-reactivity -- internal computation map, not reactive state
return node.children.reduce((sum, child) => sum + countLeaves(child), 0); const counts = new Map<LineageNode, number>();
function walk(node: LineageNode): number {
if (node.children.length === 0) {
counts.set(node, 1);
return 1;
}
const total = node.children.reduce((sum, child) => sum + walk(child), 0);
counts.set(node, total);
return total;
}
for (const root of roots) walk(root);
return counts;
} }
/** /**
@@ -57,7 +68,8 @@
totalWidth: number; totalWidth: number;
totalHeight: number; totalHeight: number;
} { } {
const totalLeaves = roots.reduce((sum, r) => sum + countLeaves(r), 0); const leafCounts = computeLeafCounts(roots);
const totalLeaves = roots.reduce((sum, r) => sum + (leafCounts.get(r) ?? 1), 0);
const totalHeight = totalLeaves * (NODE_HEIGHT + VERTICAL_GAP) - VERTICAL_GAP; const totalHeight = totalLeaves * (NODE_HEIGHT + VERTICAL_GAP) - VERTICAL_GAP;
function positionNode( function positionNode(
@@ -73,7 +85,7 @@
return { node, x, y, children: [] }; return { node, x, y, children: [] };
} }
const childLeafCounts = node.children.map(countLeaves); const childLeafCounts = node.children.map((c) => leafCounts.get(c) ?? 1);
const totalChildLeaves = childLeafCounts.reduce((a, b) => a + b, 0); const totalChildLeaves = childLeafCounts.reduce((a, b) => a + b, 0);
let currentY = startY; let currentY = startY;
@@ -98,7 +110,7 @@
let currentY = 0; let currentY = 0;
const positioned: PositionedNode[] = []; const positioned: PositionedNode[] = [];
for (const root of roots) { for (const root of roots) {
const rootLeaves = countLeaves(root); const rootLeaves = leafCounts.get(root) ?? 1;
const rootHeight = (rootLeaves / totalLeaves) * totalHeight; const rootHeight = (rootLeaves / totalLeaves) * totalHeight;
positioned.push(positionNode(root, 0, currentY, rootHeight)); positioned.push(positionNode(root, 0, currentY, rootHeight));
currentY += rootHeight; currentY += rootHeight;
@@ -222,6 +234,7 @@
<!-- Nodes --> <!-- Nodes -->
{#each allNodes as pn (pn.node.id)} {#each allNodes as pn (pn.node.id)}
{@const colors = agentTypeColor(pn.node.agentType)} {@const colors = agentTypeColor(pn.node.agentType)}
{@const colorSet = themeStore.isDark ? colors.dark : colors.light}
{@const isSelected = selectedNodeId === pn.node.id} {@const isSelected = selectedNodeId === pn.node.id}
<g <g
@@ -241,8 +254,8 @@
height={NODE_HEIGHT} height={NODE_HEIGHT}
rx="8" rx="8"
ry="8" ry="8"
fill={colors.fill} fill={colorSet.fill}
stroke={isSelected ? colors.stroke : defaultStroke} stroke={isSelected ? colorSet.stroke : defaultStroke}
stroke-width={isSelected ? 2.5 : 1.5} stroke-width={isSelected ? 2.5 : 1.5}
/> />
@@ -251,7 +264,7 @@
x={NODE_WIDTH / 2} x={NODE_WIDTH / 2}
y="22" y="22"
text-anchor="middle" text-anchor="middle"
fill={colors.text} fill={colorSet.text}
font-size="12" font-size="12"
font-weight="600" font-weight="600"
> >

View File

@@ -1,21 +1,10 @@
<script lang="ts"> <script lang="ts">
import { ResultSource } from '$lib/proto/llm_multiverse/v1/common_pb';
import type { StoredMemoryCandidate } from '$lib/stores/memory.svelte'; import type { StoredMemoryCandidate } from '$lib/stores/memory.svelte';
import { resultSourceConfig } from '$lib/types/resultSource';
let { candidate }: { candidate: StoredMemoryCandidate } = $props(); let { candidate }: { candidate: StoredMemoryCandidate } = $props();
const sourceBadge = $derived.by(() => { const sourceBadge = $derived(resultSourceConfig(candidate.source));
switch (candidate.source) {
case ResultSource.TOOL_OUTPUT:
return { label: 'Tool Output', bg: 'bg-blue-100 dark:bg-blue-900/40', text: 'text-blue-800 dark:text-blue-300' };
case ResultSource.MODEL_KNOWLEDGE:
return { label: 'Model Knowledge', bg: 'bg-purple-100 dark:bg-purple-900/40', text: 'text-purple-800 dark:text-purple-300' };
case ResultSource.WEB:
return { label: 'Web', bg: 'bg-green-100 dark:bg-green-900/40', text: 'text-green-800 dark:text-green-300' };
default:
return { label: 'Unspecified', bg: 'bg-gray-100 dark:bg-gray-800', text: 'text-gray-800 dark:text-gray-300' };
}
});
const confidencePct = $derived(Math.round(candidate.confidence * 100)); const confidencePct = $derived(Math.round(candidate.confidence * 100));

View File

@@ -36,7 +36,7 @@
</script> </script>
<div class="border-t border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 p-3 md:p-4"> <div class="border-t border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 p-3 md:p-4">
<form onsubmit={handleSubmit} class="flex items-end gap-2"> <form onsubmit={(e) => { e.preventDefault(); handleSubmit(); }} class="flex items-end gap-2">
<textarea <textarea
bind:this={textarea} bind:this={textarea}
bind:value={input} bind:value={input}
@@ -51,8 +51,7 @@
placeholder:text-gray-400 dark:placeholder:text-gray-500" placeholder:text-gray-400 dark:placeholder:text-gray-500"
></textarea> ></textarea>
<button <button
type="button" type="submit"
onclick={handleSubmit}
disabled={disabled || !input.trim()} disabled={disabled || !input.trim()}
class="min-h-[44px] min-w-[44px] rounded-xl bg-blue-600 px-4 py-2.5 text-sm font-medium text-white class="min-h-[44px] min-w-[44px] rounded-xl bg-blue-600 px-4 py-2.5 text-sm font-medium text-white
hover:bg-blue-700 focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:outline-none hover:bg-blue-700 focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:outline-none

View File

@@ -29,7 +29,7 @@
{status === 'completed' {status === 'completed'
? 'bg-green-500 text-white' ? 'bg-green-500 text-white'
: status === 'active' : status === 'active'
? 'bg-blue-500 text-white ring-2 ring-blue-300 dark:ring-blue-600 ring-offset-1 dark:ring-offset-gray-800' ? 'bg-blue-500 text-white ring-2 ring-blue-300 dark:ring-blue-600 ring-offset-1 dark:ring-offset-gray-800 animate-pulse-ring'
: 'bg-gray-200 dark:bg-gray-600 text-gray-500 dark:text-gray-400'}" : 'bg-gray-200 dark:bg-gray-600 text-gray-500 dark:text-gray-400'}"
> >
{#if status === 'completed'} {#if status === 'completed'}
@@ -46,11 +46,45 @@
</span> </span>
</div> </div>
{#if i < phases.length - 1} {#if i < phases.length - 1}
<div {@const nextStatus = getStatus(phases[i + 1].state)}
class="mb-5 h-0.5 flex-1 transition-colors duration-300 <div class="relative mb-5 h-0.5 flex-1 bg-gray-200 dark:bg-gray-600 overflow-hidden">
{getStatus(phases[i + 1].state) !== 'pending' ? 'bg-green-500' : 'bg-gray-200 dark:bg-gray-600'}" {#if nextStatus !== 'pending'}
></div> <!-- Completed: solid green fill -->
<div class="absolute inset-0 bg-green-500"></div>
{:else if status === 'active'}
<!-- Active: animated fill shimmer -->
<div class="absolute inset-0 animate-progress-fill bg-gradient-to-r from-blue-500 via-blue-400 to-blue-500 bg-[length:200%_100%]"></div>
{/if}
</div>
{/if} {/if}
{/each} {/each}
</div> </div>
</div> </div>
<style>
@keyframes pulse-ring {
0%, 100% {
box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.5);
}
50% {
box-shadow: 0 0 0 6px rgba(59, 130, 246, 0);
}
}
@keyframes progress-fill {
0% {
background-position: 200% 0;
}
100% {
background-position: -200% 0;
}
}
:global(.animate-pulse-ring) {
animation: pulse-ring 2s ease-in-out infinite;
}
:global(.animate-progress-fill) {
animation: progress-fill 2s linear infinite;
}
</style>

View File

@@ -0,0 +1,38 @@
<script lang="ts">
import type { Snippet } from 'svelte';
import ThemeToggle from '$lib/components/ThemeToggle.svelte';
let {
title,
backHref,
backLabel = 'Chat',
children
}: {
title: string;
backHref?: string;
backLabel?: string;
children?: Snippet;
} = $props();
</script>
<header class="flex items-center justify-between border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 px-4 py-3 md:px-6">
<div class="flex items-center gap-2 md:gap-4">
{#if backHref}
<!-- eslint-disable svelte/no-navigation-without-resolve -- resolveRoute is resolve; plugin does not recognize the alias -->
<a
href={backHref}
class="rounded-lg px-2.5 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 hover:text-gray-900 dark:hover:text-gray-100"
>
&larr; {backLabel}
</a>
<!-- eslint-enable svelte/no-navigation-without-resolve -->
{/if}
<h1 class="text-base md:text-lg font-semibold text-gray-900 dark:text-gray-100">{title}</h1>
</div>
<div class="flex items-center gap-2">
{#if children}
{@render children()}
{/if}
<ThemeToggle />
</div>
</header>

View File

@@ -1,5 +1,7 @@
<script lang="ts"> <script lang="ts">
import { sessionStore } from '$lib/stores/sessions.svelte'; import { sessionStore } from '$lib/stores/sessions.svelte';
import { formatRelativeDate } from '$lib/utils/date';
import Backdrop from '$lib/components/Backdrop.svelte';
let { let {
onSelectSession, onSelectSession,
@@ -41,27 +43,11 @@
onClose?.(); onClose?.();
} }
function formatDate(date: Date): string {
const now = new Date();
const diff = now.getTime() - date.getTime();
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
if (days === 0) return 'Today';
if (days === 1) return 'Yesterday';
if (days < 7) return `${days} days ago`;
return date.toLocaleDateString();
}
</script> </script>
<!-- Mobile overlay backdrop -->
{#if open} {#if open}
<div <Backdrop onClose={() => onClose?.()} />
class="fixed inset-0 z-40 bg-black/50 md:hidden"
role="button"
tabindex="-1"
onclick={onClose}
onkeydown={(e) => { if (e.key === 'Escape') onClose?.(); }}
aria-label="Close sidebar"
></div>
{/if} {/if}
<!-- Sidebar: always visible on md+, slide-in drawer on mobile when open --> <!-- Sidebar: always visible on md+, slide-in drawer on mobile when open -->
@@ -105,7 +91,7 @@
> >
<div class="min-w-0 flex-1"> <div class="min-w-0 flex-1">
<p class="truncate text-sm font-medium text-gray-900 dark:text-gray-100">{session.title}</p> <p class="truncate text-sm font-medium text-gray-900 dark:text-gray-100">{session.title}</p>
<p class="mt-0.5 text-xs text-gray-500 dark:text-gray-400">{formatDate(session.createdAt)}</p> <p class="mt-0.5 text-xs text-gray-500 dark:text-gray-400">{formatRelativeDate(session.createdAt)}</p>
</div> </div>
<button <button
type="button" type="button"

View File

@@ -0,0 +1,174 @@
import type { ChatMessage } from '$lib/types';
import type { SubagentResult, InferenceStats } from '$lib/proto/llm_multiverse/v1/common_pb';
import type { SessionConfig } from '$lib/proto/llm_multiverse/v1/orchestrator_pb';
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 { logger } from '$lib/utils/logger';
export function createOrchestration() {
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 inferenceStats: InferenceStats | null = $state(null);
async function send(
sessionId: string,
content: string,
config: SessionConfig,
messages: ChatMessage[]
): Promise<ChatMessage[]> {
error = null;
lastFailedContent = null;
orchestrationState = OrchestrationState.UNSPECIFIED;
intermediateResult = '';
finalResult = null;
inferenceStats = null;
let lastAuditState = OrchestrationState.UNSPECIFIED;
const userMessage: ChatMessage = {
id: crypto.randomUUID(),
role: 'user',
content,
// eslint-disable-next-line svelte/prefer-svelte-reactivity -- plain data, not reactive state
timestamp: new Date()
};
messages.push(userMessage);
const assistantMessage: ChatMessage = {
id: crypto.randomUUID(),
role: 'assistant',
content: '',
// eslint-disable-next-line svelte/prefer-svelte-reactivity -- plain data, not reactive state
timestamp: new Date()
};
messages.push(assistantMessage);
sessionStore.updateMessages(sessionId, messages);
isStreaming = true;
try {
for await (const response of processRequest(sessionId, content, config)) {
orchestrationState = response.state;
if (response.state !== lastAuditState) {
const stateLabel = OrchestrationState[response.state] ?? String(response.state);
logger.debug('useOrchestration', `State: ${stateLabel}`, {
sessionId,
state: 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.inferenceStats) {
inferenceStats = response.inferenceStats;
}
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 isOrcErr = err instanceof OrchestratorError;
const code = isOrcErr ? err.code : 'unknown';
const details = isOrcErr ? err.details : undefined;
const friendlyMsg = isOrcErr
? friendlyMessage(err.code)
: 'An unexpected error occurred';
const displayMsg =
code && code !== 'unknown'
? `${friendlyMsg} (${code})`
: friendlyMsg;
error = displayMsg;
lastFailedContent = content;
logger.error('useOrchestration', 'Request failed', { code, details });
auditStore.addEvent(sessionId, {
eventType: 'error',
details: `${friendlyMsg} | code=${code}${details ? ` | details=${details}` : ''}`
});
const idx = messages.length - 1;
messages[idx] = {
...messages[idx],
content: `\u26A0 ${displayMsg}`
};
} finally {
isStreaming = false;
sessionStore.updateMessages(sessionId, messages);
}
return messages;
}
function retry(
sessionId: string,
config: SessionConfig,
messages: ChatMessage[]
): { messages: ChatMessage[]; sending: boolean } {
if (!lastFailedContent) return { messages, sending: false };
const content = lastFailedContent;
// Remove the failed user+assistant pair before retrying
if (
messages.length >= 2 &&
messages[messages.length - 2].role === 'user' &&
messages[messages.length - 1].role === 'assistant' &&
messages[messages.length - 1].content.startsWith('\u26A0')
) {
messages = messages.slice(0, -2);
}
send(sessionId, content, config, messages);
return { messages, sending: true };
}
function reset() {
error = null;
finalResult = null;
inferenceStats = null;
}
return {
get isStreaming() { return isStreaming; },
get error() { return error; },
get lastFailedContent() { return lastFailedContent; },
get orchestrationState() { return orchestrationState; },
get intermediateResult() { return intermediateResult; },
get finalResult() { return finalResult; },
get inferenceStats() { return inferenceStats; },
send,
retry,
reset
};
}
/**
* Module-level singleton so orchestration state survives tab/route changes.
* The chat page uses this instead of calling createOrchestration() per mount.
*/
export const orchestrationStore = createOrchestration();

View File

@@ -12,7 +12,47 @@ import type { Message } from "@bufbuild/protobuf";
* Describes the file llm_multiverse/v1/common.proto. * Describes the file llm_multiverse/v1/common.proto.
*/ */
export const file_llm_multiverse_v1_common: GenFile = /*@__PURE__*/ export const file_llm_multiverse_v1_common: GenFile = /*@__PURE__*/
fileDesc("Ch5sbG1fbXVsdGl2ZXJzZS92MS9jb21tb24ucHJvdG8SEWxsbV9tdWx0aXZlcnNlLnYxImoKD0FnZW50SWRlbnRpZmllchIQCghhZ2VudF9pZBgBIAEoCRIwCgphZ2VudF90eXBlGAIgASgOMhwubGxtX211bHRpdmVyc2UudjEuQWdlbnRUeXBlEhMKC3NwYXduX2RlcHRoGAMgASgNIkIKDEFnZW50TGluZWFnZRIyCgZhZ2VudHMYASADKAsyIi5sbG1fbXVsdGl2ZXJzZS52MS5BZ2VudElkZW50aWZpZXIi1wEKDlN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VFlfVU5DRVJUQUlOEAMqhgEKDFJlc3VsdFNvdXJjZRIdChlSRVNVTFRfU09VUkNFX1VOU1BFQ0lGSUVEEAASHQoZUkVTVUxUX1NPVVJDRV9UT09MX09VVFBVVBABEiEKHVJFU1VMVF9TT1VSQ0VfTU9ERUxfS05PV0xFREdFEAISFQoRUkVTVUxUX1NPVVJDRV9XRUIQAyqgAQoMQXJ0aWZhY3RUeXBlEh0KGUFSVElGQUNUX1RZUEVfVU5TUEVDSUZJRUQQABIWChJBUlRJRkFDVF9UWVBFX0NPREUQARIWChJBUlRJRkFDVF9UWVBFX1RFWFQQAhIgChxBUlRJRkFDVF9UWVBFX0NPTU1BTkRfT1VUUFVUEAMSHwobQVJUSUZBQ1RfVFlQRV9TRUFSQ0hfUkVTVUxUEARiBnByb3RvMw", [file_google_protobuf_timestamp]);
/**
* A concrete output produced by an agent (code, command output, etc.).
*
* @generated from message llm_multiverse.v1.Artifact
*/
export type Artifact = Message<"llm_multiverse.v1.Artifact"> & {
/**
* Display name (filename, query, etc.)
*
* @generated from field: string label = 1;
*/
label: string;
/**
* Full content
*
* @generated from field: string content = 2;
*/
content: string;
/**
* @generated from field: llm_multiverse.v1.ArtifactType artifact_type = 3;
*/
artifactType: ArtifactType;
/**
* language, path, tool_name, exit_code, etc.
*
* @generated from field: map<string, string> metadata = 4;
*/
metadata: { [key: string]: string };
};
/**
* Describes the message llm_multiverse.v1.Artifact.
* Use `create(ArtifactSchema)` to create a new message.
*/
export const ArtifactSchema: GenMessage<Artifact> = /*@__PURE__*/
messageDesc(file_llm_multiverse_v1_common, 0);
/** /**
* Identifies a single agent in the lineage chain. * Identifies a single agent in the lineage chain.
@@ -41,7 +81,7 @@ export type AgentIdentifier = Message<"llm_multiverse.v1.AgentIdentifier"> & {
* Use `create(AgentIdentifierSchema)` to create a new message. * Use `create(AgentIdentifierSchema)` to create a new message.
*/ */
export const AgentIdentifierSchema: GenMessage<AgentIdentifier> = /*@__PURE__*/ export const AgentIdentifierSchema: GenMessage<AgentIdentifier> = /*@__PURE__*/
messageDesc(file_llm_multiverse_v1_common, 0); messageDesc(file_llm_multiverse_v1_common, 1);
/** /**
* Ordered chain of agents from orchestrator (index 0) to current agent. * Ordered chain of agents from orchestrator (index 0) to current agent.
@@ -61,7 +101,7 @@ export type AgentLineage = Message<"llm_multiverse.v1.AgentLineage"> & {
* Use `create(AgentLineageSchema)` to create a new message. * Use `create(AgentLineageSchema)` to create a new message.
*/ */
export const AgentLineageSchema: GenMessage<AgentLineage> = /*@__PURE__*/ export const AgentLineageSchema: GenMessage<AgentLineage> = /*@__PURE__*/
messageDesc(file_llm_multiverse_v1_common, 1); messageDesc(file_llm_multiverse_v1_common, 2);
/** /**
* Carried in every gRPC request for audit trail and broker enforcement. * Carried in every gRPC request for audit trail and broker enforcement.
@@ -100,7 +140,7 @@ export type SessionContext = Message<"llm_multiverse.v1.SessionContext"> & {
* Use `create(SessionContextSchema)` to create a new message. * Use `create(SessionContextSchema)` to create a new message.
*/ */
export const SessionContextSchema: GenMessage<SessionContext> = /*@__PURE__*/ export const SessionContextSchema: GenMessage<SessionContext> = /*@__PURE__*/
messageDesc(file_llm_multiverse_v1_common, 2); messageDesc(file_llm_multiverse_v1_common, 3);
/** /**
* Structured error detail for gRPC error responses. * Structured error detail for gRPC error responses.
@@ -129,7 +169,7 @@ export type ErrorDetail = Message<"llm_multiverse.v1.ErrorDetail"> & {
* Use `create(ErrorDetailSchema)` to create a new message. * Use `create(ErrorDetailSchema)` to create a new message.
*/ */
export const ErrorDetailSchema: GenMessage<ErrorDetail> = /*@__PURE__*/ export const ErrorDetailSchema: GenMessage<ErrorDetail> = /*@__PURE__*/
messageDesc(file_llm_multiverse_v1_common, 3); messageDesc(file_llm_multiverse_v1_common, 4);
/** /**
* A candidate memory entry proposed by a subagent for persistence. * A candidate memory entry proposed by a subagent for persistence.
@@ -158,7 +198,56 @@ export type MemoryCandidate = Message<"llm_multiverse.v1.MemoryCandidate"> & {
* Use `create(MemoryCandidateSchema)` to create a new message. * Use `create(MemoryCandidateSchema)` to create a new message.
*/ */
export const MemoryCandidateSchema: GenMessage<MemoryCandidate> = /*@__PURE__*/ export const MemoryCandidateSchema: GenMessage<MemoryCandidate> = /*@__PURE__*/
messageDesc(file_llm_multiverse_v1_common, 4); messageDesc(file_llm_multiverse_v1_common, 5);
/**
* Inference statistics surfaced from model-gateway through the orchestrator.
*
* @generated from message llm_multiverse.v1.InferenceStats
*/
export type InferenceStats = Message<"llm_multiverse.v1.InferenceStats"> & {
/**
* Number of tokens in the prompt.
*
* @generated from field: uint32 prompt_tokens = 1;
*/
promptTokens: number;
/**
* Number of tokens generated.
*
* @generated from field: uint32 completion_tokens = 2;
*/
completionTokens: number;
/**
* Sum of prompt + completion tokens.
*
* @generated from field: uint32 total_tokens = 3;
*/
totalTokens: number;
/**
* Model's maximum context length.
*
* @generated from field: uint32 context_window_size = 4;
*/
contextWindowSize: number;
/**
* Generation throughput (tokens per second).
*
* @generated from field: float tokens_per_second = 5;
*/
tokensPerSecond: number;
};
/**
* Describes the message llm_multiverse.v1.InferenceStats.
* Use `create(InferenceStatsSchema)` to create a new message.
*/
export const InferenceStatsSchema: GenMessage<InferenceStats> = /*@__PURE__*/
messageDesc(file_llm_multiverse_v1_common, 6);
/** /**
* Standardized return value from any subagent to its parent. * Standardized return value from any subagent to its parent.
@@ -179,9 +268,11 @@ export type SubagentResult = Message<"llm_multiverse.v1.SubagentResult"> & {
summary: string; summary: string;
/** /**
* @generated from field: repeated string artifacts = 3; * Structured artifacts produced during the agent loop.
*
* @generated from field: repeated llm_multiverse.v1.Artifact artifacts = 3;
*/ */
artifacts: string[]; artifacts: Artifact[];
/** /**
* @generated from field: llm_multiverse.v1.ResultQuality result_quality = 4; * @generated from field: llm_multiverse.v1.ResultQuality result_quality = 4;
@@ -209,7 +300,7 @@ export type SubagentResult = Message<"llm_multiverse.v1.SubagentResult"> & {
* Use `create(SubagentResultSchema)` to create a new message. * Use `create(SubagentResultSchema)` to create a new message.
*/ */
export const SubagentResultSchema: GenMessage<SubagentResult> = /*@__PURE__*/ export const SubagentResultSchema: GenMessage<SubagentResult> = /*@__PURE__*/
messageDesc(file_llm_multiverse_v1_common, 5); messageDesc(file_llm_multiverse_v1_common, 7);
/** /**
* Agent types with distinct tool permission manifests. * Agent types with distinct tool permission manifests.
@@ -450,3 +541,49 @@ export enum ResultSource {
export const ResultSourceSchema: GenEnum<ResultSource> = /*@__PURE__*/ export const ResultSourceSchema: GenEnum<ResultSource> = /*@__PURE__*/
enumDesc(file_llm_multiverse_v1_common, 5); enumDesc(file_llm_multiverse_v1_common, 5);
/**
* Type of artifact produced by an agent during its tool call loop.
*
* @generated from enum llm_multiverse.v1.ArtifactType
*/
export enum ArtifactType {
/**
* @generated from enum value: ARTIFACT_TYPE_UNSPECIFIED = 0;
*/
UNSPECIFIED = 0,
/**
* Code written via fs_write
*
* @generated from enum value: ARTIFACT_TYPE_CODE = 1;
*/
CODE = 1,
/**
* Plain text / file content from fs_read
*
* @generated from enum value: ARTIFACT_TYPE_TEXT = 2;
*/
TEXT = 2,
/**
* Output from run_code / run_shell
*
* @generated from enum value: ARTIFACT_TYPE_COMMAND_OUTPUT = 3;
*/
COMMAND_OUTPUT = 3,
/**
* Web search results
*
* @generated from enum value: ARTIFACT_TYPE_SEARCH_RESULT = 4;
*/
SEARCH_RESULT = 4,
}
/**
* Describes the enum llm_multiverse.v1.ArtifactType.
*/
export const ArtifactTypeSchema: GenEnum<ArtifactType> = /*@__PURE__*/
enumDesc(file_llm_multiverse_v1_common, 6);

View File

@@ -4,7 +4,7 @@
import type { GenEnum, GenFile, GenMessage, GenService } from "@bufbuild/protobuf/codegenv2"; import type { GenEnum, GenFile, GenMessage, GenService } from "@bufbuild/protobuf/codegenv2";
import { enumDesc, fileDesc, messageDesc, serviceDesc } from "@bufbuild/protobuf/codegenv2"; import { enumDesc, fileDesc, messageDesc, serviceDesc } from "@bufbuild/protobuf/codegenv2";
import type { AgentType, OverrideLevel, SessionContext, SubagentResult, ToolType } from "./common_pb"; import type { AgentType, InferenceStats, OverrideLevel, SessionContext, SubagentResult, ToolType } from "./common_pb";
import { file_llm_multiverse_v1_common } from "./common_pb"; import { file_llm_multiverse_v1_common } from "./common_pb";
import type { Message } from "@bufbuild/protobuf"; import type { Message } from "@bufbuild/protobuf";
@@ -12,7 +12,7 @@ import type { Message } from "@bufbuild/protobuf";
* Describes the file llm_multiverse/v1/orchestrator.proto. * Describes the file llm_multiverse/v1/orchestrator.proto.
*/ */
export const file_llm_multiverse_v1_orchestrator: GenFile = /*@__PURE__*/ export const file_llm_multiverse_v1_orchestrator: GenFile = /*@__PURE__*/
fileDesc("CiRsbG1fbXVsdGl2ZXJzZS92MS9vcmNoZXN0cmF0b3IucHJvdG8SEWxsbV9tdWx0aXZlcnNlLnYxIn4KDVNlc3Npb25Db25maWcSOAoOb3ZlcnJpZGVfbGV2ZWwYASABKA4yIC5sbG1fbXVsdGl2ZXJzZS52MS5PdmVycmlkZUxldmVsEhYKDmRpc2FibGVkX3Rvb2xzGAIgAygJEhsKE2dyYW50ZWRfcGVybWlzc2lvbnMYAyADKAkirwEKEVN1YnRhc2tEZWZpbml0aW9uEgoKAmlkGAEgASgJEhMKC2Rlc2NyaXB0aW9uGAIgASgJEjAKCmFnZW50X3R5cGUYAyABKA4yHC5sbG1fbXVsdGl2ZXJzZS52MS5BZ2VudFR5cGUSEgoKZGVwZW5kc19vbhgEIAMoCRIzCg50b29sc19yZXF1aXJlZBgFIAMoDjIbLmxsbV9tdWx0aXZlcnNlLnYxLlRvb2xUeXBlIoYCCg9TdWJhZ2VudFJlcXVlc3QSMgoHY29udGV4dBgBIAEoCzIhLmxsbV9tdWx0aXZlcnNlLnYxLlNlc3Npb25Db250ZXh0EhAKCGFnZW50X2lkGAIgASgJEjAKCmFnZW50X3R5cGUYAyABKA4yHC5sbG1fbXVsdGl2ZXJzZS52MS5BZ2VudFR5cGUSDAoEdGFzaxgEIAEoCRIfChdyZWxldmFudF9tZW1v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mVyc2UudjEuU2Vzc2lvbkNvbmZpZ0gAiAEBQhEKD19zZXNzaW9uX2NvbmZpZyK9AgoWUHJvY2Vzc1JlcXVlc3RSZXNwb25zZRI0CgVzdGF0ZRgBIAEoDjIlLmxsbV9tdWx0aXZlcnNlLnYxLk9yY2hlc3RyYXRpb25TdGF0ZRIPCgdtZXNzYWdlGAIgASgJEiAKE2ludGVybWVkaWF0ZV9yZXN1bHQYAyABKAlIAIgBARI8CgxmaW5hbF9yZXN1bHQYBCABKAsyIS5sbG1fbXVsdGl2ZXJzZS52MS5TdWJhZ2VudFJlc3VsdEgBiAEBEj8KD2luZmVyZW5jZV9zdGF0cxgFIAEoCzIhLmxsbV9tdWx0aXZlcnNlLnYxLkluZmVyZW5jZVN0YXRzSAKIAQFCFgoUX2ludGVybWVkaWF0ZV9yZXN1bHRCDwoNX2ZpbmFsX3Jlc3VsdEISChBfaW5mZXJlbmNlX3N0YXRzKuwBChJPcmNoZXN0cmF0aW9uU3RhdGUSIwofT1JDSEVTVFJBVElPTl9TVEFURV9VTlNQRUNJRklFRBAAEiMKH09SQ0hFU1RSQVRJT05fU1RBVEVfREVDT01QT1NJTkcQARIjCh9PUkNIRVNUUkFUSU9OX1NUQVRFX0RJU1BBVENISU5HEAISIQodT1JDSEVTVFJBVElPTl9TVEFURV9FWEVDVVRJTkcQAxIiCh5PUkNIRVNUUkFUSU9OX1NUQVRFX0NPTVBBQ1RJTkcQBBIgChxPUkNIRVNUUkFUSU9OX1NUQVRFX0NPTVBMRVRFEAUyfgoTT3JjaGVzdHJhdG9yU2VydmljZRJnCg5Qcm9jZXNzUmVxdWVzdBIoLmxsbV9tdWx0aXZlcnNlLnYxLlByb2Nlc3NSZXF1ZXN0UmVxdWVzdBopLmxsbV9tdWx0aXZlcnNlLnYxLlByb2Nlc3NSZXF1ZXN0UmVzcG9uc2UwAWIGcHJvdG8z", [file_llm_multiverse_v1_common]);
/** /**
* Per-session configuration for override control. * Per-session configuration for override control.
@@ -199,6 +199,13 @@ export type ProcessRequestResponse = Message<"llm_multiverse.v1.ProcessRequestRe
* @generated from field: optional llm_multiverse.v1.SubagentResult final_result = 4; * @generated from field: optional llm_multiverse.v1.SubagentResult final_result = 4;
*/ */
finalResult?: SubagentResult; finalResult?: SubagentResult;
/**
* Inference statistics from the model-gateway (on the final streamed message).
*
* @generated from field: optional llm_multiverse.v1.InferenceStats inference_stats = 5;
*/
inferenceStats?: InferenceStats;
}; };
/** /**

View File

@@ -1,4 +1,4 @@
import { createClient } from '@connectrpc/connect'; import { createClient, ConnectError, Code } from '@connectrpc/connect';
import { createGrpcWebTransport } from '@connectrpc/connect-web'; import { createGrpcWebTransport } from '@connectrpc/connect-web';
import { OrchestratorService } from '$lib/proto/llm_multiverse/v1/orchestrator_pb'; import { OrchestratorService } from '$lib/proto/llm_multiverse/v1/orchestrator_pb';
import type { import type {
@@ -9,6 +9,7 @@ import { create } from '@bufbuild/protobuf';
import { ProcessRequestRequestSchema } from '$lib/proto/llm_multiverse/v1/orchestrator_pb'; import { ProcessRequestRequestSchema } from '$lib/proto/llm_multiverse/v1/orchestrator_pb';
import { connectionStore } from '$lib/stores/connection.svelte'; import { connectionStore } from '$lib/stores/connection.svelte';
import { toastStore } from '$lib/stores/toast.svelte'; import { toastStore } from '$lib/stores/toast.svelte';
import { logger } from '$lib/utils/logger';
/** /**
* Application-level error wrapping gRPC status codes. * Application-level error wrapping gRPC status codes.
@@ -79,15 +80,18 @@ function getTransport(endpoint?: string) {
/** /**
* Reset the transport (useful for reconfiguring the endpoint). * Reset the transport (useful for reconfiguring the endpoint).
*/ */
export function resetTransport(): void { export function resetTransport(newEndpoint?: string): void {
transport = null; transport = null;
if (newEndpoint !== undefined) {
transport = createGrpcWebTransport({ baseUrl: newEndpoint });
}
} }
/** /**
* Create a configured orchestrator client. * Create a configured orchestrator client.
*/ */
function getClient(endpoint?: string) { function getClient() {
return createClient(OrchestratorService, getTransport(endpoint)); return createClient(OrchestratorService, getTransport());
} }
/** /**
@@ -109,10 +113,35 @@ function backoffDelay(attempt: number): number {
const MAX_RETRIES = 3; const MAX_RETRIES = 3;
/**
* Map numeric Code enum values to lowercase string names matching GRPC_USER_MESSAGES keys.
*/
const CODE_TO_STRING: Record<number, string> = {
[Code.Canceled]: 'cancelled',
[Code.Unknown]: 'unknown',
[Code.InvalidArgument]: 'failed_precondition',
[Code.DeadlineExceeded]: 'deadline_exceeded',
[Code.NotFound]: 'not_found',
[Code.AlreadyExists]: 'already_exists',
[Code.PermissionDenied]: 'permission_denied',
[Code.ResourceExhausted]: 'resource_exhausted',
[Code.FailedPrecondition]: 'failed_precondition',
[Code.Aborted]: 'aborted',
[Code.OutOfRange]: 'failed_precondition',
[Code.Unimplemented]: 'unimplemented',
[Code.Internal]: 'internal',
[Code.Unavailable]: 'unavailable',
[Code.DataLoss]: 'data_loss',
[Code.Unauthenticated]: 'unauthenticated'
};
/** /**
* Extract gRPC error code from an error, normalising to lowercase string. * Extract gRPC error code from an error, normalising to lowercase string.
*/ */
function extractCode(err: unknown): string { function extractCode(err: unknown): string {
if (err instanceof ConnectError) {
return CODE_TO_STRING[err.code] ?? 'unknown';
}
if (err instanceof Error && 'code' in err) { if (err instanceof Error && 'code' in err) {
const raw = (err as { code: unknown }).code; const raw = (err as { code: unknown }).code;
if (typeof raw === 'string') return raw.toLowerCase(); if (typeof raw === 'string') return raw.toLowerCase();
@@ -126,6 +155,14 @@ function extractCode(err: unknown): string {
*/ */
function toOrchestratorError(err: unknown): OrchestratorError { function toOrchestratorError(err: unknown): OrchestratorError {
if (err instanceof OrchestratorError) return err; if (err instanceof OrchestratorError) return err;
if (err instanceof ConnectError) {
const code = extractCode(err);
const details = [
err.rawMessage,
err.cause ? String(err.cause) : ''
].filter(Boolean).join('; ');
return new OrchestratorError(friendlyMessage(code), code, details || undefined);
}
if (err instanceof Error) { if (err instanceof Error) {
const code = extractCode(err); const code = extractCode(err);
return new OrchestratorError(friendlyMessage(code), code, err.message); return new OrchestratorError(friendlyMessage(code), code, err.message);
@@ -133,6 +170,13 @@ function toOrchestratorError(err: unknown): OrchestratorError {
return new OrchestratorError(friendlyMessage('unknown'), 'unknown'); return new OrchestratorError(friendlyMessage('unknown'), 'unknown');
} }
/**
* Append a diagnostic code suffix to a message, e.g. "(code: unavailable)".
*/
function diagnosticSuffix(err: OrchestratorError): string {
return err.code && err.code !== 'unknown' ? ` (code: ${err.code})` : '';
}
/** /**
* Send a request to the orchestrator and yield streaming responses. * Send a request to the orchestrator and yield streaming responses.
* *
@@ -147,8 +191,7 @@ function toOrchestratorError(err: unknown): OrchestratorError {
export async function* processRequest( export async function* processRequest(
sessionId: string, sessionId: string,
userMessage: string, userMessage: string,
sessionConfig?: SessionConfig, sessionConfig?: SessionConfig
endpoint?: string
): AsyncGenerator<ProcessRequestResponse> { ): AsyncGenerator<ProcessRequestResponse> {
const request = create(ProcessRequestRequestSchema, { const request = create(ProcessRequestRequestSchema, {
sessionId, sessionId,
@@ -156,24 +199,41 @@ export async function* processRequest(
sessionConfig sessionConfig
}); });
logger.debug('orchestrator', 'processRequest', {
sessionId,
messageLength: userMessage.length
});
let lastError: OrchestratorError | null = null; let lastError: OrchestratorError | null = null;
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) { for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
// Skip retries if already known disconnected
if (connectionStore.status === 'disconnected' && attempt > 0) {
break;
}
if (attempt > 0) { if (attempt > 0) {
connectionStore.setReconnecting(); connectionStore.setReconnecting();
const delay = backoffDelay(attempt - 1); const delay = backoffDelay(attempt - 1);
logger.warn('orchestrator', `Retry attempt ${attempt}/${MAX_RETRIES}`, {
sessionId,
previousCode: lastError?.code,
delay
});
await sleep(delay); await sleep(delay);
} }
try { try {
const client = getClient(endpoint); const client = getClient();
for await (const response of client.processRequest(request)) { for await (const response of client.processRequest(request)) {
connectionStore.reportSuccess(); connectionStore.reportSuccess();
yield response; yield response;
} }
logger.debug('orchestrator', 'Stream completed', { sessionId });
// Completed successfully — no retry needed // Completed successfully — no retry needed
return; return;
} catch (err: unknown) { } catch (err: unknown) {
logger.grpcError('orchestrator', `Request failed (attempt ${attempt + 1}/${MAX_RETRIES + 1})`, err);
lastError = toOrchestratorError(err); lastError = toOrchestratorError(err);
const code = lastError.code; const code = lastError.code;
@@ -185,7 +245,12 @@ export async function* processRequest(
// Non-transient or exhausted retries // Non-transient or exhausted retries
connectionStore.reportFailure(); connectionStore.reportFailure();
toastStore.addToast({ message: lastError.message, type: 'error' }); const suffix = diagnosticSuffix(lastError);
logger.error('orchestrator', 'Request failed permanently', {
code: lastError.code,
details: lastError.details
});
toastStore.addToast({ message: lastError.message + suffix, type: 'error' });
throw lastError; throw lastError;
} }
} }

View File

@@ -40,168 +40,9 @@ function saveEvents(events: SvelteMap<string, AuditEvent[]>) {
localStorage.setItem(STORAGE_KEY, JSON.stringify([...events.entries()])); localStorage.setItem(STORAGE_KEY, JSON.stringify([...events.entries()]));
} }
function getSampleData(): SvelteMap<string, AuditEvent[]> {
const samples = new SvelteMap<string, AuditEvent[]>();
const now = Date.now();
samples.set('session-demo-alpha', [
{
id: 'evt-001',
sessionId: 'session-demo-alpha',
timestamp: new Date(now - 300_000),
eventType: 'state_change',
details: 'Orchestration started — decomposing user request',
state: 'DECOMPOSING'
},
{
id: 'evt-002',
sessionId: 'session-demo-alpha',
timestamp: new Date(now - 280_000),
eventType: 'tool_invocation',
details: 'Invoked web_search tool for "SvelteKit best practices"',
state: 'DECOMPOSING'
},
{
id: 'evt-003',
sessionId: 'session-demo-alpha',
timestamp: new Date(now - 260_000),
eventType: 'state_change',
details: 'Dispatching subtasks to subagents',
state: 'DISPATCHING'
},
{
id: 'evt-004',
sessionId: 'session-demo-alpha',
timestamp: new Date(now - 240_000),
eventType: 'message',
details: 'Researcher agent assigned to subtask "Gather TypeScript patterns"'
},
{
id: 'evt-005',
sessionId: 'session-demo-alpha',
timestamp: new Date(now - 220_000),
eventType: 'state_change',
details: 'Subagents executing tasks',
state: 'EXECUTING'
},
{
id: 'evt-006',
sessionId: 'session-demo-alpha',
timestamp: new Date(now - 200_000),
eventType: 'tool_invocation',
details: 'Invoked code_analysis tool on project source files'
},
{
id: 'evt-007',
sessionId: 'session-demo-alpha',
timestamp: new Date(now - 180_000),
eventType: 'error',
details: 'Timeout waiting for code_analysis response (retrying)'
},
{
id: 'evt-008',
sessionId: 'session-demo-alpha',
timestamp: new Date(now - 160_000),
eventType: 'tool_invocation',
details: 'Retry: code_analysis tool succeeded'
},
{
id: 'evt-009',
sessionId: 'session-demo-alpha',
timestamp: new Date(now - 140_000),
eventType: 'state_change',
details: 'Compacting results from subagents',
state: 'COMPACTING'
},
{
id: 'evt-010',
sessionId: 'session-demo-alpha',
timestamp: new Date(now - 120_000),
eventType: 'state_change',
details: 'Orchestration complete',
state: 'COMPLETE'
}
]);
samples.set('session-demo-beta', [
{
id: 'evt-011',
sessionId: 'session-demo-beta',
timestamp: new Date(now - 600_000),
eventType: 'state_change',
details: 'Orchestration started — decomposing deployment request',
state: 'DECOMPOSING'
},
{
id: 'evt-012',
sessionId: 'session-demo-beta',
timestamp: new Date(now - 580_000),
eventType: 'state_change',
details: 'Dispatching to sysadmin agent',
state: 'DISPATCHING'
},
{
id: 'evt-013',
sessionId: 'session-demo-beta',
timestamp: new Date(now - 560_000),
eventType: 'state_change',
details: 'Executing deployment analysis',
state: 'EXECUTING'
},
{
id: 'evt-014',
sessionId: 'session-demo-beta',
timestamp: new Date(now - 540_000),
eventType: 'tool_invocation',
details: 'Invoked kubectl_check tool for cluster status'
},
{
id: 'evt-015',
sessionId: 'session-demo-beta',
timestamp: new Date(now - 520_000),
eventType: 'error',
details: 'Permission denied: kubectl access not granted for this session'
},
{
id: 'evt-016',
sessionId: 'session-demo-beta',
timestamp: new Date(now - 500_000),
eventType: 'message',
details: 'Agent requested elevated permissions for cluster access'
},
{
id: 'evt-017',
sessionId: 'session-demo-beta',
timestamp: new Date(now - 480_000),
eventType: 'state_change',
details: 'Compacting partial results',
state: 'COMPACTING'
},
{
id: 'evt-018',
sessionId: 'session-demo-beta',
timestamp: new Date(now - 460_000),
eventType: 'state_change',
details: 'Orchestration complete with warnings',
state: 'COMPLETE'
}
]);
return samples;
}
function createAuditStore() { function createAuditStore() {
const events = $state<SvelteMap<string, AuditEvent[]>>(loadEvents()); const events = $state<SvelteMap<string, AuditEvent[]>>(loadEvents());
// Seed sample data if store is empty
if (events.size === 0) {
const samples = getSampleData();
for (const [id, evts] of samples) {
events.set(id, evts);
}
saveEvents(events);
}
function addEvent( function addEvent(
sessionId: string, sessionId: string,
event: Omit<AuditEvent, 'id' | 'sessionId' | 'timestamp'> event: Omit<AuditEvent, 'id' | 'sessionId' | 'timestamp'>

View File

@@ -13,9 +13,11 @@ export interface SessionMemory {
} }
const STORAGE_KEY = 'llm-multiverse-memory-candidates'; const STORAGE_KEY = 'llm-multiverse-memory-candidates';
const SAMPLE_CLEANUP_KEY = 'llm-multiverse-sample-data-cleaned';
function loadMemory(): SvelteMap<string, StoredMemoryCandidate[]> { function loadMemory(): SvelteMap<string, StoredMemoryCandidate[]> {
if (typeof localStorage === 'undefined') return new SvelteMap(); if (typeof localStorage === 'undefined') return new SvelteMap();
_cleanupSampleData();
try { try {
const raw = localStorage.getItem(STORAGE_KEY); const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return new SvelteMap(); if (!raw) return new SvelteMap();
@@ -26,79 +28,37 @@ function loadMemory(): SvelteMap<string, StoredMemoryCandidate[]> {
} }
} }
/** One-time removal of previously seeded sample sessions. */
function _cleanupSampleData() {
if (typeof localStorage === 'undefined') return;
if (localStorage.getItem(SAMPLE_CLEANUP_KEY)) return;
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (raw) {
const arr: [string, unknown[]][] = JSON.parse(raw);
const filtered = arr.filter(([id]) => !id.startsWith('session-demo-'));
localStorage.setItem(STORAGE_KEY, JSON.stringify(filtered));
}
// Also clean audit store
const auditKey = 'llm-multiverse-audit-events';
const auditRaw = localStorage.getItem(auditKey);
if (auditRaw) {
const arr: [string, unknown[]][] = JSON.parse(auditRaw);
const filtered = arr.filter(([id]) => !id.startsWith('session-demo-'));
localStorage.setItem(auditKey, JSON.stringify(filtered));
}
} catch { /* ignore */ }
localStorage.setItem(SAMPLE_CLEANUP_KEY, '1');
}
function saveMemory(memory: SvelteMap<string, StoredMemoryCandidate[]>) { function saveMemory(memory: SvelteMap<string, StoredMemoryCandidate[]>) {
if (typeof localStorage === 'undefined') return; if (typeof localStorage === 'undefined') return;
localStorage.setItem(STORAGE_KEY, JSON.stringify([...memory.entries()])); localStorage.setItem(STORAGE_KEY, JSON.stringify([...memory.entries()]));
} }
function getSampleData(): SvelteMap<string, StoredMemoryCandidate[]> {
const samples = new SvelteMap<string, StoredMemoryCandidate[]>();
samples.set('session-demo-alpha', [
{
content: 'The user prefers TypeScript strict mode with no implicit any.',
source: ResultSource.MODEL_KNOWLEDGE,
confidence: 0.92
},
{
content: 'Project uses SvelteKit with Tailwind CSS v4 and Svelte 5 runes.',
source: ResultSource.TOOL_OUTPUT,
confidence: 0.98
},
{
content: 'Preferred testing framework is Vitest with Playwright for e2e.',
source: ResultSource.MODEL_KNOWLEDGE,
confidence: 0.75
},
{
content: 'The gRPC backend runs on port 50051 behind a Caddy reverse proxy.',
source: ResultSource.TOOL_OUTPUT,
confidence: 0.85
}
]);
samples.set('session-demo-beta', [
{
content: 'User asked about deploying to Kubernetes with Helm charts.',
source: ResultSource.WEB,
confidence: 0.67
},
{
content: 'The container registry is at registry.example.com.',
source: ResultSource.TOOL_OUTPUT,
confidence: 0.91
},
{
content: 'Deployment target is a 3-node k3s cluster running on ARM64.',
source: ResultSource.WEB,
confidence: 0.58
}
]);
samples.set('session-demo-gamma', [
{
content: 'Database schema uses PostgreSQL with pgvector extension for embeddings.',
source: ResultSource.TOOL_OUTPUT,
confidence: 0.95
},
{
content: 'The embedding model is all-MiniLM-L6-v2 with 384 dimensions.',
source: ResultSource.MODEL_KNOWLEDGE,
confidence: 0.82
}
]);
return samples;
}
function createMemoryStore() { function createMemoryStore() {
const memory = $state<SvelteMap<string, StoredMemoryCandidate[]>>(loadMemory()); const memory = $state<SvelteMap<string, StoredMemoryCandidate[]>>(loadMemory());
// Seed sample data if store is empty
if (memory.size === 0) {
const samples = getSampleData();
for (const [id, candidates] of samples) {
memory.set(id, candidates);
}
saveMemory(memory);
}
function addCandidates(sessionId: string, candidates: StoredMemoryCandidate[]) { function addCandidates(sessionId: string, candidates: StoredMemoryCandidate[]) {
if (candidates.length === 0) return; if (candidates.length === 0) return;
const existing = memory.get(sessionId) ?? []; const existing = memory.get(sessionId) ?? [];

View File

@@ -1,3 +1,4 @@
import { SvelteMap } from 'svelte/reactivity';
import type { ChatMessage } from '$lib/types'; import type { ChatMessage } from '$lib/types';
export interface Session { export interface Session {
@@ -10,24 +11,24 @@ export interface Session {
const STORAGE_KEY = 'llm-multiverse-sessions'; const STORAGE_KEY = 'llm-multiverse-sessions';
const ACTIVE_SESSION_KEY = 'llm-multiverse-active-session'; const ACTIVE_SESSION_KEY = 'llm-multiverse-active-session';
function loadSessions(): Map<string, Session> { function loadSessions(): SvelteMap<string, Session> {
if (typeof localStorage === 'undefined') return new Map(); if (typeof localStorage === 'undefined') return new SvelteMap();
try { try {
const raw = localStorage.getItem(STORAGE_KEY); const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return new Map(); if (!raw) return new SvelteMap();
const arr: [string, Session][] = JSON.parse(raw); const arr: [string, Session][] = JSON.parse(raw);
return new Map( return new SvelteMap(
arr.map(([id, s]) => [ arr.map(([id, s]) => [
id, id,
{ ...s, createdAt: new Date(s.createdAt), messages: s.messages.map(m => ({ ...m, timestamp: new Date(m.timestamp) })) } { ...s, createdAt: new Date(s.createdAt), messages: s.messages.map(m => ({ ...m, timestamp: new Date(m.timestamp) })) }
]) ])
); );
} catch { } catch {
return new Map(); return new SvelteMap();
} }
} }
function saveSessions(sessions: Map<string, Session>) { function saveSessions(sessions: SvelteMap<string, Session>) {
if (typeof localStorage === 'undefined') return; if (typeof localStorage === 'undefined') return;
localStorage.setItem(STORAGE_KEY, JSON.stringify([...sessions.entries()])); localStorage.setItem(STORAGE_KEY, JSON.stringify([...sessions.entries()]));
} }
@@ -43,7 +44,7 @@ function saveActiveSessionId(id: string) {
} }
function createSessionStore() { function createSessionStore() {
const sessions = $state<Map<string, Session>>(loadSessions()); const sessions = $state<SvelteMap<string, Session>>(loadSessions());
let activeSessionId = $state<string | null>(loadActiveSessionId()); let activeSessionId = $state<string | null>(loadActiveSessionId());
function createSession(id?: string): Session { function createSession(id?: string): Session {
@@ -66,6 +67,10 @@ function createSessionStore() {
saveActiveSessionId(id); saveActiveSessionId(id);
return sessions.get(id)!; return sessions.get(id)!;
} }
// No specific ID — prefer existing active session
if (!id && activeSessionId && sessions.has(activeSessionId)) {
return sessions.get(activeSessionId)!;
}
return createSession(id); return createSession(id);
} }

View File

@@ -5,6 +5,9 @@ const STORAGE_KEY = 'llm-multiverse-theme';
function createThemeStore() { function createThemeStore() {
let mode: ThemeMode = $state('system'); let mode: ThemeMode = $state('system');
let resolvedDark = $state(false); let resolvedDark = $state(false);
let initialized = false;
let mediaQuery: MediaQueryList | null = null;
let mediaListener: ((e: MediaQueryListEvent) => void) | null = null;
function applyTheme(isDark: boolean) { function applyTheme(isDark: boolean) {
if (typeof document === 'undefined') return; if (typeof document === 'undefined') return;
@@ -27,8 +30,10 @@ function createThemeStore() {
return window.matchMedia('(prefers-color-scheme: dark)').matches; return window.matchMedia('(prefers-color-scheme: dark)').matches;
} }
function init() { function init(): (() => void) | undefined {
if (typeof window === 'undefined') return; if (typeof window === 'undefined') return;
if (initialized) return;
initialized = true;
// Load saved preference // Load saved preference
const saved = localStorage.getItem(STORAGE_KEY) as ThemeMode | null; const saved = localStorage.getItem(STORAGE_KEY) as ThemeMode | null;
@@ -39,18 +44,26 @@ function createThemeStore() {
} }
// Listen for system preference changes // Listen for system preference changes
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)'); mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
mediaQuery.addEventListener('change', (e) => { mediaListener = (e: MediaQueryListEvent) => {
if (mode === 'system') { if (mode === 'system') {
resolvedDark = e.matches; resolvedDark = e.matches;
applyTheme(resolvedDark); applyTheme(resolvedDark);
} }
}); };
mediaQuery.addEventListener('change', mediaListener);
// Apply initial theme // Apply initial theme
resolvedDark = resolvedDark =
mode === 'dark' ? true : mode === 'light' ? false : getSystemPreference(); mode === 'dark' ? true : mode === 'light' ? false : getSystemPreference();
applyTheme(resolvedDark); applyTheme(resolvedDark);
return () => {
if (mediaQuery && mediaListener) {
mediaQuery.removeEventListener('change', mediaListener);
}
initialized = false;
};
} }
function setMode(newMode: ThemeMode) { function setMode(newMode: ThemeMode) {

View File

@@ -42,57 +42,59 @@ export function agentTypeLabel(type: AgentType): string {
} }
} }
/** export interface AgentColorSet {
* Maps AgentType enum values to Tailwind-friendly color tokens.
*/
export function agentTypeColor(type: AgentType): {
fill: string; fill: string;
stroke: string; stroke: string;
text: string; text: string;
}
export interface AgentColors {
light: AgentColorSet;
dark: AgentColorSet;
badge: string; badge: string;
} { }
/**
* Maps AgentType enum values to light/dark color tokens for SVG rendering
* and Tailwind badge classes.
*/
export function agentTypeColor(type: AgentType): AgentColors {
switch (type) { switch (type) {
case AgentType.ORCHESTRATOR: case AgentType.ORCHESTRATOR:
return { return {
fill: '#dbeafe', light: { fill: '#dbeafe', stroke: '#3b82f6', text: '#1e40af' },
stroke: '#3b82f6', dark: { fill: '#1e3a5f', stroke: '#60a5fa', text: '#93c5fd' },
text: '#1e40af', badge: 'bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300'
badge: 'bg-blue-100 text-blue-700'
}; };
case AgentType.RESEARCHER: case AgentType.RESEARCHER:
return { return {
fill: '#dcfce7', light: { fill: '#dcfce7', stroke: '#22c55e', text: '#166534' },
stroke: '#22c55e', dark: { fill: '#14532d', stroke: '#4ade80', text: '#86efac' },
text: '#166534', badge: 'bg-green-100 dark:bg-green-900/40 text-green-700 dark:text-green-300'
badge: 'bg-green-100 text-green-700'
}; };
case AgentType.CODER: case AgentType.CODER:
return { return {
fill: '#f3e8ff', light: { fill: '#f3e8ff', stroke: '#a855f7', text: '#6b21a8' },
stroke: '#a855f7', dark: { fill: '#3b0764', stroke: '#c084fc', text: '#d8b4fe' },
text: '#6b21a8', badge: 'bg-purple-100 dark:bg-purple-900/40 text-purple-700 dark:text-purple-300'
badge: 'bg-purple-100 text-purple-700'
}; };
case AgentType.SYSADMIN: case AgentType.SYSADMIN:
return { return {
fill: '#ffedd5', light: { fill: '#ffedd5', stroke: '#f97316', text: '#9a3412' },
stroke: '#f97316', dark: { fill: '#431407', stroke: '#fb923c', text: '#fdba74' },
text: '#9a3412', badge: 'bg-orange-100 dark:bg-orange-900/40 text-orange-700 dark:text-orange-300'
badge: 'bg-orange-100 text-orange-700'
}; };
case AgentType.ASSISTANT: case AgentType.ASSISTANT:
return { return {
fill: '#ccfbf1', light: { fill: '#ccfbf1', stroke: '#14b8a6', text: '#115e59' },
stroke: '#14b8a6', dark: { fill: '#134e4a', stroke: '#2dd4bf', text: '#5eead4' },
text: '#115e59', badge: 'bg-teal-100 dark:bg-teal-900/40 text-teal-700 dark:text-teal-300'
badge: 'bg-teal-100 text-teal-700'
}; };
default: default:
return { return {
fill: '#f3f4f6', light: { fill: '#f3f4f6', stroke: '#9ca3af', text: '#374151' },
stroke: '#9ca3af', dark: { fill: '#1f2937', stroke: '#6b7280', text: '#9ca3af' },
text: '#374151', badge: 'bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300'
badge: 'bg-gray-100 text-gray-700'
}; };
} }
} }
@@ -149,52 +151,3 @@ export function buildLineageTree(agents: SimpleAgentIdentifier[]): LineageNode[]
return roots; return roots;
} }
/**
* Returns sample/demo lineage data for visualization development.
* This will be replaced with real API data when available.
*/
export function getSampleLineageData(): SimpleAgentIdentifier[] {
return [
{
agentId: 'orch-001',
agentType: AgentType.ORCHESTRATOR,
spawnDepth: 0
},
{
agentId: 'research-001',
agentType: AgentType.RESEARCHER,
spawnDepth: 1,
parentId: 'orch-001'
},
{
agentId: 'coder-001',
agentType: AgentType.CODER,
spawnDepth: 1,
parentId: 'orch-001'
},
{
agentId: 'sysadmin-001',
agentType: AgentType.SYSADMIN,
spawnDepth: 1,
parentId: 'orch-001'
},
{
agentId: 'assist-001',
agentType: AgentType.ASSISTANT,
spawnDepth: 2,
parentId: 'research-001'
},
{
agentId: 'coder-002',
agentType: AgentType.CODER,
spawnDepth: 2,
parentId: 'coder-001'
},
{
agentId: 'research-002',
agentType: AgentType.RESEARCHER,
spawnDepth: 3,
parentId: 'coder-002'
}
];
}

View File

@@ -0,0 +1,23 @@
import { ResultSource } from '$lib/proto/llm_multiverse/v1/common_pb';
export interface ResultSourceStyle {
label: string;
bg: string;
text: string;
}
/**
* Returns label and badge classes for a ResultSource value.
*/
export function resultSourceConfig(source: ResultSource): ResultSourceStyle {
switch (source) {
case ResultSource.TOOL_OUTPUT:
return { label: 'Tool Output', bg: 'bg-blue-100 dark:bg-blue-900/40', text: 'text-blue-800 dark:text-blue-300' };
case ResultSource.MODEL_KNOWLEDGE:
return { label: 'Model Knowledge', bg: 'bg-purple-100 dark:bg-purple-900/40', text: 'text-purple-800 dark:text-purple-300' };
case ResultSource.WEB:
return { label: 'Web', bg: 'bg-green-100 dark:bg-green-900/40', text: 'text-green-800 dark:text-green-300' };
default:
return { label: 'Unspecified', bg: 'bg-gray-100 dark:bg-gray-800', text: 'text-gray-800 dark:text-gray-300' };
}
}

19
src/lib/utils/date.ts Normal file
View File

@@ -0,0 +1,19 @@
/**
* Formats a date as a relative string: "Today", "Yesterday", "N days ago", or locale date.
*/
export function formatRelativeDate(date: Date): string {
const now = new Date();
const diff = now.getTime() - date.getTime();
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
if (days === 0) return 'Today';
if (days === 1) return 'Yesterday';
if (days < 7) return `${days} days ago`;
return date.toLocaleDateString();
}
/**
* Formats a date as a short string like "Mar 12, 2026".
*/
export function formatShortDate(date: Date): string {
return date.toLocaleDateString([], { month: 'short', day: 'numeric', year: 'numeric' });
}

60
src/lib/utils/logger.ts Normal file
View File

@@ -0,0 +1,60 @@
/**
* Lightweight dev-mode logging utility.
* All diagnostic logging flows through this module.
*/
import { ConnectError } from '@connectrpc/connect';
declare global {
var __LLM_DEBUG: boolean | undefined;
}
function isDebugEnabled(): boolean {
return import.meta.env.DEV || globalThis.__LLM_DEBUG === true;
}
function fmt(tag: string, message: string): string {
return `[${tag}] ${message}`;
}
export const logger = {
debug(tag: string, message: string, ...data: unknown[]): void {
if (isDebugEnabled()) {
console.debug(fmt(tag, message), ...data);
}
},
info(tag: string, message: string, ...data: unknown[]): void {
if (isDebugEnabled()) {
console.info(fmt(tag, message), ...data);
}
},
warn(tag: string, message: string, ...data: unknown[]): void {
if (isDebugEnabled()) {
console.warn(fmt(tag, message), ...data);
}
},
error(tag: string, message: string, ...data: unknown[]): void {
if (isDebugEnabled()) {
console.error(fmt(tag, message), ...data);
}
},
/** Always logs regardless of debug toggle. Destructures ConnectError fields. */
grpcError(tag: string, label: string, err: unknown): void {
if (err instanceof ConnectError) {
console.error(fmt(tag, label), {
code: err.code,
rawMessage: err.rawMessage,
cause: err.cause,
metadata: Object.fromEntries(err.metadata.entries())
});
} else if (err instanceof Error) {
console.error(fmt(tag, label), { message: err.message });
} else {
console.error(fmt(tag, label), err);
}
}
};

View File

@@ -0,0 +1,13 @@
import { OverrideLevel } from '$lib/proto/llm_multiverse/v1/common_pb';
import type { SessionConfig } from '$lib/proto/llm_multiverse/v1/orchestrator_pb';
/**
* Returns true if the session config differs from defaults.
*/
export function isNonDefaultConfig(config: SessionConfig): boolean {
return (
config.overrideLevel !== OverrideLevel.NONE ||
config.disabledTools.length > 0 ||
config.grantedPermissions.length > 0
);
}

View File

@@ -1,13 +1,15 @@
<script lang="ts"> <script lang="ts">
import favicon from '$lib/assets/favicon.svg'; import favicon from '$lib/assets/favicon.svg';
import '../app.css'; import '../app.css';
import { onMount } from 'svelte';
import { themeStore } from '$lib/stores/theme.svelte'; import { themeStore } from '$lib/stores/theme.svelte';
import ToastContainer from '$lib/components/ToastContainer.svelte'; import ToastContainer from '$lib/components/ToastContainer.svelte';
let { children } = $props(); let { children } = $props();
$effect(() => { onMount(() => {
themeStore.init(); const cleanup = themeStore.init();
return cleanup;
}); });
</script> </script>

2
src/routes/+page.ts Normal file
View File

@@ -0,0 +1,2 @@
export const prerender = false;
export const ssr = false;

View File

@@ -3,7 +3,7 @@
import { goto } from '$app/navigation'; import { goto } from '$app/navigation';
import { resolveRoute } from '$app/paths'; import { resolveRoute } from '$app/paths';
import AuditTimeline from '$lib/components/AuditTimeline.svelte'; import AuditTimeline from '$lib/components/AuditTimeline.svelte';
import ThemeToggle from '$lib/components/ThemeToggle.svelte'; import PageHeader from '$lib/components/PageHeader.svelte';
import { auditStore } from '$lib/stores/audit.svelte'; import { auditStore } from '$lib/stores/audit.svelte';
import type { AuditEventType } from '$lib/stores/audit.svelte'; import type { AuditEventType } from '$lib/stores/audit.svelte';
@@ -40,26 +40,7 @@
</script> </script>
<div class="flex h-screen flex-col overflow-hidden bg-gray-50 dark:bg-gray-900"> <div class="flex h-screen flex-col overflow-hidden bg-gray-50 dark:bg-gray-900">
<!-- Header --> <PageHeader title="Audit Log" backHref={chatHref} />
<header class="flex items-center justify-between border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 px-4 py-3 md:px-6">
<div class="flex items-center gap-2 md:gap-4">
<!-- eslint-disable svelte/no-navigation-without-resolve -- resolveRoute is resolve; plugin does not recognize the alias -->
<a
href={chatHref}
class="rounded-lg px-2.5 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 hover:text-gray-900 dark:hover:text-gray-100"
>
&larr; Chat
</a>
<!-- eslint-enable svelte/no-navigation-without-resolve -->
<h1 class="text-base md:text-lg font-semibold text-gray-900 dark:text-gray-100">Audit Log</h1>
</div>
<div class="flex items-center gap-2">
<ThemeToggle />
<span class="hidden sm:inline rounded-md bg-amber-50 dark:bg-amber-900/30 px-2 py-1 text-xs text-amber-700 dark:text-amber-300">
Sample Data
</span>
</div>
</header>
<!-- Filters --> <!-- Filters -->
<div class="border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 px-4 py-3 md:px-6"> <div class="border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 px-4 py-3 md:px-6">

View File

@@ -3,7 +3,6 @@
import { goto } from '$app/navigation'; import { goto } from '$app/navigation';
import { resolveRoute } from '$app/paths'; import { resolveRoute } from '$app/paths';
import type { ChatMessage } from '$lib/types'; 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 { OverrideLevel } from '$lib/proto/llm_multiverse/v1/common_pb';
import type { SessionConfig } from '$lib/proto/llm_multiverse/v1/orchestrator_pb'; import type { SessionConfig } from '$lib/proto/llm_multiverse/v1/orchestrator_pb';
import { SessionConfigSchema } from '$lib/proto/llm_multiverse/v1/orchestrator_pb'; import { SessionConfigSchema } from '$lib/proto/llm_multiverse/v1/orchestrator_pb';
@@ -13,24 +12,18 @@
import OrchestrationProgress from '$lib/components/OrchestrationProgress.svelte'; import OrchestrationProgress from '$lib/components/OrchestrationProgress.svelte';
import ThinkingSection from '$lib/components/ThinkingSection.svelte'; import ThinkingSection from '$lib/components/ThinkingSection.svelte';
import FinalResult from '$lib/components/FinalResult.svelte'; import FinalResult from '$lib/components/FinalResult.svelte';
import InferenceStatsPanel from '$lib/components/InferenceStatsPanel.svelte';
import SessionSidebar from '$lib/components/SessionSidebar.svelte'; import SessionSidebar from '$lib/components/SessionSidebar.svelte';
import ConfigSidebar from '$lib/components/ConfigSidebar.svelte'; import ConfigSidebar from '$lib/components/ConfigSidebar.svelte';
import ThemeToggle from '$lib/components/ThemeToggle.svelte'; import ThemeToggle from '$lib/components/ThemeToggle.svelte';
import ConnectionStatus from '$lib/components/ConnectionStatus.svelte'; import ConnectionStatus from '$lib/components/ConnectionStatus.svelte';
import { processRequest, OrchestratorError, friendlyMessage } from '$lib/services/orchestrator'; import { onMount, untrack } from 'svelte';
import { OrchestrationState } from '$lib/proto/llm_multiverse/v1/orchestrator_pb';
import { sessionStore } from '$lib/stores/sessions.svelte'; import { sessionStore } from '$lib/stores/sessions.svelte';
import { memoryStore } from '$lib/stores/memory.svelte'; import { isNonDefaultConfig } from '$lib/utils/sessionConfig';
import { auditStore } from '$lib/stores/audit.svelte'; import { orchestrationStore as orchestration } from '$lib/composables/useOrchestration.svelte';
import { toastStore } from '$lib/stores/toast.svelte';
let messages: ChatMessage[] = $state([]); let messages: ChatMessage[] = $state([]);
let isStreaming = $state(false); let initialized = $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( let sessionConfig: SessionConfig = $state(
create(SessionConfigSchema, { overrideLevel: OverrideLevel.NONE }) create(SessionConfigSchema, { overrideLevel: OverrideLevel.NONE })
); );
@@ -39,12 +32,7 @@
const lineageHref = resolveRoute('/lineage'); const lineageHref = resolveRoute('/lineage');
const memoryHref = resolveRoute('/memory'); const memoryHref = resolveRoute('/memory');
const auditHref = resolveRoute('/audit'); const auditHref = resolveRoute('/audit');
const hasNonDefaultConfig = $derived(isNonDefaultConfig(sessionConfig));
const isNonDefaultConfig = $derived(
sessionConfig.overrideLevel !== OverrideLevel.NONE ||
sessionConfig.disabledTools.length > 0 ||
sessionConfig.grantedPermissions.length > 0
);
function navigateToSession(sessionId: string, replace = false) { function navigateToSession(sessionId: string, replace = false) {
const url = `${resolveRoute('/chat')}?session=${sessionId}`; const url = `${resolveRoute('/chat')}?session=${sessionId}`;
@@ -52,20 +40,32 @@
goto(url, { replaceState: replace }); goto(url, { replaceState: replace });
} }
$effect(() => { onMount(() => {
const sessionParam = $page.url.searchParams.get('session'); const sessionParam = $page.url.searchParams.get('session');
const session = sessionStore.getOrCreateSession(sessionParam ?? undefined); const session = sessionStore.getOrCreateSession(sessionParam ?? undefined);
messages = [...session.messages]; messages = [...session.messages];
if (!sessionParam || sessionParam !== session.id) { if (!sessionParam || sessionParam !== session.id) {
navigateToSession(session.id, true); navigateToSession(session.id, true);
} }
initialized = true;
});
// Sync messages when session changes via sidebar (after initial mount)
$effect(() => {
if (!initialized) return;
const sessionParam = $page.url.searchParams.get('session');
if (sessionParam) {
const session = untrack(() => sessionStore.activeSession);
if (session && session.id === sessionParam) {
messages = [...session.messages];
}
}
}); });
function handleNewChat() { function handleNewChat() {
const session = sessionStore.createSession(); const session = sessionStore.createSession();
messages = []; messages = [];
error = null; orchestration.reset();
finalResult = null;
navigateToSession(session.id); navigateToSession(session.id);
} }
@@ -74,109 +74,20 @@
const session = sessionStore.activeSession; const session = sessionStore.activeSession;
if (session) { if (session) {
messages = [...session.messages]; messages = [...session.messages];
error = null; orchestration.reset();
finalResult = null;
navigateToSession(id); navigateToSession(id);
} }
} }
async function handleSend(content: string) { async function handleSend(content: string) {
error = null;
lastFailedContent = null;
orchestrationState = OrchestrationState.UNSPECIFIED;
intermediateResult = '';
finalResult = null;
const sessionId = sessionStore.activeSessionId!; const sessionId = sessionStore.activeSessionId!;
let lastAuditState = OrchestrationState.UNSPECIFIED; messages = await orchestration.send(sessionId, content, sessionConfig, messages);
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);
}
} }
function handleRetry() { function handleRetry() {
if (!lastFailedContent) return; const sessionId = sessionStore.activeSessionId!;
const content = lastFailedContent; const result = orchestration.retry(sessionId, sessionConfig, messages);
// Remove the failed assistant message before retrying messages = result.messages;
if (messages.length >= 2) {
messages = messages.slice(0, -2);
}
handleSend(content);
} }
</script> </script>
@@ -240,7 +151,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 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'}" {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> <span class="h-2 w-2 rounded-full bg-amber-500"></span>
{/if} {/if}
<span class="hidden sm:inline">Config</span> <span class="hidden sm:inline">Config</span>
@@ -255,12 +166,12 @@
<MessageList {messages} /> <MessageList {messages} />
{#if isStreaming} {#if orchestration.isStreaming}
<OrchestrationProgress state={orchestrationState} /> <OrchestrationProgress state={orchestration.orchestrationState} />
<ThinkingSection content={intermediateResult} /> <ThinkingSection content={orchestration.intermediateResult} />
{/if} {/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 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"> <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]" <span class="h-2 w-2 animate-bounce rounded-full bg-gray-500 dark:bg-gray-400 [animation-delay:0ms]"
@@ -275,18 +186,22 @@
</div> </div>
{/if} {/if}
{#if finalResult && !isStreaming} {#if orchestration.finalResult && !orchestration.isStreaming}
<FinalResult result={finalResult} /> <FinalResult result={orchestration.finalResult} />
{/if} {/if}
{#if error} {#if orchestration.inferenceStats && !orchestration.isStreaming}
<InferenceStatsPanel stats={orchestration.inferenceStats} />
{/if}
{#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"> <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> <span>{orchestration.error}</span>
{#if lastFailedContent} {#if orchestration.lastFailedContent}
<button <button
type="button" type="button"
onclick={handleRetry} 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" 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 Retry
@@ -295,7 +210,7 @@
</div> </div>
{/if} {/if}
<MessageInput onSend={handleSend} disabled={isStreaming} /> <MessageInput onSend={handleSend} disabled={orchestration.isStreaming} />
</div> </div>
{#if showConfig} {#if showConfig}

2
src/routes/chat/+page.ts Normal file
View File

@@ -0,0 +1,2 @@
export const prerender = false;
export const ssr = false;

View File

@@ -2,18 +2,19 @@
import { resolveRoute } from '$app/paths'; import { resolveRoute } from '$app/paths';
import { AgentType } from '$lib/proto/llm_multiverse/v1/common_pb'; import { AgentType } from '$lib/proto/llm_multiverse/v1/common_pb';
import LineageTree from '$lib/components/LineageTree.svelte'; import LineageTree from '$lib/components/LineageTree.svelte';
import ThemeToggle from '$lib/components/ThemeToggle.svelte'; import PageHeader from '$lib/components/PageHeader.svelte';
import Backdrop from '$lib/components/Backdrop.svelte';
import type { LineageNode, SimpleAgentIdentifier } from '$lib/types/lineage'; import type { LineageNode, SimpleAgentIdentifier } from '$lib/types/lineage';
import { import {
buildLineageTree, buildLineageTree,
getSampleLineageData,
agentTypeLabel, agentTypeLabel,
agentTypeColor agentTypeColor
} from '$lib/types/lineage'; } from '$lib/types/lineage';
import { themeStore } from '$lib/stores/theme.svelte';
const chatHref = resolveRoute('/chat'); const chatHref = resolveRoute('/chat');
let agents: SimpleAgentIdentifier[] = $state(getSampleLineageData()); let agents: SimpleAgentIdentifier[] = $state([]);
let treeNodes: LineageNode[] = $derived(buildLineageTree(agents)); let treeNodes: LineageNode[] = $derived(buildLineageTree(agents));
let selectedNode: LineageNode | null = $state(null); let selectedNode: LineageNode | null = $state(null);
@@ -32,26 +33,7 @@
</script> </script>
<div class="flex h-screen flex-col overflow-hidden bg-gray-50 dark:bg-gray-900"> <div class="flex h-screen flex-col overflow-hidden bg-gray-50 dark:bg-gray-900">
<!-- Header --> <PageHeader title="Agent Lineage" backHref={chatHref} />
<header class="flex items-center justify-between border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 px-4 py-3 md:px-6">
<div class="flex items-center gap-2 md:gap-4">
<!-- eslint-disable svelte/no-navigation-without-resolve -- resolveRoute is resolve; plugin does not recognize the alias -->
<a
href={chatHref}
class="rounded-lg px-2.5 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 hover:text-gray-900 dark:hover:text-gray-100"
>
&larr; Chat
</a>
<!-- eslint-enable svelte/no-navigation-without-resolve -->
<h1 class="text-base md:text-lg font-semibold text-gray-900 dark:text-gray-100">Agent Lineage</h1>
</div>
<div class="flex items-center gap-2">
<ThemeToggle />
<span class="hidden sm:inline rounded-md bg-amber-50 dark:bg-amber-900/30 px-2 py-1 text-xs text-amber-700 dark:text-amber-300">
Sample Data
</span>
</div>
</header>
<div class="flex flex-1 flex-col md:flex-row overflow-hidden"> <div class="flex flex-1 flex-col md:flex-row overflow-hidden">
<!-- Main tree area --> <!-- Main tree area -->
@@ -63,12 +45,13 @@
<span class="text-xs font-medium text-gray-500 dark:text-gray-400">Agent Types:</span> <span class="text-xs font-medium text-gray-500 dark:text-gray-400">Agent Types:</span>
{#each agentTypeLegend as type (type)} {#each agentTypeLegend as type (type)}
{@const colors = agentTypeColor(type)} {@const colors = agentTypeColor(type)}
{@const colorSet = themeStore.isDark ? colors.dark : colors.light}
<span <span
class="inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-xs font-medium {colors.badge}" class="inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-xs font-medium {colors.badge}"
> >
<span <span
class="h-2 w-2 rounded-full" class="h-2 w-2 rounded-full"
style="background-color: {colors.stroke}" style="background-color: {colorSet.stroke}"
></span> ></span>
{agentTypeLabel(type)} {agentTypeLabel(type)}
</span> </span>
@@ -79,15 +62,8 @@
<!-- Detail panel: overlay on mobile, side panel on desktop --> <!-- Detail panel: overlay on mobile, side panel on desktop -->
{#if selectedNode} {#if selectedNode}
{@const colors = agentTypeColor(selectedNode.agentType)} {@const colors = agentTypeColor(selectedNode.agentType)}
<!-- Mobile backdrop --> {@const colorSet = themeStore.isDark ? colors.dark : colors.light}
<div <Backdrop onClose={() => (selectedNode = null)} />
class="fixed inset-0 z-40 bg-black/50 md:hidden"
role="button"
tabindex="-1"
onclick={() => (selectedNode = null)}
onkeydown={(e) => { if (e.key === 'Escape') selectedNode = null; }}
aria-label="Close detail panel"
></div>
<aside <aside
class="fixed inset-y-0 right-0 z-50 w-72 shrink-0 border-l border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 p-4 overflow-y-auto class="fixed inset-y-0 right-0 z-50 w-72 shrink-0 border-l border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 p-4 overflow-y-auto
md:relative md:z-auto" md:relative md:z-auto"
@@ -117,7 +93,7 @@
> >
<span <span
class="h-2 w-2 rounded-full" class="h-2 w-2 rounded-full"
style="background-color: {colors.stroke}" style="background-color: {colorSet.stroke}"
></span> ></span>
{agentTypeLabel(selectedNode.agentType)} {agentTypeLabel(selectedNode.agentType)}
</span> </span>
@@ -139,12 +115,13 @@
<ul class="mt-1 space-y-1"> <ul class="mt-1 space-y-1">
{#each selectedNode.children as child (child.id)} {#each selectedNode.children as child (child.id)}
{@const childColors = agentTypeColor(child.agentType)} {@const childColors = agentTypeColor(child.agentType)}
{@const childColorSet = themeStore.isDark ? childColors.dark : childColors.light}
<li <li
class="flex items-center gap-2 rounded-md border border-gray-100 dark:border-gray-700 px-2 py-1.5" class="flex items-center gap-2 rounded-md border border-gray-100 dark:border-gray-700 px-2 py-1.5"
> >
<span <span
class="h-2 w-2 shrink-0 rounded-full" class="h-2 w-2 shrink-0 rounded-full"
style="background-color: {childColors.stroke}" style="background-color: {childColorSet.stroke}"
></span> ></span>
<span class="truncate font-mono text-xs text-gray-700 dark:text-gray-300">{child.id}</span> <span class="truncate font-mono text-xs text-gray-700 dark:text-gray-300">{child.id}</span>
</li> </li>

View File

@@ -2,7 +2,7 @@
import { resolveRoute } from '$app/paths'; import { resolveRoute } from '$app/paths';
import { ResultSource } from '$lib/proto/llm_multiverse/v1/common_pb'; import { ResultSource } from '$lib/proto/llm_multiverse/v1/common_pb';
import MemoryCandidateCard from '$lib/components/MemoryCandidateCard.svelte'; import MemoryCandidateCard from '$lib/components/MemoryCandidateCard.svelte';
import ThemeToggle from '$lib/components/ThemeToggle.svelte'; import PageHeader from '$lib/components/PageHeader.svelte';
import { memoryStore } from '$lib/stores/memory.svelte'; import { memoryStore } from '$lib/stores/memory.svelte';
const chatHref = resolveRoute('/chat'); const chatHref = resolveRoute('/chat');
@@ -39,26 +39,7 @@
</script> </script>
<div class="flex h-screen flex-col overflow-hidden bg-gray-50 dark:bg-gray-900"> <div class="flex h-screen flex-col overflow-hidden bg-gray-50 dark:bg-gray-900">
<!-- Header --> <PageHeader title="Memory Candidates" backHref={chatHref} />
<header class="flex items-center justify-between border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 px-4 py-3 md:px-6">
<div class="flex items-center gap-2 md:gap-4">
<!-- eslint-disable svelte/no-navigation-without-resolve -- resolveRoute is resolve; plugin does not recognize the alias -->
<a
href={chatHref}
class="rounded-lg px-2.5 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 hover:text-gray-900 dark:hover:text-gray-100"
>
&larr; Chat
</a>
<!-- eslint-enable svelte/no-navigation-without-resolve -->
<h1 class="text-base md:text-lg font-semibold text-gray-900 dark:text-gray-100">Memory Candidates</h1>
</div>
<div class="flex items-center gap-2">
<ThemeToggle />
<span class="hidden sm:inline rounded-md bg-amber-50 dark:bg-amber-900/30 px-2 py-1 text-xs text-amber-700 dark:text-amber-300">
Sample Data
</span>
</div>
</header>
<!-- Filters --> <!-- Filters -->
<div class="border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 px-4 py-3 md:px-6"> <div class="border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 px-4 py-3 md:px-6">

View File

@@ -3,5 +3,13 @@ import tailwindcss from '@tailwindcss/vite';
import { defineConfig } from 'vite'; import { defineConfig } from 'vite';
export default defineConfig({ export default defineConfig({
plugins: [tailwindcss(), sveltekit()] plugins: [tailwindcss(), sveltekit()],
server: {
proxy: {
'/llm_multiverse.v1.OrchestratorService': {
target: 'http://localhost:8080',
changeOrigin: true
}
}
}
}); });