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: save chats to come back to

Salman Qureshi7320bcceac74
diff --git a/apps/desktop/src/api/mercury.ts b/apps/desktop/src/api/mercury.ts
index f15409d4..7e4540e1 100644
--- a/apps/desktop/src/api/mercury.ts
+++ b/apps/desktop/src/api/mercury.ts
@@ -54,6 +54,7 @@ export const chat = {
/** 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. */
+ save: (threadId: string, saved: boolean) => http.post<{ id: string; saved: boolean; savedAt: string | null }>(`/api/chat/threads/${encodeURIComponent(threadId)}/save`, { saved }),
undo: (threadId: string, content: string) => http.post<{ ok: boolean; content: string; removed: number }>(`/api/chat/threads/${encodeURIComponent(threadId)}/undo`, { content }),
answer: (promptId: string, action: string, targetId?: string) => http.post<{ resolved: boolean }>(`/api/chat/permission/${encodeURIComponent(promptId)}`, { action, targetId }),
settings: () => http.get<ChatSettings>("/api/chat/settings"),
diff --git a/apps/desktop/src/api/types.ts b/apps/desktop/src/api/types.ts
index 6e29ed5d..f5b46704 100644
--- a/apps/desktop/src/api/types.ts
+++ b/apps/desktop/src/api/types.ts
@@ -35,6 +35,8 @@ export interface ChatThread {
updatedAt?: string;
messages: ChatMessage[];
createdAt: string;
+ /** Saved to come back to later (unset = not saved). */
+ savedAt?: string;
}
export interface ToolStep {
diff --git a/apps/desktop/src/app/events.ts b/apps/desktop/src/app/events.ts
index c6c755fa..bd9a18f0 100644
--- a/apps/desktop/src/app/events.ts
+++ b/apps/desktop/src/app/events.ts
@@ -215,6 +215,26 @@ export async function refreshThreads(): Promise<void> {
} catch { /* offline: keep what we have */ }
}
+/**
+ * Save a thread to come back to, or unsave it. Shows at once; puts it back
+ * if the runtime says no.
+ */
+export async function setThreadSaved(threadId: string, saved: boolean): Promise<void> {
+ const mark = (savedAt: string | undefined) => {
+ const { threads, setThreads } = useChat.getState();
+ setThreads(threads.map((t) => (t.id === threadId ? { ...t, savedAt } : t)));
+ };
+ const before = useChat.getState().threads.find((t) => t.id === threadId)?.savedAt;
+ mark(saved ? new Date().toISOString() : undefined);
+ try {
+ const res = await api.chat.save(threadId, saved);
+ mark(res.savedAt ?? undefined);
+ } catch (err) {
+ mark(before);
+ throw err;
+ }
+}
+
export async function refreshBots(): Promise<void> {
try {
const { bots, available } = await api.bots.list();
diff --git a/apps/desktop/src/views/chat/ChatView.tsx b/apps/desktop/src/views/chat/ChatView.tsx
index c22b09bf..a43fbde9 100644
--- a/apps/desktop/src/views/chat/ChatView.tsx
+++ b/apps/desktop/src/views/chat/ChatView.tsx
@@ -1,8 +1,8 @@
-import { PanelLeft } from "lucide-react";
-import { useEffect } from "react";
+import { Bookmark, BookmarkCheck, PanelLeft } from "lucide-react";
+import { useEffect, useState } from "react";
import { useChat, useUi } from "~/app/store";
import { conversations, ConversationContext, useCodeSessions, listOf } from "~/app/conversation";
-import { refreshThreads, openThread } from "~/app/events";
+import { refreshThreads, openThread, setThreadSaved } from "~/app/events";
import { Button } from "~/components/ui/Button";
import { Tooltip } from "~/components/ui/Tooltip";
import { Mark } from "~/components/Logo";
@@ -49,15 +49,28 @@ export function ChatView() {
return () => { setOnCallTurn(null); if (timer) clearTimeout(timer); };
}, []);
+ // Saved chats are a bookmark, not a section: the list shows them only on ⌘⇧S.
+ const [savedOnly, setSavedOnly] = useState(false);
+ const saved = !!threads.find((t) => t.id === activeId)?.savedAt;
+ const toggleSaved = () => { if (activeId) void setThreadSaved(activeId, !saved).catch(() => {}); };
+
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (view !== "chat") return;
- if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "n" && !e.shiftKey) { e.preventDefault(); void openThread("chat", null); }
- if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "b") { e.preventDefault(); toggleSidebar(); }
+ const mod = e.metaKey || e.ctrlKey;
+ if (mod && e.key.toLowerCase() === "n" && !e.shiftKey) { e.preventDefault(); void openThread("chat", null); }
+ if (mod && e.key.toLowerCase() === "b") { e.preventDefault(); toggleSidebar(); }
+ if (mod && e.key.toLowerCase() === "s" && !e.shiftKey) { e.preventDefault(); toggleSaved(); }
+ if (mod && e.key.toLowerCase() === "s" && e.shiftKey) {
+ e.preventDefault();
+ if (!useUi.getState().sidebar) toggleSidebar();
+ setSavedOnly((v) => !v);
+ }
+ if (e.key === "Escape" && savedOnly) setSavedOnly(false);
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
- }, [toggleSidebar, view]);
+ }, [toggleSidebar, view, savedOnly, activeId, saved]);
return (
<ConversationContext.Provider value={conversations.chat}>
@@ -69,7 +82,9 @@ export function ChatView() {
onOpen={(id) => { setVoiceOpen(false); void openThread("chat", id); }}
onNew={() => { setVoiceOpen(false); void openThread("chat", null); }}
newLabel="New chat"
- searchLabel="Search chats"
+ searchLabel={savedOnly ? "Search saved" : "Search chats"}
+ savedOnly={savedOnly}
+ onLeaveSaved={() => setSavedOnly(false)}
pinned={(voice.active || voice.turns.length > 0) && (
<button onClick={() => {
// A live call opens the call screen; a finished one opens its chat.
@@ -96,6 +111,13 @@ export function ChatView() {
<Button variant="ghost" size="sm" icon onClick={toggleSidebar} aria-label="Toggle sessions"><PanelLeft size={16} /></Button>
</Tooltip>
<span className="truncate text-base font-medium text-ink">{title}</span>
+ {activeId && (
+ <Tooltip label={saved ? "Saved. Click to unsave" : "Save for later"} shortcut="⌘S" side="bottom">
+ <Button variant="ghost" size="sm" icon onClick={toggleSaved} aria-label={saved ? "Unsave this chat" : "Save this chat"} aria-pressed={saved}>
+ {saved ? <BookmarkCheck size={16} className="text-accent" /> : <Bookmark size={16} />}
+ </Button>
+ </Tooltip>
+ )}
</>
}
empty={
diff --git a/apps/desktop/src/views/chat/ThreadList.tsx b/apps/desktop/src/views/chat/ThreadList.tsx
index 72a62b1a..01daf3f9 100644
--- a/apps/desktop/src/views/chat/ThreadList.tsx
+++ b/apps/desktop/src/views/chat/ThreadList.tsx
@@ -1,9 +1,9 @@
-import { Search, SquarePen, Trash2 } from "lucide-react";
+import { Bookmark, BookmarkMinus, Search, SquarePen, Trash2, X } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { cx } from "~/lib/cx";
import * as api from "~/api/mercury";
import type { ChatThread } from "~/api/types";
-import { refreshThreads } from "~/app/events";
+import { refreshThreads, setThreadSaved } from "~/app/events";
import { useNotify } from "~/app/notify/store";
const PAGE = 40;
@@ -13,7 +13,7 @@ const PAGE = 40;
* New and search on top. Renders a page at a time and adds the next page as
* the list scrolls.
*/
-export function ThreadList({ threads, activeId, onOpen, onNew, newLabel, searchLabel, renderMeta, pinned }: {
+export function ThreadList({ threads, activeId, onOpen, onNew, newLabel, searchLabel, renderMeta, pinned, savedOnly = false, onLeaveSaved }: {
threads: ChatThread[];
activeId: string | null;
onOpen: (id: string) => void;
@@ -23,6 +23,9 @@ export function ThreadList({ threads, activeId, onOpen, onNew, newLabel, searchL
renderMeta?: (t: ChatThread) => React.ReactNode;
/** Shown above the sessions (e.g. the live Optimus voice session). */
pinned?: React.ReactNode;
+ /** Only the saved threads, newest save first (⌘⇧S); the list doesn't mark them otherwise. */
+ savedOnly?: boolean;
+ onLeaveSaved?: () => void;
}) {
const unread = useNotify((s) => s.unread);
const waiting = useNotify((s) => s.waiting);
@@ -32,11 +35,13 @@ export function ThreadList({ threads, activeId, onOpen, onNew, newLabel, searchL
const filtered = useMemo(() => {
const q = query.trim().toLowerCase();
- const sorted = [...threads].sort((a, b) => stamp(b).localeCompare(stamp(a)));
+ const sorted = savedOnly
+ ? threads.filter((t) => t.savedAt).sort((a, b) => (b.savedAt ?? "").localeCompare(a.savedAt ?? ""))
+ : [...threads].sort((a, b) => stamp(b).localeCompare(stamp(a)));
return q ? sorted.filter((t) => (t.title || t.alias || "").toLowerCase().includes(q)) : sorted;
- }, [threads, query]);
+ }, [threads, query, savedOnly]);
const page = filtered.slice(0, limit);
- const groups = useMemo(() => groupByDay(page), [page]);
+ const groups = useMemo<Array<[string, ChatThread[]]>>(() => (savedOnly ? (page.length ? [["Saved", page]] : []) : groupByDay(page)), [page, savedOnly]);
useEffect(() => { setLimit(PAGE); }, [query]);
useEffect(() => {
@@ -71,16 +76,25 @@ export function ThreadList({ threads, activeId, onOpen, onNew, newLabel, searchL
</label>
</div>
<div className="min-h-0 flex-1 overflow-y-auto px-2 pb-3">
- {pinned}
- {threads.some((t) => unread[t.id] && t.id !== activeId) && (
+ {savedOnly && (
+ <div className="mb-2 flex items-center gap-2 rounded-lg bg-ink/[0.04] px-3 py-2">
+ <Bookmark size={15} className="shrink-0 text-ink3" aria-hidden="true" />
+ <span className="flex-1 text-sm font-medium text-ink">Saved</span>
+ <button onClick={onLeaveSaved} className="flex items-center gap-1 text-xs text-ink4 hover:text-ink" aria-label="Back to all chats">
+ <X size={13} /> <kbd className="font-mono">esc</kbd>
+ </button>
+ </div>
+ )}
+ {!savedOnly && pinned}
+ {!savedOnly && threads.some((t) => unread[t.id] && t.id !== activeId) && (
<div className="flex justify-end px-3 pb-1">
<button onClick={() => { const seen = useNotify.getState().seen; for (const t of threads) if (unread[t.id]) seen(t.id); }} className="text-xs text-ink4 hover:text-ink">Mark all as read</button>
</div>
)}
- {filtered.length === 0 && <p className="px-3 pt-2 text-base text-ink4">{query ? "Nothing matches." : "No sessions yet."}</p>}
+ {filtered.length === 0 && <p className="px-3 pt-2 text-base text-ink4">{query ? "Nothing matches." : savedOnly ? "Nothing saved yet. Open a chat and press ⌘S, or the bookmark at the top." : "No sessions yet."}</p>}
{groups.map(([day, list]) => (
<div key={day} className="mb-5">
- <div className="px-3 pb-1.5 text-xs font-medium uppercase tracking-wider text-ink4">{day}</div>
+ {!savedOnly && <div className="px-3 pb-1.5 text-xs font-medium uppercase tracking-wider text-ink4">{day}</div>}
{list.map((t) => (
<div key={t.id} className={cx("group flex items-center rounded-lg", activeId === t.id ? "bg-ink/[0.07]" : "hover:bg-ink/[0.05]")}>
<button onClick={() => onOpen(t.id)} className="min-w-0 flex-1 px-3 py-2.5 text-left text-base" title={t.title || "Untitled"}>
@@ -92,9 +106,15 @@ export function ThreadList({ threads, activeId, onOpen, onNew, newLabel, searchL
</span>
{renderMeta?.(t)}
</button>
- <button onClick={() => void remove(t)} className="mr-1 hidden rounded p-1 text-ink4 hover:text-red group-hover:block" aria-label="Delete thread">
- <Trash2 size={15} />
- </button>
+ {savedOnly ? (
+ <button onClick={() => void setThreadSaved(t.id, false).catch(() => {})} className="mr-1 hidden rounded p-1 text-ink4 hover:text-ink group-hover:block" aria-label="Unsave" title="Unsave">
+ <BookmarkMinus size={15} />
+ </button>
+ ) : (
+ <button onClick={() => void remove(t)} className="mr-1 hidden rounded p-1 text-ink4 hover:text-red group-hover:block" aria-label="Delete thread">
+ <Trash2 size={15} />
+ </button>
+ )}
</div>
))}
</div>
diff --git a/src/sessions/repository.ts b/src/sessions/repository.ts
index 242d2b24..a458ee85 100644
--- a/src/sessions/repository.ts
+++ b/src/sessions/repository.ts
@@ -250,6 +250,24 @@ export class SessionRepository {
return this.get(session.id);
}
+ /**
+ * Save a session to come back to, or unsave it. Saving is a bookmark, not
+ * activity: the session keeps its place in the list (updatedAt stays).
+ */
+ setSaved(ref: string, saved: boolean): Session {
+ const session = this.get(ref);
+ if (!!session.savedAt === saved) return session;
+ if (saved) session.savedAt = Date.now();
+ else delete session.savedAt;
+ session.revision++;
+ this.writeSession(session);
+ const index = this.index.sessions.findIndex((entry) => entry.id === session.id);
+ if (index >= 0) this.index.sessions[index] = this.toIndexEntry(session);
+ this.writeIndex();
+ this.notifyMutation();
+ return this.get(session.id);
+ }
+
archive(ref: string): Session {
const session = this.get(ref);
if (session.status !== 'archived') {
diff --git a/src/sessions/types.ts b/src/sessions/types.ts
index 5183b3d3..838250b6 100644
--- a/src/sessions/types.ts
+++ b/src/sessions/types.ts
@@ -38,6 +38,8 @@ export interface Session {
revision: number;
bindings: SessionBinding[];
messages: SessionMessage[];
+ /** When the owner saved it to come back to later (unset = not saved). */
+ savedAt?: number;
}
export interface CreateSessionInput {
diff --git a/src/web/api/chat-save-route.test.ts b/src/web/api/chat-save-route.test.ts
new file mode 100644
index 00000000..93eff166
--- /dev/null
+++ b/src/web/api/chat-save-route.test.ts
@@ -0,0 +1,66 @@
+import { mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+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-save-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, { setSessionRepository } from './chat.js';
+
+function threads() {
+ const repo = new SessionRepository({ rootDir: mkdtempSync(join(tmpdir(), 'mercury-save-sessions-')), autoMigrate: false });
+ setSessionRepository(repo);
+ const older = repo.create({ title: 'Older' });
+ repo.appendMessage(older.id, { role: 'user', content: 'hi', timestamp: 1_000 });
+ const newer = repo.create({ title: 'Newer' });
+ repo.appendMessage(newer.id, { role: 'user', content: 'hello' });
+ return { repo, older: older.id, newer: newer.id };
+}
+
+const save = (id: string, body: unknown) => chat.request(`http://127.0.0.1/api/chat/threads/${id}/save`, {
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
+});
+const list = async () => ((await (await chat.request('http://127.0.0.1/api/chat/threads')).json()) as { threads: Array<{ id: string; savedAt?: string }> }).threads;
+
+/** Saved threads: a bookmark that survives restarts and doesn't reorder the list. */
+describe('POST /api/chat/threads/:id/save', () => {
+ it('saves and unsaves a thread', async () => {
+ const { older } = threads();
+ const res = await save(older, { saved: true });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toMatchObject({ id: older, saved: true });
+ expect((await list()).find((t) => t.id === older)?.savedAt).toEqual(expect.any(String));
+
+ expect(await (await save(older, { saved: false })).json()).toMatchObject({ saved: false, savedAt: null });
+ expect((await list()).find((t) => t.id === older)?.savedAt).toBeUndefined();
+ });
+
+ it('keeps the thread where it was in the list', async () => {
+ const { repo, older, newer } = threads();
+ const before = repo.get(older).updatedAt;
+ await save(older, { saved: true });
+ expect(repo.get(older).updatedAt).toBe(before);
+ expect((await list()).map((t) => t.id)).toEqual([newer, older]);
+ });
+
+ it('survives a fresh read from disk', async () => {
+ const { repo, older } = threads();
+ await save(older, { saved: true });
+ const again = new SessionRepository({ rootDir: (repo as unknown as { rootDir: string }).rootDir, autoMigrate: false });
+ expect(again.get(older).savedAt).toEqual(expect.any(Number));
+ });
+
+ it('needs a yes or no, and a real thread', async () => {
+ const { older } = threads();
+ expect((await save(older, {})).status).toBe(400);
+ expect((await save('nope', { saved: true })).status).toBe(404);
+ });
+});
diff --git a/src/web/api/chat.ts b/src/web/api/chat.ts
index 68d7edde..67612414 100644
--- a/src/web/api/chat.ts
+++ b/src/web/api/chat.ts
@@ -38,6 +38,7 @@ function toThread(session: ReturnType<SessionRepository['get']>, includeMessages
title: session.title,
// A desktop voice call saved as a thread (voice-calls.ts).
voiceCall: typeof session.messages[0]?.metadata?.voiceCall === 'string',
+ ...(session.savedAt ? { savedAt: new Date(session.savedAt).toISOString() } : {}),
createdAt: new Date(session.createdAt).toISOString(),
updatedAt: new Date(session.updatedAt).toISOString(),
messages: includeMessages ? session.messages.map((message) => ({
@@ -735,6 +736,20 @@ chat.post('/api/chat/threads/:id/delete', async (c) => {
}
});
+/** Save a thread to come back to later, or unsave it: { saved: boolean }. */
+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);
+ const body: { saved?: unknown } = await c.req.json<{ saved?: unknown }>().catch(() => ({}));
+ if (typeof body.saved !== 'boolean') return c.json({ error: 'Send { saved: true } or { saved: false }.' }, 400);
+ try {
+ const session = sessions.setSaved(id, body.saved);
+ return c.json({ id: session.id, saved: !!session.savedAt, savedAt: session.savedAt ? new Date(session.savedAt).toISOString() : null });
+ } catch {
+ return c.json({ error: 'Thread not found' }, 404);
+ }
+});
+
/**
* 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