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(research): one visible run — live progress, failures with reasons, a report even when cut short

Salman Qureshi558572d73a3a
diff --git a/DECISIONS.md b/DECISIONS.md
index 2848fcd2..41181db3 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -326,3 +326,15 @@
- **Permissions**: the roster reports each bot's tier (or `custom`), so a bot on Full access is visible as such. (`permissions.yaml` stays the single source: the deny list on every loaded `bot.yaml` is the materialized default, not an owner choice.)
- **Deliveries**: text without an extension becomes `.md`; the same content delivered again is the existing file, not a numbered copy.
- **Consequence**: An unattended run either tells the owner something worth reading, says nothing, or says it failed — and the owner finds all of it in one place. Unchanged: retries still rerun a whole turn, missed cron ticks are still skipped, and bots still fail closed on approvals (asking the owner mid-run is the next step).
+
+## ADR-033: Research is one visible run — progress, failures with reasons, a report even when it's cut short
+
+- **Context**: Research mode was a system-prompt suffix plus 3× steps and a 4× stall timeout. On the desktop it was close to invisible: `/research <topic>` and "Full research" confirmed only through `heartbeat`, which the app drops, so the owner saw "Thinking" for up to 16 minutes. `fetch_url` failures (`HTTP 403 …`, `… timed out`) are text, not errors, so every screen showed them as green checks. The stall retry was sent as `text_done`, which ended the turn on screen while the retry ran. The heartbeat showed `/75` when the budget was 225. Running out of steps, every provider failing, or an empty answer gave a generic pause or "(no text response)" and threw the gathered work away. Research stayed on, globally, for every later message in every chat, and only Cloud saved a report. Surveying ChatGPT, Gemini, Perplexity and Claude: the common pattern is plan → live progress (activity + sources) → a report viewer, and none of them handles failure well (generic errors, quota spent, no partial result).
+- **Decision**:
+ - **One run, one chat**: `/research on|plan` and the "Full research" choice switch research on for the next message *in that chat*; that message is the run; when the run ends (however it ends) research is off. `ResearchRun` (`src/core/research-run.ts`) watches it from outside the model: each search (query, results, why it found nothing), each page (read / failed + a plain reason: blocked or behind a login, not found, rate-limited, site error, timed out, no readable text), and a bounded excerpt of each page read (4 KB each, 80 KB total).
+ - **Events**: `research` (the snapshot: phase, plan questions, steps/budget, counts, sources, searches, outcome, the saved report), `research_plan` / `research_plan_resolved` (an editable plan waiting for Start; nobody answering in 10 minutes starts it as proposed), and `notice` (a line about the running turn that isn't its answer: the stall retry). `step_done` now carries `failed` and `reason`, decided on the runtime. `GET /api/chat/threads/:id/research`, `POST …/research/finish` ("write the report now"), `POST …/research/off`, `POST /api/chat/research/plan/:id`.
+ - **Reports**: a finished run gets "Coverage & gaps" only when something failed; the article (from its first `# ` heading, or the markdown file the model wrote instead of replying with it) is saved to `~/.mercury/research/<date>-<slug>.md` with every source consulted, kept as an artifact of the thread, and the run's snapshot goes on the answer's metadata so the report card survives a reload.
+ - **Cut short is still a report**: "write the report now", the step budget, every provider failing, and an empty answer all write the report from the page excerpts (default model, then the others), with "Coverage & gaps": why it stopped, plan questions not marked done, sources that failed and why, searches that found nothing. Stop (plain) ends the run as `stopped`. `/research continue` and `/research retry` start a new run in the same chat that builds on the last one.
+ - **Tool results pair by call id**: parallel calls' results don't always come back in call order; pairing by position showed a search's results on a `fetch_url` row. `resultFor()` matches `toolCallId`, and every step handler uses it.
+ - **Desktop**: a research bar above the composer (on for the next message, or the live phase · questions done · read · failed · searches · time · step N/225, with Details and "Write report now"); Details is Sources (read / cited / failed + reason, filterable) and Activity (questions, searches); the plan card to edit and Start; a report card under the answer (Open report, Copy, Sources & activity, Continue research / Go deeper, Retry N failed); a Research toggle in the composer (normal, deep research, plan first); a research notification ("Research ready: … · 41 sources read · 23 cited") instead of the plain "Done".
+- **Consequence**: The owner can see what research is doing, why sources failed, and always gets what was gathered. Not here: steering a run mid-way with new instructions (a follow-up waits in the queue), resuming a run after a restart (runs live in memory; the report file and the thread's metadata persist), export to PDF/DOCX (the artifact viewer saves the `.md`), and favicons (no third-party image requests from the app).
diff --git a/apps/desktop/src/api/mercury.ts b/apps/desktop/src/api/mercury.ts
index e886c186..a58062e3 100644
--- a/apps/desktop/src/api/mercury.ts
+++ b/apps/desktop/src/api/mercury.ts
@@ -60,6 +60,14 @@ export const chat = {
answer: (promptId: string, action: string, targetId?: string) => http.post<{ resolved: boolean }>(`/api/chat/permission/${encodeURIComponent(promptId)}`, { action, targetId }),
/** Put this chat's waiting message first in line. */
queueFirst: (threadId: string) => http.post<{ moved: number }>(`/api/chat/threads/${encodeURIComponent(threadId)}/queue/first`, {}),
+ /** This chat's research: on for the next message, the run going now, or its last one. */
+ research: (threadId: string) => http.get<{ armed: boolean; planFirst?: boolean; topic?: string | null; run: import("./types").ResearchSnapshot | null }>(`/api/chat/threads/${encodeURIComponent(threadId)}/research`),
+ /** Stop searching and write the report from what was read. */
+ finishResearch: (threadId: string) => http.post<{ ok: boolean }>(`/api/chat/threads/${encodeURIComponent(threadId)}/research/finish`, {}),
+ /** Research off for this chat's next message. */
+ researchOff: (threadId: string) => http.post<{ ok: boolean }>(`/api/chat/threads/${encodeURIComponent(threadId)}/research/off`, {}),
+ /** Start (with these sub-questions) or cancel a proposed research plan. */
+ answerResearchPlan: (id: string, action: "start" | "cancel", questions?: string[]) => http.post<{ ok: boolean }>(`/api/chat/research/plan/${encodeURIComponent(id)}`, { action, questions }),
/** Every slash command with what it does (the "/" picker). */
commands: () => http.get<{ commands: CommandEntry[] }>("/api/chat/commands").then((r) => r.commands),
settings: () => http.get<ChatSettings>("/api/chat/settings"),
diff --git a/apps/desktop/src/api/types.ts b/apps/desktop/src/api/types.ts
index 193970c5..47f2ae66 100644
--- a/apps/desktop/src/api/types.ts
+++ b/apps/desktop/src/api/types.ts
@@ -61,6 +61,60 @@ export interface ChatMessage {
stopped?: boolean;
/** Files this turn made that are worth keeping (images, PDFs, reports…). */
artifacts?: import("./artifacts").ArtifactRef[];
+ /** This answer is a research report: how the run went. */
+ research?: ResearchSnapshot;
+}
+
+/** A page a research run tried to read. */
+export interface ResearchSource {
+ url: string;
+ domain: string;
+ title?: string;
+ status: "read" | "failed";
+ reason?: string;
+ cited?: boolean;
+ at: number;
+}
+
+export interface ResearchSearch {
+ query: string;
+ results: number;
+ ok: boolean;
+ reason?: string;
+ at: number;
+}
+
+export type ResearchOutcome = "done" | "partial" | "stopped" | "failed" | "cancelled";
+
+/** A research run as the runtime reports it (research events, a report's metadata). */
+export interface ResearchSnapshot {
+ runId: string;
+ topic: string;
+ state: "running" | ResearchOutcome;
+ phase: "planning" | "searching" | "reading" | "writing";
+ questions: string[];
+ startedAt: number;
+ endedAt?: number;
+ steps: number;
+ maxSteps: number;
+ searches: number;
+ failedSearches: number;
+ read: number;
+ failed: number;
+ cited: number;
+ sourceList: ResearchSource[];
+ searchList: ResearchSearch[];
+ cut?: string;
+ report?: import("./artifacts").ArtifactRef;
+}
+
+/** A proposed research plan waiting for Start. */
+export interface ResearchPlanPrompt {
+ id: string;
+ runId: string;
+ topic: string;
+ questions: string[];
+ expiresAt: number;
}
export interface ThoughtStep {
diff --git a/apps/desktop/src/app/conversation.ts b/apps/desktop/src/app/conversation.ts
index 14c05229..4690a4bb 100644
--- a/apps/desktop/src/app/conversation.ts
+++ b/apps/desktop/src/app/conversation.ts
@@ -7,7 +7,7 @@
import { createContext, useContext } from "react";
import { create, type StoreApi, type UseBoundStore } from "zustand";
-import type { ChatMessage, PendingPrompt, ThoughtTrace } from "~/api/types";
+import type { ChatMessage, PendingPrompt, ResearchPlanPrompt, ResearchSnapshot, ThoughtTrace } from "~/api/types";
import type { AgentState } from "./store";
export type Surface = "chat" | "code";
@@ -38,6 +38,18 @@ export interface ConversationState {
/** The conversation's plan checklist (update_plan), if Mercury made one. */
plan: { steps: Array<{ label: string; status: "pending" | "active" | "done" }>; updatedAt: number } | null;
setPlan(plan: ConversationState["plan"]): void;
+ /**
+ * Research in this conversation: switched on for the next message
+ * (`armed`), and the run going now or the last one.
+ */
+ research: { armed: boolean; planFirst?: boolean; topic?: string | null; run: ResearchSnapshot | null } | null;
+ setResearch(update: (r: NonNullable<ConversationState["research"]>) => ConversationState["research"]): void;
+ /** A research plan waiting for Start. */
+ researchPlan: ResearchPlanPrompt | null;
+ setResearchPlan(plan: ResearchPlanPrompt | null): void;
+ /** A note about the running turn that isn't its answer ("provider stalled, retrying"). */
+ notice: { message: string; level: "info" | "warning"; at: number } | null;
+ setNotice(notice: ConversationState["notice"]): void;
setLive(update: (live: ThoughtTrace) => ThoughtTrace): void;
clearLive(): void;
setActive(id: string | null): void;
@@ -73,9 +85,15 @@ function makeConversation(surface: Surface): ConversationStore {
setDraft: (draft) => set({ draft }),
plan: null,
setPlan: (plan) => set({ plan }),
+ research: null,
+ setResearch: (update) => set((s) => ({ research: update(s.research ?? { armed: false, run: null }) })),
+ researchPlan: null,
+ setResearchPlan: (researchPlan) => set({ researchPlan }),
+ notice: null,
+ setNotice: (notice) => set({ notice }),
setLive: (update) => set((s) => ({ live: update(s.live ?? { reasoning: "", steps: [], startedAt: Date.now() }) })),
clearLive: () => set({ live: null }),
- setActive: (activeId) => set({ activeId, prompts: [], step: null, agent: "idle", live: null, stopping: false, plan: null }),
+ setActive: (activeId) => set({ activeId, prompts: [], step: null, agent: "idle", live: null, stopping: false, plan: null, research: null, researchPlan: null, notice: null }),
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 44764a11..be2060e9 100644
--- a/apps/desktop/src/app/events.ts
+++ b/apps/desktop/src/app/events.ts
@@ -9,7 +9,7 @@ import { useEffect } from "react";
import { openStream } from "~/api/stream";
import * as api from "~/api/mercury";
import { ApiError, http } from "~/api/client";
-import type { BotActivityEvent, BotInboxEntry, BotStatus, ChatMessage, CodeMode, PendingPrompt } from "~/api/types";
+import type { BotActivityEvent, BotInboxEntry, BotStatus, ChatMessage, CodeMode, PendingPrompt, ResearchPlanPrompt, ResearchSnapshot } from "~/api/types";
import { useBots, useChat, useRuntimeState, type AgentState } from "./store";
import { conversations, useCodeSessions, type ConversationStore, type Surface } from "./conversation";
import type { ArtifactRef } from "~/api/artifacts";
@@ -103,6 +103,37 @@ function safeJson<T>(raw: string): T | null {
/** Artifacts that arrived before their reply did: attached when it lands. */
const pendingArtifacts = new WeakMap<ConversationStore, ArtifactRef[]>();
+/** Is a step's result a failure? The runtime says so now; older ones only by the text. */
+export function stepFailed(data: Record<string, unknown>, summary: string | undefined): boolean {
+ if (typeof data.failed === "boolean") return data.failed;
+ return !!summary && /^(error|failed|denied|blocked|HTTP [45]\d\d\b|Request to .* timed out)/i.test(summary.trim());
+}
+
+const FINAL_RESEARCH = new Set(["done", "partial", "stopped", "failed", "cancelled"]);
+
+/** A research update: the chip and panel follow it; a finished run's report card goes on its answer. */
+function onResearch(store: ConversationStore, data: Record<string, unknown>): void {
+ const conv = store.getState();
+ if (data.state === "armed" || data.state === "off") {
+ const armed = data.state === "armed";
+ conv.setResearch((r) => ({ ...r, armed, planFirst: armed && data.planFirst === true, topic: typeof data.topic === "string" ? data.topic : null }));
+ return;
+ }
+ if (typeof data.runId !== "string") return;
+ const run = data as unknown as ResearchSnapshot;
+ conv.setResearch((r) => ({ ...r, armed: false, planFirst: false, run }));
+ if (!FINAL_RESEARCH.has(run.state) || run.state === "cancelled") return;
+ // The answer is the last assistant message (the run's final update comes after it).
+ const msgs = store.getState().messages;
+ for (let i = msgs.length - 1; i >= 0; i--) {
+ if (msgs[i].role === "user") break;
+ if (msgs[i].role === "assistant") {
+ store.getState().setMessages([...msgs.slice(0, i), { ...msgs[i], research: run }, ...msgs.slice(i + 1)]);
+ return;
+ }
+ }
+}
+
export function handleEvent(store: ConversationStore, event: string, raw: string): void {
const conv = store.getState();
const data = safeJson<Record<string, unknown>>(raw) ?? {};
@@ -129,6 +160,18 @@ export function handleEvent(store: ConversationStore, event: string, raw: string
conv.setAgent("thinking");
conv.setLive((l) => l);
break;
+ case "research":
+ onResearch(store, data);
+ break;
+ case "research_plan":
+ conv.setResearchPlan(data as unknown as ResearchPlanPrompt);
+ break;
+ case "research_plan_resolved":
+ if (conv.researchPlan?.id === data.id) conv.setResearchPlan(null);
+ break;
+ case "notice":
+ if (typeof data.message === "string") conv.setNotice({ message: data.message, level: data.level === "warning" ? "warning" : "info", at: Date.now() });
+ break;
case "plan": {
const steps = Array.isArray(data.steps) ? (data.steps as Array<{ label: string; status: "pending" | "active" | "done" }>) : [];
if (steps.length) conv.setPlan({ steps, updatedAt: Number(data.updatedAt) || Date.now() });
@@ -162,12 +205,14 @@ export function handleEvent(store: ConversationStore, event: string, raw: string
case "step_done": {
const tool = String(data.tool ?? "");
const summary = typeof data.summary === "string" ? data.summary : undefined;
- const failed = !!summary && /^(error|failed|denied|blocked)\b/i.test(summary.trim());
+ // "HTTP 403" and "timed out" are failures too (they used to show a green check).
+ 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, endedAt: Date.now() }; break; }
+ 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 };
});
@@ -180,6 +225,7 @@ export function handleEvent(store: ConversationStore, event: string, raw: string
break;
case "text_done": {
conv.setWaiting(null);
+ conv.setNotice(null);
const text = String(data.fullText ?? data.text ?? raw);
// 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; }
@@ -210,6 +256,7 @@ export function handleEvent(store: ConversationStore, event: string, raw: string
break;
case "error": {
conv.setWaiting(null);
+ conv.setNotice(null);
const message = typeof data.message === "string" ? data.message : raw || "Something went wrong";
conv.clearStreaming();
conv.clearLive();
@@ -300,6 +347,7 @@ export async function openThread(surface: Surface, id: string | null): Promise<v
.then((r) => {
if (store.getState().activeId !== id) return;
for (const p of r.prompts ?? []) {
+ if (p.type === "research_plan") { store.getState().setResearchPlan(p as unknown as ResearchPlanPrompt); continue; }
const kind = p.type === "choice_prompt" ? "choice" : p.type === "permission_continue" ? "continue" : "permission";
store.getState().addPrompt(toPrompt(kind, p, String(p.prompt ?? p.question ?? "")));
}
@@ -314,6 +362,14 @@ export async function openThread(surface: Surface, id: string | null): Promise<v
store.getState().setAgent("thinking");
})
.catch(() => { /* older Mercury */ });
+ // Research here: on for the next message, or a run going (opened mid-run, it picks up live).
+ void api.chat.research(id)
+ .then((r) => {
+ if (store.getState().activeId !== id) return;
+ if (r.armed || r.run) store.getState().setResearch(() => ({ armed: r.armed, planFirst: r.planFirst, topic: r.topic ?? null, run: r.run }));
+ if (r.run?.state === "running") store.getState().setAgent("working");
+ })
+ .catch(() => { /* older Mercury */ });
// The plan Mercury was working through in this conversation, if any.
void http.get<{ plan: { steps: Array<{ label: string; status: "pending" | "active" | "done" }>; updatedAt: number } | null }>(`/api/chat/plan?sessionId=${encodeURIComponent(id)}`)
.then((r) => { if (store.getState().activeId === id && r.plan?.steps?.length) store.getState().setPlan(r.plan); })
diff --git a/apps/desktop/src/app/notify/notify.test.ts b/apps/desktop/src/app/notify/notify.test.ts
index 127767a1..8ecc7baf 100644
--- a/apps/desktop/src/app/notify/notify.test.ts
+++ b/apps/desktop/src/app/notify/notify.test.ts
@@ -4,7 +4,7 @@ vi.mock("~/api/mercury", () => ({ chat: {} }));
const played: string[] = [];
vi.mock("./sounds", () => ({ playSound: (id: string) => played.push(id), SOUNDS: [], CUSTOM_MAX_BYTES: 1 }));
-const { handleActivity } = await import("./notify");
+const { handleActivity, researchNotice } = await import("./notify");
const { useNotify, DEFAULT_PREFS, worthTelling } = await import("./store");
const { conversations } = await import("../conversation");
const { useUi } = await import("../store");
@@ -29,8 +29,31 @@ describe("notifications", () => {
});
it("a long task finishing elsewhere gets a blue dot and a sound", () => {
+ vi.useFakeTimers();
handleActivity({ kind: "done", sessionId: "other", title: "Research", ms: 45_000, preview: "Report ready" });
expect(useNotify.getState().unread.other).toBeTruthy();
+ vi.advanceTimersByTime(2_000);
+ expect(played).toEqual(["pop"]);
+ vi.useRealTimers();
+ });
+
+ it("a research run says what it found instead of a plain Done", () => {
+ vi.useFakeTimers();
+ handleActivity({ kind: "done", sessionId: "other", title: "Solar", ms: 400_000, preview: "# Solar storms" });
+ handleActivity({ kind: "research", sessionId: "other", state: "partial", topic: "solar storms", read: 12, cited: 7, failed: 3 });
+ vi.advanceTimersByTime(2_000);
+ // One notification, not two.
+ expect(played).toEqual(["pop"]);
+ vi.useRealTimers();
+ const r = researchNotice({ kind: "research", sessionId: "other", state: "partial", topic: "solar storms", read: 12, cited: 7, failed: 3 });
+ expect(r.title).toBe("Partial research report: solar storms");
+ expect(r.body).toMatch(/12 sources read · 7 cited · 3 couldn't be read/);
+ expect(researchNotice({ kind: "research", sessionId: "x", state: "done", topic: "t", read: 1 }).title).toBe("Research ready: t");
+ });
+
+ it("a research run's stop or failure isn't told twice", () => {
+ handleActivity({ kind: "failed", sessionId: "other", ms: 400_000, message: "providers failed" });
+ handleActivity({ kind: "research", sessionId: "other", state: "failed", topic: "x", read: 0 });
expect(played).toEqual(["pop"]);
});
diff --git a/apps/desktop/src/app/notify/notify.ts b/apps/desktop/src/app/notify/notify.ts
index fda38594..8370fd39 100644
--- a/apps/desktop/src/app/notify/notify.ts
+++ b/apps/desktop/src/app/notify/notify.ts
@@ -19,7 +19,7 @@ import { playSound } from "./sounds";
import { useNotify, worthTelling } from "./store";
export interface ActivityEvent {
- kind: "started" | "needs_you" | "resolved" | "done" | "stopped" | "failed";
+ kind: "started" | "needs_you" | "resolved" | "done" | "stopped" | "failed" | "research";
sessionId: string;
title?: string;
id?: string;
@@ -27,6 +27,32 @@ export interface ActivityEvent {
ms?: number;
preview?: string;
message?: string;
+ /** kind "research": how a research run ended, and what it found. */
+ state?: "done" | "partial" | "stopped" | "failed";
+ topic?: string;
+ read?: number;
+ cited?: number;
+ failed?: number;
+ report?: string;
+}
+
+/**
+ * A research run's own update follows its "done" by a moment and says more
+ * ("Research ready: … · 41 sources"), so a "done" waits briefly for it.
+ */
+const heldDone = new Map<string, ReturnType<typeof setTimeout>>();
+const HOLD_DONE_MS = 1500;
+
+/** "Research ready: solar storms" and "41 sources read · 23 cited · 3 couldn't be read". */
+export function researchNotice(e: ActivityEvent): { kind: "done" | "failed"; title: string; body: string } {
+ const topic = (e.topic || e.title || "your question").replace(/\s+/g, " ").slice(0, 90);
+ const counts = [`${e.read ?? 0} source${e.read === 1 ? "" : "s"} read`, e.cited ? `${e.cited} cited` : "", e.failed ? `${e.failed} couldn't be read` : ""].filter(Boolean).join(" · ");
+ switch (e.state) {
+ case "done": return { kind: "done", title: `Research ready: ${topic}`, body: counts };
+ case "partial": return { kind: "done", title: `Partial research report: ${topic}`, body: `Stopped early, written from what was read. ${counts}` };
+ case "stopped": return { kind: "failed", title: `Research stopped: ${topic}`, body: counts };
+ default: return { kind: "failed", title: `Research didn't finish: ${topic}`, body: `${counts}. Open it to continue.` };
+ }
}
/** Which surface a session belongs to. */
@@ -174,7 +200,11 @@ export function handleActivity(e: ActivityEvent): void {
void import("../events").then(({ refreshThreads }) => refreshThreads());
}
if (watching(e.sessionId) || !worthTelling(e.kind, e.ms ?? 0, n.prefs)) return;
- if (e.kind === "done") tell("done", e.sessionId, `Done: ${label(e)}`, e.preview || "Mercury finished.");
+ if (e.kind === "done") {
+ const sessionId = e.sessionId;
+ clearTimeout(heldDone.get(sessionId));
+ heldDone.set(sessionId, setTimeout(() => { heldDone.delete(sessionId); tell("done", sessionId, `Done: ${label(e)}`, e.preview || "Mercury finished."); }, HOLD_DONE_MS));
+ }
else tell("failed", e.sessionId, `Stopped with an error: ${label(e)}`, e.message || "Something went wrong.");
// First long task: offer system notifications, once.
if (!n.prefs.asked) {
@@ -186,6 +216,17 @@ export function handleActivity(e: ActivityEvent): void {
case "stopped":
n.clearWaiting(e.sessionId);
return;
+ case "research": {
+ // Said instead of the plain "Done" it follows.
+ const held = heldDone.get(e.sessionId);
+ if (held) { clearTimeout(held); heldDone.delete(e.sessionId); }
+ // No "done" waiting: the turn was short or watched, or its failure or stop was already told.
+ if (!held) return;
+ if (watching(e.sessionId)) return;
+ const r = researchNotice(e);
+ tell(r.kind, e.sessionId, r.title, r.body);
+ return;
+ }
}
}
diff --git a/apps/desktop/src/views/chat/Composer.tsx b/apps/desktop/src/views/chat/Composer.tsx
index 7d334626..f540c314 100644
--- a/apps/desktop/src/views/chat/Composer.tsx
+++ b/apps/desktop/src/views/chat/Composer.tsx
@@ -1,4 +1,4 @@
-import { ArrowUp, AudioLines, ChevronDown, Paperclip, Shield, ShieldCheck, Square, X } from "lucide-react";
+import { ArrowUp, AudioLines, ChevronDown, 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";
@@ -63,6 +63,10 @@ export function Composer({ surface, placeholder, code, extra, blockedReason, mon
const [files, setFiles] = useState<Pending[]>([]);
const [dragging, setDragging] = useState(false);
const [sending, setSending] = useState(false);
+ // Research the next message (one run, then back to off). Chat only.
+ const [researchNext, setResearchNext] = useState<ResearchNext>("off");
+ const threadKey = useConversation((s) => s.activeId);
+ useEffect(() => { setResearchNext("off"); }, [threadKey]);
const [error, setError] = useState<string | null>(null);
const ref = useRef<HTMLTextAreaElement>(null);
const picker = useRef<HTMLInputElement>(null);
@@ -193,7 +197,8 @@ export function Composer({ surface, placeholder, code, extra, blockedReason, mon
}
async function submit(override?: string) {
- const content = (override ?? (token ? `${token.fill}${text}` : text)).trim();
+ let content = (override ?? (token ? `${token.fill}${text}` : text)).trim();
+ if (surface === "chat" && researchNext !== "off" && content && !/^[/#]/.test(content)) content = `/research ${researchNext === "plan" ? "plan " : ""}${content}`;
if ((!content && files.length === 0) || sending) return;
setSending(true);
setError(null);
@@ -201,6 +206,7 @@ export function Composer({ surface, placeholder, code, extra, blockedReason, mon
await sendMessage(surface, content, files.map((f) => ({ name: f.name, data: f.data, mime: f.mime })), code);
setText("");
setToken(null);
+ setResearchNext("off");
for (const f of files) if (f.preview) URL.revokeObjectURL(f.preview);
setFiles([]);
} catch (err) {
@@ -284,7 +290,7 @@ export function Composer({ surface, placeholder, code, extra, blockedReason, mon
else if (e.key === "Escape" && busy) { e.preventDefault(); stop(); }
if (e.key === "Tab" && e.shiftKey && onCycleMode) { e.preventDefault(); onCycleMode(); }
}}
- placeholder={!connected ? "Waiting for Mercury…" : blockedReason ?? (token ? (token.hint || (token.kind === "skill" ? "What should the skill do?" : "Add details, or press Enter")) : placeholder)}
+ placeholder={!connected ? "Waiting for Mercury…" : blockedReason ?? (researchNext !== "off" && !token ? "What should Mercury research?" : token ? (token.hint || (token.kind === "skill" ? "What should the skill do?" : "Add details, or press Enter")) : placeholder)}
rows={1}
disabled={!connected}
className={cx("block max-h-[240px] w-full resize-none overflow-y-auto bg-transparent pb-1 pt-4 text-md leading-[26px] text-ink caret-accent placeholder:truncate placeholder:text-ink4", mono ? "pl-3 pr-5 font-mono text-[14.5px]" : token ? "pl-2.5 pr-5" : "px-5")}
@@ -308,6 +314,7 @@ export function Composer({ surface, placeholder, code, extra, blockedReason, mon
</Tooltip>
)}
<ModelPicker />
+ {surface === "chat" && <ResearchToggle value={researchNext} onChange={(v) => { setResearchNext(v); ref.current?.focus(); }} />}
{surface === "chat" && <ModePicker />}
<div className="flex-1" />
{busy ? (
@@ -402,6 +409,29 @@ function ModelPicker() {
);
}
+type ResearchNext = "off" | "on" | "plan";
+
+/** Research the next message: a full report from live sources, optionally with a plan to check first. */
+function ResearchToggle({ value, onChange }: { value: ResearchNext; onChange: (v: ResearchNext) => void }) {
+ const on = value !== "off";
+ 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]", on ? "bg-accent/10 text-accent" : "text-ink3")} aria-label="Research" aria-pressed={on}>
+ <Telescope size={14} />
+ {on ? (value === "plan" ? "Research · plan first" : "Research") : "Research"}
+ </button>
+ }
+ >
+ <MenuLabel>Your next message</MenuLabel>
+ <MenuItem selected={value === "off"} onSelect={() => onChange("off")}>Normal answer</MenuItem>
+ <MenuItem selected={value === "on"} onSelect={() => onChange("on")} hint="many sources, a full report">Deep research</MenuItem>
+ <MenuItem selected={value === "plan"} onSelect={() => onChange("plan")} hint="check the questions first">Deep research, plan first</MenuItem>
+ </Menu>
+ );
+}
+
function ModePicker() {
const { allowAll: mode, setAllowAll } = usePermissionMode();
const allowAll = mode === true;
diff --git a/apps/desktop/src/views/chat/Conversation.tsx b/apps/desktop/src/views/chat/Conversation.tsx
index 2e184ef9..00c8194f 100644
--- a/apps/desktop/src/views/chat/Conversation.tsx
+++ b/apps/desktop/src/views/chat/Conversation.tsx
@@ -11,6 +11,8 @@ import { ThinkingDots } from "~/components/indicators/Thinking";
import { Message, StreamingMessage } from "./Message";
import { Composer, type ComposerProps } from "./Composer";
import { WaitingNotice } from "./Waiting";
+import { ResearchBar, ResearchPlan } from "./Research";
+import { AlertTriangle, Info } from "lucide-react";
const PAGE = 30;
@@ -32,6 +34,7 @@ export function Conversation({ header, empty, composer }: { header: ReactNode; e
const live = useConversation((s) => s.live);
const waiting = useConversation((s) => s.waiting);
const stopping = useConversation((s) => s.stopping);
+ const notice = useConversation((s) => s.notice);
const scroller = useRef<HTMLDivElement>(null);
const content = useRef<HTMLDivElement>(null);
const [visible, setVisible] = useState(PAGE);
@@ -110,6 +113,13 @@ export function Conversation({ header, empty, composer }: { header: ReactNode; e
) : !streaming && !live && (agent === "thinking" || agent === "working") && (
<ThinkingDots label={stopping ? "Stopping" : agent === "working" && step?.tool ? `Running ${step.tool}` : "Thinking"} className="pl-10" />
)}
+ {notice && busy && (
+ <p className={cx("ml-10 flex items-start gap-2 text-xs", notice.level === "warning" ? "text-amber" : "text-ink3")} role="status">
+ {notice.level === "warning" ? <AlertTriangle size={13} className="mt-px shrink-0" aria-hidden="true" /> : <Info size={13} className="mt-px shrink-0" aria-hidden="true" />}
+ {notice.message}
+ </p>
+ )}
+ <ResearchPlan />
{prompts.map((p, i) => (
<div key={p.id} className="min-w-0 pl-10">
<Approval prompt={p} onAnswer={(v) => answerPrompt(store, p, v)} keys={i === prompts.length - 1} />
@@ -132,6 +142,7 @@ export function Conversation({ header, empty, composer }: { header: ReactNode; e
)}
</div>
+ <ResearchBar />
<PlanCard surface={composer.surface} />
<Composer {...composer} />
</section>
diff --git a/apps/desktop/src/views/chat/Message.tsx b/apps/desktop/src/views/chat/Message.tsx
index 4d7bbbfc..2a607437 100644
--- a/apps/desktop/src/views/chat/Message.tsx
+++ b/apps/desktop/src/views/chat/Message.tsx
@@ -15,6 +15,7 @@ import { UserAvatar, useDisplayName } from "~/components/UserAvatar";
import { usePulse } from "~/app/pulse";
import { ArtifactStrip } from "~/components/artifacts/ArtifactCard";
import { UndoMessage } from "./UndoMessage";
+import { ResearchReport } from "./Research";
import { ReadAloudButton, ReadAloudNotice, useReadingThis } from "~/components/readAloud/ReadAloud";
/**
@@ -72,7 +73,12 @@ export const Message = memo(function Message({ message, undoable = false }: { me
)}
{body && <Markdown text={body} />}
{stopped && <StoppedMarker partial={!!body} />}
- {message.artifacts && message.artifacts.length > 0 && <ArtifactStrip items={message.artifacts} />}
+ {message.research
+ ? <ResearchReport run={message.research} content={body} />
+ : message.artifacts && message.artifacts.length > 0 && <ArtifactStrip items={message.artifacts} />}
+ {message.research && message.artifacts && message.artifacts.filter((a) => a.id !== message.research?.report?.id).length > 0 && (
+ <ArtifactStrip items={message.artifacts.filter((a) => a.id !== message.research?.report?.id)} />
+ )}
<MessageMeta timestamp={message.timestamp} copy={body || undefined} listen={body ? { id: message.id, text: body } : undefined} />
<ReadAloudNotice id={message.id} />
</div>
diff --git a/apps/desktop/src/views/chat/Research.test.ts b/apps/desktop/src/views/chat/Research.test.ts
new file mode 100644
index 00000000..425ff691
--- /dev/null
+++ b/apps/desktop/src/views/chat/Research.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("~/api/mercury", () => ({ chat: {} }));
+const { elapsed, outcomeLine, researchCounts } = await import("./Research");
+const { handleEvent, stepFailed } = await import("~/app/events");
+const { conversations } = await import("~/app/conversation");
+
+const snap = (over: Record<string, unknown> = {}) => ({
+ runId: "r1", topic: "solar storms", state: "running", phase: "reading", questions: [], startedAt: 0, steps: 4, maxSteps: 225,
+ searches: 2, failedSearches: 0, read: 3, failed: 1, cited: 0, sourceList: [], searchList: [], ...over,
+});
+
+describe("research on the desktop", () => {
+ it("counts and endings read plainly", () => {
+ expect(researchCounts({ read: 1, failed: 0, searches: 1, cited: 0 })).toBe("1 source read · 1 search");
+ expect(researchCounts({ read: 31, failed: 3, searches: 12, cited: 20 }, { cited: true })).toBe("31 sources read · 20 cited · 3 couldn't be read · 12 searches");
+ expect(elapsed(372_000)).toBe("6:12");
+ expect(outcomeLine(snap({ state: "partial", cut: "you asked it to finish now" }) as never).title).toBe("Partial report: stopped early because you asked it to finish now");
+ expect(outcomeLine(snap({ state: "done" }) as never).tone).toBe("ok");
+ });
+
+ it("an HTTP 403 or a timeout is a failed step, not a green check", () => {
+ expect(stepFailed({ failed: true }, "anything")).toBe(true);
+ expect(stepFailed({ failed: false }, "Error: looks like one")).toBe(false);
+ // Older runtimes don't say; the text decides.
+ expect(stepFailed({}, "HTTP 403 Forbidden for https://x.com")).toBe(true);
+ expect(stepFailed({}, "Request to https://x.com timed out after 30 seconds.")).toBe(true);
+ expect(stepFailed({}, "# A page")).toBe(false);
+ });
+
+ it("follows a run, and puts the finished run's card on its answer", () => {
+ const store = conversations.chat;
+ store.setState({ activeId: "t1", messages: [{ id: "u", role: "user", content: "q", timestamp: "" }], research: null, agent: "working" });
+ handleEvent(store, "research", JSON.stringify({ state: "armed", planFirst: true, topic: "solar storms" }));
+ expect(store.getState().research).toMatchObject({ armed: true, planFirst: true });
+ handleEvent(store, "research", JSON.stringify(snap()));
+ expect(store.getState().research).toMatchObject({ armed: false, run: { runId: "r1", state: "running" } });
+ handleEvent(store, "text_done", JSON.stringify({ fullText: "# Solar storms\n\nReport" }));
+ handleEvent(store, "research", JSON.stringify(snap({ state: "done", cited: 2 })));
+ const last = store.getState().messages[store.getState().messages.length - 1];
+ expect(last.research).toMatchObject({ runId: "r1", state: "done", cited: 2 });
+ });
+
+ it("a stall notice is a note, not the answer", () => {
+ const store = conversations.chat;
+ store.setState({ activeId: "t1", messages: [], notice: null });
+ handleEvent(store, "notice", JSON.stringify({ message: "Mercury detected a stalled provider", level: "warning" }));
+ expect(store.getState().notice).toMatchObject({ level: "warning" });
+ expect(store.getState().messages).toHaveLength(0);
+ handleEvent(store, "text_done", JSON.stringify({ fullText: "done" }));
+ expect(store.getState().notice).toBeNull();
+ });
+
+ it("a research plan waits for an answer and goes when it's resolved", () => {
+ const store = conversations.chat;
+ store.setState({ activeId: "t1", researchPlan: null });
+ handleEvent(store, "research_plan", JSON.stringify({ id: "rplan_1", runId: "r1", topic: "t", questions: ["a?", "b?"], expiresAt: 1 }));
+ expect(store.getState().researchPlan?.questions).toEqual(["a?", "b?"]);
+ handleEvent(store, "research_plan_resolved", JSON.stringify({ id: "rplan_1", action: "start" }));
+ expect(store.getState().researchPlan).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/views/chat/Research.tsx b/apps/desktop/src/views/chat/Research.tsx
new file mode 100644
index 00000000..44c1362f
--- /dev/null
+++ b/apps/desktop/src/views/chat/Research.tsx
@@ -0,0 +1,349 @@
+import { AlertTriangle, BookOpen, Check, ChevronRight, CircleSlash, Copy, FileText, Globe, ListChecks, Plus, RotateCw, Search, Telescope, Trash2, X } from "lucide-react";
+import { useEffect, useState } from "react";
+import * as api from "~/api/mercury";
+import type { ResearchSnapshot, ResearchSource } from "~/api/types";
+import { useConversation, useConversationStore } from "~/app/conversation";
+import { sendMessage } from "~/app/events";
+import { ArtifactViewer } from "~/components/artifacts/ArtifactViewer";
+import { Button } from "~/components/ui/Button";
+import { Dialog } from "~/components/ui/Dialog";
+import { Segmented } from "~/components/ui/bits";
+import { cx } from "~/lib/cx";
+
+/**
+ * Research, made visible. Four pieces:
+ * - ResearchBar above the composer: research is on for your next
+ * message, or a run is going (phase, counts, time) with
+ * Details and "Write report now"
+ * - ResearchPlan a proposed plan to edit, then Start (plan-first runs)
+ * - ResearchReport under a report: how the run went, the file, and
+ * Continue / Retry failed sources when it fell short
+ * - ResearchDetails Activity and Sources: every search and every page,
+ * and why the ones that failed failed
+ */
+
+const PHASE: Record<ResearchSnapshot["phase"], string> = {
+ planning: "Planning",
+ searching: "Searching",
+ reading: "Reading sources",
+ writing: "Writing the report",
+};
+
+export function elapsed(ms: number): string {
+ const s = Math.max(0, Math.round(ms / 1000));
+ if (s < 60) return `${s}s`;
+ const m = Math.floor(s / 60);
+ if (m < 60) return `${m}:${String(s % 60).padStart(2, "0")}`;
+ return `${Math.floor(m / 60)}h ${m % 60}m`;
+}
+
+/** "31 sources read · 3 couldn't be read · 12 searches". */
+export function researchCounts(r: Pick<ResearchSnapshot, "read" | "failed" | "searches" | "cited">, opts: { cited?: boolean } = {}): string {
+ const parts = [`${r.read} source${r.read === 1 ? "" : "s"} read`];
+ if (opts.cited && r.cited) parts.push(`${r.cited} cited`);
+ if (r.failed) parts.push(`${r.failed} couldn't be read`);
+ parts.push(`${r.searches} search${r.searches === 1 ? "" : "es"}`);
+ return parts.join(" · ");
+}
+
+/** What a finished (or cut-short) run says about itself. */
+export function outcomeLine(r: ResearchSnapshot): { title: string; tone: "ok" | "warn" | "bad" } {
+ switch (r.state) {
+ case "done": return { title: "Research report", tone: "ok" };
+ case "partial": return { title: `Partial report: stopped early because ${r.cut ?? "it was interrupted"}`, tone: "warn" };
+ case "stopped": return { title: r.cut === "you stopped it" ? "Research stopped" : `Research stopped: ${r.cut ?? "you stopped it"}`, tone: "warn" };
+ case "failed": return { title: `Research didn't finish: ${r.cut ?? "something went wrong"}`, tone: "bad" };
+ case "cancelled": return { title: "Research cancelled", tone: "warn" };
+ default: return { title: "Researching", tone: "ok" };
+ }
+}
+
+function useNow(active: boolean): number {
+ const [now, setNow] = useState(Date.now());
+ useEffect(() => {
+ if (!active) return;
+ const t = setInterval(() => setNow(Date.now()), 1000);
+ return () => clearInterval(t);
+ }, [active]);
+ return now;
+}
+
+/* ── above the composer ─────────────────────────────────────────── */
+
+export function ResearchBar() {
+ const research = useConversation((s) => s.research);
+ const threadId = useConversation((s) => s.activeId);
+ const streaming = useConversation((s) => !!s.streaming);
+ const plan = useConversation((s) => s.plan);
+ const run = research?.run;
+ const running = run?.state === "running";
+ const now = useNow(running);
+ const [open, setOpen] = useState(false);
+ const [finishing, setFinishing] = useState(false);
+ const [problem, setProblem] = useState<string | null>(null);
+ useEffect(() => { setFinishing(false); setProblem(null); }, [run?.runId]);
+
+ if (!research || (!research.armed && !running)) return null;
+
+ if (!running) {
+ return (
+ <Shell>
+ <Telescope size={15} className="shrink-0 text-accent" aria-hidden="true" />
+ <span className="min-w-0 flex-1 truncate text-sm text-ink2">
+ <span className="font-medium text-ink">Research is on</span> for your next message{research.planFirst ? ", with a plan to check first" : ""}. It searches live sources and writes a full report, then switches off.
+ </span>
+ {threadId && <Button size="sm" variant="ghost" onClick={() => void api.chat.researchOff(threadId).catch(() => {})}>Turn off</Button>}
+ </Shell>
+ );
+ }
+
+ const phase = streaming && run.phase !== "planning" ? "writing" : run.phase;
+ const steps = plan?.steps ?? [];
+ const done = steps.filter((s) => s.status === "done").length;
+
+ async function finish() {
+ if (!threadId) return;
+ setFinishing(true);
+ setProblem(null);
+ try {
+ await api.chat.finishResearch(threadId);
+ } catch (e) {
+ setFinishing(false);
+ setProblem(e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ return (
+ <Shell>
+ <span className="relative flex h-4 w-4 shrink-0 items-center justify-center" aria-hidden="true">
+ <span className="absolute h-2.5 w-2.5 animate-ping rounded-full bg-accent/40" />
+ <span className="h-2 w-2 rounded-full bg-accent" />
+ </span>
+ <button onClick={() => setOpen(true)} className="flex min-w-0 flex-1 items-center gap-2 text-left" aria-label="Research details">
+ <span className="shrink-0 text-sm font-medium text-ink">{finishing ? "Writing the report" : PHASE[phase]}</span>
+ <span className="min-w-0 truncate text-xs text-ink3">
+ {steps.length >= 2 ? `${done} of ${steps.length} questions · ` : ""}
+ {run.read} read{run.failed ? ` · ${run.failed} failed` : ""} · {run.searches} searches · {elapsed(now - run.startedAt)} · step {run.steps}/{run.maxSteps}
+ </span>
+ <ChevronRight size={14} className="shrink-0 text-ink4" />
+ </button>
+ {problem && <span className="max-w-[220px] truncate text-xs text-red" title={problem}>{problem}</span>}
+ {phase !== "writing" && phase !== "planning" && run.read > 0 && !finishing && (
+ <Button size="sm" variant="ghost" onClick={() => void finish()} title="Stop searching and write the report from what's been read">Write report now</Button>
+ )}
+ <ResearchDetails run={run} open={open} onOpenChange={setOpen} />
+ </Shell>
+ );
+}
+
+function Shell({ children }: { children: React.ReactNode }) {
+ return (
+ <div className="shrink-0 px-8 pt-1">
+ <div className="mx-auto w-full max-w-[780px]">
+ <section className="flex items-center gap-3 rounded-2xl border border-line bg-surface px-4 py-2 shadow-[0_1px_2px_rgb(0_0_0/0.04)]" role="status" aria-label="Research">
+ {children}
+ </section>
+ </div>
+ </div>
+ );
+}
+
+/* ── the plan, before starting ──────────────────────────────────── */
+
+export function ResearchPlan() {
+ const plan = useConversation((s) => s.researchPlan);
+ const store = useConversationStore();
+ const [questions, setQuestions] = useState<string[]>([]);
+ const [busy, setBusy] = useState<"start" | "cancel" | null>(null);
+ const [problem, setProblem] = useState<string | null>(null);
+ const now = useNow(!!plan);
+ useEffect(() => { setQuestions(plan?.questions ?? []); setBusy(null); setProblem(null); }, [plan?.id]); // eslint-disable-line react-hooks/exhaustive-deps
+ if (!plan) return null;
+ const left = Math.max(0, plan.expiresAt - now);
+
+ async function answer(action: "start" | "cancel") {
+ if (!plan) return;
+ setBusy(action);
+ setProblem(null);
+ try {
+ await api.chat.answerResearchPlan(plan.id, action, questions.map((q) => q.trim()).filter(Boolean));
+ store.getState().setResearchPlan(null);
+ } catch (e) {
+ setBusy(null);
+ setProblem(e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ return (
+ <div className="ml-10 flex flex-col gap-3 rounded-xl border border-line bg-surface px-4 py-3.5" role="group" aria-label="Research plan">
+ <div className="flex items-start gap-2.5">
+ <ListChecks size={16} className="mt-0.5 shrink-0 text-accent" aria-hidden="true" />
+ <div className="min-w-0 flex-1">
+ <p className="text-sm font-medium text-ink">Research plan</p>
+ <p className="text-xs text-ink3">Edit the questions it will answer, then start. Nothing has been searched yet.</p>
+ </div>
+ </div>
+ <ol className="flex flex-col gap-1.5 pl-[26px]">
+ {questions.map((q, i) => (
+ <li key={i} className="flex items-center gap-2">
+ <span className="w-4 shrink-0 text-right font-mono text-xs text-ink4">{i + 1}</span>
+ <input value={q} onChange={(e) => setQuestions(questions.map((x, j) => (j === i ? e.target.value : x)))}
+ className="h-8 min-w-0 flex-1 rounded-md border border-line bg-surface px-2.5 text-sm text-ink focus:border-line-strong focus:outline-none" aria-label={`Question ${i + 1}`} />
+ <button onClick={() => setQuestions(questions.filter((_, j) => j !== i))} disabled={questions.length <= 1}
+ className="rounded p-1.5 text-ink4 hover:text-red disabled:opacity-30" aria-label={`Remove question ${i + 1}`}><Trash2 size={13} /></button>
+ </li>
+ ))}
+ {questions.length < 8 && (
+ <li className="pl-6">
+ <button onClick={() => setQuestions([...questions, ""])} className="flex items-center gap-1.5 text-xs text-ink2 hover:text-ink"><Plus size={13} /> Add a question</button>
+ </li>
+ )}
+ </ol>
+ <div className="flex flex-wrap items-center gap-2 pl-[26px]">
+ <Button size="sm" variant="primary" loading={busy === "start"} disabled={!!busy || !questions.some((q) => q.trim())} onClick={() => void answer("start")}>Start research</Button>
+ <Button size="sm" variant="ghost" loading={busy === "cancel"} disabled={!!busy} onClick={() => void answer("cancel")}>Cancel</Button>
+ <span className="text-xs text-ink4">Starts as shown in {elapsed(left)} if you don't answer.</span>
+ {problem && <span className="text-xs text-red">{problem}</span>}
+ </div>
+ </div>
+ );
+}
+
+/* ── under a report ─────────────────────────────────────────────── */
+
+export function ResearchReport({ run, content }: { run: ResearchSnapshot; content: string }) {
+ const threadId = useConversation((s) => s.activeId);
+ const surface = useConversation((s) => s.surface);
+ const latest = useConversation((s) => s.research?.run?.runId === run.runId || !s.research?.run);
+ const busy = useConversation((s) => s.agent === "thinking" || s.agent === "working" || s.agent === "streaming");
+ const [details, setDetails] = useState(false);
+ const [reportOpen, setReportOpen] = useState(false);
+ const [copied, setCopied] = useState(false);
+ const { title, tone } = outcomeLine(run);
+ const took = run.endedAt ? elapsed(run.endedAt - run.startedAt) : null;
+ const shortOf = run.state !== "done";
+
+ function again(cmd: "/research continue" | "/research retry") {
+ if (!threadId) return;
+ void sendMessage(surface, cmd).catch(() => {});
+ }
+
+ return (
+ <div className={cx("mt-3 flex flex-col gap-2.5 rounded-xl border px-3.5 py-3",
+ tone === "ok" ? "border-line bg-soft" : tone === "warn" ? "border-amber/40 bg-amber/[0.05]" : "border-red/40 bg-red/[0.05]")} aria-label="Research summary">
+ <div className="flex items-start gap-2.5">
+ {tone === "ok" ? <BookOpen size={15} className="mt-0.5 shrink-0 text-accent" aria-hidden="true" />
+ : tone === "warn" ? <AlertTriangle size={15} className="mt-0.5 shrink-0 text-amber" aria-hidden="true" />
+ : <CircleSlash size={15} className="mt-0.5 shrink-0 text-red" aria-hidden="true" />}
+ <div className="min-w-0 flex-1">
+ <p className="text-sm font-medium text-ink">{title}</p>
+ <p className="text-xs text-ink3">{researchCounts(run, { cited: true })}{took ? ` · ${took}` : ""}</p>
+ </div>
+ </div>
+ <div className="flex flex-wrap items-center gap-1.5 pl-[25px]">
+ {run.report && <Button size="sm" variant="secondary" onClick={() => setReportOpen(true)}><FileText size={13} /> Open report</Button>}
+ {content.trim() && (
+ <Button size="sm" variant="ghost" onClick={() => { void navigator.clipboard.writeText(content).then(() => { setCopied(true); setTimeout(() => setCopied(false), 1500); }); }}>
+ {copied ? <Check size={13} /> : <Copy size={13} />} {copied ? "Copied" : "Copy"}
+ </Button>
+ )}
+ <Button size="sm" variant="ghost" onClick={() => setDetails(true)}><Globe size={13} /> Sources & activity</Button>
+ {latest && !busy && (
+ <>
+ <Button size="sm" variant={shortOf ? "secondary" : "ghost"} onClick={() => again("/research continue")}>
+ <Telescope size={13} /> {shortOf ? "Continue research" : "Go deeper"}
+ </Button>
+ {run.failed > 0 && <Button size="sm" variant="ghost" onClick={() => again("/research retry")}><RotateCw size={13} /> Retry {run.failed} failed</Button>}
+ </>
+ )}
+ </div>
+ <ResearchDetails run={run} open={details} onOpenChange={setDetails} />
+ {run.report && (
+ <Dialog open={reportOpen} onOpenChange={setReportOpen} title="Research report" width={900}>
+ {reportOpen && <div className="-m-5 h-[75vh]"><ArtifactViewer id={run.report.id} onDeleted={() => setReportOpen(false)} /></div>}
+ </Dialog>
+ )}
+ </div>
+ );
+}
+
+/* ── Activity and Sources ───────────────────────────────────────── */
+
+export function ResearchDetails({ run, open, onOpenChange }: { run: ResearchSnapshot; open: boolean; onOpenChange: (o: boolean) => void }) {
+ const [tab, setTab] = useState<"activity" | "sources">("sources");
+ const [filter, setFilter] = useState<"all" | "failed">("all");
+ const plan = useConversation((s) => s.plan);
+ const sources = [...run.sourceList].reverse().filter((s) => filter === "all" || s.status === "failed");
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange} title={run.topic.length > 70 ? `${run.topic.slice(0, 70)}…` : run.topic} description={researchCounts(run, { cited: true })} width={720}>
+ <div className="flex flex-col gap-3">
+ <div className="flex items-center gap-2">
+ <Segmented value={tab} onChange={setTab} options={[{ value: "sources", label: `Sources (${run.read + run.failed})` }, { value: "activity", label: "Activity" }]} />
+ <div className="flex-1" />
+ {tab === "sources" && run.failed > 0 && <Segmented value={filter} onChange={setFilter} options={[{ value: "all", label: "All" }, { value: "failed", label: `Failed (${run.failed})` }]} />}
+ </div>
+ {tab === "sources" ? (
+ sources.length === 0
+ ? <p className="py-6 text-center text-sm text-ink3">{run.state === "running" ? "No pages read yet: it's still searching." : "No pages were read."}</p>
+ : <ul className="flex max-h-[55vh] flex-col divide-y divide-line overflow-y-auto rounded-lg border border-line">{sources.map((s) => <SourceRow key={s.url} source={s} />)}</ul>
+ ) : (
+ <div className="flex max-h-[55vh] flex-col gap-4 overflow-y-auto">
+ {(plan?.steps?.length ?? 0) > 0 && run.state === "running" ? (
+ <section>
+ <h3 className="mb-1.5 text-xs font-medium uppercase tracking-wide text-ink4">Questions</h3>
+ <ol className="flex flex-col gap-1">
+ {plan!.steps.map((s, i) => (
+ <li key={i} className="flex items-start gap-2 text-sm">
+ {s.status === "done" ? <Check size={14} className="mt-0.5 shrink-0 text-accent" /> : <span className={cx("mt-1.5 h-2 w-2 shrink-0 rounded-full", s.status === "active" ? "animate-pulse bg-accent" : "border border-ink4")} />}
+ <span className={s.status === "done" ? "text-ink3" : s.status === "active" ? "font-medium text-ink" : "text-ink2"}>{s.label}</span>
+ </li>
+ ))}
+ </ol>
+ </section>
+ ) : run.questions.length > 0 && (
+ <section>
+ <h3 className="mb-1.5 text-xs font-medium uppercase tracking-wide text-ink4">Questions</h3>
+ <ol className="flex list-decimal flex-col gap-1 pl-5 text-sm text-ink2">{run.questions.map((q, i) => <li key={i}>{q}</li>)}</ol>
+ </section>
+ )}
+ <section>
+ <h3 className="mb-1.5 text-xs font-medium uppercase tracking-wide text-ink4">Searches ({run.searches})</h3>
+ {run.searchList.length === 0 ? <p className="text-sm text-ink3">None yet.</p> : (
+ <ul className="flex flex-col gap-1">
+ {[...run.searchList].reverse().map((q, i) => (
+ <li key={i} className="flex items-start gap-2 text-sm">
+ <Search size={13} className={cx("mt-1 shrink-0", q.ok ? "text-ink4" : "text-red")} aria-hidden="true" />
+ <span className="min-w-0 flex-1">
+ <span className="text-ink2" data-selectable>{q.query || "(top stories)"}</span>
+ <span className={cx("ml-2 text-xs", q.ok ? "text-ink4" : "text-red")}>{q.ok ? `${q.results} results` : q.reason ?? "found nothing"}</span>
+ </span>
+ </li>
+ ))}
+ </ul>
+ )}
+ </section>
+ {run.cut && <p className="rounded-md border border-amber/40 bg-amber/[0.06] px-3 py-2 text-sm text-ink2">Stopped early because {run.cut}.</p>}
+ </div>
+ )}
+ </div>
+ </Dialog>
+ );
+}
+
+function SourceRow({ source: s }: { source: ResearchSource }) {
+ return (
+ <li className="flex items-start gap-3 px-3 py-2">
+ <span className={cx("mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-md font-mono text-2xs uppercase",
+ s.status === "failed" ? "bg-red/10 text-red" : s.cited ? "bg-accent/15 text-accent" : "bg-ink/[0.06] text-ink3")} aria-hidden="true">
+ {s.status === "failed" ? <X size={12} /> : s.domain.slice(0, 2)}
+ </span>
+ <span className="min-w-0 flex-1">
+ <a href={s.url} target="_blank" rel="noreferrer" className="block truncate text-sm text-ink hover:underline" title={s.url}>{s.title || s.domain}</a>
+ <span className="block truncate text-xs text-ink4">{s.domain}</span>
+ </span>
+ <span className={cx("shrink-0 text-xs", s.status === "failed" ? "text-red" : s.cited ? "text-accent" : "text-ink4")}>
+ {s.status === "failed" ? s.reason ?? "failed" : s.cited ? "cited" : "read"}
+ </span>
+ </li>
+ );
+}
diff --git a/apps/desktop/src/views/chat/picker.ts b/apps/desktop/src/views/chat/picker.ts
index f35e50d0..2689c618 100644
--- a/apps/desktop/src/views/chat/picker.ts
+++ b/apps/desktop/src/views/chat/picker.ts
@@ -31,7 +31,7 @@ export type PickerItem =
const DESKTOP_COMMANDS = new Set([
"/help", "/whatsnew", "/status", "/progress", "/log",
"/models", "/models use ", "/cloud models", "/cloud use ",
- "/research", "/research on", "/research off", "/research ",
+ "/research", "/research on", "/research off", "/research plan ", "/research continue", "/research retry", "/research ",
"/budget", "/saver", "/saver toggle", "/memory", "/tools", "/mcp",
"/skills", "/skills search ", "/skills install ",
"/plugins", "/plugins search ", "/plugins install ", "/plugins update",
diff --git a/src/channels/web.ts b/src/channels/web.ts
index a4efa269..9107ef9e 100644
--- a/src/channels/web.ts
+++ b/src/channels/web.ts
@@ -4,6 +4,7 @@ import type { ChannelMessage, ChannelAttachment } from '../types/channel.js';
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';
type CloudEventHandler = (event: ChatEvent) => boolean;
@@ -21,7 +22,7 @@ interface PendingInteraction {
}
export interface ChatEvent {
- type: 'activity' | 'thinking' | 'reasoning' | 'plan' | 'artifacts' | 'provider' | 'heartbeat' | 'step_start' | 'step_done' | 'text_delta' | 'text_done' | 'permission_request' | 'permission_continue' | 'permission_mode' | 'permission_resolved' | 'choice_prompt' | 'choice_resolved' | 'loop_warning' | 'error' | 'bot_activity' | 'status' | 'session_switched' | 'queued';
+ type: 'activity' | 'thinking' | 'reasoning' | 'plan' | 'artifacts' | 'provider' | 'heartbeat' | 'step_start' | 'step_done' | 'text_delta' | 'text_done' | 'permission_request' | 'permission_continue' | 'permission_mode' | 'permission_resolved' | 'choice_prompt' | 'choice_resolved' | 'loop_warning' | 'error' | 'bot_activity' | 'status' | 'session_switched' | 'queued' | 'research' | 'research_plan' | 'research_plan_resolved' | 'notice';
data?: Record<string, unknown>;
}
@@ -85,6 +86,11 @@ export class WebChannel extends BaseChannel {
client.close();
}
this.sseClients.clear();
+ for (const [id, plan] of this.researchPlans) {
+ clearTimeout(plan.timer);
+ plan.resolve({ action: 'cancel', questions: plan.questions });
+ this.researchPlans.delete(id);
+ }
for (const [id, interaction] of this.pendingInteractions) {
clearTimeout(interaction.timer);
interaction.resolve(interaction.kind === 'mode' ? 'ask-me' : interaction.kind === 'choice' ? '' : 'no');
@@ -119,7 +125,63 @@ export class WebChannel extends BaseChannel {
/** Prompts still waiting in a session, as the events that asked them. */
pendingFor(sessionId: string): ChatEvent[] {
- return [...this.pendingInteractions.values()].filter((i) => i.sessionId === sessionId && i.event).map((i) => i.event!);
+ const prompts = [...this.pendingInteractions.values()].filter((i) => i.sessionId === sessionId && i.event).map((i) => i.event!);
+ const plans = [...this.researchPlans.values()].filter((p) => p.sessionId === sessionId).map((p) => p.event);
+ return [...prompts, ...plans];
+ }
+
+ /** Research plans waiting for the owner's Start (see askResearchPlan). */
+ private researchPlans = new Map<string, { sessionId?: string; event: ChatEvent; resolve: (a: { action: 'start' | 'cancel'; questions: string[] }) => void; timer: ReturnType<typeof setTimeout>; questions: string[] }>();
+
+ /**
+ * Show a research plan the owner can edit, and wait for Start or Cancel.
+ * Nobody answering in `timeoutMs` starts the plan as proposed: they asked
+ * for the research, the plan was only a chance to steer it.
+ */
+ askResearchPlan(runId: string, topic: string, questions: string[], targetId: string | undefined, timeoutMs: number): Promise<{ action: 'start' | 'cancel'; questions: string[]; timedOut?: boolean }> {
+ const id = `rplan_${runId}`;
+ const event: ChatEvent = { type: 'research_plan', data: { id, runId, topic, questions, targetId, expiresAt: Date.now() + timeoutMs } };
+ return new Promise((resolve) => {
+ const timer = setTimeout(() => {
+ if (!this.researchPlans.delete(id)) return;
+ this.broadcast({ type: 'research_plan_resolved', data: { id, action: 'start', targetId } });
+ resolve({ action: 'start', questions, timedOut: true });
+ }, timeoutMs);
+ timer.unref?.();
+ this.researchPlans.set(id, { sessionId: targetId, event, resolve, timer, questions });
+ this.broadcast(event);
+ });
+ }
+
+ /** The owner's answer to a research plan. False when it's gone (answered, timed out). */
+ answerResearchPlan(id: string, action: 'start' | 'cancel', questions?: string[]): boolean {
+ const p = this.researchPlans.get(id);
+ if (!p) return false;
+ this.researchPlans.delete(id);
+ clearTimeout(p.timer);
+ const kept = (questions ?? p.questions).map((q) => String(q).trim()).filter(Boolean).slice(0, 8);
+ p.resolve({ action, questions: kept.length ? kept : p.questions });
+ this.broadcast({ type: 'research_plan_resolved', data: { id, action, targetId: p.sessionId } });
+ return true;
+ }
+
+ /** A research run as it stands: phase, counts, sources and how each went. */
+ sendResearch(snapshot: ResearchSnapshot, targetId?: string): void {
+ this.broadcast({ type: 'research', data: { ...snapshot, targetId } });
+ }
+
+ /** Research switched on (or off) for a chat's next message. */
+ sendResearchArmed(armed: boolean, targetId: string | undefined, info: { topic?: string | null; planFirst?: boolean } = {}): void {
+ this.broadcast({ type: 'research', data: { state: armed ? 'armed' : 'off', topic: info.topic ?? null, planFirst: !!info.planFirst, targetId } });
+ }
+
+ /**
+ * A line about the turn that is not its answer: "the provider stalled,
+ * retrying". Sent as text_done it ended the turn on screen while the work
+ * went on.
+ */
+ sendNotice(message: string, targetId?: string, level: 'info' | 'warning' = 'info'): void {
+ this.broadcast({ type: 'notice', data: { message, level, targetId } });
}
/**
@@ -142,8 +204,18 @@ export class WebChannel extends BaseChannel {
case 'choice_prompt':
data = { kind: 'needs_you', id: d.id, prompt: String(d.prompt ?? d.question ?? '').slice(0, 300) };
break;
+ case 'research_plan':
+ data = { kind: 'needs_you', id: d.id, prompt: `Research plan ready: ${String(d.topic ?? '').slice(0, 200)}` };
+ break;
+ case 'research':
+ // A finished (or cut-short) research run: the notification can say what came of it.
+ if (d.state === 'done' || d.state === 'partial' || d.state === 'stopped' || d.state === 'failed') {
+ data = { kind: 'research', state: d.state, topic: String(d.topic ?? '').slice(0, 200), read: d.read, cited: d.cited, failed: d.failed, report: (d.report as { name?: string } | undefined)?.name };
+ }
+ break;
case 'permission_resolved':
case 'choice_resolved':
+ case 'research_plan_resolved':
data = { kind: 'resolved', id: d.id };
break;
case 'text_done': {
@@ -446,12 +518,13 @@ export class WebChannel extends BaseChannel {
}
sendStepDone(toolName: string, result: unknown, targetId?: string): void {
- const summary = typeof result === 'string'
- ? result.slice(0, 200)
- : String(result).slice(0, 200);
+ const text = typeof result === 'string' ? result : String(result);
+ const summary = text.slice(0, 200);
+ // Whether it failed, decided here: "HTTP 403 …" and "timed out" are text, not errors.
+ const reason = stepFailure(toolName, text);
this.broadcast({
type: 'step_done',
- data: { tool: toolName, summary, targetId },
+ data: { tool: toolName, summary, failed: reason !== null, ...(reason ? { reason } : {}), targetId },
});
}
diff --git a/src/core/agent.ts b/src/core/agent.ts
index bf0a1740..655d87d6 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -1,7 +1,7 @@
import { generateText, streamText, stepCountIs } from 'ai';
import path from 'node:path';
import { homedir } from 'node:os';
-import { existsSync, readdirSync } from 'node:fs';
+import { existsSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs';
import { getHeapStatistics } from 'node:v8';
import type { ChannelMessage, ChannelType } from '../types/channel.js';
import type { ProviderRegistry } from '../providers/registry.js';
@@ -45,6 +45,7 @@ import { WebChannel } from '../channels/web.js';
import type { ArrowSelectOption } from '../utils/arrow-select.js';
import { setAskUserHandler } from '../capabilities/interaction/ask-user.js';
import { classifyResearchIntent } from './research-intent.js';
+import { coverageSection, parsePlanLines, reportBody, reportFileName, RESEARCH_PLAN_SYSTEM, RESEARCH_WRITE_SYSTEM, sourcesAppendix, unansweredFrom, type ResearchRun } from './research-run.js';
import type { SpotifyClient } from '../spotify/client.js';
import { fallbackSessionTitle, isThinOpening, normalizeGeneratedSessionTitle, SessionResolutionError, type SessionRepository } from '../sessions/index.js';
import { PLAYER_CONTROLS, handlePlayerAction, formatNowPlaying } from '../spotify/ui.js';
@@ -97,7 +98,7 @@ import { verbPoolFor } from '../ui/status-word.js';
import { StallWatchdog } from './stall-watchdog.js';
import { setProgressPulse } from './progress-pulse.js';
import { selectActiveTools } from './tool-exposure.js';
-import { createTaskSurface } from './task-surface.js';
+import { createTaskSurface, type DoneInput } from './task-surface.js';
import { buildFileChangePreview } from '../utils/file-preview.js';
import { whatsNewText } from '../utils/whats-new.js';
import { handleBotsCommand as handleBotsCommandImpl } from './commands/bots-command.js';
@@ -429,6 +430,21 @@ class ToolCallLoopDetector {
* envelope, so failures were detected by accident and the loop detector's
* failed flag never fired.
*/
+/**
+ * The result of toolCalls[i]. Results of parallel calls don't always come
+ * back in call order, so match by the call's id; by position only when there
+ * is no id. (By position, a fetch_url step showed a search's results.)
+ */
+export function resultFor(toolCalls: readonly unknown[] | undefined, toolResults: readonly unknown[] | undefined, i: number): unknown {
+ if (!toolResults) return undefined;
+ const id = (toolCalls?.[i] as { toolCallId?: unknown } | undefined)?.toolCallId;
+ if (typeof id === 'string' && id) {
+ const match = toolResults.find((r) => (r as { toolCallId?: unknown } | null)?.toolCallId === id);
+ if (match !== undefined) return match;
+ }
+ return toolResults[i];
+}
+
export function toolResultValue(tr: unknown): unknown {
if (tr && typeof tr === 'object') {
const o = tr as { output?: unknown; result?: unknown };
@@ -1166,6 +1182,112 @@ export class Agent {
});
}
+ /** Tell screens how a research run stands (the desktop's chip, panel and report card). */
+ private emitResearch(msg: ChannelMessage, run: ResearchRun): void {
+ const channel = this.channels.getChannelForMessage(msg);
+ if (channel instanceof WebChannel) channel.sendResearch(run.snapshot(), msg.channelId);
+ }
+
+ /** How long a proposed research plan waits for Start before it starts as proposed. */
+ private static readonly RESEARCH_PLAN_WAIT_MS = 10 * 60 * 1000;
+
+ /**
+ * Plan first: one small model call proposes the sub-questions; the owner
+ * edits them and presses Start, or cancels. False = cancelled. A plan that
+ * can't be drafted just starts the research (the owner asked for it).
+ */
+ private async planResearch(msg: ChannelMessage, channel: WebChannel, run: ResearchRun): Promise<boolean> {
+ run.phase = 'planning';
+ this.emitResearch(msg, run);
+ this.markProgress('Planning the research...');
+ let questions: string[] = [];
+ try {
+ const model = this.providers.getDefault().getModelInstance();
+ const out = await generateText({ model, system: RESEARCH_PLAN_SYSTEM, messages: [{ role: 'user', content: run.topic }], maxOutputTokens: 400 });
+ questions = parsePlanLines(out.text);
+ } catch (err) {
+ logger.warn({ err: err instanceof Error ? err.message : String(err) }, 'Research plan: drafting failed; starting without one');
+ }
+ if (!questions.length) {
+ channel.sendNotice("Couldn't draft a plan, so the research is starting without one.", msg.channelId, 'warning');
+ return true;
+ }
+ run.setQuestions(questions);
+ this.emitResearch(msg, run);
+ // Waiting for the owner is not a stall.
+ const keepAlive = setInterval(() => this.markProgress('Waiting for you to start the research...'), 20_000);
+ try {
+ const answer = await channel.askResearchPlan(run.id, run.topic, questions, msg.channelId, Agent.RESEARCH_PLAN_WAIT_MS);
+ if (answer.action === 'cancel') {
+ run.end('cancelled', 'you cancelled it');
+ return false;
+ }
+ run.setQuestions(answer.questions);
+ if (answer.timedOut) channel.sendNotice('No answer on the plan, so the research started with it as proposed.', msg.channelId);
+ channel.sendPlan(run.questions.map((label) => ({ label, status: 'pending' })), msg.channelId);
+ return true;
+ } finally {
+ clearInterval(keepAlive);
+ this.markProgress('Starting the research...');
+ }
+ }
+
+ /**
+ * The report from the pages a run read, without the conversation: for a
+ * run cut short. Tries the default model, then the others.
+ */
+ private async writeResearchFromNotes(run: ResearchRun): Promise<string | null> {
+ const notes = run.notesText();
+ if (!notes.trim()) return null;
+ const names = [this.providers.getDefault().name, ...this.providers.listAvailable()].filter((n, i, a) => a.indexOf(n) === i);
+ const prompt = `Research question: ${run.topic}\n${run.questions.length ? `Sub-questions:\n${run.questions.map((q) => `- ${q}`).join('\n')}\n` : ''}\nSource notes (what was read before the research stopped):\n\n${notes}`;
+ for (const name of names.slice(0, 4)) {
+ const provider = this.providers.get(name);
+ if (!provider) continue;
+ try {
+ const out = await generateText({ model: provider.getModelInstance(), system: RESEARCH_WRITE_SYSTEM, messages: [{ role: 'user', content: prompt }], maxOutputTokens: 6000 });
+ const text = out.text.trim();
+ if (text) return text;
+ } catch (err) {
+ logger.warn({ provider: name, err: err instanceof Error ? err.message : String(err) }, 'Research: report writing failed on this provider');
+ }
+ }
+ return null;
+ }
+
+ /** Keep a research report as a file with the conversation (Artifacts), with every source consulted. */
+ private saveResearchReport(run: ResearchRun, text: string, threadId: string): Artifact | null {
+ try {
+ const dir = path.join(getMercuryHome(), 'research');
+ mkdirSync(dir, { recursive: true });
+ const title = /^#\s+(.+)$/m.exec(text)?.[1]?.trim() || run.topic;
+ const file = path.join(dir, reportFileName(title, run.startedAt));
+ const appendix = sourcesAppendix(run);
+ writeFileSync(file, `${text.trim()}\n${appendix ? `\n---\n\n${appendix}\n` : ''}`, 'utf-8');
+ const saved = artifactStore().add({ threadId, path: file, kind: 'text', tool: 'research', surface: 'chat' });
+ run.report = { ...artifactRef(saved) };
+ return saved;
+ } catch (err) {
+ logger.warn({ err: err instanceof Error ? err.message : String(err) }, 'Research: saving the report failed');
+ return null;
+ }
+ }
+
+ /**
+ * "Write the report now" from a screen: stop searching and write it from
+ * what was read. False when there's no research running in that chat.
+ */
+ finishResearch(sessionId: string): { ok: boolean; reason?: string } {
+ const run = this.researchMode.currentRun();
+ if (!run || run.sessionId !== sessionId || run.outcome !== 'running') return { ok: false, reason: 'No research is running in this chat.' };
+ if (run.readCount() === 0) return { ok: false, reason: 'Nothing has been read yet, so there is nothing to write from. Stop it instead, or let it read a few sources.' };
+ if (!this.currentAbort || this.currentAbort.signal.aborted) return { ok: false, reason: 'The research is already finishing.' };
+ run.finishRequested = true;
+ this.currentAbortReason = 'stopped';
+ this.currentAbort.abort();
+ return { ok: true };
+ }
+
/** One small model call: does this message ask for a full research article? */
private async wantsResearch(text: string): Promise<boolean> {
let model: ReturnType<ReturnType<ProviderRegistry['getDefault']>['getModelInstance']>;
@@ -1199,9 +1321,10 @@ export class Agent {
// research-shaped question asks again. Quick answer is listed FIRST, so
// the picker starts on it and an accidental Enter never starts a long
// research run.
+ const planOption = channel instanceof WebChannel ? ['Full research, show me the plan first'] : [];
const choice = await this.presentChoiceWithTimeout(
`This looks like a research question. ${explanation}\n\nHow do you want to proceed?`,
- ['Quick answer (normal conversation)', 'Full research mode (deep, multi-source article)'],
+ ['Quick answer (normal conversation)', 'Full research mode (deep, multi-source article)', ...planOption],
msg.channelId,
msg.channelType,
MERCURY_CODE_HANDOFF_TIMEOUT_MS,
@@ -1209,9 +1332,11 @@ export class Agent {
);
if (choice.toLowerCase().startsWith('full')) {
- this.researchMode.setOn(msg.content.trim().slice(0, 120));
+ const planFirst = /plan first/i.test(choice);
+ this.researchMode.setOn(msg.content.trim().slice(0, 160), { sessionId: msg.channelId, planFirst });
if (channel instanceof WebChannel) {
- channel.sendHeartbeat('Research mode: On. Gathering sources and building the article now — this may take a while.', msg.channelId);
+ // The research chip says it from here on (state, phase, sources).
+ channel.sendResearchArmed(true, msg.channelId, { topic: msg.content.trim().slice(0, 160), planFirst });
} else {
await channel.send('Research mode: **On**. Gathering sources and building the article now — this may take a while.', msg.channelId).catch(() => {});
}
@@ -1784,12 +1909,11 @@ export class Agent {
logger.warn({ elapsedSec, stallSec, msgId: msg.id }, 'Foreground task stalled — aborting');
this.currentAbortReason = 'stalled';
this.currentAbort.abort();
- if (channel) {
- void channel.send(
- `Mercury detected a stalled provider after ${stallSec}s without progress. Reconnecting and retrying automatically.`,
- msg.channelId,
- ).catch((e) => logger.warn({ e }, 'channel send failed'));
- }
+ const stallLine = `Mercury detected a stalled provider after ${stallSec}s without progress. Reconnecting and retrying automatically.`;
+ // On the apps this is a note in the running turn, not its answer
+ // (sent as a reply, it ended the turn on screen while the retry ran).
+ if (channel instanceof WebChannel) channel.sendNotice(stallLine, msg.channelId, 'warning');
+ else if (channel) void channel.send(stallLine, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));
timer = setTimeout(tick, HEARTBEAT_MAX_MS);
return;
}
@@ -1798,12 +1922,17 @@ export class Agent {
const handoffHint = elapsedMs >= LONG_TASK_HANDOFF_SUGGEST_MS
? '\nUse /bg current to move to background.'
: '';
+ const stepBudget = this.saverMode.adjustMaxSteps(MAX_STEPS) * this.researchMode.getMaxStepsMultiplier();
const stepInfo = this.completedStepCount > 0
- ? ` · step ${this.completedStepCount}/${MAX_STEPS}`
+ ? ` · step ${this.completedStepCount}/${stepBudget}`
+ : '';
+ const run = this.researchMode.currentRun();
+ const researchInfo = run && run.sessionId === msg.channelId
+ ? ` · researching: ${run.snapshot().searches} searches, ${run.readCount()} sources read${run.failedSources().length ? `, ${run.failedSources().length} failed` : ''}`
: '';
const narrative = formatNarrative(this.stepNarrative, this.currentActivity, 3);
const narrativeBlock = narrative ? `\n${narrative}` : '';
- const heartbeatText = `⏳ Working... ${elapsedSec}s elapsed${stepInfo}.${narrativeBlock}${handoffHint}`;
+ const heartbeatText = `⏳ Working... ${elapsedSec}s elapsed${stepInfo}${researchInfo}.${narrativeBlock}${handoffHint}`;
// CLI: update one message in place instead of stacking new ones.
// Web/cloud: send a non-terminal heartbeat so the cloud response handler stays alive.
@@ -2663,6 +2792,11 @@ export class Agent {
this.markProgress('Starting...');
this.pushLiveActivity('Starting task');
};
+ // Research switched on for this chat: this message is the run.
+ const researchRun = !isSlashCommand && msg.channelType !== 'internal' && this.researchMode.armedForSession(msg.channelId)
+ ? this.researchMode.beginRun(msg.channelId, msg.content, this.saverMode.adjustMaxSteps(MAX_STEPS) * 3)
+ : null;
+ if (researchRun) this.emitResearch(msg, researchRun);
if (!isSlashCommand) raiseTurnIndicator();
const stopHeartbeat = isSlashCommand ? () => {} : this.startForegroundHeartbeat(msg);
const heapBaseline = process.memoryUsage().heapUsed;
@@ -3007,6 +3141,8 @@ export class Agent {
let cliResponseStreamed = false;
let requiresContinuationApproval = false;
let memoryPressureStop = false;
+ // Why a research run is ending before its article ("you asked it to finish now").
+ let researchCut: string | null = null;
const loopDetector = new ToolCallLoopDetector();
let loopWarningSent = false;
let selfCheckCount = 0;
@@ -3045,11 +3181,19 @@ export class Agent {
surface: this.programmingMode.isActive() ? 'code' : 'chat',
mercuryHome: getMercuryHome(),
});
+ // Research runs: every search and page read, shown live as it happens.
+ const observeResearch = (tool: string, input: unknown, value: unknown): void => {
+ if (!researchRun) return;
+ try {
+ researchRun.observe(tool, input, value);
+ this.emitResearch(msg, researchRun);
+ } catch { /* watching must never break a turn */ }
+ };
const noteToolSteps = (toolCalls: readonly any[] | undefined, toolResults: readonly any[] | undefined): void => {
if (!toolCalls || !toolResults) return;
for (let i = 0; i < toolCalls.length; i++) {
const tc = toolCalls[i];
- const raw = toolResultValue(toolResults[i]);
+ const raw = toolResultValue(resultFor(toolCalls, toolResults, i));
const text = typeof raw === 'string' ? raw : JSON.stringify(raw ?? '');
turnToolTrace.push(formatToolTraceLine({
tool: tc.toolName,
@@ -3087,6 +3231,81 @@ export class Agent {
const surface = createTaskSurface(channel, msg.channelType, msg.channelId);
surface.begin();
+ // Research, plan first: propose the sub-questions, let the owner edit
+ // them, and start (or not) on their word. Only screens that can show
+ // an editable plan get this; elsewhere the run starts straight away.
+ if (researchRun?.planFirst) {
+ if (channel instanceof WebChannel) {
+ const suffixBefore = this.researchMode.getSystemPromptSuffix();
+ const go = await this.planResearch(msg, channel, researchRun);
+ // The prompt was built before the plan existed: give the model the approved one.
+ if (go && suffixBefore) systemPrompt = systemPrompt.replace(suffixBefore, this.researchMode.getSystemPromptSuffix());
+ if (!go) {
+ if (this.currentWorkKey) {
+ this.workLedger.markCompleted(this.currentWorkKey, 'Research cancelled before it started.');
+ this.workLedger.markDelivered(this.currentWorkKey);
+ }
+ await channel.send('Research cancelled. Nothing was searched.', msg.channelId).catch(() => {});
+ this.lifecycle.transition('idle');
+ return;
+ }
+ }
+ researchRun.phase = 'searching';
+ this.emitResearch(msg, researchRun);
+ }
+
+ /**
+ * A research run that can't finish normally (a stop with "write the
+ * report now", the step budget, every provider failing) still gives
+ * the owner a report: written from the pages it read, with what it
+ * couldn't cover. False when there's nothing to write from, or the
+ * writing failed too; the caller's own ending then applies.
+ */
+ const deliverResearchReport = async (cut: string): Promise<boolean> => {
+ if (!researchRun || !channel || msg.channelType === 'internal' || researchRun.readCount() === 0) return false;
+ researchRun.phase = 'writing';
+ this.emitResearch(msg, researchRun);
+ this.markProgress('Writing the report from what was gathered...');
+ const body = await this.writeResearchFromNotes(researchRun).catch((err) => {
+ logger.warn({ err: err instanceof Error ? err.message : String(err) }, 'Research: writing the report from notes failed');
+ return null;
+ });
+ if (!body) return false;
+ const unanswered = unansweredFrom(channel instanceof WebChannel ? channel.plans.get(msg.channelId)?.steps : undefined);
+ researchRun.markCited(body);
+ const coverage = coverageSection(researchRun, { cut, unanswered });
+ const text = coverage ? `${body}\n\n${coverage}` : body;
+ researchRun.end('partial', cut);
+ const saved = canonicalSessionId ? this.saveResearchReport(researchRun, text, canonicalSessionId) : null;
+ if (canonicalSessionId) {
+ this.sessions.appendMessage(canonicalSessionId, {
+ role: 'assistant',
+ content: text,
+ externalMessageId: `${msg.id}:assistant`,
+ metadata: {
+ channelType: msg.channelType, channelId: msg.channelId, traceId,
+ elapsedMs: Date.now() - startTime, steps: this.completedStepCount,
+ research: researchRun.snapshot(),
+ ...(saved ? { artifacts: [artifactRef(saved)] } : {}),
+ },
+ });
+ }
+ if (saved) this.announceArtifacts(channel, [saved], msg.channelId);
+ if (this.currentWorkKey) this.workLedger.markCompleted(this.currentWorkKey, text);
+ const reportDone: DoneInput = {
+ finalText: text,
+ elapsedMs: Date.now() - startTime,
+ stepCount: this.completedStepCount,
+ meta: { provider: 'unknown', model: 'unknown', inputTokens: 0, outputTokens: 0, totalTokens: 0, budgetUsed: this.tokenBudget.getDailyUsed(), budgetTotal: this.tokenBudget.getBudget(), budgetPercentage: this.tokenBudget.getUsagePercentage() },
+ traceId,
+ alreadyStreamed: false,
+ };
+ await surface.done(reportDone);
+ if (this.currentWorkKey) this.workLedger.markDelivered(this.currentWorkKey);
+ this.lifecycle.transition('idle');
+ return true;
+ };
+
// Saver-mode-aware request limits. When saver is off these resolve to
// the original constants (byte-identical to pre-saver behavior).
let effectiveMaxOutputTokens = this.saverMode.adjustMaxOutputTokens(MODEL_OUTPUT_TOKEN_LIMIT);
@@ -3172,17 +3391,18 @@ export class Agent {
if (typeof cmd === 'string') {
executeCommandsRun.push(cmd);
if (VERIFICATION_COMMAND_PATTERN.test(cmd)) {
- const vResult = toolResultValue(toolResults[i]);
+ const vResult = toolResultValue(resultFor(toolCalls, toolResults, i));
const vText = typeof vResult === 'string' ? vResult : JSON.stringify(vResult ?? '');
recordVerification(cmd, vText);
}
}
}
- const trValue = toolResultValue(toolResults[i]);
+ const trValue = toolResultValue(resultFor(toolCalls, toolResults, i));
recordExecuteToolResult(tc.toolName, trValue);
this.maybeShowFileChange(channel, msg, tc.toolName, tc.input, trValue);
this.maybeRecordPlanProgress(channel, tc.toolName, tc.input, msg.channelId);
artifactCollector.observe(tc.toolName, tc.input, trValue, this.capabilities.getCwd());
+ observeResearch(tc.toolName, tc.input, trValue);
const resultStr = typeof trValue === 'string' ? trValue : JSON.stringify(trValue ?? '');
const failed = resultStr.length < 5000 && (
resultStr.startsWith('Error:') ||
@@ -3302,7 +3522,7 @@ export class Agent {
}
if (toolResults) {
for (let i = 0; i < toolResults.length; i++) {
- const tr = toolResults[i] as any;
+ const tr = resultFor(toolCalls, toolResults, i) as any;
const tcName = toolCalls[i]?.toolName as string | undefined;
if (tcName) {
(channel as CLIChannel).sendStepDone(tcName, toolResultValue(tr));
@@ -3316,7 +3536,7 @@ export class Agent {
}
if (toolResults) {
for (let i = 0; i < toolResults.length; i++) {
- const tr = toolResults[i] as any;
+ const tr = resultFor(toolCalls, toolResults, i) as any;
const tcName = toolCalls[i]?.toolName as string | undefined;
if (tcName) {
void tgCh.sendStepDone(tcName, toolResultValue(tr), msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));
@@ -3330,7 +3550,7 @@ export class Agent {
}
if (toolResults) {
for (let i = 0; i < toolResults.length; i++) {
- const tr = toolResults[i] as any;
+ const tr = resultFor(toolCalls, toolResults, i) as any;
const tcName = toolCalls[i]?.toolName as string | undefined;
if (tcName) {
void sigCh.sendStepDone(tcName, toolResultValue(tr), msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));
@@ -3344,7 +3564,7 @@ export class Agent {
}
if (toolResults) {
for (let i = 0; i < toolResults.length; i++) {
- const tr = toolResults[i] as any;
+ 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);
@@ -3358,7 +3578,7 @@ export class Agent {
}
if (toolResults) {
for (let i = 0; i < toolResults.length; i++) {
- const tr = toolResults[i] as any;
+ const tr = resultFor(toolCalls, toolResults, i) as any;
const tcName = toolCalls[i]?.toolName as string | undefined;
if (tcName) {
void dcCh.sendStepDone(tcName, toolResultValue(tr), msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));
@@ -3372,7 +3592,7 @@ export class Agent {
}
if (toolResults) {
for (let i = 0; i < toolResults.length; i++) {
- const tr = toolResults[i] as any;
+ const tr = resultFor(toolCalls, toolResults, i) as any;
const tcName = toolCalls[i]?.toolName as string | undefined;
if (tcName) {
void Promise.resolve(slCh.sendStepDone(tcName, toolResultValue(tr), msg.channelId)).catch((e) => logger.warn({ e }, 'channel send failed'));
@@ -3428,16 +3648,17 @@ export class Agent {
if (typeof cmd === 'string') {
executeCommandsRun.push(cmd);
if (VERIFICATION_COMMAND_PATTERN.test(cmd)) {
- const vResult = toolResultValue(toolResults[i]);
+ const vResult = toolResultValue(resultFor(toolCalls, toolResults, i));
const vText = typeof vResult === 'string' ? vResult : JSON.stringify(vResult ?? '');
recordVerification(cmd, vText);
}
}
}
- recordExecuteToolResult(tc.toolName, toolResultValue(toolResults[i]));
- this.maybeShowFileChange(channel, msg, tc.toolName, tc.input, toolResultValue(toolResults[i]));
+ recordExecuteToolResult(tc.toolName, toolResultValue(resultFor(toolCalls, toolResults, i)));
+ this.maybeShowFileChange(channel, msg, tc.toolName, tc.input, toolResultValue(resultFor(toolCalls, toolResults, i)));
this.maybeRecordPlanProgress(channel, tc.toolName, tc.input, msg.channelId);
- artifactCollector.observe(tc.toolName, tc.input, toolResultValue(toolResults[i]), this.capabilities.getCwd());
+ artifactCollector.observe(tc.toolName, tc.input, toolResultValue(resultFor(toolCalls, toolResults, i)), this.capabilities.getCwd());
+ observeResearch(tc.toolName, tc.input, toolResultValue(resultFor(toolCalls, toolResults, i)));
loopDetector.record(tc.toolName, tc.input as Record<string, any>, false);
}
}
@@ -3755,10 +3976,18 @@ export class Agent {
continue;
}
if (this.currentAbortReason === 'backgrounded') {
+ researchRun?.end('stopped', 'it was moved to the background');
result = { text: 'This task was moved to the background and will report back when it finishes.', usage: undefined };
break;
}
+ if (this.currentAbortReason === 'stopped' && researchRun?.finishRequested && researchRun.readCount() > 0) {
+ // "Write the report now": stop searching, keep what was read.
+ this.currentAbortReason = null;
+ researchCut = 'you asked it to finish now';
+ break;
+ }
if (this.currentAbortReason === 'stopped' || this.currentAbortReason === 'halted') {
+ researchRun?.end('stopped', 'you stopped it');
result = { text: `⏹ Task ${this.currentAbortReason}. Its work entry was cancelled — a restart will not resume it. Send the request again or ask me to continue if you change your mind.`, usage: undefined };
this.currentAbortReason = null;
break;
@@ -3814,6 +4043,12 @@ export class Agent {
}
}
+ if (!result && researchRun && !memoryPressureStop) {
+ const cut = researchCut ?? (lastError ? `of an error (${whitelabelProviderError(lastError)})` : 'it was interrupted');
+ if (await deliverResearchReport(cut)) return;
+ researchRun.end('failed', cut);
+ }
+
if (!result) {
const failureBlock = providerFailures.size > 0
? `\nPer-provider:\n- ${[...providerFailures.entries()].slice(0, 8).map(([name, reason]) => `${name}: ${reason}`).join('\n- ')}`
@@ -4039,7 +4274,7 @@ export class Agent {
for (let i = 0; i < toolCalls.length; i++) {
const tc = toolCalls[i];
executeTurnToolsUsed.add(tc.toolName);
- const guardToolResult = toolResultValue(toolResults[i]);
+ const guardToolResult = toolResultValue(resultFor(toolCalls, toolResults, i));
recordExecuteToolResult(tc.toolName, guardToolResult);
// Remember WHY the work did not land, so an honest pause
// can tell the user what actually blocked it.
@@ -4050,6 +4285,7 @@ export class Agent {
this.maybeShowFileChange(channel, msg, tc.toolName, tc.input, guardToolResult);
this.maybeRecordPlanProgress(channel, tc.toolName, tc.input, msg.channelId);
artifactCollector.observe(tc.toolName, tc.input, guardToolResult, this.capabilities.getCwd());
+ observeResearch(tc.toolName, tc.input, guardToolResult);
loopDetector.record(tc.toolName, tc.input as Record<string, any>, false);
}
}
@@ -4257,6 +4493,8 @@ export class Agent {
if (!loopAbortController.signal.aborted && turnEnd() === 'steps-exhausted') {
logger.warn({ steps: lastRoundSteps, budget: effectiveMaxSteps }, 'Step budget exhausted past continuation bound — pausing task honestly');
+ if (await deliverResearchReport(`it used its whole step budget (${effectiveMaxSteps} steps)`)) return;
+ researchRun?.end('failed', `it used its whole step budget (${effectiveMaxSteps} steps)`);
await pauseHonestly(
STEPS_PAUSED_BANNER,
'Step budget reached with work pending. Send "continue" to resume with a fresh budget.',
@@ -4315,7 +4553,26 @@ export class Agent {
// Recompute AFTER the guard: the continuation's output (not the
// original narration) must be what reaches the session store, the
// work ledger, and the final delivery.
- const finalText = (result.text || '').trim() || '(no text response)';
+ let finalText = (result.text || '').trim() || '(no text response)';
+ let researchReportText: string | null = null;
+
+ // A research run: an empty answer still gets a report from what was
+ // read; a finished one says what it couldn't read and is kept as a file.
+ if (researchRun && researchRun.outcome === 'running') {
+ if (!(result.text || '').trim()) {
+ if (await deliverResearchReport('the model returned no text')) return;
+ researchRun.end('failed', 'the model returned no text');
+ } else {
+ researchReportText = reportBody(finalText, researchRun.writtenArticle);
+ researchRun.markCited(researchReportText);
+ const coverage = coverageSection(researchRun);
+ if (coverage) {
+ finalText = `${finalText}\n\n${coverage}`;
+ researchReportText = `${researchReportText}\n\n${coverage}`;
+ }
+ researchRun.end('done');
+ }
+ }
// Store plan output when in plan mode for later execution
if (this.programmingMode.isPlan() && preGuardText !== '(no text response)') {
@@ -4367,6 +4624,10 @@ export class Agent {
if (canonicalSessionId && artifactCollector.size > 0) {
try { turnArtifacts = artifactCollector.finalize(canonicalSessionId, artifactStore()); } catch (err) { logger.warn({ err }, 'Keeping artifacts failed'); }
}
+ if (researchRun?.outcome === 'done' && canonicalSessionId) {
+ const saved = this.saveResearchReport(researchRun, researchReportText ?? finalText, canonicalSessionId);
+ if (saved) turnArtifacts = [saved, ...turnArtifacts.filter((a) => a.id !== saved.id)];
+ }
if (canonicalSessionId) {
if (turnToolTrace.length > 0) {
this.sessions.appendMessage(canonicalSessionId, {
@@ -4401,6 +4662,7 @@ export class Agent {
outputTokens: result.usage?.outputTokens ?? 0,
...(lastVerificationNote ? { verification: lastVerificationNote } : {}),
...(turnArtifacts.length ? { artifacts: turnArtifacts.map(artifactRef) } : {}),
+ ...(researchRun ? { research: researchRun.snapshot() } : {}),
},
});
if (turnArtifacts.length && channel) this.announceArtifacts(channel, turnArtifacts, msg.channelId);
@@ -4525,6 +4787,11 @@ export class Agent {
} catch { /* best effort */ }
this.lifecycle.transition('idle');
} finally {
+ if (researchRun) {
+ researchRun.end('failed', 'it ended before writing a report');
+ this.emitResearch(msg, researchRun);
+ this.researchMode.endRun();
+ }
clearInterval(memoryGuard);
stallWatchdog.stop();
stopHeartbeat();
diff --git a/src/core/commands/chat-command.ts b/src/core/commands/chat-command.ts
index d9a5e296..2b53baf9 100644
--- a/src/core/commands/chat-command.ts
+++ b/src/core/commands/chat-command.ts
@@ -36,7 +36,7 @@ import {
} from '../../utils/config.js';
import { MAX_STEPS } from '../agent.js';
import path from 'node:path';
-import type { ChannelMessage, ChannelType } from '../../types/channel.js';
+import type { ChannelType } from '../../types/channel.js';
import { createProvider, ProviderRegistry as ProviderRegistryImpl } from '../../providers/registry.js';
import { ProgrammingMode } from '../programming-mode.js';
import { logger } from '../../utils/logger.js';
@@ -1204,56 +1204,90 @@ export async function handleChatCommand(agent: Agent, content: string, channelTy
if (cmd.startsWith('/research')) {
const rawArgs = trimmed.slice('/research'.length).trim();
+ const sub = rawArgs.toLowerCase();
+ const web = channel instanceof WebChannel ? channel : null;
+ // Research a message as a real user turn in this chat: the same session
+ // as the command (without it the turn, and its report, went to another one).
+ const asked = agent.currentMessage?.channelId === channelId ? agent.currentMessage : null;
+ const research = (content: string, opts: { topic?: string; planFirst?: boolean } = {}): void => {
+ agent.researchMode.setOn(opts.topic ?? content.slice(0, 160), { sessionId: channelId, planFirst: opts.planFirst });
+ web?.sendResearchArmed(true, channelId, { topic: opts.topic ?? content.slice(0, 160), planFirst: opts.planFirst });
+ agent.enqueueMessage({
+ id: `research-${Date.now().toString(36)}`,
+ channelId,
+ channelType: channelType as ChannelType,
+ senderId: 'user',
+ senderName: 'You',
+ content,
+ timestamp: Date.now(),
+ ...(asked?.sessionId ? { sessionId: asked.sessionId } : {}),
+ ...(asked?.metadata ? { metadata: { ...asked.metadata } } : {}),
+ });
+ };
- if (!rawArgs || rawArgs.toLowerCase() === 'status') {
+ if (!rawArgs || sub === 'status') {
await channel.send(agent.researchMode.getStatusText(), channelId);
return true;
}
- if (rawArgs.toLowerCase() === 'on') {
- agent.researchMode.setOn();
- await channel.send(
- 'Research mode: **On**\nI will perform deep, multi-source web research and produce a full markdown research article. Long tasks are expected. Use `/research off` to exit.',
- channelId,
- );
+ if (sub === 'on' || sub === 'plan') {
+ agent.researchMode.setOn(undefined, { sessionId: channelId, planFirst: sub === 'plan' });
+ web?.sendResearchArmed(true, channelId, { planFirst: sub === 'plan' });
+ await channel.send(`Research: **On** for your next message here${sub === 'plan' ? ' (plan first)' : ''}. I'll search live sources, cross-check them and write a full report; then research switches off again. \`/research off\` cancels.`, channelId);
return true;
}
- if (rawArgs.toLowerCase() === 'off') {
+ if (sub === 'off') {
agent.researchMode.setOff();
- await channel.send('Research mode: **Off**\nBack to normal conversation mode.', channelId);
+ web?.sendResearchArmed(false, channelId);
+ await channel.send('Research: **Off**. Back to normal conversation.', channelId);
return true;
}
- if (rawArgs.toLowerCase() === 'toggle') {
- const newState = agent.researchMode.toggle();
- await channel.send(`Research mode: **${newState === 'on' ? 'On' : 'Off'}**`, channelId);
+ if (sub === 'toggle') {
+ const on = !agent.researchMode.armedForSession(channelId);
+ if (on) agent.researchMode.setOn(undefined, { sessionId: channelId });
+ else agent.researchMode.setOff();
+ web?.sendResearchArmed(on, channelId);
+ await channel.send(`Research: **${on ? 'On' : 'Off'}**${on ? ' for your next message here' : ''}`, channelId);
return true;
}
- // Treat remaining args as a topic + enable research mode
- agent.researchMode.setOn(rawArgs);
- if (channel instanceof WebChannel) {
- channel.sendHeartbeat(`Research mode: On. Topic: ${rawArgs}. I will gather live sources and produce a full research article.`, channelId);
- } else {
- await channel.send(
- `Research mode: **On**\nTopic: ${rawArgs}\nI will gather live sources and produce a full research article. Use \`/research off\` to exit.`,
- channelId,
- );
+ // Pick up where the last run in this chat left off.
+ if (sub === 'continue' || sub === 'retry') {
+ const last = agent.researchMode.runFor(channelId);
+ if (!last) {
+ await channel.send('There is no earlier research in this chat to continue. Use `/research <topic>` to start one.', channelId);
+ return true;
+ }
+ const snap = last.snapshot();
+ if (sub === 'retry') {
+ const failed = last.failedSources().slice(0, 12);
+ if (!failed.length) {
+ await channel.send('Every source in the last research was read; there is nothing to retry.', channelId);
+ return true;
+ }
+ research(`Retry the sources that couldn't be read in the research on "${snap.topic}", then update the report with anything new. Try each once more; if one fails again, find another source for the same point.\n${failed.map((f) => `- ${f.url} (${f.reason ?? 'failed'})`).join('\n')}`, { topic: snap.topic });
+ return true;
+ }
+ const gaps = [
+ ...(snap.cut ? [`it stopped early because ${snap.cut}`] : []),
+ ...last.failedSources().slice(0, 8).map((f) => `${f.domain} couldn't be read (${f.reason ?? 'failed'})`),
+ ];
+ research(`Continue the research on "${snap.topic}". Build on the report already in this conversation: keep what it established, fill in what it doesn't cover, and write the full updated report.${gaps.length ? `\nKnown gaps:\n${gaps.map((g) => `- ${g}`).join('\n')}` : ''}`, { topic: snap.topic });
+ return true;
}
- // Enqueue the topic as a real user message so the agent immediately
- // begins researching it, rather than only setting mode + topic and
- // waiting for the user to repeat themselves.
- const researchTopicMsg: ChannelMessage = {
- id: `research-${Date.now().toString(36)}`,
- channelId,
- channelType: channelType as ChannelType,
- senderId: 'user',
- senderName: 'You',
- content: rawArgs,
- timestamp: Date.now(),
- };
- agent.enqueueMessage(researchTopicMsg);
+
+ // "/research plan <topic>": show the plan before starting.
+ const planned = /^plan\s+(.+)$/is.exec(rawArgs);
+ if (planned) {
+ research(planned[1].trim(), { planFirst: true });
+ return true;
+ }
+
+ // Anything else is the topic: research it now.
+ if (!web) await channel.send(`Research: **On**\nTopic: ${rawArgs}\nI'll gather live sources and write a full report.`, channelId);
+ research(rawArgs);
return true;
}
diff --git a/src/core/commands/slash-list.ts b/src/core/commands/slash-list.ts
index 1b315b4e..b5ee39be 100644
--- a/src/core/commands/slash-list.ts
+++ b/src/core/commands/slash-list.ts
@@ -74,6 +74,9 @@ export const SLASH_COMMANDS: readonly string[] = [
'/research on',
'/research off',
'/research toggle',
+ '/research plan ',
+ '/research continue',
+ '/research retry',
'/research ',
'/spotify',
'/budget',
diff --git a/src/core/research-mode.ts b/src/core/research-mode.ts
index 14d462f5..390183c7 100644
--- a/src/core/research-mode.ts
+++ b/src/core/research-mode.ts
@@ -1,82 +1,147 @@
import { logger } from '../utils/logger.js';
+import { ResearchRun, type ResearchSnapshot } from './research-run.js';
+
export type ResearchModeState = 'off' | 'on';
+/**
+ * Research is one run, not a sticky mode. "On" means the next message in the
+ * chat that asked (or any chat, when none was named) is researched; when that
+ * run ends — finished, cut short, stopped — research is off again, so the
+ * follow-up "thanks" isn't a 225-step research pass in every chat.
+ */
export class ResearchMode {
private state: ResearchModeState = 'off';
private topic: string | null = null;
+ /** The chat it was switched on for; null = whichever message comes next. */
+ private armedFor: string | null = null;
+ private planFirst = false;
+ private run: ResearchRun | null = null;
+ /** The last run in each chat, for Continue / Retry and screens that open later. */
+ private lastRuns = new Map<string, ResearchRun>();
getState(): ResearchModeState {
- return this.state;
+ return this.run ? 'on' : this.state;
}
isActive(): boolean {
- return this.state === 'on';
+ return this.state === 'on' || this.run !== null;
}
- setOn(topic?: string): void {
+ setOn(topic?: string, opts: { sessionId?: string; planFirst?: boolean } = {}): void {
this.state = 'on';
this.topic = topic || null;
- logger.info({ topic: this.topic }, 'Research mode: on');
+ this.armedFor = opts.sessionId ?? null;
+ this.planFirst = !!opts.planFirst;
+ logger.info({ topic: this.topic, sessionId: this.armedFor, planFirst: this.planFirst }, 'Research mode: on');
}
+ /** Off for the next message; a run already going finishes (Stop ends it). */
setOff(): void {
this.state = 'off';
this.topic = null;
+ this.armedFor = null;
+ this.planFirst = false;
logger.info('Research mode: off');
}
toggle(): ResearchModeState {
- if (this.state === 'off') {
- this.state = 'on';
- } else {
- this.state = 'off';
- this.topic = null;
- }
+ if (this.state === 'off') this.setOn();
+ else this.setOff();
logger.info({ state: this.state }, 'Research mode toggled');
return this.state;
}
+ /** Is research switched on for this chat's next message? */
+ armedForSession(sessionId: string): boolean {
+ return this.state === 'on' && (this.armedFor === null || this.armedFor === sessionId);
+ }
+
+ isPlanFirst(): boolean {
+ return this.planFirst;
+ }
+
+ /** The message that starts the run arrived: research it. */
+ beginRun(sessionId: string, content: string, maxSteps: number): ResearchRun {
+ const run = new ResearchRun(this.topic || content.trim().slice(0, 160), sessionId, maxSteps, this.planFirst);
+ this.state = 'off';
+ this.armedFor = null;
+ this.planFirst = false;
+ this.run = run;
+ this.lastRuns.set(sessionId, run);
+ if (this.lastRuns.size > 50) this.lastRuns.delete(this.lastRuns.keys().next().value as string);
+ logger.info({ runId: run.id, sessionId, topic: run.topic }, 'Research run started');
+ return run;
+ }
+
+ currentRun(): ResearchRun | null {
+ return this.run;
+ }
+
+ /** The run for this chat: the one going, else its last one. */
+ runFor(sessionId: string): ResearchRun | null {
+ if (this.run?.sessionId === sessionId) return this.run;
+ return this.lastRuns.get(sessionId) ?? null;
+ }
+
+ /** What a screen opening this chat should show. */
+ stateFor(sessionId: string): { armed: boolean; planFirst: boolean; topic: string | null; run: ResearchSnapshot | null } {
+ const run = this.runFor(sessionId);
+ return { armed: this.armedForSession(sessionId), planFirst: this.planFirst, topic: this.topic, run: run ? run.snapshot() : null };
+ }
+
+ /** The run's turn is over (however it ended). Research is off again. */
+ endRun(): void {
+ if (!this.run) return;
+ if (this.run.outcome === 'running') this.run.end('done');
+ logger.info({ runId: this.run.id, outcome: this.run.outcome }, 'Research run ended');
+ this.run = null;
+ this.topic = null;
+ }
+
setTopic(topic: string): void {
this.topic = topic;
}
getTopic(): string | null {
- return this.topic;
+ return this.run?.topic ?? this.topic;
}
getStatusText(): string {
+ if (this.run) return `Research: running | Topic: ${this.run.topic}`;
if (this.state === 'off') return 'Research mode: Off';
- let text = 'Research mode: On';
+ let text = 'Research mode: On (for your next message)';
if (this.topic) text += ` | Topic: ${this.topic}`;
return text;
}
/**
- * Multiplier applied to the per-task tool-call cap while research mode is active.
+ * Multiplier applied to the per-task tool-call cap while a research run is going.
* Research requires many fetch/search iterations; keep the hard cap but raise it.
*/
getMaxStepsMultiplier(): number {
- return this.state === 'on' ? 3 : 1;
+ return this.run ? 3 : 1;
}
/**
- * Multiplier applied to the foreground stall timeout while research mode is active.
+ * Multiplier applied to the foreground stall timeout while a research run is going.
* Research tasks run long by design; do not abort them as stalled.
*/
getStallMsMultiplier(): number {
- return this.state === 'on' ? 4 : 1;
+ return this.run ? 4 : 1;
}
getSystemPromptSuffix(): string {
- if (this.state === 'off') return '';
+ if (!this.run) return '';
let suffix = '\n\n**RESEARCH MODE IS ACTIVE**';
suffix += '\nMode: RESEARCH';
suffix += '\nYou are performing deep research for the user. Your job is to produce a thorough, well-structured research article, not a quick chat answer.';
suffix += '\n\nResearch workflow:';
- suffix += '\n1. Break the question into sub-questions and plan which sources to consult.';
+ suffix += this.run.questions.length
+ ? `\n1. The owner approved this plan. Call update_plan once with exactly these steps, then mark each one active and done as you cover it:\n${this.run.questions.map((q, i) => ` ${i + 1}. ${q}`).join('\n')}`
+ : '\n1. Break the question into 3-6 sub-questions. Call update_plan with them as steps, and mark each one active and done as you cover it — the owner watches that list.';
suffix += '\n2. ALWAYS use web_search and fetch_url to gather real, current information from the web. Do not rely on memory or prior knowledge for facts, dates, or news — verify everything live.';
suffix += '\n3. Build a visual plan while researching. Actively inspect source pages for relevant photos, diagrams, charts, maps, or infographics and preserve their original direct image URLs.';
suffix += '\n4. Cross-check claims across multiple sources. Prefer primary sources, official statements, and reputable outlets.';
@@ -91,12 +156,12 @@ export class ResearchMode {
suffix += '\n- Embed images as `![specific descriptive alt text](https://direct-image-url)` using the original public image URL, not a webpage URL, search-result thumbnail, local file, or invented URL.';
suffix += '\n- Prefer informative visuals over decoration. Do not repeat an image, and omit only when diligent source review finds no safe, relevant public image.';
suffix += '\n- Include a `## Sources` section at the end listing all URLs consulted.';
- suffix += '\n- The final markdown is treated as the research artifact and will be rendered as a full article on Mercury Cloud.';
- suffix += '\n\nIf the user asks a follow-up in the same thread, treat it as a refinement of this research: reuse the context, gather more if needed, and update or extend the article accordingly. If something is unclear, ask a short clarifying question before spending a long research pass.';
+ suffix += '\n- Write the whole article in your final reply, not in a file: Mercury saves your reply as the report file itself. Do not create or write a file for it, and do not reply with only a summary.';
+ suffix += '\n- Between tool calls, say nothing (no "Let me search…"); the owner sees each step live.';
+ suffix += '\n- When a source fails (blocked, timed out, not found), try another source for the same point; do not retry the same URL more than once. Mercury lists failed sources for the owner itself, so do not add your own list of them.';
+ suffix += '\n\nIf the conversation already holds an earlier report on this topic, build on it: keep what it established and extend or correct it.';
- if (this.topic) {
- suffix += `\n\nResearch topic: ${this.topic}`;
- }
+ suffix += `\n\nResearch topic: ${this.run.topic}`;
return suffix;
}
diff --git a/src/core/research-run.test.ts b/src/core/research-run.test.ts
new file mode 100644
index 00000000..aa6b09ee
--- /dev/null
+++ b/src/core/research-run.test.ts
@@ -0,0 +1,150 @@
+import { describe, expect, it } from 'vitest';
+import { coverageSection, fetchFailure, parsePlanLines, reportBody, reportFileName, ResearchRun, sourcesAppendix, stepFailure, unansweredFrom } from './research-run.js';
+import { ResearchMode } from './research-mode.js';
+
+const page = (title: string) => `# ${title}\n\n${'Real page text about the topic. '.repeat(20)}`;
+
+describe('fetch failures', () => {
+ it('names why a page could not be read', () => {
+ expect(fetchFailure('HTTP 403 Forbidden for https://x.com/a')).toBe('blocked or behind a login (HTTP 403)');
+ expect(fetchFailure('HTTP 404 Not Found for https://x.com/a')).toBe('page not found (HTTP 404)');
+ expect(fetchFailure('HTTP 429 Too Many Requests for https://x.com')).toBe('rate-limited (HTTP 429)');
+ expect(fetchFailure('HTTP 503 Service Unavailable for https://x.com')).toBe('the site had an error (HTTP 503)');
+ expect(fetchFailure('Request to https://x.com timed out after 30 seconds.')).toBe('timed out after 30 s');
+ expect(fetchFailure('Error fetching https://x.com: getaddrinfo ENOTFOUND x.com')).toBe('getaddrinfo ENOTFOUND x.com');
+ expect(fetchFailure('Enable JavaScript')).toMatch(/almost no readable text/);
+ expect(fetchFailure(page('A real article'))).toBeNull();
+ });
+
+ it('marks failed steps that used to show a green check', () => {
+ expect(stepFailure('fetch_url', 'HTTP 403 Forbidden for https://x.com')).toMatch(/HTTP 403/);
+ expect(stepFailure('fetch_url', 'Request to https://x.com timed out after 30 seconds.')).toMatch(/timed out/);
+ expect(stepFailure('web_search', 'Error: web search found nothing')).toBeTruthy();
+ expect(stepFailure('fetch_url', page('fine'))).toBeNull();
+ // A short but real tool result elsewhere is not a failure.
+ expect(stepFailure('read_file', 'ok')).toBeNull();
+ });
+});
+
+describe('a research run', () => {
+ it('counts searches, reads and failures, and keeps a page read once as read', () => {
+ const run = new ResearchRun('solar storms', 's1', 225);
+ run.observe('web_search', { query: 'solar storm 2026' }, 'Results:\n1. https://a.org/x\n2. https://b.org/y');
+ run.observe('web_search', { query: 'nothing' }, 'Error: web search found nothing: no source found anything (Parallel: timed out). Tell the owner which sources were tried');
+ run.observe('fetch_url', { url: 'https://a.org/x' }, page('Solar storms explained'));
+ run.observe('fetch_url', { url: 'https://paywall.com/p' }, 'HTTP 403 Forbidden for https://paywall.com/p');
+ run.observe('fetch_url', { url: 'https://a.org/x' }, 'Request to https://a.org/x timed out after 30 seconds.');
+ const s = run.snapshot();
+ expect(s).toMatchObject({ searches: 2, failedSearches: 1, read: 1, failed: 1, steps: 5, phase: 'reading', state: 'running' });
+ expect(s.searchList[0].results).toBe(2);
+ expect(s.searchList[1].reason).toMatch(/Parallel: timed out/);
+ expect(s.sourceList.find((x) => x.url === 'https://a.org/x')).toMatchObject({ status: 'read', title: 'Solar storms explained', domain: 'a.org' });
+ expect(run.notesText()).toContain('### Source: https://a.org/x');
+ });
+
+ it('a retry that works replaces the failure', () => {
+ const run = new ResearchRun('t', 's1', 10);
+ run.observe('fetch_url', { url: 'https://x.org' }, 'HTTP 503 Service Unavailable for https://x.org');
+ run.observe('fetch_url', { url: 'https://x.org' }, page('Back up'));
+ expect(run.snapshot()).toMatchObject({ read: 1, failed: 0 });
+ });
+
+ it('marks cited sources and lists all of them with the report', () => {
+ const run = new ResearchRun('t', 's1', 10);
+ run.observe('fetch_url', { url: 'https://a.org/x' }, page('A'));
+ run.observe('fetch_url', { url: 'https://b.org/y' }, page('B'));
+ run.markCited('As [A says](https://a.org/x), …');
+ expect(run.snapshot().cited).toBe(1);
+ const appendix = sourcesAppendix(run);
+ expect(appendix).toContain('✓ cited · [A](https://a.org/x)');
+ expect(appendix).toContain('· read · [B](https://b.org/y)');
+ });
+
+ it('ends once', () => {
+ const run = new ResearchRun('t', 's1', 10);
+ run.end('stopped', 'you stopped it');
+ run.end('done');
+ expect(run.snapshot()).toMatchObject({ state: 'stopped', cut: 'you stopped it' });
+ });
+});
+
+describe('coverage & gaps', () => {
+ it('is empty for a clean finished run', () => {
+ const run = new ResearchRun('t', 's1', 10);
+ run.observe('fetch_url', { url: 'https://a.org' }, page('A'));
+ expect(coverageSection(run)).toBe('');
+ });
+
+ it('says why a cut run is incomplete, what is not covered, and what failed', () => {
+ const run = new ResearchRun('t', 's1', 10);
+ run.observe('fetch_url', { url: 'https://a.org' }, page('A'));
+ run.observe('fetch_url', { url: 'https://b.org/p' }, 'HTTP 403 Forbidden for https://b.org/p');
+ run.observe('web_search', { query: 'q' }, 'Error: web search found nothing: blocked (429)');
+ const text = coverageSection(run, { cut: 'you asked it to finish now', unanswered: unansweredFrom([{ label: 'Costs', status: 'pending' }, { label: 'History', status: 'done' }, { label: 'Synthesize findings into a report', status: 'pending' }]) });
+ expect(text).toContain('## Coverage & gaps');
+ expect(text).toContain('stopped early because you asked it to finish now');
+ expect(text).toContain('from the 1 source read');
+ expect(text).toContain('- Costs');
+ expect(text).not.toContain('- History');
+ expect(text).not.toContain('Synthesize');
+ expect(text).toContain('[b.org](https://b.org/p): blocked or behind a login (HTTP 403)');
+ expect(text).toContain('“q”');
+ });
+});
+
+describe('helpers', () => {
+ it('reads plan lines and names report files', () => {
+ expect(parsePlanLines('# Sub-questions for Solar Storms\n\nWhat causes solar storms?')).toEqual(['What causes solar storms?']);
+ expect(parsePlanLines('Sub-questions:\n1. What causes solar storms?\n- How are they forecast?\n• What did the May 2024 storm do?\nok')).toEqual([
+ 'What causes solar storms?', 'How are they forecast?', 'What did the May 2024 storm do?',
+ ]);
+ expect(reportFileName('Solar Storms: A Guide!', new Date(2026, 10, 2, 9, 5).getTime())).toBe('2026-11-02-0905-solar-storms-a-guide.md');
+ });
+});
+
+describe('research mode is one run', () => {
+ it('applies to the chat that asked, then switches off', () => {
+ const mode = new ResearchMode();
+ mode.setOn('topic', { sessionId: 'a' });
+ expect(mode.armedForSession('b')).toBe(false);
+ expect(mode.armedForSession('a')).toBe(true);
+ expect(mode.getMaxStepsMultiplier()).toBe(1);
+ const run = mode.beginRun('a', 'what about it', 225);
+ expect(run.topic).toBe('topic');
+ expect(mode.getMaxStepsMultiplier()).toBe(3);
+ expect(mode.getSystemPromptSuffix()).toContain('RESEARCH MODE IS ACTIVE');
+ expect(mode.armedForSession('a')).toBe(false);
+ mode.endRun();
+ expect(mode.isActive()).toBe(false);
+ expect(mode.getSystemPromptSuffix()).toBe('');
+ expect(mode.stateFor('a').run?.state).toBe('done');
+ expect(mode.stateFor('b').run).toBeNull();
+ });
+
+ it('puts an approved plan in the prompt', () => {
+ const mode = new ResearchMode();
+ mode.setOn(undefined, { planFirst: true });
+ const run = mode.beginRun('a', 'solar storms', 225);
+ expect(run.planFirst).toBe(true);
+ run.setQuestions(['What causes them?', 'How are they forecast?']);
+ expect(mode.getSystemPromptSuffix()).toContain('1. What causes them?');
+ });
+});
+
+describe('the report kept', () => {
+ it('drops the narration before the article', () => {
+ expect(reportBody("I'll research this.\n\nNow let me search:\n\n# Solar storms\n\nBody")).toBe('# Solar storms\n\nBody');
+ expect(reportBody('No heading, just text')).toBe('No heading, just text');
+ });
+
+ it('uses the article the model saved to a file when the reply is only a summary', () => {
+ const run = new ResearchRun('t', 's1', 10);
+ const article = `# Solid-state batteries\n\n${'A long article paragraph. '.repeat(100)}`;
+ run.observe('create_file', { path: '/Users/me/ssb.md', content: article }, 'Successfully created /Users/me/ssb.md (19811 bytes)');
+ run.observe('write_file', { path: '/Users/me/notes.txt', content: 'x'.repeat(5000) }, 'ok');
+ expect(run.writtenArticle?.path).toBe('/Users/me/ssb.md');
+ expect(reportBody('Done. Here is a summary: key takeaways…', run.writtenArticle)).toBe(article.trim());
+ // A real article in the reply wins over a short file.
+ expect(reportBody(article, { content: '# Short\n\nnotes' })).toBe(article.trim());
+ });
+});
diff --git a/src/core/research-run.ts b/src/core/research-run.ts
new file mode 100644
index 00000000..980fbdfc
--- /dev/null
+++ b/src/core/research-run.ts
@@ -0,0 +1,333 @@
+import { randomUUID } from 'node:crypto';
+
+/**
+ * One research run, watched from the outside: every search and every page
+ * Mercury tried to read, and how each went. The owner sees this live
+ * (phase, counts, which sources failed and why), the report ends with what
+ * it couldn't cover, and a run cut short (a stop, the step budget, a
+ * provider failure) still becomes a report written from what was read.
+ *
+ * Nothing here talks to a model or a channel; the agent feeds it tool steps
+ * and reads snapshots.
+ */
+
+export type ResearchPhase = 'planning' | 'searching' | 'reading' | 'writing';
+export type ResearchOutcome = 'done' | 'partial' | 'stopped' | 'failed' | 'cancelled';
+
+export interface ResearchSource {
+ url: string;
+ domain: string;
+ title?: string;
+ status: 'read' | 'failed';
+ /** Why it couldn't be read, in plain words ("blocked (HTTP 403)"). */
+ reason?: string;
+ /** The report links to it. */
+ cited?: boolean;
+ at: number;
+}
+
+export interface ResearchSearch {
+ query: string;
+ results: number;
+ ok: boolean;
+ reason?: string;
+ at: number;
+}
+
+/** What screens get: the run as it stands. */
+export interface ResearchSnapshot {
+ runId: string;
+ topic: string;
+ state: 'running' | ResearchOutcome;
+ phase: ResearchPhase;
+ questions: string[];
+ startedAt: number;
+ endedAt?: number;
+ steps: number;
+ maxSteps: number;
+ searches: number;
+ failedSearches: number;
+ read: number;
+ failed: number;
+ cited: number;
+ sourceList: ResearchSource[];
+ searchList: ResearchSearch[];
+ /** Why it ended before a finished article, when it did. */
+ cut?: string;
+ /** The saved report (an artifact ref), once there is one. */
+ report?: { id: string; name: string; path: string; size: number; kind: string; mime: string };
+}
+
+const MAX_SOURCES = 120;
+const MAX_SEARCHES = 60;
+/** Page text kept per source and in total, to write a report from if the run is cut short. */
+const NOTE_PER_SOURCE = 4_000;
+const NOTES_TOTAL = 80_000;
+
+export function domainOf(url: string): string {
+ try { return new URL(url).hostname.replace(/^www\./, ''); } catch { return url.slice(0, 60); }
+}
+
+/**
+ * Why a fetch_url result is a failure, or null when it's a page. fetch_url
+ * reports failures as text ("HTTP 403 Forbidden for …", "… timed out …"),
+ * never as an error, so every screen showed them as read.
+ */
+export function fetchFailure(result: string): string | null {
+ const t = result.trim();
+ const http = /^HTTP (\d{3})\b/.exec(t);
+ if (http) {
+ const code = Number(http[1]);
+ if (code === 401 || code === 402 || code === 403) return `blocked or behind a login (HTTP ${code})`;
+ if (code === 404 || code === 410) return `page not found (HTTP ${code})`;
+ if (code === 429) return 'rate-limited (HTTP 429)';
+ if (code >= 500) return `the site had an error (HTTP ${code})`;
+ return `HTTP ${code}`;
+ }
+ if (/^Request to .* timed out/i.test(t)) return 'timed out after 30 s';
+ if (/^Error fetching /i.test(t)) return t.replace(/^Error fetching \S+:\s*/i, '').slice(0, 120) || 'could not connect';
+ if (/^Error:/i.test(t)) return t.replace(/^Error:\s*/i, '').slice(0, 120);
+ if (/^(blocked|denied)\b/i.test(t)) return t.slice(0, 120);
+ if (t.length < 200 && !/https?:\/\//.test(t)) return 'almost no readable text (needs a browser or a login)';
+ return null;
+}
+
+/** Is a step summary a failure? The same rules every screen should use. */
+export function stepFailure(tool: string, result: string): string | null {
+ const t = result.trim();
+ if (tool === 'fetch_url' && /^(HTTP [45]\d\d\b|Request to .* timed out|Error fetching )/i.test(t)) return fetchFailure(t);
+ if (/^(error|failed|denied|blocked)\b/i.test(t)) return t.replace(/^error:\s*/i, '').slice(0, 160);
+ return null;
+}
+
+function titleFromPage(text: string): string | undefined {
+ const h = /^#\s+(.+)$/m.exec(text) ?? /<title>([^<]{3,160})<\/title>/i.exec(text);
+ return h ? h[1].trim().slice(0, 140) : undefined;
+}
+
+export class ResearchRun {
+ readonly id = randomUUID().slice(0, 12);
+ readonly startedAt = Date.now();
+ phase: ResearchPhase = 'searching';
+ questions: string[] = [];
+ steps = 0;
+ /** The owner asked to stop searching and write the report now. */
+ finishRequested = false;
+ outcome: 'running' | ResearchOutcome = 'running';
+ endedAt?: number;
+ cut?: string;
+ report?: ResearchSnapshot['report'];
+ private sources = new Map<string, ResearchSource>();
+ private searchList: ResearchSearch[] = [];
+ private notes = new Map<string, string>();
+ private notesSize = 0;
+ /** A markdown article the model saved to a file during the run (some do, despite being asked not to). */
+ writtenArticle?: { path: string; content: string };
+
+ constructor(
+ readonly topic: string,
+ readonly sessionId: string,
+ readonly maxSteps: number,
+ readonly planFirst = false,
+ ) {
+ if (planFirst) this.phase = 'planning';
+ }
+
+ /** One finished tool call. */
+ observe(tool: string, input: unknown, result: unknown): void {
+ this.steps++;
+ const args = (input ?? {}) as Record<string, unknown>;
+ const text = typeof result === 'string' ? result : JSON.stringify(result ?? '');
+ if (tool === 'web_search') {
+ this.phase = 'searching';
+ const query = typeof args.query === 'string' ? args.query : '';
+ const failed = /^Error:/i.test(text.trim());
+ const results = failed ? 0 : new Set(text.match(/https?:\/\/[^\s)\]>"']+/g) ?? []).size;
+ const reason = failed ? text.replace(/^Error:\s*(web search found nothing:\s*)?/i, '').split('. Tell the owner')[0].slice(0, 200) : undefined;
+ this.searchList.push({ query: query.slice(0, 200), results, ok: !failed, ...(reason ? { reason } : {}), at: Date.now() });
+ if (this.searchList.length > MAX_SEARCHES) this.searchList.shift();
+ return;
+ }
+ if ((tool === 'write_file' || tool === 'create_file') && typeof args.path === 'string' && /\.(md|markdown)$/i.test(args.path)) {
+ const content = typeof args.content === 'string' ? args.content : '';
+ if (content.length > 800 && !/^(Error|⚠)/.test(text.trim()) && content.length > (this.writtenArticle?.content.length ?? 0)) {
+ this.writtenArticle = { path: args.path, content };
+ }
+ return;
+ }
+ if (tool === 'fetch_url') {
+ this.phase = 'reading';
+ const url = typeof args.url === 'string' ? args.url : '';
+ if (!url) return;
+ const reason = fetchFailure(text);
+ const prev = this.sources.get(url);
+ // A page read once stays read; a retry that worked replaces a failure.
+ if (prev?.status === 'read' && reason) return;
+ this.sources.set(url, {
+ url, domain: domainOf(url), status: reason ? 'failed' : 'read',
+ ...(reason ? { reason } : { title: titleFromPage(text) }), at: Date.now(),
+ });
+ if (this.sources.size > MAX_SOURCES) this.sources.delete(this.sources.keys().next().value as string);
+ if (!reason) this.keepNote(url, text);
+ }
+ }
+
+ private keepNote(url: string, text: string): void {
+ if (this.notesSize >= NOTES_TOTAL || this.notes.has(url)) return;
+ const note = text.slice(0, Math.min(NOTE_PER_SOURCE, NOTES_TOTAL - this.notesSize));
+ this.notes.set(url, note);
+ this.notesSize += note.length;
+ }
+
+ /** The model started writing the answer. */
+ writing(): void {
+ this.phase = 'writing';
+ }
+
+ setQuestions(questions: string[]): void {
+ this.questions = questions.map((q) => q.trim()).filter(Boolean).slice(0, 8);
+ }
+
+ readCount(): number {
+ return [...this.sources.values()].filter((s) => s.status === 'read').length;
+ }
+
+ failedSources(): ResearchSource[] {
+ return [...this.sources.values()].filter((s) => s.status === 'failed');
+ }
+
+ failedSearches(): ResearchSearch[] {
+ return this.searchList.filter((s) => !s.ok);
+ }
+
+ /** Mark the sources the report links to. */
+ markCited(report: string): void {
+ for (const s of this.sources.values()) {
+ if (s.status === 'read' && report.includes(s.url.replace(/[#?].*$/, ''))) s.cited = true;
+ }
+ }
+
+ /** What was read, for writing a report without the conversation. */
+ notesText(): string {
+ return [...this.notes.entries()].map(([url, text]) => `### Source: ${url}\n${text}`).join('\n\n');
+ }
+
+ end(outcome: ResearchOutcome, cut?: string): void {
+ if (this.outcome !== 'running') return;
+ this.outcome = outcome;
+ this.endedAt = Date.now();
+ if (cut) this.cut = cut;
+ }
+
+ snapshot(): ResearchSnapshot {
+ const list = [...this.sources.values()];
+ return {
+ runId: this.id,
+ topic: this.topic,
+ state: this.outcome,
+ phase: this.phase,
+ questions: this.questions,
+ startedAt: this.startedAt,
+ ...(this.endedAt ? { endedAt: this.endedAt } : {}),
+ steps: this.steps,
+ maxSteps: this.maxSteps,
+ searches: this.searchList.length,
+ failedSearches: this.failedSearches().length,
+ read: list.filter((s) => s.status === 'read').length,
+ failed: list.filter((s) => s.status === 'failed').length,
+ cited: list.filter((s) => s.cited).length,
+ sourceList: list.slice(-80),
+ searchList: this.searchList.slice(-30),
+ ...(this.cut ? { cut: this.cut } : {}),
+ ...(this.report ? { report: this.report } : {}),
+ };
+ }
+}
+
+/**
+ * "Coverage & gaps": what the report couldn't cover and why. Always added
+ * to a report written after a cut; added to a finished one only when
+ * something failed, so a clean report stays clean.
+ */
+export function coverageSection(run: ResearchRun, opts: { cut?: string; unanswered?: string[] } = {}): string {
+ const failed = run.failedSources();
+ const failedSearches = run.failedSearches();
+ const unanswered = opts.unanswered ?? [];
+ if (!opts.cut && failed.length === 0 && failedSearches.length === 0 && unanswered.length === 0) return '';
+ const lines: string[] = ['## Coverage & gaps', ''];
+ const read = run.readCount();
+ if (opts.cut) lines.push(`This report is incomplete: the research stopped early because ${opts.cut}. It is written from the ${read} source${read === 1 ? '' : 's'} read before that.`, '');
+ if (unanswered.length) {
+ lines.push('**Not covered yet:**');
+ for (const q of unanswered.slice(0, 8)) lines.push(`- ${q}`);
+ lines.push('');
+ }
+ if (failed.length) {
+ lines.push(`**Sources that couldn't be read (${failed.length}):**`);
+ for (const s of failed.slice(0, 20)) lines.push(`- [${s.domain}](${s.url}): ${s.reason ?? 'failed'}`);
+ if (failed.length > 20) lines.push(`- …and ${failed.length - 20} more`);
+ lines.push('');
+ }
+ if (failedSearches.length) {
+ lines.push(`**Searches that found nothing (${failedSearches.length}):**`);
+ for (const s of failedSearches.slice(0, 8)) lines.push(`- “${s.query}”${s.reason ? `: ${s.reason}` : ''}`);
+ lines.push('');
+ }
+ return lines.join('\n').trimEnd();
+}
+
+/** The sources list saved with the report file: everything consulted, and how it went. */
+export function sourcesAppendix(run: ResearchRun): string {
+ const s = run.snapshot();
+ if (!s.sourceList.length) return '';
+ const lines = ['## All sources consulted', ''];
+ for (const src of s.sourceList) {
+ const mark = src.status === 'failed' ? `✗ ${src.reason ?? 'failed'}` : src.cited ? '✓ cited' : '· read';
+ lines.push(`- ${mark} · [${src.title ?? src.domain}](${src.url})`);
+ }
+ return lines.join('\n');
+}
+
+/** Plan steps the model hasn't marked done: what the report doesn't cover yet. */
+export function unansweredFrom(plan: Array<{ label: string; status: string }> | undefined): string[] {
+ // "Write the report" steps are the writing, not a question the report misses.
+ const writing = /^(synthesi[sz]e|write|compile|draft|summari[sz]e|produce|create|assemble|finali[sz]e)\b/i;
+ return (plan ?? []).filter((s) => s.status !== 'done' && !writing.test(s.label.trim())).map((s) => s.label);
+}
+
+/**
+ * The report to keep: the article itself. A reply usually is the article;
+ * some models save it to a file and reply with a summary, and a reply can
+ * open with the narration of earlier steps ("Let me search…"), which the
+ * file doesn't need.
+ */
+export function reportBody(reply: string, written?: { content: string }): string {
+ const fromHeading = (t: string): string => {
+ const at = t.search(/^#\s+\S/m);
+ return at > 0 ? t.slice(at) : t;
+ };
+ const body = fromHeading(reply.trim());
+ if (written && written.content.trim().length > body.length * 1.5) return fromHeading(written.content.trim());
+ return body;
+}
+
+export function reportFileName(topic: string, at = Date.now()): string {
+ const d = new Date(at);
+ const stamp = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}-${String(d.getHours()).padStart(2, '0')}${String(d.getMinutes()).padStart(2, '0')}`;
+ const slug = topic.toLowerCase().normalize('NFKD').replace(/[^\w\s-]/g, '').trim().replace(/[\s_]+/g, '-').replace(/-+/g, '-').slice(0, 50).replace(/-$/, '') || 'research';
+ return `${stamp}-${slug}.md`;
+}
+
+/** The sub-questions a plan-first run proposes, from the model's lines. */
+export function parsePlanLines(text: string): string[] {
+ return text.split('\n')
+ // Headings and preambles ("# Sub-questions for …", "Here is the plan:") aren't questions.
+ .filter((l) => !/^\s*#/.test(l) && !/:\s*$/.test(l))
+ .map((l) => l.replace(/^\s*(?:[-*•]|\d+[.)])\s*/, '').replace(/^\*\*(.+)\*\*$/, '$1').trim())
+ .filter((l) => l.length >= 6 && l.length <= 200)
+ .slice(0, 7);
+}
+
+export const RESEARCH_PLAN_SYSTEM = `You plan a research report. Given the owner's question, write 3 to 6 sub-questions that together answer it fully, one per line, no numbering, no preamble. Each is short and specific, and checkable against sources on the web.`;
+
+export const RESEARCH_WRITE_SYSTEM = `You write a research report from source notes. Use ONLY what the notes say; never add facts from memory. Rich markdown: a "# Title", a short TL;DR, "##" sections, inline links to the sources ("[according to …](url)"), and a "## Sources" list at the end. Where the notes don't cover something, say so plainly instead of guessing.`;
diff --git a/src/core/tool-result-order.test.ts b/src/core/tool-result-order.test.ts
new file mode 100644
index 00000000..0435e7d1
--- /dev/null
+++ b/src/core/tool-result-order.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from 'vitest';
+import { resultFor } from './agent.js';
+
+describe('tool results', () => {
+ it('pair with their call by id, not by position', () => {
+ const calls = [{ toolCallId: 'a', toolName: 'web_search' }, { toolCallId: 'b', toolName: 'fetch_url' }];
+ const results = [{ toolCallId: 'b', output: 'page' }, { toolCallId: 'a', output: 'search results' }];
+ expect(resultFor(calls, results, 0)).toEqual({ toolCallId: 'a', output: 'search results' });
+ expect(resultFor(calls, results, 1)).toEqual({ toolCallId: 'b', output: 'page' });
+ });
+
+ it('fall back to position without ids', () => {
+ expect(resultFor([{ toolName: 'x' }], ['r0'], 0)).toBe('r0');
+ expect(resultFor([{ toolCallId: 'z' }], [{ toolCallId: 'y' }], 0)).toEqual({ toolCallId: 'y' });
+ expect(resultFor([{}], undefined, 0)).toBeUndefined();
+ });
+});
diff --git a/src/index.ts b/src/index.ts
index 7df20363..51d77ed4 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -96,7 +96,7 @@ import { selectWithArrowKeys } from './utils/arrow-select.js';
import { ProviderModelFetchError, fetchProviderModelCatalog } from './utils/provider-models.js';
import { initCloudTokenStore } from './cloud/token-store.js';
import { clearCloudRuntimeOnline, markCloudRuntimeOnline } from './cloud/runtime-status.js';
-import { startWebServer, stopWebServer, updateStatus as updateWebStatus, setUserMemory as setWebUserMemory, setWebChannel as setWebWebChannel, setScheduler as setWebScheduler, setAgentSupervisor as setWebSupervisor, setBackgroundTaskManager as setWebBgTasks, setSpotifyClient as setWebSpotify, setProgrammingMode as setWebProgrammingMode, setModelSwitchCallback as setWebModelSwitch, setCurrentProviderCallback as setWebCurrentProvider, setStatusSnapshotCallback as setWebStatusSnapshot, setKanbanSupervisor as setWebKanban, setKanbanBoardManager as setWebBoardManager, setKanbanProviders as setWebKanbanProviders, setIDEProviders as setWebIDEProviders, setSessionRepository as setWebSessions, setSessionSyncEnabledCallback as setWebSessionSyncEnabled, setBotManager as setWebBotManager, setBotsWebhookSecret, setShutdownHandler, setMcpManager as setWebMcpManager, setStopCallback as setWebStop, setSessionBusyLookup as setWebSessionBusy, setQueueControls as setWebQueueControls, setBudgetControls as setWebBudgetControls } from './web/server.js';
+import { startWebServer, stopWebServer, updateStatus as updateWebStatus, setUserMemory as setWebUserMemory, setWebChannel as setWebWebChannel, setScheduler as setWebScheduler, setAgentSupervisor as setWebSupervisor, setBackgroundTaskManager as setWebBgTasks, setSpotifyClient as setWebSpotify, setProgrammingMode as setWebProgrammingMode, setModelSwitchCallback as setWebModelSwitch, setCurrentProviderCallback as setWebCurrentProvider, setStatusSnapshotCallback as setWebStatusSnapshot, setKanbanSupervisor as setWebKanban, setKanbanBoardManager as setWebBoardManager, setKanbanProviders as setWebKanbanProviders, setIDEProviders as setWebIDEProviders, setSessionRepository as setWebSessions, setSessionSyncEnabledCallback as setWebSessionSyncEnabled, setBotManager as setWebBotManager, setBotsWebhookSecret, setShutdownHandler, setMcpManager as setWebMcpManager, setStopCallback as setWebStop, setSessionBusyLookup as setWebSessionBusy, setQueueControls as setWebQueueControls, setResearchControls as setWebResearchControls, setBudgetControls as setWebBudgetControls } from './web/server.js';
import { validateApiKey, validateBaseUrl, validateModelName } from './providers/provider-meta.js';
import { setFirstProviderHandler, setProvidersReload } from './web/api/providers.js';
import { setCloudReload } from './web/api/cloud.js';
@@ -3526,6 +3526,11 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
setWebStop(() => agent.stopAllWork('stopped'));
setWebSessionBusy((sessionId) => agent.isBusyWith(sessionId));
setWebQueueControls({ state: (id) => agent.queueStateFor(id), prioritize: (id) => agent.prioritize(id) });
+ setWebResearchControls({
+ state: (id) => agent.researchMode.stateFor(id),
+ finish: (id) => agent.finishResearch(id),
+ off: (id) => { if (agent.researchMode.armedForSession(id)) agent.researchMode.setOff(); webChannel.sendResearchArmed(false, id); },
+ });
setWebBudgetControls({ config: () => config, tokens: () => tokenBudget, saver: () => agent.saverMode });
// Titles made before they were checked: fix them once, quietly, after start-up.
if (!daemonOwnsRuntime) {
diff --git a/src/plugins/commands.test.ts b/src/plugins/commands.test.ts
index 3759c656..3b06c048 100644
--- a/src/plugins/commands.test.ts
+++ b/src/plugins/commands.test.ts
@@ -9,7 +9,7 @@ const root = dirname(fileURLToPath(import.meta.url));
describe('reserved command names', () => {
it('cover every built-in in the TUI autocomplete list (SLASH_COMMANDS)', () => {
- const src = readFileSync(join(root, '..', 'ui', 'input-composer.tsx'), 'utf8');
+ const src = readFileSync(join(root, '..', 'core', 'commands', 'slash-list.ts'), 'utf8');
const block = src.slice(src.indexOf('export const SLASH_COMMANDS'), src.indexOf('];', src.indexOf('export const SLASH_COMMANDS')));
const names = [...block.matchAll(/'\/([a-z][a-z0-9_-]*)/g)].map((m) => m[1]);
expect(names.length).toBeGreaterThan(20);
diff --git a/src/utils/manual.ts b/src/utils/manual.ts
index 4a9e20cf..098d44d3 100644
--- a/src/utils/manual.ts
+++ b/src/utils/manual.ts
@@ -134,11 +134,14 @@ export const CHAT_COMMAND_HELP: ReadonlyArray<readonly [string, string]> = [
['/code chat', 'Switch back to regular chat instantly (alias: /code back)'],
['/chat', 'Return to chat mode (tears down Mercury Code if active)'],
['/code toggle', 'Cycle through: off → auto → plan → execute → off'],
- ['/research', 'Show research mode status'],
- ['/research on', 'Enable deep research mode (web research + rich markdown article)'],
- ['/research off', 'Exit research mode'],
- ['/research toggle', 'Toggle research mode on/off'],
- ['/research <topic>', 'Enable research mode for a specific topic'],
+ ['/research', 'Show research status'],
+ ['/research on', 'Research your next message here (live sources, full report), then switch off'],
+ ['/research off', 'Cancel research for your next message'],
+ ['/research toggle', 'Switch research on/off for your next message'],
+ ['/research <topic>', 'Research a topic now'],
+ ['/research plan <topic>', 'Show the research plan first; edit it, then start'],
+ ['/research continue', 'Continue the last research here, filling its gaps'],
+ ['/research retry', "Retry the sources the last research couldn't read"],
['/ws exit', 'Exit workspace IDE mode back to general chat'],
['/ws open <path>', 'Open a workspace directory in IDE mode'],
['/ws refresh', 'Refresh file tree + git status panel'],
@@ -435,11 +438,14 @@ export function getTelegramHelp(): string {
lines.push('');
lines.push('**Research Mode**');
- lines.push('/research — Show current research mode status');
- lines.push('/research on — Enable deep web research + rich markdown article');
- lines.push('/research off — Exit research mode');
- lines.push('/research toggle — Toggle research mode');
- lines.push('/research <topic> — Enable research mode for a specific topic');
+ lines.push('/research — Show research status');
+ lines.push('/research on — Research your next message (live sources, full report), then switch off');
+ lines.push('/research off — Cancel research for your next message');
+ lines.push('/research toggle — Switch research on/off for your next message');
+ lines.push('/research <topic> — Research a topic now');
+ lines.push('/research plan <topic> — Show the plan first; edit it, then start');
+ lines.push('/research continue — Continue the last research, filling its gaps');
+ lines.push("/research retry — Retry the sources the last research couldn't read");
lines.push('');
lines.push('**Sub-Agents**');
diff --git a/src/web/api-contract.ts b/src/web/api-contract.ts
index 1cfb41af..1695dff6 100644
--- a/src/web/api-contract.ts
+++ b/src/web/api-contract.ts
@@ -51,6 +51,7 @@ export const API_FEATURES: readonly string[] = Object.freeze([
'threads.save', // POST /api/chat/threads/:id/save { saved } — thread.savedAt
'cloud.signin', // GET /api/cloud/status, POST/GET/DELETE /api/cloud/signin (browser pairing from any client) // POST /api/voice/check { vendor, key?, endpoint? }
'brain.map', // GET /api/brain/map[?archive=1] — themes, sub-themes, notes, related links
+ '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 }
]);
export interface ApiContractInfo {
diff --git a/src/web/api/chat.ts b/src/web/api/chat.ts
index 566a2709..d4cfae79 100644
--- a/src/web/api/chat.ts
+++ b/src/web/api/chat.ts
@@ -53,6 +53,7 @@ function toThread(session: ReturnType<SessionRepository['get']>, includeMessages
sequence: message.sequence,
...(typeof message.metadata?.voiceRole === 'string' ? { voice: message.metadata.voiceRole } : {}),
...(Array.isArray(message.metadata?.artifacts) && message.metadata.artifacts.length ? { artifacts: message.metadata.artifacts } : {}),
+ ...(message.metadata?.research && typeof message.metadata.research === 'object' ? { research: message.metadata.research } : {}),
...(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}` })) }
: {}),
@@ -84,6 +85,16 @@ let queueControls: { state: (threadId: string) => QueueState; prioritize: (threa
export function setQueueControls(controls: typeof queueControls): void {
queueControls = controls;
}
+
+/** Research runs per chat: what's going on, "write the report now". */
+let researchControls: {
+ state: (sessionId: string) => Record<string, unknown>;
+ finish: (sessionId: string) => { ok: boolean; reason?: string };
+ off: (sessionId: string) => void;
+} | null = null;
+export function setResearchControls(controls: typeof researchControls): void {
+ researchControls = controls;
+}
/** The same stop the terminal's Esc and `/stop` use: abort the running turn, cancel its work entry. */
export function setStopCallback(fn: () => Promise<string>): void {
stopFn = fn;
@@ -765,6 +776,36 @@ chat.post('/api/chat/threads/:id/queue/first', (c) => {
return c.json({ moved: queueControls.prioritize(c.req.param('id')) });
});
+// This chat's research: switched on for the next message, running (phase, sources…), or its last run.
+chat.get('/api/chat/threads/:id/research', (c) => {
+ if (!researchControls) return c.json({ armed: false, run: null });
+ return c.json(researchControls.state(c.req.param('id')));
+});
+
+// "Write the report now": stop searching and write the report from what was read.
+chat.post('/api/chat/threads/:id/research/finish', (c) => {
+ if (!researchControls) return c.json({ error: 'Not available on this runtime' }, 503);
+ const r = researchControls.finish(c.req.param('id'));
+ return r.ok ? c.json({ ok: true }) : c.json({ ok: false, error: r.reason }, 409);
+});
+
+// Research off for this chat's next message (a run already going is stopped with Stop).
+chat.post('/api/chat/threads/:id/research/off', (c) => {
+ if (!researchControls) return c.json({ error: 'Not available on this runtime' }, 503);
+ researchControls.off(c.req.param('id'));
+ return c.json({ ok: true });
+});
+
+// The owner's answer to a research plan: { action: 'start' | 'cancel', questions?: string[] }.
+chat.post('/api/chat/research/plan/:id', async (c) => {
+ if (!webChannel) return c.json({ error: 'Web channel not initialized' }, 503);
+ const body: { action?: unknown; questions?: unknown } = await c.req.json<{ action?: unknown; questions?: unknown }>().catch(() => ({}));
+ if (body.action !== 'start' && body.action !== 'cancel') return c.json({ error: 'Send { action: "start" } or { action: "cancel" }.' }, 400);
+ const questions = Array.isArray(body.questions) ? body.questions.filter((q): q is string => typeof q === 'string').slice(0, 8) : undefined;
+ const ok = webChannel.answerResearchPlan(c.req.param('id'), body.action, questions);
+ return ok ? c.json({ ok: true }) : c.json({ ok: false, error: 'That plan was already answered or has expired.' }, 410);
+});
+
chat.post('/api/chat/threads/:id/save', async (c) => {
const id = c.req.param('id');
if (!sessions) return c.json({ error: 'Session repository not initialized' }, 503);
diff --git a/src/web/server.ts b/src/web/server.ts
index 598034b0..910231f1 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -21,7 +21,7 @@ import artifactRoutes from './api/artifacts.js';
import configRoutes from './api/config.js';
import systemRoutes, { setScheduler } from './api/system.js';
import brainRoutes, { setUserMemory } from './api/brain.js';
-import chatRoutes, { setWebChannel, setProgrammingMode, setModelSwitchCallback, setCurrentProviderCallback, setStatusSnapshotCallback, setSessionRepository, setSessionSyncEnabledCallback, setStopCallback, setSessionBusyLookup, setQueueControls } from './api/chat.js';
+import chatRoutes, { setWebChannel, setProgrammingMode, setModelSwitchCallback, setCurrentProviderCallback, setStatusSnapshotCallback, setSessionRepository, setSessionSyncEnabledCallback, setStopCallback, setSessionBusyLookup, setQueueControls, setResearchControls } from './api/chat.js';
import agentRoutes, { setAgentSupervisor, setBackgroundTaskManager } from './api/agents.js';
import botsRoutes, { setBotManager, setBotsWebhookSecret } from './api/bots.js';
import spotifyRoutes, { setSpotifyClient } from './api/spotify.js';
@@ -234,7 +234,7 @@ if (spaAvailable) {
}
export { setShutdownHandler, setMcpManager };
-export { setStopCallback, setSessionBusyLookup, setQueueControls };
+export { setStopCallback, setSessionBusyLookup, setQueueControls, setResearchControls };
export { updateStatus, setUserMemory, setWebChannel, setScheduler, setAgentSupervisor, setBackgroundTaskManager, setSpotifyClient, setProgrammingMode, setModelSwitchCallback, setCurrentProviderCallback, setStatusSnapshotCallback, setKanbanSupervisor, setKanbanBoardManager, setKanbanProviders, setIDEProviders, setBotManager, setBotsWebhookSecret };
let webServer: ReturnType<typeof createAdaptorServer> | null = null;