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: show each turn as it happens; thinking effort per chat with detection (ADR-041)

Salman Qureshid00d441080f4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fd98ef72..c9d20af8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,24 @@
## Unreleased
+### Seeing Mercury work
+- **A reply reads top to bottom as it happens.** In Mercury Desktop the thinking, each tool it runs, the answer and any notes appear in order at the bottom of the chat, where you already are. Before, the activity sat above the answer and scrolled out of view as the answer grew.
+- **Tools show while they run.** Each tool appears when it starts, with a live timer, and gets a tick or an error with the real duration when it ends. Before, a tool appeared only after it had finished, so a long command showed nothing. Failures show their reason, and long runs fold earlier steps away.
+- **A status line under the running reply** always says what's happening ("Running npm test", "Thinking", "Calling anthropic") and how long the reply has taken. If the model sends nothing for 20 seconds it says it's waiting on the model, and after two minutes it suggests stopping and trying again.
+- **No more flicker.** The status no longer flips back to "Thinking" every few seconds. A reply no longer appears to end while Mercury keeps working, and notes like "Checking my work…" stay inside the reply.
+- **Thinking you can read.**
+ - **Claude:** Claude 5 models (Opus, Sonnet and Haiku 5.x, Fable) already think, but showed nothing; Mercury now asks for a readable summary.
+ - **ChatGPT:** ChatGPT sign-in models now send a reasoning summary.
+ - **Other servers:** Ollama, LM Studio, vLLM, LiteLLM and other OpenAI-compatible servers had their thinking dropped. It now shows.
+ - **While and after:** thinking stays open while it streams and folds to "Thought for 12s" when the model moves on. Reopened chats keep their thinking and steps.
+- **Choose how hard the model thinks, per chat** (#188). An Effort picker next to the model in the composer (Auto, Low, Medium, High, plus Off, Extra high and Max where the model takes them) sets the effort for that chat. "Model default" goes back to the model's own setting, which the picker's last item (or `/effort global <level>`) changes for every chat without its own. In the terminal and chat apps: `/effort`, `/effort high`, `/effort default`. `/status` shows the effort in use and where it comes from. On Claude 4.6–4.8, thinking turns on when a level is picked and stays off on Auto, as before.
+- **Effort on OpenAI-compatible servers.**
+ - **Ollama** is asked which models can think, and only those get a picker. gpt-oss gets Low/Medium/High; other thinking models get Off/High.
+ - **LiteLLM** reports each model's `supports_reasoning`.
+ - **OpenRouter** lists each model's supported parameters, and the effort is sent in its own `reasoning` field.
+ - **Other servers** (LM Studio, vLLM, custom endpoints) get a picker for known reasoning models: o-series, GPT-5, gpt-oss, Gemini 2.5+, Claude 4.6+ and Grok 3 mini.
+ - **If a server rejects the effort,** the request is resent without it and Mercury stops sending it to that model, instead of the reply failing.
+
### 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.
diff --git a/DECISIONS.md b/DECISIONS.md
index ad94ff55..b5cc2ef9 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -451,3 +451,63 @@
- Fresh installs carry six general-purpose skills, and nothing reinstalls a skill the owner removed.
- No default skill can make shell commands prompt-free.
- A skill gets used when its description fits or when the user names it. Skill authors should write descriptions that say plainly when to use the skill.
+
+## ADR-041: A turn is shown as it happens: live tool events, readable thinking, effort per model
+
+- **Context**:
+ - **Activity was drawn above the answer.** Mercury Desktop rendered a running turn as its thought process (thinking and tool steps), then the streamed text. With the view pinned to the bottom, the activity scrolled off the top as the answer grew.
+ - **Tool events arrived late.** The web channel sent `step_start` and `step_done` back to back from `onStepFinish`, after the step and all its tools had finished. A long command showed nothing, and every duration was about 0s. The real-time `experimental_onToolCallStart`/`Finish` hooks fed only the terminal.
+ - **The status flickered.** The progress path re-sent a typing signal every ~4s for Telegram. On web this was a `thinking` event, and the desktop treated it as "set state to Thinking". A `markProgress()` after the reply could start a phantom turn.
+ - **Progress notes ended the turn on screen.** Mid-turn notes went through `channel.send`, which on web is `text_done`: "Checking my work…", "picking up where I left off", "getting started on the real build", Autopilot notes and the reasoning-loop warning.
+ - **Reasoning never reached the screen:**
+ - Claude 5-era models think by default but return empty thinking blocks unless the request sets `display: "summarized"`, and Mercury sent no thinking options at all.
+ - The AI SDK's OpenAI chat parser ignores the non-standard `reasoning_content` / `reasoning` field used by Ollama, LM Studio, vLLM and LiteLLM.
+ - ChatGPT requests asked for no summary.
+ - Continuation and guard rounds dropped reasoning entirely.
+ - **The effort control was incomplete.** Per-model reasoning levels existed in the API (`model-prefs.ts`) but only for ChatGPT, OpenAI reasoning models and Ollama. The desktop never showed them, and there was no terminal command.
+ - **Prior art agrees.** ChatGPT, Claude, Cursor, Codex, Copilot, Zed and Perplexity show activity inline and in time order inside the current reply. Thinking is open while it streams and collapsed after ("Thought for Ns"). Tool rows carry status and duration. There is never a bare spinner: a step and a timer are always shown. Effort is a pill beside the model picker, hidden where unsupported.
+- **Decision**:
+ - **Tool events are live and paired.**
+ - `pushLiveToolEvent` sends `step_start`/`step_done` to the web channel when each tool starts and ends, in every round (main, continuation, guard, fallback).
+ - Events carry the tool call `id`, a readable `title` (from `formatToolStep`) and the SDK's `durationMs`.
+ - The `onStepFinish` web branch is removed.
+ - `pushLiveActivity` phases go to web as a `phase` event.
+ - **Mid-turn notes are `progress` events on web** (`sendProgressNote`). Other channels still get a message.
+ - **Thinking events cannot regress state.** The desktop treats `thinking` as "a turn is alive": it starts a turn only when none is showing, never downgrades Working/Answering, and ignores one within 2.5s of a reply. The runtime no longer refreshes typing after delivering the reply.
+ - **One reasoning sink.** `reasoningSink()` feeds the terminal preview, the web `reasoning` event and the turn trace from every streaming round. `stepAwareTextStream` closes a thinking block at each step boundary and tool call, so interleaved thinking shows as separate blocks.
+ - **Reasoning on the wire** (`providers/reasoning-wire.ts`):
+ - **Anthropic** goes through a per-call middleware.
+ - Models that think by default (Opus/Sonnet/Haiku 5+, Fable, Mythos) always get `thinking: {type: "adaptive", display: "summarized"}`. Display changes visibility only; the thinking happens and is billed either way.
+ - Opt-in models (Opus/Sonnet 4.6, Opus 4.7/4.8) get adaptive thinking only when the owner picks an effort. Auto leaves their requests unchanged, so no new thinking blocks appear in their tool loops.
+ - The effort goes to `output_config.effort`, limited to the levels the model accepts: 4.6 has no `xhigh`, and pre-4.6 models get nothing.
+ - **Chat Completions** responses (streamed and not) have `reasoning_content`/`reasoning` folded into `<think>` tags by a fetch wrapper. `extractReasoningMiddleware` turns them back into reasoning parts, which also handles models that write `<think>` themselves.
+ - **ChatGPT (Codex backend)** requests ask for `reasoning.summary: "auto"`.
+ - **The OpenAI API is deliberately not changed.** Its summaries need a verified organization, and an unverified one would answer 400.
+ - **The trace is kept.** `TurnTrace` (per turn, bounded to 150 items and 24k characters of thinking) records thinking blocks and tool calls with durations. It is saved as the reply's `metadata.trace` and returned by the threads API. The desktop drops the separate "Used N tools" entry when the reply carries the same calls.
+ - **The desktop draws a timeline** (`app/trace.ts`, `TurnTimeline.tsx`): thinking, tool groups, streamed text and notes in order, newest at the bottom. A status line shows the current activity and the turn's elapsed time. It warns after 20s and again after 120s with no event while no tool is running. A finished reply folds it into "Thought for…" / "Worked for… · N steps". The jump pill says "New activity" while a turn runs.
+ - **Effort is per model**, as before, with levels extended to `xhigh` and `max`. It is shown as a composer pill beside the model picker only when the current model has levels, and set in chat with `/effort [level]`. A per-chat effort was rejected for now: on Anthropic a top-level effort change invalidates the message cache, and a per-model setting keeps it stable.
+- **Consequences**:
+ - Long tool calls are visible while they run, with true durations. A silent model reads as "waiting on the model", not as a frozen screen.
+ - Claude 5 users see thinking summaries at no extra token cost.
+ - Choosing an effort on Claude 4.6–4.8 turns on thinking, and with it thinking-block handling in tool loops. This happens only when chosen.
+ - Older desktops still work: `step_start`/`step_done` keep their fields, and `progress`/`phase` are ignored. Older runtimes still work with the new desktop, which matches steps by tool name when no id is sent.
+ - The web dashboard shows `progress` notes as messages and offers the new levels.
+- **Amendment (issue #188): effort per chat, detected per server.**
+ - **Two layers.** The model's saved level (`model-prefs.json`) is the global default. A chat can override it (`chat-effort.json`, keyed by the turn's lane: a desktop thread id, `cli`, or a channel conversation; at most 1000).
+ - Each turn claims its chat in a turn-scoped value (`claimEffortChat`), so every request it makes reads that chat's override through `effortFor()`, with no plumbing through call sites. That covers Anthropic middleware, the OpenAI-style fetch hook and ChatGPT.
+ - A chat's "auto" sends nothing even when the model has a default.
+ - A chat pick the current model can't take falls back to the model's default and is reported (`chatUnsupported`).
+ - `/effort <level>`, `/effort default` and `/effort global <level>`. `/status` shows the effective level and its source.
+ - `POST /api/chat/effort` and `GET /api/chat/models?sessionId=` (`current.effort`). The desktop picker sets the chat; a pick made before a new chat exists is applied when its thread is created.
+ - **Levels for OpenAI-compatible servers are learned, in order of trust** (`reasoning-caps.ts`, `reasoning-discovery.ts`):
+ 1. **A 400 to an effort.** The fetch hook resends the request without the effort and records the model as taking none, for 7 days. A later discovery can't overrule it.
+ 2. **What the server says**, cached for a day:
+ - Ollama `/api/show` capabilities. gpt-oss gets low/medium/high; other thinking models get off/high. Non-thinking models get none, which stops the "does not support thinking" errors the old fixed list could cause.
+ - LiteLLM `/model/info` `supports_reasoning`.
+ - OpenRouter `supported_parameters`. Its effort is sent as `reasoning: {effort}`.
+ 3. **Known reasoning families by name**: o-series, GPT-5, gpt-oss, Gemini 2.5+, Claude 4.6+ and Grok 3 mini.
+
+ Discovery runs when a screen lists models (the current model, bounded at 2.5s) and on `/effort`.
+ - **Rejected:**
+ - A probe request on every startup (cost, and side effects on metered gateways).
+ - Treating every OpenAI-compatible model as effort-capable (a wrong guess would cost a 400 on the first request of every chat).
diff --git a/apps/desktop/src/api/mercury.ts b/apps/desktop/src/api/mercury.ts
index 32555aaf..acc7773d 100644
--- a/apps/desktop/src/api/mercury.ts
+++ b/apps/desktop/src/api/mercury.ts
@@ -4,7 +4,7 @@
═══════════════════════════════════════════════════════════════ */
import { http, ApiError } from "./client";
-import type { TurnsInfo } from "./types";
+import type { ChatEffort, 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,
@@ -106,7 +106,9 @@ export const chat = {
commands: () => http.get<{ commands: CommandEntry[] }>("/api/chat/commands").then((r) => r.commands),
settings: () => http.get<ChatSettings>("/api/chat/settings"),
updateSettings: (patch: Partial<ChatSettings>) => http.put<ChatSettings>("/api/chat/settings", patch),
- models: () => http.get<ModelsResponse>("/api/chat/models"),
+ models: (sessionId?: string | null) => http.get<ModelsResponse>(`/api/chat/models${sessionId ? `?sessionId=${encodeURIComponent(sessionId)}` : ""}`),
+ /** This chat's effort: a level, "auto", or null for the model's default (#188). */
+ setEffort: (sessionId: string, level: ReasoningChoice | null) => http.post<{ ok: boolean; effort: ChatEffort }>("/api/chat/effort", { sessionId, level }),
switchModel: (provider: string, model?: string) => http.post<{ ok: boolean; message: string }>("/api/chat/models/switch", { provider, model }),
setReasoning: (provider: string, model: string, reasoning: ReasoningChoice | null) => http.post<{ ok: boolean }>("/api/chat/models/prefs", { provider, model, reasoning }),
};
diff --git a/apps/desktop/src/api/types.ts b/apps/desktop/src/api/types.ts
index 6e3b7a24..06fbde72 100644
--- a/apps/desktop/src/api/types.ts
+++ b/apps/desktop/src/api/types.ts
@@ -168,22 +168,41 @@ export interface ResearchPlanPrompt {
export interface ThoughtStep {
id: number;
+ /** The tool call id (runtimes that send tool events live); matches its step_done. */
+ key?: string;
tool: string;
label: string;
+ /** "Read src/x.ts", "Run npm test": what the step did, in words. */
+ title?: string;
/** "stopped": cut off by the stop button before it finished. */
status: "running" | "done" | "error" | "stopped";
summary?: string;
startedAt: number;
endedAt?: number;
+ /** How long the tool ran (the runtime's own measure where it sent one). */
+ durationMs?: number;
}
+/** One entry of a turn's timeline, in the order it happened. */
+export type TraceItem =
+ | { kind: "reasoning"; text: string; startedAt: number; endedAt?: number }
+ | { kind: "step"; key: string }
+ | { kind: "text"; text: string }
+ | { kind: "note"; text: string; at: number };
+
export interface ThoughtTrace {
reasoning: string;
steps: ThoughtStep[];
+ /** The order things happened in (newer runtimes and live turns). */
+ items?: TraceItem[];
startedAt: number;
endedAt?: number;
/** The turn was stopped by you, not finished. */
stopped?: boolean;
+ /** Live only: what the runtime says it is doing between tools ("Calling anthropic"). */
+ phase?: string;
+ /** Live only: when the runtime last sent anything for this turn. */
+ lastEventAt?: number;
}
export interface MessageAttachment {
@@ -194,7 +213,7 @@ export interface MessageAttachment {
src?: string;
}
-export type ReasoningLevel = "off" | "low" | "medium" | "high";
+export type ReasoningLevel = "off" | "low" | "medium" | "high" | "xhigh" | "max";
export type ReasoningChoice = ReasoningLevel | "auto";
export interface ModelDescription {
@@ -206,8 +225,17 @@ export interface ModelDescription {
reasoningLevels: ReasoningLevel[];
}
+/** The effort a chat's requests carry, and where it comes from (#188). */
+export interface ChatEffort {
+ effective: ReasoningChoice;
+ source: "chat" | "model" | "auto";
+ modelDefault: ReasoningChoice;
+ chat: ReasoningChoice | null;
+ chatUnsupported?: boolean;
+}
+
export interface ModelsResponse {
- current: { name: string; model: string } & ModelDescription;
+ current: { name: string; model: string; effort?: ChatEffort } & ModelDescription;
providers: ({ name: string; model: string; available: boolean; isCurrent?: boolean } & ModelDescription)[];
}
diff --git a/apps/desktop/src/app/conversation.ts b/apps/desktop/src/app/conversation.ts
index 0b44715d..1069d2c3 100644
--- a/apps/desktop/src/app/conversation.ts
+++ b/apps/desktop/src/app/conversation.ts
@@ -9,6 +9,7 @@ import { createContext, useContext } from "react";
import { create, type StoreApi, type UseBoundStore } from "zustand";
import type { ChatMessage, PendingPrompt, ResearchPlanPrompt, ResearchSnapshot, ThoughtTrace } from "~/api/types";
import type { AgentState } from "./store";
+import { newTrace } from "./trace";
export type Surface = "chat" | "code";
@@ -32,6 +33,9 @@ export interface ConversationState {
waiting: { position: number; busyWith?: string; busySessionId?: string } | null;
setWaiting(waiting: ConversationState["waiting"]): void;
setStopping(stopping: boolean): void;
+ /** An effort picked before this chat existed: applied when its thread is created. */
+ pendingEffort?: import("~/api/types").ReasoningChoice;
+ setPendingEffort(level: import("~/api/types").ReasoningChoice | undefined): void;
/** Text to put in the box (an undone message); the composer takes it once. */
draft: string | null;
setDraft(draft: string | null): void;
@@ -83,6 +87,8 @@ function makeConversation(surface: Surface): ConversationStore {
setStopping: (stopping) => set({ stopping }),
draft: null,
setDraft: (draft) => set({ draft }),
+ pendingEffort: undefined,
+ setPendingEffort: (pendingEffort) => set({ pendingEffort }),
plan: null,
setPlan: (plan) => set({ plan }),
research: null,
@@ -91,9 +97,9 @@ function makeConversation(surface: Surface): ConversationStore {
setResearchPlan: (researchPlan) => set({ researchPlan }),
notice: null,
setNotice: (notice) => set({ notice }),
- setLive: (update) => set((s) => ({ live: update(s.live ?? { reasoning: "", steps: [], startedAt: Date.now() }) })),
+ setLive: (update) => set((s) => ({ live: update(s.live ?? newTrace()) })),
clearLive: () => set({ live: null }),
- setActive: (activeId) => set({ activeId, prompts: [], step: null, agent: "idle", live: null, stopping: false, plan: null, research: null, researchPlan: null, notice: null }),
+ setActive: (activeId) => set({ activeId, prompts: [], step: null, agent: "idle", live: null, stopping: false, plan: null, research: null, researchPlan: null, notice: null, pendingEffort: undefined }),
setMessages: (messages) => set({ messages }),
addMessage: (message) => set((s) => ({ messages: [...s.messages, message] })),
appendStreaming: (text) => set((s) => ({ streaming: s.streaming + text })),
diff --git a/apps/desktop/src/app/events.ts b/apps/desktop/src/app/events.ts
index 8f20f50f..bc3c013c 100644
--- a/apps/desktop/src/app/events.ts
+++ b/apps/desktop/src/app/events.ts
@@ -14,6 +14,7 @@ import { useBots, useChat, useRuntimeState, type AgentState } from "./store";
import { conversations, useCodeSessions, type ConversationStore, type Surface } from "./conversation";
import type { ArtifactRef } from "~/api/artifacts";
import { useNotify } from "./notify/store";
+import { addNote, addReasoning, addText, endReasoning, finishTool, finishTrace, hasProcess, markStopped, newTrace, normalizeMessages, setPhase, startTool } from "./trace";
export function useRuntimeEvents(enabled: boolean): void {
const chatId = conversations.chat((s) => s.activeId);
@@ -100,6 +101,9 @@ function safeJson<T>(raw: string): T | null {
}
}
+/** When each surface's last reply landed: a late "thinking" right after it is not a new turn. */
+const lastReplyAt = new WeakMap<ConversationStore, number>();
+
/** Artifacts that arrived before their reply did: attached when it lands. */
const pendingArtifacts = new WeakMap<ConversationStore, ArtifactRef[]>();
@@ -143,7 +147,8 @@ export function handleEvent(store: ConversationStore, event: string, raw: string
switch (event) {
case "connected":
case "provider":
- useRuntimeState.getState().setProvider(String(data.provider ?? ""), String(data.model ?? ""));
+ // `connected` names it `provider`; older `provider` events only `name`.
+ useRuntimeState.getState().setProvider(String(data.provider ?? data.name ?? ""), String(data.model ?? ""));
break;
case "status":
// The runtime's live status: a permission change made anywhere (a toggle here, /permissions
@@ -165,11 +170,27 @@ export function handleEvent(store: ConversationStore, event: string, raw: string
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":
+ case "thinking": {
+ // Sent every few seconds while a turn makes progress (it keeps a
+ // Telegram typing dot alive). It starts a turn on screen only when none
+ // is showing, and never turns "Working"/"Answering" back to "Thinking".
conv.setWaiting(null);
- conv.setAgent("thinking");
+ const quiet = conv.agent === "idle" || conv.agent === "offline";
+ if (quiet && !conv.live && Date.now() - (lastReplyAt.get(store) ?? 0) < 2500) break;
+ if (quiet) conv.setAgent("thinking");
conv.setLive((l) => l);
break;
+ }
+ case "phase":
+ if (typeof data.phase === "string" && data.phase) {
+ const label = typeof data.detail === "string" && data.detail && !/^(stall|step budget|verification gate|execute guard|completion contract)$/i.test(data.detail) ? `${data.phase} · ${data.detail}` : data.phase;
+ if (conv.live || conv.agent !== "idle") conv.setLive((l) => setPhase(l, label));
+ }
+ break;
+ case "progress":
+ // "Checking my work…": a note inside the running turn, not its reply.
+ if (typeof data.text === "string" && data.text.trim()) conv.setLive((l) => addNote(l, data.text as string));
+ break;
case "research":
onResearch(store, data);
break;
@@ -201,15 +222,21 @@ export function handleEvent(store: ConversationStore, event: string, raw: string
}
case "reasoning":
conv.setWaiting(null);
- if (data.done === true) break;
- if (typeof data.text === "string" && data.text) conv.setLive((l) => ({ ...l, reasoning: (l.reasoning + data.text).slice(-20_000) }));
+ if (data.done === true) { if (conv.live) conv.setLive((l) => endReasoning(l)); break; }
+ if (typeof data.text === "string" && data.text) conv.setLive((l) => addReasoning(l, data.text as string));
break;
case "step_start": {
conv.setWaiting(null);
const tool = String(data.tool ?? "");
conv.setStep({ total: Number(data.totalSteps ?? 0), current: Number(data.step ?? data.stepNumber ?? 0), tool });
conv.setAgent("working");
- conv.setLive((l) => ({ ...l, steps: [...l.steps, { id: Number(data.step ?? l.steps.length + 1), tool, label: String(data.label ?? tool), status: "running" as const, startedAt: Date.now() }].slice(-100) }));
+ conv.setLive((l) => startTool(l, {
+ key: typeof data.id === "string" ? data.id : undefined,
+ tool,
+ title: typeof data.title === "string" ? data.title : undefined,
+ label: String(data.label ?? tool),
+ step: Number(data.step) || undefined,
+ }));
break;
}
case "step_done": {
@@ -219,19 +246,20 @@ export function handleEvent(store: ConversationStore, event: string, raw: string
const failed = stepFailed(data, summary);
const shown = failed && typeof data.reason === "string" && data.reason ? data.reason : summary;
conv.setStep({ total: Number(data.totalSteps ?? 0), current: Number(data.stepNumber ?? 0), tool });
- conv.setLive((l) => {
- const steps = [...l.steps];
- for (let i = steps.length - 1; i >= 0; i--) {
- if (steps[i].status === "running" && steps[i].tool === tool) { steps[i] = { ...steps[i], status: failed ? "error" : "done", summary: shown, endedAt: Date.now() }; break; }
- }
- return { ...l, steps };
- });
+ conv.setLive((l) => finishTool(l, {
+ key: typeof data.id === "string" ? data.id : undefined,
+ tool,
+ failed,
+ summary: shown,
+ durationMs: typeof data.durationMs === "number" ? data.durationMs : undefined,
+ }));
break;
}
case "text_delta":
conv.setWaiting(null);
conv.setAgent("streaming");
conv.appendStreaming(String(data.text ?? ""));
+ conv.setLive((l) => addText(l, String(data.text ?? "")));
break;
case "text_done": {
conv.setWaiting(null);
@@ -240,7 +268,8 @@ export function handleEvent(store: ConversationStore, event: string, raw: string
// The runtime's reply to a stop is its "⏹ Task stopped" note: end the turn as stopped.
if (isStopNote(text) || (store.getState().stopping && !text.trim())) { finishStopped(store); void refreshThreads(); break; }
const live = store.getState().live;
- const trace = live && (live.reasoning || live.steps.length) ? { ...live, endedAt: Date.now(), steps: live.steps.map((st) => st.status === "running" ? { ...st, status: "done" as const, endedAt: Date.now() } : st) } : undefined;
+ const trace = hasProcess(live) ? finishTrace(live) : undefined;
+ lastReplyAt.set(store, Date.now());
conv.clearStreaming();
conv.clearLive();
const artifacts = pendingArtifacts.get(store);
@@ -413,7 +442,7 @@ export async function openThread(surface: Surface, id: string | null): Promise<v
.catch(() => { /* older Mercury: no plans */ });
try {
const thread = await api.chat.thread(id);
- store.getState().setMessages(thread.messages ?? []);
+ store.getState().setMessages(normalizeMessages(thread.messages ?? []));
} catch {
store.getState().setMessages([]);
} finally {
@@ -432,7 +461,13 @@ export async function sendMessage(surface: Surface, content: string, attachments
if (!id) {
const thread = await api.chat.createThread(surface === "code" ? `Code · ${content.slice(0, 40)}` : undefined);
id = thread.id;
+ // An effort picked before the chat existed belongs to it.
+ const pendingEffort = store.getState().pendingEffort;
store.getState().setActive(id);
+ if (pendingEffort) {
+ store.getState().setPendingEffort(undefined);
+ await api.chat.setEffort(id, pendingEffort).catch(() => undefined);
+ }
store.getState().setMessages([]);
if (surface === "code") useCodeSessions.getState().upsert({ id, folder: code?.folder ?? null, createdAt: new Date().toISOString() });
}
@@ -448,7 +483,7 @@ export async function sendMessage(surface: Surface, content: string, attachments
};
store.getState().addMessage(optimistic);
store.getState().setAgent("thinking");
- store.getState().setLive(() => ({ reasoning: "", steps: [], startedAt: Date.now() }));
+ store.getState().setLive(() => newTrace());
await api.chat.send(content, id, attachments.map(({ name, data }) => ({ name, data })), code ? { programming: code.mode, cwd: code.folder ?? undefined } : undefined);
void refreshThreads();
}
@@ -468,7 +503,7 @@ export async function stopTurn(store: ConversationStore): Promise<void> {
const s = store.getState();
if (s.stopping) return;
s.setStopping(true);
- if (s.live) s.setLive((l) => ({ ...l, steps: l.steps.map((st) => (st.status === "running" ? { ...st, status: "stopped" as const, endedAt: Date.now() } : st)) }));
+ if (s.live) s.setLive((l) => markStopped(l));
try {
await api.chat.stop(s.activeId);
} catch (err) {
@@ -530,9 +565,7 @@ function finishStopped(store: ConversationStore): void {
s.setStopping(false);
// Nothing was running any more (the answer finished first): nothing to mark.
if (!busy && !partial && !live) return;
- const trace = live && (live.reasoning || live.steps.length)
- ? { ...live, stopped: true, endedAt: now, steps: live.steps.map((st) => (st.status === "running" ? { ...st, status: "stopped" as const, endedAt: now } : st)) }
- : undefined;
+ const trace = hasProcess(live) ? finishTrace(live, { stopped: true }, now) : undefined;
s.addMessage({ id: crypto.randomUUID(), role: "assistant", content: partial, stopped: true, timestamp: new Date().toISOString(), ...(trace ? { trace } : {}) });
s.setAgent(s.prompts.length ? "needs-you" : "idle");
}
diff --git a/apps/desktop/src/app/trace.test.ts b/apps/desktop/src/app/trace.test.ts
new file mode 100644
index 00000000..5b38b90a
--- /dev/null
+++ b/apps/desktop/src/app/trace.test.ts
@@ -0,0 +1,125 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+/**
+ * A running turn reads top to bottom in the order it happened, and the
+ * status never blinks back to "Thinking" while tools run or text streams.
+ */
+vi.mock("~/api/mercury", () => ({ chat: {} }));
+
+const { conversations } = await import("./conversation");
+const { handleEvent } = await import("./events");
+const { formatDuration, fromStored, normalizeMessages } = await import("./trace");
+const { blocksOf } = await import("~/components/TurnTimeline");
+const { traceSummary } = await import("~/components/ThoughtProcess");
+const store = conversations.chat;
+const ev = (type: string, data: Record<string, unknown> = {}) => handleEvent(store, type, JSON.stringify(data));
+
+describe("a running turn as a timeline", () => {
+ beforeEach(() => store.setState({ activeId: "a", waiting: null, agent: "thinking", messages: [], streaming: "", live: null, stopping: false, notice: null, prompts: [] }));
+
+ it("keeps thinking, tools, text and notes in order, pairing tools by call id", () => {
+ ev("reasoning", { text: "Plan the change." });
+ ev("step_start", { id: "c1", tool: "read_file", title: "Reading a.ts", label: "read_file(path=a.ts)", step: 1 });
+ ev("step_start", { id: "c2", tool: "read_file", title: "Reading b.ts", label: "read_file(path=b.ts)", step: 2 });
+ // Out of order: the second finishes first. Ids pair them, not tool names.
+ ev("step_done", { id: "c2", tool: "read_file", summary: "12 lines", failed: false, durationMs: 40 });
+ ev("step_done", { id: "c1", tool: "read_file", summary: "HTTP 403", failed: true, reason: "Forbidden", durationMs: 900 });
+ ev("text_delta", { text: "Here is " });
+ ev("progress", { text: "Checking my work…" });
+ ev("text_delta", { text: "the fix." });
+
+ const live = store.getState().live!;
+ expect(blocksOf(live).map((b) => b.kind)).toEqual(["reasoning", "steps", "text", "note", "text"]);
+ const [a, b] = live.steps;
+ expect(a).toMatchObject({ key: "c1", status: "error", summary: "Forbidden", durationMs: 900 });
+ expect(b).toMatchObject({ key: "c2", status: "done", durationMs: 40 });
+ });
+
+ it("a progress note never ends the turn", () => {
+ ev("progress", { text: "Alright — getting started…" });
+ expect(store.getState().messages).toHaveLength(0);
+ expect(store.getState().agent).toBe("thinking");
+ });
+
+ it("the periodic thinking signal doesn't flip Working or Answering back to Thinking", () => {
+ ev("step_start", { id: "c1", tool: "run_command", title: "Running npm test" });
+ expect(store.getState().agent).toBe("working");
+ ev("thinking");
+ expect(store.getState().agent).toBe("working");
+ ev("text_delta", { text: "ok" });
+ ev("thinking");
+ expect(store.getState().agent).toBe("streaming");
+ });
+
+ it("a late thinking signal right after the reply doesn't start a phantom turn", () => {
+ ev("text_delta", { text: "Done." });
+ ev("text_done", { fullText: "Done." });
+ ev("thinking");
+ expect(store.getState().agent).toBe("idle");
+ expect(store.getState().live).toBeNull();
+ });
+
+ it("the finished reply keeps the process without the streamed text", () => {
+ ev("reasoning", { text: "Hmm." });
+ ev("step_start", { id: "c1", tool: "web_search", title: "Searching x" });
+ ev("step_done", { id: "c1", tool: "web_search", summary: "5 results", failed: false, durationMs: 1200 });
+ ev("text_delta", { text: "Answer" });
+ ev("text_done", { fullText: "Answer" });
+ const msg = store.getState().messages.at(-1)!;
+ expect(msg.content).toBe("Answer");
+ expect(msg.trace?.items?.map((i) => i.kind)).toEqual(["reasoning", "step"]);
+ expect(traceSummary(msg.trace!)).toMatch(/^Worked for .* · 1 step$/);
+ });
+
+ it("older runtimes (no call id): the latest running step of that tool finishes", () => {
+ ev("step_start", { tool: "read_file", label: "read_file" });
+ ev("step_done", { tool: "read_file", summary: "ok" });
+ expect(store.getState().live?.steps[0].status).toBe("done");
+ });
+
+ it("phases show what happens between tools", () => {
+ ev("phase", { phase: "Calling anthropic", detail: "claude-opus-5-5" });
+ expect(store.getState().live?.phase).toBe("Calling anthropic · claude-opus-5-5");
+ });
+});
+
+describe("history", () => {
+ const stored = {
+ startedAt: 1000, endedAt: 9000,
+ items: [
+ { kind: "reasoning", text: "Think.", startedAt: 1000, endedAt: 2000 },
+ { kind: "tool", id: "c1", title: "Running npm test", status: "done", startedAt: 2000, durationMs: 5000, summary: "passed" },
+ ],
+ };
+
+ it("a stored trace becomes the screen's shape", () => {
+ const t = fromStored(stored)!;
+ expect(t.reasoning).toBe("Think.");
+ expect(t.steps[0]).toMatchObject({ key: "c1", title: "Running npm test", status: "done", durationMs: 5000 });
+ expect(t.items?.map((i) => i.kind)).toEqual(["reasoning", "step"]);
+ });
+
+ it("drops the separate tools row where the reply carries its own trace", () => {
+ const msgs = normalizeMessages([
+ { id: "u", role: "user", content: "go", timestamp: "" },
+ { id: "t", role: "assistant", kind: "tool-call", content: "[Tool activity]\n- run_command → ok", timestamp: "" },
+ { id: "r", role: "assistant", content: "Done", timestamp: "", trace: stored } as never,
+ ]);
+ expect(msgs.map((m) => m.id)).toEqual(["u", "r"]);
+ expect(msgs[1].trace?.steps).toHaveLength(1);
+ });
+
+ it("keeps the tools row for replies saved before traces were kept", () => {
+ const msgs = normalizeMessages([
+ { id: "t", role: "assistant", kind: "tool-call", content: "[Tool activity]\n- x → ok", timestamp: "" },
+ { id: "r", role: "assistant", content: "Done", timestamp: "" },
+ ]);
+ expect(msgs).toHaveLength(2);
+ });
+});
+
+it("durations read plainly", () => {
+ expect(formatDuration(400)).toBe("0.4s");
+ expect(formatDuration(12_000)).toBe("12s");
+ expect(formatDuration(65_000)).toBe("1m 05s");
+});
diff --git a/apps/desktop/src/app/trace.ts b/apps/desktop/src/app/trace.ts
new file mode 100644
index 00000000..17f6f678
--- /dev/null
+++ b/apps/desktop/src/app/trace.ts
@@ -0,0 +1,223 @@
+/* ═══════════════════════════════════════════════════════════════
+ A turn's thought process as a timeline, in the order it happened:
+ thinking, tool calls, the answer as it streams, notes ("Checking my
+ work…"). Pure functions over ThoughtTrace so the event handler, the
+ stop button and the history loader all build the same shape.
+
+ `items` is the order; `steps` holds each tool call's state (an item
+ points at its step by key); `reasoning` is all the thinking joined, for
+ older readers.
+ ═══════════════════════════════════════════════════════════════ */
+
+import type { ChatMessage, ThoughtStep, ThoughtTrace, TraceItem } from "~/api/types";
+
+const MAX_REASONING = 24_000;
+const MAX_ITEMS = 300;
+
+export function newTrace(now = Date.now()): ThoughtTrace {
+ return { reasoning: "", steps: [], items: [], startedAt: now, lastEventAt: now };
+}
+
+function itemsOf(t: ThoughtTrace): TraceItem[] {
+ return t.items ?? [];
+}
+
+function cap(items: TraceItem[]): TraceItem[] {
+ return items.length > MAX_ITEMS ? items.slice(items.length - MAX_ITEMS) : items;
+}
+
+/** The tool step running right now (the latest one), if any. */
+export function runningStep(t: ThoughtTrace): ThoughtStep | undefined {
+ for (let i = t.steps.length - 1; i >= 0; i--) if (t.steps[i].status === "running") return t.steps[i];
+ return undefined;
+}
+
+export function addReasoning(t: ThoughtTrace, text: string, now = Date.now()): ThoughtTrace {
+ if (!text) return t;
+ const items = [...itemsOf(t)];
+ const last = items[items.length - 1];
+ if (last?.kind === "reasoning" && !last.endedAt) items[items.length - 1] = { ...last, text: last.text + text };
+ else items.push({ kind: "reasoning", text, startedAt: now });
+ return { ...t, items: cap(items), reasoning: (t.reasoning + text).slice(-MAX_REASONING), lastEventAt: now, phase: undefined };
+}
+
+/** The current thinking block ended (the answer, a tool call or a new step began). */
+export function endReasoning(t: ThoughtTrace, now = Date.now()): ThoughtTrace {
+ const items = itemsOf(t);
+ const last = items[items.length - 1];
+ if (last?.kind !== "reasoning" || last.endedAt) return { ...t, lastEventAt: now };
+ return { ...t, items: [...items.slice(0, -1), { ...last, endedAt: now }], reasoning: t.reasoning ? `${t.reasoning}\n\n` : t.reasoning, lastEventAt: now };
+}
+
+export function startTool(t: ThoughtTrace, ev: { key?: string; tool: string; title?: string; label?: string; step?: number }, now = Date.now()): ThoughtTrace {
+ const closed = endReasoning(t, now);
+ const key = ev.key || `${ev.tool}:${now}:${closed.steps.length}`;
+ if (closed.steps.some((s) => s.key === key)) return closed;
+ const step: ThoughtStep = {
+ id: ev.step ?? closed.steps.length + 1,
+ key,
+ tool: ev.tool,
+ label: ev.label || ev.tool,
+ ...(ev.title ? { title: ev.title } : {}),
+ status: "running",
+ startedAt: now,
+ };
+ return {
+ ...closed,
+ steps: [...closed.steps, step].slice(-MAX_ITEMS),
+ items: cap([...itemsOf(closed), { kind: "step", key }]),
+ lastEventAt: now,
+ phase: undefined,
+ };
+}
+
+export function finishTool(
+ t: ThoughtTrace,
+ ev: { key?: string; tool: string; failed: boolean; summary?: string; durationMs?: number },
+ now = Date.now(),
+): ThoughtTrace {
+ const steps = [...t.steps];
+ let i = -1;
+ if (ev.key) i = steps.findIndex((s) => s.key === ev.key);
+ // Older runtimes: no call id, match the latest running step of that tool.
+ if (i < 0) for (let j = steps.length - 1; j >= 0; j--) if (steps[j].status === "running" && steps[j].tool === ev.tool) { i = j; break; }
+ if (i < 0) return { ...t, lastEventAt: now };
+ const s = steps[i];
+ const durationMs = typeof ev.durationMs === "number" ? ev.durationMs : now - s.startedAt;
+ steps[i] = { ...s, status: ev.failed ? "error" : "done", summary: ev.summary, endedAt: s.startedAt + durationMs, durationMs };
+ return { ...t, steps, lastEventAt: now };
+}
+
+/** Answer text as it streams, in order with the tools around it. */
+export function addText(t: ThoughtTrace, text: string, now = Date.now()): ThoughtTrace {
+ if (!text) return t;
+ const closed = endReasoning(t, now);
+ const items = [...itemsOf(closed)];
+ const last = items[items.length - 1];
+ if (last?.kind === "text") items[items.length - 1] = { ...last, text: last.text + text };
+ else items.push({ kind: "text", text });
+ return { ...closed, items: cap(items), lastEventAt: now, phase: undefined };
+}
+
+export function addNote(t: ThoughtTrace, text: string, now = Date.now()): ThoughtTrace {
+ if (!text.trim()) return t;
+ const closed = endReasoning(t, now);
+ return { ...closed, items: cap([...itemsOf(closed), { kind: "note", text, at: now }]), lastEventAt: now };
+}
+
+export function setPhase(t: ThoughtTrace, phase: string, now = Date.now()): ThoughtTrace {
+ return { ...t, phase, lastEventAt: now };
+}
+
+/** Any event from the runtime: the turn is alive. */
+export function touch(t: ThoughtTrace, now = Date.now()): ThoughtTrace {
+ return { ...t, lastEventAt: now };
+}
+
+/** Did the turn think or run anything worth keeping above the answer? */
+export function hasProcess(t: ThoughtTrace | null | undefined): t is ThoughtTrace {
+ return !!t && (!!t.reasoning.trim() || t.steps.length > 0 || itemsOf(t).some((i) => i.kind === "note"));
+}
+
+/**
+ * The trace kept on the finished reply: no streamed text (the reply has
+ * it), every step ended. `stopped`: running steps were cut off.
+ */
+export function finishTrace(t: ThoughtTrace, opts: { stopped?: boolean } = {}, now = Date.now()): ThoughtTrace {
+ const closed = endReasoning(t, now);
+ return {
+ reasoning: closed.reasoning.trim(),
+ startedAt: closed.startedAt,
+ endedAt: now,
+ ...(opts.stopped ? { stopped: true } : {}),
+ items: itemsOf(closed).filter((i) => i.kind !== "text"),
+ steps: closed.steps.map((s) => (s.status === "running"
+ ? { ...s, status: opts.stopped ? ("stopped" as const) : ("done" as const), endedAt: now, durationMs: now - s.startedAt }
+ : s)),
+ };
+}
+
+/** Stop pressed: what was running shows as stopped straight away. */
+export function markStopped(t: ThoughtTrace, now = Date.now()): ThoughtTrace {
+ return { ...t, steps: t.steps.map((s) => (s.status === "running" ? { ...s, status: "stopped" as const, endedAt: now, durationMs: now - s.startedAt } : s)) };
+}
+
+/* ── history ── */
+
+interface StoredItem {
+ kind?: unknown; text?: unknown; startedAt?: unknown; endedAt?: unknown;
+ id?: unknown; title?: unknown; status?: unknown; durationMs?: unknown; summary?: unknown;
+}
+
+const num = (v: unknown): number | undefined => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
+
+/**
+ * A reply's trace as the runtime keeps it ({startedAt, endedAt, items}) →
+ * the screen's shape. A trace already in that shape passes through.
+ */
+export function fromStored(raw: unknown): ThoughtTrace | undefined {
+ if (!raw || typeof raw !== "object") return undefined;
+ const r = raw as { startedAt?: unknown; endedAt?: unknown; items?: unknown; reasoning?: unknown; steps?: unknown };
+ if (typeof r.reasoning === "string" && Array.isArray(r.steps)) return raw as ThoughtTrace;
+ if (!Array.isArray(r.items)) return undefined;
+ const startedAt = num(r.startedAt) ?? Date.now();
+ const trace: ThoughtTrace = { reasoning: "", steps: [], items: [], startedAt, endedAt: num(r.endedAt) ?? startedAt };
+ const parts: string[] = [];
+ for (const it of r.items as StoredItem[]) {
+ if (it?.kind === "reasoning" && typeof it.text === "string" && it.text.trim()) {
+ trace.items!.push({ kind: "reasoning", text: it.text, startedAt: num(it.startedAt) ?? startedAt, endedAt: num(it.endedAt) ?? startedAt });
+ parts.push(it.text.trim());
+ } else if (it?.kind === "tool" && typeof it.id === "string") {
+ const title = typeof it.title === "string" ? it.title : "";
+ const at = num(it.startedAt) ?? startedAt;
+ const durationMs = num(it.durationMs);
+ trace.steps.push({
+ id: trace.steps.length + 1,
+ key: it.id,
+ tool: title.split(" ")[0] || "tool",
+ label: title,
+ title,
+ status: it.status === "error" ? "error" : "done",
+ startedAt: at,
+ ...(durationMs !== undefined ? { durationMs, endedAt: at + durationMs } : {}),
+ ...(typeof it.summary === "string" ? { summary: it.summary } : {}),
+ });
+ trace.items!.push({ kind: "step", key: it.id });
+ }
+ }
+ trace.reasoning = parts.join("\n\n");
+ return trace.items!.length ? trace : undefined;
+}
+
+/**
+ * Messages from the runtime → the screen: stored traces normalised, and the
+ * separate "used N tools" entry dropped where the reply carries the same
+ * calls in its own trace.
+ */
+export function normalizeMessages(messages: ChatMessage[]): ChatMessage[] {
+ const out: ChatMessage[] = [];
+ for (const m of messages) {
+ if (m.role !== "assistant" || !(m as { trace?: unknown }).trace) { out.push(m); continue; }
+ const trace = fromStored((m as { trace?: unknown }).trace);
+ const msg: ChatMessage = { ...m };
+ if (trace) msg.trace = trace;
+ else delete msg.trace;
+ if (trace?.steps.length) {
+ const prev = out[out.length - 1];
+ if (prev && (prev.kind === "tool-call" || prev.role === "tool")) out.pop();
+ }
+ out.push(msg);
+ }
+ return out;
+}
+
+/** "0.4s", "12s", "1m 05s". */
+export function formatDuration(ms: number): string {
+ if (ms < 1000) return `${Math.max(0.1, ms / 1000).toFixed(1)}s`;
+ const s = Math.round(ms / 1000);
+ if (s < 60) return `${s}s`;
+ const m = Math.floor(s / 60);
+ const rest = s % 60;
+ if (m < 60) return `${m}m ${String(rest).padStart(2, "0")}s`;
+ return `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, "0")}m`;
+}
diff --git a/apps/desktop/src/components/ThoughtProcess.tsx b/apps/desktop/src/components/ThoughtProcess.tsx
index 451e1480..74450d61 100644
--- a/apps/desktop/src/components/ThoughtProcess.tsx
+++ b/apps/desktop/src/components/ThoughtProcess.tsx
@@ -1,64 +1,38 @@
-import { Brain, Check, ChevronRight, CircleAlert, Square } from "lucide-react";
-import { useEffect, useRef, useState } from "react";
+import { Brain, ChevronRight, Square } from "lucide-react";
+import { useState } from "react";
import type { ThoughtTrace } from "~/api/types";
-import { Spinner } from "~/components/ui/bits";
+import { formatDuration } from "~/app/trace";
+import { TraceTimeline } from "~/components/TurnTimeline";
import { cx } from "~/lib/cx";
-/**
- * How an answer was reached. Live: open, with the reasoning streaming in a
- * short scrolling window and each step appearing as it runs. Done: folded
- * into one line ("Thought for 12s · 4 steps") above the answer, open on click.
- */
-export function ThoughtProcess({ trace, live = false, stopping = false }: { trace: ThoughtTrace; live?: boolean; stopping?: boolean }) {
- const [open, setOpen] = useState(live);
- const box = useRef<HTMLDivElement>(null);
- useEffect(() => { if (live) setOpen(true); }, [live]);
- useEffect(() => {
- const el = box.current;
- if (el && live) el.scrollTop = el.scrollHeight;
- }, [trace.reasoning, live]);
-
- const seconds = Math.max(1, Math.round(((trace.endedAt ?? Date.now()) - trace.startedAt) / 1000));
- const running = trace.steps.find((s) => s.status === "running");
+/** "Thought for 12s", "Worked for 1m 05s · 6 steps · 1 failed", "Stopped after 9s · 2 steps". */
+export function traceSummary(trace: ThoughtTrace): string {
+ const took = formatDuration(Math.max(0, (trace.endedAt ?? trace.startedAt) - trace.startedAt));
+ const n = trace.steps.length;
const failed = trace.steps.filter((s) => s.status === "error").length;
- const steps = trace.steps.length ? ` · ${trace.steps.length} step${trace.steps.length === 1 ? "" : "s"}` : "";
- const summary = live
- ? stopping ? "Stopping" : running ? `Running ${running.tool}` : trace.reasoning ? "Thinking" : "Starting"
- : trace.stopped ? `Stopped after ${seconds}s${steps}` : `Thought for ${seconds}s${trace.steps.length ? ` · ${trace.steps.length} step${trace.steps.length === 1 ? "" : "s"}` : ""}${failed ? ` · ${failed} failed` : ""}`;
-
- if (!live && !trace.reasoning && trace.steps.length === 0) return null;
+ const steps = n ? ` · ${n} step${n === 1 ? "" : "s"}` : "";
+ if (trace.stopped) return `Stopped after ${took}${steps}`;
+ return `${n ? "Worked" : "Thought"} for ${took}${steps}${failed ? ` · ${failed} failed` : ""}`;
+}
+/**
+ * How a finished answer was reached, folded into one line above it; open
+ * on click for the thinking and every step, in the order they happened.
+ * (The running turn shows the same timeline open, in StreamingMessage.)
+ */
+export function ThoughtProcess({ trace }: { trace: ThoughtTrace }) {
+ const [open, setOpen] = useState(false);
+ if (!trace.reasoning.trim() && trace.steps.length === 0 && !(trace.items ?? []).some((i) => i.kind === "note")) return null;
return (
<div className="mb-3">
<button onClick={() => setOpen((o) => !o)} className="flex items-center gap-2 rounded-md py-1 text-sm text-ink3 hover:text-ink" aria-expanded={open}>
- {live ? <Spinner size={13} className="text-cyan" /> : trace.stopped ? <Square size={11} className="fill-current" aria-hidden="true" /> : <Brain size={14} aria-hidden="true" />}
- <span className={cx(live && "text-cyan")}>{summary}{live && "…"}</span>
+ {trace.stopped ? <Square size={11} className="fill-current" aria-hidden="true" /> : <Brain size={14} aria-hidden="true" />}
+ <span>{traceSummary(trace)}</span>
<ChevronRight size={14} className={cx("transition-transform", open && "rotate-90")} aria-hidden="true" />
</button>
{open && (
<div className="ml-[7px] mt-1 border-l border-line pl-4">
- {trace.reasoning && (
- <div ref={box} className={cx("whitespace-pre-wrap text-[13.5px] leading-relaxed text-ink3", live ? "thought-stream max-h-[7.5em] overflow-hidden" : "max-h-[18em] overflow-y-auto")} data-selectable>
- {trace.reasoning.trim()}
- </div>
- )}
- {trace.steps.length > 0 && (
- <ol className={cx("flex flex-col gap-1.5", trace.reasoning && "mt-3")}>
- {trace.steps.map((s) => (
- <li key={`${s.id}-${s.startedAt}`} className="flex items-start gap-2 text-[13px]">
- <span className="mt-[3px] flex h-4 w-4 shrink-0 items-center justify-center">
- {s.status === "running" ? <Spinner size={11} className="text-accent" /> : s.status === "stopped" ? <Square size={10} className="fill-current text-ink4" aria-label="stopped" /> : s.status === "error" ? <CircleAlert size={13} className="text-red" /> : <Check size={13} className="text-accent" strokeWidth={2.5} />}
- </span>
- <span className="min-w-0 flex-1">
- <span className="break-all font-mono text-ink2">{s.label}</span>
- {s.status === "stopped" && <span className="mt-0.5 block text-xs text-ink4">Stopped before it finished</span>}
- {s.summary && s.status !== "running" && <span className="mt-0.5 line-clamp-2 block text-xs text-ink4">{s.summary}</span>}
- </span>
- {s.endedAt && <span className="shrink-0 font-mono text-2xs text-ink4">{((s.endedAt - s.startedAt) / 1000).toFixed(1)}s</span>}
- </li>
- ))}
- </ol>
- )}
+ <TraceTimeline trace={trace} expanded now={trace.endedAt ?? Date.now()} />
</div>
)}
</div>
diff --git a/apps/desktop/src/components/TurnTimeline.tsx b/apps/desktop/src/components/TurnTimeline.tsx
new file mode 100644
index 00000000..b4b85e09
--- /dev/null
+++ b/apps/desktop/src/components/TurnTimeline.tsx
@@ -0,0 +1,228 @@
+import { AlertTriangle, Brain, Check, ChevronRight, CircleAlert, CornerDownRight, Square } from "lucide-react";
+import { useEffect, useRef, useState } from "react";
+import type { ThoughtStep, ThoughtTrace, TraceItem } from "~/api/types";
+import type { AgentState } from "~/app/store";
+import { formatDuration, runningStep } from "~/app/trace";
+import { Markdown } from "~/components/Markdown";
+import { StreamCaret } from "~/components/indicators/Thinking";
+import { Spinner } from "~/components/ui/bits";
+import { cx } from "~/lib/cx";
+
+/* ═══════════════════════════════════════════════════════════════
+ A turn as it happened, top to bottom: thinking, the tools it ran, the
+ answer, notes — newest at the bottom, where the reader already is.
+ Live, the open thinking block streams and the running tool ticks; a
+ status line under it all always says what is happening and for how
+ long, so a quiet model reads as waiting, never as a frozen screen.
+ ═══════════════════════════════════════════════════════════════ */
+
+/** The current time, re-rendered every `ms` while `active`. */
+export function useNow(active: boolean, ms = 1000): number {
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ if (!active) return;
+ setNow(Date.now());
+ const id = setInterval(() => setNow(Date.now()), ms);
+ return () => clearInterval(id);
+ }, [active, ms]);
+ return active ? now : Date.now();
+}
+
+type Block =
+ | { kind: "reasoning"; item: Extract<TraceItem, { kind: "reasoning" }>; index: number }
+ | { kind: "steps"; steps: ThoughtStep[]; index: number }
+ | { kind: "text"; text: string; index: number }
+ | { kind: "note"; text: string; index: number };
+
+/** Items → blocks: consecutive tool calls form one group. Older traces (no items): thinking, then steps. */
+export function blocksOf(trace: ThoughtTrace): Block[] {
+ const items: TraceItem[] = trace.items ?? [
+ ...(trace.reasoning.trim() ? [{ kind: "reasoning" as const, text: trace.reasoning, startedAt: trace.startedAt, endedAt: trace.endedAt ?? trace.startedAt }] : []),
+ ...trace.steps.map((s, i) => ({ kind: "step" as const, key: s.key ?? `legacy-${i}` })),
+ ];
+ const byKey = new Map(trace.steps.map((s, i) => [s.key ?? `legacy-${i}`, s]));
+ const blocks: Block[] = [];
+ items.forEach((item, index) => {
+ if (item.kind === "step") {
+ const step = byKey.get(item.key);
+ if (!step) return;
+ const last = blocks[blocks.length - 1];
+ if (last?.kind === "steps") last.steps.push(step);
+ else blocks.push({ kind: "steps", steps: [step], index });
+ } else if (item.kind === "reasoning") {
+ if (item.text.trim()) blocks.push({ kind: "reasoning", item, index });
+ } else if (item.kind === "text") {
+ if (item.text) blocks.push({ kind: "text", text: item.text, index });
+ } else {
+ blocks.push({ kind: "note", text: item.text, index });
+ }
+ });
+ return blocks;
+}
+
+/** `expanded`: a finished turn opened on purpose — its thinking shows open too. */
+export function TraceTimeline({ trace, live = false, expanded = false, now }: { trace: ThoughtTrace; live?: boolean; expanded?: boolean; now: number }) {
+ const blocks = blocksOf(trace);
+ return (
+ <div className="flex flex-col gap-2.5">
+ {blocks.map((b, i) => {
+ const last = live && i === blocks.length - 1;
+ switch (b.kind) {
+ case "reasoning":
+ return <ReasoningBlock key={`r${b.index}`} text={b.item.text} startedAt={b.item.startedAt} endedAt={b.item.endedAt} active={last && !b.item.endedAt} expanded={expanded} now={now} />;
+ case "steps":
+ return <StepGroup key={`s${b.index}`} steps={b.steps} live={live} now={now} />;
+ case "text":
+ return (
+ <div key={`t${b.index}`} className="min-w-0">
+ <Markdown text={b.text} streaming={last} />
+ {last && <StreamCaret />}
+ </div>
+ );
+ case "note":
+ return (
+ <p key={`n${b.index}`} className="flex items-start gap-2 text-[13px] text-ink3">
+ <CornerDownRight size={13} className="mt-[3px] shrink-0 text-ink4" aria-hidden="true" />
+ <span className="min-w-0">{b.text.replace(/^[^\p{L}\p{N}*_`]+/u, "")}</span>
+ </p>
+ );
+ }
+ })}
+ </div>
+ );
+}
+
+/** One thinking block: open while it streams, folded to "Thought for 8s" once the model moves on. */
+function ReasoningBlock({ text, startedAt, endedAt, active, expanded, now }: { text: string; startedAt: number; endedAt?: number; active: boolean; expanded: boolean; now: number }) {
+ // Your click wins; otherwise open while it streams (and in an opened finished turn).
+ const [userOpen, setUserOpen] = useState<boolean | null>(null);
+ const open = userOpen ?? (active || expanded);
+ const box = useRef<HTMLDivElement>(null);
+ useEffect(() => {
+ const el = box.current;
+ if (el && active) el.scrollTop = el.scrollHeight;
+ }, [text, active]);
+ const took = formatDuration(Math.max(0, (endedAt ?? now) - startedAt));
+ return (
+ <div className="min-w-0">
+ <button onClick={() => setUserOpen(!open)} className="group/r flex items-center gap-2 rounded-md py-0.5 text-sm text-ink3 hover:text-ink" aria-expanded={open}>
+ <Brain size={14} className={cx(active && "text-cyan")} aria-hidden="true" />
+ <span className={cx(active && "shimmer-text")}>{active ? `Thinking · ${took}` : `Thought for ${took}`}</span>
+ <ChevronRight size={14} className={cx("transition-transform", open && "rotate-90")} aria-hidden="true" />
+ </button>
+ {open && (
+ <div
+ ref={box}
+ className={cx(
+ "ml-[7px] mt-1 whitespace-pre-wrap border-l border-line pl-4 text-[13.5px] leading-relaxed text-ink3",
+ active ? "thought-stream max-h-[7.5em] overflow-hidden" : "max-h-[18em] overflow-y-auto",
+ )}
+ data-selectable
+ >
+ {text.trim()}
+ </div>
+ )}
+ </div>
+ );
+}
+
+const SHOW_STEPS = 4;
+
+/** A run of tool calls. Long runs show the latest few; failures always show. */
+function StepGroup({ steps, live, now }: { steps: ThoughtStep[]; live: boolean; now: number }) {
+ const [all, setAll] = useState(false);
+ const hidden = all ? [] : steps.slice(0, Math.max(0, steps.length - SHOW_STEPS)).filter((s) => s.status !== "error" && s.status !== "running");
+ const hiddenKeys = new Set(hidden);
+ const shown = steps.filter((s) => !hiddenKeys.has(s));
+ return (
+ <ol className="flex flex-col gap-1">
+ {hidden.length > 0 && (
+ <li>
+ <button onClick={() => setAll(true)} className="flex items-center gap-2 py-0.5 text-[13px] text-ink4 hover:text-ink2">
+ <ChevronRight size={13} aria-hidden="true" />
+ {hidden.length} earlier step{hidden.length === 1 ? "" : "s"}
+ </button>
+ </li>
+ )}
+ {shown.map((s) => <StepRow key={s.key ?? `${s.id}-${s.startedAt}`} step={s} live={live} now={now} />)}
+ </ol>
+ );
+}
+
+function StepRow({ step: s, live, now }: { step: ThoughtStep; live: boolean; now: number }) {
+ const [open, setOpen] = useState(false);
+ const running = s.status === "running";
+ const ms = s.durationMs ?? (s.endedAt ? s.endedAt - s.startedAt : running && live ? now - s.startedAt : undefined);
+ const title = s.title || s.label;
+ const failed = s.status === "error";
+ const detail = s.summary && !running ? s.summary : "";
+ return (
+ <li className="min-w-0">
+ <button
+ onClick={() => detail && setOpen((o) => !o)}
+ className={cx("flex w-full min-w-0 items-start gap-2 rounded-md text-left text-[13px]", detail && "hover:text-ink")}
+ aria-expanded={detail ? open : undefined}
+ >
+ <span className="mt-[3px] flex h-4 w-4 shrink-0 items-center justify-center">
+ {running ? <Spinner size={11} className="text-accent" />
+ : s.status === "stopped" ? <Square size={10} className="fill-current text-ink4" aria-label="stopped" />
+ : failed ? <CircleAlert size={13} className="text-red" aria-label="failed" />
+ : <Check size={13} className="text-accent" strokeWidth={2.5} aria-label="done" />}
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className={cx("block truncate", running ? "text-ink" : "text-ink2", !s.title && "font-mono")} title={s.label}>{title}</span>
+ {s.status === "stopped" && <span className="mt-0.5 block text-xs text-ink4">Stopped before it finished</span>}
+ {detail && (failed || open) && (
+ <span className={cx("mt-0.5 block break-words text-xs", failed ? "text-red/90" : "text-ink4", !open && "line-clamp-2")}>{detail}</span>
+ )}
+ </span>
+ {ms !== undefined && <span className={cx("shrink-0 pt-px font-mono text-2xs", running ? "text-ink3" : "text-ink4")}>{formatDuration(ms)}</span>}
+ </button>
+ </li>
+ );
+}
+
+/** How long without a word from the runtime before the status line says so. */
+const QUIET_MS = 20_000;
+const LONG_QUIET_MS = 120_000;
+
+/**
+ * The line under a running turn: what is happening right now and how long
+ * the turn has taken. Hidden while the answer is visibly streaming.
+ */
+export function LiveStatus({ trace, agent, stopping, now }: { trace: ThoughtTrace; agent: AgentState; stopping: boolean; now: number }) {
+ const items = trace.items ?? [];
+ const last = items[items.length - 1];
+ const quietFor = now - (trace.lastEventAt ?? trace.startedAt);
+ const writing = last?.kind === "text" && quietFor < 2500 && !stopping;
+ if (writing) return null;
+ const step = runningStep(trace);
+ const thinking = last?.kind === "reasoning" && !last.endedAt;
+ const what = stopping ? "Stopping"
+ : step ? (step.title || step.label)
+ : thinking ? "Thinking"
+ : trace.phase ? trace.phase
+ : agent === "needs-you" ? "Waiting for you"
+ : items.length === 0 ? "Starting"
+ : agent === "streaming" ? "Writing"
+ : "Working";
+ const total = formatDuration(Math.max(0, now - trace.startedAt));
+ const waitingOnModel = !step && !stopping && agent !== "needs-you" && quietFor >= QUIET_MS;
+ return (
+ <div className="flex flex-col gap-1" role="status" aria-live="polite">
+ <div className="flex items-center gap-2 text-[13px] text-ink3">
+ <Spinner size={12} className={stopping ? "text-ink4" : "text-cyan"} />
+ <span className="min-w-0 truncate shimmer-text">{what}…</span>
+ <span className="shrink-0 font-mono text-2xs text-ink4">{total}</span>
+ </div>
+ {waitingOnModel && (
+ <p className={cx("ml-5 flex items-start gap-1.5 text-xs", quietFor >= LONG_QUIET_MS ? "text-amber" : "text-ink4")}>
+ {quietFor >= LONG_QUIET_MS && <AlertTriangle size={12} className="mt-px shrink-0" aria-hidden="true" />}
+ {quietFor >= LONG_QUIET_MS
+ ? `No response from the model for ${formatDuration(quietFor)}. It may be overloaded — you can stop and try again.`
+ : `Waiting for the model · ${formatDuration(quietFor)}`}
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/styles/base.css b/apps/desktop/src/styles/base.css
index 0398df8f..07815375 100644
--- a/apps/desktop/src/styles/base.css
+++ b/apps/desktop/src/styles/base.css
@@ -119,4 +119,13 @@ button, input, textarea, a, [role="button"], [data-no-drag] { -webkit-app-region
.md-alert-caution { --alert: rgb(var(--red)); }
/* ── Live thought process ── */
+/* Text that is "in progress": a soft light passing over it. */
+.shimmer-text {
+ background: linear-gradient(90deg, rgb(var(--ink-3)) 0%, rgb(var(--ink-3)) 40%, rgb(var(--ink)) 50%, rgb(var(--ink-3)) 60%, rgb(var(--ink-3)) 100%);
+ background-size: 250% 100%;
+ -webkit-background-clip: text; background-clip: text; color: transparent;
+ animation: shimmer-text 2.4s linear infinite;
+}
+@keyframes shimmer-text { from { background-position: 100% 0; } to { background-position: -150% 0; } }
+@media (prefers-reduced-motion: reduce) { .shimmer-text { animation: none; color: rgb(var(--ink-3)); background: none; } }
.thought-stream { mask-image: linear-gradient(to bottom, transparent 0, #000 18px); -webkit-mask-image: linear-gradient(to bottom, transparent 0, #000 18px); }
diff --git a/apps/desktop/src/views/chat/Composer.tsx b/apps/desktop/src/views/chat/Composer.tsx
index f4842f08..aaf580c2 100644
--- a/apps/desktop/src/views/chat/Composer.tsx
+++ b/apps/desktop/src/views/chat/Composer.tsx
@@ -1,8 +1,8 @@
-import { ArrowUp, AudioLines, ChevronDown, Paperclip, Shield, ShieldCheck, Square, Telescope, X } from "lucide-react";
+import { ArrowUp, AudioLines, ChevronDown, Gauge, Paperclip, Shield, ShieldCheck, Square, Telescope, X } from "lucide-react";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { cx } from "~/lib/cx";
import * as api from "~/api/mercury";
-import type { ModelsResponse } from "~/api/types";
+import type { ChatEffort, ModelsResponse, ReasoningChoice, ReasoningLevel } from "~/api/types";
import { usePermissionMode } from "~/app/permission";
import { useBots, useRuntimeState } from "~/app/store";
import { CommandPicker } from "./CommandPicker";
@@ -371,11 +371,14 @@ function ModelPicker() {
const [models, setModels] = useState<ModelsResponse | null>(null);
const provider = useRuntimeState((s) => s.provider);
const model = useRuntimeState((s) => s.model);
+ const store = useConversationStore();
+ const threadId = useConversation((s) => s.activeId);
+ const pendingEffort = useConversation((s) => s.pendingEffort);
async function load() {
- try { setModels(await api.chat.models()); } catch { setModels(null); }
+ try { setModels(await api.chat.models(threadId)); } catch { setModels(null); }
}
- useEffect(() => { void load(); }, [provider, model]);
+ useEffect(() => { void load(); }, [provider, model, threadId]); // eslint-disable-line react-hooks/exhaustive-deps
const label = models?.current?.label || model || provider || "Model";
const groups = new Map<string, ModelsResponse["providers"]>();
@@ -385,7 +388,9 @@ function ModelPicker() {
groups.set(p.group, list);
}
+ const current = models?.current;
return (
+ <>
<Menu
side="top"
trigger={
@@ -408,6 +413,93 @@ function ModelPicker() {
))}
{groups.size === 0 && <MenuItem disabled>No providers configured</MenuItem>}
</Menu>
+ {current && current.reasoningLevels?.length > 0 && (
+ <EffortPicker
+ effort={withPending(current.effort ?? fallbackEffort(current.reasoning), pendingEffort)}
+ levels={current.reasoningLevels}
+ modelLabel={current.label}
+ onChat={(level) => {
+ // A new chat has no thread yet: the pick waits for the first message (sendMessage).
+ if (!threadId) { store.getState().setPendingEffort(level ?? undefined); return; }
+ void api.chat.setEffort(threadId, level).catch(() => undefined).then(load);
+ }}
+ onDefault={(level) => {
+ void api.chat.setReasoning(current.name, current.model, level === "auto" ? null : level).catch(() => undefined).then(load);
+ }}
+ />
+ )}
+ </>
+ );
+}
+
+const EFFORT_LABEL: Record<ReasoningChoice, string> = { auto: "Auto", off: "Off", low: "Low", medium: "Medium", high: "High", xhigh: "Extra high", max: "Max" };
+const EFFORT_HINT: Partial<Record<ReasoningChoice, string>> = {
+ auto: "the model decides",
+ off: "answer straight away",
+ low: "quick, light thinking",
+ high: "thinks it through",
+ xhigh: "for hard coding and agent work",
+ max: "slowest, most thorough",
+};
+
+/** Older runtimes report only the model's level. */
+function fallbackEffort(reasoning: ReasoningChoice | undefined): ChatEffort {
+ const r = reasoning ?? "auto";
+ return { effective: r, source: r === "auto" ? "auto" : "model", modelDefault: r, chat: null };
+}
+
+/** A pick made before the chat existed shows as this chat's. */
+function withPending(effort: ChatEffort, pending: ReasoningChoice | undefined): ChatEffort {
+ return pending ? { ...effort, chat: pending, effective: pending, source: "chat" } : effort;
+}
+
+/**
+ * How hard the model thinks in this chat (#188). Picks apply to this chat
+ * only; "Default" follows the model's own setting, which the last item
+ * changes for every chat without a pick of its own. Shown only for models
+ * that take an effort.
+ */
+function EffortPicker({ effort, levels, modelLabel, onChat, onDefault }: {
+ effort: ChatEffort;
+ levels: ReasoningLevel[];
+ modelLabel: string;
+ onChat: (level: ReasoningChoice | null) => void;
+ onDefault: (level: ReasoningChoice) => void;
+}) {
+ const choices: ReasoningChoice[] = ["auto", ...levels];
+ const own = effort.source === "chat" && effort.chat !== null;
+ const shown = effort.effective === "auto" ? "Effort" : EFFORT_LABEL[effort.effective];
+ return (
+ <Menu
+ side="top"
+ trigger={
+ <button
+ className={cx("flex h-8 items-center gap-1.5 rounded-md px-2 text-sm hover:bg-ink/[0.06]", effort.effective === "auto" ? "text-ink3" : "text-ink2")}
+ aria-label="Thinking effort"
+ title={`${EFFORT_LABEL[effort.effective]} · ${own ? "this chat" : effort.source === "model" ? `${modelLabel} default` : "the model decides"}`}
+ >
+ <Gauge size={14} />
+ {shown}
+ {own && <span className="h-1.5 w-1.5 rounded-full bg-accent" aria-label="set for this chat" />}
+ <ChevronDown size={12} className="text-ink4" />
+ </button>
+ }
+ >
+ <MenuLabel>Thinking effort · this chat</MenuLabel>
+ <MenuItem selected={!effort.chat} hint={EFFORT_LABEL[effort.modelDefault]} onSelect={() => onChat(null)}>Model default</MenuItem>
+ {choices.map((level) => (
+ <MenuItem key={level} selected={effort.chat === level} hint={EFFORT_HINT[level]} onSelect={() => onChat(level)}>
+ {EFFORT_LABEL[level]}
+ </MenuItem>
+ ))}
+ {effort.chatUnsupported && <MenuItem disabled>This model can't use the chat's pick; its default applies</MenuItem>}
+ {own && effort.chat && effort.chat !== effort.modelDefault && (
+ <>
+ <MenuSeparator />
+ <MenuItem onSelect={() => onDefault(effort.chat!)}>Make {EFFORT_LABEL[effort.chat]} the default for {modelLabel}</MenuItem>
+ </>
+ )}
+ </Menu>
);
}
diff --git a/apps/desktop/src/views/chat/Conversation.tsx b/apps/desktop/src/views/chat/Conversation.tsx
index ab703491..2cf4ad13 100644
--- a/apps/desktop/src/views/chat/Conversation.tsx
+++ b/apps/desktop/src/views/chat/Conversation.tsx
@@ -5,6 +5,7 @@ import { jumpLabel, useFollowBottom } from "./follow";
import { cx } from "~/lib/cx";
import { useConversation, useConversationStore } from "~/app/conversation";
import { answerPrompt } from "~/app/events";
+import { runningStep } from "~/app/trace";
import { StateLabel } from "~/components/indicators/StateOrb";
import { Approval } from "~/components/indicators/Approval";
import { ThinkingDots } from "~/components/indicators/Thinking";
@@ -41,6 +42,7 @@ export function Conversation({ header, empty, composer }: { header: ReactNode; e
const [visible, setVisible] = useState(PAGE);
const prepend = useRef<{ height: number; top: number } | null>(null);
const follow = useFollowBottom(scroller, content, activeId);
+ const liveStep = live ? runningStep(live) : undefined;
const busy = !!streaming || stopping || agent === "thinking" || agent === "working" || agent === "streaming";
// While the reader is up the page: count what arrived, and notice the reply ending.
@@ -80,7 +82,7 @@ export function Conversation({ header, empty, composer }: { header: ReactNode; e
<section className="flex min-w-0 flex-1 flex-col">
<header className="flex h-[52px] shrink-0 items-center gap-2 border-b border-line px-4" data-tauri-drag-region>
<div className="flex min-w-0 flex-1 items-center gap-3">{header}</div>
- <StateLabel state={agent} detail={step?.tool ? `${step.tool}${step.total ? ` ${step.current}/${step.total}` : ""}` : undefined} />
+ <StateLabel state={agent} detail={liveStep ? (liveStep.title || liveStep.tool) : step?.tool || undefined} />
</header>
<div className="relative flex min-h-0 flex-1 flex-col">
@@ -107,7 +109,7 @@ export function Conversation({ header, empty, composer }: { header: ReactNode; e
)}
{shown.map((m) => <Message key={m.id} message={m} undoable={m.id === lastYours} />)}
{(streaming || (live && (agent === "thinking" || agent === "working" || agent === "streaming" || agent === "needs-you"))) && (
- <StreamingMessage text={streaming} live={live} stopping={stopping} />
+ <StreamingMessage text={streaming} live={live} agent={agent} stopping={stopping} />
)}
{waiting && !streaming ? (
<WaitingNotice threadId={activeId} waiting={waiting} />
diff --git a/apps/desktop/src/views/chat/Message.tsx b/apps/desktop/src/views/chat/Message.tsx
index 9e0e0061..cd9dd3e6 100644
--- a/apps/desktop/src/views/chat/Message.tsx
+++ b/apps/desktop/src/views/chat/Message.tsx
@@ -10,6 +10,8 @@ import { StreamCaret } from "~/components/indicators/Thinking";
import { ActionResult } from "~/components/indicators/Activity";
import { Attachments } from "~/components/Attachments";
import { ThoughtProcess } from "~/components/ThoughtProcess";
+import { LiveStatus, TraceTimeline, useNow } from "~/components/TurnTimeline";
+import type { AgentState } from "~/app/store";
import { cx } from "~/lib/cx";
import { isStopNote } from "~/app/events";
import { UserAvatar, useDisplayName } from "~/components/UserAvatar";
@@ -206,16 +208,24 @@ function ToolActivity({ content }: { content: string }) {
);
}
-/** The answer being written, with its thought process above it (open while it runs). */
-export function StreamingMessage({ text, live, stopping = false }: { text: string; live: ThoughtTrace | null; stopping?: boolean }) {
+/**
+ * The turn being worked on, as a timeline in the order things happen
+ * (thinking, tools, the answer as it streams, notes), with a status line
+ * at the bottom: what is running now and for how long.
+ */
+export function StreamingMessage({ text, live, agent, stopping = false }: { text: string; live: ThoughtTrace | null; agent: AgentState; stopping?: boolean }) {
+ const now = useNow(true);
+ const trace = live ?? null;
+ // Older runtimes may stream text without a trace of it: show it as written.
+ const textInTrace = !!trace?.items?.some((i) => i.kind === "text");
return (
<div className="flex gap-4">
<span className="mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center" aria-hidden="true"><Mark size={22} /></span>
- <div className="min-w-0 flex-1">
+ <div className="flex min-w-0 flex-1 flex-col gap-2.5">
<Speaker who="mercury" />
- {live && <ThoughtProcess trace={live} live={!text} stopping={stopping} />}
- {stopping && text && <div className="mb-2 text-sm text-ink3">Stopping…</div>}
- {text && <><Markdown text={text} streaming /><StreamCaret /></>}
+ {trace && <TraceTimeline trace={trace} live now={now} />}
+ {text && !textInTrace && <div className="min-w-0"><Markdown text={text} streaming /><StreamCaret /></div>}
+ {trace && <LiveStatus trace={trace} agent={agent} stopping={stopping} now={now} />}
</div>
</div>
);
diff --git a/apps/desktop/src/views/chat/follow.test.ts b/apps/desktop/src/views/chat/follow.test.ts
index 08b1c269..401800cc 100644
--- a/apps/desktop/src/views/chat/follow.test.ts
+++ b/apps/desktop/src/views/chat/follow.test.ts
@@ -3,7 +3,7 @@ import { jumpLabel } from "./follow";
describe("jumpLabel", () => {
it("says what happened below while you read further up", () => {
- expect(jumpLabel({ busy: true, unseen: 0, finished: false })).toBe("Mercury is writing");
+ expect(jumpLabel({ busy: true, unseen: 0, finished: false })).toBe("New activity");
expect(jumpLabel({ busy: false, unseen: 1, finished: true })).toBe("1 new message");
expect(jumpLabel({ busy: true, unseen: 3, finished: false })).toBe("3 new messages");
expect(jumpLabel({ busy: false, unseen: 0, finished: true })).toBe("Reply finished");
diff --git a/apps/desktop/src/views/chat/follow.ts b/apps/desktop/src/views/chat/follow.ts
index 19882bbb..326f4f74 100644
--- a/apps/desktop/src/views/chat/follow.ts
+++ b/apps/desktop/src/views/chat/follow.ts
@@ -111,7 +111,7 @@ export function useFollowBottom(scroller: RefObject<HTMLDivElement | null>, cont
/** What the jump pill says while the reader is up the page. */
export function jumpLabel({ busy, unseen, finished }: { busy: boolean; unseen: number; finished: boolean }): string {
if (unseen > 0) return `${unseen} new message${unseen === 1 ? "" : "s"}`;
- if (busy) return "Mercury is writing";
+ if (busy) return "New activity";
if (finished) return "Reply finished";
return "Jump to latest";
}
diff --git a/src/channels/web-live-steps.test.ts b/src/channels/web-live-steps.test.ts
new file mode 100644
index 00000000..429b9390
--- /dev/null
+++ b/src/channels/web-live-steps.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, it } from 'vitest';
+import { WebChannel } from './web.js';
+
+/**
+ * Tool events reach the desktop as each tool starts and ends (not both
+ * after the step), carrying the call id that pairs them and the runtime's
+ * own duration. Notes mid-turn are progress events, never a finished reply.
+ */
+function capture(ch: WebChannel): Array<{ type: string; data?: Record<string, unknown> }> {
+ const sent: Array<{ type: string; data?: Record<string, unknown> }> = [];
+ (ch as unknown as { broadcast: (e: { type: string; data?: Record<string, unknown> }) => boolean }).broadcast = (e) => { sent.push(e); return true; };
+ return sent;
+}
+
+describe('web channel live tool events', () => {
+ it('start and finish carry the call id, a readable title and the duration', () => {
+ const ch = new WebChannel('Mercury');
+ const sent = capture(ch);
+ ch.sendToolStarted('call_1', 'read_file', { path: 'src/a.ts' }, 's1');
+ ch.sendToolFinished('call_1', 'read_file', 'line 1\nline 2', false, 41.6, 's1');
+ expect(sent[0]).toMatchObject({ type: 'step_start', data: { id: 'call_1', step: 1, tool: 'read_file', targetId: 's1' } });
+ expect(sent[0].data?.title).toBe('Reading a.ts');
+ expect(String(sent[0].data?.title)).not.toMatch(/^[^\p{L}\p{N}]/u);
+ expect(sent[1]).toEqual({ type: 'step_done', data: { id: 'call_1', tool: 'read_file', summary: 'line 1\nline 2', failed: false, durationMs: 42, targetId: 's1' } });
+ });
+
+ it('a thrown tool error is a failure with a reason', () => {
+ const ch = new WebChannel('Mercury');
+ const sent = capture(ch);
+ ch.sendToolFinished('c', 'run_command', new Error('spawn ENOENT'), true, 5, 's1');
+ expect(sent[0].data).toMatchObject({ failed: true });
+ expect(String(sent[0].data?.reason)).toBeTruthy();
+ });
+
+ it('progress notes and phases are their own events', () => {
+ const ch = new WebChannel('Mercury');
+ const sent = capture(ch);
+ ch.sendProgressNote('Checking my work…', 's1');
+ ch.sendPhase('Calling anthropic', 'claude-opus-5-5', 's1');
+ ch.sendProviderInfo('anthropic', 'claude-opus-5-5', 's1');
+ expect(sent.map((e) => e.type)).toEqual(['progress', 'phase', 'provider']);
+ expect(sent.some((e) => e.type === 'text_done')).toBe(false);
+ expect(sent[2].data).toMatchObject({ name: 'anthropic', provider: 'anthropic' });
+ });
+});
diff --git a/src/channels/web.ts b/src/channels/web.ts
index f8da6106..8fad9169 100644
--- a/src/channels/web.ts
+++ b/src/channels/web.ts
@@ -5,9 +5,19 @@ import { logger } from '../utils/logger.js';
import { randomUUID } from 'node:crypto';
import { userFacingAiError } from '../utils/redact.js';
import { stepFailure, type ResearchSnapshot } from '../core/research-run.js';
+import { formatToolStep } from '../utils/tool-label.js';
type CloudEventHandler = (event: ChatEvent) => boolean;
+function safeJson(value: unknown): string {
+ try { return JSON.stringify(value) ?? ''; } catch { return String(value); }
+}
+
+/** "Read src/x.ts", "Run npm test": the tool's label without its icon. */
+function toolTitle(toolName: string, args: Record<string, unknown>): string {
+ return formatToolStep(toolName, args).replace(/^[^\p{L}\p{N}]+/u, '').trim() || toolName;
+}
+
type PendingInteractionKind = 'permission' | 'continue' | 'mode' | 'choice';
interface PendingInteraction {
@@ -22,7 +32,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' | 'queue_dropped' | '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' | 'progress' | 'phase' | '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>;
}
@@ -487,6 +497,54 @@ export class WebChannel extends BaseChannel {
});
}
+ /**
+ * A tool started running, sent the moment it starts (not when the step
+ * ends), so a screen shows what is running during a long command. `id` is
+ * the tool call id: the matching tool_done carries it.
+ */
+ sendToolStarted(id: string, toolName: string, args: Record<string, unknown>, targetId?: string): void {
+ const channelId = targetId || 'default';
+ const step = (this.stepCounter.get(channelId) || 0) + 1;
+ this.stepCounter.set(channelId, step);
+ const label = Object.keys(args).length > 0
+ ? `${toolName}(${Object.entries(args).slice(0, 3).map(([k, v]) => `${k}=${typeof v === 'string' && v.length > 50 ? v.slice(0, 50) + '...' : v}`).join(', ')})`
+ : toolName;
+ this.broadcast({
+ type: 'step_start',
+ data: { id, step, tool: toolName, label: String(label), title: toolTitle(toolName, args), targetId },
+ });
+ }
+
+ /** The tool with this call id finished (or failed), with how long it ran. */
+ sendToolFinished(id: string, toolName: string, result: unknown, failed: boolean, durationMs: number | undefined, targetId?: string): void {
+ const text = result == null ? '' : typeof result === 'string' ? result : safeJson(result);
+ const summary = text.slice(0, 200);
+ // "HTTP 403 …" and "timed out" come back as text, not errors.
+ const reason = failed ? (stepFailure(toolName, text) ?? (summary.split('\n')[0] || 'failed')) : stepFailure(toolName, text);
+ this.broadcast({
+ type: 'step_done',
+ data: {
+ id, tool: toolName, summary, failed: reason !== null,
+ ...(reason ? { reason } : {}),
+ ...(typeof durationMs === 'number' && Number.isFinite(durationMs) ? { durationMs: Math.max(0, Math.round(durationMs)) } : {}),
+ targetId,
+ },
+ });
+ }
+
+ /** What the turn is doing between tools ("Calling anthropic", "Retrying after a stall"…). */
+ sendPhase(phase: string, detail: string | undefined, targetId?: string): void {
+ this.broadcast({ type: 'phase', data: { phase, ...(detail ? { detail } : {}), targetId } });
+ }
+
+ /**
+ * A note while the turn keeps working ("Checking my work…"). Not a reply:
+ * a screen shows it inside the running turn instead of ending the turn.
+ */
+ sendProgressNote(text: string, targetId?: string): void {
+ this.broadcast({ type: 'progress', data: { text, targetId } });
+ }
+
/**
* The model's reasoning as it streams, for clients that show the thought
* process live. Deltas are batched (≤ 8 events/s per target); null closes
@@ -548,7 +606,8 @@ export class WebChannel extends BaseChannel {
sendProviderInfo(name: string, model: string, targetId?: string): void {
this.broadcast({
type: 'provider',
- data: { name, model, targetId },
+ // `provider` too: screens read the same field as on `connected`.
+ data: { name, provider: name, model, targetId },
});
}
diff --git a/src/core/agent.ts b/src/core/agent.ts
index a09eb8db..70accbc3 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -137,6 +137,8 @@ const NOTE_COOLDOWN_MS = 3 * 60 * 1000;
import { runReflection } from '../learning/reflection.js';
import { createOwnerSectionsMemo } from '../learning/owner-brief.js';
import type { ApplyResult } from '../memory/beliefs.js';
+import { TurnTrace, toolSummary } from './turn-trace.js';
+import { claimEffortChat } from '../utils/model-prefs.js';
import { TurnUsage, billingEntries, type SourceUsageTotals, type StepUsageLike, type TurnUsageTotals } from './turn-usage.js';
/**
@@ -162,11 +164,21 @@ export function stepAwareTextStream(
// fired — every step's narration ran into the next as word salad
// ("…in this project.Found the situation…") in the live tail.
if (part.type === 'start-step' || part.type === 'step-start') {
+ // A new step's thinking is its own block on screen.
+ if (reasoningBuf) {
+ reasoningBuf = '';
+ onReasoning?.(null);
+ }
if (!firstStep && sawTextInStep) yield '\n\n';
firstStep = false;
sawTextInStep = false;
continue;
}
+ if ((part.type === 'tool-call' || part.type === 'tool-input-start') && reasoningBuf) {
+ reasoningBuf = '';
+ onReasoning?.(null);
+ continue;
+ }
if (part.type === 'reasoning-delta' && part.text) {
// Live thinking feedback: the model reasoning before speaking is
// surfaced as a preview instead of dead air.
@@ -617,6 +629,8 @@ interface TurnState {
programming: ProgrammingMode | null;
/** Set once the turn has fully ended (late timers check it). */
done: boolean;
+ /** What the turn thought and ran, in order: kept with the reply (turn-trace.ts). */
+ readonly trace: TurnTrace;
}
/** The canonical session a message names, if any. */
@@ -670,6 +684,15 @@ export class Agent {
return this.turnStore.getStore();
}
+ /**
+ * The chat the calling code runs in (the turn's lane: a desktop thread
+ * id, "cli", or a channel conversation); undefined outside a turn. Keys a
+ * chat's own settings, such as its effort override.
+ */
+ currentChatKey(): string | undefined {
+ return this.turn()?.laneKey;
+ }
+
/** Is any turn running? (Use isLaneBusy / turnForChannel for one chat.) */
get processing(): boolean {
return this.activeTurns.size > 0;
@@ -2357,6 +2380,8 @@ export class Agent {
*/
private pushLiveActivity(phase: string, detail?: string): void {
this.cliFeed()?.setLiveActivity(phase, detail);
+ const web = this.currentMessage ? this.channels.getChannelForMessage(this.currentMessage) : undefined;
+ if (web instanceof WebChannel) web.sendPhase(phase, detail, this.currentMessage!.channelId);
}
/**
@@ -2372,6 +2397,40 @@ export class Agent {
return ch;
}
+ /**
+ * A note while the turn keeps working ("Checking my work…"). On the web
+ * channel a plain send is a finished reply, which would end the turn on
+ * screen while work goes on; there it is a progress event instead.
+ */
+ private async sendProgressNote(channel: { send(text: string, targetId?: string): Promise<void> }, text: string, channelId: string): Promise<void> {
+ if (channel instanceof WebChannel) {
+ channel.sendProgressNote(text, channelId);
+ return;
+ }
+ await channel.send(text, channelId);
+ }
+
+ /**
+ * Where a stream's reasoning goes: the terminal's thinking preview, the
+ * desktop's live thought process, and the turn's trace (kept with the
+ * reply). `null` ends the current thinking block.
+ */
+ private reasoningSink(channel: unknown, channelId: string): (preview: string | null, delta?: string) => void {
+ const cli = channel instanceof CLIChannel ? channel : null;
+ const web = channel instanceof WebChannel ? channel : null;
+ const trace = this.turn()?.trace;
+ return (preview, delta) => {
+ cli?.showThinkingPreview(preview);
+ if (preview === null) {
+ trace?.reasoningEnded();
+ web?.sendReasoning(null, channelId);
+ return;
+ }
+ if (delta) trace?.reasoning(delta);
+ web?.sendReasoning(delta ?? '', channelId);
+ };
+ }
+
/**
* Push a tool execution event to the CLI live feedback in real time.
* Unlike onStepFinish (which fires after the whole LLM step), this fires at
@@ -2392,6 +2451,17 @@ export class Agent {
try { current.toolStarted(this.currentMessage.channelId, toolName); } catch { /* best effort */ }
}
}
+ const turn = this.turn();
+ if (status === 'running') turn?.trace.toolStarted(callId, formatToolStep(toolName, (argsOrResult as Record<string, unknown>) || {}));
+ else turn?.trace.toolFinished(callId, status === 'error', durationMs, toolSummary(argsOrResult));
+ // Mercury Desktop and the web dashboard see each tool as it starts and
+ // ends, not only after the whole step.
+ const web = this.currentMessage ? this.channels.getChannelForMessage(this.currentMessage) : undefined;
+ if (web instanceof WebChannel) {
+ const target = this.currentMessage!.channelId;
+ if (status === 'running') web.sendToolStarted(callId, toolName, (argsOrResult as Record<string, unknown>) || {}, target);
+ else web.sendToolFinished(callId, toolName, argsOrResult, status === 'error', durationMs, target);
+ }
const ch = this.cliFeed();
if (!ch) return;
if (status === 'running') {
@@ -2691,6 +2761,7 @@ export class Agent {
lifecycle: new Lifecycle('idle'),
programming: null,
done: false,
+ trace: new TurnTrace(),
};
this.activeTurns.set(laneKey, turn);
logger.info({ turn: turn.id, lane: laneKey, running: this.activeTurns.size, limit: this.governor.limit() }, 'Turn started');
@@ -2700,6 +2771,8 @@ export class Agent {
// This turn's working directory, tools switch and image switch are its own.
this.capabilities.claimTurnState(startCwd);
claimToolImagesForTurn();
+ // Its requests carry this chat's effort override, if it has one (#188).
+ claimEffortChat(laneKey);
try {
await this.runQueuedItem(item);
} finally {
@@ -2873,7 +2946,7 @@ export class Agent {
});
const text = (opts.channel
? await this.withProviderDeadline(
- opts.channel.stream(stepAwareTextStream(stream.fullStream), opts.channelId),
+ opts.channel.stream(stepAwareTextStream(stream.fullStream, this.reasoningSink(opts.channel, opts.channelId)), opts.channelId),
opts.abortController,
deadlineAt,
)
@@ -4139,7 +4212,7 @@ export class Agent {
// Not yet at check limit — let it continue with a note
loopDetector.reset();
loopWarningSent = false;
- await channel.send(`☿ **Mercury Autopilot** · Observing ${analysis.tool} (${analysis.count} calls, ${Math.round(analysis.paramDiversity * 100)}% diversity). Continuing under monitoring.`, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));
+ await this.sendProgressNote(channel, `☿ **Mercury Autopilot** · Observing ${analysis.tool} (${analysis.count} calls, ${Math.round(analysis.paramDiversity * 100)}% diversity). Continuing under monitoring.`, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));
} else {
loopWarningSent = true;
const shouldContinue = await channel.askToContinue(
@@ -4218,19 +4291,7 @@ export class Agent {
}
}
} else if (channel instanceof WebChannel) {
- const webCh = channel as WebChannel;
- for (const tc of toolCalls) {
- webCh.sendToolFeedback(tc.toolName, tc.input as Record<string, any>, msg.channelId);
- }
- if (toolResults) {
- for (let i = 0; i < toolResults.length; i++) {
- const tr = resultFor(toolCalls, toolResults, i) as any;
- const tcName = toolCalls[i]?.toolName as string | undefined;
- if (tcName) {
- webCh.sendStepDone(tcName, toolResultValue(tr), msg.channelId);
- }
- }
- }
+ // Sent live, as each tool starts and ends (pushLiveToolEvent).
} else if (channel instanceof DiscordChannel) {
const dcCh = channel as DiscordChannel;
for (const tc of toolCalls) {
@@ -4275,7 +4336,7 @@ export class Agent {
logger.warn('Reasoning loop detected — model keeps thinking without acting, aborting');
if (!loopWarningSent && channel && msg.channelType !== 'internal') {
loopWarningSent = true;
- await channel.send('⚠ I\'m stuck in a reasoning loop (thinking without taking action). Stopping.', msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));
+ await this.sendProgressNote(channel, '⚠ I\'m stuck in a reasoning loop (thinking without taking action). Stopping.', msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));
}
loopAbortController.abort();
return;
@@ -4420,13 +4481,9 @@ export class Agent {
const cliChThinking = channel instanceof CLIChannel ? channel : null;
// Clients that show the thought process live (Mercury Desktop) get the reasoning text.
- const webChThinking = channel instanceof WebChannel ? channel : null;
- const reasoningTarget = msg.channelId;
+ const reasoningSink = this.reasoningSink(channel, msg.channelId);
const trackedStream = this.withProgressStream((async function* () {
- for await (const chunk of (stepAwareTextStream(streamResult.fullStream, (preview, delta) => {
- cliChThinking?.showThinkingPreview(preview);
- if (webChThinking) webChThinking.sendReasoning(preview === null ? null : delta ?? '', reasoningTarget);
- }))) {
+ for await (const chunk of (stepAwareTextStream(streamResult.fullStream, reasoningSink))) {
if (chunk) hasStreamedOutput = true;
cliChThinking?.showThinkingPreview(null);
yield chunk;
@@ -4520,7 +4577,7 @@ export class Agent {
providerDeadlineAt,
);
const chunk: string[] = [];
- for await (const c of stepAwareTextStream(continueResult.fullStream)) chunk.push(c);
+ for await (const c of stepAwareTextStream(continueResult.fullStream, this.reasoningSink(channel, msg.channelId))) chunk.push(c);
const piece = chunk.join('');
const cFinish: string = await continueResult.finishReason;
if (cFinish === 'error') throw new Error('Continuation stream ended with an error');
@@ -4870,7 +4927,7 @@ export class Agent {
const isDuplicateWarning = lastGuardMsg?.role === 'agent'
&& lastGuardMsg.content.startsWith('Getting started on the real build now');
if (channel && msg.channelType !== 'internal' && !isDuplicateWarning) {
- await channel.send(
+ await this.sendProgressNote(channel,
`Alright — getting started on the real build now (attempt ${executeGuardRounds} of ${MAX_EXECUTE_CONTINUATIONS})...`,
msg.channelId,
).catch((e) => logger.warn({ e }, 'channel send failed'));
@@ -4973,7 +5030,7 @@ export class Agent {
});
const guardText = channel
? await this.withProviderDeadline(
- channel.stream(stepAwareTextStream(guardStream.fullStream), msg.channelId),
+ channel.stream(stepAwareTextStream(guardStream.fullStream, this.reasoningSink(channel, msg.channelId)), msg.channelId),
loopAbortController,
guardDeadlineAt,
)
@@ -5057,7 +5114,7 @@ export class Agent {
this.markProgress('Step budget reached — continuing...');
this.pushLiveActivity('Resuming with a fresh step budget', 'step budget');
if (channel && msg.channelType !== 'internal') {
- await channel.send(
+ await this.sendProgressNote(channel,
`This one's a bigger build than a single pass — picking up right where I left off...`,
msg.channelId,
).catch((e) => logger.warn({ e }, 'channel send failed'));
@@ -5120,7 +5177,7 @@ export class Agent {
this.markProgress('Verifying changes...');
this.pushLiveActivity('Verifying the work', 'verification gate');
if (channel && msg.channelType !== 'internal') {
- await channel.send(
+ await this.sendProgressNote(channel,
'Checking my work before I call it done — running the build/tests now...',
msg.channelId,
).catch((e) => logger.warn({ e }, 'channel send failed'));
@@ -5346,6 +5403,8 @@ export class Agent {
channelId: msg.channelId,
...(typeof msg.metadata?.requestId === 'string' ? { requestId: msg.metadata.requestId } : {}),
...(billedProvider ? { provider: billedProvider.name, model: billedProvider.model } : {}),
+ // The thought process as shown live, for the reopened chat.
+ ...(() => { const t = this.turn(); const trace = t?.trace.snapshot(t.startedAt); return trace ? { trace } : {}; })(),
// Per-turn trace, shown by /trace <id>.
traceId,
elapsedMs: Date.now() - startTime,
@@ -5421,7 +5480,9 @@ export class Agent {
forceBanner: isMercuryCodeExecution,
});
replyDelivered();
- this.markProgress();
+ // Progress, without the typing refresh: a "thinking" event after the
+ // reply would make a screen think a new turn started.
+ this.lastProgressAt = Date.now();
} else {
replyDelivered();
logger.debug('Internal prompt processed, no channel response needed');
diff --git a/src/core/commands/chat-command.test.ts b/src/core/commands/chat-command.test.ts
index 3e9c3339..bedf38a9 100644
--- a/src/core/commands/chat-command.test.ts
+++ b/src/core/commands/chat-command.test.ts
@@ -131,3 +131,51 @@ describe('/model on the attached terminal (web channel)', () => {
expect(switched).not.toHaveBeenCalled();
});
});
+
+describe('/effort (#188)', () => {
+ function effortAgent(channel: WebChannel, model: string, chatKey?: string): Agent {
+ return {
+ config: { providers: {} },
+ providers: { getDefault: () => ({ name: 'anthropic', model, getModel: () => model }) },
+ channels: { get: () => channel },
+ currentChatKey: () => chatKey,
+ capabilities: { getChatCommandContext: () => ({ config: () => ({ providers: {} }) }) },
+ } as unknown as Agent;
+ }
+
+ it('sets this chat only, resets to the default, and changes the default with global', async () => {
+ const prefs = await import('../../utils/model-prefs.js');
+ prefs.resetModelPrefsCache();
+ prefs.resetChatEffortCache();
+ const { channel, sent } = sseChannel('sess-1');
+ const agent = effortAgent(channel, 'claude-opus-5-5', 'sess-1');
+ const state = () => prefs.effortFor('anthropic', 'claude-opus-5-5', 'sess-1');
+
+ await handleChatCommand(agent, '/effort', 'web', 'sess-1');
+ expect(sent.at(-1)).toContain('**Auto** (the model decides)');
+ expect(sent.at(-1)).toContain('xhigh');
+
+ await handleChatCommand(agent, '/effort xhigh', 'web', 'sess-1');
+ expect(state()).toMatchObject({ effective: 'xhigh', source: 'chat' });
+ expect(prefs.effortFor('anthropic', 'claude-opus-5-5', 'other-chat').effective).toBeUndefined();
+ expect(sent.at(-1)).toContain('this chat');
+
+ await handleChatCommand(agent, '/effort global medium', 'web', 'sess-1');
+ expect(prefs.effortFor('anthropic', 'claude-opus-5-5', 'other-chat').effective).toBe('medium');
+ expect(state().effective).toBe('xhigh');
+
+ await handleChatCommand(agent, '/effort default', 'web', 'sess-1');
+ expect(state()).toMatchObject({ effective: 'medium', source: 'model' });
+
+ await handleChatCommand(agent, '/effort turbo', 'web', 'sess-1');
+ expect(sent.at(-1)).toContain('takes: auto, low, medium, high, xhigh, max');
+ prefs.resetModelPrefsCache();
+ prefs.resetChatEffortCache();
+ });
+
+ it('says so for a model without an effort setting', async () => {
+ const { channel, sent } = sseChannel('sess-1');
+ await handleChatCommand(effortAgent(channel, 'claude-haiku-4-5', 'sess-1'), '/effort high', 'web', 'sess-1');
+ expect(sent.at(-1)).toContain('has no effort setting');
+ });
+});
diff --git a/src/core/commands/chat-command.ts b/src/core/commands/chat-command.ts
index a6a54a14..8a02cfb9 100644
--- a/src/core/commands/chat-command.ts
+++ b/src/core/commands/chat-command.ts
@@ -35,6 +35,8 @@ import {
clearSlackAccess,
} from '../../utils/config.js';
import { MAX_STEPS } from '../agent.js';
+import { displayModelName, effortFor, effortLabel, setChatEffort, setModelPref, type ReasoningLevel } from '../../utils/model-prefs.js';
+import { discoverReasoningCaps } from '../../providers/reasoning-discovery.js';
import path from 'node:path';
import type { ChannelType } from '../../types/channel.js';
import { createProvider, ProviderRegistry as ProviderRegistryImpl } from '../../providers/registry.js';
@@ -280,12 +282,18 @@ export async function handleChatCommand(agent: Agent, content: string, channelTy
`Slack access: ${getSlackAccessSummary(config)}`,
`Budget: ${budget.getStatusText()}`,
saverLine,
+ effortStatusLine(agent),
`Skills: ${ctx.skillNames().length > 0 ? ctx.skillNames().join(', ') : 'none'}`,
];
await channel.send(lines.join('\n'), channelId);
return true;
}
+ if (cmd === '/effort' || cmd.startsWith('/effort ')) {
+ await channel.send(await effortCommand(agent, trimmed.slice('/effort'.length).trim().toLowerCase()), channelId);
+ return true;
+ }
+
if (cmd === '/models' || cmd === '/model' || cmd.startsWith('/models ') || cmd.startsWith('/model ')) {
const base = cmd.startsWith('/model ') || cmd === '/model' ? '/model' : '/models';
const rawArgs = trimmed.slice(base.length).trim();
@@ -1790,3 +1798,73 @@ export async function handleChatCommand(agent: Agent, content: string, channelTy
return false;
}
+
+/**
+ * /effort (issue #188): how hard the current model thinks in this chat.
+ * /effort what applies here, and the levels this model takes
+ * /effort <level> this chat only
+ * /effort default this chat back to the model's default
+ * /effort global <level> the model's default (every chat without its own)
+ */
+export async function effortCommand(agent: Agent, arg: string): Promise<string> {
+ const current = agent.providers.getDefault();
+ const provider = current.name;
+ const model = current.getModel();
+ const pc = (agent.config.providers as unknown as Record<string, import('../../utils/config.js').ProviderConfig | undefined>)[provider];
+ // An OpenAI-compatible server may say which models take an effort.
+ if (pc) await discoverReasoningCaps({ ...pc, model }, model).catch(() => undefined);
+ const chatKey = (agent as { currentChatKey?: () => string | undefined }).currentChatKey?.();
+ const name = displayModelName(provider, model);
+ const state = effortFor(provider, model, chatKey);
+ if (!state.levels.length) {
+ return `${name} has no effort setting Mercury can apply — it decides how much to think on its own.`;
+ }
+ const choices = ['auto', ...state.levels];
+ const usage = 'Use `/effort <level>` for this chat, `/effort default` to go back to the model\'s default, `/effort global <level>` to change that default.';
+ const [verb, value] = arg.split(/\s+/, 2);
+
+ if (!arg) {
+ const applied = effortLabel(state.effective ?? 'auto');
+ const why = state.source === 'chat' ? 'set for this chat'
+ : state.source === 'model' ? 'this model\'s default'
+ : 'the model decides';
+ return [
+ `**Effort** · ${name}: **${applied}** (${why})`,
+ `Model default: ${effortLabel(state.modelDefault)}${state.chat ? ` · This chat: ${effortLabel(state.chat)}` : ''}`,
+ ...(state.chatUnsupported ? [`This chat asked for ${effortLabel(state.chat!)}, which ${name} doesn't take, so its default applies.`] : []),
+ `Levels: ${choices.join(' · ')}`,
+ usage,
+ ].join('\n');
+ }
+ if (verb === 'default' || verb === 'reset' || verb === 'clear') {
+ if (chatKey) setChatEffort(chatKey, null);
+ return `This chat now uses ${name}'s default: **${effortLabel(state.modelDefault)}**.`;
+ }
+ if (verb === 'global') {
+ if (!value || !choices.includes(value)) return `\`/effort global <level>\` — ${name} takes: ${choices.join(', ')}.`;
+ setModelPref(provider, model, { reasoning: value === 'auto' ? null : (value as ReasoningLevel) });
+ return `Default effort for ${name}: **${effortLabel(value)}**${state.chat ? ` (this chat keeps its own: ${effortLabel(state.chat)})` : ''}.`;
+ }
+ if (!choices.includes(verb)) return `${name} takes: ${choices.join(', ')}. ${usage}`;
+ if (!chatKey) {
+ setModelPref(provider, model, { reasoning: verb === 'auto' ? null : (verb as ReasoningLevel) });
+ return `Default effort for ${name}: **${effortLabel(verb)}**.`;
+ }
+ setChatEffort(chatKey, verb as ReasoningLevel | 'auto');
+ return `Effort for this chat: **${effortLabel(verb)}** (${name}). Applies from the next message; \`/effort default\` goes back to ${effortLabel(state.modelDefault)}.`;
+}
+
+/** "Effort: High (this chat)" for /status (#188: the effective setting and where it comes from). */
+function effortStatusLine(agent: Agent): string {
+ try {
+ const current = agent.providers.getDefault();
+ const chatKey = (agent as { currentChatKey?: () => string | undefined }).currentChatKey?.();
+ const state = effortFor(current.name, current.getModel(), chatKey);
+ if (!state.levels.length) return 'Effort: not adjustable for this model';
+ const where = state.source === 'chat' ? 'this chat' : state.source === 'model' ? 'model default' : 'model decides';
+ return `Effort: ${effortLabel(state.effective ?? 'auto')} (${where})`;
+ } catch {
+ return 'Effort: —';
+ }
+}
+
diff --git a/src/core/commands/slash-list.ts b/src/core/commands/slash-list.ts
index 0a991570..4814b416 100644
--- a/src/core/commands/slash-list.ts
+++ b/src/core/commands/slash-list.ts
@@ -96,6 +96,10 @@ export const SLASH_COMMANDS: readonly string[] = [
'/memory',
'/models',
'/models use ',
+ '/effort',
+ '/effort default',
+ '/effort global ',
+ '/effort ',
'/cloud',
'/cloud models',
'/cloud use ',
diff --git a/src/core/step-aware-text-stream.test.ts b/src/core/step-aware-text-stream.test.ts
index 05b280a3..a3e2c5ce 100644
--- a/src/core/step-aware-text-stream.test.ts
+++ b/src/core/step-aware-text-stream.test.ts
@@ -68,4 +68,20 @@ describe('stepAwareTextStream', () => {
expect(previews.length).toBeGreaterThan(0);
expect(previews.at(-1)).toBeNull(); // cleared once text starts
});
-});
\ No newline at end of file
+
+ it('every step gets its own thinking block: a tool call or a new step closes it', async () => {
+ const events: Array<string | null> = [];
+ const fullStream = [
+ { type: 'start-step' },
+ { type: 'reasoning-delta', id: 'r1', text: 'plan A' },
+ { type: 'tool-call', toolCallId: 'c1', toolName: 'read_file', input: {} },
+ { type: 'start-step' },
+ { type: 'reasoning-delta', id: 'r2', text: 'plan B' },
+ { type: 'start-step' },
+ { type: 'text-delta', id: 't1', text: 'done' },
+ ];
+ await collect(stepAwareTextStream(fullStream as any, (preview, delta) => events.push(preview === null ? null : delta ?? '')));
+ expect(events).toEqual(['plan A', null, 'plan B', null, null]);
+ });
+});
+
diff --git a/src/core/turn-trace.test.ts b/src/core/turn-trace.test.ts
new file mode 100644
index 00000000..bad58eeb
--- /dev/null
+++ b/src/core/turn-trace.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from 'vitest';
+import { TurnTrace, toolSummary } from './turn-trace.js';
+
+describe('TurnTrace', () => {
+ it('keeps thinking and tools in order, with durations', () => {
+ let now = 1000;
+ const t = new TurnTrace(() => now);
+ t.reasoning('Plan ');
+ t.reasoning('it.');
+ now = 1500;
+ t.toolStarted('c1', '📖 Read src/x.ts');
+ now = 1800;
+ t.toolFinished('c1', false, 250, 'ok');
+ t.reasoning('Next.');
+ t.reasoningEnded();
+ t.toolStarted('c2', 'Run npm test');
+ now = 4000;
+ const snap = t.snapshot(900)!;
+ expect(snap.startedAt).toBe(900);
+ expect(snap.items.map((i) => i.kind)).toEqual(['reasoning', 'tool', 'reasoning', 'tool']);
+ expect(snap.items[0]).toMatchObject({ text: 'Plan it.', startedAt: 1000, endedAt: 1500 });
+ expect(snap.items[1]).toMatchObject({ id: 'c1', title: 'Read src/x.ts', status: 'done', durationMs: 250, summary: 'ok' });
+ // Still running when the turn ended: cut off.
+ expect(snap.items[3]).toMatchObject({ id: 'c2', status: 'error', summary: 'Stopped' });
+ });
+
+ it('is empty when the turn neither thought nor ran anything', () => {
+ expect(new TurnTrace().snapshot(0)).toBeUndefined();
+ });
+
+ it('caps a very long turn', () => {
+ const t = new TurnTrace();
+ for (let i = 0; i < 400; i++) { t.toolStarted(`c${i}`, 'x'); t.toolFinished(`c${i}`, false, 1, undefined); }
+ t.reasoning('y'.repeat(100_000));
+ const snap = t.snapshot(0)!;
+ expect(snap.items.length).toBeLessThanOrEqual(150);
+ const text = snap.items.filter((i) => i.kind === 'reasoning').map((i) => (i as { text: string }).text).join('');
+ expect(text.length).toBeLessThanOrEqual(24_000);
+ });
+
+ it('summarises a result to its first line', () => {
+ expect(toolSummary('\n first line \nsecond')).toBe('first line');
+ expect(toolSummary({ ok: true })).toBe('{"ok":true}');
+ expect(toolSummary(new Error('boom'))).toBe('boom');
+ expect(toolSummary(undefined)).toBeUndefined();
+ });
+});
diff --git a/src/core/turn-trace.ts b/src/core/turn-trace.ts
new file mode 100644
index 00000000..36d3b8c8
--- /dev/null
+++ b/src/core/turn-trace.ts
@@ -0,0 +1,120 @@
+/**
+ * What one turn thought and ran, in the order it happened: thinking blocks
+ * and tool calls with their durations. Kept with the reply (session message
+ * metadata `trace`) so a screen shows the same thought process after the
+ * chat is reopened as it did live. Bounded: a long agentic turn keeps its
+ * most recent steps and a capped amount of thinking text.
+ */
+
+export interface TraceReasoning {
+ kind: 'reasoning';
+ text: string;
+ startedAt: number;
+ endedAt?: number;
+}
+
+export interface TraceTool {
+ kind: 'tool';
+ id: string;
+ /** "Read src/x.ts", "Run npm test". */
+ title: string;
+ status: 'running' | 'done' | 'error';
+ startedAt: number;
+ endedAt?: number;
+ durationMs?: number;
+ /** First line of the result (or the error). */
+ summary?: string;
+}
+
+export type TraceItem = TraceReasoning | TraceTool;
+
+export interface StoredTrace {
+ startedAt: number;
+ endedAt: number;
+ items: TraceItem[];
+}
+
+const MAX_ITEMS = 150;
+const MAX_REASONING_CHARS = 24_000;
+const MAX_BLOCK_CHARS = 8_000;
+const MAX_SUMMARY = 160;
+
+export function toolSummary(result: unknown): string | undefined {
+ if (result == null) return undefined;
+ let text: string;
+ if (typeof result === 'string') text = result;
+ else if (result instanceof Error) text = result.message;
+ else {
+ try { text = JSON.stringify(result) ?? ''; } catch { text = String(result); }
+ }
+ const line = text.split('\n').find((l) => l.trim())?.trim() ?? '';
+ if (!line) return undefined;
+ return line.length > MAX_SUMMARY ? `${line.slice(0, MAX_SUMMARY - 1)}…` : line;
+}
+
+export class TurnTrace {
+ private items: TraceItem[] = [];
+ private reasoningChars = 0;
+ private openReasoning: TraceReasoning | null = null;
+
+ constructor(private readonly now: () => number = Date.now) {}
+
+ reasoning(delta: string): void {
+ if (!delta) return;
+ if (!this.openReasoning) {
+ this.openReasoning = { kind: 'reasoning', text: '', startedAt: this.now() };
+ this.push(this.openReasoning);
+ }
+ const room = Math.min(MAX_BLOCK_CHARS - this.openReasoning.text.length, MAX_REASONING_CHARS - this.reasoningChars);
+ if (room <= 0) return;
+ const piece = delta.slice(0, room);
+ this.openReasoning.text += piece;
+ this.reasoningChars += piece.length;
+ }
+
+ reasoningEnded(): void {
+ if (this.openReasoning) this.openReasoning.endedAt = this.now();
+ this.openReasoning = null;
+ }
+
+ toolStarted(id: string, title: string): void {
+ this.reasoningEnded();
+ if (this.items.some((item) => item.kind === 'tool' && item.id === id)) return;
+ this.push({ kind: 'tool', id, title: title.replace(/^[^\p{L}\p{N}]+/u, '').trim() || title, status: 'running', startedAt: this.now() });
+ }
+
+ toolFinished(id: string, failed: boolean, durationMs: number | undefined, summary: string | undefined): void {
+ const step = [...this.items].reverse().find((item): item is TraceTool => item.kind === 'tool' && item.id === id);
+ if (!step) return;
+ const endedAt = this.now();
+ step.status = failed ? 'error' : 'done';
+ step.endedAt = endedAt;
+ step.durationMs = typeof durationMs === 'number' && Number.isFinite(durationMs) ? Math.max(0, Math.round(durationMs)) : endedAt - step.startedAt;
+ if (summary) step.summary = summary;
+ }
+
+ get size(): number {
+ return this.items.length;
+ }
+
+ /** The trace to keep with the reply; undefined when the turn neither thought nor ran anything. */
+ snapshot(startedAt: number): StoredTrace | undefined {
+ this.reasoningEnded();
+ const items = this.items.filter((item) => item.kind === 'tool' || item.text.trim());
+ if (!items.length) return undefined;
+ const endedAt = this.now();
+ return {
+ startedAt,
+ endedAt,
+ // Anything still marked running when the turn ended was cut off.
+ items: items.map((item) => (item.kind === 'tool' && item.status === 'running'
+ ? { ...item, status: 'error' as const, endedAt, durationMs: endedAt - item.startedAt, summary: item.summary ?? 'Stopped' }
+ : { ...item })),
+ };
+ }
+
+ private push(item: TraceItem): void {
+ this.items.push(item);
+ if (this.items.length > MAX_ITEMS) this.items.splice(0, this.items.length - MAX_ITEMS);
+ }
+}
diff --git a/src/plugins/types.ts b/src/plugins/types.ts
index a2164f01..88bca3b2 100644
--- a/src/plugins/types.ts
+++ b/src/plugins/types.ts
@@ -36,7 +36,7 @@ export const RESERVED_PLUGIN_IDS: ReadonlySet<string> = new Set(['mcp']);
* TUI's SLASH_COMMANDS by src/plugins/commands.test.ts.
*/
export const RESERVED_COMMANDS: ReadonlySet<string> = new Set([
- 'agents', 'bg', 'bot', 'bots', 'budget', 'call', 'calls', 'chat', 'cloud', 'code', 'halt', 'help', 'log', 'memory', 'menu', 'models', 'model',
+ 'agents', 'bg', 'bot', 'bots', 'budget', 'call', 'calls', 'chat', 'cloud', 'code', 'effort', 'halt', 'help', 'log', 'memory', 'menu', 'models', 'model',
'permissions', 'plugin', 'plugins', 'progress', 'research', 'reset', 'server', 'saver', 'session', 'sessions', 'skills', 'spotify',
'status', 'stop', 'stream', 'tools', 'update', 'view', 'whatsnew', 'ws', 'start', 'skip', 'new', 'compact', 'clear',
'approve', 'deny', 'yes', 'no', 'cancel', 'pair', 'unpair', 'telegram', 'discord', 'slack', 'signal', 'web', 'exit', 'quit',
diff --git a/src/providers/anthropic.ts b/src/providers/anthropic.ts
index 8b08d173..c772fc62 100644
--- a/src/providers/anthropic.ts
+++ b/src/providers/anthropic.ts
@@ -1,6 +1,7 @@
import { createAnthropic } from '@ai-sdk/anthropic';
import { generateText, streamText } from 'ai';
import { BaseProvider } from './base.js';
+import { withAnthropicThinking } from './reasoning-wire.js';
import type { ProviderConfig } from '../utils/config.js';
import type { LLMResponse, LLMStreamChunk } from './base.js';
@@ -8,7 +9,7 @@ export class AnthropicProvider extends BaseProvider {
readonly name = 'anthropic';
readonly model: string;
private client: ReturnType<typeof createAnthropic>;
- private modelInstance: ReturnType<ReturnType<typeof createAnthropic>['languageModel']>;
+ private modelInstance: ReturnType<typeof withAnthropicThinking>;
constructor(config: ProviderConfig) {
super(config);
@@ -17,7 +18,8 @@ export class AnthropicProvider extends BaseProvider {
this.client = createAnthropic({
apiKey: config.apiKey,
});
- this.modelInstance = this.client(config.model);
+ // Thinking shown as a summary and the owner's effort level, per request.
+ this.modelInstance = withAnthropicThinking(this.client(config.model), this.name, config.model);
}
async generateText(prompt: string, systemPrompt: string): Promise<LLMResponse> {
diff --git a/src/providers/chatgpt-web.ts b/src/providers/chatgpt-web.ts
index a58fc07b..07f58808 100644
--- a/src/providers/chatgpt-web.ts
+++ b/src/providers/chatgpt-web.ts
@@ -21,8 +21,10 @@ const UNSUPPORTED_FIELDS = [
function sanitiseBody(raw: string, providerName: string): string {
const body = JSON.parse(raw);
- // User-chosen reasoning level for this model (dashboard reasoning picker).
- if (typeof body.model === 'string') applyReasoningToBody(body, effectiveReasoning(providerName, body.model));
+ // User-chosen reasoning level for this model (dashboard reasoning picker),
+ // and a summary of the reasoning so a screen can show the model thinking
+ // (the Codex backend serves summaries on every ChatGPT plan).
+ if (typeof body.model === 'string') applyReasoningToBody(body, effectiveReasoning(providerName, body.model), { summary: true });
// Required
body.store = false;
diff --git a/src/providers/openai-compat.ts b/src/providers/openai-compat.ts
index b58c2c07..2319859b 100644
--- a/src/providers/openai-compat.ts
+++ b/src/providers/openai-compat.ts
@@ -7,27 +7,46 @@ import { logger } from '../utils/logger.js';
import { aimlapiHeaders } from './aimlapi-attribution.js';
import { basicAuthHeaders } from './basic-auth.js';
import { registerSecretValue } from '../utils/redact.js';
-import { applyReasoningToBody, effectiveReasoning, providerHasReasoningControl } from '../utils/model-prefs.js';
+import { applyReasoningToBody, effectiveReasoning, isOpenRouterUrl, providerHasReasoningControl } from '../utils/model-prefs.js';
+import { rememberCaps } from '../utils/reasoning-caps.js';
+import { reasoningAsThinkTags, withThinkTagReasoning, type WireModel } from './reasoning-wire.js';
/**
- * fetch that applies the user's reasoning level for the requested model.
- * Done on the wire because the AI SDK drops reasoningEffort for model ids it
- * doesn't recognise as reasoning models (every Ollama model, for one).
+ * fetch that applies the reasoning level for the requested model (the
+ * running chat's override, else the model's default). Done on the wire
+ * because the AI SDK drops reasoningEffort for model ids it doesn't
+ * recognise as reasoning models (every Ollama model, for one).
+ *
+ * A server that answers 400 to the effort (an older vLLM, a model without
+ * reasoning behind a gateway) gets the same request again without it, and
+ * the model is remembered as taking none (reasoning-caps.ts): a wrong guess
+ * costs one retry, never a failed turn.
*/
-function withReasoningPref(providerName: string): typeof fetch {
+export function withReasoningPref(providerName: string, baseUrl?: string, base: typeof fetch = globalThis.fetch): typeof fetch {
+ const openRouter = isOpenRouterUrl(baseUrl);
return async (input, init) => {
+ let model: string | undefined;
+ let original: string | undefined;
if (typeof init?.body === 'string') {
try {
const body = JSON.parse(init.body) as Record<string, unknown>;
+ model = typeof body.model === 'string' ? body.model : undefined;
// Only levels this model accepts (e.g. never an effort for gpt-4o).
- const level = typeof body.model === 'string' ? effectiveReasoning(providerName, body.model) : undefined;
+ const level = model ? effectiveReasoning(providerName, model) : undefined;
if (level) {
- applyReasoningToBody(body, level);
+ applyReasoningToBody(body, level, { openRouter });
+ original = init.body;
init = { ...init, body: JSON.stringify(body) };
}
} catch { /* not JSON — pass through */ }
}
- return globalThis.fetch(input, init);
+ const response = await base(input, init);
+ if (original === undefined || !model || (response.status !== 400 && response.status !== 422)) return response;
+ const text = await response.clone().text().catch(() => '');
+ if (!/reasoning|effort|think/i.test(text)) return response;
+ rememberCaps(providerName, model, [], 'rejected');
+ logger.warn({ provider: providerName, model, status: response.status }, 'Server rejected the reasoning effort; resent without it and stopped sending it for this model');
+ return base(input, { ...init, body: original });
};
}
@@ -35,7 +54,7 @@ export class OpenAICompatProvider extends BaseProvider {
readonly name: string;
readonly model: string;
private client: ReturnType<typeof createOpenAI>;
- private modelInstance: ReturnType<ReturnType<typeof createOpenAI>['languageModel']>;
+ private modelInstance: WireModel;
private readonly usesResponsesApi: boolean;
constructor(config: ProviderConfig, { useChatApi }: { useChatApi?: boolean } = {}) {
@@ -58,10 +77,14 @@ export class OpenAICompatProvider extends BaseProvider {
headers: basicAuth ? { ...attribution, ...basicAuth } : attribution,
// Only providers with a reasoning control get the hook; the rest keep
// the SDK's default fetch untouched.
- fetch: providerHasReasoningControl(config.name) ? withReasoningPref(config.name) : undefined,
+ // Chat Completions servers also get their reasoning field carried
+ // through (reasoning-wire.ts); the Responses API has it natively.
+ fetch: useChatApi
+ ? reasoningAsThinkTags(providerHasReasoningControl(config.name) ? withReasoningPref(config.name, config.baseUrl) : globalThis.fetch)
+ : providerHasReasoningControl(config.name) ? withReasoningPref(config.name, config.baseUrl) : undefined,
});
this.modelInstance = useChatApi
- ? this.client.chat(config.model)
+ ? withThinkTagReasoning(this.client.chat(config.model))
: this.client(config.model);
}
diff --git a/src/providers/reasoning-discovery.test.ts b/src/providers/reasoning-discovery.test.ts
new file mode 100644
index 00000000..d5794702
--- /dev/null
+++ b/src/providers/reasoning-discovery.test.ts
@@ -0,0 +1,185 @@
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { discoverReasoningCaps, probeReasoningLevels } from './reasoning-discovery.js';
+import { withReasoningPref } from './openai-compat.js';
+import {
+ claimEffortChat, effortFor, effectiveReasoning, reasoningLevelsFor, resetChatEffortCache, resetModelPrefsCache, setChatEffort, setModelPref,
+} from '../utils/model-prefs.js';
+import { cachedCaps, heuristicLevels, rememberCaps, resetReasoningCapsCache } from '../utils/reasoning-caps.js';
+import { runInTurnScope } from '../utils/turn-scope.js';
+import type { ProviderConfig } from '../utils/config.js';
+
+/**
+ * Effort for OpenAI-compatible servers (#188): what the server says, else
+ * the model's name, and a 400 to an effort settles it for good — the
+ * request is resent without it instead of failing.
+ */
+let home: string;
+const previousHome = process.env.MERCURY_HOME;
+beforeEach(() => {
+ home = mkdtempSync(join(tmpdir(), 'mercury-caps-'));
+ process.env.MERCURY_HOME = home;
+ resetModelPrefsCache();
+ resetChatEffortCache();
+ resetReasoningCapsCache();
+});
+afterEach(() => {
+ resetModelPrefsCache();
+ resetChatEffortCache();
+ resetReasoningCapsCache();
+ if (previousHome === undefined) delete process.env.MERCURY_HOME;
+ else process.env.MERCURY_HOME = previousHome;
+ rmSync(home, { recursive: true, force: true });
+});
+
+const pc = (name: string, baseUrl: string, model = 'm'): ProviderConfig => ({ name, baseUrl, model, apiKey: 'k', enabled: true });
+const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
+
+describe('what a server says', () => {
+ it('Ollama: only models with the thinking capability, gpt-oss with its own levels', async () => {
+ const seen: string[] = [];
+ const fake = (async (url: string, init?: RequestInit) => {
+ seen.push(String(url));
+ const model = JSON.parse(String(init?.body)).model as string;
+ return json({ capabilities: model === 'llama3.2' ? ['completion', 'tools'] : ['completion', 'tools', 'thinking'] });
+ }) as unknown as typeof fetch;
+ const ollama = pc('ollamaLocal', 'http://localhost:11434/v1');
+ expect(await probeReasoningLevels(ollama, 'qwen3:8b', fake)).toEqual(['off', 'high']);
+ expect(await probeReasoningLevels(ollama, 'gpt-oss:20b', fake)).toEqual(['low', 'medium', 'high']);
+ expect(await probeReasoningLevels(ollama, 'llama3.2', fake)).toEqual([]);
+ expect(seen[0]).toBe('http://localhost:11434/api/show');
+ });
+
+ it('LiteLLM: supports_reasoning per model', async () => {
+ const fake = (async () => json({ data: [
+ { model_name: 'claude', model_info: { supports_reasoning: true } },
+ { model_name: 'gpt-4o', model_info: { supports_reasoning: false } },
+ ] })) as unknown as typeof fetch;
+ const litellm = pc('litellm', 'http://proxy:4000/v1');
+ expect(await probeReasoningLevels(litellm, 'claude', fake)).toEqual(['low', 'medium', 'high']);
+ expect(await probeReasoningLevels(litellm, 'gpt-4o', fake)).toEqual([]);
+ expect(await probeReasoningLevels(litellm, 'unknown', fake)).toBeUndefined();
+ });
+
+ it('OpenRouter: supported_parameters', async () => {
+ const fake = (async () => json({ data: [
+ { id: 'deepseek/deepseek-r1', supported_parameters: ['reasoning', 'tools'] },
+ { id: 'mistral/small', supported_parameters: ['tools'] },
+ ] })) as unknown as typeof fetch;
+ const or = pc('openaiCompat', 'https://openrouter.ai/api/v1');
+ expect(await probeReasoningLevels(or, 'deepseek/deepseek-r1', fake)).toEqual(['low', 'medium', 'high']);
+ expect(await probeReasoningLevels(or, 'mistral/small', fake)).toEqual([]);
+ });
+
+ it('a server that cannot say (or is down) leaves the guess in place', async () => {
+ const down = (async () => { throw new Error('ECONNREFUSED'); }) as unknown as typeof fetch;
+ expect(await probeReasoningLevels(pc('ollamaLocal', 'http://x/v1'), 'qwen3', down)).toBeUndefined();
+ expect(await probeReasoningLevels(pc('lmStudio', 'http://x/v1'), 'gpt-oss-20b', down)).toBeUndefined();
+ expect(reasoningLevelsFor('lmStudio', 'gpt-oss-20b')).toEqual(['low', 'medium', 'high']);
+ });
+
+ it('a discovered answer replaces the guess', async () => {
+ expect(reasoningLevelsFor('ollamaLocal', 'llama3.2')).toEqual(['off', 'low', 'medium', 'high']);
+ const fake = (async () => json({ capabilities: ['completion'] })) as unknown as typeof fetch;
+ await discoverReasoningCaps(pc('ollamaLocal', 'http://localhost:11434/v1', 'llama3.2'), 'llama3.2', fake);
+ expect(reasoningLevelsFor('ollamaLocal', 'llama3.2')).toEqual([]);
+ });
+});
+
+describe('names, when nothing else is known', () => {
+ it.each([
+ ['gpt-5.2', ['low', 'medium', 'high']],
+ ['openai/o4-mini', ['low', 'medium', 'high']],
+ ['gpt-oss-120b', ['low', 'medium', 'high']],
+ ['gemini-2.5-pro', ['low', 'medium', 'high']],
+ ['anthropic/claude-sonnet-4-6', ['low', 'medium', 'high']],
+ ['grok-3-mini', ['low', 'high']],
+ ['llama-3.3-70b', []],
+ ['gpt-4o', []],
+ ['claude-3-5-sonnet', []],
+ ])('%s', (model, levels) => {
+ expect(heuristicLevels(model)).toEqual(levels);
+ });
+});
+
+describe('a server that rejects the effort', () => {
+ it('gets the request again without it, and never again for that model', async () => {
+ setModelPref('openaiCompat', 'gpt-5-mini', { reasoning: 'high' });
+ const bodies: Array<Record<string, unknown>> = [];
+ const fake = (async (_url: unknown, init?: RequestInit) => {
+ const body = JSON.parse(String(init?.body));
+ bodies.push(body);
+ return 'reasoning_effort' in body ? json({ error: { message: 'Unrecognized request argument supplied: reasoning_effort' } }, 400) : json({ ok: true });
+ }) as unknown as typeof fetch;
+ const f = withReasoningPref('openaiCompat', 'http://vllm:8000/v1', fake);
+ const res = await f('http://vllm:8000/v1/chat/completions', { method: 'POST', body: JSON.stringify({ model: 'gpt-5-mini', messages: [] }) });
+ expect(res.status).toBe(200);
+ expect(bodies.map((b) => 'reasoning_effort' in b)).toEqual([true, false]);
+ expect(cachedCaps('openaiCompat', 'gpt-5-mini')?.source).toBe('rejected');
+ expect(reasoningLevelsFor('openaiCompat', 'gpt-5-mini')).toEqual([]);
+ await f('http://vllm:8000/v1/chat/completions', { method: 'POST', body: JSON.stringify({ model: 'gpt-5-mini', messages: [] }) });
+ expect(bodies.at(-1)).not.toHaveProperty('reasoning_effort');
+ });
+
+ it('an unrelated 400 is passed through untouched', async () => {
+ setModelPref('openaiCompat', 'gpt-5-mini', { reasoning: 'high' });
+ let calls = 0;
+ const fake = (async () => { calls++; return json({ error: { message: 'context length exceeded' } }, 400); }) as unknown as typeof fetch;
+ const res = await withReasoningPref('openaiCompat', undefined, fake)('u', { method: 'POST', body: JSON.stringify({ model: 'gpt-5-mini', messages: [] }) });
+ expect(res.status).toBe(400);
+ expect(calls).toBe(1);
+ });
+
+ it('OpenRouter gets its own reasoning field', async () => {
+ setModelPref('openaiCompat', 'openai/o4-mini', { reasoning: 'low' });
+ let sent: Record<string, unknown> = {};
+ const fake = (async (_u: unknown, init?: RequestInit) => { sent = JSON.parse(String(init?.body)); return json({}); }) as unknown as typeof fetch;
+ await withReasoningPref('openaiCompat', 'https://openrouter.ai/api/v1', fake)('u', { method: 'POST', body: JSON.stringify({ model: 'openai/o4-mini', messages: [] }) });
+ expect(sent.reasoning).toEqual({ effort: 'low' });
+ expect(sent).not.toHaveProperty('reasoning_effort');
+ });
+
+ it('a later discovery does not overrule a rejection', () => {
+ rememberCaps('litellm', 'x', [], 'rejected');
+ rememberCaps('litellm', 'x', ['low', 'medium', 'high'], 'discovered');
+ expect(reasoningLevelsFor('litellm', 'x')).toEqual([]);
+ });
+});
+
+describe('per-chat effort (#188)', () => {
+ it("a chat's override wins over the model default, only inside that chat's turn", () => {
+ setModelPref('anthropic', 'claude-opus-5-5', { reasoning: 'medium' });
+ setChatEffort('thread-a', 'max');
+ expect(effectiveReasoning('anthropic', 'claude-opus-5-5')).toBe('medium');
+ runInTurnScope(() => {
+ claimEffortChat('thread-a');
+ expect(effectiveReasoning('anthropic', 'claude-opus-5-5')).toBe('max');
+ });
+ runInTurnScope(() => {
+ claimEffortChat('thread-b');
+ expect(effectiveReasoning('anthropic', 'claude-opus-5-5')).toBe('medium');
+ });
+ });
+
+ it('"auto" in a chat sends nothing even with a default; clearing goes back to the default', () => {
+ setModelPref('anthropic', 'claude-opus-5-5', { reasoning: 'high' });
+ setChatEffort('t', 'auto');
+ expect(effortFor('anthropic', 'claude-opus-5-5', 't')).toMatchObject({ effective: undefined, source: 'chat', modelDefault: 'high' });
+ setChatEffort('t', null);
+ expect(effortFor('anthropic', 'claude-opus-5-5', 't')).toMatchObject({ effective: 'high', source: 'model' });
+ });
+
+ it('a pick the current model cannot take falls back to its default, and says so', () => {
+ setChatEffort('t', 'xhigh');
+ expect(effortFor('anthropic', 'claude-opus-4-6', 't')).toMatchObject({ effective: undefined, chatUnsupported: true });
+ expect(effortFor('anthropic', 'claude-opus-5-5', 't')).toMatchObject({ effective: 'xhigh', source: 'chat' });
+ });
+
+ it('survives a restart', () => {
+ setChatEffort('t', 'low');
+ resetChatEffortCache();
+ expect(effortFor('anthropic', 'claude-opus-5-5', 't').effective).toBe('low');
+ });
+});
diff --git a/src/providers/reasoning-discovery.ts b/src/providers/reasoning-discovery.ts
new file mode 100644
index 00000000..2e78d39f
--- /dev/null
+++ b/src/providers/reasoning-discovery.ts
@@ -0,0 +1,96 @@
+/**
+ * Ask an OpenAI-compatible server which models take a reasoning effort,
+ * where it can say (see utils/reasoning-caps.ts for how the answer is used):
+ *
+ * Ollama POST /api/show → capabilities includes "thinking"
+ * (gpt-oss takes low/medium/high; other thinking models on/off)
+ * LiteLLM GET /model/info → model_info.supports_reasoning
+ * OpenRouter GET /api/v1/models → supported_parameters includes "reasoning"
+ *
+ * Anything else has no way to tell: the model's name decides, and a 400
+ * from the server settles it (openai-compat.ts). Never throws; a slow or
+ * missing endpoint just leaves the guess in place.
+ */
+import type { ProviderConfig } from '../utils/config.js';
+import type { ReasoningLevel } from '../utils/model-prefs.js';
+import { isOpenRouterUrl } from '../utils/model-prefs.js';
+import { capsKnown, COMPAT_CHAT_PROVIDERS, rememberCaps } from '../utils/reasoning-caps.js';
+import { basicAuthHeaders } from './basic-auth.js';
+import { logger } from '../utils/logger.js';
+
+const TIMEOUT_MS = 2500;
+const inFlight = new Map<string, Promise<void>>();
+
+function root(baseUrl: string): string {
+ return baseUrl.replace(/\/+$/, '').replace(/\/v1$/i, '');
+}
+
+function authHeaders(pc: ProviderConfig): Record<string, string> {
+ const basic = basicAuthHeaders(pc);
+ if (basic) return basic;
+ return pc.apiKey ? { Authorization: `Bearer ${pc.apiKey}` } : {};
+}
+
+async function getJson(url: string, init: RequestInit, fetchImpl: typeof fetch): Promise<unknown> {
+ const ctrl = new AbortController();
+ const timer = setTimeout(() => ctrl.abort(), TIMEOUT_MS);
+ try {
+ const res = await fetchImpl(url, { ...init, signal: ctrl.signal });
+ if (!res.ok) return undefined;
+ return await res.json();
+ } catch {
+ return undefined;
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+/** What the server says about this model; undefined when it can't say. */
+export async function probeReasoningLevels(pc: ProviderConfig, model: string, fetchImpl: typeof fetch = globalThis.fetch): Promise<ReasoningLevel[] | undefined> {
+ if (!pc.baseUrl) return undefined;
+ if (pc.name === 'ollamaLocal' || pc.name === 'ollamaCloud') {
+ const info = await getJson(`${root(pc.baseUrl)}/api/show`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...authHeaders(pc) },
+ body: JSON.stringify({ model }),
+ }, fetchImpl) as { capabilities?: unknown } | undefined;
+ if (!info || !Array.isArray(info.capabilities)) return undefined;
+ if (!info.capabilities.includes('thinking')) return [];
+ return /gpt-oss/i.test(model) ? ['low', 'medium', 'high'] : ['off', 'high'];
+ }
+ if (isOpenRouterUrl(pc.baseUrl)) {
+ const list = await getJson('https://openrouter.ai/api/v1/models', { headers: authHeaders(pc) }, fetchImpl) as { data?: Array<{ id?: string; supported_parameters?: unknown }> } | undefined;
+ const entry = list?.data?.find((m) => m.id === model);
+ if (!entry || !Array.isArray(entry.supported_parameters)) return undefined;
+ return entry.supported_parameters.includes('reasoning') ? ['low', 'medium', 'high'] : [];
+ }
+ if (pc.name === 'litellm') {
+ const info = await getJson(`${root(pc.baseUrl)}/model/info`, { headers: authHeaders(pc) }, fetchImpl) as { data?: Array<{ model_name?: string; model_info?: { supports_reasoning?: unknown } }> } | undefined;
+ const entry = info?.data?.find((m) => m.model_name === model);
+ const supports = entry?.model_info?.supports_reasoning;
+ if (typeof supports !== 'boolean') return undefined;
+ return supports ? ['low', 'medium', 'high'] : [];
+ }
+ return undefined;
+}
+
+/**
+ * Learn this model's levels from its server once a day (no-op where the
+ * server can't say, or it is already known). Safe to call on every picker
+ * open: concurrent calls share one request.
+ */
+export async function discoverReasoningCaps(pc: ProviderConfig, model: string = pc.model, fetchImpl?: typeof fetch): Promise<void> {
+ if (!COMPAT_CHAT_PROVIDERS.has(pc.name) || !model || capsKnown(pc.name, model)) return;
+ const key = `${pc.name}::${model}`;
+ const running = inFlight.get(key);
+ if (running) return running;
+ const job = (async () => {
+ const levels = await probeReasoningLevels(pc, model, fetchImpl);
+ if (levels) {
+ rememberCaps(pc.name, model, levels, 'discovered');
+ logger.debug({ provider: pc.name, model, levels }, 'Reasoning levels discovered');
+ }
+ })().finally(() => inFlight.delete(key));
+ inFlight.set(key, job);
+ return job;
+}
diff --git a/src/providers/reasoning-wire.test.ts b/src/providers/reasoning-wire.test.ts
new file mode 100644
index 00000000..bca16037
--- /dev/null
+++ b/src/providers/reasoning-wire.test.ts
@@ -0,0 +1,184 @@
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { createAnthropic } from '@ai-sdk/anthropic';
+import { createOpenAI } from '@ai-sdk/openai';
+import { streamText } from 'ai';
+import { foldReasoningChunk, foldReasoningMessage, reasoningAsThinkTags, withAnthropicThinking, withThinkTagReasoning } from './reasoning-wire.js';
+import { anthropicThinkingOptions, claudeThinking, reasoningLevelsFor, resetModelPrefsCache, setModelPref } from '../utils/model-prefs.js';
+
+/**
+ * Reasoning reaches the screen only if the request asks for it (Claude) or
+ * the reply's non-standard field is carried through (Chat Completions).
+ * These run the real AI SDK providers against a fake fetch and check the
+ * wire bodies and the parts that come out.
+ */
+
+let home: string;
+const previousHome = process.env.MERCURY_HOME;
+beforeEach(() => {
+ home = mkdtempSync(join(tmpdir(), 'mercury-reasoning-'));
+ process.env.MERCURY_HOME = home;
+ resetModelPrefsCache();
+});
+afterEach(() => {
+ resetModelPrefsCache();
+ if (previousHome === undefined) delete process.env.MERCURY_HOME;
+ else process.env.MERCURY_HOME = previousHome;
+ rmSync(home, { recursive: true, force: true });
+});
+
+describe('Claude thinking rules', () => {
+ it.each([
+ ['claude-opus-5-5', true, ['low', 'medium', 'high', 'xhigh', 'max']],
+ ['claude-sonnet-5-5', true, ['low', 'medium', 'high', 'xhigh', 'max']],
+ ['claude-haiku-5-5', true, ['low', 'medium', 'high', 'xhigh', 'max']],
+ ['claude-sonnet-5', true, ['low', 'medium', 'high', 'xhigh', 'max']],
+ ['claude-fable-5-1', true, ['low', 'medium', 'high', 'xhigh', 'max']],
+ ['claude-opus-4-8', false, ['low', 'medium', 'high', 'xhigh', 'max']],
+ ['claude-opus-4-7', false, ['low', 'medium', 'high', 'xhigh', 'max']],
+ ['claude-opus-4-6', false, ['low', 'medium', 'high', 'max']],
+ ['claude-sonnet-4-6', false, ['low', 'medium', 'high', 'max']],
+ ['anthropic/claude-opus-5-5', true, ['low', 'medium', 'high', 'xhigh', 'max']],
+ ] as const)('%s', (model, byDefault, levels) => {
+ expect(claudeThinking(model)).toEqual({ thinksByDefault: byDefault, adaptive: true, levels });
+ expect(reasoningLevelsFor('anthropic', model)).toEqual(levels);
+ });
+
+ it.each(['claude-haiku-4-5', 'claude-sonnet-4-5', 'claude-opus-4-5', 'claude-3-7-sonnet-latest', 'claude-sonnet-4-20250514', 'gpt-5'])('%s: nothing sent, no levels', (model) => {
+ expect(claudeThinking(model).adaptive).toBe(false);
+ expect(reasoningLevelsFor('anthropic', model)).toEqual([]);
+ expect(anthropicThinkingOptions(model, 'high')).toBeUndefined();
+ });
+
+ it('models that think anyway always get a summary; opt-in models only with an effort', () => {
+ expect(anthropicThinkingOptions('claude-opus-5-5', undefined)).toEqual({ thinking: { type: 'adaptive', display: 'summarized' } });
+ expect(anthropicThinkingOptions('claude-opus-5-5', 'low')).toEqual({ thinking: { type: 'adaptive', display: 'summarized' }, effort: 'low' });
+ expect(anthropicThinkingOptions('claude-opus-4-8', undefined)).toBeUndefined();
+ expect(anthropicThinkingOptions('claude-opus-4-8', 'xhigh')).toEqual({ thinking: { type: 'adaptive', display: 'summarized' }, effort: 'xhigh' });
+ // 4.6 has no xhigh: an effort it can't take is not sent.
+ expect(anthropicThinkingOptions('claude-opus-4-6', 'xhigh')).toBeUndefined();
+ });
+});
+
+function anthropicSse(): Response {
+ const usage = { input_tokens: 10, output_tokens: 5 };
+ const events = [
+ { type: 'message_start', message: { id: 'm1', type: 'message', role: 'assistant', model: 'claude-opus-5-5', content: [], stop_reason: null, usage } },
+ { type: 'content_block_start', index: 0, content_block: { type: 'thinking', thinking: '', signature: '' } },
+ { type: 'content_block_delta', index: 0, delta: { type: 'thinking_delta', thinking: 'Weighing the options.' } },
+ { type: 'content_block_delta', index: 0, delta: { type: 'signature_delta', signature: 'sig' } },
+ { type: 'content_block_stop', index: 0 },
+ { type: 'content_block_start', index: 1, content_block: { type: 'text', text: '' } },
+ { type: 'content_block_delta', index: 1, delta: { type: 'text_delta', text: 'Hello' } },
+ { type: 'content_block_stop', index: 1 },
+ { type: 'message_delta', delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 5 } },
+ { type: 'message_stop' },
+ ];
+ const body = events.map((e) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join('');
+ return new Response(body, { status: 200, headers: { 'content-type': 'text/event-stream' } });
+}
+
+describe('Anthropic requests', () => {
+ async function wireBody(model: string): Promise<{ body: Record<string, any>; reasoning: string }> {
+ let body: Record<string, any> = {};
+ const anthropic = createAnthropic({
+ apiKey: 'k',
+ fetch: (async (_url: unknown, init?: RequestInit) => { body = JSON.parse(String(init?.body)); return anthropicSse(); }) as typeof fetch,
+ });
+ const result = streamText({ model: withAnthropicThinking(anthropic(model), 'anthropic', model), prompt: 'hi' });
+ let reasoning = '';
+ for await (const part of result.fullStream) if (part.type === 'reasoning-delta') reasoning += part.text;
+ return { body, reasoning };
+ }
+
+ it('asks Claude 5 models for summarized thinking and streams it as reasoning', async () => {
+ const { body, reasoning } = await wireBody('claude-opus-5-5');
+ expect(body.thinking).toEqual({ type: 'adaptive', display: 'summarized' });
+ expect(body.output_config).toBeUndefined();
+ expect(reasoning).toBe('Weighing the options.');
+ });
+
+ it("sends the owner's effort, read on every request", async () => {
+ setModelPref('anthropic', 'claude-opus-5-5', { reasoning: 'max' });
+ const { body } = await wireBody('claude-opus-5-5');
+ expect(body.output_config).toEqual({ effort: 'max' });
+ });
+
+ it('leaves opt-in models untouched on Auto', async () => {
+ const { body } = await wireBody('claude-opus-4-8');
+ expect(body.thinking).toBeUndefined();
+ expect(body.output_config).toBeUndefined();
+ });
+});
+
+describe('Chat Completions reasoning fields', () => {
+ it('folds reasoning deltas into a think block closed by the answer', () => {
+ const open = new Map<number, boolean>();
+ const a = { choices: [{ index: 0, delta: { reasoning_content: 'Let me ' } }] };
+ const b = { choices: [{ index: 0, delta: { reasoning: 'think.' } }] };
+ const c = { choices: [{ index: 0, delta: { content: 'Answer' } }] };
+ foldReasoningChunk(a, open);
+ foldReasoningChunk(b, open);
+ foldReasoningChunk(c, open);
+ expect([a, b, c].map((x) => x.choices[0].delta)).toEqual([
+ { content: '<think>Let me ' },
+ { content: 'think.' },
+ { content: '</think>Answer' },
+ ]);
+ });
+
+ it('closes the block on a tool call or the end of the choice', () => {
+ const open = new Map<number, boolean>();
+ foldReasoningChunk({ choices: [{ index: 0, delta: { reasoning_content: 'plan' } }] }, open);
+ const tool = { choices: [{ index: 0, delta: { tool_calls: [{ index: 0, id: 'c1', function: { name: 'x', arguments: '{}' } }] } }] };
+ foldReasoningChunk(tool, open);
+ expect((tool.choices[0].delta as Record<string, unknown>).content).toBe('</think>');
+ foldReasoningChunk({ choices: [{ index: 0, delta: { reasoning: 'more' } }] }, open);
+ const end = { choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] };
+ foldReasoningChunk(end, open);
+ expect((end.choices[0].delta as Record<string, unknown>).content).toBe('</think>');
+ });
+
+ it('leaves ordinary chunks alone', () => {
+ const chunk = { choices: [{ index: 0, delta: { content: 'plain' } }] };
+ expect(foldReasoningChunk(chunk, new Map())).toBe(false);
+ expect(chunk.choices[0].delta).toEqual({ content: 'plain' });
+ });
+
+ it('puts a non-streamed reasoning field in front of the content', () => {
+ const body = { choices: [{ message: { role: 'assistant', content: 'Hi', reasoning_content: 'why' } }] };
+ expect(foldReasoningMessage(body)).toBe(true);
+ expect(body.choices[0].message).toEqual({ role: 'assistant', content: '<think>why</think>Hi' });
+ });
+
+ it('end to end: an Ollama-style stream comes out as reasoning parts and clean text', async () => {
+ const chunks = [
+ { id: 'c', object: 'chat.completion.chunk', created: 1, model: 'm', choices: [{ index: 0, delta: { role: 'assistant', reasoning: 'Thinking it ' } }] },
+ { id: 'c', object: 'chat.completion.chunk', created: 1, model: 'm', choices: [{ index: 0, delta: { reasoning: 'over.' } }] },
+ { id: 'c', object: 'chat.completion.chunk', created: 1, model: 'm', choices: [{ index: 0, delta: { content: 'The answer.' } }] },
+ { id: 'c', object: 'chat.completion.chunk', created: 1, model: 'm', choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] },
+ ];
+ // Split mid-line to exercise the line buffer.
+ const raw = chunks.map((c) => `data: ${JSON.stringify(c)}\n\n`).join('') + 'data: [DONE]\n\n';
+ const cut = Math.floor(raw.length / 2);
+ const fakeFetch = (async () => new Response(new ReadableStream({
+ start(controller) {
+ controller.enqueue(new TextEncoder().encode(raw.slice(0, cut)));
+ controller.enqueue(new TextEncoder().encode(raw.slice(cut)));
+ controller.close();
+ },
+ }), { status: 200, headers: { 'content-type': 'text/event-stream' } })) as typeof fetch;
+ const openai = createOpenAI({ apiKey: 'k', baseURL: 'http://localhost:1/v1', fetch: reasoningAsThinkTags(fakeFetch) });
+ const result = streamText({ model: withThinkTagReasoning(openai.chat('qwen3')), prompt: 'hi' });
+ let reasoning = '';
+ let text = '';
+ for await (const part of result.fullStream) {
+ if (part.type === 'reasoning-delta') reasoning += part.text;
+ if (part.type === 'text-delta') text += part.text;
+ }
+ expect(reasoning).toBe('Thinking it over.');
+ expect(text).toBe('The answer.');
+ });
+});
diff --git a/src/providers/reasoning-wire.ts b/src/providers/reasoning-wire.ts
new file mode 100644
index 00000000..f833433d
--- /dev/null
+++ b/src/providers/reasoning-wire.ts
@@ -0,0 +1,172 @@
+/**
+ * Getting a model's reasoning onto the screen, per wire format.
+ *
+ * - Anthropic: the request has to ask for it. Claude 5-era models think by
+ * default but return empty thinking blocks unless the request says
+ * display "summarized"; the owner's effort level rides on the same call.
+ * Applied per call (middleware), so a level changed in the desktop takes
+ * effect on the next request without rebuilding the provider.
+ * - Chat Completions servers (Ollama, LM Studio, vLLM, LiteLLM, llama.cpp…):
+ * reasoning arrives in a non-standard `reasoning_content` / `reasoning`
+ * field that the AI SDK's OpenAI chat parser ignores. The fetch below
+ * folds it into the content as <think>…</think>, and the SDK's
+ * extractReasoningMiddleware turns that back into proper reasoning parts.
+ * Models that already write <think> tags into their content are handled
+ * by the same middleware.
+ */
+import { extractReasoningMiddleware, wrapLanguageModel, type LanguageModelMiddleware } from 'ai';
+import { anthropicThinkingOptions, effectiveReasoning } from '../utils/model-prefs.js';
+
+/** The model type wrapLanguageModel takes and returns. */
+export type WireModel = Parameters<typeof wrapLanguageModel>[0]['model'];
+
+/** Anthropic: summarized thinking where the model thinks, plus the chosen effort. */
+export function anthropicThinkingMiddleware(providerName: string, model: string): LanguageModelMiddleware {
+ return {
+ specificationVersion: 'v3',
+ transformParams: async ({ params }) => {
+ const extra = anthropicThinkingOptions(model, effectiveReasoning(providerName, model));
+ if (!extra) return params;
+ const providerOptions = (params.providerOptions ?? {}) as Record<string, Record<string, unknown>>;
+ const anthropic = providerOptions.anthropic ?? {};
+ return {
+ ...params,
+ providerOptions: {
+ ...providerOptions,
+ // A caller's explicit thinking/effort wins.
+ anthropic: { ...extra, ...anthropic },
+ },
+ } as typeof params;
+ },
+ };
+}
+
+export function withAnthropicThinking(model: WireModel, providerName: string, modelId: string): WireModel {
+ return wrapLanguageModel({ model, middleware: anthropicThinkingMiddleware(providerName, modelId) });
+}
+
+const THINK_OPEN = '<think>';
+const THINK_CLOSE = '</think>';
+
+function reasoningOf(part: Record<string, unknown> | undefined): string | undefined {
+ if (!part) return undefined;
+ for (const key of ['reasoning_content', 'reasoning'] as const) {
+ const value = part[key];
+ if (typeof value === 'string') {
+ delete part[key];
+ if (value) return value;
+ }
+ }
+ return undefined;
+}
+
+/**
+ * Rewrite one parsed streaming chunk in place. `open` tracks, per choice,
+ * whether a <think> block is currently open. Returns true if it changed.
+ */
+export function foldReasoningChunk(chunk: unknown, open: Map<number, boolean>): boolean {
+ const choices = (chunk as { choices?: unknown })?.choices;
+ if (!Array.isArray(choices)) return false;
+ let changed = false;
+ for (const raw of choices) {
+ const choice = raw as { index?: number; delta?: Record<string, unknown>; finish_reason?: unknown };
+ const idx = typeof choice.index === 'number' ? choice.index : 0;
+ const delta = choice.delta;
+ const reasoning = reasoningOf(delta);
+ if (reasoning !== undefined || (delta && ('reasoning_content' in delta || 'reasoning' in delta))) changed = true;
+ const content = typeof delta?.content === 'string' ? delta.content : '';
+ const hasToolCalls = Array.isArray(delta?.tool_calls) && delta!.tool_calls.length > 0;
+ let prefix = '';
+ if (reasoning) {
+ prefix = (open.get(idx) ? '' : THINK_OPEN) + reasoning;
+ open.set(idx, true);
+ }
+ // The answer, a tool call or the end of the choice closes the block.
+ if (open.get(idx) && (content || hasToolCalls || choice.finish_reason)) {
+ prefix += THINK_CLOSE;
+ open.set(idx, false);
+ }
+ if (prefix) {
+ if (!choice.delta) choice.delta = {};
+ choice.delta.content = prefix + content;
+ changed = true;
+ }
+ }
+ return changed;
+}
+
+/** Non-streaming response: put the reasoning in front of the content as a think block. */
+export function foldReasoningMessage(body: unknown): boolean {
+ const choices = (body as { choices?: unknown })?.choices;
+ if (!Array.isArray(choices)) return false;
+ let changed = false;
+ for (const raw of choices) {
+ const message = (raw as { message?: Record<string, unknown> }).message;
+ const reasoning = reasoningOf(message);
+ if (!message || !reasoning) continue;
+ const content = typeof message.content === 'string' ? message.content : '';
+ message.content = `${THINK_OPEN}${reasoning}${THINK_CLOSE}${content}`;
+ changed = true;
+ }
+ return changed;
+}
+
+function foldEventStream(body: ReadableStream<Uint8Array>): ReadableStream<Uint8Array> {
+ const decoder = new TextDecoder();
+ const encoder = new TextEncoder();
+ const open = new Map<number, boolean>();
+ let pending = '';
+ const rewriteLine = (line: string): string => {
+ const m = /^data:\s?(.*)$/.exec(line);
+ if (!m || m[1].trim() === '[DONE]' || !m[1].trim()) return line;
+ try {
+ const chunk = JSON.parse(m[1]);
+ return foldReasoningChunk(chunk, open) ? `data: ${JSON.stringify(chunk)}` : line;
+ } catch {
+ return line;
+ }
+ };
+ return body.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({
+ transform(bytes, controller) {
+ pending += decoder.decode(bytes, { stream: true });
+ const lines = pending.split('\n');
+ pending = lines.pop() ?? '';
+ if (lines.length) controller.enqueue(encoder.encode(lines.map(rewriteLine).join('\n') + '\n'));
+ },
+ flush(controller) {
+ pending += decoder.decode();
+ if (pending) controller.enqueue(encoder.encode(rewriteLine(pending)));
+ },
+ }));
+}
+
+/** fetch for Chat Completions providers that carries reasoning fields through as think tags. */
+export function reasoningAsThinkTags(base: typeof fetch = globalThis.fetch): typeof fetch {
+ return async (input, init) => {
+ const response = await base(input, init);
+ if (!response.ok || !response.body) return response;
+ const type = response.headers.get('content-type') ?? '';
+ if (type.includes('text/event-stream')) {
+ const headers = new Headers(response.headers);
+ headers.delete('content-length');
+ return new Response(foldEventStream(response.body), { status: response.status, statusText: response.statusText, headers });
+ }
+ if (type.includes('application/json')) {
+ const text = await response.text();
+ let out = text;
+ try {
+ const parsed = JSON.parse(text);
+ if (foldReasoningMessage(parsed)) out = JSON.stringify(parsed);
+ } catch { /* not JSON after all — pass it on untouched */ }
+ const headers = new Headers(response.headers);
+ headers.delete('content-length');
+ return new Response(out, { status: response.status, statusText: response.statusText, headers });
+ }
+ return response;
+ };
+}
+
+/** A Chat Completions model whose <think> blocks come out as reasoning parts. */
+export function withThinkTagReasoning(model: WireModel): WireModel {
+ return wrapLanguageModel({ model, middleware: extractReasoningMiddleware({ tagName: 'think' }) });
+}
diff --git a/src/utils/manual.ts b/src/utils/manual.ts
index 796bb5d2..de2f2885 100644
--- a/src/utils/manual.ts
+++ b/src/utils/manual.ts
@@ -98,6 +98,10 @@ export const CHAT_COMMAND_HELP: ReadonlyArray<readonly [string, string]> = [
['/permissions', 'Change permission mode (Ask Me / Allow All)'],
['/models', 'List configured providers and their models'],
['/models use <provider>', 'Switch the default model (saved across restarts)'],
+ ['/effort', 'Show the thinking effort in this chat and the levels the model takes'],
+ ['/effort <auto|low|medium|high|xhigh|max>', 'Set the thinking effort for this chat only'],
+ ['/effort default', "Go back to the model's default effort in this chat"],
+ ['/effort global <level>', "Change the model's default effort (every chat without its own)"],
['/cloud models', 'List Mercury Cloud models for your tier'],
['/cloud use <model-id>', 'Switch to a Mercury Cloud model'],
['/view', 'Toggle progress view (balanced/detailed)'],
@@ -396,6 +400,7 @@ export function getTelegramHelp(): string {
lines.push('/update ignore — Silence the offered update notice');
lines.push('/permissions — Switch Ask Me / Allow All mode');
lines.push('/models — List providers or switch AI model (saved across restarts)');
+ lines.push('/effort — Show or set how hard the current model thinks');
lines.push('/cloud models — List Mercury Cloud models and switch');
lines.push('/stream — Toggle text streaming on/off');
lines.push("/stop — Stop this chat's task, its agents and waiting messages now (other chats keep going)");
@@ -514,6 +519,7 @@ export function getDiscordHelp(): string {
lines.push('/update ignore \u2014 Silence the offered update notice');
lines.push('/permissions \u2014 Switch Ask Me / Allow All mode');
lines.push('/models \u2014 List providers or switch AI model (saved across restarts)');
+ lines.push('/effort \u2014 Show or set how hard the current model thinks');
lines.push('/cloud models \u2014 List Mercury Cloud models and switch');
lines.push('/stop \u2014 Stop the current task and its agents now');
lines.push('/halt \u2014 Emergency: stop all agents and clear the queue');
diff --git a/src/utils/model-prefs.test.ts b/src/utils/model-prefs.test.ts
index c3c0ba9d..f66f4b12 100644
--- a/src/utils/model-prefs.test.ts
+++ b/src/utils/model-prefs.test.ts
@@ -88,6 +88,21 @@ describe('reasoning', () => {
expect(body.reasoning_effort).toBe('none');
});
+ it('asks the Responses API for a reasoning summary where wanted, never with Off', () => {
+ const body: Record<string, unknown> = { input: [] };
+ applyReasoningToBody(body, undefined, { summary: true });
+ expect(body.reasoning).toEqual({ summary: 'auto' });
+ const withLevel: Record<string, unknown> = { input: [], reasoning: { summary: 'detailed' } };
+ applyReasoningToBody(withLevel, 'low', { summary: true });
+ expect(withLevel.reasoning).toEqual({ summary: 'detailed', effort: 'low' });
+ const off: Record<string, unknown> = { input: [] };
+ applyReasoningToBody(off, 'off', { summary: true });
+ expect(off.reasoning).toEqual({ effort: 'none' });
+ const chat: Record<string, unknown> = { messages: [] };
+ applyReasoningToBody(chat, undefined, { summary: true });
+ expect(chat).toEqual({ messages: [] });
+ });
+
it('leaves the body alone on auto', () => {
const body: Record<string, unknown> = { messages: [] };
applyReasoningToBody(body, undefined);
diff --git a/src/utils/model-prefs.ts b/src/utils/model-prefs.ts
index 7899783c..b2828d27 100644
--- a/src/utils/model-prefs.ts
+++ b/src/utils/model-prefs.ts
@@ -10,8 +10,10 @@
import { existsSync, readFileSync, writeFileSync, renameSync } from 'node:fs';
import { join } from 'node:path';
import { getMercuryHome } from './config.js';
+import { ScopedValue } from './turn-scope.js';
+import { cachedCaps, heuristicLevels } from './reasoning-caps.js';
-export type ReasoningLevel = 'off' | 'low' | 'medium' | 'high';
+export type ReasoningLevel = 'off' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';
export interface ModelPref {
/** User-chosen display name; absent means use the generated one. */
@@ -20,7 +22,7 @@ export interface ModelPref {
reasoning?: ReasoningLevel;
}
-const REASONING_LEVELS: readonly ReasoningLevel[] = ['off', 'low', 'medium', 'high'];
+const REASONING_LEVELS: readonly ReasoningLevel[] = ['off', 'low', 'medium', 'high', 'xhigh', 'max'];
const MAX_LABEL_LENGTH = 80;
/** Same bound Agent.switchProvider applies to model ids. */
const MAX_REF_LENGTH = 256;
@@ -128,28 +130,202 @@ export function resetModelPrefsCache(): void {
/** OpenAI API models that accept a reasoning effort: o-series and GPT-5 family. */
const OPENAI_REASONING_MODEL = /^(o\d|gpt-5)/i;
-/** Providers with any reasoning control (decides whether to hook requests at all). */
+/** Providers with their own request path (no OpenAI-style effort field from here). */
+const OWN_WIRE = new Set(['anthropic', 'deepseek', 'mercuryCloud', 'mimo', 'mimoTokenPlan', 'githubCopilot']);
+
+/**
+ * Providers whose requests go through the OpenAI-style hook (decides whether
+ * to hook requests at all; the hook changes a body only when the model has
+ * levels and one is chosen).
+ */
export function providerHasReasoningControl(provider: string): boolean {
- return ['chatgptWeb', 'openai', 'ollamaLocal', 'ollamaCloud'].includes(provider);
+ return !OWN_WIRE.has(provider);
+}
+
+/**
+ * What a Claude model does with thinking, from its id (any prefix or date
+ * suffix: "claude-opus-5-5", "anthropic/claude-sonnet-4-6-2026…").
+ *
+ * - thinksByDefault: Claude 5-era models (Opus/Sonnet/Haiku 5+, Fable,
+ * Mythos) run adaptive thinking whether or not it is asked for, and some
+ * reject turning it off. Their thinking text is "omitted" unless the
+ * request asks for a summary.
+ * - adaptive: accepts thinking {type: "adaptive"} (4.6 and later). Older
+ * models (4.5, 3.x) only take a token budget, which Mercury does not send.
+ * - levels: output_config.effort values the model accepts. "xhigh" arrived
+ * with Opus 4.7; 4.6 has low…high plus max.
+ */
+export interface ClaudeThinking {
+ thinksByDefault: boolean;
+ adaptive: boolean;
+ levels: ReasoningLevel[];
+}
+
+const NO_CLAUDE_THINKING: ClaudeThinking = { thinksByDefault: false, adaptive: false, levels: [] };
+
+export function claudeThinking(model: string): ClaudeThinking {
+ const id = model.toLowerCase();
+ if (/claude-(fable|mythos)\b/.test(id)) {
+ return { thinksByDefault: true, adaptive: true, levels: ['low', 'medium', 'high', 'xhigh', 'max'] };
+ }
+ const m = /claude-(opus|sonnet|haiku)-(\d+)(?:[-.](\d)(?!\d))?/.exec(id);
+ if (!m) return NO_CLAUDE_THINKING;
+ const family = m[1];
+ const version = Number(m[2]) + (m[3] ? Number(m[3]) / 10 : 0);
+ if (version >= 5) return { thinksByDefault: true, adaptive: true, levels: ['low', 'medium', 'high', 'xhigh', 'max'] };
+ if (version >= 4.7 && family === 'opus') return { thinksByDefault: false, adaptive: true, levels: ['low', 'medium', 'high', 'xhigh', 'max'] };
+ if (version >= 4.6 && family !== 'haiku') return { thinksByDefault: false, adaptive: true, levels: ['low', 'medium', 'high', 'max'] };
+ return NO_CLAUDE_THINKING;
}
/**
* Levels a model can honour. ChatGPT/OpenAI models may reject "none", so they
* get no Off; Ollama maps Off to reasoning_effort "none" (thinking off). On
* the OpenAI API only reasoning models accept an effort at all: gpt-4o or
- * gpt-4.1 would answer 400 "Unsupported parameter". Anything else: none.
+ * gpt-4.1 would answer 400 "Unsupported parameter". Claude gets the efforts
+ * its model accepts and no Off (Opus 5.5 rejects disabling thinking; on
+ * older models "not set" already means no thinking). Anything else: none.
*/
export function reasoningLevelsFor(provider: string, model?: string): ReasoningLevel[] {
if (provider === 'chatgptWeb') return ['low', 'medium', 'high'];
- if (provider === 'openai') return model && OPENAI_REASONING_MODEL.test(model) ? ['low', 'medium', 'high'] : [];
- if (provider === 'ollamaLocal' || provider === 'ollamaCloud') return ['off', 'low', 'medium', 'high'];
- return [];
+ if (provider === 'anthropic') return model ? claudeThinking(model).levels : [];
+ if (OWN_WIRE.has(provider)) return [];
+ const ollama = provider === 'ollamaLocal' || provider === 'ollamaCloud';
+ if (!model) return ollama ? ['off', 'low', 'medium', 'high'] : [];
+ // What the server said (or a 400 it answered) beats any guess (reasoning-caps.ts).
+ const known = cachedCaps(provider, model);
+ if (known) return known.levels;
+ if (provider === 'openai') return OPENAI_REASONING_MODEL.test(model) ? ['low', 'medium', 'high'] : [];
+ // Until Ollama has been asked: its own levels for gpt-oss, on/off for the rest.
+ if (ollama) return /gpt-oss/i.test(model) ? ['low', 'medium', 'high'] : ['off', 'low', 'medium', 'high'];
+ return heuristicLevels(model);
+}
+
+/** How a level reads on screen: "auto" → "Auto", "xhigh" → "Extra high". */
+export function effortLabel(level: string): string {
+ return ({ auto: 'Auto', off: 'Off', low: 'Low', medium: 'Medium', high: 'High', xhigh: 'Extra high', max: 'Max' } as Record<string, string>)[level] ?? level;
+}
+
+// ─── Per-chat effort (issue #188) ────────────────────────────────────────────
+
+/**
+ * A chat can override its model's effort ("/effort high" in that chat, the
+ * desktop's Effort picker). The running turn names its chat here, so every
+ * request it makes reads that chat's override. Kept in
+ * ~/.mercury/chat-effort.json, keyed by the chat (the turn's lane: a
+ * desktop thread id, "cli", or a channel conversation).
+ */
+const effortChat = new ScopedValue<string | undefined>(undefined);
+const MAX_CHAT_OVERRIDES = 1000;
+let chatEfforts: Record<string, ReasoningLevel | 'auto'> | null = null;
+
+function chatEffortPath(): string {
+ return join(getMercuryHome(), 'chat-effort.json');
+}
+
+function loadChatEfforts(): Record<string, ReasoningLevel | 'auto'> {
+ if (chatEfforts) return chatEfforts;
+ chatEfforts = Object.create(null) as Record<string, ReasoningLevel | 'auto'>;
+ try {
+ const raw = existsSync(chatEffortPath()) ? JSON.parse(readFileSync(chatEffortPath(), 'utf-8')) : {};
+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
+ for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
+ if (isValidModelRef(k) && (v === 'auto' || isReasoningLevel(v))) chatEfforts[k] = v;
+ }
+ }
+ } catch { /* unreadable: no overrides */ }
+ return chatEfforts;
}
-/** The saved level for a model, only if that model can still honour it. */
+/** The running turn's chat: its requests read this chat's override. */
+export function claimEffortChat(chatKey: string): void {
+ effortChat.claim(chatKey);
+}
+
+export function currentEffortChat(): string | undefined {
+ return effortChat.get();
+}
+
+export function getChatEffort(chatKey: string): ReasoningLevel | 'auto' | undefined {
+ return loadChatEfforts()[chatKey];
+}
+
+/** Set a chat's override; null clears it (back to the model's default). */
+export function setChatEffort(chatKey: string, level: ReasoningLevel | 'auto' | null): void {
+ if (!isValidModelRef(chatKey)) return;
+ const all = loadChatEfforts();
+ delete all[chatKey];
+ if (level) all[chatKey] = level;
+ const keys = Object.keys(all);
+ if (keys.length > MAX_CHAT_OVERRIDES) for (const k of keys.slice(0, keys.length - MAX_CHAT_OVERRIDES)) delete all[k];
+ const tmp = `${chatEffortPath()}.tmp`;
+ writeFileSync(tmp, JSON.stringify(all, null, 2), 'utf-8');
+ renameSync(tmp, chatEffortPath());
+}
+
+export interface EffortState {
+ /** What requests carry: undefined = nothing (the model decides). */
+ effective: ReasoningLevel | undefined;
+ /** Where it comes from: this chat's override, the model's default, or neither. */
+ source: 'chat' | 'model' | 'auto';
+ /** The model's saved default ("auto" when none). */
+ modelDefault: ReasoningLevel | 'auto';
+ /** This chat's override, if any. */
+ chat?: ReasoningLevel | 'auto';
+ /** The chat asked for a level this model doesn't take: the model's default applies. */
+ chatUnsupported?: boolean;
+ levels: ReasoningLevel[];
+}
+
+/** The effort a request for this model carries in this chat, and why. */
+export function effortFor(provider: string, model: string, chatKey: string | undefined = effortChat.get()): EffortState {
+ const levels = reasoningLevelsFor(provider, model);
+ const saved = getModelPref(provider, model).reasoning;
+ const modelDefault = saved && levels.includes(saved) ? saved : undefined;
+ const chat = chatKey ? getChatEffort(chatKey) : undefined;
+ const base = { modelDefault: modelDefault ?? ('auto' as const), levels, ...(chat ? { chat } : {}) };
+ if (chat === 'auto' && levels.length) return { ...base, effective: undefined, source: 'chat' };
+ if (chat && chat !== 'auto') {
+ if (levels.includes(chat)) return { ...base, effective: chat, source: 'chat' };
+ if (levels.length) return { ...base, effective: modelDefault, source: modelDefault ? 'model' : 'auto', chatUnsupported: true };
+ }
+ return { ...base, effective: modelDefault, source: modelDefault ? 'model' : 'auto' };
+}
+
+/** The level a request for this model carries (the running chat's override, else the model's default). */
export function effectiveReasoning(provider: string, model: string): ReasoningLevel | undefined {
- const level = getModelPref(provider, model).reasoning;
- return level && reasoningLevelsFor(provider, model).includes(level) ? level : undefined;
+ return effortFor(provider, model).effective;
+}
+
+/** Test hook. */
+export function resetChatEffortCache(): void {
+ chatEfforts = null;
+}
+
+/** Is this an OpenRouter endpoint (its effort goes in `reasoning: {effort}`)? */
+export function isOpenRouterUrl(baseUrl: string | undefined): boolean {
+ return !!baseUrl && /(^|\/\/|\.)openrouter\.ai(\/|:|$)/i.test(baseUrl);
+}
+
+/**
+ * Anthropic provider options for one request: show the thinking (as the
+ * API's summary) wherever the model thinks, and apply the chosen effort.
+ *
+ * - Models that think by default always get display "summarized": the
+ * thinking happens and is billed either way; without it the stream carries
+ * empty thinking blocks and the screen shows a long silent pause.
+ * - Models where thinking is opt-in (4.6–4.8) think only when the owner
+ * picked an effort; "Auto" leaves the request exactly as before.
+ */
+export function anthropicThinkingOptions(model: string, level: ReasoningLevel | undefined): Record<string, unknown> | undefined {
+ const caps = claudeThinking(model);
+ if (!caps.adaptive) return undefined;
+ const effort = level && caps.levels.includes(level) ? level : undefined;
+ if (!caps.thinksByDefault && !effort) return undefined;
+ return {
+ thinking: { type: 'adaptive', display: 'summarized' },
+ ...(effort ? { effort } : {}),
+ };
}
/**
@@ -157,15 +333,30 @@ export function effectiveReasoning(provider: string, model: string): ReasoningLe
* Done at the HTTP layer because the AI SDK drops reasoningEffort for model
* ids it doesn't recognise as reasoning models (anything not o1/o3/o4/gpt-5*).
*/
-export function applyReasoningToBody(body: Record<string, unknown>, level: ReasoningLevel | undefined): void {
- if (!level) return;
+export function applyReasoningToBody(
+ body: Record<string, unknown>,
+ level: ReasoningLevel | undefined,
+ { summary = false, openRouter = false }: { summary?: boolean; openRouter?: boolean } = {},
+): void {
if (Array.isArray(body.input)) {
- // Responses API
+ // Responses API. A summary of the reasoning, where asked for, is what a
+ // screen can show while the model thinks (the raw reasoning never is).
+ if (!level && !summary) return;
const reasoning = (body.reasoning && typeof body.reasoning === 'object' ? body.reasoning : {}) as Record<string, unknown>;
- body.reasoning = { ...reasoning, effort: level === 'off' ? 'none' : level };
- } else if (Array.isArray(body.messages)) {
- // Chat Completions (Ollama's /v1 maps "none" to thinking off)
- body.reasoning_effort = level === 'off' ? 'none' : level;
+ body.reasoning = {
+ ...reasoning,
+ ...(level ? { effort: level === 'off' ? 'none' : level } : {}),
+ ...(summary && level !== 'off' && reasoning.summary === undefined ? { summary: 'auto' } : {}),
+ };
+ } else if (level && Array.isArray(body.messages)) {
+ if (openRouter) {
+ // OpenRouter's unified field, mapped to each upstream's own control.
+ const reasoning = (body.reasoning && typeof body.reasoning === 'object' ? body.reasoning : {}) as Record<string, unknown>;
+ body.reasoning = { ...reasoning, effort: level === 'off' ? 'none' : level };
+ } else {
+ // Chat Completions (Ollama's /v1 maps "none" to thinking off)
+ body.reasoning_effort = level === 'off' ? 'none' : level;
+ }
}
}
diff --git a/src/utils/reasoning-caps.ts b/src/utils/reasoning-caps.ts
new file mode 100644
index 00000000..8c3c93b7
--- /dev/null
+++ b/src/utils/reasoning-caps.ts
@@ -0,0 +1,113 @@
+/**
+ * Which effort levels a model behind an OpenAI-compatible server takes.
+ *
+ * Nothing in the OpenAI API says whether a model accepts reasoning_effort,
+ * so this is learned, in order of trust:
+ * 1. "rejected": the server answered 400 to a request carrying an effort.
+ * The request was resent without it, and none is sent again (expires
+ * after a week, in case the server is upgraded).
+ * 2. "discovered": the server said so. Ollama lists a model's
+ * capabilities, LiteLLM has supports_reasoning, OpenRouter lists each
+ * model's supported parameters (providers/reasoning-discovery.ts).
+ * 3. A known reasoning family by name (o-series, GPT-5, gpt-oss, Gemini
+ * 2.5+, Claude 4.6+, Grok 3 mini).
+ * Kept in ~/.mercury/reasoning-caps.json.
+ */
+import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { getMercuryHome } from './config.js';
+import type { ReasoningLevel } from './model-prefs.js';
+
+export type CapsSource = 'discovered' | 'rejected';
+
+export interface ReasoningCaps {
+ levels: ReasoningLevel[];
+ source: CapsSource;
+ at: number;
+}
+
+const DISCOVERED_TTL_MS = 24 * 60 * 60 * 1000;
+const REJECTED_TTL_MS = 7 * 24 * 60 * 60 * 1000;
+const MAX_ENTRIES = 500;
+const VALID: readonly ReasoningLevel[] = ['off', 'low', 'medium', 'high', 'xhigh', 'max'];
+
+/** Providers Mercury reaches over OpenAI Chat Completions (registry.ts). */
+export const COMPAT_CHAT_PROVIDERS: ReadonlySet<string> = new Set([
+ 'ollamaLocal', 'ollamaCloud', 'atomicChat', 'aimlapi', 'atlascloud', 'runcrate', 'cloudgpu', 'openaiCompat', 'litellm', 'lmStudio',
+]);
+
+let caps: Record<string, ReasoningCaps> | null = null;
+
+function path(): string {
+ return join(getMercuryHome(), 'reasoning-caps.json');
+}
+
+function key(provider: string, model: string): string {
+ return `${provider}::${model}`;
+}
+
+function load(): Record<string, ReasoningCaps> {
+ if (caps) return caps;
+ caps = Object.create(null) as Record<string, ReasoningCaps>;
+ try {
+ const raw = existsSync(path()) ? JSON.parse(readFileSync(path(), 'utf-8')) : {};
+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
+ for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
+ const c = v as Partial<ReasoningCaps> | null;
+ if (!c || (c.source !== 'discovered' && c.source !== 'rejected') || typeof c.at !== 'number' || !Array.isArray(c.levels)) continue;
+ caps[k] = { source: c.source, at: c.at, levels: c.levels.filter((l): l is ReasoningLevel => (VALID as readonly string[]).includes(l as string)) };
+ }
+ }
+ } catch { /* unreadable: start empty */ }
+ return caps;
+}
+
+function save(): void {
+ try {
+ const all = load();
+ const entries = Object.entries(all).sort((a, b) => b[1].at - a[1].at).slice(0, MAX_ENTRIES);
+ const tmp = `${path()}.tmp`;
+ writeFileSync(tmp, JSON.stringify(Object.fromEntries(entries), null, 2), 'utf-8');
+ renameSync(tmp, path());
+ } catch { /* best effort: the in-memory copy still applies */ }
+}
+
+/** What is known about this model, if still fresh. */
+export function cachedCaps(provider: string, model: string, now = Date.now()): ReasoningCaps | undefined {
+ const c = load()[key(provider, model)];
+ if (!c) return undefined;
+ const ttl = c.source === 'rejected' ? REJECTED_TTL_MS : DISCOVERED_TTL_MS;
+ return now - c.at > ttl ? undefined : c;
+}
+
+/** Is a fresh discovery result (or a rejection) already known? */
+export function capsKnown(provider: string, model: string): boolean {
+ return cachedCaps(provider, model) !== undefined;
+}
+
+export function rememberCaps(provider: string, model: string, levels: ReasoningLevel[], source: CapsSource, now = Date.now()): void {
+ const all = load();
+ // A server's own rejection outranks what it (or a name) suggested.
+ const prior = all[key(provider, model)];
+ if (source === 'discovered' && prior?.source === 'rejected' && now - prior.at <= REJECTED_TTL_MS) return;
+ all[key(provider, model)] = { levels, source, at: now };
+ save();
+}
+
+/** Test hook. */
+export function resetReasoningCapsCache(): void {
+ caps = null;
+}
+
+/**
+ * Known reasoning families that take the OpenAI reasoning_effort field
+ * (directly, or mapped by a gateway such as LiteLLM or OpenRouter).
+ */
+export function heuristicLevels(model: string): ReasoningLevel[] {
+ const id = model.toLowerCase();
+ if (/(^|[/:])(o[1-9])(-mini|-pro|-preview)?(\b|[-:])/.test(id) || /(^|[/:])gpt-5/.test(id) || /gpt-oss/.test(id)) return ['low', 'medium', 'high'];
+ if (/gemini-(2\.5|[3-9])/.test(id)) return ['low', 'medium', 'high'];
+ if (/claude-(opus|sonnet|haiku)-(4[-.][6-9]|[5-9])/.test(id) || /claude-(fable|mythos)/.test(id)) return ['low', 'medium', 'high'];
+ if (/grok-3-mini/.test(id)) return ['low', 'high'];
+ return [];
+}
diff --git a/src/web/api-contract.ts b/src/web/api-contract.ts
index 36e4fa54..fa10e1f3 100644
--- a/src/web/api-contract.ts
+++ b/src/web/api-contract.ts
@@ -59,6 +59,8 @@ export const API_FEATURES: readonly string[] = Object.freeze([
'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.effort', // POST /api/chat/effort, GET /api/chat/models?sessionId= current.effort — per-chat effort (#188)
+ 'chat.trace', // live step ids/durations, progress/phase events, message.trace on replies (ADR-041)
'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/chat.ts b/src/web/api/chat.ts
index 64234bf5..f6c86da9 100644
--- a/src/web/api/chat.ts
+++ b/src/web/api/chat.ts
@@ -19,9 +19,11 @@ import { basicAuthHeaders } from '../../providers/basic-auth.js';
import type { SessionRepository } from '../../sessions/index.js';
import { SessionTitleError } from '../../sessions/repository.js';
import { loadPermissionMode, savePermissionMode } from '../../capabilities/permission-mode-store.js';
+import { discoverReasoningCaps } from '../../providers/reasoning-discovery.js';
import {
getModelPref, setModelPref, humanizeModelName, modelGroupLabel,
reasoningLevelsFor, effectiveReasoning, isReasoningLevel, isValidModelRef, type ReasoningLevel,
+ effortFor, setChatEffort,
} from '../../utils/model-prefs.js';
let webChannel: WebChannel | null = null;
@@ -83,6 +85,7 @@ function toThread(session: ReturnType<SessionRepository['get']>, includeMessages
...(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) : {}),
+ ...(message.role === 'assistant' && message.metadata?.trace && typeof message.metadata.trace === 'object' ? { trace: message.metadata.trace } : {}),
...(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}` })) }
: {}),
@@ -554,6 +557,10 @@ chat.get('/api/chat/models', async (c) => {
const config = loadConfig();
const active = getActiveProviders(config);
const current = currentProviderFn ? currentProviderFn() : { name: config.providers.default || '', model: '' };
+ // An OpenAI-compatible server may say which models take an effort: ask
+ // about the current one before answering (bounded; cached for a day).
+ const currentPc = active.find((p) => p.name === current.name);
+ if (currentPc && current.model) await discoverReasoningCaps(currentPc, current.model).catch(() => undefined);
const entries: ({ name: string; model: string; available: boolean; isCurrent: boolean } & ReturnType<typeof describeModel>)[] = [];
const perProvider = await Promise.all(active.map((p) => listProviderModels(p)));
for (const [i, p] of active.entries()) {
@@ -569,7 +576,46 @@ chat.get('/api/chat/models', async (c) => {
});
}
}
- return c.json({ current: { ...current, ...describeModel(current.name, current.model) }, providers: entries });
+ // The chat's own effort (#188), when the screen says which chat it shows.
+ const sessionId = c.req.query('sessionId');
+ const chatKey = sessionId && isValidModelRef(sessionId) ? sessionId : undefined;
+ const effort = effortFor(current.name, current.model, chatKey);
+ return c.json({
+ current: {
+ ...current,
+ ...describeModel(current.name, current.model),
+ effort: {
+ effective: effort.effective ?? 'auto',
+ source: effort.source,
+ modelDefault: effort.modelDefault,
+ chat: effort.chat ?? null,
+ ...(effort.chatUnsupported ? { chatUnsupported: true } : {}),
+ },
+ },
+ providers: entries,
+ });
+});
+
+/**
+ * One chat's effort override (#188): a level this model takes, "auto" (let
+ * the model decide, whatever the default), or null to use the model's
+ * default again.
+ */
+chat.post('/api/chat/effort', async (c) => {
+ const body = await c.req.json<Record<string, unknown>>().catch(() => null);
+ if (!body || !isValidModelRef(body.sessionId)) return c.json({ error: 'sessionId is required' }, 400);
+ const level = body.level;
+ if (level !== null && level !== undefined && typeof level !== 'string') return c.json({ error: 'level must be a string or null' }, 400);
+ const config = loadConfig();
+ const current = currentProviderFn ? currentProviderFn() : { name: config.providers.default || '', model: '' };
+ if (typeof level === 'string' && level !== 'auto' && level !== 'default') {
+ if (!isReasoningLevel(level) || !reasoningLevelsFor(current.name, current.model).includes(level)) {
+ return c.json({ error: `${humanizeModelName(current.model)} doesn't take the effort '${level}'` }, 400);
+ }
+ }
+ setChatEffort(body.sessionId, level === null || level === undefined || level === 'default' ? null : (level as ReasoningLevel | 'auto'));
+ const effort = effortFor(current.name, current.model, body.sessionId);
+ return c.json({ ok: true, effort: { effective: effort.effective ?? 'auto', source: effort.source, modelDefault: effort.modelDefault, chat: effort.chat ?? null } });
});
/** Rename a model (label) and/or set its reasoning level. null / '' / 'auto' resets. */
diff --git a/src/web/api/model-prefs-route.test.ts b/src/web/api/model-prefs-route.test.ts
index 24d52c5c..50e109c7 100644
--- a/src/web/api/model-prefs-route.test.ts
+++ b/src/web/api/model-prefs-route.test.ts
@@ -100,3 +100,31 @@ describe('GET /api/chat/models', () => {
}
});
});
+
+describe('POST /api/chat/effort (#188)', () => {
+ const effort = (body: unknown) => chat.request('http://127.0.0.1/api/chat/effort', {
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
+ });
+
+ it("sets one chat's effort, reports it with the model's, and clears it", async () => {
+ const { setCurrentProviderCallback } = await import('./chat.js');
+ const prefs = await import('../../utils/model-prefs.js');
+ prefs.resetChatEffortCache();
+ setCurrentProviderCallback(() => ({ name: 'ollamaLocal', model: 'qwen3.8:27b' }));
+
+ const set = await effort({ sessionId: 'thread-1', level: 'high' });
+ expect(set.status).toBe(200);
+ expect(((await set.json()) as { effort: unknown }).effort).toMatchObject({ effective: 'high', source: 'chat', chat: 'high' });
+
+ const models = await (await chat.request('http://127.0.0.1/api/chat/models?sessionId=thread-1')).json() as { current: { effort: unknown } };
+ expect(models.current.effort).toMatchObject({ effective: 'high', source: 'chat' });
+ const other = await (await chat.request('http://127.0.0.1/api/chat/models?sessionId=thread-2')).json() as { current: { effort: unknown } };
+ expect(other.current.effort).toMatchObject({ source: 'auto', chat: null });
+
+ expect((await effort({ sessionId: 'thread-1', level: 'max' })).status).toBe(400);
+ expect((await effort({ level: 'high' })).status).toBe(400);
+
+ const cleared = await (await effort({ sessionId: 'thread-1', level: null })).json() as { effort: unknown };
+ expect(cleared.effort).toMatchObject({ source: 'auto', chat: null });
+ });
+});
diff --git a/ui/src/components/chat/ModelSwitcher.tsx b/ui/src/components/chat/ModelSwitcher.tsx
index aa5b0151..c881e78a 100644
--- a/ui/src/components/chat/ModelSwitcher.tsx
+++ b/ui/src/components/chat/ModelSwitcher.tsx
@@ -24,7 +24,9 @@ const REASONING_COPY: Record<ReasoningChoice, { title: string; hint: string }> =
off: { title: "Off", hint: "Fastest: answers without thinking first" },
low: { title: "Light", hint: "A quick think: good for simple tasks" },
medium: { title: "Balanced", hint: "A good mix of speed and depth" },
- high: { title: "Deep", hint: "Thinks hardest: slower, best for tricky work" },
+ high: { title: "Deep", hint: "Thinks it through: slower, best for tricky work" },
+ xhigh: { title: "Extra deep", hint: "For hard coding and long agent work" },
+ max: { title: "Max", hint: "Thinks hardest: slowest and most thorough" },
};
const keyOf = (p: { name: string; model: string }) => `${p.name}::${p.model}`;
diff --git a/ui/src/hooks/useSSE.ts b/ui/src/hooks/useSSE.ts
index c2178a7c..67ffcbed 100644
--- a/ui/src/hooks/useSSE.ts
+++ b/ui/src/hooks/useSSE.ts
@@ -115,6 +115,20 @@ export function useSSE(): SSEResult {
}
});
+ // A note while the turn keeps working ("Checking my work…"): shown, but the turn goes on.
+ es.addEventListener("progress", (e) => {
+ try {
+ const data = JSON.parse((e as MessageEvent).data);
+ if (typeof data.text !== "string" || !data.text.trim()) return;
+ store.getState().addMessage({
+ id: crypto.randomUUID(),
+ role: "assistant",
+ content: data.text,
+ timestamp: new Date().toISOString(),
+ });
+ } catch { /* ignore */ }
+ });
+
es.addEventListener("permission_request", (e) => {
try {
const data = JSON.parse((e as MessageEvent).data);
diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts
index a785e763..25651c41 100644
--- a/ui/src/lib/api.ts
+++ b/ui/src/lib/api.ts
@@ -686,7 +686,7 @@ export interface ToolStep {
result?: string;
}
-export type ReasoningLevel = "off" | "low" | "medium" | "high";
+export type ReasoningLevel = "off" | "low" | "medium" | "high" | "xhigh" | "max";
export type ReasoningChoice = ReasoningLevel | "auto";
/** Plain-language view of a model (see src/utils/model-prefs.ts). */
diff --git a/website/docs/cli-commands/in-chat-commands.mdx b/website/docs/cli-commands/in-chat-commands.mdx
index 098d366d..8eb7ac30 100644
--- a/website/docs/cli-commands/in-chat-commands.mdx
+++ b/website/docs/cli-commands/in-chat-commands.mdx
@@ -16,6 +16,10 @@ Type these during a conversation with Mercury. Most work in both CLI and Telegra
| `/permissions` | Change permission mode (Ask Me / Allow All) |
| `/models` | List configured models/providers for this session |
| `/models use <provider>` | Switch the current session model/provider |
+| `/effort` | Show the thinking effort in this chat, where it comes from (this chat or the model's default) and the levels the model takes |
+| `/effort <level>` | Set the effort for this chat only: `auto`, `low`, `medium`, `high`, and `off`/`xhigh`/`max` where the model takes them |
+| `/effort default` | Clear this chat's effort and use the model's default again |
+| `/effort global <level>` | Change the model's default effort, used by every chat without its own (Mercury Desktop: the Effort picker's last item) |
| `/tools` | List all currently loaded tools |
| `/mcp` | Show [MCP servers](../integrations/mcp) and whether they are connected |
| `/mcp tools <server>` | List an MCP server's tools and which ones the agent may use |