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: undo your last message

Salman Qureshi98ffd01daa09
diff --git a/apps/desktop/src/api/mercury.ts b/apps/desktop/src/api/mercury.ts
index 676f3059..f15409d4 100644
--- a/apps/desktop/src/api/mercury.ts
+++ b/apps/desktop/src/api/mercury.ts
@@ -53,6 +53,8 @@ export const chat = {
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", {}),
+ /** Take back your last message and the reply (stop the turn first); returns your text. */
+ undo: (threadId: string, content: string) => http.post<{ ok: boolean; content: string; removed: number }>(`/api/chat/threads/${encodeURIComponent(threadId)}/undo`, { content }),
answer: (promptId: string, action: string, targetId?: string) => http.post<{ resolved: boolean }>(`/api/chat/permission/${encodeURIComponent(promptId)}`, { action, targetId }),
settings: () => http.get<ChatSettings>("/api/chat/settings"),
updateSettings: (patch: Partial<ChatSettings>) => http.put<ChatSettings>("/api/chat/settings", patch),
diff --git a/apps/desktop/src/app/conversation.ts b/apps/desktop/src/app/conversation.ts
index a72f9ddc..90c398f2 100644
--- a/apps/desktop/src/app/conversation.ts
+++ b/apps/desktop/src/app/conversation.ts
@@ -26,6 +26,9 @@ export interface ConversationState {
/** The stop button was pressed and the runtime hasn't confirmed yet. */
stopping: boolean;
setStopping(stopping: boolean): void;
+ /** Text to put in the box (an undone message); the composer takes it once. */
+ draft: string | null;
+ setDraft(draft: string | null): void;
/** 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;
@@ -58,6 +61,8 @@ function makeConversation(surface: Surface): ConversationStore {
live: null,
stopping: false,
setStopping: (stopping) => set({ stopping }),
+ draft: null,
+ setDraft: (draft) => set({ draft }),
plan: null,
setPlan: (plan) => set({ plan }),
setLive: (update) => set((s) => ({ live: update(s.live ?? { reasoning: "", steps: [], startedAt: Date.now() }) })),
diff --git a/apps/desktop/src/app/events.ts b/apps/desktop/src/app/events.ts
index 441561c9..c6c755fa 100644
--- a/apps/desktop/src/app/events.ts
+++ b/apps/desktop/src/app/events.ts
@@ -8,7 +8,7 @@
import { useEffect } from "react";
import { openStream } from "~/api/stream";
import * as api from "~/api/mercury";
-import { http } from "~/api/client";
+import { ApiError, http } from "~/api/client";
import type { BotActivityEvent, ChatMessage, CodeMode, PendingPrompt } from "~/api/types";
import { useBots, useChat, useRuntimeState, type AgentState } from "./store";
import { conversations, useCodeSessions, type ConversationStore, type Surface } from "./conversation";
@@ -313,6 +313,45 @@ export async function stopTurn(store: ConversationStore): Promise<void> {
setTimeout(() => { if (store.getState().stopping) finishStopped(store); }, 8000);
}
+/** Is Mercury working on this conversation right now (or still stopping)? */
+export function turnRunning(store: ConversationStore): boolean {
+ const s = store.getState();
+ return s.stopping || !!s.streaming || (s.agent !== "idle" && s.agent !== "offline");
+}
+
+const pause = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+/**
+ * Undo your last message: stop the turn if it's running (and wait for it
+ * to end), take the message and Mercury's reply out of the conversation
+ * (the runtime forgets them too), and put your text back in the box.
+ */
+export async function undoLast(store: ConversationStore, message: ChatMessage): Promise<void> {
+ const threadId = store.getState().activeId;
+ if (!threadId) throw new Error("No conversation is open.");
+ if (turnRunning(store)) {
+ await stopTurn(store);
+ for (let waited = 0; turnRunning(store) && waited < 12_000; waited += 150) await pause(150);
+ }
+ // The runtime may still be writing the stopped turn: give it a moment.
+ let result: Awaited<ReturnType<typeof api.chat.undo>> | null = null;
+ for (let attempt = 0; ; attempt++) {
+ try {
+ result = await api.chat.undo(threadId, message.content);
+ break;
+ } catch (err) {
+ const busy = err instanceof ApiError && err.status === 409 && err.data.busy === true;
+ if (!busy || attempt >= 25) throw err;
+ await pause(400);
+ }
+ }
+ const s = store.getState();
+ if (s.activeId !== threadId) return;
+ const at = s.messages.findIndex((m) => m.id === message.id);
+ s.setMessages(at >= 0 ? s.messages.slice(0, at) : s.messages);
+ s.setDraft(result.content);
+}
+
/** End the current turn as stopped: keep the partial answer, mark the trace, say so. */
function finishStopped(store: ConversationStore): void {
const s = store.getState();
diff --git a/apps/desktop/src/app/undo.test.ts b/apps/desktop/src/app/undo.test.ts
new file mode 100644
index 00000000..3af03eb7
--- /dev/null
+++ b/apps/desktop/src/app/undo.test.ts
@@ -0,0 +1,54 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { ApiError } from "~/api/client";
+
+const stopCall = vi.fn(async () => ({ ok: true }));
+const undoCall = vi.fn();
+vi.mock("~/api/mercury", () => ({ chat: { stop: () => stopCall(), undo: (id: string, content: string) => undoCall(id, content) } }));
+
+const { conversations } = await import("./conversation");
+const { undoLast, turnRunning } = await import("./events");
+
+const store = conversations.chat;
+const msg = (id: string, role: "user" | "assistant", content: string) => ({ id, role, content, timestamp: "2026-10-28T10:00:00Z" });
+
+describe("undo your last message", () => {
+ beforeEach(() => {
+ stopCall.mockClear();
+ undoCall.mockReset();
+ store.setState({
+ activeId: "t1", streaming: "", live: null, agent: "idle", stopping: false, prompts: [], step: null, draft: null,
+ messages: [msg("a", "user", "Hi"), msg("b", "assistant", "Hello"), msg("c", "user", "Weather tomorow?"), msg("d", "assistant", "Rain.")],
+ });
+ });
+
+ it("when nothing is running: takes it back and puts the text in the box", async () => {
+ undoCall.mockResolvedValue({ ok: true, content: "Weather tomorow?", removed: 2 });
+ expect(turnRunning(store)).toBe(false);
+ await undoLast(store, msg("c", "user", "Weather tomorow?"));
+ expect(stopCall).not.toHaveBeenCalled();
+ expect(undoCall).toHaveBeenCalledWith("t1", "Weather tomorow?");
+ expect(store.getState().messages.map((m) => m.id)).toEqual(["a", "b"]);
+ expect(store.getState().draft).toBe("Weather tomorow?");
+ });
+
+ it("while Mercury works: stops first, waits out the runtime, then undoes", async () => {
+ store.setState({ agent: "working", messages: store.getState().messages.slice(0, 3) });
+ // The runtime ends the turn shortly after the stop.
+ stopCall.mockImplementation(async () => { setTimeout(() => store.setState({ agent: "idle", stopping: false }), 50); return { ok: true }; });
+ undoCall
+ .mockRejectedValueOnce(new ApiError("still working", 409, null, { busy: true }))
+ .mockResolvedValueOnce({ ok: true, content: "Weather tomorow?", removed: 2 });
+ await undoLast(store, msg("c", "user", "Weather tomorow?"));
+ expect(stopCall).toHaveBeenCalledOnce();
+ expect(undoCall).toHaveBeenCalledTimes(2);
+ expect(store.getState().messages.map((m) => m.id)).toEqual(["a", "b"]);
+ expect(store.getState().draft).toBe("Weather tomorow?");
+ });
+
+ it("a refusal other than busy is reported, and nothing changes", async () => {
+ undoCall.mockRejectedValue(new ApiError("Only your last message can be undone.", 409, null, { notLast: true }));
+ await expect(undoLast(store, msg("a", "user", "Hi"))).rejects.toThrow("Only your last message");
+ expect(store.getState().messages).toHaveLength(4);
+ expect(store.getState().draft).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/views/chat/Composer.tsx b/apps/desktop/src/views/chat/Composer.tsx
index e2c4c56a..9f6270c5 100644
--- a/apps/desktop/src/views/chat/Composer.tsx
+++ b/apps/desktop/src/views/chat/Composer.tsx
@@ -83,6 +83,15 @@ export function Composer({ surface, placeholder, code, extra, blockedReason, mon
return () => window.removeEventListener("keydown", onKey, true);
}, [recording]); // eslint-disable-line react-hooks/exhaustive-deps
+ // An undone message comes back here, in place of what was typed.
+ const undone = useConversation((s) => s.draft);
+ useEffect(() => {
+ if (undone == null) return;
+ setText(undone);
+ convStore.getState().setDraft(null);
+ requestAnimationFrame(() => { const el = ref.current; if (el) { el.focus(); el.setSelectionRange(el.value.length, el.value.length); } });
+ }, [undone, convStore]);
+
useEffect(() => {
if (draft == null) return;
setText(draft);
diff --git a/apps/desktop/src/views/chat/Conversation.tsx b/apps/desktop/src/views/chat/Conversation.tsx
index 8fd7ebfd..645d26f3 100644
--- a/apps/desktop/src/views/chat/Conversation.tsx
+++ b/apps/desktop/src/views/chat/Conversation.tsx
@@ -35,6 +35,8 @@ export function Conversation({ header, empty, composer }: { header: ReactNode; e
useEffect(() => { setVisible(PAGE); stickToBottom.current = true; }, [activeId]);
const shown = messages.length > visible ? messages.slice(messages.length - visible) : messages;
+ // Only your last message can be undone.
+ const lastYours = [...messages].reverse().find((m) => m.role === "user")?.id;
const hiddenCount = messages.length - shown.length;
useLayoutEffect(() => {
const el = scroller.current;
@@ -84,7 +86,7 @@ export function Conversation({ header, empty, composer }: { header: ReactNode; e
{hiddenCount} earlier message{hiddenCount === 1 ? "" : "s"}
</button>
)}
- {shown.map((m) => <Message key={m.id} message={m} />)}
+ {shown.map((m) => <Message key={m.id} message={m} undoable={m.id === lastYours} />)}
{(streaming || (live && (agent === "thinking" || agent === "working" || agent === "streaming" || agent === "needs-you"))) && (
<StreamingMessage text={streaming} live={live} stopping={stopping} />
)}
diff --git a/apps/desktop/src/views/chat/Message.tsx b/apps/desktop/src/views/chat/Message.tsx
index ec4be956..17276e87 100644
--- a/apps/desktop/src/views/chat/Message.tsx
+++ b/apps/desktop/src/views/chat/Message.tsx
@@ -12,6 +12,7 @@ import { isStopNote } from "~/app/events";
import { UserAvatar, useDisplayName } from "~/components/UserAvatar";
import { usePulse } from "~/app/pulse";
import { ArtifactStrip } from "~/components/artifacts/ArtifactCard";
+import { UndoMessage } from "./UndoMessage";
import { ReadAloudButton, ReadAloudNotice, useReadingThis } from "~/components/readAloud/ReadAloud";
/**
@@ -22,7 +23,7 @@ import { ReadAloudButton, ReadAloudNotice, useReadingThis } from "~/components/r
* - tool-call a collapsed "used N tools" row; open it for each call
* - system a muted note
*/
-export const Message = memo(function Message({ message }: { message: ChatMessage }) {
+export const Message = memo(function Message({ message, undoable = false }: { message: ChatMessage; undoable?: boolean }) {
const you = useDisplayName();
if (message.role === "user") {
const files = message.attachments ?? [];
@@ -37,7 +38,7 @@ export const Message = memo(function Message({ message }: { message: ChatMessage
{text}
</p>
)}
- <MessageMeta timestamp={message.timestamp} copy={text || undefined} align="end" />
+ <MessageMeta timestamp={message.timestamp} copy={text || undefined} align="end" undo={undoable ? message : undefined} />
</div>
<span className="mt-1 flex h-7 w-7 shrink-0 items-center justify-center" title={you} aria-hidden="true"><UserAvatar size={26} /></span>
</div>
@@ -99,7 +100,7 @@ function Speaker({ who }: { who: "you" | "mercury" }) {
}
/** Time and copy, shown on hover so the conversation stays quiet. */
-function MessageMeta({ timestamp, copy, listen, align = "start" }: { timestamp: string; copy?: string; listen?: { id: string; text: string }; align?: "start" | "end" }) {
+function MessageMeta({ timestamp, copy, listen, undo, align = "start" }: { timestamp: string; copy?: string; listen?: { id: string; text: string }; undo?: ChatMessage; align?: "start" | "end" }) {
const [copied, setCopied] = useState(false);
const reading = useReadingThis(listen?.id ?? "");
const time = formatTime(timestamp);
@@ -116,6 +117,7 @@ function MessageMeta({ timestamp, copy, listen, align = "start" }: { timestamp:
</button>
)}
{listen && <ReadAloudButton id={listen.id} text={listen.text} />}
+ {undo && <UndoMessage message={undo} />}
{time && <span className="px-1.5 text-xs text-ink4">{time}</span>}
</div>
);
diff --git a/apps/desktop/src/views/chat/UndoMessage.tsx b/apps/desktop/src/views/chat/UndoMessage.tsx
new file mode 100644
index 00000000..4d57f5b3
--- /dev/null
+++ b/apps/desktop/src/views/chat/UndoMessage.tsx
@@ -0,0 +1,59 @@
+import { Loader2, Undo2 } from "lucide-react";
+import { useState } from "react";
+import type { ChatMessage } from "~/api/types";
+import { useConversationStore } from "~/app/conversation";
+import { turnRunning, undoLast } from "~/app/events";
+import { Button } from "~/components/ui/Button";
+import { Dialog } from "~/components/ui/Dialog";
+
+/**
+ * Undo on your last message: it leaves the conversation (with Mercury's
+ * reply) and comes back to the box to change. While Mercury is still
+ * working on it, ask first: undoing stops that work.
+ */
+export function UndoMessage({ message }: { message: ChatMessage }) {
+ const store = useConversationStore();
+ const [asking, setAsking] = useState(false);
+ const [working, setWorking] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ async function run() {
+ setAsking(false);
+ setError(null);
+ setWorking(true);
+ try {
+ await undoLast(store, message);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : "Couldn't undo that.");
+ } finally {
+ setWorking(false);
+ }
+ }
+
+ return (
+ <>
+ <button
+ onClick={() => (turnRunning(store) ? setAsking(true) : void run())}
+ disabled={working}
+ className="flex h-6 items-center gap-1 rounded-md px-1.5 text-xs text-ink4 hover:bg-ink/[0.06] hover:text-ink disabled:opacity-60"
+ aria-label="Undo this message"
+ title="Take this message back to edit it"
+ >
+ {working ? <Loader2 size={13} className="animate-spin" /> : <Undo2 size={13} />}
+ {working ? "Undoing…" : "Undo"}
+ </button>
+ {error && <span className="px-1.5 text-xs text-red" role="alert">{error}</span>}
+ <Dialog
+ open={asking}
+ onOpenChange={setAsking}
+ title="Stop and undo?"
+ description="Mercury is still working on this message. Undo stops that work, removes your message and the reply so far, and puts your message back in the box to edit."
+ >
+ <div className="flex justify-end gap-2">
+ <Button variant="ghost" onClick={() => setAsking(false)}>Keep working</Button>
+ <Button variant="primary" onClick={() => void run()}>Stop and undo</Button>
+ </div>
+ </Dialog>
+ </>
+ );
+}
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 4283c407..dd425003 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -1075,6 +1075,13 @@ export class Agent {
if (workKey) this.queuedWorkKeys.add(workKey);
}
+ /** Is a turn for this session running, or waiting in the queue? */
+ isBusyWith(sessionId: string): boolean {
+ const of = (m: ChannelMessage | null | undefined) => m?.sessionId ?? (typeof m?.metadata?.sessionId === 'string' ? m.metadata.sessionId : undefined);
+ if (this.processing && of(this.currentMessage) === sessionId) return true;
+ return this.messageQueue.some((i) => of(i.message) === sessionId);
+ }
+
/**
* Where work for one channel stands: running now, waiting in the queue,
* or neither; and what Mercury is busy with when it's something else.
diff --git a/src/index.ts b/src/index.ts
index 4054bd97..1979e535 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -95,7 +95,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 } 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 } 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';
@@ -3508,6 +3508,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
setSkillBuilder({ provider: () => providers.getDefault(), tools: () => Object.keys(capabilities.getTools()).sort() });
setCloudReload(() => agent.reloadProviders());
setWebStop(() => agent.stopAllWork('stopped'));
+ setWebSessionBusy((sessionId) => agent.isBusyWith(sessionId));
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/sessions/repository.ts b/src/sessions/repository.ts
index 0c60c3e9..242d2b24 100644
--- a/src/sessions/repository.ts
+++ b/src/sessions/repository.ts
@@ -220,6 +220,22 @@ export class SessionRepository {
return message;
}
+ /**
+ * Take back a message and everything after it (undo the last exchange):
+ * it leaves the history the agent reads, so Mercury forgets it too.
+ * Returns what was removed, oldest first.
+ */
+ removeFrom(sessionRef: string, messageId: string): SessionMessage[] {
+ const session = this.get(sessionRef);
+ const at = session.messages.findIndex((message) => message.id === messageId.toLowerCase());
+ if (at < 0) throw new Error('Message not found in this session');
+ const removed = session.messages.splice(at);
+ this.touchAndWrite(session);
+ this.writeIndex();
+ this.notifyMutation();
+ return removed;
+ }
+
updateTitle(ref: string, title: string, titleSource: Session['titleSource'] = 'user'): Session {
const normalized = title.replace(/\s+/g, ' ').trim();
if (!normalized) throw new Error('Session title is required');
diff --git a/src/web/api/chat-undo-route.test.ts b/src/web/api/chat-undo-route.test.ts
new file mode 100644
index 00000000..fc3e92e8
--- /dev/null
+++ b/src/web/api/chat-undo-route.test.ts
@@ -0,0 +1,70 @@
+import { mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, 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-undo-route-'));
+ fs.writeFileSync(path.join(dir, 'mercury.yaml'), 'identity:\n owner: Test\n');
+ process.env.MERCURY_HOME = dir;
+});
+
+import { SessionRepository } from '../../sessions/repository.js';
+import chat, { setSessionBusyLookup, setSessionRepository } from './chat.js';
+
+function conversation() {
+ const repo = new SessionRepository({ rootDir: mkdtempSync(join(tmpdir(), 'mercury-undo-sessions-')), autoMigrate: false });
+ setSessionRepository(repo);
+ const s = repo.create({ title: 'Undo test' });
+ const first = repo.appendMessage(s.id, { role: 'user', content: 'What is the weather?' });
+ repo.appendMessage(s.id, { role: 'assistant', content: 'Sunny.' });
+ const last = repo.appendMessage(s.id, { role: 'user', content: 'And tomorow?', metadata: { attachments: [{ name: 'a.png' }] } });
+ repo.appendMessage(s.id, { role: 'assistant', kind: 'tool-call', content: 'searched' });
+ repo.appendMessage(s.id, { role: 'assistant', content: 'Rain.' });
+ return { repo, id: s.id, first, last };
+}
+
+const undo = (id: string, messageId?: string) => chat.request(`http://127.0.0.1/api/chat/threads/${id}/undo`, {
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(messageId ? { messageId } : {}),
+});
+
+afterEach(() => setSessionBusyLookup(null));
+
+/** Undo: take back your last message and the reply, so Mercury forgets them too. */
+describe('POST /api/chat/threads/:id/undo', () => {
+ it('removes your last message and everything after it, and hands its text back', async () => {
+ const { repo, id, last } = conversation();
+ const res = await undo(id, last.id);
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ ok: true, content: 'And tomorow?', attachments: [{ name: 'a.png' }], removed: 3 });
+ expect(repo.get(id).messages.map((m) => m.content)).toEqual(['What is the weather?', 'Sunny.']);
+ });
+
+ it('only the last message can be undone', async () => {
+ const { repo, id, first } = conversation();
+ const res = await undo(id, first.id);
+ expect(res.status).toBe(409);
+ expect(await res.json()).toMatchObject({ notLast: true });
+ expect(repo.get(id).messages).toHaveLength(5);
+ });
+
+ it('a message shown before it was saved is matched by its text', async () => {
+ const { repo, id } = conversation();
+ const by = (content: string) => chat.request(`http://127.0.0.1/api/chat/threads/${id}/undo`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ content }) });
+ expect((await by('What is the weather?')).status).toBe(409);
+ expect((await by('And tomorow?')).status).toBe(200);
+ expect(repo.get(id).messages).toHaveLength(2);
+ });
+
+ it('waits for a running turn: stop it first', async () => {
+ const { repo, id, last } = conversation();
+ setSessionBusyLookup((sessionId) => sessionId === id);
+ const res = await undo(id, last.id);
+ expect(res.status).toBe(409);
+ expect(await res.json()).toMatchObject({ busy: true });
+ expect(repo.get(id).messages).toHaveLength(5);
+ });
+});
diff --git a/src/web/api/chat.ts b/src/web/api/chat.ts
index fcd6a13b..68d7edde 100644
--- a/src/web/api/chat.ts
+++ b/src/web/api/chat.ts
@@ -70,6 +70,11 @@ export function setCurrentProviderCallback(fn: () => { name: string; model: stri
}
let stopFn: (() => Promise<string>) | null = null;
+let busyFn: ((sessionId: string) => boolean) | null = null;
+/** Whether a session has a turn running or queued (undo waits for it). */
+export function setSessionBusyLookup(fn: ((sessionId: string) => boolean) | null): void {
+ busyFn = fn;
+}
/** 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;
@@ -730,6 +735,30 @@ chat.post('/api/chat/threads/:id/delete', async (c) => {
}
});
+/**
+ * Undo: take back your last message and Mercury's reply to it, so you can
+ * change it. Only the last message you sent, and only once its turn has
+ * ended (stop it first). Returns what you wrote, to put back in the box.
+ */
+chat.post('/api/chat/threads/:id/undo', async (c) => {
+ const id = c.req.param('id');
+ if (!sessions) return c.json({ error: 'Session repository not initialized' }, 503);
+ // Which message the client means: its id, or (for a message the client
+ // showed before the runtime saved it) its text. Either must be the last one.
+ const body: { messageId?: string; content?: string } = await c.req.json<{ messageId?: string; content?: string }>().catch(() => ({}));
+ let session;
+ try { session = sessions.get(id); } catch { return c.json({ error: 'Thread not found' }, 404); }
+ if (busyFn?.(session.id)) return c.json({ error: 'Mercury is still working on this. Stop it first.', busy: true }, 409);
+ const last = [...session.messages].reverse().find((m) => m.role === 'user' && (m.kind ?? 'message') === 'message');
+ if (!last) return c.json({ error: 'There is nothing to undo.' }, 409);
+ const notLast = (body.messageId && body.messageId.toLowerCase() !== last.id)
+ || (typeof body.content === 'string' && body.content.trim() !== last.content.trim());
+ if (notLast) return c.json({ error: 'Only your last message can be undone.', notLast: true }, 409);
+ const removed = sessions.removeFrom(session.id, last.id);
+ const attachments = (last.metadata as { attachments?: unknown } | undefined)?.attachments;
+ return c.json({ ok: true, content: last.content, attachments: Array.isArray(attachments) ? attachments : [], removed: removed.length });
+});
+
chat.post('/api/chat/threads/:id/messages', async (c) => {
return c.json({ error: 'Messages are written by /api/chat/send and the agent runtime' }, 410);
});
diff --git a/src/web/server.ts b/src/web/server.ts
index e47ad9dd..281a7fd6 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -20,7 +20,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 } from './api/chat.js';
+import chatRoutes, { setWebChannel, setProgrammingMode, setModelSwitchCallback, setCurrentProviderCallback, setStatusSnapshotCallback, setSessionRepository, setSessionSyncEnabledCallback, setStopCallback, setSessionBusyLookup } 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';
@@ -229,7 +229,7 @@ if (spaAvailable) {
}
export { setShutdownHandler, setMcpManager };
-export { setStopCallback };
+export { setStopCallback, setSessionBusyLookup };
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;