summaryrefslogtreecommitdiffhomepage
path: root/packages/frontend/src
diff options
context:
space:
mode:
authorAdam Malczewski <[email protected]>2026-06-02 13:57:41 +0900
committerAdam Malczewski <[email protected]>2026-06-02 13:57:41 +0900
commitd27d97bb3aa0c13f4032bab54703ebb9e1c84c81 (patch)
treeb5bcfed65be5a4d27a7bbe6b46e338dcd489c2e0 /packages/frontend/src
parent3671b82cc624117476e30b95eaf7d2bc3b34ae28 (diff)
parentc1439ea8c677ddfd11c219de39c3e77c7e297a9b (diff)
downloaddispatch-d27d97bb3aa0c13f4032bab54703ebb9e1c84c81.tar.gz
dispatch-d27d97bb3aa0c13f4032bab54703ebb9e1c84c81.zip
Merge branch 'dev' into u3/agent-effort-level
# Conflicts: # packages/api/tests/agent-manager.test.ts
Diffstat (limited to 'packages/frontend/src')
-rw-r--r--packages/frontend/src/App.svelte57
-rw-r--r--packages/frontend/src/lib/components/ContextWindowPanel.svelte85
-rw-r--r--packages/frontend/src/lib/components/SidebarPanel.svelte11
-rw-r--r--packages/frontend/src/lib/context-window.ts37
-rw-r--r--packages/frontend/src/lib/tabs.svelte.ts17
-rw-r--r--packages/frontend/src/lib/types.ts7
6 files changed, 213 insertions, 1 deletions
diff --git a/packages/frontend/src/App.svelte b/packages/frontend/src/App.svelte
index 3f1c500..ecfdc9f 100644
--- a/packages/frontend/src/App.svelte
+++ b/packages/frontend/src/App.svelte
@@ -75,6 +75,62 @@ $effect(() => {
}
});
+// ─── Context-window max lookup ─────────────────────────────────
+// Resolve the active model's MAXIMUM context window from models.dev (via the
+// API), so the Context Window sidebar view can show `current / max`. Cached
+// per provider+model; `null` when unknown (the view then hides the
+// denominator/percentage). Only Claude-backed providers are resolvable.
+let contextLimit = $state<number | null>(null);
+const contextLimitCache = new Map<string, number | null>();
+
+$effect(() => {
+ const tab = tabStore.activeTab;
+ const keyId = tab?.keyId ?? null;
+ const modelId = tab?.modelId ?? null;
+ const provider = keyId ? (modelsData.keys.find((k) => k.id === keyId)?.provider ?? null) : null;
+
+ if (!provider || !modelId) {
+ contextLimit = null;
+ return;
+ }
+
+ const cacheKey = `${provider}/${modelId}`;
+ if (contextLimitCache.has(cacheKey)) {
+ contextLimit = contextLimitCache.get(cacheKey) ?? null;
+ return;
+ }
+
+ // Clear immediately so a slow/failed fetch can't leave the PREVIOUS
+ // model's max on screen (which would render this model's tokens against
+ // the wrong denominator). The view degrades to a bare token count until
+ // the fetch resolves.
+ contextLimit = null;
+
+ // Fetch is async; guard against a stale response overwriting a newer
+ // selection by re-checking the active tab's key/model on resolve.
+ void (async () => {
+ try {
+ const res = await fetch(
+ `${config.apiBase}/models/context-limit?provider=${encodeURIComponent(provider)}&modelId=${encodeURIComponent(modelId)}`,
+ );
+ if (!res.ok) return;
+ const data = (await res.json()) as { contextLimit?: number | null };
+ const limit = data.contextLimit ?? null;
+ contextLimitCache.set(cacheKey, limit);
+ const current = tabStore.activeTab;
+ const currentProvider = current?.keyId
+ ? (modelsData.keys.find((k) => k.id === current.keyId)?.provider ?? null)
+ : null;
+ if (currentProvider === provider && current?.modelId === modelId) {
+ contextLimit = limit;
+ }
+ } catch {
+ // Leave contextLimit as-is on network error; view falls back to
+ // showing the bare token count.
+ }
+ })();
+});
+
onMount(() => {
// Apply persisted theme (or the shared DEFAULT_THEME if nothing is
// stored) so the first paint matches what the Settings panel will
@@ -138,6 +194,7 @@ onMount(() => {
tasks={tabStore.activeTab?.tasks ?? []}
cacheStats={tabStore.activeTab?.cacheStats ?? null}
cacheTabTitle={tabStore.activeTab?.title ?? null}
+ {contextLimit}
permissionLog={tabStore.permissionLog}
apiBase={config.apiBase}
activeKeyId={tabStore.activeTab?.keyId ?? null}
diff --git a/packages/frontend/src/lib/components/ContextWindowPanel.svelte b/packages/frontend/src/lib/components/ContextWindowPanel.svelte
new file mode 100644
index 0000000..6c7de05
--- /dev/null
+++ b/packages/frontend/src/lib/components/ContextWindowPanel.svelte
@@ -0,0 +1,85 @@
+<script lang="ts">
+import { computeContextUsage } from "../context-window.js";
+import type { CacheStats } from "../types.js";
+
+const {
+ cacheStats = null,
+ contextLimit = null,
+ tabTitle = null,
+ modelId = null,
+}: {
+ cacheStats?: CacheStats | null;
+ contextLimit?: number | null;
+ tabTitle?: string | null;
+ modelId?: string | null;
+} = $props();
+
+const usage = $derived(computeContextUsage(cacheStats, contextLimit));
+
+// As the window fills, escalate color: calm → warning → danger.
+function fillClass(pct: number): string {
+ if (pct >= 90) return "progress-error";
+ if (pct >= 70) return "progress-warning";
+ return "progress-success";
+}
+
+function fmt(n: number): string {
+ return n.toLocaleString();
+}
+
+const hasUsage = $derived((cacheStats?.last ?? null) !== null);
+</script>
+
+<div class="flex flex-col gap-3 flex-1 min-h-0 overflow-y-auto">
+ {#if !hasUsage}
+ <p class="text-xs text-base-content/50">
+ No context data yet. Send a message — the current context size appears
+ here after the first response.
+ </p>
+ {:else}
+ <div class="bg-base-200 rounded-lg p-2">
+ <div class="flex items-center gap-1.5 mb-2">
+ <span class="text-xs font-semibold">Context Window</span>
+ {#if tabTitle}
+ <span class="badge badge-xs badge-ghost">{tabTitle}</span>
+ {/if}
+ {#if usage.percent !== null}
+ <span class="badge badge-xs ml-auto">{usage.percent.toFixed(2)}%</span>
+ {/if}
+ </div>
+
+ <!-- Headline: current / max (or just current when max is unknown) -->
+ <div class="flex items-baseline gap-1.5">
+ <span class="text-lg font-mono font-semibold">{fmt(usage.current)}</span>
+ {#if usage.max !== null}
+ <span class="text-xs text-base-content/50 font-mono">/ {fmt(usage.max)}</span>
+ {/if}
+ <span class="text-xs text-base-content/40 ml-1">tokens</span>
+ </div>
+
+ {#if usage.percent !== null}
+ <progress
+ class="progress w-full h-2 mt-1.5 {fillClass(usage.percent)}"
+ value={usage.percent}
+ max="100"
+ ></progress>
+ {:else}
+ <p class="text-xs text-base-content/40 mt-1.5">
+ Max context size unknown for this model.
+ </p>
+ {/if}
+
+ {#if modelId}
+ <div class="text-xs text-base-content/40 mt-1.5 truncate" title={modelId}>
+ {modelId}
+ </div>
+ {/if}
+ </div>
+
+ <p class="text-xs text-base-content/40">
+ Current context = the most recent request's prompt + output (what the
+ model actually held in its window that turn). Grows as the conversation
+ gets longer. Resets on reload.
+ </p>
+ {/if}
+</div>
diff --git a/packages/frontend/src/lib/components/SidebarPanel.svelte b/packages/frontend/src/lib/components/SidebarPanel.svelte
index 3372396..519f411 100644
--- a/packages/frontend/src/lib/components/SidebarPanel.svelte
+++ b/packages/frontend/src/lib/components/SidebarPanel.svelte
@@ -4,6 +4,7 @@ import type { CacheStats, KeyInfo, LogEntry, TaskItem } from "../types.js";
import CacheRatePanel from "./CacheRatePanel.svelte";
import ClaudeReset from "./ClaudeReset.svelte";
import ConfigPanel from "./ConfigPanel.svelte";
+import ContextWindowPanel from "./ContextWindowPanel.svelte";
import DebugPanel from "./DebugPanel.svelte";
import KeyUsage from "./KeyUsage.svelte";
import ModelSelector from "./ModelSelector.svelte";
@@ -27,6 +28,7 @@ const {
tasks = [],
cacheStats = null,
cacheTabTitle = null,
+ contextLimit = null,
permissionLog = [],
apiBase = "",
activeKeyId = null,
@@ -47,6 +49,7 @@ const {
tasks?: TaskItem[];
cacheStats?: CacheStats | null;
cacheTabTitle?: string | null;
+ contextLimit?: number | null;
permissionLog?: LogEntry[];
apiBase?: string;
activeKeyId?: string | null;
@@ -89,6 +92,7 @@ const viewOptions = [
"Chat Settings",
"Key Usage",
"Cache Rate",
+ "Context Window",
"Claude Reset",
"Model Status",
"Tasks",
@@ -170,6 +174,13 @@ function contentClass(_selected: string): string {
<KeyUsage {keys} {apiBase} />
{:else if panel.selected === "Cache Rate"}
<CacheRatePanel {cacheStats} tabTitle={cacheTabTitle} />
+ {:else if panel.selected === "Context Window"}
+ <ContextWindowPanel
+ {cacheStats}
+ {contextLimit}
+ tabTitle={cacheTabTitle}
+ modelId={activeModelId}
+ />
{:else if panel.selected === "Claude Reset"}
<ClaudeReset {apiBase} />
{:else if panel.selected === "Model Status"}
diff --git a/packages/frontend/src/lib/context-window.ts b/packages/frontend/src/lib/context-window.ts
new file mode 100644
index 0000000..c4321f8
--- /dev/null
+++ b/packages/frontend/src/lib/context-window.ts
@@ -0,0 +1,37 @@
+import type { CacheStats } from "./types.js";
+
+/**
+ * Context-window occupancy for the current tab/model.
+ *
+ * `current` is the size of the model's context on the MOST RECENT request —
+ * the last turn's full prompt (`inputTokens`, which already includes cached
+ * tokens for Anthropic) plus what the model generated that turn
+ * (`outputTokens`). This mirrors how opencode derives context fullness from
+ * the last assistant message, and reflects what actually occupies the model's
+ * window — NOT the session-cumulative totals shown by the Cache Rate view.
+ *
+ * `max` is the model's maximum context window from models.dev (or `null` when
+ * unknown). `percent` is `current / max * 100` clamped to [0, 100] (unrounded;
+ * the UI decides the displayed precision), or `null` when
+ * `max` is unknown — in which case the UI shows the bare token count with no
+ * denominator or progress bar.
+ */
+export interface ContextUsage {
+ current: number;
+ max: number | null;
+ percent: number | null;
+}
+
+export function computeContextUsage(
+ cacheStats: CacheStats | null | undefined,
+ contextLimit: number | null | undefined,
+): ContextUsage {
+ const last = cacheStats?.last ?? null;
+ const current = last ? last.inputTokens + last.outputTokens : 0;
+ const max = typeof contextLimit === "number" && contextLimit > 0 ? contextLimit : null;
+ // Precise (unrounded) percentage clamped to [0, 100]; the UI formats the
+ // decimal places. Kept unrounded so small contexts against huge windows
+ // (e.g. a few thousand tokens vs. 1,000,000) still read non-zero.
+ const percent = max ? Math.max(0, Math.min(100, (current / max) * 100)) : null;
+ return { current, max, percent };
+}
diff --git a/packages/frontend/src/lib/tabs.svelte.ts b/packages/frontend/src/lib/tabs.svelte.ts
index d3061c3..ec718bd 100644
--- a/packages/frontend/src/lib/tabs.svelte.ts
+++ b/packages/frontend/src/lib/tabs.svelte.ts
@@ -761,6 +761,13 @@ export function createTabStore() {
keyId?: string | null;
modelId?: string | null;
parentTabId?: string | null;
+ // Backend usage aggregate (GET /tabs). Structurally identical to
+ // CacheStats, so it seeds `cacheStats` directly on reload. This is the
+ // initial seed (hydrate runs only when tabs.length === 0, i.e. a true
+ // reload); thereafter `turn-sealed` REPLACES cacheStats with the same
+ // aggregate each turn, keeping the live accumulator reconciled to the DB
+ // truth. Neither path ADDS to live events, so there is no double-count.
+ usageStats?: CacheStats | null;
}> = [];
try {
const res = await fetch(`${config.apiBase}/tabs`);
@@ -849,6 +856,7 @@ export function createTabStore() {
chunkLimit: appSettings.chunkLimit,
oldestLoadedSeq: win.oldestSeq,
totalChunks: win.total,
+ cacheStats: row.usageStats ?? undefined,
};
});
@@ -933,6 +941,15 @@ export function createTabStore() {
// tail into the sealed chunk log (refetch real seqs), preserving any
// newer in-flight turn. Deferred while scrolled up.
reconcileSealedTurn(tabId, event.turnId);
+ // Reconcile cacheStats to the DB source-of-truth carried on the event.
+ // REPLACE (not add): the aggregate already includes every persisted
+ // usage row for this tab, so this both lands the just-sealed turn's
+ // usage AND self-heals any live overshoot (e.g. a rate-limited
+ // fallback attempt streamed usage live but was discarded server-side).
+ // `usageStats === undefined` (older backend) leaves cacheStats as-is.
+ if (event.usageStats !== undefined) {
+ updateTab(tabId, { cacheStats: event.usageStats ?? undefined });
+ }
break;
}
case "statuses": {
diff --git a/packages/frontend/src/lib/types.ts b/packages/frontend/src/lib/types.ts
index 285b4d2..173f68c 100644
--- a/packages/frontend/src/lib/types.ts
+++ b/packages/frontend/src/lib/types.ts
@@ -140,7 +140,12 @@ export type AgentEvent =
| { type: "turn-start"; turnId: string }
// Fires after the turn settled AND its chunks were persisted (after the DB
// write, post status:idle). Triggers the frontend's reconcile-from-DB.
- | { type: "turn-sealed"; turnId: string }
+ // `usageStats` carries the tab's authoritative usage aggregate (read after the
+ // usage rows were persisted); the store REPLACES `cacheStats` with it,
+ // reconciling the live accumulator to the DB truth (self-heals the live
+ // overshoot from a discarded rate-limited fallback attempt). null ⇒ no usage
+ // rows; absent ⇒ leave cacheStats untouched.
+ | { type: "turn-sealed"; turnId: string; usageStats?: CacheStats | null }
// Sent on every WS (re)connect: a snapshot of every tab the backend is
// currently tracking and its live status. The frontend uses this to
// detect desync after a reconnect (e.g. bun --watch restart killed the