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(desktop): Artifacts tab and artifacts under replies

Salman Qureshia2890745a9a7
diff --git a/apps/desktop/src-tauri/capabilities/default.json b/apps/desktop/src-tauri/capabilities/default.json
index 05f3c6ff..de64cd6e 100644
--- a/apps/desktop/src-tauri/capabilities/default.json
+++ b/apps/desktop/src-tauri/capabilities/default.json
@@ -21,6 +21,7 @@
"autostart:default",
"deep-link:default",
"opener:default",
+ "opener:allow-reveal-item-in-dir",
"os:default",
"os:allow-hostname",
"process:default",
diff --git a/apps/desktop/src/api/artifacts.ts b/apps/desktop/src/api/artifacts.ts
new file mode 100644
index 00000000..f43e3b18
--- /dev/null
+++ b/apps/desktop/src/api/artifacts.ts
@@ -0,0 +1,78 @@
+import { apiUrl, authHeaders, http } from "./client";
+
+/** What Mercury made, by conversation (GET /api/artifacts*). */
+export type ArtifactKind = "image" | "video" | "audio" | "pdf" | "document" | "text" | "file";
+
+/** What a chat message carries about its artifacts. */
+export interface ArtifactRef { id: string; name: string; kind: ArtifactKind; mime: string; size: number; path: string }
+
+export interface ArtifactItem {
+ id: string;
+ threadId: string;
+ threadTitle: string | null;
+ threadExists: boolean;
+ name: string;
+ kind: ArtifactKind;
+ mime: string;
+ size: number;
+ originalPath: string;
+ originalExists: boolean;
+ createdAt: number;
+ tool?: string;
+ surface?: "chat" | "code";
+}
+
+export interface ArtifactPage { items: ArtifactItem[]; nextCursor: string | null; counts: Record<string, number> }
+
+export const artifactsApi = {
+ list: (q: { kind?: string; q?: string; threadId?: string; cursor?: string | null; limit?: number } = {}) => {
+ const p = new URLSearchParams();
+ if (q.kind && q.kind !== "all") p.set("kind", q.kind);
+ if (q.q) p.set("q", q.q);
+ if (q.threadId) p.set("threadId", q.threadId);
+ if (q.cursor) p.set("cursor", q.cursor);
+ p.set("limit", String(q.limit ?? 40));
+ return http.get<ArtifactPage>(`/api/artifacts?${p}`);
+ },
+ 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. */
+ exportTo: (id: string, dest: string) => http.post<{ ok: boolean; path: string }>(`/api/artifacts/${encodeURIComponent(id)}/export`, { dest }),
+};
+
+/**
+ * The file, as a blob URL (an <img> or <video> can't send the auth header).
+ * Kept for the session, the oldest released past 40 so memory stays bounded.
+ */
+const cache = new Map<string, Promise<string | null>>();
+export function artifactBlobUrl(id: string): Promise<string | null> {
+ let hit = cache.get(id);
+ if (!hit) {
+ hit = fetch(apiUrl(`/api/artifacts/${encodeURIComponent(id)}/file`), { headers: authHeaders() })
+ .then(async (r) => (r.ok ? URL.createObjectURL(await r.blob()) : null))
+ .catch(() => null);
+ cache.set(id, hit);
+ if (cache.size > 40) {
+ const [oldest, url] = cache.entries().next().value as [string, Promise<string | null>];
+ cache.delete(oldest);
+ void url.then((u) => { if (u) URL.revokeObjectURL(u); });
+ }
+ }
+ return hit;
+}
+
+export async function artifactText(id: string, max = 400_000): Promise<string> {
+ const r = await fetch(apiUrl(`/api/artifacts/${encodeURIComponent(id)}/file`), { headers: authHeaders() });
+ if (!r.ok) throw new Error(`Couldn't load it (${r.status})`);
+ const t = await r.text();
+ return t.length > max ? `${t.slice(0, max)}\n\n… (cut off here; save the file to read the rest)` : t;
+}
+
+export function formatBytes(n: number): string {
+ if (n < 1024) return `${n} B`;
+ if (n < 1024 ** 2) return `${Math.round(n / 1024)} KB`;
+ if (n < 1024 ** 3) return `${(n / 1024 ** 2).toFixed(1)} MB`;
+ return `${(n / 1024 ** 3).toFixed(2)} GB`;
+}
+
+export const KIND_LABEL: Record<ArtifactKind, string> = { image: "Image", video: "Video", audio: "Audio", pdf: "PDF", document: "Document", text: "Notes", file: "File" };
diff --git a/apps/desktop/src/api/types.ts b/apps/desktop/src/api/types.ts
index 4817a557..6e29ed5d 100644
--- a/apps/desktop/src/api/types.ts
+++ b/apps/desktop/src/api/types.ts
@@ -57,6 +57,8 @@ export interface ChatMessage {
trace?: ThoughtTrace;
/** You stopped this turn; content is whatever was written before that. */
stopped?: boolean;
+ /** Files this turn made that are worth keeping (images, PDFs, reports…). */
+ artifacts?: import("./artifacts").ArtifactRef[];
}
export interface ThoughtStep {
diff --git a/apps/desktop/src/app/events.ts b/apps/desktop/src/app/events.ts
index 10c687cb..83e43879 100644
--- a/apps/desktop/src/app/events.ts
+++ b/apps/desktop/src/app/events.ts
@@ -12,6 +12,7 @@ import { 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";
+import type { ArtifactRef } from "~/api/artifacts";
export function useRuntimeEvents(enabled: boolean): void {
const chatId = conversations.chat((s) => s.activeId);
@@ -78,7 +79,10 @@ function safeJson<T>(raw: string): T | null {
}
}
-function handleEvent(store: ConversationStore, event: string, raw: string): void {
+/** Artifacts that arrived before their reply did: attached when it lands. */
+const pendingArtifacts = new WeakMap<ConversationStore, ArtifactRef[]>();
+
+export function handleEvent(store: ConversationStore, event: string, raw: string): void {
const conv = store.getState();
const data = safeJson<Record<string, unknown>>(raw) ?? {};
// A scoped stream may still carry another session's events on old runtimes.
@@ -98,6 +102,18 @@ function handleEvent(store: ConversationStore, event: string, raw: string): void
if (steps.length) conv.setPlan({ steps, updatedAt: Number(data.updatedAt) || Date.now() });
break;
}
+ case "artifacts": {
+ const items = Array.isArray(data.items) ? (data.items as ArtifactRef[]) : [];
+ if (!items.length) break;
+ const last = conv.messages[conv.messages.length - 1];
+ const turnOver = conv.agent === "idle" || conv.agent === "needs-you";
+ if (turnOver && last?.role === "assistant") {
+ conv.setMessages([...conv.messages.slice(0, -1), { ...last, artifacts: [...(last.artifacts ?? []), ...items] }]);
+ } else {
+ pendingArtifacts.set(store, [...(pendingArtifacts.get(store) ?? []), ...items]);
+ }
+ break;
+ }
case "reasoning":
if (data.done === true) break;
if (typeof data.text === "string" && data.text) conv.setLive((l) => ({ ...l, reasoning: (l.reasoning + data.text).slice(-20_000) }));
@@ -135,7 +151,9 @@ function handleEvent(store: ConversationStore, event: string, raw: string): void
const trace = live && (live.reasoning || live.steps.length) ? { ...live, endedAt: Date.now(), steps: live.steps.map((st) => st.status === "running" ? { ...st, status: "done" as const, endedAt: Date.now() } : st) } : undefined;
conv.clearStreaming();
conv.clearLive();
- conv.addMessage({ id: crypto.randomUUID(), role: "assistant", content: text, timestamp: new Date().toISOString(), ...(trace ? { trace } : {}) });
+ const artifacts = pendingArtifacts.get(store);
+ pendingArtifacts.delete(store);
+ conv.addMessage({ id: crypto.randomUUID(), role: "assistant", content: text, timestamp: new Date().toISOString(), ...(trace ? { trace } : {}), ...(artifacts?.length ? { artifacts } : {}) });
conv.setStep(null);
store.getState().setAgent(store.getState().prompts.length ? "needs-you" : "idle");
void refreshThreads();
diff --git a/apps/desktop/src/app/store.ts b/apps/desktop/src/app/store.ts
index 744fe118..de91bcc1 100644
--- a/apps/desktop/src/app/store.ts
+++ b/apps/desktop/src/app/store.ts
@@ -7,7 +7,7 @@
import { create } from "zustand";
import type { BotStatus, ChatThread, PendingPrompt } from "~/api/types";
-export type View = "chat" | "code" | "bots" | "brain" | "plugins" | "skills" | "settings";
+export type View = "chat" | "artifacts" | "code" | "bots" | "brain" | "plugins" | "skills" | "settings";
/** What the agent is doing right now; drives the StateOrb everywhere. */
export type AgentState = "idle" | "thinking" | "streaming" | "working" | "needs-you" | "offline";
diff --git a/apps/desktop/src/components/artifacts/ArtifactCard.tsx b/apps/desktop/src/components/artifacts/ArtifactCard.tsx
new file mode 100644
index 00000000..4337fc0b
--- /dev/null
+++ b/apps/desktop/src/components/artifacts/ArtifactCard.tsx
@@ -0,0 +1,70 @@
+import { File, FileImage, FileText, FileVideo, Music, Presentation, Sheet, Play } from "lucide-react";
+import { useEffect, useState } from "react";
+import { artifactBlobUrl, formatBytes, KIND_LABEL, type ArtifactKind, type ArtifactRef } from "~/api/artifacts";
+import { Dialog } from "~/components/ui/Dialog";
+import { cx } from "~/lib/cx";
+import { ArtifactViewer } from "./ArtifactViewer";
+
+/**
+ * Artifacts as cards: a real thumbnail for images, an icon for the rest
+ * (videos aren't downloaded just to draw a tile). The strip under a reply
+ * opens each one in the previewer.
+ */
+
+const TONE: Record<ArtifactKind, string> = {
+ image: "bg-cyan/15 text-cyan", video: "bg-accent/15 text-accent", audio: "bg-amber/15 text-amber", pdf: "bg-red/12 text-red",
+ document: "bg-ink/[0.07] text-ink2", text: "bg-ink/[0.07] text-ink2", file: "bg-ink/[0.07] text-ink3",
+};
+
+export function ArtifactIcon({ kind, name, size = 32 }: { kind: ArtifactKind; name: string; size?: number }) {
+ const ext = name.split(".").pop()?.toLowerCase() ?? "";
+ const Icon = kind === "image" ? FileImage : kind === "video" ? FileVideo : kind === "audio" ? Music : kind === "pdf" ? FileText
+ : kind === "document" ? (/^(xlsx?|ods|numbers|csv)$/.test(ext) ? Sheet : /^(pptx?|odp|key)$/.test(ext) ? Presentation : FileText)
+ : kind === "text" ? FileText : File;
+ return (
+ <span className={cx("flex shrink-0 items-center justify-center rounded-lg", TONE[kind])} style={{ width: size, height: size }} aria-hidden="true">
+ <Icon size={Math.round(size * 0.5)} />
+ </span>
+ );
+}
+
+export function ArtifactThumb({ id, kind, name, className }: { id: string; kind: ArtifactKind; name: string; className?: string }) {
+ const [url, setUrl] = useState<string | null>(null);
+ useEffect(() => {
+ if (kind !== "image") return;
+ let live = true;
+ void artifactBlobUrl(id).then((u) => { if (live) setUrl(u); });
+ return () => { live = false; };
+ }, [id, kind]);
+ if (kind === "image" && url) return <img src={url} alt={name} className={cx("h-full w-full object-cover", className)} loading="lazy" draggable={false} />;
+ return (
+ <span className={cx("relative flex h-full w-full items-center justify-center bg-soft", className)}>
+ <ArtifactIcon kind={kind} name={name} size={40} />
+ {kind === "video" && <Play size={14} className="absolute bottom-2 right-2 fill-current text-ink3" />}
+ <span className="absolute left-2 top-2 rounded bg-surface/90 px-1.5 font-mono text-2xs uppercase text-ink3">{name.split(".").pop()}</span>
+ </span>
+ );
+}
+
+/** Under a reply: what this turn made, one tap from a preview. */
+export function ArtifactStrip({ items, onOpenThread }: { items: ArtifactRef[]; onOpenThread?: (threadId: string) => void }) {
+ const [open, setOpen] = useState<string | null>(null);
+ if (!items.length) return null;
+ return (
+ <div className="mt-3 flex flex-wrap gap-2" aria-label="Artifacts">
+ {items.map((a) => (
+ <button key={a.id} onClick={() => setOpen(a.id)} title={a.path}
+ className="group flex w-[220px] items-center gap-2.5 overflow-hidden rounded-xl border border-line bg-surface p-1.5 pr-3 text-left transition-colors hover:border-ink/25">
+ <span className="h-12 w-12 shrink-0 overflow-hidden rounded-lg"><ArtifactThumb id={a.id} kind={a.kind} name={a.name} /></span>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-sm text-ink">{a.name}</span>
+ <span className="block text-xs text-ink4">{KIND_LABEL[a.kind]} · {formatBytes(a.size)}</span>
+ </span>
+ </button>
+ ))}
+ <Dialog open={!!open} onOpenChange={(o) => { if (!o) setOpen(null); }} title="Artifact" width={860}>
+ {open && <div className="-m-5 h-[70vh]"><ArtifactViewer id={open} onOpenThread={onOpenThread ? (t) => { setOpen(null); onOpenThread(t); } : undefined} onDeleted={() => setOpen(null)} /></div>}
+ </Dialog>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/components/artifacts/ArtifactViewer.tsx b/apps/desktop/src/components/artifacts/ArtifactViewer.tsx
new file mode 100644
index 00000000..82768f83
--- /dev/null
+++ b/apps/desktop/src/components/artifacts/ArtifactViewer.tsx
@@ -0,0 +1,184 @@
+import { Copy, Download, FileText, FolderOpen, MessageSquareText, Trash2 } from "lucide-react";
+import { useEffect, useState } from "react";
+import { artifactBlobUrl, artifactText, artifactsApi, formatBytes, KIND_LABEL, type ArtifactItem, type ArtifactKind } from "~/api/artifacts";
+import { Markdown } from "~/components/Markdown";
+import { Button } from "~/components/ui/Button";
+import { Badge, Spinner } from "~/components/ui/bits";
+import { ConfirmButton } from "~/components/ui/kit";
+import { useConnections } from "~/shell/connections";
+import { isTauri } from "~/shell/tauri";
+import { cx } from "~/lib/cx";
+import { ArtifactIcon } from "./ArtifactCard";
+
+/**
+ * One artifact, previewed for its kind: an image, a video or audio player,
+ * the PDF itself, rendered Markdown, text, a CSV table. Office files can't
+ * be previewed here, so they offer saving and opening instead. Actions:
+ * save a copy, show it in Finder, copy its path, open the conversation it
+ * came from, delete Mercury's copy.
+ */
+
+function errorText(e: unknown): string {
+ return e instanceof Error ? e.message : String(e);
+}
+
+export function ArtifactViewer({ id, onOpenThread, onDeleted }: { id: string; onOpenThread?: (threadId: string) => void; onDeleted?: () => void }) {
+ const [a, setA] = useState<ArtifactItem | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [note, setNote] = useState<{ text: string; ok: boolean } | null>(null);
+ const local = useConnections((s) => s.connections.find((c) => c.id === s.activeId)?.kind === "local");
+
+ useEffect(() => {
+ let live = true;
+ setA(null);
+ setError(null);
+ artifactsApi.get(id).then((x) => { if (live) setA(x); }).catch((e) => { if (live) setError(errorText(e)); });
+ return () => { live = false; };
+ }, [id]);
+
+ async function saveAs() {
+ if (!a) return;
+ setNote(null);
+ try {
+ if (isTauri && local) {
+ const { save } = await import("@tauri-apps/plugin-dialog");
+ const dest = await save({ defaultPath: a.name, title: `Save ${a.name}` });
+ if (!dest) return;
+ await artifactsApi.exportTo(a.id, dest);
+ setNote({ text: `Saved to ${dest}`, ok: true });
+ } else {
+ const url = await artifactBlobUrl(a.id);
+ if (!url) throw new Error("Couldn't load the file.");
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = a.name;
+ link.click();
+ }
+ } catch (e) { setNote({ text: errorText(e), ok: false }); }
+ }
+
+ async function reveal() {
+ if (!a) return;
+ try {
+ const { revealItemInDir } = await import("@tauri-apps/plugin-opener");
+ await revealItemInDir(a.originalPath);
+ } catch (e) { setNote({ text: errorText(e), ok: false }); }
+ }
+
+ if (error) return <p className="p-6 text-sm text-red">{error}</p>;
+ if (!a) return <div className="p-6"><Spinner size={16} /></div>;
+
+ return (
+ <div className="flex h-full min-h-0 flex-col">
+ <div className="flex items-start gap-3 border-b border-line px-5 py-4">
+ <ArtifactIcon kind={a.kind} name={a.name} size={36} />
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-2"><span className="truncate text-base font-medium text-ink" data-selectable>{a.name}</span><Badge>{KIND_LABEL[a.kind]}</Badge></div>
+ <div className="mt-0.5 truncate font-mono text-xs text-ink3" title={a.originalPath} data-selectable>{a.originalPath}</div>
+ <div className="text-xs text-ink4">{formatBytes(a.size)} · {new Date(a.createdAt).toLocaleString()}{a.threadTitle ? ` · from “${a.threadTitle}”` : ""}{!a.originalExists ? " · original moved or deleted (Mercury's copy is kept)" : ""}</div>
+ </div>
+ </div>
+
+ <div className="flex flex-wrap items-center gap-1.5 border-b border-line px-5 py-2">
+ <Button size="sm" variant="primary" onClick={() => void saveAs()}><Download size={13} /> {isTauri && local ? "Save as…" : "Download"}</Button>
+ {isTauri && local && a.originalExists && <Button size="sm" variant="ghost" onClick={() => void reveal()}><FolderOpen size={13} /> Show in Finder</Button>}
+ <Button size="sm" variant="ghost" onClick={() => { void navigator.clipboard.writeText(a.originalPath); setNote({ text: "Path copied.", ok: true }); }}><Copy size={13} /> Copy path</Button>
+ {onOpenThread && a.threadExists && <Button size="sm" variant="ghost" onClick={() => onOpenThread(a.threadId)}><MessageSquareText size={13} /> Open conversation</Button>}
+ <span className="flex-1" />
+ <ConfirmButton size="sm" variant="ghost" confirmLabel="Delete Mercury's copy?" onConfirm={() => void artifactsApi.remove(a.id).then(() => onDeleted?.()).catch((e) => setNote({ text: errorText(e), ok: false }))}><Trash2 size={13} /></ConfirmButton>
+ </div>
+ {note && <p className={cx("px-5 pt-2 text-xs", note.ok ? "text-accent" : "text-red")}>{note.text}</p>}
+
+ <div className="min-h-0 flex-1 overflow-auto p-5">
+ <Preview a={a} />
+ </div>
+ </div>
+ );
+}
+
+function useBlob(id: string): { url: string | null; failed: boolean } {
+ const [url, setUrl] = useState<string | null>(null);
+ const [failed, setFailed] = useState(false);
+ useEffect(() => {
+ let live = true;
+ setUrl(null);
+ setFailed(false);
+ artifactBlobUrl(id).then((u) => { if (!live) return; if (u) setUrl(u); else setFailed(true); });
+ return () => { live = false; };
+ }, [id]);
+ return { url, failed };
+}
+
+function Preview({ a }: { a: ArtifactItem }) {
+ const textual = a.kind === "text" || (a.kind === "document" && a.mime === "text/csv") || (a.kind === "file" && a.mime.startsWith("text/"));
+ if (textual) return <TextPreview a={a} />;
+ if (a.kind === "image" || a.kind === "video" || a.kind === "audio" || a.kind === "pdf") return <MediaPreview a={a} />;
+ return <NoPreview kind={a.kind} />;
+}
+
+function MediaPreview({ a }: { a: ArtifactItem }) {
+ const { url, failed } = useBlob(a.id);
+ if (failed) return <p className="text-sm text-red">Couldn't load the file.</p>;
+ if (!url) return <div className="flex items-center gap-2 text-sm text-ink3"><Spinner size={13} /> Loading {a.size > 20 * 1024 ** 2 ? `(${formatBytes(a.size)})` : ""}…</div>;
+ if (a.kind === "image") return <img src={url} alt={a.name} className="mx-auto max-h-full max-w-full rounded-lg object-contain" />;
+ if (a.kind === "video") return <video src={url} controls className="mx-auto max-h-full max-w-full rounded-lg bg-black" />;
+ if (a.kind === "audio") return <audio src={url} controls className="w-full" />;
+ return <iframe src={url} title={a.name} className="h-full min-h-[480px] w-full rounded-lg border border-line bg-white" />;
+}
+
+function TextPreview({ a }: { a: ArtifactItem }) {
+ const [text, setText] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ useEffect(() => { let live = true; artifactText(a.id).then((t) => { if (live) setText(t); }).catch((e) => { if (live) setError(errorText(e)); }); return () => { live = false; }; }, [a.id]);
+ if (error) return <p className="text-sm text-red">{error}</p>;
+ if (text === null) return <Spinner size={13} />;
+ if (a.mime === "text/markdown") return <div className="mx-auto max-w-[760px]" data-selectable><Markdown text={text} /></div>;
+ if (a.mime === "text/csv") return <CsvTable text={text} />;
+ return <pre className="whitespace-pre-wrap break-words font-mono text-[12.5px] leading-relaxed text-ink" data-selectable>{text}</pre>;
+}
+
+/** The first 200 rows of a CSV as a table (quotes handled, enough for a preview). */
+export function parseCsv(text: string, maxRows = 200): string[][] {
+ const rows: string[][] = [];
+ let row: string[] = [];
+ let cell = "";
+ let quoted = false;
+ for (let i = 0; i < text.length && rows.length < maxRows; i++) {
+ const ch = text[i];
+ if (quoted) {
+ if (ch === '"' && text[i + 1] === '"') { cell += '"'; i++; }
+ else if (ch === '"') quoted = false;
+ else cell += ch;
+ } else if (ch === '"') quoted = true;
+ else if (ch === ",") { row.push(cell); cell = ""; }
+ else if (ch === "\n" || ch === "\r") {
+ if (ch === "\r" && text[i + 1] === "\n") i++;
+ row.push(cell); rows.push(row); row = []; cell = "";
+ } else cell += ch;
+ }
+ if ((cell || row.length) && rows.length < maxRows) { row.push(cell); rows.push(row); }
+ return rows;
+}
+
+function CsvTable({ text }: { text: string }) {
+ const rows = parseCsv(text);
+ if (!rows.length) return <p className="text-sm text-ink3">Empty.</p>;
+ const [head, ...body] = rows;
+ return (
+ <div className="overflow-auto rounded-lg border border-line">
+ <table className="min-w-full text-left text-xs">
+ <thead className="bg-soft"><tr>{head.map((h, i) => <th key={i} className="whitespace-nowrap border-b border-line px-2.5 py-1.5 font-medium text-ink">{h}</th>)}</tr></thead>
+ <tbody>{body.map((r, i) => <tr key={i} className="border-b border-line last:border-0">{r.map((c, j) => <td key={j} className="whitespace-nowrap px-2.5 py-1 text-ink2">{c}</td>)}</tr>)}</tbody>
+ </table>
+ </div>
+ );
+}
+
+function NoPreview({ kind }: { kind: ArtifactKind }) {
+ return (
+ <div className="flex flex-col items-center gap-2 py-12 text-center">
+ <FileText size={28} className="text-ink4" />
+ <p className="text-sm text-ink3">{kind === "document" ? "Office files can't be previewed here." : "No preview for this kind of file."} Save it or show it in Finder to open it.</p>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/components/artifacts/artifacts.test.ts b/apps/desktop/src/components/artifacts/artifacts.test.ts
new file mode 100644
index 00000000..29b4e419
--- /dev/null
+++ b/apps/desktop/src/components/artifacts/artifacts.test.ts
@@ -0,0 +1,47 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("~/api/mercury", () => ({ chat: { stop: async () => ({ ok: true }) } }));
+
+const { conversations } = await import("~/app/conversation");
+const { handleEvent } = await import("~/app/events");
+const { parseCsv } = await import("./ArtifactViewer");
+
+const store = conversations.chat;
+const ref = (id: string) => ({ id, name: `${id}.png`, kind: "image" as const, mime: "image/png", size: 10, path: `/tmp/${id}.png` });
+
+describe("artifacts in chat", () => {
+ beforeEach(() => {
+ store.setState({ messages: [], streaming: "", live: null, agent: "idle", stopping: false, prompts: [], step: null, activeId: null });
+ });
+
+ it("holds artifacts that arrive mid-turn and attaches them to the reply", () => {
+ store.setState({ agent: "working", messages: [{ id: "u", role: "user", content: "draw", timestamp: "" }] });
+ handleEvent(store, "artifacts", JSON.stringify({ items: [ref("a")] }));
+ expect(store.getState().messages).toHaveLength(1);
+ handleEvent(store, "text_done", JSON.stringify({ fullText: "Here it is." }));
+ const last = store.getState().messages.at(-1)!;
+ expect(last.role).toBe("assistant");
+ expect(last.artifacts?.map((a) => a.id)).toEqual(["a"]);
+ });
+
+ it("attaches artifacts that arrive after the reply to that reply", () => {
+ store.setState({ agent: "idle", messages: [{ id: "u", role: "user", content: "draw", timestamp: "" }, { id: "r", role: "assistant", content: "Done.", timestamp: "" }] });
+ handleEvent(store, "artifacts", JSON.stringify({ items: [ref("b")] }));
+ expect(store.getState().messages.at(-1)!.artifacts?.map((a) => a.id)).toEqual(["b"]);
+ });
+
+ it("doesn't leak held artifacts into the next turn", () => {
+ store.setState({ agent: "working" });
+ handleEvent(store, "text_done", JSON.stringify({ fullText: "No files." }));
+ expect(store.getState().messages.at(-1)!.artifacts).toBeUndefined();
+ });
+});
+
+describe("parseCsv", () => {
+ it("handles quotes, escaped quotes, commas and CRLF", () => {
+ expect(parseCsv('name,note\r\n"Smith, J","said ""hi"""\nx,y')).toEqual([["name", "note"], ["Smith, J", 'said "hi"'], ["x", "y"]]);
+ });
+ it("caps rows for the preview", () => {
+ expect(parseCsv("a\nb\nc\nd", 2)).toHaveLength(2);
+ });
+});
diff --git a/apps/desktop/src/layout/Rail.tsx b/apps/desktop/src/layout/Rail.tsx
index 067682ac..a9ee743d 100644
--- a/apps/desktop/src/layout/Rail.tsx
+++ b/apps/desktop/src/layout/Rail.tsx
@@ -1,4 +1,4 @@
-import { Bot, Brain, Code2, MessageSquare, Puzzle, Settings, Sparkles } from "lucide-react";
+import { Bot, Brain, Code2, MessageSquare, Puzzle, Settings, Sparkles, Layers } from "lucide-react";
import { useEffect } from "react";
import { cx } from "~/lib/cx";
import { useRuntimeState, useUi, type View } from "~/app/store";
@@ -8,6 +8,7 @@ import { Tooltip } from "~/components/ui/Tooltip";
const ITEMS: Array<{ view: View; label: string; icon: typeof MessageSquare; key: string }> = [
{ view: "chat", label: "Chat", icon: MessageSquare, key: "1" },
+ { view: "artifacts", label: "Artifacts", icon: Layers, key: "7" },
{ view: "code", label: "Code", icon: Code2, key: "2" },
{ view: "bots", label: "Bots", icon: Bot, key: "3" },
{ view: "brain", label: "Brain", icon: Brain, key: "4" },
diff --git a/apps/desktop/src/layout/Workspace.tsx b/apps/desktop/src/layout/Workspace.tsx
index 31cb37b2..616b28c2 100644
--- a/apps/desktop/src/layout/Workspace.tsx
+++ b/apps/desktop/src/layout/Workspace.tsx
@@ -17,6 +17,7 @@ import { PluginsView } from "~/views/plugins/PluginsView";
import { SkillsView } from "~/views/skills/SkillsView";
import { SettingsView } from "~/views/settings/SettingsView";
import { BrainView } from "~/views/brain/BrainView";
+import { ArtifactsView } from "~/views/artifacts/ArtifactsView";
import { ErrorBoundary } from "~/components/ErrorBoundary";
import { CloudBanner } from "~/views/settings/Cloud";
import { CallLayer } from "~/views/call/Call";
@@ -51,6 +52,7 @@ export function Workspace({ connection, health, onSwitchConnection }: { connecti
<main className="relative flex min-w-0 flex-1 flex-col">
{/* Each view behind its own crash boundary: one broken view never blanks the window. */}
<Pane active={view === "chat"}><ErrorBoundary label="Chat"><ChatView /></ErrorBoundary></Pane>
+ <Pane active={view === "artifacts"}><ErrorBoundary label="Artifacts"><ArtifactsView /></ErrorBoundary></Pane>
<Pane active={view === "code"}><ErrorBoundary label="Mercury Code"><CodeView /></ErrorBoundary></Pane>
<Pane active={view === "bots"}><ErrorBoundary label="Bots"><BotsView /></ErrorBoundary></Pane>
<Pane active={view === "brain"}><ErrorBoundary label="Brain"><BrainView /></ErrorBoundary></Pane>
diff --git a/apps/desktop/src/views/artifacts/ArtifactsView.tsx b/apps/desktop/src/views/artifacts/ArtifactsView.tsx
new file mode 100644
index 00000000..5c195c8c
--- /dev/null
+++ b/apps/desktop/src/views/artifacts/ArtifactsView.tsx
@@ -0,0 +1,168 @@
+import { Layers, MessageSquareText, RefreshCw, X } from "lucide-react";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { artifactsApi, formatBytes, type ArtifactItem, type ArtifactKind } from "~/api/artifacts";
+import { openThread } from "~/app/events";
+import { useCodeSessions } from "~/app/conversation";
+import { useUi } from "~/app/store";
+import { ArtifactThumb } from "~/components/artifacts/ArtifactCard";
+import { ArtifactViewer } from "~/components/artifacts/ArtifactViewer";
+import { Button } from "~/components/ui/Button";
+import { Spinner } from "~/components/ui/bits";
+import { SearchField } from "~/components/ui/kit";
+import { cx } from "~/lib/cx";
+
+/**
+ * Artifacts: everything Mercury made (images, videos, audio, PDFs,
+ * documents, notes), newest first. Search, a tab per kind, a page at a time
+ * as you scroll. Each card says which conversation made it; open the
+ * conversation, or narrow to it. Deleting a conversation deletes its
+ * artifacts (Mercury's copies; your files stay).
+ */
+
+type Tab = "all" | ArtifactKind;
+const TABS: Array<{ id: Tab; label: string }> = [
+ { id: "all", label: "All" }, { id: "image", label: "Images" }, { id: "video", label: "Videos" }, { id: "audio", label: "Audio" },
+ { id: "pdf", label: "PDFs" }, { id: "document", label: "Documents" }, { id: "text", label: "Notes" }, { id: "file", label: "Files" },
+];
+
+function errorText(e: unknown): string {
+ return e instanceof Error ? e.message : String(e);
+}
+
+function when(ms: number): string {
+ const d = new Date(ms);
+ const today = new Date();
+ return d.toDateString() === today.toDateString() ? d.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" }) : d.toLocaleDateString([], { month: "short", day: "numeric", year: d.getFullYear() === today.getFullYear() ? undefined : "numeric" });
+}
+
+export function ArtifactsView() {
+ const view = useUi((s) => s.view);
+ const setView = useUi((s) => s.setView);
+ const codeSessions = useCodeSessions((s) => s.sessions);
+ const [tab, setTab] = useState<Tab>("all");
+ const [query, setQuery] = useState("");
+ const [thread, setThread] = useState<{ id: string; title: string } | null>(null);
+ const [items, setItems] = useState<ArtifactItem[]>([]);
+ const [counts, setCounts] = useState<Record<string, number>>({});
+ const [cursor, setCursor] = useState<string | null>(null);
+ const [loading, setLoading] = useState(false);
+ const [loaded, setLoaded] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [selected, setSelected] = useState<string | null>(null);
+ const sentinel = useRef<HTMLDivElement>(null);
+ const reqId = useRef(0);
+ const visible = view === "artifacts";
+
+ const load = useCallback(async (more: boolean) => {
+ const my = ++reqId.current;
+ setLoading(true);
+ setError(null);
+ try {
+ const page = await artifactsApi.list({ kind: tab, q: query.trim() || undefined, threadId: thread?.id, cursor: more ? cursor : null, limit: 40 });
+ if (my !== reqId.current) return;
+ setItems((cur) => (more ? [...cur, ...page.items.filter((x) => !cur.some((c) => c.id === x.id))] : page.items));
+ setCursor(page.nextCursor);
+ setCounts(page.counts);
+ setLoaded(true);
+ } catch (e) {
+ if (my === reqId.current) setError(errorText(e));
+ } finally {
+ if (my === reqId.current) setLoading(false);
+ }
+ }, [tab, query, thread, cursor]);
+
+ // New filters: start over (search waits for a pause in typing).
+ useEffect(() => {
+ if (!visible) return;
+ const t = setTimeout(() => void load(false), query ? 250 : 0);
+ return () => clearTimeout(t);
+ }, [visible, tab, query, thread]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ // A page at a time as you reach the bottom.
+ useEffect(() => {
+ const el = sentinel.current;
+ if (!el) return;
+ const io = new IntersectionObserver((entries) => { if (entries[0]?.isIntersecting && cursor && !loading) void load(true); }, { rootMargin: "400px" });
+ io.observe(el);
+ return () => io.disconnect();
+ }, [cursor, loading, load]);
+
+ const openConversation = (threadId: string) => {
+ const code = codeSessions.some((s) => s.id === threadId);
+ setView(code ? "code" : "chat");
+ void openThread(code ? "code" : "chat", threadId);
+ };
+
+ return (
+ <div className="flex h-full min-h-0">
+ <div className="flex min-w-0 flex-1 flex-col">
+ <div className="flex h-[52px] shrink-0 items-center gap-3 border-b border-line px-5" data-tauri-drag-region>
+ <span className="text-base font-semibold text-ink" data-tauri-drag-region>Artifacts</span>
+ <span className="text-xs text-ink4" data-tauri-drag-region>{counts.all ?? 0} made by Mercury</span>
+ <span className="flex-1" data-tauri-drag-region />
+ <SearchField value={query} onChange={setQuery} placeholder="Search by name or path" className="w-[260px]" />
+ <Button variant="ghost" size="sm" icon onClick={() => void load(false)} loading={loading && loaded} aria-label="Refresh"><RefreshCw size={14} /></Button>
+ </div>
+ <div className="flex shrink-0 flex-wrap items-center gap-1 border-b border-line px-4 py-2">
+ {TABS.filter((t) => t.id === "all" || (counts[t.id] ?? 0) > 0 || tab === t.id).map((t) => (
+ <button key={t.id} onClick={() => setTab(t.id)} aria-pressed={tab === t.id}
+ className={cx("flex h-7 items-center gap-1.5 rounded-md px-2.5 text-sm", tab === t.id ? "bg-ink/[0.08] text-ink" : "text-ink3 hover:bg-ink/[0.04] hover:text-ink")}>
+ {t.label}<span className="font-mono text-2xs text-ink4">{t.id === "all" ? counts.all ?? 0 : counts[t.id] ?? 0}</span>
+ </button>
+ ))}
+ {thread && (
+ <span className="ml-2 flex items-center gap-1.5 rounded-full border border-line px-2.5 py-0.5 text-xs text-ink2">
+ <MessageSquareText size={11} /> {thread.title}
+ <button onClick={() => setThread(null)} className="text-ink4 hover:text-ink" aria-label="Show all conversations"><X size={11} /></button>
+ </span>
+ )}
+ </div>
+
+ <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>}
+ {loaded && items.length === 0 && (
+ <div className="flex flex-col items-center gap-2 py-20 text-center">
+ <Layers size={26} className="text-ink4" />
+ <p className="max-w-[420px] text-sm text-ink3">
+ {query || tab !== "all" || thread ? "Nothing matches." : "When Mercury makes something for you (an image, a video, a PDF, a report) it shows up here, with the conversation it came from."}
+ </p>
+ </div>
+ )}
+ <div className="grid grid-cols-[repeat(auto-fill,minmax(180px,1fr))] gap-3">
+ {items.map((a) => (
+ <div key={a.id} className={cx("group flex flex-col overflow-hidden rounded-xl border bg-surface text-left transition-colors", selected === a.id ? "border-accent/60" : "border-line hover:border-ink/25")}>
+ <button onClick={() => setSelected(a.id)} className="aspect-[4/3] w-full overflow-hidden" aria-label={`Open ${a.name}`}>
+ <ArtifactThumb id={a.id} kind={a.kind} name={a.name} />
+ </button>
+ <div className="flex flex-col gap-0.5 px-2.5 py-2">
+ <button onClick={() => setSelected(a.id)} className="truncate text-left text-sm text-ink" title={a.name}>{a.name}</button>
+ <span className="text-2xs text-ink4">{formatBytes(a.size)} · {when(a.createdAt)}</span>
+ {a.threadExists && a.threadTitle && (
+ <button onClick={() => setThread({ id: a.threadId, title: a.threadTitle! })} className="truncate text-left text-2xs text-ink3 hover:text-ink hover:underline" title="Only this conversation's artifacts">
+ {a.threadTitle}
+ </button>
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+ <div ref={sentinel} className="h-8" />
+ {loading && loaded && <div className="flex justify-center py-3"><Spinner size={14} /></div>}
+ </div>
+ </div>
+
+ {selected && (
+ <aside className="flex w-[46%] min-w-[380px] max-w-[720px] shrink-0 flex-col border-l border-line bg-soft">
+ <div className="flex h-[52px] items-center justify-end px-3" data-tauri-drag-region>
+ <Button size="sm" variant="ghost" icon onClick={() => setSelected(null)} aria-label="Close preview"><X size={15} /></Button>
+ </div>
+ <div className="min-h-0 flex-1">
+ <ArtifactViewer key={selected} id={selected} onOpenThread={openConversation}
+ onDeleted={() => { setItems((cur) => cur.filter((x) => x.id !== selected)); setSelected(null); void load(false); }} />
+ </div>
+ </aside>
+ )}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/views/chat/Message.tsx b/apps/desktop/src/views/chat/Message.tsx
index fcc73a1a..2434e5b4 100644
--- a/apps/desktop/src/views/chat/Message.tsx
+++ b/apps/desktop/src/views/chat/Message.tsx
@@ -11,6 +11,7 @@ import { cx } from "~/lib/cx";
import { isStopNote } from "~/app/events";
import { UserAvatar, useDisplayName } from "~/components/UserAvatar";
import { usePulse } from "~/app/pulse";
+import { ArtifactStrip } from "~/components/artifacts/ArtifactCard";
/**
* One entry in a conversation. Each kind the runtime stores gets its own
@@ -67,6 +68,7 @@ export const Message = memo(function Message({ message }: { message: ChatMessage
)}
{body && <Markdown text={body} />}
{stopped && <StoppedMarker partial={!!body} />}
+ {message.artifacts && message.artifacts.length > 0 && <ArtifactStrip items={message.artifacts} />}
<MessageMeta timestamp={message.timestamp} copy={body || undefined} />
</div>
</div>