Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat: stop button in Chat and Code
Salman Qureshi742c72ee3c02
diff --git a/apps/desktop/src/api/mercury.ts b/apps/desktop/src/api/mercury.tsindex e5193532..385e9845 100644--- a/apps/desktop/src/api/mercury.ts+++ b/apps/desktop/src/api/mercury.ts@@ -51,6 +51,8 @@ export const chat = {deleteThread: (id: string) => http.post<{ deleted: boolean }>(`/api/chat/threads/${encodeURIComponent(id)}/delete`, { confirmSessionId: id }),send: (content: string, sessionId?: string, attachments?: Array<{ name: string; data: string }>, code?: { programming: string; cwd?: string }) =>http.post<{ sent: boolean; sessionId: string }>("/api/chat/send", { content, sessionId, ...(attachments?.length ? { attachments } : {}), ...(code ?? {}) }),+ /** Interrupt the running turn (same as /stop). Needs the "chat.stop" feature. */+ stop: () => http.post<{ ok: boolean; note?: string }>("/api/chat/stop", {}),answer: (promptId: string, action: string, targetId?: string) => http.post<{ resolved: boolean }>(`/api/chat/permission/${encodeURIComponent(promptId)}`, { action, targetId }),settings: () => http.get<ChatSettings>("/api/chat/settings"),updateSettings: (patch: Partial<ChatSettings>) => http.put<ChatSettings>("/api/chat/settings", patch),diff --git a/apps/desktop/src/api/types.ts b/apps/desktop/src/api/types.tsindex 6c9f2cac..57680131 100644--- a/apps/desktop/src/api/types.ts+++ b/apps/desktop/src/api/types.ts@@ -53,13 +53,16 @@ export interface ChatMessage {attachments?: MessageAttachment[];/** How the answer was reached (live turns only): reasoning and steps. */trace?: ThoughtTrace;+ /** You stopped this turn; content is whatever was written before that. */+ stopped?: boolean;}export interface ThoughtStep {id: number;tool: string;label: string;- status: "running" | "done" | "error";+ /** "stopped": cut off by the stop button before it finished. */+ status: "running" | "done" | "error" | "stopped";summary?: string;startedAt: number;endedAt?: number;@@ -70,6 +73,8 @@ export interface ThoughtTrace {steps: ThoughtStep[];startedAt: number;endedAt?: number;+ /** The turn was stopped by you, not finished. */+ stopped?: boolean;}export interface MessageAttachment {diff --git a/apps/desktop/src/app/conversation.ts b/apps/desktop/src/app/conversation.tsindex 2fb52af1..ef832f3d 100644--- a/apps/desktop/src/app/conversation.ts+++ b/apps/desktop/src/app/conversation.ts@@ -23,6 +23,9 @@ export interface ConversationState {prompts: PendingPrompt[];/** The current turn's thought process, streaming. */live: ThoughtTrace | null;+ /** The stop button was pressed and the runtime hasn't confirmed yet. */+ stopping: boolean;+ setStopping(stopping: boolean): void;setLive(update: (live: ThoughtTrace) => ThoughtTrace): void;clearLive(): void;setActive(id: string | null): void;@@ -50,9 +53,11 @@ function makeConversation(surface: Surface): ConversationStore {step: null,prompts: [],live: null,+ stopping: false,+ setStopping: (stopping) => set({ stopping }),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 }),+ setActive: (activeId) => set({ activeId, prompts: [], step: null, agent: "idle", live: null, stopping: false }),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.tsindex 9bf4d91e..de236153 100644--- a/apps/desktop/src/app/events.ts+++ b/apps/desktop/src/app/events.ts@@ -123,6 +123,8 @@ function handleEvent(store: ConversationStore, event: string, raw: string): voidbreak;case "text_done": {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; }const live = store.getState().live;const trace = live && (live.reasoning || live.steps.length) ? { ...live, endedAt: Date.now(), steps: live.steps.map((st) => st.status === "running" ? { ...st, status: "done" as const, endedAt: Date.now() } : st) } : undefined;conv.clearStreaming();@@ -153,6 +155,7 @@ function handleEvent(store: ConversationStore, event: string, raw: string): voidconv.setStep(null);conv.setAgent("idle");conv.addMessage({ id: crypto.randomUUID(), role: "system", content: message, timestamp: new Date().toISOString() });+ conv.setStopping(false);break;}default:@@ -244,6 +247,51 @@ export async function sendMessage(surface: Surface, content: string, attachmentsvoid refreshThreads();}+/** The note the runtime sends back when a turn is stopped (agent.ts, "⏹ Task stopped. …"). */+export function isStopNote(text: string): boolean {+ return /^\s*⏹\s*Task (stopped|halted)\b/.test(text);+}++/**+ * Stop button. Marks what was running as stopped straight away (so the+ * screen never claims a step finished), asks the runtime to stop, and ends+ * the turn when its confirmation arrives, or after a few seconds if it+ * never does (an older runtime, or the turn ended on its own meanwhile).+ */+export async function stopTurn(store: ConversationStore): Promise<void> {+ const s = store.getState();+ if (s.stopping) return;+ s.setStopping(true);+ if (s.live) s.setLive((l) => ({ ...l, steps: l.steps.map((st) => (st.status === "running" ? { ...st, status: "stopped" as const, endedAt: Date.now() } : st)) }));+ try {+ await api.chat.stop();+ } catch (err) {+ store.getState().setStopping(false);+ throw err;+ }+ setTimeout(() => { if (store.getState().stopping) finishStopped(store); }, 8000);+}++/** End the current turn as stopped: keep the partial answer, mark the trace, say so. */+function finishStopped(store: ConversationStore): void {+ const s = store.getState();+ const partial = s.streaming;+ const live = s.live;+ const now = Date.now();+ const busy = s.agent === "thinking" || s.agent === "working" || s.agent === "streaming";+ s.clearStreaming();+ s.clearLive();+ s.setStep(null);+ s.setStopping(false);+ // Nothing was running any more (the answer finished first): nothing to mark.+ if (!busy && !partial && !live) return;+ const trace = live && (live.reasoning || live.steps.length)+ ? { ...live, stopped: true, endedAt: now, steps: live.steps.map((st) => (st.status === "running" ? { ...st, status: "stopped" as const, endedAt: now } : st)) }+ : undefined;+ s.addMessage({ id: crypto.randomUUID(), role: "assistant", content: partial, stopped: true, timestamp: new Date().toISOString(), ...(trace ? { trace } : {}) });+ s.setAgent(s.prompts.length ? "needs-you" : "idle");+}+export async function answerPrompt(store: ConversationStore, prompt: PendingPrompt, value: string | null): Promise<void> {await api.chat.answer(prompt.id, value ?? "", prompt.targetId);store.getState().removePrompt(prompt.id);diff --git a/apps/desktop/src/app/stop.test.ts b/apps/desktop/src/app/stop.test.tsnew file mode 100644index 00000000..8ba884da--- /dev/null+++ b/apps/desktop/src/app/stop.test.ts@@ -0,0 +1,62 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const stopCall = vi.fn(async () => ({ ok: true }));+vi.mock("~/api/mercury", () => ({ chat: { stop: () => stopCall() } }));++const { conversations } = await import("./conversation");+const { isStopNote, stopTurn } = await import("./events");++const store = conversations.chat;++describe("stop button", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ store.setState({ messages: [], streaming: "", live: null, agent: "idle", stopping: false, prompts: [], step: null });+ stopCall.mockClear();+ });++ it("recognises the runtime's stop note", () => {+ expect(isStopNote("⏹ Task stopped. Its work entry was cancelled — a restart will not resume it.")).toBe(true);+ expect(isStopNote("⏹ Task halted. …")).toBe(true);+ expect(isStopNote("The task stopped early because of rain.")).toBe(false);+ });++ it("marks running steps as stopped at once, never as done", async () => {+ store.setState({ agent: "working", live: { reasoning: "", startedAt: 1, steps: [+ { id: 1, tool: "read_file", label: "read_file", status: "done", startedAt: 1, endedAt: 2 },+ { id: 2, tool: "run_command", label: "run_command", status: "running", startedAt: 2 },+ ] } });+ await stopTurn(store);+ expect(stopCall).toHaveBeenCalledOnce();+ expect(store.getState().stopping).toBe(true);+ expect(store.getState().live?.steps.map((s) => s.status)).toEqual(["done", "stopped"]);+ });++ it("ends the turn as stopped and keeps the partial answer", async () => {+ store.setState({ agent: "streaming", streaming: "Half an ans", live: { reasoning: "thinking…", startedAt: 1, steps: [] } });+ await stopTurn(store);+ vi.advanceTimersByTime(8000);+ const s = store.getState();+ expect(s.stopping).toBe(false);+ expect(s.agent).toBe("idle");+ expect(s.streaming).toBe("");+ const last = s.messages.at(-1);+ expect(last?.stopped).toBe(true);+ expect(last?.content).toBe("Half an ans");+ expect(last?.trace?.stopped).toBe(true);+ });++ it("adds nothing when the answer had already finished", async () => {+ store.setState({ agent: "idle" });+ await stopTurn(store);+ vi.advanceTimersByTime(8000);+ expect(store.getState().messages).toHaveLength(0);+ });++ it("lets you press stop again if the runtime refused", async () => {+ stopCall.mockRejectedValueOnce(new Error("offline"));+ store.setState({ agent: "working" });+ await expect(stopTurn(store)).rejects.toThrow("offline");+ expect(store.getState().stopping).toBe(false);+ });+});diff --git a/apps/desktop/src/components/ThoughtProcess.tsx b/apps/desktop/src/components/ThoughtProcess.tsxindex 5d25b90d..451e1480 100644--- a/apps/desktop/src/components/ThoughtProcess.tsx+++ b/apps/desktop/src/components/ThoughtProcess.tsx@@ -1,4 +1,4 @@-import { Brain, Check, ChevronRight, CircleAlert } from "lucide-react";+import { Brain, Check, ChevronRight, CircleAlert, Square } from "lucide-react";import { useEffect, useRef, useState } from "react";import type { ThoughtTrace } from "~/api/types";import { Spinner } from "~/components/ui/bits";@@ -9,7 +9,7 @@ import { cx } from "~/lib/cx";* short scrolling window and each step appearing as it runs. Done: folded* into one line ("Thought for 12s · 4 steps") above the answer, open on click.*/-export function ThoughtProcess({ trace, live = false }: { trace: ThoughtTrace; live?: boolean }) {+export function ThoughtProcess({ trace, live = false, stopping = false }: { trace: ThoughtTrace; live?: boolean; stopping?: boolean }) {const [open, setOpen] = useState(live);const box = useRef<HTMLDivElement>(null);useEffect(() => { if (live) setOpen(true); }, [live]);@@ -21,16 +21,17 @@ export function ThoughtProcess({ trace, live = false }: { trace: ThoughtTrace; lconst seconds = Math.max(1, Math.round(((trace.endedAt ?? Date.now()) - trace.startedAt) / 1000));const running = trace.steps.find((s) => s.status === "running");const failed = trace.steps.filter((s) => s.status === "error").length;+ const steps = trace.steps.length ? ` · ${trace.steps.length} step${trace.steps.length === 1 ? "" : "s"}` : "";const summary = live- ? running ? `Running ${running.tool}` : trace.reasoning ? "Thinking" : "Starting"- : `Thought for ${seconds}s${trace.steps.length ? ` · ${trace.steps.length} step${trace.steps.length === 1 ? "" : "s"}` : ""}${failed ? ` · ${failed} failed` : ""}`;+ ? stopping ? "Stopping" : running ? `Running ${running.tool}` : trace.reasoning ? "Thinking" : "Starting"+ : trace.stopped ? `Stopped after ${seconds}s${steps}` : `Thought for ${seconds}s${trace.steps.length ? ` · ${trace.steps.length} step${trace.steps.length === 1 ? "" : "s"}` : ""}${failed ? ` · ${failed} failed` : ""}`;if (!live && !trace.reasoning && trace.steps.length === 0) return null;return (<div className="mb-3"><button onClick={() => setOpen((o) => !o)} className="flex items-center gap-2 rounded-md py-1 text-sm text-ink3 hover:text-ink" aria-expanded={open}>- {live ? <Spinner size={13} className="text-cyan" /> : <Brain size={14} aria-hidden="true" />}+ {live ? <Spinner size={13} className="text-cyan" /> : trace.stopped ? <Square size={11} className="fill-current" aria-hidden="true" /> : <Brain size={14} aria-hidden="true" />}<span className={cx(live && "text-cyan")}>{summary}{live && "…"}</span><ChevronRight size={14} className={cx("transition-transform", open && "rotate-90")} aria-hidden="true" /></button>@@ -46,10 +47,11 @@ export function ThoughtProcess({ trace, live = false }: { trace: ThoughtTrace; l{trace.steps.map((s) => (<li key={`${s.id}-${s.startedAt}`} className="flex items-start gap-2 text-[13px]"><span className="mt-[3px] flex h-4 w-4 shrink-0 items-center justify-center">- {s.status === "running" ? <Spinner size={11} className="text-accent" /> : s.status === "error" ? <CircleAlert size={13} className="text-red" /> : <Check size={13} className="text-accent" strokeWidth={2.5} />}+ {s.status === "running" ? <Spinner size={11} className="text-accent" /> : s.status === "stopped" ? <Square size={10} className="fill-current text-ink4" aria-label="stopped" /> : s.status === "error" ? <CircleAlert size={13} className="text-red" /> : <Check size={13} className="text-accent" strokeWidth={2.5} />}</span><span className="min-w-0 flex-1"><span className="break-all font-mono text-ink2">{s.label}</span>+ {s.status === "stopped" && <span className="mt-0.5 block text-xs text-ink4">Stopped before it finished</span>}{s.summary && s.status !== "running" && <span className="mt-0.5 line-clamp-2 block text-xs text-ink4">{s.summary}</span>}</span>{s.endedAt && <span className="shrink-0 font-mono text-2xs text-ink4">{((s.endedAt - s.startedAt) / 1000).toFixed(1)}s</span>}diff --git a/apps/desktop/src/views/chat/Composer.tsx b/apps/desktop/src/views/chat/Composer.tsxindex 47284cb0..9cc238bc 100644--- a/apps/desktop/src/views/chat/Composer.tsx+++ b/apps/desktop/src/views/chat/Composer.tsx@@ -1,11 +1,11 @@-import { ArrowUp, ChevronDown, Paperclip, Shield, ShieldCheck, X } from "lucide-react";+import { ArrowUp, ChevronDown, Paperclip, Shield, ShieldCheck, Square, X } from "lucide-react";import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";import { cx } from "~/lib/cx";import * as api from "~/api/mercury";import type { ChatSettings, ModelsResponse } from "~/api/types";import { useRuntimeState } from "~/app/store";-import { sendMessage, type CodeTurn } from "~/app/events";-import { useConversation, type Surface } from "~/app/conversation";+import { sendMessage, stopTurn, type CodeTurn } from "~/app/events";+import { useConversation, useConversationStore, type Surface } from "~/app/conversation";import { Button } from "~/components/ui/Button";import { Menu, MenuItem, MenuLabel, MenuSeparator } from "~/components/ui/Menu";import { Tooltip } from "~/components/ui/Tooltip";@@ -57,6 +57,8 @@ export function Composer({ surface, placeholder, code, extra, blockedReason, monconst ref = useRef<HTMLTextAreaElement>(null);const picker = useRef<HTMLInputElement>(null);const agent = useConversation((s) => s.agent);+ const stopping = useConversation((s) => s.stopping);+ const convStore = useConversationStore();const connected = useRuntimeState((s) => s.connected);useEffect(() => {@@ -140,6 +142,12 @@ export function Composer({ surface, placeholder, code, extra, blockedReason, mon}const busy = agent === "thinking" || agent === "streaming" || agent === "working";+ // While Mercury works the send button is a stop button; typing a follow-up turns it back into send.+ const showStop = busy && text.trim().length === 0 && files.length === 0;+ function stop() {+ setError(null);+ void stopTurn(convStore).catch((err) => setError(err instanceof Error ? `Couldn't stop: ${err.message}` : "Couldn't stop"));+ }const canSend = connected && !blockedReason && (text.trim().length > 0 || files.length > 0);return (@@ -182,6 +190,7 @@ export function Composer({ surface, placeholder, code, extra, blockedReason, mononKeyDown={(e) => {if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) { e.preventDefault(); void submit(); }if (e.key === "Escape" && text) { e.preventDefault(); setText(""); }+ 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 ?? placeholder}@@ -210,15 +219,23 @@ export function Composer({ surface, placeholder, code, extra, blockedReason, mon{surface === "chat" && <ModePicker />}<div className="flex-1" />{busy ? (- <span className="mr-2 text-xs text-ink4">{agent === "streaming" ? "Answering" : agent === "working" ? "Working" : "Thinking"}…</span>+ <span className="mr-2 text-xs text-ink4">{stopping ? "Stopping" : agent === "streaming" ? "Answering" : agent === "working" ? "Working" : "Thinking"}…</span>) : text.length > 0 ? (<span className="mr-2 hidden text-2xs text-ink4 sm:inline">⇧↵ new line</span>) : null}- <Tooltip label="Send" shortcut="↵" side="top">- <Button variant="primary" size="md" icon onClick={() => void submit()} disabled={!canSend} loading={sending} aria-label="Send" className="!rounded-full">- <ArrowUp size={17} strokeWidth={2.4} />- </Button>- </Tooltip>+ {showStop ? (+ <Tooltip label={stopping ? "Stopping…" : "Stop"} shortcut="esc" side="top">+ <Button variant="primary" size="md" icon onClick={stop} disabled={stopping || !connected} aria-label="Stop" className="!rounded-full">+ <Square size={13} className="fill-current" strokeWidth={0} />+ </Button>+ </Tooltip>+ ) : (+ <Tooltip label="Send" shortcut="↵" side="top">+ <Button variant="primary" size="md" icon onClick={() => void submit()} disabled={!canSend} loading={sending} aria-label="Send" className="!rounded-full">+ <ArrowUp size={17} strokeWidth={2.4} />+ </Button>+ </Tooltip>+ )}</div></div></div>diff --git a/apps/desktop/src/views/chat/Conversation.tsx b/apps/desktop/src/views/chat/Conversation.tsxindex 45ecd58d..2061743b 100644--- a/apps/desktop/src/views/chat/Conversation.tsx+++ b/apps/desktop/src/views/chat/Conversation.tsx@@ -26,6 +26,7 @@ export function Conversation({ header, empty, composer }: { header: ReactNode; econst step = useConversation((s) => s.step);const prompts = useConversation((s) => s.prompts);const live = useConversation((s) => s.live);+ const stopping = useConversation((s) => s.stopping);const scroller = useRef<HTMLDivElement>(null);const stickToBottom = useRef(true);const [visible, setVisible] = useState(PAGE);@@ -84,10 +85,10 @@ export function Conversation({ header, empty, composer }: { header: ReactNode; e)}{shown.map((m) => <Message key={m.id} message={m} />)}{(streaming || (live && (agent === "thinking" || agent === "working" || agent === "streaming" || agent === "needs-you"))) && (- <StreamingMessage text={streaming} live={live} />+ <StreamingMessage text={streaming} live={live} stopping={stopping} />)}{!streaming && !live && (agent === "thinking" || agent === "working") && (- <ThinkingDots label={agent === "working" && step?.tool ? `Running ${step.tool}` : "Thinking"} className="pl-10" />+ <ThinkingDots label={stopping ? "Stopping" : agent === "working" && step?.tool ? `Running ${step.tool}` : "Thinking"} className="pl-10" />)}{prompts.map((p) => (<div key={p.id} className="pl-10">diff --git a/apps/desktop/src/views/chat/Message.tsx b/apps/desktop/src/views/chat/Message.tsxindex db7642d8..04d0eaef 100644--- a/apps/desktop/src/views/chat/Message.tsx+++ b/apps/desktop/src/views/chat/Message.tsx@@ -1,4 +1,4 @@-import { Check, ChevronRight, Copy, Wrench } from "lucide-react";+import { Check, ChevronRight, Copy, Square, Wrench } from "lucide-react";import { memo, useState } from "react";import type { ChatMessage, ThoughtTrace } from "~/api/types";import { Mark } from "~/components/Logo";@@ -8,6 +8,7 @@ import { ActionResult } from "~/components/indicators/Activity";import { Attachments } from "~/components/Attachments";import { ThoughtProcess } from "~/components/ThoughtProcess";import { cx } from "~/lib/cx";+import { isStopNote } from "~/app/events";import { UserAvatar, useDisplayName } from "~/components/UserAvatar";import { usePulse } from "~/app/pulse";@@ -46,6 +47,9 @@ export const Message = memo(function Message({ message }: { message: ChatMessage</div>);}+ // Stopped turns: from this session (message.stopped) or from history (the runtime's note).+ const stopped = message.stopped || isStopNote(message.content);+ const body = stopped && isStopNote(message.content) ? "" : message.content;return (<div className="group flex gap-4"><span className="mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center" aria-hidden="true"><Mark size={22} /></span>@@ -57,13 +61,24 @@ export const Message = memo(function Message({ message }: { message: ChatMessage{message.steps.map((s, i) => <ActionResult key={i} tool={s.tool} status={s.status} detail={s.result} />)}</div>)}- <Markdown text={message.content} />- <MessageMeta timestamp={message.timestamp} copy={message.content} />+ {body && <Markdown text={body} />}+ {stopped && <StoppedMarker partial={!!body} />}+ <MessageMeta timestamp={message.timestamp} copy={body || undefined} /></div></div>);});+/** The honest end of a stopped turn: nothing after this was done. */+function StoppedMarker({ partial }: { partial: boolean }) {+ return (+ <div className={cx("flex items-center gap-2 text-sm text-ink3", partial && "mt-3")}>+ <span className="flex h-5 w-5 items-center justify-center rounded-full bg-ink/[0.07]"><Square size={9} className="fill-current" aria-hidden="true" /></span>+ {partial ? "Stopped by you. The answer above is incomplete." : "Stopped by you before an answer was written."}+ </div>+ );+}+/** Who is speaking: a small name line beside the avatar, so turns never blur together. */function Speaker({ who }: { who: "you" | "mercury" }) {const you = useDisplayName();@@ -155,13 +170,14 @@ function ToolActivity({ content }: { content: string }) {}/** The answer being written, with its thought process above it (open while it runs). */-export function StreamingMessage({ text, live }: { text: string; live: ThoughtTrace | null }) {+export function StreamingMessage({ text, live, stopping = false }: { text: string; live: ThoughtTrace | null; stopping?: boolean }) {return (<div className="flex gap-4"><span className="mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center" aria-hidden="true"><Mark size={22} /></span><div className="min-w-0 flex-1"><Speaker who="mercury" />- {live && <ThoughtProcess trace={live} live={!text} />}+ {live && <ThoughtProcess trace={live} live={!text} stopping={stopping} />}+ {stopping && text && <div className="mb-2 text-sm text-ink3">Stopping…</div>}{text && <><Markdown text={text} streaming /><StreamCaret /></>}</div></div>diff --git a/src/index.ts b/src/index.tsindex 8f326e55..9efce57b 100644--- a/src/index.ts+++ b/src/index.ts@@ -94,7 +94,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 } 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 } from './web/server.js';import { isWebAuthInitialized, setWebPassword, writeAttachToken, initWebAuth } from './web/auth.js';import { startLoopLagMonitor } from './utils/loop-lag.js';import { McpManager, probeMcpServer, validateMcpConfig, type McpServerStatus } from './capabilities/mcp/index.js';@@ -3527,6 +3527,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {setWebProgrammingMode(agent.programmingMode);setWebBgTasks(agent.backgroundTasks);setWebModelSwitch((provider, model) => agent.switchProvider(provider, model));+ setWebStop(() => agent.stopAllWork('stopped'));setWebCurrentProvider(() => agent.getCurrentProvider());// Live bottom bar for attached terminals and the dashboard: one snapshot,// pushed on every model switch and checked every 2 s for anything else.diff --git a/src/web/api-contract.ts b/src/web/api-contract.tsindex 7f3f4e25..cb9231b4 100644--- a/src/web/api-contract.ts+++ b/src/web/api-contract.ts@@ -37,6 +37,7 @@ export const API_FEATURES: readonly string[] = Object.freeze(['voice', // /api/voice, /api/voice/events, /api/voice/control (Optimus)'usage.history', // GET /api/usage/history?days= — tokens per local day'brain.people', // PATCH/merge persons, person checks, GET /api/brain/graph/v2+ 'chat.stop', // POST /api/chat/stop — interrupt the running turn (same as /stop)]);export interface ApiContractInfo {diff --git a/src/web/api/chat-stop-route.test.ts b/src/web/api/chat-stop-route.test.tsnew file mode 100644index 00000000..8477b70c--- /dev/null+++ b/src/web/api/chat-stop-route.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it, vi } from 'vitest';++await vi.hoisted(async () => {+ const fs = await import('node:fs');+ const os = await import('node:os');+ const path = await import('node:path');+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mercury-stop-route-'));+ fs.writeFileSync(path.join(dir, 'mercury.yaml'), 'identity:\n owner: Test\n');+ process.env.MERCURY_HOME = dir;+});++import chat, { setStopCallback } from './chat.js';++const stop = () => chat.request('http://127.0.0.1/api/chat/stop', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' });++/** The desktop stop button: the same stop the terminal's Esc and /stop use. */+describe('POST /api/chat/stop', () => {+ it('runs the stop routine and returns its note', async () => {+ const fn = vi.fn(async () => 'Foreground task stopped, locks released, task board cleared.');+ setStopCallback(fn);+ const res = await stop();+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ ok: true, note: 'Foreground task stopped, locks released, task board cleared.' });+ expect(fn).toHaveBeenCalledOnce();+ });++ it('reports a failure instead of pretending it stopped', async () => {+ setStopCallback(async () => { throw new Error('supervisor busy'); });+ const res = await stop();+ expect(res.status).toBe(500);+ expect(await res.json()).toEqual({ error: 'supervisor busy' });+ });+});diff --git a/src/web/api/chat.ts b/src/web/api/chat.tsindex e625a978..633f569c 100644--- a/src/web/api/chat.ts+++ b/src/web/api/chat.ts@@ -64,6 +64,12 @@ export function setCurrentProviderCallback(fn: () => { name: string; model: stricurrentProviderFn = fn;}+let stopFn: (() => Promise<string>) | null = null;+/** 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;+}+let statusSnapshotFn: (() => Record<string, unknown>) | null = null;/** The runtime's live status (model, mode, permissions, tokens…) for the connected frame. */@@ -268,6 +274,17 @@ chat.put('/api/chat/settings', async (c) => {// ─── Permission Resolution ───────────────────────────────────+/** Stop button: interrupt whatever Mercury is doing right now. */+chat.post('/api/chat/stop', async (c) => {+ if (!stopFn) return c.json({ error: 'Stop is not available on this runtime' }, 503);+ try {+ const note = await stopFn();+ return c.json({ ok: true, note });+ } catch (err) {+ return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);+ }+});+chat.post('/api/chat/permission/:id', async (c) => {if (!webChannel) {return c.json({ error: 'Web channel not initialized' }, 503);diff --git a/src/web/server.ts b/src/web/server.tsindex fbcb0969..8b8fe351 100644--- a/src/web/server.ts+++ b/src/web/server.ts@@ -15,7 +15,7 @@ import providerRoutes from './api/providers.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 } from './api/chat.js';+import chatRoutes, { setWebChannel, setProgrammingMode, setModelSwitchCallback, setCurrentProviderCallback, setStatusSnapshotCallback, setSessionRepository, setSessionSyncEnabledCallback, setStopCallback } 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';@@ -219,6 +219,7 @@ if (spaAvailable) {}export { setShutdownHandler, setMcpManager };+export { setStopCallback };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;