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(artifacts): save what Mercury makes in ~/mercury-artifacts, one folder per chat

Salman Qureshi3fc220a91724
diff --git a/DECISIONS.md b/DECISIONS.md
index 14f0c9e0..b3650305 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -339,3 +339,9 @@
- **Desktop**: a research bar above the composer (on for the next message, or the live phase · questions done · read · failed · searches · time · step N/225, with Details and "Write report now"); Details is Sources (read / cited / failed + reason, filterable) and Activity (questions, searches); the plan card to edit and Start; a report card under the answer (Open report, Copy, Sources & activity, Continue research / Go deeper, Retry N failed); a Research toggle in the composer (normal, deep research, plan first); a research notification ("Research ready: … · 41 sources read · 23 cited") instead of the plain "Done".
- **Consequence**: The owner can see what research is doing, why sources failed, and always gets what was gathered. Not here: steering a run mid-way with new instructions (a follow-up waits in the queue), resuming a run after a restart (runs live in memory; the report file and the thread's metadata persist).
- **Export and site icons (follow-up)**: any Markdown or text artifact can be saved as a PDF or a Word document (`GET /api/artifacts/:id/file?as=pdf|docx`, `POST …/export { dest, as }`; flag `artifacts.convert`), from the report card's Export menu and the artifact viewer's "Export as". Both are written by the runtime with no library or browser (`src/artifacts/convert/`: Markdown → blocks via `marked`, a small zip writer for the `.docx`, a PDF writer on the PDF core fonts with real glyph widths, page numbers and clickable links). The PDF's core fonts cover Western European text (other scripts show as "?"; the Word file keeps every character). Site icons in the source list come from `GET /api/chat/favicon?domain=` (flag `chat.favicon`): the runtime fetches the site's `/favicon.ico` through the SSRF guard, then DuckDuckGo's icon service, keeps only real images (≤ 100 KB), and caches them in `~/.mercury/cache/favicons` (30 days; "no icon" 7 days). The app still loads nothing from third parties.
+
+## ADR-034: What Mercury makes goes in ~/mercury-artifacts, one folder per chat
+
+- **Context**: The daemon runs from the home folder (so it doesn't write into a repo), and a chat's tools resolve paths against that folder, so every file a chat made without a full path landed loose in `~` (`how-to-programming-research.md`, `open-source-articles-….txt`). Models also wrote absolute home paths, because the prompt said the working directory was `~`. The artifact store's copies under `~/.mercury/artifacts` are for the apps, not for browsing, and research reports went to the hidden `~/.mercury/research`.
+- **Decision**: One visible output folder, `~/mercury-artifacts` (the owner's choice of name; `artifacts.outputDir` changes it, `~` paths allowed): `Research/` for reports, and `Chats/<date> <chat title or its first words>/` for each chat that makes something. A normal chat turn whose working directory would be the home folder works in its chat's folder instead (tools, `run_command`, and the prompt's "Working directory", plus one line telling the model to keep files there unless the owner names another place). Not changed: Code sessions and workspaces (their project folder), a terminal opened inside a project (its folder), bots (their own folders), internal turns, and any path the owner gives. A chat's folder is named once and recorded in `~/.mercury/artifacts/chat-folders.json`, so a title generated later never moves files; same-name chats get "(2)". The folder is created when the turn starts and removed when it ends if nothing was saved (a lone `.DS_Store` counts as empty), so there are no empty folders. `GET /api/artifacts/folder` reports the folder and files Mercury made that sit loose in the home folder; `POST /api/artifacts/folder/tidy` (this computer only) moves those into their chats' folders and updates the artifact records, so Open and Show in Finder still work. It moves only files in the artifact store, never anything else in the home folder. The desktop Artifacts view shows where files are saved, has Open folder, and offers the move once.
+- **Consequence**: The home folder stays clean, and what Mercury made is grouped the way the owner remembers it, by conversation. A relative path in a normal chat ("read notes.md") now means the chat's folder, not `~`; full paths and `~/…` are unaffected. Not here: moving files written before the artifact store existed (Mercury can't know it made them), and per-bot output under the same folder (bots keep `~/.mercury/bots/<id>`).
diff --git a/apps/desktop/src-tauri/capabilities/default.json b/apps/desktop/src-tauri/capabilities/default.json
index 65b964fc..3c47efc5 100644
--- a/apps/desktop/src-tauri/capabilities/default.json
+++ b/apps/desktop/src-tauri/capabilities/default.json
@@ -24,6 +24,17 @@
"deep-link:default",
"opener:default",
"opener:allow-reveal-item-in-dir",
+ {
+ "identifier": "opener:allow-open-path",
+ "allow": [
+ {
+ "path": "$HOME/mercury-artifacts"
+ },
+ {
+ "path": "$HOME/mercury-artifacts/**"
+ }
+ ]
+ },
"os:default",
"os:allow-hostname",
"process:default",
diff --git a/apps/desktop/src/api/artifacts.ts b/apps/desktop/src/api/artifacts.ts
index 1722d9d4..1ca2a43e 100644
--- a/apps/desktop/src/api/artifacts.ts
+++ b/apps/desktop/src/api/artifacts.ts
@@ -37,6 +37,10 @@ export const artifactsApi = {
get: (id: string) => http.get<{ artifact: ArtifactItem }>(`/api/artifacts/${encodeURIComponent(id)}`).then((r) => r.artifact),
remove: (id: string) => http.delete<{ ok: boolean }>(`/api/artifacts/${encodeURIComponent(id)}`),
/** Save a copy to a folder on the computer Mercury runs on. */
+ /** Where Mercury saves what it makes (~/mercury-artifacts), and files it left loose in the home folder. */
+ folder: () => http.get<{ path: string; display: string; exists: boolean; strays: Array<{ id: string; name: string; path: string; threadId: string; threadTitle: string | null }> }>("/api/artifacts/folder"),
+ /** Move those loose files into their chats' folders. */
+ tidy: () => http.post<{ moved: Array<{ name: string; to: string }>; failed: Array<{ name: string; error: string }> }>("/api/artifacts/folder/tidy", {}),
/** Save a copy on this computer; `as` makes a Markdown/text artifact a PDF or Word document. */
exportTo: (id: string, dest: string, as?: "pdf" | "docx") => http.post<{ ok: boolean; path: string }>(`/api/artifacts/${encodeURIComponent(id)}/export`, { dest, ...(as ? { as } : {}) }),
};
diff --git a/apps/desktop/src/views/artifacts/ArtifactsView.tsx b/apps/desktop/src/views/artifacts/ArtifactsView.tsx
index 5c195c8c..fce96398 100644
--- a/apps/desktop/src/views/artifacts/ArtifactsView.tsx
+++ b/apps/desktop/src/views/artifacts/ArtifactsView.tsx
@@ -10,6 +10,7 @@ import { Button } from "~/components/ui/Button";
import { Spinner } from "~/components/ui/bits";
import { SearchField } from "~/components/ui/kit";
import { cx } from "~/lib/cx";
+import { OutputFolder } from "./OutputFolder";
/**
* Artifacts: everything Mercury made (images, videos, audio, PDFs,
@@ -118,6 +119,7 @@ export function ArtifactsView() {
)}
</div>
+ <OutputFolder visible={visible} onTidied={() => void load(false)} />
<div className="min-h-0 flex-1 overflow-y-auto p-4">
{error && <p className="mb-3 text-sm text-red">{error}</p>}
{!loaded && <div className="p-6"><Spinner size={16} /></div>}
diff --git a/apps/desktop/src/views/artifacts/OutputFolder.tsx b/apps/desktop/src/views/artifacts/OutputFolder.tsx
new file mode 100644
index 00000000..44f5227d
--- /dev/null
+++ b/apps/desktop/src/views/artifacts/OutputFolder.tsx
@@ -0,0 +1,99 @@
+import { FolderInput, FolderOpen, X } from "lucide-react";
+import { useEffect, useState } from "react";
+import { artifactsApi } from "~/api/artifacts";
+import { Button } from "~/components/ui/Button";
+import { useConnections } from "~/shell/connections";
+import { isTauri } from "~/shell/tauri";
+
+type Folder = Awaited<ReturnType<typeof artifactsApi.folder>>;
+
+const DISMISSED = "mercury.artifacts.tidy.dismissed";
+function dismissedFor(): string {
+ try { return localStorage.getItem(DISMISSED) ?? ""; } catch { return ""; }
+}
+
+/**
+ * Where Mercury keeps what it makes (~/mercury-artifacts: Research/ and a
+ * folder per chat), one click from Finder. And, once, an offer to move the
+ * files Mercury left loose in your home folder before that folder existed
+ * into their chats' folders. Only files Mercury knows it made; never anything else.
+ */
+export function OutputFolder({ visible, onTidied }: { visible: boolean; onTidied: () => void }) {
+ const local = useConnections((s) => s.connections.find((c) => c.id === s.activeId)?.kind === "local");
+ const [folder, setFolder] = useState<Folder | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [note, setNote] = useState<{ text: string; ok: boolean } | null>(null);
+ const [dismissed, setDismissed] = useState(dismissedFor);
+
+ useEffect(() => {
+ if (!visible) return;
+ let live = true;
+ artifactsApi.folder().then((f) => { if (live) setFolder(f); }).catch(() => { /* older Mercury */ });
+ return () => { live = false; };
+ }, [visible]);
+
+ if (!folder) return null;
+ const strayKey = folder.strays.map((s) => s.id).sort().join(",");
+ const offer = local && folder.strays.length > 0 && dismissed !== strayKey;
+
+ async function open() {
+ const { openPath, revealItemInDir } = await import("@tauri-apps/plugin-opener");
+ try {
+ await openPath(folder!.path);
+ } catch {
+ // A folder set somewhere else than ~/mercury-artifacts: show it in Finder instead.
+ try { await revealItemInDir(folder!.path); } catch (e) { setNote({ text: e instanceof Error ? e.message : String(e), ok: false }); }
+ }
+ }
+
+ async function tidy() {
+ setBusy(true);
+ setNote(null);
+ try {
+ const r = await artifactsApi.tidy();
+ setNote(r.failed.length
+ ? { text: `Moved ${r.moved.length}; couldn't move ${r.failed.map((f) => `${f.name} (${f.error})`).join(", ")}.`, ok: false }
+ : { text: `Moved ${r.moved.length} file${r.moved.length === 1 ? "" : "s"} into ${folder!.display}.`, ok: true });
+ setFolder(await artifactsApi.folder());
+ onTidied();
+ } catch (e) {
+ setNote({ text: e instanceof Error ? e.message : String(e), ok: false });
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ function notNow() {
+ try { localStorage.setItem(DISMISSED, strayKey); } catch { /* per-device nicety */ }
+ setDismissed(strayKey);
+ }
+
+ const names = folder.strays.slice(0, 3).map((s) => s.name).join(", ") + (folder.strays.length > 3 ? ` and ${folder.strays.length - 3} more` : "");
+
+ return (
+ <div className="flex shrink-0 flex-col gap-2 border-b border-line px-5 py-2">
+ <div className="flex items-center gap-2 text-xs text-ink3">
+ <FolderOpen size={13} className="shrink-0 text-ink4" aria-hidden="true" />
+ <span className="min-w-0 truncate">
+ Saved in <span className="font-mono text-ink2" data-selectable title={folder.path}>{folder.display}</span>
+ <span className="text-ink4">: Research, and a folder for each chat</span>
+ </span>
+ <span className="flex-1" />
+ {isTauri && local && (folder.exists
+ ? <Button size="sm" variant="ghost" onClick={() => void open()}>Open folder</Button>
+ : <span className="text-ink4">made when Mercury saves its first file</span>)}
+ </div>
+ {offer && (
+ <div className="flex flex-wrap items-center gap-2.5 rounded-lg border border-line bg-soft px-3 py-2">
+ <FolderInput size={14} className="shrink-0 text-accent" aria-hidden="true" />
+ <span className="min-w-0 flex-1 text-sm text-ink2">
+ {folder.strays.length} file{folder.strays.length === 1 ? "" : "s"} Mercury made {folder.strays.length === 1 ? "is" : "are"} loose in your home folder ({names}). Move {folder.strays.length === 1 ? "it" : "them"} into {folder.strays.length === 1 ? "its chat's folder" : "their chats' folders"}?
+ </span>
+ <Button size="sm" variant="primary" loading={busy} onClick={() => void tidy()}>Move {folder.strays.length === 1 ? "it" : "them"}</Button>
+ <Button size="sm" variant="ghost" onClick={notNow} aria-label="Not now"><X size={13} /> Not now</Button>
+ </div>
+ )}
+ {note && <p className={note.ok ? "text-xs text-accent" : "text-xs text-red"}>{note.text}</p>}
+ </div>
+ );
+}
diff --git a/src/artifacts/output-dir.test.ts b/src/artifacts/output-dir.test.ts
new file mode 100644
index 00000000..d8186f72
--- /dev/null
+++ b/src/artifacts/output-dir.test.ts
@@ -0,0 +1,73 @@
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
+import { homedir, tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, describe, expect, it } from 'vitest';
+import { ChatFolders, folderLabel, freeName, outputRoot } from './output-dir.js';
+
+const dirs: string[] = [];
+const tmp = () => { const d = mkdtempSync(join(tmpdir(), 'outdir-')); dirs.push(d); return d; };
+afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); });
+const NOV2 = new Date(2026, 10, 2, 22, 0).getTime();
+
+describe('the output folder', () => {
+ it('is ~/mercury-artifacts unless set to an absolute or ~ path', () => {
+ expect(outputRoot()).toBe(join(homedir(), 'mercury-artifacts'));
+ expect(outputRoot('~/Work/Mercury')).toBe(join(homedir(), 'Work', 'Mercury'));
+ expect(outputRoot('/Volumes/data/out/')).toBe('/Volumes/data/out');
+ expect(outputRoot('relative/dir')).toBe(join(homedir(), 'mercury-artifacts'));
+ });
+
+ it('names folders like a person would, safely', () => {
+ expect(folderLabel('How to become rich?')).toBe('How to become rich');
+ expect(folderLabel('/research solar storms: a/b <c>')).toBe('solar storms a b c');
+ expect(folderLabel('...')).toBe('Chat');
+ expect(folderLabel('word '.repeat(30)).length).toBeLessThanOrEqual(48);
+ expect(folderLabel('a\u0000b\nc')).toBe('a b c');
+ });
+
+ it('gives each chat one folder, named once, never reused by another chat', () => {
+ const root = tmp();
+ const index = join(tmp(), 'index.json');
+ const f = new ChatFolders(root, index);
+ const a = f.pathFor('s1', 'How to become rich', NOV2);
+ expect(a).toBe(join(root, 'Chats', '2026-11-02 How to become rich'));
+ // A new title later doesn't move it.
+ expect(f.pathFor('s1', 'Wealth building guide', NOV2 + 3600_000)).toBe(a);
+ // Another chat with the same words gets its own.
+ expect(f.pathFor('s2', 'How to become rich', NOV2)).toBe(`${a} (2)`);
+ // The names survive a restart.
+ expect(new ChatFolders(root, index).pathFor('s1', 'x', 0)).toBe(a);
+ });
+
+ it('exists only while it holds something', () => {
+ const root = tmp();
+ const f = new ChatFolders(root, join(tmp(), 'index.json'));
+ const empty = f.open('s1', 'nothing made', NOV2);
+ expect(existsSync(empty)).toBe(true);
+ f.close(empty);
+ expect(existsSync(empty)).toBe(false);
+ expect(existsSync(join(root, 'Chats'))).toBe(false);
+ const used = f.open('s2', 'made a file', NOV2);
+ writeFileSync(join(used, 'notes.md'), '# hi');
+ f.close(used);
+ expect(readdirSync(used)).toEqual(['notes.md']);
+ // Finder's .DS_Store alone is still empty.
+ const finder = f.open('s3', 'finder looked', NOV2);
+ writeFileSync(join(finder, '.DS_Store'), '');
+ f.close(finder);
+ expect(existsSync(finder)).toBe(false);
+ // Never anything outside the output folder.
+ const outside = tmp();
+ mkdirSync(join(outside, 'x'));
+ f.close(join(outside, 'x'));
+ expect(existsSync(join(outside, 'x'))).toBe(true);
+ });
+
+ it('finds a free file name', () => {
+ const d = tmp();
+ writeFileSync(join(d, 'r.md'), '');
+ writeFileSync(join(d, 'r (2).md'), '');
+ expect(freeName(d, 'r.md')).toBe('r (3).md');
+ expect(freeName(d, 'new.md')).toBe('new.md');
+ });
+});
diff --git a/src/artifacts/output-dir.ts b/src/artifacts/output-dir.ts
new file mode 100644
index 00000000..178ceb17
--- /dev/null
+++ b/src/artifacts/output-dir.ts
@@ -0,0 +1,141 @@
+import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
+import { getMercuryHome } from '../utils/config.js';
+import { logger } from '../utils/logger.js';
+
+/**
+ * Where the files Mercury makes go: one visible folder in your home folder,
+ * `~/mercury-artifacts` (or `artifacts.outputDir`), instead of loose files
+ * in `~` (the daemon's working folder).
+ *
+ * ~/mercury-artifacts/
+ * Research/ research reports
+ * Chats/2026-11-02 How to become rich/ what that chat made
+ *
+ * A chat's folder is named once (its date and title, or its first words) and
+ * keeps that name, so a renamed chat never moves files you already opened.
+ * It exists only while it holds something: made at the start of a turn,
+ * removed again if the turn left it empty.
+ */
+
+export const DEFAULT_OUTPUT_DIR = '~/mercury-artifacts';
+
+export function expandHome(p: string): string {
+ if (p === '~') return homedir();
+ if (p.startsWith('~/')) return join(homedir(), p.slice(2));
+ return p;
+}
+
+/** The output folder, absolute. A relative or unusable setting falls back to the default. */
+export function outputRoot(setting?: string | null): string {
+ const raw = (setting ?? '').trim();
+ const p = raw ? expandHome(raw) : expandHome(DEFAULT_OUTPUT_DIR);
+ return isAbsolute(p) ? resolve(p) : expandHome(DEFAULT_OUTPUT_DIR);
+}
+
+export function researchDir(root: string): string {
+ return join(root, 'Research');
+}
+
+/** A chat's label as a folder name: no path or reserved characters, short, never empty. */
+export function folderLabel(text: string, max = 48): string {
+ const clean = text
+ .replace(/^\/\S+\s*/, '') // "/research …" is about the rest
+ .replace(/[\\/:*?"<>|#%{}^~[\]`]/g, ' ')
+ .replace(/[^\P{C}]/gu, ' ')
+ .replace(/\s+/g, ' ')
+ .trim();
+ let label = clean;
+ if (label.length > max) {
+ label = label.slice(0, max);
+ const space = label.lastIndexOf(' ');
+ if (space > max * 0.6) label = label.slice(0, space);
+ }
+ label = label.replace(/^[.\s]+|[.\s]+$/g, '');
+ return label || 'Chat';
+}
+
+const day = (at: number): string => {
+ const d = new Date(at);
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
+};
+
+export class ChatFolders {
+ private map: Record<string, string> | null = null;
+
+ /** `index` is Mercury's own record of which chat has which folder (kept in ~/.mercury, not in the output folder). */
+ constructor(readonly root: string, private readonly index: string) {}
+
+ private load(): Record<string, string> {
+ if (this.map) return this.map;
+ try { this.map = existsSync(this.index) ? JSON.parse(readFileSync(this.index, 'utf-8')) as Record<string, string> : {}; } catch { this.map = {}; }
+ return this.map!;
+ }
+
+ private save(): void {
+ try {
+ mkdirSync(dirname(this.index), { recursive: true });
+ const tmp = `${this.index}.tmp`;
+ writeFileSync(tmp, JSON.stringify(this.map ?? {}), 'utf-8');
+ renameSync(tmp, this.index);
+ } catch (err) {
+ logger.warn({ err: err instanceof Error ? err.message : String(err) }, 'Chat folders: saving the index failed');
+ }
+ }
+
+ /** The folder for a chat (not created). `label` names it the first time; later calls keep that name. */
+ pathFor(sessionId: string, label: string, createdAt: number): string {
+ const map = this.load();
+ const known = map[sessionId];
+ if (known) return join(this.root, 'Chats', known);
+ const taken = new Set(Object.values(map));
+ const base = `${day(createdAt)} ${folderLabel(label)}`;
+ let name = base;
+ for (let n = 2; taken.has(name) || existsSync(join(this.root, 'Chats', name)); n++) name = `${base} (${n})`;
+ map[sessionId] = name;
+ this.save();
+ return join(this.root, 'Chats', name);
+ }
+
+ /** Make it for a turn. */
+ open(sessionId: string, label: string, createdAt: number): string {
+ const dir = this.pathFor(sessionId, label, createdAt);
+ mkdirSync(dir, { recursive: true });
+ return dir;
+ }
+
+ /** The turn ended: an empty folder goes (and Chats/ too, if that leaves it empty). */
+ close(dir: string): void {
+ for (const d of [dir, dirname(dir)]) {
+ try {
+ if (!d.startsWith(this.root) || d === this.root) return;
+ // Only Finder's .DS_Store left counts as empty.
+ if (readdirSync(d).some((f) => f !== '.DS_Store')) return;
+ try { rmSync(d, { recursive: true }); } catch { /* a race: leave it */ }
+ } catch { return; }
+ }
+ }
+
+ /** The folder name a chat has (for tests and the apps). */
+ nameOf(sessionId: string): string | undefined {
+ const known = this.load()[sessionId];
+ return known ? basename(known) : undefined;
+ }
+}
+
+let shared: ChatFolders | null = null;
+/** The one ChatFolders for an output folder (the agent and the API share its index). */
+export function chatFoldersFor(root: string): ChatFolders {
+ if (shared?.root !== root) shared = new ChatFolders(root, join(getMercuryHome(), 'artifacts', 'chat-folders.json'));
+ return shared;
+}
+
+/** A free name for `name` in `dir`: "report.md", then "report (2).md"… */
+export function freeName(dir: string, name: string): string {
+ if (!existsSync(join(dir, name))) return name;
+ const dot = name.lastIndexOf('.');
+ const stem = dot > 0 ? name.slice(0, dot) : name;
+ const ext = dot > 0 ? name.slice(dot) : '';
+ for (let n = 2; ; n++) if (!existsSync(join(dir, `${stem} (${n})${ext}`))) return `${stem} (${n})${ext}`;
+}
diff --git a/src/artifacts/store.ts b/src/artifacts/store.ts
index f3f62552..2c242bc0 100644
--- a/src/artifacts/store.ts
+++ b/src/artifacts/store.ts
@@ -106,6 +106,21 @@ export class ArtifactStore {
return true;
}
+ /** Every record, newest first (not paged: for sweeps over all of them). */
+ all(): Artifact[] {
+ return [...this.load()];
+ }
+
+ /** The owner's file moved (tidied into the output folder): remember where it is now. */
+ relocate(id: string, originalPath: string): Artifact | null {
+ const a = this.load().find((x) => x.id === id);
+ if (!a) return null;
+ a.originalPath = originalPath;
+ a.name = basename(originalPath);
+ this.save();
+ return a;
+ }
+
/** The thread was deleted: its artifacts go too (Mercury's copies; the owner's originals stay). */
removeThread(threadId: string): number {
const items = this.load();
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 655d87d6..0cd4561f 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -16,6 +16,7 @@ import type { ScheduledTaskManifest } from './scheduler.js';
import { DeepSeekProvider } from '../providers/deepseek.js';
import { ArtifactCollector } from '../artifacts/collector.js';
import { artifactStore, type Artifact } from '../artifacts/store.js';
+import { chatFoldersFor, outputRoot, researchDir, type ChatFolders } from '../artifacts/output-dir.js';
import { artifactKindLabel, artifactRef, formatBytes } from '../artifacts/ref.js';
import { getMercuryHome } from '../utils/config.js';
import { createProvider } from '../providers/registry.js';
@@ -1182,6 +1183,11 @@ export class Agent {
});
}
+ /** One folder per chat in the output folder (~/mercury-artifacts/Chats). */
+ private chatFolders(): ChatFolders {
+ return chatFoldersFor(outputRoot(this.config.artifacts?.outputDir));
+ }
+
/** Tell screens how a research run stands (the desktop's chip, panel and report card). */
private emitResearch(msg: ChannelMessage, run: ResearchRun): void {
const channel = this.channels.getChannelForMessage(msg);
@@ -1258,7 +1264,7 @@ export class Agent {
/** Keep a research report as a file with the conversation (Artifacts), with every source consulted. */
private saveResearchReport(run: ResearchRun, text: string, threadId: string): Artifact | null {
try {
- const dir = path.join(getMercuryHome(), 'research');
+ const dir = researchDir(outputRoot(this.config.artifacts?.outputDir));
mkdirSync(dir, { recursive: true });
const title = /^#\s+(.+)$/m.exec(text)?.[1]?.trim() || run.topic;
const file = path.join(dir, reportFileName(title, run.startedAt));
@@ -2792,6 +2798,9 @@ export class Agent {
this.markProgress('Starting...');
this.pushLiveActivity('Starting task');
};
+ // This chat's folder in ~/mercury-artifacts for the turn, if it gets one (set below).
+ let chatFolder: string | null = null;
+ let cwdBeforeChatFolder: string | null = null;
// Research switched on for this chat: this message is the run.
const researchRun = !isSlashCommand && msg.channelType !== 'internal' && this.researchMode.armedForSession(msg.channelId)
? this.researchMode.beginRun(msg.channelId, msg.content, this.saverMode.adjustMaxSteps(MAX_STEPS) * 3)
@@ -3008,7 +3017,34 @@ export class Agent {
}
}
+ const suppliedSessionId = msg.sessionId ?? (typeof msg.metadata?.sessionId === 'string' ? msg.metadata.sessionId : undefined);
+ const externalConversationId = msg.channelType === 'cli'
+ ? 'current'
+ : typeof msg.metadata?.externalConversationId === 'string' ? msg.metadata.externalConversationId : msg.channelId;
+ const canonicalSession = this.sessions.getOrCreateBound(msg.channelType, externalConversationId, suppliedSessionId);
+ canonicalSessionId = canonicalSession.id;
+
+ // A normal chat that would write loose files into the home folder (the
+ // daemon's folder) writes into its own folder in ~/mercury-artifacts.
+ // Code sessions, workspaces, a terminal opened in a project: unchanged.
+ if (!isSlashCommand && msg.channelType !== 'internal' && !this.programmingMode.isActive()
+ && path.resolve(this.capabilities.getCwd()) === path.resolve(homedir())) {
+ try {
+ const firstWords = canonicalSession.messages.find((m) => m.role === 'user')?.content ?? msg.content;
+ // A real title when the chat has one; otherwise its first words (titles come after the first reply).
+ const label = canonicalSession.title && canonicalSession.titleSource !== 'fallback' ? canonicalSession.title : fallbackSessionTitle(firstWords) || firstWords;
+ const dir = this.chatFolders().open(canonicalSession.id, label, canonicalSession.createdAt || Date.now());
+ cwdBeforeChatFolder = this.capabilities.getCwd();
+ chatFolder = dir;
+ this.capabilities.setCwd(dir);
+ this.capabilities.permissions.addTempScope(dir, true, true);
+ } catch (err) {
+ logger.warn({ err: err instanceof Error ? err.message : String(err) }, 'Chat folder unavailable; working in the home folder');
+ }
+ }
+
let systemPrompt = this.buildSystemPrompt();
+ if (chatFolder) systemPrompt += `\n- Files you make go in the working directory (this chat's folder in the owner's Mercury artifacts folder), unless the owner names another place. Use relative paths or that folder; never write loose files into the home folder.`;
if (msg.metadata?.workContinuation === true) {
const attempt = typeof msg.metadata.continuationAttempt === 'number' ? msg.metadata.continuationAttempt : 1;
const reason = typeof msg.metadata.continuationReason === 'string' ? msg.metadata.continuationReason : 'The prior execution was interrupted.';
@@ -3019,12 +3055,6 @@ export class Agent {
} else if (msg.metadata?.workRecovered === true) {
systemPrompt += '\n\n[SYSTEM: RECOVERED WORK] This request was recovered after the agent restarted or its prior run was interrupted. Inspect the current filesystem, external state, and conversation before acting. Do not repeat side effects that may already have completed. Continue from observed state, and explicitly report any ambiguity you cannot safely resolve.';
}
- const suppliedSessionId = msg.sessionId ?? (typeof msg.metadata?.sessionId === 'string' ? msg.metadata.sessionId : undefined);
- const externalConversationId = msg.channelType === 'cli'
- ? 'current'
- : typeof msg.metadata?.externalConversationId === 'string' ? msg.metadata.externalConversationId : msg.channelId;
- const canonicalSession = this.sessions.getOrCreateBound(msg.channelType, externalConversationId, suppliedSessionId);
- canonicalSessionId = canonicalSession.id;
const canonicalMessageId = typeof msg.metadata?.canonicalMessageId === 'string' ? msg.metadata.canonicalMessageId : undefined;
const requestId = typeof msg.metadata?.requestId === 'string' ? msg.metadata.requestId : undefined;
this.sessions.appendMessage(canonicalSession.id, {
@@ -4787,6 +4817,10 @@ export class Agent {
} catch { /* best effort */ }
this.lifecycle.transition('idle');
} finally {
+ if (chatFolder) {
+ if (cwdBeforeChatFolder && this.capabilities.getCwd() === chatFolder) this.capabilities.setCwd(cwdBeforeChatFolder);
+ this.chatFolders().close(chatFolder);
+ }
if (researchRun) {
researchRun.end('failed', 'it ended before writing a report');
this.emitResearch(msg, researchRun);
diff --git a/src/index.ts b/src/index.ts
index 51d77ed4..2296a617 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -104,7 +104,7 @@ import { spawnDetachedRestart } from './cli/daemon.js';
import { recordVoiceCalls } from './plugins/voice-calls.js';
import { setChannelRuntime } from './web/api/channels.js';
import { setSkillBuilder } from './web/api/system.js';
-import { setArtifactSessions } from './web/api/artifacts.js';
+import { setArtifactOutputDir, setArtifactSessions } from './web/api/artifacts.js';
import { artifactStore } from './artifacts/store.js';
import { isWebAuthInitialized, setWebPassword, writeAttachToken, initWebAuth } from './web/auth.js';
import { startLoopLagMonitor } from './utils/loop-lag.js';
@@ -2530,6 +2530,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
const sessions = new SessionRepository();
// Artifacts follow their thread: drop those whose thread is gone (deleted anywhere), now and every hour.
setArtifactSessions(sessions);
+ setArtifactOutputDir(() => config.artifacts?.outputDir);
const sweepArtifacts = () => {
try {
const removed = artifactStore().reconcile((id) => { try { return sessions.get(id).status !== 'deleted'; } catch { return false; } });
diff --git a/src/utils/config.ts b/src/utils/config.ts
index c415b508..2b685ffc 100644
--- a/src/utils/config.ts
+++ b/src/utils/config.ts
@@ -295,6 +295,10 @@ export interface MercuryConfig {
corsOrigins?: string[];
};
mcp?: McpConfig;
+ /** Where the files Mercury makes go (default ~/mercury-artifacts): Research/ and one folder per chat. */
+ artifacts?: {
+ outputDir?: string;
+ };
}
function getEnv(key: string, fallback: string = ''): string {
diff --git a/src/web/api-contract.ts b/src/web/api-contract.ts
index 913e8662..2ffee8ef 100644
--- a/src/web/api-contract.ts
+++ b/src/web/api-contract.ts
@@ -52,6 +52,7 @@ export const API_FEATURES: readonly string[] = Object.freeze([
'cloud.signin', // GET /api/cloud/status, POST/GET/DELETE /api/cloud/signin (browser pairing from any client) // POST /api/voice/check { vendor, key?, endpoint? }
'brain.map', // GET /api/brain/map[?archive=1] — themes, sub-themes, notes, related links
'artifacts.convert', // GET /api/artifacts/:id/file?as=pdf|docx, POST /api/artifacts/:id/export { dest, as } — Markdown/text as PDF or Word
+ 'artifacts.folder', // GET /api/artifacts/folder (the output folder, loose files), POST /api/artifacts/folder/tidy
'chat.favicon', // GET /api/chat/favicon?domain= — a site's icon (204 when it has none), fetched and cached by the runtime
'chat.research', // SSE 'research' / 'research_plan' / 'research_plan_resolved' / 'notice'; GET /api/chat/threads/:id/research, POST …/research/finish, …/research/off, POST /api/chat/research/plan/:id; message.research; step_done { failed, reason }
]);
diff --git a/src/web/api/artifacts-tidy.test.ts b/src/web/api/artifacts-tidy.test.ts
new file mode 100644
index 00000000..4946e480
--- /dev/null
+++ b/src/web/api/artifacts-tidy.test.ts
@@ -0,0 +1,54 @@
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { describe, expect, it, vi } from 'vitest';
+
+const home = 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-tidy-'));
+ process.env.MERCURY_HOME = path.join(dir, '.mercury');
+ process.env.HOME = dir;
+ return dir;
+});
+
+import artifacts, { setArtifactOutputDir } from './artifacts.js';
+import { artifactStore } from '../../artifacts/store.js';
+
+const local = { incoming: { socket: { remoteAddress: '127.0.0.1' } } };
+
+describe('tidying loose files into the output folder', () => {
+ it('lists only what Mercury made in the home folder, and moves each into its chat folder', async () => {
+ setArtifactOutputDir(() => undefined);
+ const loose = join(home, 'how-to-programming-research.md');
+ writeFileSync(loose, '# Report');
+ mkdirSync(join(home, 'Projects'), { recursive: true });
+ const nested = join(home, 'Projects', 'kept.md');
+ writeFileSync(nested, 'x');
+ writeFileSync(join(home, 'factorial.ts'), 'not Mercury’s'); // not an artifact: never touched
+ const a = artifactStore().add({ threadId: 't1', path: loose, kind: 'text' });
+ artifactStore().add({ threadId: 't2', path: nested, kind: 'text' });
+
+ const info = (await (await artifacts.request('http://127.0.0.1/api/artifacts/folder')).json()) as { path: string; strays: Array<{ id: string; name: string }> };
+ expect(info.path).toBe(join(home, 'mercury-artifacts'));
+ expect(info.strays.map((s) => s.name)).toEqual(['how-to-programming-research.md']);
+
+ const remote = await artifacts.request('http://127.0.0.1/api/artifacts/folder/tidy', { method: 'POST' }, { incoming: { socket: { remoteAddress: '10.0.0.9' } } });
+ expect(remote.status).toBe(403);
+
+ const res = (await (await artifacts.request('http://127.0.0.1/api/artifacts/folder/tidy', { method: 'POST' }, local)).json()) as { moved: Array<{ to: string }>; failed: unknown[] };
+ expect(res.failed).toEqual([]);
+ expect(res.moved).toHaveLength(1);
+ const to = res.moved[0].to;
+ expect(to.startsWith(join(home, 'mercury-artifacts', 'Chats'))).toBe(true);
+ expect(to.endsWith('how-to-programming-research.md')).toBe(true);
+ expect(readFileSync(to, 'utf-8')).toBe('# Report');
+ expect(existsSync(loose)).toBe(false);
+ expect(existsSync(join(home, 'factorial.ts'))).toBe(true);
+ expect(existsSync(nested)).toBe(true);
+ // Show in Finder still finds it.
+ expect(artifactStore().get(a.id)?.originalPath).toBe(to);
+ const again = (await (await artifacts.request('http://127.0.0.1/api/artifacts/folder')).json()) as { strays: unknown[] };
+ expect(again.strays).toEqual([]);
+ });
+});
diff --git a/src/web/api/artifacts.ts b/src/web/api/artifacts.ts
index c0345b7f..75b7ea67 100644
--- a/src/web/api/artifacts.ts
+++ b/src/web/api/artifacts.ts
@@ -1,5 +1,7 @@
-import { copyFileSync, createReadStream, existsSync, statSync, writeFileSync } from 'node:fs';
-import { dirname, isAbsolute } from 'node:path';
+import { copyFileSync, createReadStream, existsSync, mkdirSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { dirname, isAbsolute, join, resolve } from 'node:path';
+import { chatFoldersFor, freeName, outputRoot } from '../../artifacts/output-dir.js';
import { Readable } from 'node:stream';
import { Hono } from 'hono';
import { artifactStore, type Artifact } from '../../artifacts/store.js';
@@ -20,11 +22,28 @@ const asFormat = (v: unknown): ConvertFormat | null => (v === 'pdf' || v === 'do
* GET /api/artifacts/:id/file?as=pdf|docx a Markdown/text artifact as a PDF or Word document
* POST /api/artifacts/:id/export { dest, as? } Save as… (this computer only), converted when `as` is given
* DELETE /api/artifacts/:id forget one (Mercury's copy only)
+ * GET /api/artifacts/folder the output folder (~/mercury-artifacts) and files Mercury left loose in the home folder
+ * POST /api/artifacts/folder/tidy move those loose files into their chats' folders (this computer only)
*/
let sessions: SessionRepository | null = null;
export function setArtifactSessions(repo: SessionRepository | null): void { sessions = repo; }
+/** The configured output folder (artifacts.outputDir), read when asked so a config change applies. */
+let outputSetting: () => string | undefined = () => undefined;
+export function setArtifactOutputDir(fn: () => string | undefined): void { outputSetting = fn; }
+
+/** Files Mercury made that sit loose in the home folder (from before the output folder existed). */
+function strays(): Artifact[] {
+ const home = resolve(homedir());
+ const seen = new Set<string>();
+ return artifactStore().all().filter((a) => {
+ if (seen.has(a.originalPath)) return false;
+ seen.add(a.originalPath);
+ return resolve(dirname(a.originalPath)) === home && existsSync(a.originalPath);
+ });
+}
+
const KINDS: Array<ArtifactKind | 'all'> = ['all', 'image', 'video', 'audio', 'pdf', 'document', 'text', 'file'];
function withThread(a: Artifact) {
@@ -52,6 +71,35 @@ artifacts.get('/api/artifacts', (c) => {
return c.json({ items: r.items.map(withThread), nextCursor: r.nextCursor, counts: r.counts });
});
+artifacts.get('/api/artifacts/folder', (c) => {
+ const root = outputRoot(outputSetting());
+ const home = resolve(homedir());
+ const display = root === home ? '~' : root.startsWith(`${home}/`) ? `~${root.slice(home.length)}` : root;
+ return c.json({ path: root, display, exists: existsSync(root), strays: strays().map((a) => ({ id: a.id, name: a.name, path: a.originalPath, threadId: a.threadId, threadTitle: withThread(a).threadTitle })) });
+});
+
+artifacts.post('/api/artifacts/folder/tidy', (c) => {
+ if (!isLoopbackRequest(c)) return c.json({ error: 'Tidying files only works on the computer Mercury runs on.' }, 403);
+ const folders = chatFoldersFor(outputRoot(outputSetting()));
+ const moved: Array<{ name: string; to: string }> = [];
+ const failed: Array<{ name: string; error: string }> = [];
+ for (const a of strays()) {
+ try {
+ const thread = withThread(a);
+ const dir = folders.pathFor(a.threadId, thread.threadTitle || a.name.replace(/\.[^.]+$/, ''), a.createdAt);
+ mkdirSync(dir, { recursive: true });
+ const to = join(dir, freeName(dir, a.name));
+ try { renameSync(a.originalPath, to); } catch { copyFileSync(a.originalPath, to); unlinkSync(a.originalPath); }
+ // Every record of this file (the same file in two threads) follows it.
+ for (const same of artifactStore().all().filter((x) => x.originalPath === a.originalPath)) artifactStore().relocate(same.id, to);
+ moved.push({ name: a.name, to });
+ } catch (err) {
+ failed.push({ name: a.name, error: err instanceof Error ? err.message : String(err) });
+ }
+ }
+ return c.json({ moved, failed });
+});
+
artifacts.get('/api/artifacts/:id', (c) => {
const a = artifactStore().get(c.req.param('id'));
return a ? c.json({ artifact: withThread(a) }) : c.json({ error: 'Not found' }, 404);