Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat: rename chats in web and desktop
Seth Wilson524b8502c5f1
diff --git a/apps/desktop/src/api/mercury.ts b/apps/desktop/src/api/mercury.tsindex eab4895a..810738f8 100644--- a/apps/desktop/src/api/mercury.ts+++ b/apps/desktop/src/api/mercury.ts@@ -72,6 +72,7 @@ export const chat = {threads: () => http.get<{ threads: ChatThread[] }>("/api/chat/threads"),thread: (id: string) => http.get<ChatThread>(`/api/chat/threads/${encodeURIComponent(id)}`),createThread: (title?: string) => http.post<ChatThread>("/api/chat/threads", { title }),+ renameThread: (id: string, title: string) => http.put<{ id: string; title: string }>(`/api/chat/threads/${encodeURIComponent(id)}/title`, { title }),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 ?? {}) }),diff --git a/apps/desktop/src/app/events.ts b/apps/desktop/src/app/events.tsindex be2060e9..8766daf9 100644--- a/apps/desktop/src/app/events.ts+++ b/apps/desktop/src/app/events.ts@@ -298,6 +298,13 @@ export async function refreshThreads(): Promise<void> {} catch { /* offline: keep what we have */ }}+/** Only update local labels after the runtime has persisted the owner's title. */+export async function renameThread(threadId: string, title: string): Promise<void> {+ const renamed = await api.chat.renameThread(threadId, title);+ const { threads, setThreads } = useChat.getState();+ setThreads(threads.map((thread) => thread.id === renamed.id ? { ...thread, title: renamed.title } : thread));+}+/*** Save a thread to come back to, or unsave it. Shows at once; puts it back* if the runtime says no.diff --git a/apps/desktop/src/app/rename.test.ts b/apps/desktop/src/app/rename.test.tsnew file mode 100644index 00000000..02eec464--- /dev/null+++ b/apps/desktop/src/app/rename.test.ts@@ -0,0 +1,22 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const renameCall = vi.fn();+vi.mock('~/api/mercury', () => ({ chat: { renameThread: (id: string, title: string) => renameCall(id, title) } }));+const { renameThread } = await import('./events');+const { useChat } = await import('./store');+const thread = (id: string, title: string) => ({ id, title, createdAt: '2026-11-06T10:00:00Z', messages: [] });++describe('rename a chat', () => {+ beforeEach(() => { renameCall.mockReset(); useChat.setState({ threads: [thread('one', 'Original'), thread('two', 'Other')] }); });+ it('updates the canonical title in place after the server confirms persistence', async () => {+ renameCall.mockResolvedValue({ id: 'one', title: 'New name π' });+ await renameThread('one', ' New name π ');+ expect(renameCall).toHaveBeenCalledWith('one', ' New name π ');+ expect(useChat.getState().threads.map(t => t.title)).toEqual(['New name π', 'Other']);+ });+ it('retains the existing title and surfaces failures for the dialog', async () => {+ renameCall.mockRejectedValue(new Error('Could not save'));+ await expect(renameThread('one', 'Changed')).rejects.toThrow('Could not save');+ expect(useChat.getState().threads[0].title).toBe('Original');+ });+});diff --git a/apps/desktop/src/views/chat/ThreadList.tsx b/apps/desktop/src/views/chat/ThreadList.tsxindex 8557f1ee..07f73310 100644--- a/apps/desktop/src/views/chat/ThreadList.tsx+++ b/apps/desktop/src/views/chat/ThreadList.tsx@@ -1,10 +1,13 @@-import { Bookmark, BookmarkMinus, Search, SquarePen, Trash2, X } from "lucide-react";+import { Bookmark, BookmarkMinus, Pencil, 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, setThreadSaved } from "~/app/events";+import { refreshThreads, renameThread, setThreadSaved } from "~/app/events";import { useNotify } from "~/app/notify/store";+import { Dialog } from "~/components/ui/Dialog";+import { Button } from "~/components/ui/Button";+import { Input } from "~/components/ui/Input";const PAGE = 40;@@ -33,6 +36,12 @@ export function ThreadList({ threads, activeId, onOpen, onNew, newLabel, searchLconst waiting = useNotify((s) => s.waiting);const [limit, setLimit] = useState(PAGE);const [query, setQuery] = useState("");+ const [renameTarget, setRenameTarget] = useState<ChatThread | null>(null);+ const [title, setTitle] = useState("");+ const [saving, setSaving] = useState(false);+ const [renameError, setRenameError] = useState<string | null>(null);+ const normalizedTitle = title.replace(/\s+/g, " ").trim();+ const titleLength = Array.from(normalizedTitle).length;const sentinel = useRef<HTMLDivElement>(null);const filtered = useMemo(() => {@@ -65,6 +74,18 @@ export function ThreadList({ threads, activeId, onOpen, onNew, newLabel, searchL} catch { /* keep */ }}+ async function saveTitle(event: React.FormEvent) {+ event.preventDefault();+ if (!renameTarget || saving || !titleLength || titleLength > 120) return;+ setSaving(true);+ setRenameError(null);+ try {+ await renameThread(renameTarget.id, normalizedTitle);+ setRenameTarget(null);+ } catch (error) { setRenameError(error instanceof Error ? error.message : "Could not save the chat name."); }+ finally { setSaving(false); }+ }+return (<aside className="flex h-full w-[300px] shrink-0 flex-col border-r border-line bg-soft"><div className="flex shrink-0 flex-col gap-2 px-3 pb-2 pt-3" data-tauri-drag-region>@@ -122,6 +143,12 @@ export function ThreadList({ threads, activeId, onOpen, onNew, newLabel, searchL</span>{renderMeta?.(t)}</button>+ <button+ onClick={() => { setRenameTarget(t); setTitle(t.title || ""); setRenameError(null); }}+ className={cx("mr-1 rounded p-1 text-ink4 hover:text-ink focus-visible:opacity-100 group-hover:opacity-100", activeId === t.id ? "opacity-100" : "opacity-0")}+ aria-label={`Rename ${t.title || "chat"}`} title="Rename chat">+ <Pencil 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} />@@ -137,6 +164,20 @@ export function ThreadList({ threads, activeId, onOpen, onNew, newLabel, searchL))}<div ref={sentinel} className="h-px" aria-hidden="true" /></div>+ <Dialog open={renameTarget !== null} onOpenChange={open => { if (!open && !saving) setRenameTarget(null); }} title="Rename chat" description="Choose a name up to 120 characters. Mercury will keep the name you choose.">+ <form onSubmit={saveTitle} className="space-y-4">+ <div className="space-y-2">+ <label htmlFor="chat-title" className="text-sm font-medium">Chat name</label>+ <Input id="chat-title" value={title} disabled={saving} autoFocus onFocus={event => event.target.select()} onChange={event => setTitle(event.target.value)} aria-describedby="chat-title-length" />+ <p id="chat-title-length" className={cx("text-xs", titleLength > 120 ? "text-red" : "text-ink3")}>{titleLength}/120 characters</p>+ {renameError && <p role="alert" className="text-sm text-red">{renameError}</p>}+ </div>+ <div className="flex justify-end gap-2">+ <Button type="button" variant="outline" disabled={saving} onClick={() => setRenameTarget(null)}>Cancel</Button>+ <Button type="submit" disabled={saving || !titleLength || titleLength > 120}>{saving ? "Savingβ¦" : "Save"}</Button>+ </div>+ </form>+ </Dialog></aside>);}diff --git a/src/core/agent.ts b/src/core/agent.tsindex 9c802c2b..bda70d1d 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -5826,6 +5826,8 @@ Is this productive iteration or a stuck loop?`,for (const session of this.sessions.list()) {const firstUser = session.messages.find((m) => m.role === 'user' && (m.kind ?? 'message') === 'message');if (!firstUser) continue;+ // Voice labels are deterministic timestamps/durations, not model titles.+ if (typeof session.messages[0]?.metadata?.voiceCall === 'string') continue;if (session.titleSource === 'fallback') {const title = fallbackSessionTitle(firstUser.content);if (title !== session.title) { this.sessions.updateTitle(session.id, title, 'fallback', { touch: false }); recut++; }diff --git a/src/core/session-title-repair.test.ts b/src/core/session-title-repair.test.tsnew file mode 100644index 00000000..9110d4f0--- /dev/null+++ b/src/core/session-title-repair.test.ts@@ -0,0 +1,43 @@+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { SessionRepository } from '../sessions/repository.js';+import { Agent } from './agent.js';++describe('automatic title repair respects user renames', () => {+ let root: string;+ let sessions: SessionRepository;+ beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'mercury-repair-titles-')); sessions = new SessionRepository({ rootDir: root, autoMigrate: false }); });+ afterEach(() => rmSync(root, { recursive: true, force: true }));++ it('leaves deterministic voice labels and owner titles unchanged at startup', async () => {+ const voice = sessions.create({ title: 'Voice call Β· 4:32 PM Β· 1h 3m', titleSource: 'generated' });+ sessions.appendMessage(voice.id, { role: 'user', content: 'Discuss the trip', metadata: { voiceCall: 'call-1' } });+ const owner = sessions.create({ title: 'This is my chosen title, kept exactly' });+ sessions.appendMessage(owner.id, { role: 'user', content: 'Hi' });+ const ordinary = sessions.create({ title: voice.title, titleSource: 'generated' });+ sessions.appendMessage(ordinary.id, { role: 'user', content: 'A normal chat about a voice call' });+ const generateTitle = vi.fn();+ const agent = Object.assign(Object.create(Agent.prototype), { sessions, generateTitle }) as Agent;+ await expect(agent.repairSessionTitles()).resolves.toEqual({ regenerated: 0, recut: 1 });+ expect(sessions.get(voice.id).title).toBe(voice.title);+ expect(sessions.get(owner.id).title).toBe(owner.title);+ expect(sessions.get(ordinary.id).title).toBe('Voice call Β· 4:32 PM');+ expect(generateTitle).not.toHaveBeenCalled();+ });++ it('does not overwrite an owner rename made while repair awaited the model', async () => {+ const session = sessions.create({ title: 'I appreciate your request, but cannot help', titleSource: 'generated' });+ sessions.appendMessage(session.id, { role: 'user', content: 'Plan a holiday' });+ sessions.appendMessage(session.id, { role: 'assistant', content: 'Let us plan it' });+ let finish!: (title: string) => void;+ const generated = new Promise<string>(resolve => { finish = resolve; });+ const agent = Object.assign(Object.create(Agent.prototype), { sessions, generateTitle: () => generated }) as Agent;+ const repair = agent.repairSessionTitles();+ sessions.updateTitle(session.id, 'My holiday plan');+ finish('Holiday Planning');+ await repair;+ expect(sessions.get(session.id)).toMatchObject({ title: 'My holiday plan', titleSource: 'user' });+ });+});diff --git a/src/plugins/voice-calls.test.ts b/src/plugins/voice-calls.test.tsindex 2f308c16..993b9823 100644--- a/src/plugins/voice-calls.test.ts+++ b/src/plugins/voice-calls.test.ts@@ -44,6 +44,15 @@ describe('voice calls as chat threads', () => {expect(sessions.list().some((s) => s.id === threadId)).toBe(false);});+ it('keeps a name chosen by the owner while the call is still active', () => {+ voiceFeed.started('renamed-call');+ const id = voiceFeed.snapshot().threadId!;+ voiceFeed.said('renamed-call', 'owner', 'Plan our trip');+ sessions.updateTitle(id, 'Trip planning with Mercury');+ voiceFeed.ended('renamed-call', 'completed');+ expect(sessions.get(id)).toMatchObject({ title: 'Trip planning with Mercury', titleSource: 'user' });+ });+it('without a live transcript (older Optimus), the question and answer are what gets saved', () => {voiceFeed.started('desk-3');const threadId = voiceFeed.snapshot().threadId!;diff --git a/src/plugins/voice-calls.ts b/src/plugins/voice-calls.tsindex 3dcce8d8..3c3b5353 100644--- a/src/plugins/voice-calls.ts+++ b/src/plugins/voice-calls.ts@@ -30,7 +30,7 @@ export function recordVoiceCalls(sessions: SessionRepository): () => void {if (ev.type === 'state') {if (s.active && s.callId && current?.callId !== s.callId) {const startedAt = s.startedAt ?? Date.now();- const session = sessions.create({ title: `Voice call Β· ${clock(startedAt)}`, titleSource: 'user' });+ const session = sessions.create({ title: `Voice call Β· ${clock(startedAt)}`, titleSource: 'generated' });current = { callId: s.callId, threadId: session.id, startedAt, saved: 0 };voiceFeed.setThread(session.id);} else if (!s.active && current && s.endedAt) {@@ -42,7 +42,7 @@ export function recordVoiceCalls(sessions: SessionRepository): () => void {return;}const secs = (s.endedAt - done.startedAt) / 1000;- sessions.updateTitle(done.threadId, `Voice call Β· ${clock(done.startedAt)} Β· ${callDuration(secs)}`, 'user');+ sessions.updateTitle(done.threadId, `Voice call Β· ${clock(done.startedAt)} Β· ${callDuration(secs)}`, 'generated');}return;}diff --git a/src/sessions/repository.test.ts b/src/sessions/repository.test.tsindex 162b0685..04b5f787 100644--- a/src/sessions/repository.test.ts+++ b/src/sessions/repository.test.ts@@ -150,6 +150,21 @@ describe('SessionRepository', () => {expect(() => repository.updateTitle(session.id, ' '.repeat(2))).toThrow(/required/);});+ it('keeps a user rename when automatic generation or startup repair finishes later', async () => {+ const { root, repository } = fixture();+ const session = repository.create();+ repository.appendMessage(session.id, { role: 'user', content: 'Discuss the launch' });+ // Simulate a title generator/repair suspended while the owner renames.+ let finish!: () => void;+ const delayedTitle = new Promise<void>(resolve => { finish = resolve; }).then(() => repository.updateTitle(session.id, 'Automatic title', 'generated'));+ const renamed = repository.updateTitle(session.id, 'My launch plan', 'user', { touch: false });+ finish();+ await delayedTitle;+ repository.updateTitle(session.id, 'Fallback title', 'fallback');+ const reloaded = new SessionRepository({ rootDir: join(root, 'sessions'), autoMigrate: false });+ expect(reloaded.get(session.id)).toMatchObject({ title: 'My launch plan', titleSource: 'user', revision: renamed.revision });+ });+it('imports legacy web and short-term JSON idempotently without deleting sources', () => {const root = mkdtempSync(join(tmpdir(), 'mercury-migration-'));const web = join(root, 'web-chat-history');@@ -178,7 +193,7 @@ describe('SessionRepository', () => {describe('SessionRepository.updateTitle without touching', () => {it('renames without moving the session in the list', () => {const repo = new SessionRepository({ rootDir: mkdtempSync(join(tmpdir(), 'mercury-retitle-')), autoMigrate: false });- const older = repo.create({ title: 'Older' });+ const older = repo.create({ title: 'Older', titleSource: 'generated' });repo.appendMessage(older.id, { role: 'user', content: 'a', timestamp: 1_000 });const newer = repo.create({ title: 'Newer' });repo.appendMessage(newer.id, { role: 'user', content: 'b', timestamp: Date.now() + 60_000 });diff --git a/src/sessions/repository.ts b/src/sessions/repository.tsindex f5a9fce5..14f24c47 100644--- a/src/sessions/repository.ts+++ b/src/sessions/repository.ts@@ -71,6 +71,8 @@ export class SessionResolutionError extends Error {}}+export class SessionTitleError extends Error {}+export class SessionRepository {readonly rootDir: string;private readonly indexPath: string;@@ -243,9 +245,18 @@ export class SessionRepository {*/updateTitle(ref: string, title: string, titleSource: Session['titleSource'] = 'user', options: { touch?: boolean } = {}): Session {const normalized = title.replace(/\s+/g, ' ').trim();- if (!normalized) throw new Error('Session title is required');- if (normalized.length > 120) throw new Error('Session title must be 120 characters or fewer');+ if (!normalized) throw new SessionTitleError('Session title is required');+ const characters = Array.from(normalized);+ if (characters.length > 120) throw new SessionTitleError('Session title must be 120 characters or fewer');+ // for...of leaves unpaired surrogates intact; reject them rather than+ // persisting a title that changes when encoded by a client or filesystem.+ if (characters.some((character) => {+ const point = character.codePointAt(0)!;+ return point < 32 || (point >= 127 && point <= 159) || (point >= 0xd800 && point <= 0xdfff);+ })) throw new SessionTitleError('Session title must contain valid text without control characters');const session = this.get(ref);+ // A background generation/repair may finish after the owner renamed it.+ if (session.titleSource === 'user' && titleSource !== 'user') return session;if (session.title === normalized && session.titleSource === titleSource) return session;session.title = normalized;session.titleSource = titleSource;diff --git a/src/web/api/chat-rename-route.test.ts b/src/web/api/chat-rename-route.test.tsnew file mode 100644index 00000000..b354171b--- /dev/null+++ b/src/web/api/chat-rename-route.test.ts@@ -0,0 +1,70 @@+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, beforeEach, 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-rename-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';++const rename = (id: string, body: unknown) => chat.request(`http://127.0.0.1/api/chat/threads/${id}/title`, {+ method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),+});++describe('PUT /api/chat/threads/:id/title', () => {+ let root: string;+ let repo: SessionRepository;+ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'mercury-rename-sessions-'));+ repo = new SessionRepository({ rootDir: root, autoMigrate: false });+ setSessionRepository(repo);+ });+ afterEach(() => { vi.restoreAllMocks(); rmSync(root, { recursive: true, force: true }); });++ it('persists an owner title, preserves history and order, and returns it on reload', async () => {+ const session = repo.create();+ repo.appendMessage(session.id, { role: 'user', content: 'A first message', timestamp: 1000 });+ const before = repo.get(session.id);+ const response = await rename(session.id, { title: ' ζ θ‘ θ¨η»\nπ ' });+ expect(response.status).toBe(200);+ expect(await response.json()).toEqual({ id: session.id, title: 'ζ θ‘ θ¨η» π' });+ const reloaded = new SessionRepository({ rootDir: root, autoMigrate: false });+ expect(reloaded.get(session.id)).toMatchObject({ title: 'ζ θ‘ θ¨η» π', titleSource: 'user', updatedAt: before.updatedAt, messages: before.messages, revision: before.revision + 1 });+ setSessionRepository(reloaded);+ const list = await (await chat.request('http://127.0.0.1/api/chat/threads')).json() as { threads: Array<{ title: string }> };+ expect(list.threads[0].title).toBe('ζ θ‘ θ¨η» π');+ const detail = await (await chat.request(`http://127.0.0.1/api/chat/threads/${session.id}`)).json();+ expect(detail).toMatchObject({ title: 'ζ θ‘ θ¨η» π', messages: [{ content: 'A first message' }] });+ });++ it('accepts 120 Unicode code points and rejects 121 without silently truncating', async () => {+ const session = repo.create();+ expect((await rename(session.id, { title: 'π'.repeat(120) })).status).toBe(200);+ expect((await rename(session.id, { title: 'π'.repeat(121) })).status).toBe(400);+ expect(repo.get(session.id).title).toBe('π'.repeat(120));+ });++ it.each([null, {}, { title: 1 }, { title: '' }, { title: ' \n\t ' }, { title: 'bad\0title' }, { title: '\u0080' }, { title: '\ud800' }])('rejects invalid input without changing the session: %j', async body => {+ const session = repo.create({ title: 'Original' });+ expect((await rename(session.id, body)).status).toBe(400);+ expect(repo.get(session.id).title).toBe('Original');+ expect(repo.get(session.id).revision).toBe(session.revision);+ });++ it('returns 404 for unknown sessions and an honest 500 for persistence failures', async () => {+ expect((await rename('missing', { title: 'Name' })).status).toBe(404);+ const session = repo.create();+ vi.spyOn(repo, 'updateTitle').mockImplementation(() => { throw new Error('disk full'); });+ const response = await rename(session.id, { title: 'Name' });+ expect(response.status).toBe(500);+ expect(await response.json()).toEqual({ error: 'Could not save the chat name. Please try again.' });+ });+});diff --git a/src/web/api/chat.ts b/src/web/api/chat.tsindex 01f00fb4..2c317089 100644--- a/src/web/api/chat.ts+++ b/src/web/api/chat.ts@@ -16,6 +16,7 @@ import { existsSync, readFileSync, writeFileSync, readdirSync, statSync, rmSyncimport { join, extname, basename, relative, resolve } from 'node:path';import { getMercuryHome, loadConfig, getActiveProviders } from '../../utils/config.js';import type { SessionRepository } from '../../sessions/index.js';+import { SessionTitleError } from '../../sessions/repository.js';import { loadPermissionMode, savePermissionMode } from '../../capabilities/permission-mode-store.js';import {getModelPref, setModelPref, humanizeModelName, modelGroupLabel,@@ -752,6 +753,24 @@ chat.get('/api/chat/threads/:id', (c) => {}});+/** Owner titles survive automatic naming and keep the conversation's position. */+chat.put('/api/chat/threads/:id/title', async (c) => {+ if (!sessions) return c.json({ error: 'Session repository not initialized' }, 503);+ const body: unknown = await c.req.json().catch(() => null);+ if (!body || typeof body !== 'object' || !('title' in body) || typeof body.title !== 'string') {+ return c.json({ error: 'Send { title: "New chat name" }.' }, 400);+ }+ const id = c.req.param('id');+ try { sessions.get(id); } catch { return c.json({ error: 'Thread not found' }, 404); }+ try {+ const session = sessions.updateTitle(id, body.title, 'user', { touch: false });+ return c.json({ id: session.id, title: session.title });+ } catch (error) {+ if (error instanceof SessionTitleError) return c.json({ error: error.message }, 400);+ return c.json({ error: 'Could not save the chat name. Please try again.' }, 500);+ }+});+chat.delete('/api/chat/threads/:id', (c) => {const id = c.req.param('id');if (!sessions) return c.json({ error: 'Session repository not initialized' }, 503);diff --git a/ui/src/components/chat/ThreadList.tsx b/ui/src/components/chat/ThreadList.tsxindex 445adada..744cb9c2 100644--- a/ui/src/components/chat/ThreadList.tsx+++ b/ui/src/components/chat/ThreadList.tsx@@ -1,5 +1,5 @@import { useState } from "react";-import { Plus, Trash2, Download, MessageSquare } from "lucide-react";+import { Plus, Trash2, Download, MessageSquare, Pencil } from "lucide-react";import { cn } from "@/lib/utils";import { Button } from "@/components/ui/button";import { ScrollArea } from "@/components/ui/scroll-area";@@ -14,12 +14,15 @@ import {AlertDialogTitle,} from "@/components/ui/alert-dialog";import type { ChatThread } from "@/lib/api";+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";interface ThreadListProps {threads: ChatThread[];activeThreadId: string | null;onSelect: (id: string) => void;onDelete: (id: string) => void;+ onRename: (id: string, title: string) => Promise<void>;onNew: () => void;onExport: (id: string) => void;}@@ -29,10 +32,29 @@ export function ThreadList({activeThreadId,onSelect,onDelete,+ onRename,onNew,onExport,}: ThreadListProps) {const [deleteTarget, setDeleteTarget] = useState<string | null>(null);+ const [renameTarget, setRenameTarget] = useState<ChatThread | null>(null);+ const [title, setTitle] = useState("");+ const [saving, setSaving] = useState(false);+ const [renameError, setRenameError] = useState<string | null>(null);+ const normalizedTitle = title.replace(/\s+/g, " ").trim();+ const titleLength = Array.from(normalizedTitle).length;++ async function saveTitle(event: React.FormEvent) {+ event.preventDefault();+ if (!renameTarget || saving || !titleLength || titleLength > 120) return;+ setSaving(true);+ setRenameError(null);+ try {+ await onRename(renameTarget.id, normalizedTitle);+ setRenameTarget(null);+ } catch (error) { setRenameError(error instanceof Error ? error.message : "Could not save the chat name."); }+ finally { setSaving(false); }+ }function formatDate(iso: string): string {const d = new Date(iso);@@ -86,6 +108,7 @@ export function ThreadList({formatDate={formatDate}onSelect={() => onSelect(thread.id)}onDelete={() => setDeleteTarget(thread.id)}+ onRename={() => { setRenameTarget(thread); setTitle(thread.title ?? ""); setRenameError(null); }}onExport={() => onExport(thread.id)}/>);@@ -94,6 +117,27 @@ export function ThreadList({)}</ScrollArea>+ <Dialog open={renameTarget !== null} onOpenChange={open => { if (!open && !saving) setRenameTarget(null); }}>+ <DialogContent>+ <form onSubmit={saveTitle}>+ <DialogHeader>+ <DialogTitle>Rename chat</DialogTitle>+ <DialogDescription>Choose a name up to 120 characters. Mercury will keep the name you choose.</DialogDescription>+ </DialogHeader>+ <div className="my-4 space-y-2">+ <label htmlFor="chat-title" className="text-sm font-medium">Chat name</label>+ <Input id="chat-title" value={title} disabled={saving} autoFocus onFocus={event => event.target.select()} onChange={event => setTitle(event.target.value)} aria-describedby="chat-title-length" />+ <p id="chat-title-length" className={cn("text-xs", titleLength > 120 ? "text-destructive" : "text-muted-foreground")}>{titleLength}/120 characters</p>+ {renameError && <p role="alert" className="text-sm text-destructive">{renameError}</p>}+ </div>+ <DialogFooter>+ <Button type="button" variant="outline" disabled={saving} onClick={() => setRenameTarget(null)}>Cancel</Button>+ <Button type="submit" disabled={saving || !titleLength || titleLength > 120}>{saving ? "Savingβ¦" : "Save"}</Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+{/* Delete confirmation */}<AlertDialogopen={deleteTarget !== null}@@ -135,6 +179,7 @@ function ThreadItem({formatDate,onSelect,onDelete,+ onRename,onExport,}: {thread: ChatThread;@@ -142,6 +187,7 @@ function ThreadItem({formatDate: (iso: string) => string;onSelect: () => void;onDelete: () => void;+ onRename: () => void;onExport: () => void;}) {return (@@ -163,6 +209,13 @@ function ThreadItem({</div></div>+ <button+ onClick={event => { event.stopPropagation(); onRename(); }}+ className={cn("shrink-0 rounded-md p-1 text-muted-foreground hover:bg-muted hover:text-foreground transition-opacity focus-visible:opacity-100", isActive ? "opacity-100" : "opacity-0 group-hover:opacity-100")}+ aria-label={`Rename ${thread.title || "chat"}`} title="Rename chat">+ <Pencil className="h-3.5 w-3.5" />+ </button>+{/* Delete button */}<buttononClick={(e) => {diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.tsindex c4375d5c..25d40c2a 100644--- a/ui/src/lib/api.ts+++ b/ui/src/lib/api.ts@@ -217,6 +217,7 @@ export const chat = {threads: {list: () => get<{ threads: ChatThread[] }>("/api/chat/threads"),create: (title?: string) => post<ChatThread>("/api/chat/threads", { title }),+ rename: (id: string, title: string) => put<{ id: string; title: string }>(`/api/chat/threads/${encodeURIComponent(id)}/title`, { title }),get: (id: string) => get<ChatThread>(`/api/chat/threads/${id}`),delete: (id: string) => post<{ deleted: boolean; syncPending: boolean }>(`/api/chat/threads/${id}/delete`, { confirmSessionId: id }),addMessage: (id: string, role: string, content: string) =>diff --git a/ui/src/pages/Chat.tsx b/ui/src/pages/Chat.tsxindex cd2c2848..5f2f0e2b 100644--- a/ui/src/pages/Chat.tsx+++ b/ui/src/pages/Chat.tsx@@ -542,6 +542,12 @@ export function ChatPage() {}}+ async function handleRenameThread(id: string, title: string) {+ const renamed = await api.chat.threads.rename(id, title);+ const { threads, setThreads } = useChatStore.getState();+ setThreads(threads.map(thread => thread.id === renamed.id ? { ...thread, title: renamed.title } : thread));+ }+async function handleDeleteThread(id: string) {try {await api.chat.threads.delete(id);@@ -603,6 +609,7 @@ export function ChatPage() {activeThreadId={activeThreadId}onSelect={handleSelectThread}onDelete={handleDeleteThread}+ onRename={handleRenameThread}onNew={() => handleNewThread()}onExport={handleExportThread}/>@@ -635,6 +642,7 @@ export function ChatPage() {setSidebarOpen(false);}}onDelete={handleDeleteThread}+ onRename={handleRenameThread}onNew={() => {handleNewThread();setSidebarOpen(false);diff --git a/website/docs/desktop/mercury-desktop.mdx b/website/docs/desktop/mercury-desktop.mdxindex c80cffb5..e3095e52 100644--- a/website/docs/desktop/mercury-desktop.mdx+++ b/website/docs/desktop/mercury-desktop.mdx@@ -107,7 +107,7 @@ Add as many connections as you like and switch between them from the top bar. Th## What else is in the app-- **Chat and Code.** Conversations, and a coding workspace per project.+- **Chat and Code.** Conversations, and a coding workspace per project. Use the pencil beside a conversation to rename it; the name is saved on the connected Mercury and automatic titles won't replace it.- **Research.** A research bar with live progress, sources read and failed with reasons, and a report you can export as PDF or Word.- **Bots.** Create and run bots, and read their results in one inbox.- **Notifications** when a reply, a research run or a bot needs you.diff --git a/website/docs/integrations/web-dashboard.mdx b/website/docs/integrations/web-dashboard.mdxindex 4a43ba4e..ef20155a 100644--- a/website/docs/integrations/web-dashboard.mdx+++ b/website/docs/integrations/web-dashboard.mdx@@ -50,6 +50,7 @@ A multi-thread chat interface with SSE streaming.- **Thread sidebar** β Lists all conversations. Click any thread to switch; the URL updates to `/chat/<id>` so you can bookmark or share links.- **New Chat** button β Creates a new thread and navigates to its URL.+- **Rename** β Use the pencil beside a conversation to choose a name (up to 120 characters). Save applies it; Cancel or Escape keeps the existing name. Your name survives restarts and automatic title generation.- **Delete** β Hover a thread (or open it) to reveal a trash icon. Confirmation dialog prevents accidents.- **Model switcher** β Top of the chat header. Pick any configured provider; the choice is per-thread.- **Code Mode toggle** β Switches the agent into coding mode for the active thread (file edits, shell calls allowed under your permission policy).