Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(copilot): add Export Chat as Markdown option to session menu (#13070)

Toran Bruce Richards60ce5f40a644
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx
index 0a6a38587b..6b9a655fe0 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx
@@ -1,6 +1,7 @@
"use client";
import {
getGetV2ListSessionsQueryKey,
+ getV2GetSession,
useGetV2ListSessions,
usePatchV2UpdateSessionTitle,
} from "@/app/api/__generated__/endpoints/chat/chat";
@@ -25,9 +26,12 @@ import { cn } from "@/lib/utils";
import {
CheckCircle,
CircleNotch,
+ DownloadSimpleIcon,
DotsThree,
+ PencilSimpleIcon,
PlusCircleIcon,
PlusIcon,
+ TrashIcon,
} from "@phosphor-icons/react";
import { useQueryClient } from "@tanstack/react-query";
import { AnimatePresence, motion } from "framer-motion";
@@ -39,6 +43,7 @@ import { shouldShowSessionProcessingIndicator } from "../../sessionActivity";
import { useCopilotUIStore } from "../../store";
import { useSessionDeletion } from "../../useSessionDeletion";
import { NotificationToggle } from "./components/NotificationToggle/NotificationToggle";
+import { fetchAndExportChat } from "../../helpers/exportChatAsMarkdown";
import { DeleteChatDialog } from "../DeleteChatDialog/DeleteChatDialog";
import { UsagePopover } from "../UsageLimits/UsagePopover/UsagePopover";
@@ -66,6 +71,9 @@ export function ChatSidebar() {
const [editingSessionId, setEditingSessionId] = useState<string | null>(null);
const [editingTitle, setEditingTitle] = useState("");
+ const [exportingSessionIds, setExportingSessionIds] = useState<Set<string>>(
+ new Set(),
+ );
const renameInputRef = useRef<HTMLInputElement>(null);
const renameCancelledRef = useRef(false);
@@ -152,6 +160,36 @@ export function ChatSidebar() {
requestDelete(id, title);
}
+ async function handleExportClick(
+ e: React.MouseEvent,
+ id: string,
+ title: string | null | undefined,
+ ) {
+ e.stopPropagation();
+ if (exportingSessionIds.has(id)) return;
+ setExportingSessionIds((prev) => new Set(prev).add(id));
+ try {
+ await fetchAndExportChat(id, title, getV2GetSession);
+ toast({ title: "Chat exported" });
+ } catch (error) {
+ console.error("Failed to export chat:", { id, title, error });
+ toast({
+ title: "Export failed",
+ description:
+ error instanceof Error
+ ? error.message
+ : "Could not export this chat. Please try again.",
+ variant: "destructive",
+ });
+ } finally {
+ setExportingSessionIds((prev) => {
+ const next = new Set(prev);
+ next.delete(id);
+ return next;
+ });
+ }
+ }
+
function formatDate(dateString: string) {
const date = new Date(dateString);
const now = new Date();
@@ -305,7 +343,12 @@ export function ChatSidebar() {
) : (
<button
onClick={() => handleSelectSession(session.id)}
- className="w-full px-3 py-2.5 pr-10 text-left"
+ className={cn(
+ "w-full px-3 py-2.5 text-left",
+ exportingSessionIds.has(session.id)
+ ? "pr-[68px]"
+ : "pr-10",
+ )}
>
<div className="flex min-w-0 max-w-full items-center gap-2">
<div className="min-w-0 flex-1">
@@ -360,6 +403,18 @@ export function ChatSidebar() {
</div>
</button>
)}
+ {exportingSessionIds.has(session.id) && (
+ <div
+ className="pointer-events-none absolute right-9 top-1/2 z-10 -translate-y-1/2 rounded-full bg-white text-zinc-600 shadow-sm"
+ aria-label="Exporting chat"
+ title="Exporting chat…"
+ >
+ <div className="relative h-7 w-7">
+ <div className="absolute inset-0 animate-spin rounded-full border-2 border-zinc-200 border-t-zinc-700" />
+ <DownloadSimpleIcon className="absolute inset-0 m-auto h-3.5 w-3.5" />
+ </div>
+ </div>
+ )}
{editingSessionId !== session.id && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
@@ -377,8 +432,31 @@ export function ChatSidebar() {
handleRenameClick(e, session.id, session.title)
}
>
+ <PencilSimpleIcon className="mr-2 h-4 w-4" />
Rename
</DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={(e) =>
+ handleExportClick(e, session.id, session.title)
+ }
+ onSelect={(e) => {
+ if (exportingSessionIds.has(session.id))
+ e.preventDefault();
+ }}
+ disabled={exportingSessionIds.has(session.id)}
+ >
+ {exportingSessionIds.has(session.id) ? (
+ <CircleNotch
+ className="mr-2 h-4 w-4 animate-spin"
+ weight="bold"
+ />
+ ) : (
+ <DownloadSimpleIcon className="mr-2 h-4 w-4" />
+ )}
+ {exportingSessionIds.has(session.id)
+ ? "Exporting…"
+ : "Export chat"}
+ </DropdownMenuItem>
<DropdownMenuItem
onClick={(e) =>
handleDeleteClick(e, session.id, session.title)
@@ -386,6 +464,7 @@ export function ChatSidebar() {
disabled={isDeleting}
className="text-red-600 focus:bg-red-50 focus:text-red-600"
>
+ <TrashIcon className="mr-2 h-4 w-4" />
Delete chat
</DropdownMenuItem>
</DropdownMenuContent>
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/exportChatAsMarkdown.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/exportChatAsMarkdown.test.ts
new file mode 100644
index 0000000000..c7c08aec0a
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/exportChatAsMarkdown.test.ts
@@ -0,0 +1,310 @@
+import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
+import {
+ exportChatAsMarkdown,
+ fetchAndExportChat,
+} from "../exportChatAsMarkdown";
+
+describe("exportChatAsMarkdown", () => {
+ let clickSpy: ReturnType<typeof vi.fn>;
+ let removeSpy: ReturnType<typeof vi.fn>;
+ let anchor: {
+ href: string;
+ download: string;
+ click: ReturnType<typeof vi.fn>;
+ remove: ReturnType<typeof vi.fn>;
+ };
+
+ beforeEach(() => {
+ clickSpy = vi.fn();
+ removeSpy = vi.fn();
+
+ anchor = { href: "", download: "", click: clickSpy, remove: removeSpy };
+
+ vi.stubGlobal(
+ "URL",
+ Object.assign(URL, {
+ createObjectURL: vi.fn().mockReturnValue("blob:fake-url"),
+ revokeObjectURL: vi.fn(),
+ }),
+ );
+
+ vi.spyOn(document, "createElement").mockReturnValue(
+ anchor as unknown as HTMLAnchorElement,
+ );
+
+ vi.spyOn(document.body, "appendChild").mockImplementation(
+ (node) => node as ChildNode,
+ );
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ it("triggers a download with .md extension", () => {
+ exportChatAsMarkdown("session-1", "My Chat", []);
+ expect(clickSpy).toHaveBeenCalled();
+ expect(removeSpy).toHaveBeenCalled();
+ expect(anchor.download).toMatch(/\.md$/);
+ expect(URL.revokeObjectURL).toHaveBeenCalledWith("blob:fake-url");
+ });
+
+ it("includes the chat title in the filename", () => {
+ exportChatAsMarkdown("session-1", "My Chat", []);
+ expect(anchor.download).toContain("My Chat");
+ });
+
+ it("falls back to 'Untitled chat' when title is null", () => {
+ exportChatAsMarkdown("session-1", null, []);
+ expect(anchor.download).toContain("Untitled chat");
+ });
+
+ it("renders user and assistant messages with headers", () => {
+ const messages = [
+ { role: "user", content: "Hello", tool_calls: null },
+ { role: "assistant", content: "Hi there", tool_calls: null },
+ ];
+ exportChatAsMarkdown("session-1", "Test", messages);
+
+ const blob: Blob = (URL.createObjectURL as ReturnType<typeof vi.fn>).mock
+ .calls[0][0];
+ return blob.text().then((text) => {
+ expect(text).toContain("## User");
+ expect(text).toContain("Hello");
+ expect(text).toContain("## Assistant");
+ expect(text).toContain("Hi there");
+ });
+ });
+
+ it("skips tool result messages (role === 'tool')", () => {
+ const messages = [
+ { role: "tool", content: "tool result", tool_calls: null },
+ ];
+ exportChatAsMarkdown("session-1", "Test", messages);
+
+ const blob: Blob = (URL.createObjectURL as ReturnType<typeof vi.fn>).mock
+ .calls[0][0];
+ return blob.text().then((text) => {
+ expect(text).not.toContain("tool result");
+ expect(text).not.toContain("## Tool");
+ });
+ });
+
+ it("renders tool calls as blockquotes with emoji", () => {
+ const messages = [
+ {
+ role: "assistant",
+ content: null,
+ tool_calls: [
+ {
+ function: {
+ name: "search_web",
+ arguments: JSON.stringify({ query: "cats" }),
+ },
+ },
+ ],
+ },
+ ];
+ exportChatAsMarkdown("session-1", "Test", messages);
+
+ const blob: Blob = (URL.createObjectURL as ReturnType<typeof vi.fn>).mock
+ .calls[0][0];
+ return blob.text().then((text) => {
+ expect(text).toContain("> 🔧");
+ expect(text).toContain("search_web");
+ });
+ });
+
+ it("sanitizes path traversal in title", () => {
+ exportChatAsMarkdown("session-1", "../../etc/passwd", []);
+ expect(anchor.download).not.toContain("..");
+ expect(anchor.download).not.toContain("/");
+ });
+
+ it("falls back to 'Untitled chat' when title is undefined", () => {
+ exportChatAsMarkdown("session-1", undefined, []);
+ expect(anchor.download).toContain("Untitled chat");
+ });
+
+ it("uses 'unknown_tool' when tool call has no function name", () => {
+ const messages = [
+ {
+ role: "assistant",
+ content: null,
+ tool_calls: [{ function: { name: undefined, arguments: "{}" } }],
+ },
+ ];
+ exportChatAsMarkdown("session-1", "Test", messages);
+
+ const blob: Blob = (URL.createObjectURL as ReturnType<typeof vi.fn>).mock
+ .calls[0][0];
+ return blob.text().then((text) => {
+ expect(text).toContain("unknown_tool");
+ });
+ });
+
+ it("handles invalid JSON in tool call arguments gracefully", () => {
+ const messages = [
+ {
+ role: "assistant",
+ content: null,
+ tool_calls: [
+ { function: { name: "my_tool", arguments: "not-valid-json" } },
+ ],
+ },
+ ];
+ exportChatAsMarkdown("session-1", "Test", messages);
+
+ const blob: Blob = (URL.createObjectURL as ReturnType<typeof vi.fn>).mock
+ .calls[0][0];
+ return blob.text().then((text) => {
+ expect(text).toContain("my_tool");
+ expect(text).toContain("not-valid-json");
+ });
+ });
+
+ it("includes export date in the markdown body", () => {
+ exportChatAsMarkdown("session-1", "Test", []);
+
+ const blob: Blob = (URL.createObjectURL as ReturnType<typeof vi.fn>).mock
+ .calls[0][0];
+ return blob.text().then((text) => {
+ expect(text).toMatch(/_Exported: \d{4}-\d{2}-\d{2}_/);
+ });
+ });
+});
+
+describe("fetchAndExportChat", () => {
+ let clickSpy: ReturnType<typeof vi.fn>;
+ let anchor: {
+ href: string;
+ download: string;
+ click: ReturnType<typeof vi.fn>;
+ remove: ReturnType<typeof vi.fn>;
+ };
+
+ beforeEach(() => {
+ clickSpy = vi.fn();
+ anchor = { href: "", download: "", click: clickSpy, remove: vi.fn() };
+
+ vi.stubGlobal(
+ "URL",
+ Object.assign(URL, {
+ createObjectURL: vi.fn().mockReturnValue("blob:fake-url"),
+ revokeObjectURL: vi.fn(),
+ }),
+ );
+
+ vi.spyOn(document, "createElement").mockReturnValue(
+ anchor as unknown as HTMLAnchorElement,
+ );
+
+ vi.spyOn(document.body, "appendChild").mockImplementation(
+ (node) => node as ChildNode,
+ );
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ it("calls exportChatAsMarkdown when fetch succeeds", async () => {
+ const mockFetch = vi.fn().mockResolvedValue({
+ status: 200,
+ data: {
+ messages: [{ role: "user", content: "Hello", tool_calls: null }],
+ },
+ });
+ await fetchAndExportChat("session-1", "My Chat", mockFetch);
+ expect(clickSpy).toHaveBeenCalled();
+ expect(anchor.download).toMatch(/\.md$/);
+ });
+
+ it("throws when fetch returns non-200 status (includes status code)", async () => {
+ const mockFetch = vi.fn().mockResolvedValue({ status: 404, data: {} });
+ await expect(
+ fetchAndExportChat("session-1", "My Chat", mockFetch),
+ ).rejects.toThrow("Failed to fetch session (status: 404)");
+ });
+
+ it("handles null messages array gracefully", async () => {
+ const mockFetch = vi.fn().mockResolvedValue({
+ status: 200,
+ data: { messages: null },
+ });
+ await fetchAndExportChat("session-1", "My Chat", mockFetch);
+ expect(clickSpy).toHaveBeenCalled();
+ });
+
+ it("paginates via before_sequence until has_more_messages is false", async () => {
+ const mockFetch = vi
+ .fn()
+ .mockResolvedValueOnce({
+ status: 200,
+ data: {
+ messages: [
+ { role: "user", content: "page2-msg-a", tool_calls: null },
+ { role: "assistant", content: "page2-msg-b", tool_calls: null },
+ ],
+ has_more_messages: true,
+ oldest_sequence: 42,
+ },
+ })
+ .mockResolvedValueOnce({
+ status: 200,
+ data: {
+ messages: [
+ { role: "user", content: "page1-msg-a", tool_calls: null },
+ { role: "assistant", content: "page1-msg-b", tool_calls: null },
+ ],
+ has_more_messages: false,
+ oldest_sequence: 1,
+ },
+ });
+
+ await fetchAndExportChat("session-1", "My Chat", mockFetch);
+
+ expect(mockFetch).toHaveBeenCalledTimes(2);
+ expect(mockFetch).toHaveBeenNthCalledWith(1, "session-1", { limit: 200 });
+ expect(mockFetch).toHaveBeenNthCalledWith(2, "session-1", {
+ limit: 200,
+ before_sequence: 42,
+ });
+ expect(clickSpy).toHaveBeenCalled();
+ });
+
+ it("throws when pagination cap is hit while has_more is still true", async () => {
+ const mockFetch = vi.fn().mockResolvedValue({
+ status: 200,
+ data: {
+ messages: [{ role: "user", content: "msg", tool_calls: null }],
+ has_more_messages: true,
+ oldest_sequence: 1,
+ },
+ });
+
+ await expect(
+ fetchAndExportChat("session-1", "My Chat", mockFetch),
+ ).rejects.toThrow(/exceeded \d+ messages/);
+
+ expect(clickSpy).not.toHaveBeenCalled();
+ });
+
+ it("stops paginating when oldest_sequence is null even if has_more is true", async () => {
+ const mockFetch = vi.fn().mockResolvedValue({
+ status: 200,
+ data: {
+ messages: [{ role: "user", content: "Hello", tool_calls: null }],
+ has_more_messages: true,
+ oldest_sequence: null,
+ },
+ });
+
+ await fetchAndExportChat("session-1", "My Chat", mockFetch);
+
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ expect(clickSpy).toHaveBeenCalled();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/exportChatAsMarkdown.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/exportChatAsMarkdown.ts
new file mode 100644
index 0000000000..eb9128f2fc
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/exportChatAsMarkdown.ts
@@ -0,0 +1,125 @@
+interface SessionChatMessage {
+ role: string;
+ content: string | null;
+ tool_calls: unknown[] | null;
+}
+
+interface ToolCall {
+ function?: {
+ name?: string;
+ arguments?: string;
+ };
+}
+
+function formatToolCalls(toolCalls: unknown[]): string {
+ return toolCalls
+ .map((tc) => {
+ const call = tc as ToolCall;
+ const name = call.function?.name ?? "unknown_tool";
+ let argsStr = "";
+ try {
+ const args = JSON.parse(call.function?.arguments ?? "{}") as Record<
+ string,
+ unknown
+ >;
+ argsStr = Object.entries(args)
+ .map(([k, v]) => `${k}=${JSON.stringify(v)}`)
+ .join(", ");
+ } catch {
+ argsStr = call.function?.arguments ?? "";
+ }
+ return `> 🔧 \`${name}(${argsStr})\``;
+ })
+ .join("\n");
+}
+
+function sanitizeFilename(name: string): string {
+ return name
+ .replace(/\.\./g, "_")
+ .replace(/[\\/:*?"<>|\x00-\x1f]/g, "_")
+ .replace(/^\.+/, "")
+ .slice(0, 100);
+}
+
+export function exportChatAsMarkdown(
+ _sessionId: string,
+ title: string | null | undefined,
+ messages: SessionChatMessage[],
+): void {
+ const displayTitle = title || "Untitled chat";
+ const date = new Date().toISOString().slice(0, 10);
+
+ const lines: string[] = [`# ${displayTitle}`, `_Exported: ${date}_`, ""];
+
+ for (const msg of messages) {
+ if (msg.role === "tool") continue;
+
+ if (msg.role === "user") {
+ lines.push("## User", "");
+ if (msg.content) lines.push(msg.content, "");
+ } else if (msg.role === "assistant") {
+ lines.push("## Assistant", "");
+ if (msg.tool_calls && msg.tool_calls.length > 0) {
+ lines.push(formatToolCalls(msg.tool_calls), "");
+ }
+ if (msg.content) lines.push(msg.content, "");
+ }
+ }
+
+ const markdown = lines.join("\n");
+ const blob = new Blob([markdown], { type: "text/markdown;charset=utf-8" });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = `chat-${sanitizeFilename(displayTitle)}-${date}.md`;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ URL.revokeObjectURL(url);
+}
+
+const EXPORT_PAGE_SIZE = 200;
+const EXPORT_MAX_PAGES = 100;
+
+export async function fetchAndExportChat(
+ id: string,
+ title: string | null | undefined,
+ fetchSession: typeof import("@/app/api/__generated__/endpoints/chat/chat").getV2GetSession,
+): Promise<void> {
+ const allMessages: SessionChatMessage[] = [];
+ let beforeSequence: number | undefined = undefined;
+ let truncated = false;
+
+ for (let page = 0; page < EXPORT_MAX_PAGES; page++) {
+ const opts: { limit: number; before_sequence?: number } = {
+ limit: EXPORT_PAGE_SIZE,
+ };
+ if (beforeSequence !== undefined) opts.before_sequence = beforeSequence;
+
+ const response = await fetchSession(id, opts);
+ if (response.status !== 200) {
+ throw new Error(`Failed to fetch session (status: ${response.status})`);
+ }
+
+ const pageMessages = (response.data.messages ??
+ []) as unknown as SessionChatMessage[];
+ allMessages.unshift(...pageMessages);
+
+ const hasMore = !!response.data.has_more_messages;
+ const oldestSeq = response.data.oldest_sequence;
+ if (!hasMore || oldestSeq == null) break;
+ if (page === EXPORT_MAX_PAGES - 1) {
+ truncated = true;
+ break;
+ }
+ beforeSequence = oldestSeq;
+ }
+
+ if (truncated) {
+ throw new Error(
+ `Chat export exceeded ${EXPORT_MAX_PAGES * EXPORT_PAGE_SIZE} messages. Please contact support to export this chat.`,
+ );
+ }
+
+ exportChatAsMarkdown(id, title, allMessages);
+}