Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(desktop): parity with concurrent chats, final stop and per-step token accounting

Salman Qureshi8d9f0a1b47ae
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8a28cb64..fd98ef72 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,13 @@
## Unreleased
+### Mercury Desktop
+- **See which chats are working.** A spinner in the sidebar marks a chat Mercury is working on, and a clock marks one waiting for a free slot. The status bar shows how many chats are running (for example 2/4), and clicking it lists them so you can open one.
+- **Choose how many chats run at once** in Settings → AI → Chats at once. Automatic picks a number from your computer's memory. A change applies right away.
+- **Stop clears what was waiting.** When Stop drops a chat's waiting messages, that chat stops showing "Waiting…" and tells you they weren't sent.
+- **What each reply cost.** Hover a reply to see its tokens, how much came from the prompt cache, its steps and how long it took. The tooltip shows the exact numbers and the model.
+- **Today's token split** (cached, new and output) appears in Settings → Budgets and in the status bar's token panel. A new "Prompt cache" setting lets cache hits count at their real price. The provider and source breakdowns now add up to the daily total.
+
### Skills
- **Six useful built-in skills.** Alongside `web-search`: `computer-health` (why the computer is slow or full, what's running, why a container is down), `tidy-files` (clean up and sort folders safely), `data-analysis` (spreadsheets and CSVs, computed and checked), `long-documents` (long PDFs and logs, with page references) and `documents` (make or convert Word, PDF and slides). None of them can act without asking. Each is installed once: delete one and it stays deleted.
- **`tweet-notifier` and `screenshot` are no longer installed or reinstalled on start.** If your copy is exactly as Mercury installed it, it's moved to `~/.mercury/skills/_retired-<name>/` (nothing is deleted). A copy you edited stays as it is.
diff --git a/apps/desktop/src/api/mercury.ts b/apps/desktop/src/api/mercury.ts
index 1cfa5920..32555aaf 100644
--- a/apps/desktop/src/api/mercury.ts
+++ b/apps/desktop/src/api/mercury.ts
@@ -4,6 +4,7 @@
═══════════════════════════════════════════════════════════════ */
import { http, ApiError } from "./client";
+import type { TurnsInfo } from "./types";
import type { CommandEntry } from "~/views/chat/picker";
import type { SkillDraft,
BotApproval, BotInboxEntry, BotManifest, BotPlan, CrewSpec, BotRunRecord, BotStatus, BotTier, BotTierId, ChatMessage, ChatSettings, ChatThread, CodeStatus, HealthInfo,
@@ -87,6 +88,10 @@ export const chat = {
save: (threadId: string, saved: boolean) => http.post<{ id: string; saved: boolean; savedAt: string | null }>(`/api/chat/threads/${encodeURIComponent(threadId)}/save`, { saved }),
undo: (threadId: string, content: string) => http.post<{ ok: boolean; content: string; removed: number }>(`/api/chat/threads/${encodeURIComponent(threadId)}/undo`, { content }),
answer: (promptId: string, action: string, targetId?: string) => http.post<{ resolved: boolean }>(`/api/chat/permission/${encodeURIComponent(promptId)}`, { action, targetId }),
+ /** Which chats are working now, which wait for a slot, and how many may run at once. */
+ running: () => http.get<TurnsInfo>("/api/chat/running"),
+ /** How many chats may run at once: 0 = automatic, else 1–16. Applies at once. */
+ setConcurrency: (maxTurns: number) => http.put<TurnsInfo>("/api/chat/concurrency", { maxTurns }),
/** Put this chat's waiting message first in line. */
queueFirst: (threadId: string) => http.post<{ moved: number }>(`/api/chat/threads/${encodeURIComponent(threadId)}/queue/first`, {}),
/** This chat's research: on for the next message, the run going now, or its last one. */
diff --git a/apps/desktop/src/api/types.ts b/apps/desktop/src/api/types.ts
index 6f0c52e3..6e3b7a24 100644
--- a/apps/desktop/src/api/types.ts
+++ b/apps/desktop/src/api/types.ts
@@ -98,6 +98,20 @@ export interface ChatMessage {
artifacts?: import("./artifacts").ArtifactRef[];
/** This answer is a research report: how the run went. */
research?: ResearchSnapshot;
+ /** What this reply cost: every model step of its turn (runtimes from #296 on). */
+ usage?: ReplyUsage;
+}
+
+/** One reply's tokens, steps, time and model. */
+export interface ReplyUsage {
+ inputTokens: number;
+ /** Of the input, how much the provider served from its prompt cache. */
+ cachedInputTokens: number;
+ outputTokens: number;
+ steps?: number;
+ elapsedMs?: number;
+ provider?: string;
+ model?: string;
}
/** A page a research run tried to read. */
@@ -480,3 +494,23 @@ export interface SkillDraft {
instructions: string;
allowedTools?: string[];
}
+
+/** A chat a turn runs or waits in (runtimes from ADR-037 on). */
+export interface TurnChat {
+ /** The thread it belongs to — desktop chats always have one. */
+ sessionId?: string;
+ channelType: string;
+ channelId: string;
+}
+
+/** Chats running at once, and the limit. */
+export interface TurnsInfo {
+ /** In effect now. */
+ limit: number;
+ /** What was set: 0 = automatic. */
+ configured: number;
+ /** What automatic gives on this machine. */
+ auto: number;
+ running: Array<TurnChat & { startedAt: number; activity: string; steps: number }>;
+ waiting: Array<TurnChat & { waiting: number; position: number }>;
+}
diff --git a/apps/desktop/src/app/events.ts b/apps/desktop/src/app/events.ts
index 345a547a..8f20f50f 100644
--- a/apps/desktop/src/app/events.ts
+++ b/apps/desktop/src/app/events.ts
@@ -9,7 +9,7 @@ import { useEffect } from "react";
import { openStream } from "~/api/stream";
import * as api from "~/api/mercury";
import { ApiError, http } from "~/api/client";
-import type { BotActivityEvent, BotInboxEntry, BotStatus, ChatMessage, CodeMode, PendingPrompt, ResearchPlanPrompt, ResearchSnapshot } from "~/api/types";
+import type { BotActivityEvent, BotInboxEntry, BotStatus, ChatMessage, CodeMode, PendingPrompt, ReplyUsage, ResearchPlanPrompt, ResearchSnapshot } from "~/api/types";
import { useBots, useChat, useRuntimeState, type AgentState } from "./store";
import { conversations, useCodeSessions, type ConversationStore, type Surface } from "./conversation";
import type { ArtifactRef } from "~/api/artifacts";
@@ -155,6 +155,16 @@ export function handleEvent(store: ConversationStore, event: string, raw: string
conv.setWaiting({ position: Number(data.position) || 1, busyWith: typeof data.busyWith === "string" ? data.busyWith : undefined, busySessionId: typeof data.busySessionId === "string" ? data.busySessionId : undefined });
conv.setAgent("thinking");
break;
+ case "queue_dropped": {
+ // A stop took this chat's waiting message(s) out of line (ADR-038): they won't run.
+ const wasWaiting = !!conv.waiting;
+ conv.setWaiting(null);
+ if (conv.stopping) { finishStopped(store); break; }
+ if (wasWaiting && !conv.streaming && !conv.live) conv.setAgent("idle");
+ const n = Number(data.dropped) || 1;
+ conv.setNotice({ message: `Stopped before it started: ${n === 1 ? "your waiting message wasn't sent" : `${n} waiting messages weren't sent`}.`, level: "info", at: Date.now() });
+ break;
+ }
case "thinking":
conv.setWaiting(null);
conv.setAgent("thinking");
@@ -235,7 +245,8 @@ export function handleEvent(store: ConversationStore, event: string, raw: string
conv.clearLive();
const artifacts = pendingArtifacts.get(store);
pendingArtifacts.delete(store);
- conv.addMessage({ id: crypto.randomUUID(), role: "assistant", content: text, timestamp: new Date().toISOString(), ...(trace ? { trace } : {}), ...(artifacts?.length ? { artifacts } : {}) });
+ const usage = replyUsage(data.usage);
+ conv.addMessage({ id: crypto.randomUUID(), role: "assistant", content: text, timestamp: new Date().toISOString(), ...(trace ? { trace } : {}), ...(artifacts?.length ? { artifacts } : {}), ...(usage ? { usage } : {}) });
conv.setStep(null);
store.getState().setAgent(store.getState().prompts.length ? "needs-you" : "idle");
void refreshThreads();
@@ -271,6 +282,25 @@ export function handleEvent(store: ConversationStore, event: string, raw: string
}
}
+/** What a reply cost, from the runtime's final event (runtimes from #296 on). */
+export function replyUsage(raw: unknown): ReplyUsage | undefined {
+ if (!raw || typeof raw !== "object") return undefined;
+ const u = raw as Record<string, unknown>;
+ const n = (v: unknown) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : undefined);
+ const inputTokens = n(u.inputTokens);
+ const outputTokens = n(u.outputTokens);
+ if (inputTokens === undefined || outputTokens === undefined) return undefined;
+ return {
+ inputTokens,
+ outputTokens,
+ cachedInputTokens: n(u.cachedInputTokens) ?? 0,
+ ...(typeof u.provider === "string" ? { provider: u.provider } : {}),
+ ...(typeof u.model === "string" ? { model: u.model } : {}),
+ ...(n(u.steps) !== undefined ? { steps: n(u.steps) } : {}),
+ ...(n(u.elapsedMs) !== undefined ? { elapsedMs: n(u.elapsedMs) } : {}),
+ };
+}
+
function toPrompt(kind: PendingPrompt["kind"], data: Record<string, unknown>, text: string): PendingPrompt {
const rawOptions = Array.isArray(data.options) ? data.options : [];
const options = rawOptions.map((o) => {
diff --git a/apps/desktop/src/app/notify/notify.ts b/apps/desktop/src/app/notify/notify.ts
index 1bf14b65..0bb95abc 100644
--- a/apps/desktop/src/app/notify/notify.ts
+++ b/apps/desktop/src/app/notify/notify.ts
@@ -17,6 +17,7 @@ import { useUi } from "../store";
import { useVoice } from "../voice";
import { playSound } from "./sounds";
import { useNotify, worthTelling } from "./store";
+import { refreshPulse } from "../pulse";
export interface ActivityEvent {
kind: "started" | "needs_you" | "resolved" | "done" | "stopped" | "failed" | "research";
@@ -179,6 +180,8 @@ function label(e: ActivityEvent): string {
}
export function handleActivity(e: ActivityEvent): void {
+ // Which chats are working changed: refresh the sidebar's markers now, not at the next poll.
+ if (e.kind === "started" || e.kind === "done" || e.kind === "stopped" || e.kind === "failed") void refreshPulse.turns();
const n = useNotify.getState();
// On a call, Mercury is already talking to you.
if (useVoice.getState().active) return;
diff --git a/apps/desktop/src/app/parity.test.ts b/apps/desktop/src/app/parity.test.ts
new file mode 100644
index 00000000..c631b5aa
--- /dev/null
+++ b/apps/desktop/src/app/parity.test.ts
@@ -0,0 +1,72 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+/**
+ * Mercury Desktop and the runtime's newer work (ADR-037/038, #296): a dropped
+ * waiting message clears "Waiting", replies carry what they cost, running
+ * chats map to their threads, and today's split reads plainly.
+ */
+vi.mock("~/api/mercury", () => ({ chat: {} }));
+
+const { conversations } = await import("./conversation");
+const { handleEvent, replyUsage } = await import("./events");
+const { turnStates } = await import("./pulse");
+const { usageLabel } = await import("~/views/chat/Message");
+const { splitLine } = await import("~/views/settings/Budgets");
+const store = conversations.chat;
+
+describe("a stop drops this chat's waiting message", () => {
+ beforeEach(() => store.setState({ activeId: "a", waiting: null, agent: "idle", messages: [], streaming: "", live: null, stopping: false, notice: null }));
+
+ it("clears Waiting, goes idle and says it wasn't sent", () => {
+ handleEvent(store, "queued", JSON.stringify({ position: 1 }));
+ expect(store.getState().agent).toBe("thinking");
+ handleEvent(store, "queue_dropped", JSON.stringify({ targetId: "a", dropped: 1 }));
+ expect(store.getState().waiting).toBeNull();
+ expect(store.getState().agent).toBe("idle");
+ expect(store.getState().notice?.message).toMatch(/wasn't sent/);
+ });
+
+ it("finishes a stop that was waiting for the runtime", () => {
+ store.setState({ stopping: true, agent: "thinking" });
+ handleEvent(store, "queue_dropped", JSON.stringify({ targetId: "a", dropped: 2 }));
+ expect(store.getState().stopping).toBe(false);
+ });
+});
+
+describe("what a reply cost", () => {
+ beforeEach(() => store.setState({ activeId: "a", messages: [], streaming: "", live: null, stopping: false }));
+
+ it("the final event's usage lands on the reply", () => {
+ handleEvent(store, "text_done", JSON.stringify({ fullText: "Done.", usage: { inputTokens: 14000, cachedInputTokens: 11480, outputTokens: 420, steps: 6, elapsedMs: 12400, provider: "anthropic", model: "claude-x" } }));
+ const reply = store.getState().messages.at(-1)!;
+ expect(reply.usage).toEqual({ inputTokens: 14000, cachedInputTokens: 11480, outputTokens: 420, steps: 6, elapsedMs: 12400, provider: "anthropic", model: "claude-x" });
+ expect(usageLabel(reply.usage!).short).toBe("14K tokens · 82% cached · 6 steps · 12s");
+ expect(usageLabel(reply.usage!).detail).toContain("anthropic · claude-x");
+ });
+
+ it("an older runtime's reply has no usage, and bad input is ignored", () => {
+ handleEvent(store, "text_done", JSON.stringify({ fullText: "Hi" }));
+ expect(store.getState().messages.at(-1)!.usage).toBeUndefined();
+ expect(replyUsage({ inputTokens: "x", outputTokens: 1 })).toBeUndefined();
+ expect(usageLabel({ inputTokens: 100, cachedInputTokens: 0, outputTokens: 20 }).short).toBe("120 tokens");
+ });
+});
+
+describe("running chats and today's split", () => {
+ it("maps running and waiting chats to thread ids (desktop chats are web sessions)", () => {
+ const states = turnStates({
+ limit: 4, configured: 0, auto: 4,
+ running: [{ sessionId: "s1", channelType: "web", channelId: "s1", startedAt: 1, activity: "", steps: 0 }, { channelType: "telegram", channelId: "123", startedAt: 1, activity: "", steps: 0 }],
+ waiting: [{ channelType: "web", channelId: "s2", waiting: 1, position: 1 }],
+ });
+ expect([...states.running]).toEqual(["s1"]);
+ expect([...states.queued]).toEqual(["s2"]);
+ expect(turnStates(null).running.size).toBe(0);
+ });
+
+ it("reads today's split plainly, and says nothing before anything ran", () => {
+ expect(splitLine({ inputTokens: 122_000, cachedInputTokens: 101_000, noCacheInputTokens: 21_000, outputTokens: 4_400 })).toMatch(/^122K in \(101K from cache · 83%\) · 21K new · 4\.4K out$/);
+ expect(splitLine({ inputTokens: 0, cachedInputTokens: 0, noCacheInputTokens: 0, outputTokens: 0 })).toBeNull();
+ expect(splitLine(undefined)).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/app/pulse.ts b/apps/desktop/src/app/pulse.ts
index bf9f455b..8c966952 100644
--- a/apps/desktop/src/app/pulse.ts
+++ b/apps/desktop/src/app/pulse.ts
@@ -5,6 +5,7 @@
═══════════════════════════════════════════════════════════════ */
import { useEffect } from "react";
+import type { TurnsInfo } from "~/api/types";
import { create } from "zustand";
import { http } from "~/api/client";
@@ -12,9 +13,12 @@ export interface UsageInfo {
dailyUsed: number;
dailyBudget: number;
remaining: number;
+ /** What counted toward the budget, by provider and by source (sums to dailyUsed on current runtimes). */
byProvider: Record<string, number>;
byChannel: Record<string, number>;
- requestLog: Array<{ provider: string; model: string; inputTokens: number; outputTokens: number; totalTokens: number; channelType: string; timestamp: number }>;
+ requestLog: Array<{ provider: string; model: string; inputTokens: number; outputTokens: number; totalTokens: number; channelType: string; timestamp: number; cachedInputTokens?: number; noCacheInputTokens?: number; countedTokens?: number }>;
+ /** Today's input/output split (runtimes from #296 on). */
+ split?: import("~/views/settings/Budgets").DailySplit;
}
export interface ScheduleInfo {
@@ -44,6 +48,8 @@ interface PulseState {
usage: UsageInfo | null;
schedules: ScheduleInfo[];
background: BackgroundInfo;
+ /** Chats working now and waiting for a slot; null on runtimes without it. */
+ turns: TurnsInfo | null;
}
export const usePulse = create<PulseState>(() => ({
@@ -52,6 +58,7 @@ export const usePulse = create<PulseState>(() => ({
usage: null,
schedules: [],
background: { tasks: [], agents: [] },
+ turns: null,
}));
async function loadIdentity() {
@@ -66,6 +73,9 @@ async function loadUsage() {
async function loadSchedules() {
try { usePulse.setState({ schedules: (await http.get<{ schedules: ScheduleInfo[] }>("/api/schedules")).schedules }); } catch { /* keep */ }
}
+async function loadTurns() {
+ try { usePulse.setState({ turns: await http.get<TurnsInfo>("/api/chat/running") }); } catch { usePulse.setState({ turns: null }); }
+}
async function loadBackground() {
const [tasks, agents] = await Promise.all([
http.get<{ tasks: BackgroundInfo["tasks"] }>("/api/bg").then((r) => r.tasks).catch(() => []),
@@ -80,15 +90,26 @@ export function usePulsePolling(connectionId: string): void {
void loadUsage();
void loadSchedules();
void loadBackground();
+ void loadTurns();
const timers = [
+ setInterval(() => void loadTurns(), 4_000),
setInterval(() => void loadUsage(), 20_000),
setInterval(() => void loadSchedules(), 60_000),
setInterval(() => void loadBackground(), 8_000),
];
- const onFocus = () => { void loadUsage(); void loadBackground(); };
+ const onFocus = () => { void loadUsage(); void loadBackground(); void loadTurns(); };
window.addEventListener("focus", onFocus);
return () => { timers.forEach(clearInterval); window.removeEventListener("focus", onFocus); };
}, [connectionId]);
}
-export const refreshPulse = { usage: loadUsage, schedules: loadSchedules, background: loadBackground };
+export const refreshPulse = { usage: loadUsage, schedules: loadSchedules, background: loadBackground, turns: loadTurns };
+
+/** The thread ids that are working now / waiting for a slot. */
+export function turnStates(turns: TurnsInfo | null): { running: Set<string>; queued: Set<string> } {
+ const id = (t: { sessionId?: string; channelType: string; channelId: string }) => t.sessionId ?? (t.channelType === "web" ? t.channelId : undefined);
+ return {
+ running: new Set((turns?.running ?? []).map(id).filter((v): v is string => !!v)),
+ queued: new Set((turns?.waiting ?? []).map(id).filter((v): v is string => !!v)),
+ };
+}
diff --git a/apps/desktop/src/extensions/builtin-status.tsx b/apps/desktop/src/extensions/builtin-status.tsx
index 3b7208c0..db4ca65f 100644
--- a/apps/desktop/src/extensions/builtin-status.tsx
+++ b/apps/desktop/src/extensions/builtin-status.tsx
@@ -1,10 +1,13 @@
import { forwardRef, useEffect, useState, type ComponentPropsWithoutRef } from "react";
-import { Bot, CalendarClock, Code2, Coins, Cpu, Layers, Server, Shield, ShieldCheck, Trash2 } from "lucide-react";
+import { Bot, CalendarClock, Clock, Code2, Coins, Cpu, Layers, MessagesSquare, Server, Shield, ShieldCheck, Trash2 } from "lucide-react";
import { cx } from "~/lib/cx";
import * as api from "~/api/mercury";
import type { CodeStatus } from "~/api/types";
import { usePermissionMode } from "~/app/permission";
-import { useBots, useRuntimeState, useUi } from "~/app/store";
+import { useBots, useChat, useRuntimeState, useUi } from "~/app/store";
+import { openThread } from "~/app/events";
+import { surfaceOf } from "~/app/notify/notify";
+import type { TurnChat } from "~/api/types";
import { refreshPulse, usePulse, type ScheduleInfo } from "~/app/pulse";
import { scheduleDetail, scheduleIsActive } from "~/app/schedule-status";
import { http } from "~/api/client";
@@ -12,6 +15,7 @@ import { useConnections } from "~/shell/connections";
import { StateOrb, LABELS } from "~/components/indicators/StateOrb";
import { StatusButton, StatusPopover } from "~/layout/StatusBar";
import { compact } from "~/views/bots/Usage";
+import { splitLine } from "~/views/settings/Budgets";
import { mercuryUi } from "./registry";
import { useVoice, phaseOf, PHASE_LABEL } from "~/app/voice";
import { OptimusFace } from "~/components/OptimusFace";
@@ -77,6 +81,53 @@ function Background() {
);
}
+const CHANNEL_LABELS: Record<string, string> = { cli: "Terminal", telegram: "Telegram", discord: "Discord", slack: "Slack", signal: "Signal", internal: "Scheduled task", web: "Chat" };
+
+/**
+ * Chats working at once (ADR-037): how many of the slots are in use, which
+ * chats, and which wait for a slot. Hidden when nothing runs.
+ */
+function ChatsRunning() {
+ const turns = usePulse((s) => s.turns);
+ const threads = useChat((s) => s.threads);
+ const setView = useUi((s) => s.setView);
+ const openSettings = useUi((s) => s.openSettings);
+ if (!turns || turns.running.length === 0) return null;
+ const titleOf = (t: TurnChat) => {
+ const thread = t.sessionId ? threads.find((th) => th.id === t.sessionId) : undefined;
+ return thread?.title?.replace(/^Code · /, "") || CHANNEL_LABELS[t.channelType] || t.channelType;
+ };
+ const open = (t: TurnChat) => {
+ if (!t.sessionId || !threads.some((th) => th.id === t.sessionId)) return;
+ const surface = surfaceOf(t.sessionId);
+ setView(surface);
+ void openThread(surface, t.sessionId);
+ };
+ const busy = turns.running.length >= turns.limit;
+ return (
+ <StatusPopover width={360} trigger={
+ <Trigger title="Chats working now" tone={busy && turns.waiting.length ? "amber" : "accent"}>
+ <MessagesSquare size={13} />
+ <span>{turns.running.length}/{turns.limit}</span>
+ </Trigger>
+ }>
+ <PanelTitle>Chats working · {turns.running.length} of {turns.limit}</PanelTitle>
+ {turns.running.map((t) => (
+ <button key={`${t.channelType}:${t.channelId}`} onClick={() => open(t)} className="block w-full text-left">
+ <Line icon={<MessagesSquare size={13} />} title={titleOf(t)} detail={`${t.activity || "working"}${t.steps ? ` · step ${t.steps}` : ""} · ${Math.max(1, Math.round((Date.now() - t.startedAt) / 1000))}s`} />
+ </button>
+ ))}
+ {turns.waiting.length > 0 && <div className="mt-2 text-xs font-medium text-ink3">Waiting for a slot</div>}
+ {turns.waiting.map((t) => (
+ <button key={`w:${t.channelType}:${t.channelId}`} onClick={() => open(t)} className="block w-full text-left">
+ <Line icon={<Clock size={13} />} title={titleOf(t)} detail={`${t.waiting} message${t.waiting === 1 ? "" : "s"} · #${t.position} in line`} />
+ </button>
+ ))}
+ <button onClick={() => openSettings("concurrency")} className="mt-1 w-full rounded-md px-1 py-1.5 text-left text-xs text-accent hover:underline">Chats at once: {turns.configured ? turns.configured : `automatic (${turns.auto})`}</button>
+ </StatusPopover>
+ );
+}
+
/** Bots at work: the rail's bot icon and how many are running. Hidden when none are. */
function BotsRunning() {
const bots = useBots((s) => s.bots);
@@ -203,6 +254,7 @@ function Tokens() {
<span className="text-2xl font-semibold tracking-tight">{compact(usage.dailyUsed)}</span>
<span className="font-mono text-xs text-ink3">of {compact(usage.dailyBudget)} · {compact(usage.remaining)} left</span>
</div>
+ {splitLine(usage.split) && <p className="mb-3 font-mono text-xs text-ink3">{splitLine(usage.split)}</p>}
<Breakdown title="By source" rows={channels} total={usage.dailyUsed} />
<Breakdown title="By provider" rows={providers} total={usage.dailyUsed} />
{models.size > 0 && (
@@ -294,6 +346,7 @@ export function registerBuiltinStatusItems(): void {
mercuryUi.registerStatusItem({ id: "mercury.connection", title: "Connection", area: "status.left", priority: 100, render: Connection });
mercuryUi.registerStatusItem({ id: "mercury.agent", title: "Agent state", area: "status.left", priority: 90, render: AgentState });
mercuryUi.registerStatusItem({ id: "mercury.optimus", title: "Optimus voice", area: "status.left", priority: 88, render: OptimusVoice });
+ mercuryUi.registerStatusItem({ id: "mercury.chats", title: "Chats working", area: "status.left", priority: 87, render: ChatsRunning });
mercuryUi.registerStatusItem({ id: "mercury.bots", title: "Bots running", area: "status.left", priority: 85, render: BotsRunning });
mercuryUi.registerStatusItem({ id: "mercury.background", title: "Background work", area: "status.left", priority: 80, render: Background });
mercuryUi.registerStatusItem({ id: "mercury.schedules", title: "Schedules", area: "status.left", priority: 70, render: Schedules });
diff --git a/apps/desktop/src/views/chat/Message.tsx b/apps/desktop/src/views/chat/Message.tsx
index 2a607437..9e0e0061 100644
--- a/apps/desktop/src/views/chat/Message.tsx
+++ b/apps/desktop/src/views/chat/Message.tsx
@@ -2,7 +2,8 @@ import { Check, ChevronRight, Copy, Square, Wrench } from "lucide-react";
import { CommandChip } from "./CommandChip";
import { splitCommand } from "./picker";
import { memo, useState } from "react";
-import type { ChatMessage, ThoughtTrace } from "~/api/types";
+import type { ChatMessage, ReplyUsage, ThoughtTrace } from "~/api/types";
+import { compact } from "~/views/bots/Usage";
import { Mark } from "~/components/Logo";
import { Markdown } from "~/components/Markdown";
import { StreamCaret } from "~/components/indicators/Thinking";
@@ -79,7 +80,7 @@ export const Message = memo(function Message({ message, undoable = false }: { me
{message.research && message.artifacts && message.artifacts.filter((a) => a.id !== message.research?.report?.id).length > 0 && (
<ArtifactStrip items={message.artifacts.filter((a) => a.id !== message.research?.report?.id)} />
)}
- <MessageMeta timestamp={message.timestamp} copy={body || undefined} listen={body ? { id: message.id, text: body } : undefined} />
+ <MessageMeta timestamp={message.timestamp} copy={body || undefined} listen={body ? { id: message.id, text: body } : undefined} usage={message.usage} />
<ReadAloudNotice id={message.id} />
</div>
</div>
@@ -108,7 +109,22 @@ function Speaker({ who }: { who: "you" | "mercury" }) {
}
/** Time and copy, shown on hover so the conversation stays quiet. */
-function MessageMeta({ timestamp, copy, listen, undo, align = "start" }: { timestamp: string; copy?: string; listen?: { id: string; text: string }; undo?: ChatMessage; align?: "start" | "end" }) {
+/** "14k tokens · 82% cached · 6 steps · 12s" for a reply, and the detail for its tooltip. */
+export function usageLabel(u: ReplyUsage): { short: string; detail: string } {
+ const total = u.inputTokens + u.outputTokens;
+ const cachedPct = u.inputTokens > 0 ? Math.round((u.cachedInputTokens / u.inputTokens) * 100) : 0;
+ const parts = [`${compact(total)} tokens`];
+ if (u.cachedInputTokens > 0) parts.push(`${cachedPct}% cached`);
+ if (u.steps && u.steps > 1) parts.push(`${u.steps} steps`);
+ if (u.elapsedMs && u.elapsedMs >= 1000) parts.push(`${Math.round(u.elapsedMs / 1000)}s`);
+ const detail = [
+ `${u.inputTokens.toLocaleString()} in (${u.cachedInputTokens.toLocaleString()} from cache) · ${u.outputTokens.toLocaleString()} out`,
+ u.model ? `${u.provider ? `${u.provider} · ` : ""}${u.model}` : "",
+ ].filter(Boolean).join("\n");
+ return { short: parts.join(" · "), detail };
+}
+
+function MessageMeta({ timestamp, copy, listen, undo, usage, align = "start" }: { timestamp: string; copy?: string; listen?: { id: string; text: string }; undo?: ChatMessage; usage?: ReplyUsage; align?: "start" | "end" }) {
const [copied, setCopied] = useState(false);
const reading = useReadingThis(listen?.id ?? "");
const time = formatTime(timestamp);
@@ -127,6 +143,7 @@ function MessageMeta({ timestamp, copy, listen, undo, align = "start" }: { times
{listen && <ReadAloudButton id={listen.id} text={listen.text} />}
{undo && <UndoMessage message={undo} />}
{time && <span className="px-1.5 text-xs text-ink4">{time}</span>}
+ {usage && (() => { const u = usageLabel(usage); return <span className="px-1.5 font-mono text-2xs text-ink4" title={u.detail}>{u.short}</span>; })()}
</div>
);
}
diff --git a/apps/desktop/src/views/chat/ThreadList.tsx b/apps/desktop/src/views/chat/ThreadList.tsx
index 07f73310..91987dbc 100644
--- a/apps/desktop/src/views/chat/ThreadList.tsx
+++ b/apps/desktop/src/views/chat/ThreadList.tsx
@@ -1,10 +1,12 @@
-import { Bookmark, BookmarkMinus, Pencil, Search, SquarePen, Trash2, X } from "lucide-react";
+import { Bookmark, BookmarkMinus, Clock, Pencil, Search, SquarePen, Trash2, X } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { cx } from "~/lib/cx";
import * as api from "~/api/mercury";
import type { ChatThread } from "~/api/types";
import { refreshThreads, renameThread, setThreadSaved } from "~/app/events";
import { useNotify } from "~/app/notify/store";
+import { turnStates, usePulse } from "~/app/pulse";
+import { Spinner } from "~/components/ui/bits";
import { Dialog } from "~/components/ui/Dialog";
import { Button } from "~/components/ui/Button";
import { Input } from "~/components/ui/Input";
@@ -34,6 +36,9 @@ export function ThreadList({ threads, activeId, onOpen, onNew, newLabel, searchL
}) {
const unread = useNotify((s) => s.unread);
const waiting = useNotify((s) => s.waiting);
+ // Chats run at once: which are working now, which wait for a free slot.
+ const turns = usePulse((s) => s.turns);
+ const { running, queued } = useMemo(() => turnStates(turns), [turns]);
const [limit, setLimit] = useState(PAGE);
const [query, setQuery] = useState("");
const [renameTarget, setRenameTarget] = useState<ChatThread | null>(null);
@@ -139,7 +144,9 @@ export function ThreadList({ threads, activeId, onOpen, onNew, newLabel, searchL
<span className={cx("min-w-0 flex-1 truncate", activeId === t.id ? "text-ink" : unread[t.id] ? "font-medium text-ink" : "text-ink2 group-hover:text-ink")}>{(t.title || "Untitled").replace(/^Code · /, "")}</span>
{t.id in waiting
? <span className="h-2 w-2 shrink-0 rounded-full bg-amber" aria-label="Waiting for you" title="Waiting for your answer" />
- : unread[t.id] && activeId !== t.id ? <span className="h-2 w-2 shrink-0 rounded-full bg-blue" aria-label="New" title="Something new" /> : null}
+ : running.has(t.id) ? <span className="shrink-0 text-accent" aria-label="Working" title="Working on it"><Spinner size={11} /></span>
+ : queued.has(t.id) ? <span className="shrink-0 text-ink4" aria-label="In line" title="Waiting for a free slot"><Clock size={12} aria-hidden="true" /></span>
+ : unread[t.id] && activeId !== t.id ? <span className="h-2 w-2 shrink-0 rounded-full bg-blue" aria-label="New" title="Something new" /> : null}
</span>
{renderMeta?.(t)}
</button>
diff --git a/apps/desktop/src/views/settings/Budgets.tsx b/apps/desktop/src/views/settings/Budgets.tsx
index 6cd913dc..0ec85f66 100644
--- a/apps/desktop/src/views/settings/Budgets.tsx
+++ b/apps/desktop/src/views/settings/Budgets.tsx
@@ -12,16 +12,32 @@ import { compact } from "~/views/bots/Usage";
* in, and the caps for bots. Saves apply at once, no restart.
*/
+/** Today's input/output split (runtimes from #296 on). */
+export interface DailySplit { inputTokens: number; cachedInputTokens: number; noCacheInputTokens: number; outputTokens: number }
+
export interface BudgetState {
- daily: { budget: number; used: number; remaining: number; percentage: number };
+ daily: { budget: number; used: number; remaining: number; percentage: number; split?: DailySplit; cachedWeight?: number };
saver: { state: "off" | "on" | "auto"; autoEnabled: boolean; autoThreshold: number; savedToday: number; savedLifetime: number };
bots: { enabled: boolean; perBot: number; fleet: number };
}
-type BudgetPatch = { dailyBudget?: number; saver?: { manual?: boolean; autoEnabled?: boolean; autoThreshold?: number }; bots?: { perBot?: number; fleet?: number } };
+type BudgetPatch = { dailyBudget?: number; cachedWeight?: number; saver?: { manual?: boolean; autoEnabled?: boolean; autoThreshold?: number }; bots?: { perBot?: number; fleet?: number } };
const DAILY_PRESETS = [500_000, 1_000_000, 2_000_000, 5_000_000, 10_000_000];
const THRESHOLDS = ["50", "75", "90"] as const;
+/** How much a prompt-cache hit counts toward the daily budget. */
+const CACHE_WEIGHTS = [
+ { value: "1", label: "In full" },
+ { value: "0.5", label: "Half" },
+ { value: "0.1", label: "At cost" },
+] as const;
+
+/** "122k in (102k from cache · 83%) · 18k new · 4.4k out", or null before anything ran today. */
+export function splitLine(split: DailySplit | undefined): string | null {
+ if (!split || (split.inputTokens <= 0 && split.outputTokens <= 0)) return null;
+ const pct = split.inputTokens > 0 ? Math.round((split.cachedInputTokens / split.inputTokens) * 100) : 0;
+ return `${compact(split.inputTokens)} in (${compact(split.cachedInputTokens)} from cache · ${pct}%) · ${compact(split.noCacheInputTokens)} new · ${compact(split.outputTokens)} out`;
+}
/** "2M", "750k", "1,500,000" → tokens; null when it isn't a number. */
export function parseTokens(text: string): number | null {
@@ -75,6 +91,7 @@ export function BudgetsSettings() {
<div className="h-1.5 overflow-hidden rounded-full bg-ink/[0.07]" role="meter" aria-valuemin={0} aria-valuemax={daily.budget} aria-valuenow={daily.used} aria-label="Tokens used today">
<div className={cx("h-full rounded-full", ratio >= 0.9 ? "bg-red" : ratio >= 0.75 ? "bg-amber" : "bg-accent")} style={{ width: `${ratio * 100}%` }} />
</div>
+ {splitLine(daily.split) && <div className="font-mono text-xs text-ink3">Today: {splitLine(daily.split)}</div>}
<TokenField
id="budget-daily"
label="Tokens a day"
@@ -87,6 +104,21 @@ export function BudgetsSettings() {
</div>
</section>
+ {daily.cachedWeight !== undefined && (
+ <section className="flex flex-col gap-3">
+ <h3 className="text-sm font-medium text-ink">Prompt cache</h3>
+ <div className="flex flex-col divide-y divide-line rounded-lg border border-line bg-surface">
+ <Row title="Cache hits count" hint="Every model call in a turn counts. Providers charge far less for the part of a request they already have cached; “At cost” counts it at about its price.">
+ <Segmented
+ value={CACHE_WEIGHTS.find((w) => Number(w.value) === daily.cachedWeight)?.value ?? ("" as (typeof CACHE_WEIGHTS)[number]["value"])}
+ onChange={(v) => void save({ cachedWeight: Number(v) })}
+ options={CACHE_WEIGHTS.map((w) => ({ value: w.value, label: w.label }))}
+ />
+ </Row>
+ </div>
+ </section>
+ )}
+
<section className="flex flex-col gap-3">
<h3 className="text-sm font-medium text-ink">Token Saver</h3>
<div className="flex flex-col divide-y divide-line rounded-lg border border-line bg-surface">
diff --git a/apps/desktop/src/views/settings/Concurrency.tsx b/apps/desktop/src/views/settings/Concurrency.tsx
new file mode 100644
index 00000000..1f818814
--- /dev/null
+++ b/apps/desktop/src/views/settings/Concurrency.tsx
@@ -0,0 +1,67 @@
+import { useEffect, useState } from "react";
+import * as api from "~/api/mercury";
+import { ApiError } from "~/api/client";
+import type { TurnsInfo } from "~/api/types";
+import { refreshPulse } from "~/app/pulse";
+import { Segmented, Spinner } from "~/components/ui/bits";
+
+/**
+ * Chats at once (ADR-037): how many chats Mercury works on together. Each
+ * chat still handles its own messages one after another; this is how many
+ * different chats run side by side. Automatic picks a limit from the
+ * machine's memory (2 on Termux and small machines). Applies at once.
+ */
+const CHOICES = ["0", "1", "2", "3", "4", "6", "8"] as const;
+
+export function ConcurrencySettings() {
+ const [info, setInfo] = useState<TurnsInfo | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [saving, setSaving] = useState(false);
+
+ useEffect(() => {
+ api.chat.running()
+ .then(setInfo)
+ .catch((e) => setError(e instanceof ApiError && (e.status === 404 || e.status === 503)
+ ? "This Mercury runs one chat at a time. Update it to work on several chats together."
+ : e instanceof Error ? e.message : String(e)));
+ }, []);
+
+ async function choose(value: string) {
+ setSaving(true);
+ setError(null);
+ try {
+ setInfo(await api.chat.setConcurrency(Number(value)));
+ void refreshPulse.turns();
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ if (!info) return error ? <p className="text-sm text-ink3">{error}</p> : <div className="py-10 text-ink3"><Spinner size={18} /></div>;
+ const current = CHOICES.find((c) => Number(c) === info.configured) ?? ("" as (typeof CHOICES)[number]);
+ return (
+ <div className="flex flex-col gap-6">
+ <p className="text-sm text-ink3">
+ Mercury works on several chats at the same time: a long task in one chat doesn't make the others wait. Each chat still handles its own messages in order.
+ </p>
+ {error && <p className="text-sm text-red" role="alert">{error}</p>}
+ <section className="flex flex-col gap-3">
+ <h3 className="text-sm font-medium text-ink">Chats at once</h3>
+ <div className="flex flex-col gap-3 rounded-lg border border-line bg-surface px-4 py-3">
+ <Segmented value={current} onChange={(v) => void choose(v)}
+ options={CHOICES.map((c) => ({ value: c, label: c === "0" ? `Auto (${info.auto})` : c }))} />
+ <p className="text-xs text-ink3">
+ {info.configured === 0 ? `Automatic: ${info.auto} on this computer, from its memory.` : `Set to ${info.configured}.`}
+ {" "}When memory runs short, new chats wait for a free slot even below the limit. 1 means one chat at a time.
+ {saving && " Saving…"}
+ </p>
+ <p className="font-mono text-xs text-ink3">
+ Now: {info.running.length} working · {info.waiting.reduce((n, w) => n + w.waiting, 0)} waiting · limit {info.limit}
+ </p>
+ </div>
+ </section>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/views/settings/SettingsView.tsx b/apps/desktop/src/views/settings/SettingsView.tsx
index 6bb3bafb..9a719435 100644
--- a/apps/desktop/src/views/settings/SettingsView.tsx
+++ b/apps/desktop/src/views/settings/SettingsView.tsx
@@ -19,6 +19,7 @@ import { Profile } from "./Profile";
import { ModelsSettings } from "./Models";
import { VoiceSettings } from "./Voice";
import { BudgetsSettings } from "./Budgets";
+import { ConcurrencySettings } from "./Concurrency";
import { ChannelsSettings } from "./Channels";
import { isVisible, orderedIds, useContributions, type ContributionArea } from "~/extensions/registry";
import { NotificationsSettings } from "./Notifications";
@@ -28,13 +29,13 @@ import { NotificationsSettings } from "./Notifications";
* page shows them as tabs across the top. Everything about the models
* (which ones, voice, what they may spend) sits together under AI.
*/
-type Section = "profile" | "models" | "voice" | "budgets" | "channels" | "notifications" | "appearance" | "statusbar" | "startup" | "connections" | "devices" | "analytics" | "about";
+type Section = "profile" | "models" | "voice" | "budgets" | "concurrency" | "channels" | "notifications" | "appearance" | "statusbar" | "startup" | "connections" | "devices" | "analytics" | "about";
type GroupId = "profile" | "ai" | "messaging" | "app" | "connections" | "analytics" | "about";
const GROUPS: Array<{ id: GroupId; label: string; icon: typeof Palette; tabs: Array<{ id: Section; label: string }> }> = [
{ id: "profile", label: "Profile", icon: UserRound, tabs: [{ id: "profile", label: "Profile" }] },
- { id: "ai", label: "AI", icon: Sparkles, tabs: [{ id: "models", label: "Models" }, { id: "voice", label: "Voice" }, { id: "budgets", label: "Budgets" }] },
+ { id: "ai", label: "AI", icon: Sparkles, tabs: [{ id: "models", label: "Models" }, { id: "voice", label: "Voice" }, { id: "budgets", label: "Budgets" }, { id: "concurrency", label: "Chats at once" }] },
{ id: "messaging", label: "Messaging", icon: MessagesSquare, tabs: [{ id: "channels", label: "Channels" }, { id: "notifications", label: "Notifications" }] },
{ id: "app", label: "App", icon: Palette, tabs: [{ id: "appearance", label: "Appearance" }, { id: "statusbar", label: "Status bar" }, { id: "startup", label: "Start-up" }] },
{ id: "connections", label: "Connections", icon: Server, tabs: [{ id: "connections", label: "Runtimes" }, { id: "devices", label: "Paired devices" }] },
@@ -103,6 +104,7 @@ export function SettingsView({ connection, health, onSwitchConnection }: { conne
{section === "models" && <ModelsSettings />}
{section === "voice" && <VoiceSettings onOpenModels={() => go("models")} />}
{section === "budgets" && <BudgetsSettings />}
+ {section === "concurrency" && <ConcurrencySettings />}
{section === "notifications" && <NotificationsSettings />}
{section === "channels" && <ChannelsSettings />}
{section === "appearance" && <Appearance />}
diff --git a/src/channels/web.ts b/src/channels/web.ts
index 752f6e2c..f8da6106 100644
--- a/src/channels/web.ts
+++ b/src/channels/web.ts
@@ -22,7 +22,7 @@ interface PendingInteraction {
}
export interface ChatEvent {
- type: 'activity' | 'thinking' | 'reasoning' | 'plan' | 'artifacts' | 'provider' | 'heartbeat' | 'step_start' | 'step_done' | 'text_delta' | 'text_done' | 'permission_request' | 'permission_continue' | 'permission_mode' | 'permission_resolved' | 'choice_prompt' | 'choice_resolved' | 'loop_warning' | 'error' | 'bot_activity' | 'status' | 'session_switched' | 'queued' | 'research' | 'research_plan' | 'research_plan_resolved' | 'notice' | 'owner_approval';
+ type: 'activity' | 'thinking' | 'reasoning' | 'plan' | 'artifacts' | 'provider' | 'heartbeat' | 'step_start' | 'step_done' | 'text_delta' | 'text_done' | 'permission_request' | 'permission_continue' | 'permission_mode' | 'permission_resolved' | 'choice_prompt' | 'choice_resolved' | 'loop_warning' | 'error' | 'bot_activity' | 'status' | 'session_switched' | 'queued' | 'queue_dropped' | 'research' | 'research_plan' | 'research_plan_resolved' | 'notice' | 'owner_approval';
data?: Record<string, unknown>;
}
@@ -279,6 +279,11 @@ export class WebChannel extends BaseChannel {
this.broadcast({ type: 'queued', data: { targetId, ...data } });
}
+ /** Waiting messages of this chat were dropped (a stop): they will not run (ADR-038). */
+ sendQueueDropped(targetId: string, data: { dropped: number; reason: string }): void {
+ this.broadcast({ type: 'queue_dropped', data: { targetId, ...data } });
+ }
+
sendSessionSwitched(targetId: string, session: { id: string; shortId: string; alias: string; title: string }): void {
this.broadcast({ type: 'session_switched', data: { targetId, id: session.id, shortId: session.shortId, alias: session.alias, title: session.title } });
}
@@ -390,10 +395,10 @@ export class WebChannel extends BaseChannel {
return [...this.sseClients.values()].some((client) => client.sessionId === targetId);
}
- async send(content: string, targetId?: string, elapsedMs?: number): Promise<void> {
+ async send(content: string, targetId?: string, elapsedMs?: number, usage?: Record<string, unknown>): Promise<void> {
const delivered = this.broadcast({
type: 'text_done',
- data: { fullText: content, elapsedMs, targetId },
+ data: { fullText: content, elapsedMs, targetId, ...(usage ? { usage } : {}) },
});
if (!delivered) throw new Error('Cloud WebSocket could not accept the terminal response');
}
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 1ec13f1f..a09eb8db 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -619,6 +619,11 @@ interface TurnState {
done: boolean;
}
+/** The canonical session a message names, if any. */
+function sessionOf(msg: ChannelMessage): string | undefined {
+ return msg.sessionId ?? (typeof msg.metadata?.sessionId === 'string' ? msg.metadata.sessionId : undefined);
+}
+
/**
* The lane a message runs in: one turn at a time per lane, lanes run
* concurrently (ADR-037). A canonical session id when the message names
@@ -1449,13 +1454,14 @@ export class Agent {
}
/** Every running turn, oldest first: what each chat is doing (for /progress, status screens). */
- runningTurns(): Array<{ laneKey: string; channelType: string; channelId: string; content: string; activity: string; startedAt: number; completedSteps: number; narrative: import('../utils/tool-label.js').NarrativeStep[] }> {
+ runningTurns(): Array<{ laneKey: string; channelType: string; channelId: string; sessionId?: string; content: string; activity: string; startedAt: number; completedSteps: number; narrative: import('../utils/tool-label.js').NarrativeStep[] }> {
return [...this.activeTurns.values()]
.sort((a, b) => a.startedAt - b.startedAt)
.map((t) => ({
laneKey: t.laneKey,
channelType: t.message.channelType,
channelId: t.message.channelId,
+ ...(sessionOf(t.message) ? { sessionId: sessionOf(t.message) } : {}),
content: t.message.content,
activity: t.activity,
startedAt: t.startedAt,
@@ -1464,6 +1470,28 @@ export class Agent {
}));
}
+ /**
+ * Chats with messages waiting (for their own chat or a free slot), each
+ * once, with how many messages wait and the place of its first one.
+ */
+ waitingChats(): Array<{ channelType: string; channelId: string; sessionId?: string; waiting: number; position: number }> {
+ const out = new Map<string, { channelType: string; channelId: string; sessionId?: string; waiting: number; position: number }>();
+ this.messageQueue.forEach((item, i) => {
+ const lane = laneKeyFor(item.message);
+ const known = out.get(lane);
+ if (known) { known.waiting++; return; }
+ const sessionId = sessionOf(item.message);
+ out.set(lane, { channelType: item.message.channelType, channelId: item.message.channelId, ...(sessionId ? { sessionId } : {}), waiting: 1, position: this.positionOf(i) });
+ });
+ return [...out.values()];
+ }
+
+ /** Change how many chats run at once, live (ADR-037); waiting chats start if there is room now. */
+ setConcurrentTurnLimit(limit: number): void {
+ this.governor.setLimit(limit);
+ this.processQueue();
+ }
+
/**
* Abort one running turn. Its work entry is cancelled for a user stop (a
* restart never resumes it); a background hand-off keeps it. Returns
@@ -1808,6 +1836,17 @@ export class Agent {
this.queuedWorkKeys.delete(item.workKey);
try { this.workLedger.markCancelled(item.workKey, reason); } catch { /* entry may not exist */ }
}
+ // A screen showing "Waiting…" for one of them must hear it won't run.
+ // Best effort: telling a screen must never get in the way of the stop.
+ let web: { sendQueueDropped?: (target: string, data: { dropped: number; reason: string }) => void } | undefined;
+ try { web = this.channels?.get?.('web') as unknown as typeof web; } catch { web = undefined; }
+ if (web?.sendQueueDropped) {
+ const perChat = new Map<string, number>();
+ for (const item of dropped) if (item.message.channelType === 'web') perChat.set(item.message.channelId, (perChat.get(item.message.channelId) ?? 0) + 1);
+ for (const [target, count] of perChat) {
+ try { web.sendQueueDropped(target, { dropped: count, reason }); } catch { /* best effort */ }
+ }
+ }
this.announceQueue();
return dropped.length;
}
@@ -5360,6 +5399,7 @@ export class Agent {
inputTokens: turnTotals.inputTokens,
outputTokens: turnTotals.outputTokens,
totalTokens: turnTotals.totalTokens,
+ cachedInputTokens: turnTotals.cachedInputTokens,
budgetUsed: this.tokenBudget.getDailyUsed(),
budgetTotal: this.tokenBudget.getBudget(),
budgetPercentage: this.tokenBudget.getUsagePercentage(),
diff --git a/src/core/concurrent-turns.test.ts b/src/core/concurrent-turns.test.ts
index 079590cd..8f05765e 100644
--- a/src/core/concurrent-turns.test.ts
+++ b/src/core/concurrent-turns.test.ts
@@ -136,6 +136,20 @@ describe('concurrent turns', () => {
await agent.whenIdle();
});
+ it('raising the limit starts waiting chats at once', async () => {
+ const { agent, send, finish, log } = harness(1);
+ send(msg('a1', 'chat-a'));
+ send(msg('b1', 'chat-b'));
+ await tick(5);
+ expect(log).toEqual(['start a1']);
+ agent.setConcurrentTurnLimit(2);
+ await tick(5);
+ expect(log).toEqual(['start a1', 'start b1']);
+ await finish('a1');
+ await finish('b1');
+ await agent.whenIdle();
+ });
+
it('/stop in one chat stops only that chat', async () => {
const { agent, send, finish, log } = harness();
send(msg('a1', 'chat-a'));
diff --git a/src/core/stop-contract.test.ts b/src/core/stop-contract.test.ts
index 5fa3e0e6..42641bd8 100644
--- a/src/core/stop-contract.test.ts
+++ b/src/core/stop-contract.test.ts
@@ -152,3 +152,17 @@ describe("a stop clears the chat's line", () => {
expect(internals.messageQueue).toEqual([]);
});
});
+
+describe('the desktop hears about dropped waiting messages (ADR-038)', () => {
+ it('each web chat whose messages a stop dropped gets one queue_dropped with the count', async () => {
+ const { agent, workLedger } = bare();
+ const dropped: Array<{ target: string; dropped: number }> = [];
+ Object.assign(agent, { channels: { get: (t: string) => (t === 'web' ? { sendQueued: () => {}, sendQueueDropped: (target: string, d: { dropped: number }) => dropped.push({ target, dropped: d.dropped }) } : undefined) } });
+ startFakeTurn(agent, msg('a1', 'chat-a'));
+ for (const m of [msg('a2', 'chat-a'), msg('a3', 'chat-a'), msg('b1', 'chat-b')]) agent.queueMessage(m, workLedger.accept(m).entry.key);
+ expect(agent.waitingChats().map((w) => [w.channelId, w.waiting])).toEqual([['chat-a', 2], ['chat-b', 1]]);
+ await agent.stopAllWork('stopped', { channelId: 'chat-a' });
+ expect(dropped).toEqual([{ target: 'chat-a', dropped: 2 }]);
+ expect(agent.waitingChats().map((w) => w.channelId)).toEqual(['chat-b']);
+ });
+});
diff --git a/src/core/task-surface.ts b/src/core/task-surface.ts
index 73e13201..a5e8c26c 100644
--- a/src/core/task-surface.ts
+++ b/src/core/task-surface.ts
@@ -21,6 +21,8 @@ export interface CompletionMetaLike {
inputTokens: number;
outputTokens: number;
totalTokens: number;
+ /** Input tokens served from the provider's prompt cache (#296), when known. */
+ cachedInputTokens?: number;
budgetUsed: number;
budgetTotal: number;
budgetPercentage: number;
@@ -76,6 +78,8 @@ interface CliTaskChannel extends Channel {
interface WebTaskChannel extends Channel {
sendError(message: string, targetId?: string): boolean;
+ /** The final reply, with what it cost (older web channels ignore `usage`). */
+ send(content: string, targetId?: string, elapsedMs?: number, usage?: Record<string, unknown>): Promise<void>;
}
const hasFn = (obj: unknown, name: string): boolean => typeof (obj as Record<string, unknown> | null)?.[name] === 'function';
@@ -116,8 +120,17 @@ export function createTaskSurface(channel: Channel | undefined, channelType: Cha
return {
kind: 'web',
begin() {},
- async done({ finalText, elapsedMs }) {
- await web.send(finalText, channelId, elapsedMs);
+ async done({ finalText, elapsedMs, stepCount, meta }) {
+ // What the reply cost, so a screen can show it as soon as it lands.
+ await web.send(finalText, channelId, elapsedMs, {
+ provider: meta.provider,
+ model: meta.model,
+ inputTokens: meta.inputTokens,
+ cachedInputTokens: meta.cachedInputTokens ?? 0,
+ outputTokens: meta.outputTokens,
+ steps: stepCount,
+ elapsedMs,
+ });
},
async pause(banner) {
await web.send(banner, channelId).catch(warnSend);
diff --git a/src/core/testing/fake-turns.ts b/src/core/testing/fake-turns.ts
index 96226f6e..48713195 100644
--- a/src/core/testing/fake-turns.ts
+++ b/src/core/testing/fake-turns.ts
@@ -14,7 +14,7 @@ import { Lifecycle } from '../lifecycle.js';
* an always-admitting governor and a capability stub with a plain cwd.
*/
export function bareTurnFields(opts: { limit?: number; cwd?: string } = {}): Record<string, unknown> {
- const limit = opts.limit ?? 4;
+ let limit = opts.limit ?? 4;
let cwd = opts.cwd ?? process.cwd();
return {
messageQueue: [],
@@ -27,6 +27,7 @@ export function bareTurnFields(opts: { limit?: number; cwd?: string } = {}): Rec
lastAdmitRefusal: null,
governor: {
limit: () => limit,
+ setLimit: (n: number) => { limit = n; },
canAdmit: (running: number) => (running === 0 || running < limit ? { ok: true } : { ok: false, reason: 'capacity' }),
noteIdle: () => {},
},
diff --git a/src/index.ts b/src/index.ts
index 92219d80..a032cdf5 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -46,6 +46,7 @@ import {
clearSlackAccess,
} from './utils/config.js';
import type { MercuryConfig } from './utils/config.js';
+import { autoTurnLimit, machineFacts, resolveTurnLimit } from './core/turn-governor.js';
import type { ProviderName } from './utils/config.js';
import { logger } from './utils/logger.js';
import { devBuildLabel, isDevBuild } from './utils/dev-build.js';
@@ -99,7 +100,7 @@ import { ProviderModelFetchError, fetchProviderModelCatalog } from './utils/prov
import { withBaseUrl } from './providers/basic-auth.js';
import { initCloudTokenStore } from './cloud/token-store.js';
import { clearCloudRuntimeOnline, markCloudRuntimeOnline } from './cloud/runtime-status.js';
-import { startWebServer, stopWebServer, updateStatus as updateWebStatus, setUserMemory as setWebUserMemory, setWebChannel as setWebWebChannel, setScheduler as setWebScheduler, setAgentSupervisor as setWebSupervisor, setBackgroundTaskManager as setWebBgTasks, setSpotifyClient as setWebSpotify, setProgrammingMode as setWebProgrammingMode, setModelSwitchCallback as setWebModelSwitch, setCurrentProviderCallback as setWebCurrentProvider, setStatusSnapshotCallback as setWebStatusSnapshot, setKanbanSupervisor as setWebKanban, setKanbanBoardManager as setWebBoardManager, setKanbanProviders as setWebKanbanProviders, setIDEProviders as setWebIDEProviders, setSessionRepository as setWebSessions, setSessionSyncEnabledCallback as setWebSessionSyncEnabled, setBotManager as setWebBotManager, setBotsWebhookSecret, setShutdownHandler, setMcpManager as setWebMcpManager, setStopCallback as setWebStop, setSessionBusyLookup as setWebSessionBusy, setQueueControls as setWebQueueControls, setResearchControls as setWebResearchControls, setBudgetControls as setWebBudgetControls } from './web/server.js';
+import { startWebServer, stopWebServer, updateStatus as updateWebStatus, setUserMemory as setWebUserMemory, setWebChannel as setWebWebChannel, setScheduler as setWebScheduler, setAgentSupervisor as setWebSupervisor, setBackgroundTaskManager as setWebBgTasks, setSpotifyClient as setWebSpotify, setProgrammingMode as setWebProgrammingMode, setModelSwitchCallback as setWebModelSwitch, setCurrentProviderCallback as setWebCurrentProvider, setStatusSnapshotCallback as setWebStatusSnapshot, setKanbanSupervisor as setWebKanban, setKanbanBoardManager as setWebBoardManager, setKanbanProviders as setWebKanbanProviders, setIDEProviders as setWebIDEProviders, setSessionRepository as setWebSessions, setSessionSyncEnabledCallback as setWebSessionSyncEnabled, setBotManager as setWebBotManager, setBotsWebhookSecret, setShutdownHandler, setMcpManager as setWebMcpManager, setStopCallback as setWebStop, setSessionBusyLookup as setWebSessionBusy, setQueueControls as setWebQueueControls, setTurnControls as setWebTurnControls, setResearchControls as setWebResearchControls, setBudgetControls as setWebBudgetControls } from './web/server.js';
import { validateApiKey, validateBaseUrl, validateModelName } from './providers/provider-meta.js';
import { setFirstProviderHandler, setProvidersReload } from './web/api/providers.js';
import { setCloudReload } from './web/api/cloud.js';
@@ -3565,6 +3566,19 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
setWebStop((target) => agent.stopAllWork('stopped', target));
setWebSessionBusy((sessionId) => agent.isBusyWith(sessionId));
setWebQueueControls({ state: (id) => agent.queueStateFor(id), prioritize: (id) => agent.prioritize(id) });
+ setWebTurnControls({
+ running: () => agent.runningTurns().map((t) => ({
+ ...(t.sessionId ? { sessionId: t.sessionId } : {}),
+ channelType: t.channelType, channelId: t.channelId, startedAt: t.startedAt, activity: t.activity, steps: t.completedSteps,
+ })),
+ waiting: () => agent.waitingChats(),
+ limit: () => ({ limit: agent.governor.limit(), configured: config.concurrency?.maxTurns ?? 0, auto: autoTurnLimit(machineFacts()) }),
+ setLimit: (configured) => {
+ config.concurrency = { ...(config.concurrency ?? {}), maxTurns: configured };
+ saveConfig(config);
+ agent.setConcurrentTurnLimit(resolveTurnLimit(configured, machineFacts()));
+ },
+ });
setWebResearchControls({
state: (id) => agent.researchMode.stateFor(id),
finish: (id) => agent.finishResearch(id),
diff --git a/src/web/api-contract.ts b/src/web/api-contract.ts
index a319969b..36e4fa54 100644
--- a/src/web/api-contract.ts
+++ b/src/web/api-contract.ts
@@ -56,6 +56,9 @@ export const API_FEATURES: readonly string[] = Object.freeze([
'chat.favicon', // GET /api/chat/favicon?domain= — a site's icon (204 when it has none), fetched and cached by the runtime
'security.remote', // device pairing needs the owner (202 + POST /api/auth/token/pending), sensitive remote actions 428 + X-Mercury-Approval, /api/security/* (this computer), SSE 'owner_approval' (local activity), expired devices 401 { expired }
'updates', // GET /api/updates[?seen=1], POST /api/updates/check, POST /api/updates/server { version?, now? } (202; remote → 428 owner), POST /api/updates/server/cancel — see UPDATES.md
+ 'chat.running', // GET /api/chat/running (running + waiting chats, limit), PUT /api/chat/concurrency { maxTurns } — ADR-037; SSE 'queue_dropped' (ADR-038)
+ 'budget.split', // GET /api/budget daily.split + daily.cachedWeight, PUT { cachedWeight }; /api/usage split + counted breakdowns — #296
+ 'chat.usage', // message.usage on assistant replies; text_done { usage } — what each reply cost
'chat.research', // SSE 'research' / 'research_plan' / 'research_plan_resolved' / 'notice'; GET /api/chat/threads/:id/research, POST …/research/finish, …/research/off, POST /api/chat/research/plan/:id; message.research; step_done { failed, reason }
]);
diff --git a/src/web/api/budget.ts b/src/web/api/budget.ts
index 6c8ccd31..c8b3bb19 100644
--- a/src/web/api/budget.ts
+++ b/src/web/api/budget.ts
@@ -1,6 +1,6 @@
import { Hono } from 'hono';
import { saveConfig, type MercuryConfig } from '../../utils/config.js';
-import type { TokenBudget } from '../../utils/tokens.js';
+import { cachedWeightOf, type TokenBudget } from '../../utils/tokens.js';
import type { SaverMode } from '../../core/saver-mode.js';
/**
@@ -11,7 +11,10 @@ import type { SaverMode } from '../../core/saver-mode.js';
* PUT /api/budget { dailyBudget?, saver?: { manual?, autoEnabled?, autoThreshold? },
* bots?: { perBot?, fleet? } } → the same shape as GET
*
- * daily: today's tokens against the daily cap (Mercury pauses at the cap).
+ * daily: today's tokens against the daily cap (Mercury pauses at the cap),
+ * with today's split (cache hits, uncached input, output) and
+ * `cachedWeight`: how much a cache hit counts toward the cap (0–1).
+ * PUT { cachedWeight } sets it.
* saver: Token Saver: on by hand, or on by itself at a share of the cap.
* bots: the cap a bot gets when it sets none, and the cap for all bots
* together (0 = no cap).
@@ -38,6 +41,8 @@ function snapshot(c: BudgetControls) {
used: tokens.getDailyUsed(),
remaining: tokens.getRemaining(),
percentage: Math.round(tokens.getUsagePercentage()),
+ split: tokens.getDailySplit(),
+ cachedWeight: cachedWeightOf(cfg),
},
saver: {
state: saver.getState(),
@@ -74,6 +79,7 @@ budget.put('/api/budget', async (c) => {
if (!controls) return c.json({ error: 'Budgets are not available yet.' }, 503);
const body = (await c.req.json().catch(() => ({}))) as {
dailyBudget?: unknown;
+ cachedWeight?: unknown;
saver?: { manual?: unknown; autoEnabled?: unknown; autoThreshold?: unknown };
bots?: { perBot?: unknown; fleet?: unknown };
};
@@ -83,6 +89,9 @@ budget.put('/api/budget', async (c) => {
const perBot = body.bots?.perBot === undefined ? undefined : tokensFrom(body.bots.perBot, 'The per-bot budget', 0);
const fleet = body.bots?.fleet === undefined ? undefined : tokensFrom(body.bots.fleet, 'The all-bots budget', 0);
for (const v of [daily, perBot, fleet]) if (typeof v === 'string') return c.json({ error: v }, 400);
+ if (body.cachedWeight !== undefined && (typeof body.cachedWeight !== 'number' || !Number.isFinite(body.cachedWeight) || body.cachedWeight < 0 || body.cachedWeight > 1)) {
+ return c.json({ error: 'cachedWeight must be a number from 0 to 1.' }, 400);
+ }
const s = body.saver ?? {};
if (s.manual !== undefined && typeof s.manual !== 'boolean') return c.json({ error: 'saver.manual must be true or false.' }, 400);
if (s.autoEnabled !== undefined && typeof s.autoEnabled !== 'boolean') return c.json({ error: 'saver.autoEnabled must be true or false.' }, 400);
@@ -97,6 +106,11 @@ budget.put('/api/budget', async (c) => {
if (typeof s.autoEnabled === 'boolean') saver.setAutoEnabled(s.autoEnabled);
if (s.manual === true && !saver.isManual()) saver.enable();
if (s.manual === false && saver.isManual()) saver.disable();
+ if (typeof body.cachedWeight === 'number') {
+ const cfg = controls.config();
+ cfg.tokens = { ...cfg.tokens, cachedWeight: Math.round(body.cachedWeight * 100) / 100 };
+ saveConfig(cfg);
+ }
if (typeof perBot === 'number' || typeof fleet === 'number') {
const cfg = controls.config();
cfg.bots = cfg.bots ?? ({} as MercuryConfig['bots']);
diff --git a/src/web/api/chat.ts b/src/web/api/chat.ts
index 0003a300..64234bf5 100644
--- a/src/web/api/chat.ts
+++ b/src/web/api/chat.ts
@@ -39,6 +39,27 @@ export function setSessionSyncEnabledCallback(fn: () => boolean): void {
sessionSyncEnabledFn = fn;
}
+/**
+ * What one reply cost (#296: every step of its turn), from what the turn
+ * recorded: tokens in (and how many came from the prompt cache), tokens out,
+ * steps, time and the model. Nothing for replies recorded before usage was.
+ */
+function usageOf(meta: Record<string, unknown> | undefined): { usage?: { provider?: string; model?: string; inputTokens: number; cachedInputTokens: number; outputTokens: number; steps?: number; elapsedMs?: number } } {
+ if (!meta || typeof meta.inputTokens !== 'number' || typeof meta.outputTokens !== 'number') return {};
+ const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : undefined);
+ return {
+ usage: {
+ ...(typeof meta.provider === 'string' ? { provider: meta.provider } : {}),
+ ...(typeof meta.model === 'string' ? { model: meta.model } : {}),
+ inputTokens: num(meta.inputTokens) ?? 0,
+ cachedInputTokens: num(meta.cachedInputTokens) ?? 0,
+ outputTokens: num(meta.outputTokens) ?? 0,
+ ...(num(meta.steps) !== undefined ? { steps: num(meta.steps) } : {}),
+ ...(num(meta.elapsedMs) !== undefined ? { elapsedMs: num(meta.elapsedMs) } : {}),
+ },
+ };
+}
+
function toThread(session: ReturnType<SessionRepository['get']>, includeMessages = true) {
return {
id: session.id,
@@ -61,6 +82,7 @@ function toThread(session: ReturnType<SessionRepository['get']>, includeMessages
...(typeof message.metadata?.voiceRole === 'string' ? { voice: message.metadata.voiceRole } : {}),
...(Array.isArray(message.metadata?.artifacts) && message.metadata.artifacts.length ? { artifacts: message.metadata.artifacts } : {}),
...(message.metadata?.research && typeof message.metadata.research === 'object' ? { research: message.metadata.research } : {}),
+ ...(message.role === 'assistant' ? usageOf(message.metadata) : {}),
...(Array.isArray(message.metadata?.attachments) && message.metadata.attachments.length > 0
? { attachments: (message.metadata.attachments as Array<{ name: string; kind: string; mime?: string; ref: string }>).map((a) => ({ name: a.name, kind: a.kind, mime: a.mime, url: `/api/chat/uploads/${a.ref}` })) }
: {}),
@@ -93,6 +115,37 @@ export function setQueueControls(controls: typeof queueControls): void {
queueControls = controls;
}
+/** A chat a turn runs or waits in, as screens see it (ADR-037). */
+export interface TurnChat {
+ /** The thread/session it belongs to, when it has one (desktop/web chats always do). */
+ sessionId?: string;
+ channelType: string;
+ channelId: string;
+}
+
+/** Chats running at once: what runs, what waits, and the limit (ADR-037). */
+export interface TurnControls {
+ running: () => Array<TurnChat & { startedAt: number; activity: string; steps: number }>;
+ waiting: () => Array<TurnChat & { waiting: number; position: number }>;
+ /** `limit`: in effect now. `configured`: 0 = automatic. `auto`: what automatic gives on this machine. */
+ limit: () => { limit: number; configured: number; auto: number };
+ /** Set the configured limit (0 = automatic); applies at once and persists. */
+ setLimit: (configured: number) => void;
+}
+let turnControls: TurnControls | null = null;
+export function setTurnControls(controls: TurnControls | null): void {
+ turnControls = controls;
+}
+
+function turnsSnapshot(controls: TurnControls) {
+ const label = (activity: string) => activity.replace(/^\W+/u, '').replace(/\s+/g, ' ').trim().slice(0, 90);
+ return {
+ ...controls.limit(),
+ running: controls.running().map((t) => ({ ...t, activity: label(t.activity) })),
+ waiting: controls.waiting(),
+ };
+}
+
/** Research runs per chat: what's going on, "write the report now". */
let researchControls: {
state: (sessionId: string) => Record<string, unknown>;
@@ -815,6 +868,24 @@ chat.post('/api/chat/threads/:id/delete', async (c) => {
});
/** Save a thread to come back to later, or unsave it: { saved: boolean }. */
+// Which chats are working right now, which wait, and how many may run at once (ADR-037).
+chat.get('/api/chat/running', (c) => {
+ if (!turnControls) return c.json({ error: 'Not available on this runtime' }, 503);
+ return c.json(turnsSnapshot(turnControls));
+});
+
+// How many chats may run at once: { maxTurns: 0 (automatic) … 16 }. Applies at once.
+chat.put('/api/chat/concurrency', async (c) => {
+ if (!turnControls) return c.json({ error: 'Not available on this runtime' }, 503);
+ const body = await c.req.json<{ maxTurns?: unknown }>().catch(() => ({} as { maxTurns?: unknown }));
+ const n = body.maxTurns;
+ if (typeof n !== 'number' || !Number.isInteger(n) || n < 0 || n > 16) {
+ return c.json({ error: 'maxTurns must be a whole number from 0 (automatic) to 16.' }, 400);
+ }
+ turnControls.setLimit(n);
+ return c.json(turnsSnapshot(turnControls));
+});
+
// Where this chat's message stands: running, waiting in line (and behind what), or nothing.
chat.get('/api/chat/threads/:id/queue', (c) => {
if (!queueControls) return c.json({ state: 'none' });
diff --git a/src/web/api/desktop-parity.test.ts b/src/web/api/desktop-parity.test.ts
new file mode 100644
index 00000000..d0f84755
--- /dev/null
+++ b/src/web/api/desktop-parity.test.ts
@@ -0,0 +1,142 @@
+import { describe, expect, it, vi, beforeEach } from 'vitest';
+
+await vi.hoisted(async () => {
+ const fs = await import('node:fs');
+ const os = await import('node:os');
+ const path = await import('node:path');
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mercury-desktop-parity-'));
+ fs.writeFileSync(path.join(dir, 'mercury.yaml'), 'identity:\n owner: Test\n');
+ process.env.MERCURY_HOME = dir;
+});
+
+import { writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { getMercuryHome, loadConfig, type MercuryConfig } from '../../utils/config.js';
+import { TokenBudget } from '../../utils/tokens.js';
+import { SaverMode } from '../../core/saver-mode.js';
+import budget, { setBudgetControls } from './budget.js';
+import chat, { setSessionRepository, setTurnControls, type TurnControls } from './chat.js';
+import { SessionRepository } from '../../sessions/repository.js';
+import { mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import system from './system.js';
+
+/**
+ * What Mercury Desktop reads for today's runtime work (ADR-037/038, #296):
+ * which chats run and wait, the concurrency limit, the token split and cache
+ * weight, breakdowns that add up to the daily total.
+ */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+const json = async (res: Response): Promise<any> => res.json();
+const send = (app: { request: (url: string, init?: RequestInit) => Response | Promise<Response> }, method: string, path: string, body?: unknown) =>
+ app.request(`http://127.0.0.1${path}`, { method, headers: { 'Content-Type': 'application/json' }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
+
+describe('/api/chat/running and /api/chat/concurrency', () => {
+ let configured = 0;
+ const controls: TurnControls = {
+ running: () => [{ sessionId: 's1', channelType: 'web', channelId: 's1', startedAt: 1, activity: '🔎 Searching the web', steps: 2 }],
+ waiting: () => [{ sessionId: 's2', channelType: 'web', channelId: 's2', waiting: 2, position: 1 }],
+ limit: () => ({ limit: configured || 4, configured, auto: 4 }),
+ setLimit: (n) => { configured = n; },
+ };
+ beforeEach(() => { configured = 0; setTurnControls(controls); });
+
+ it('reports running and waiting chats with the limit; activity labels are trimmed of icons', async () => {
+ const body = await json(await send(chat, 'GET', '/api/chat/running'));
+ expect(body).toEqual({
+ limit: 4, configured: 0, auto: 4,
+ running: [{ sessionId: 's1', channelType: 'web', channelId: 's1', startedAt: 1, activity: 'Searching the web', steps: 2 }],
+ waiting: [{ sessionId: 's2', channelType: 'web', channelId: 's2', waiting: 2, position: 1 }],
+ });
+ });
+
+ it('sets the limit (0 = automatic) and refuses anything else', async () => {
+ const ok = await json(await send(chat, 'PUT', '/api/chat/concurrency', { maxTurns: 2 }));
+ expect(ok).toMatchObject({ limit: 2, configured: 2 });
+ for (const bad of [-1, 17, 2.5, '3', null]) {
+ expect((await send(chat, 'PUT', '/api/chat/concurrency', { maxTurns: bad })).status).toBe(400);
+ }
+ expect(configured).toBe(2);
+ });
+
+ it('is 503 on a runtime without it wired', async () => {
+ setTurnControls(null);
+ expect((await send(chat, 'GET', '/api/chat/running')).status).toBe(503);
+ });
+});
+
+describe('/api/budget: split and cache weight (#296)', () => {
+ let config: MercuryConfig;
+ let tokens: TokenBudget;
+ beforeEach(() => {
+ config = loadConfig();
+ tokens = new TokenBudget(config);
+ tokens.resetUsage();
+ setBudgetControls({ config: () => config, tokens: () => tokens, saver: () => new SaverMode(config) });
+ });
+
+ it("reports today's split and the weight, and sets the weight live", async () => {
+ tokens.recordUsage({ provider: 'p', model: 'm', inputTokens: 1000, outputTokens: 100, totalTokens: 1100, cachedInputTokens: 800, noCacheInputTokens: 200, channelType: 'web' });
+ const before = await json(await send(budget, 'GET', '/api/budget'));
+ expect(before.daily.split).toEqual({ inputTokens: 1000, cachedInputTokens: 800, noCacheInputTokens: 200, outputTokens: 100 });
+ expect(before.daily.cachedWeight).toBe(1);
+ const after = await json(await send(budget, 'PUT', '/api/budget', { cachedWeight: 0.1 }));
+ expect(after.daily.cachedWeight).toBe(0.1);
+ // The next request counts cache hits at the new weight.
+ const used = tokens.getDailyUsed();
+ tokens.recordUsage({ provider: 'p', model: 'm', inputTokens: 1000, outputTokens: 0, totalTokens: 1000, cachedInputTokens: 1000, noCacheInputTokens: 0, channelType: 'web' });
+ expect(tokens.getDailyUsed() - used).toBe(100);
+ });
+
+ it('refuses a weight outside 0–1', async () => {
+ for (const bad of [-0.1, 1.5, 'half']) expect((await send(budget, 'PUT', '/api/budget', { cachedWeight: bad })).status).toBe(400);
+ });
+});
+
+describe('/api/usage: breakdowns add up to what the budget counted', () => {
+ it('sums counted tokens per provider and channel, and reports the split', async () => {
+ const today = new Date().toISOString().slice(0, 10);
+ writeFileSync(join(getMercuryHome(), 'token-usage.json'), JSON.stringify({
+ dailyUsed: 300, dailyBudget: 1000, lastResetDate: today,
+ dailySplit: { inputTokens: 2000, cachedInputTokens: 1800, noCacheInputTokens: 200, outputTokens: 100 },
+ requestLog: [
+ { timestamp: 1, provider: 'anthropic', model: 'm', inputTokens: 2000, outputTokens: 100, totalTokens: 2100, channelType: 'web', cachedInputTokens: 1800, countedTokens: 300 },
+ ],
+ }));
+ const body = await json(await send(system, 'GET', '/api/usage'));
+ expect(body.byProvider).toEqual({ anthropic: 300 });
+ expect(body.byChannel).toEqual({ web: 300 });
+ expect(body.dailyUsed).toBe(300);
+ expect(body.split).toEqual({ inputTokens: 2000, cachedInputTokens: 1800, noCacheInputTokens: 200, outputTokens: 100 });
+ });
+
+ it("an old row without countedTokens counts in full; yesterday's split is not today's", async () => {
+ writeFileSync(join(getMercuryHome(), 'token-usage.json'), JSON.stringify({
+ dailyUsed: 50, dailyBudget: 1000, lastResetDate: '2020-01-01',
+ dailySplit: { inputTokens: 1, cachedInputTokens: 0, noCacheInputTokens: 1, outputTokens: 1 },
+ requestLog: [{ timestamp: 1, provider: 'x', model: 'm', inputTokens: 40, outputTokens: 10, totalTokens: 50, channelType: 'cli' }],
+ }));
+ const body = await json(await send(system, 'GET', '/api/usage'));
+ expect(body.byProvider).toEqual({ x: 50 });
+ expect(body.split).toBeUndefined();
+ });
+});
+
+describe('thread messages carry what each reply cost (#296)', () => {
+ it('assistant replies with recorded usage have it; others do not', async () => {
+ const repo = new SessionRepository({ rootDir: mkdtempSync(join(tmpdir(), 'mercury-parity-sessions-')), autoMigrate: false });
+ setSessionRepository(repo);
+ const session = repo.create();
+ repo.appendMessage(session.id, { role: 'user', content: 'hi', timestamp: 1 });
+ repo.appendMessage(session.id, {
+ role: 'assistant', content: 'hello', timestamp: 2,
+ metadata: { provider: 'anthropic', model: 'claude-x', inputTokens: 12000, cachedInputTokens: 10000, noCacheInputTokens: 2000, outputTokens: 300, steps: 3, elapsedMs: 4200, traceId: 't' },
+ });
+ repo.appendMessage(session.id, { role: 'assistant', content: 'old reply', timestamp: 3 });
+ const body = await json(await send(chat, 'GET', `/api/chat/threads/${session.id}`));
+ const [user, reply, old] = body.messages;
+ expect(user.usage).toBeUndefined();
+ expect(reply.usage).toEqual({ provider: 'anthropic', model: 'claude-x', inputTokens: 12000, cachedInputTokens: 10000, outputTokens: 300, steps: 3, elapsedMs: 4200 });
+ expect(old.usage).toBeUndefined();
+ });
+});
diff --git a/src/web/api/system.ts b/src/web/api/system.ts
index 56aface6..70276427 100644
--- a/src/web/api/system.ts
+++ b/src/web/api/system.ts
@@ -226,7 +226,11 @@ system.get('/api/usage', (c) => {
outputTokens: number;
totalTokens: number;
channelType: string;
+ cachedInputTokens?: number;
+ noCacheInputTokens?: number;
+ countedTokens?: number;
}>;
+ dailySplit?: { inputTokens: number; cachedInputTokens: number; noCacheInputTokens: number; outputTokens: number };
} = {
dailyUsed: 0,
dailyBudget: 0,
@@ -248,9 +252,12 @@ system.get('/api/usage', (c) => {
const byProvider: Record<string, number> = {};
const byChannel: Record<string, number> = {};
+ // What each request added to the daily total (cache hits at tokens.cachedWeight), so the
+ // breakdowns add up to dailyUsed; older rows without it counted in full.
for (const row of data.requestLog || []) {
- byProvider[row.provider] = (byProvider[row.provider] || 0) + (row.totalTokens || 0);
- byChannel[row.channelType] = (byChannel[row.channelType] || 0) + (row.totalTokens || 0);
+ const counted = typeof row.countedTokens === 'number' ? row.countedTokens : (row.totalTokens || 0);
+ byProvider[row.provider] = (byProvider[row.provider] || 0) + counted;
+ byChannel[row.channelType] = (byChannel[row.channelType] || 0) + counted;
}
// The budget the runtime enforces is the live one. The tracker file carries whatever was
@@ -268,6 +275,10 @@ system.get('/api/usage', (c) => {
requestLog: (data.requestLog || []).slice(-100).reverse(),
byProvider,
byChannel,
+ // Today's input/output split across every request (#296), when the tracker has it.
+ ...(data.dailySplit && typeof data.dailySplit === 'object' && data.lastResetDate === new Date().toISOString().slice(0, 10)
+ ? { split: data.dailySplit }
+ : {}),
});
});
diff --git a/src/web/server.ts b/src/web/server.ts
index 8efae9a8..d21c6877 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -21,7 +21,7 @@ import artifactRoutes from './api/artifacts.js';
import configRoutes from './api/config.js';
import systemRoutes, { setScheduler } from './api/system.js';
import brainRoutes, { setUserMemory } from './api/brain.js';
-import chatRoutes, { setWebChannel, setProgrammingMode, setModelSwitchCallback, setCurrentProviderCallback, setStatusSnapshotCallback, setSessionRepository, setSessionSyncEnabledCallback, setStopCallback, setSessionBusyLookup, setQueueControls, setResearchControls } from './api/chat.js';
+import chatRoutes, { setWebChannel, setProgrammingMode, setModelSwitchCallback, setCurrentProviderCallback, setStatusSnapshotCallback, setSessionRepository, setSessionSyncEnabledCallback, setStopCallback, setSessionBusyLookup, setQueueControls, setResearchControls, setTurnControls } from './api/chat.js';
import agentRoutes, { setAgentSupervisor, setBackgroundTaskManager } from './api/agents.js';
import botsRoutes, { setBotManager, setBotsWebhookSecret } from './api/bots.js';
import spotifyRoutes, { setSpotifyClient } from './api/spotify.js';
@@ -253,7 +253,7 @@ if (spaAvailable) {
}
export { setShutdownHandler, setMcpManager };
-export { setStopCallback, setSessionBusyLookup, setQueueControls, setResearchControls };
+export { setStopCallback, setSessionBusyLookup, setQueueControls, setResearchControls, setTurnControls };
export { updateStatus, setUserMemory, setWebChannel, setScheduler, setAgentSupervisor, setBackgroundTaskManager, setSpotifyClient, setProgrammingMode, setModelSwitchCallback, setCurrentProviderCallback, setStatusSnapshotCallback, setKanbanSupervisor, setKanbanBoardManager, setKanbanProviders, setIDEProviders, setBotManager, setBotsWebhookSecret };
let webServer: ReturnType<typeof createAdaptorServer> | null = null;