Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/cli/export-command.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ describe("atomic-agent export args (ATO-1054)", () => {
expect(parseExportArgs([])).toMatch(/session id or --last/);
expect(parseExportArgs(["s-1", "--last"])).toMatch(/not both/);
expect(parseExportArgs(["s-1", "s-2"])).toMatch(/one session id/);
expect(parseExportArgs(["s-1", "--format", "pdf"])).toMatch(/unknown format: pdf/);
expect(parseExportArgs(["s-1", "--format", "rtf"])).toMatch(/unknown format: rtf/);
expect(parseExportArgs(["s-1", "--out"])).toMatch(/--out needs a value/);
expect(parseExportArgs(["s-1", "--bogus"])).toMatch(/unknown option/);
});
Expand Down
21 changes: 12 additions & 9 deletions src/cli/export-command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,24 @@ import { describeToolCall } from "../tools/describe-tool-call.js";

const HELP =
[
"atomic-agent export — save one chat as Markdown, HTML or Word (ATO-1054)",
"atomic-agent export — save one chat as Markdown, HTML, Word or PDF (ATO-1054)",
"",
"Usage:",
" atomic-agent export <sessionId> [--format md|html|docx] [--out <file>] [--no-tools]",
" atomic-agent export --last [--format md|html|docx] [--out <file>] [--no-tools]",
" atomic-agent export <sessionId> [--format md|html|docx|pdf] [--out <file>] [--no-tools]",
" atomic-agent export --last [--format md|html|docx|pdf] [--out <file>] [--no-tools]",
"",
"Markdown and HTML go to stdout unless --out is given. Word (docx) is",
"written to --out, or to a file named after the chat in the current",
"folder. --last exports the most recent chat. --no-tools leaves out the",
"one line per tool step. For a PDF, open the HTML in a browser and print",
"it, or use Export in the desktop app. Session ids: `/session` in the TUI.",
"Markdown and HTML go to stdout unless --out is given. Word (docx) and",
"PDF are written to --out, or to a file named after the chat in the",
"current folder. --last exports the most recent chat. --no-tools leaves",
"out the one line per tool step. The PDF uses the standard PDF fonts:",
"text outside Western European scripts is transliterated or shown as ?,",
"and the file says so; Markdown and Word keep every character. In the",
"TUI, `/export` saves the open chat. Session ids: `/session` in the TUI.",
"",
"Examples:",
" atomic-agent export --last > chat.md",
" atomic-agent export s-1234 --format docx --out ~/Documents/chat.docx",
" atomic-agent export --last --format pdf",
].join("\n") + "\n";

/** Exit codes follow the dispatcher's split: 0 ok, 1 failed, 2 usage. */
Expand Down Expand Up @@ -101,7 +104,7 @@ export function parseExportArgs(args: readonly string[]): ParsedExportArgs | str
if (!last && !sessionId) return "give a session id or --last";
if (last && sessionId) return "give a session id or --last, not both";
const format = parseChatExportFormat(formatRaw);
if (!format) return `unknown format: ${formatRaw} (md, html or docx)`;
if (!format) return `unknown format: ${formatRaw} (md, html, docx or pdf)`;
return { sessionId, last, format, out, tools };
}

Expand Down
2 changes: 1 addition & 1 deletion src/http/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ Step labels in history (ATO-1382): `GET /api/sessions/{id}` adds `done_line` to

Searching past chats (ATO-1149, [session-search.ts](../session/session-search.ts)): `GET /api/sessions/search?q=…` finds words in the user messages and closing replies of stored sessions with SQLite FTS5 (tool calls and tool output are not indexed). It covers the current working directory, or every folder with `scope=all`; `limit` defaults to 10, max 25, at most 3 hits per session. The answer is `200 { query, hits, pending }`: each hit carries `sessionId`, `title`, `workingDir`, `updatedAt`, `line` (index into the session's chat lines), `kind`, `source` (`chat`, `telegram`, `discord`, `webhook`, `task`, `imported`, for a label) and a `snippet` with the matched words in `«` `»`. Task sessions rank below an interactive chat that matches as well; incognito chats, Fusion workers and sessions stamped `metadata.internal` / `metadata.subagent` are never indexed. The index is filled at search time, not on every write: each search reindexes up to 500 sessions changed since they were last indexed, newest first (transcripts read without the write lock, the index written 25 sessions per transaction), and `pending` counts the rest. `400` for an empty or over-500-character `q`, `503` when the index cannot be created.

[Export route](route-session-export.ts) (ATO-1054): `GET /api/sessions/{id}/export?format=markdown|html|docx[&tools=0]` answers `{ id, format, filename, mimeType, encoding, content }` (`utf8` text, or `base64` for DOCX), built by [exportChat](../session/chat-export-render.ts). PDF is printed by the client from the `html` format. `400` for another format, `404` for an unknown id.
[Export route](route-session-export.ts) (ATO-1054): `GET /api/sessions/{id}/export?format=markdown|html|docx|pdf[&tools=0]` answers `{ id, format, filename, mimeType, encoding, content }` (`utf8` text, or `base64` for DOCX and PDF), built by [exportChat](../session/chat-export-render.ts). The desktop prints its PDF from the `html` format; `pdf` is the browserless writer (standard fonts, WinAnsi). `400` for another format, `404` for an unknown id.


[Archive route](route-session-archived.ts) (ATO-1150): `POST /api/sessions/{id}/archived` with `{ archived: true | false }` (`400` for anything but a boolean, `404` for an unknown id) archives or unarchives a chat through `SessionStore.setSessionArchived`: `metadata.archived: true`, or no `archived` key once unarchived, stamped with `metadata.archivedSetAt` so a copy read before the change (a turn still running) cannot write the old flag back. `GET /api/sessions` lists `archived` on every row; the desktop's sidebar draws archived chats in their own section and the terminal's rail and session picker leave them out. `updatedAt` is not touched.
Expand Down
7 changes: 5 additions & 2 deletions src/http/route-session-export.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ describe("GET /api/sessions/{id}/export (ATO-1054)", () => {
expect(body.content).not.toMatch(/\n- /);
});

it("answers HTML and a base64 DOCX", async () => {
it("answers HTML, a base64 DOCX and a base64 PDF", async () => {
seed("ex-3");
const html = (await (await get("ex-3", "?format=html")).json()) as ExportBody;
expect(html.encoding).toBe("utf8");
Expand All @@ -66,11 +66,14 @@ describe("GET /api/sessions/{id}/export (ATO-1054)", () => {
expect(docx).toMatchObject({ format: "docx", filename: "Trip plan.docx", encoding: "base64" });
const zip = await JSZip.loadAsync(Buffer.from(docx.content, "base64"));
expect(await zip.file("word/document.xml")!.async("string")).toContain("Lisbon");
const pdf = (await (await get("ex-3", "?format=pdf")).json()) as ExportBody;
expect(pdf).toMatchObject({ format: "pdf", filename: "Trip plan.pdf", mimeType: "application/pdf", encoding: "base64" });
expect(Buffer.from(pdf.content, "base64").subarray(0, 8).toString("latin1")).toBe("%PDF-1.4");
});

it("refuses an unknown format and a missing session", async () => {
seed("ex-4");
expect((await get("ex-4", "?format=pdf")).status).toBe(400);
expect((await get("ex-4", "?format=rtf")).status).toBe(400);
expect((await get("nope")).status).toBe(404);
});
});
11 changes: 6 additions & 5 deletions src/http/route-session-export.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,16 @@ import { openaiError } from "./openai-errors.js";
import { sendError, sendJson, type HttpHandler } from "./request-context.js";

/**
* `GET /api/sessions/{id}/export?format=markdown|html|docx[&tools=0]` —
* `GET /api/sessions/{id}/export?format=markdown|html|docx|pdf[&tools=0]` —
* one chat as a document (ATO-1054).
*
* The answer is JSON, not the raw file, so a client that already speaks
* JSON to this server needs nothing new to read it:
* `{ id, format, filename, mimeType, encoding, content }`, where
* `encoding` is `utf8` for Markdown and HTML and `base64` for DOCX. The
* client writes `content` to wherever the person chose. PDF is the
* client's job: it prints the `html` format (Electron `printToPDF`).
* `encoding` is `utf8` for Markdown and HTML and `base64` for DOCX and
* PDF. The client writes `content` to wherever the person chose. The
* desktop prints the `html` format itself (Electron `printToPDF`), which
* keeps every script; `pdf` is the browserless writer the terminal uses.
*
* `format` defaults to Markdown and also takes `md` / `word`; anything
* else is `400`. `tools=0` leaves out the one-line-per-tool-step list.
Expand All @@ -28,7 +29,7 @@ export function createExportSessionHandler(): HttpHandler {
const url = new URL(req.url ?? "/", "http://localhost");
const format = parseChatExportFormat(url.searchParams.get("format"));
if (!format) {
sendError(res, 400, openaiError("format must be markdown, html or docx", "invalid_request_error", "format"));
sendError(res, 400, openaiError("format must be markdown, html, docx or pdf", "invalid_request_error", "format"));
return;
}
const state = ctx.runtime.sessionStore.load(id);
Expand Down
2 changes: 1 addition & 1 deletion src/session/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ Read README.md for state/retention changes; ../runtime/docs/lifecycle.md for con

[Turn progress](turn-progress.ts) (ATO-1109): `executeTurn` marks a turn's progress when it starts and checkpoints the transcript with the marker after every completed step (`SessionStore.checkpointTurn`, one row write guarded on the turn's own mark). A turn that ends on its own clears the marker; one that ends `cancelled`, or whose process died (the boot sweep ends the row and keeps the marker), keeps it so the work can be continued. The task runner continues tasks cut off by a crash or a restart; nothing continues a turn a person stopped. A chat turn a restart cut off ([interrupted-chat-turn.ts](interrupted-chat-turn.ts), ATO-448) is never continued on its own: opening its session in the TUI shows a one-line offer, and `/resume` (`AgentRuntime.interruptedTurns`, the same entry point for the desktop or an HTTP client) sends one continuing turn, starting with a note that tools may or may not have completed and side effects must be checked before they are repeated. Taking it marks the turn "resume queued" in memory, so it is offered once; the continuing turn replaces the marker when it starts, and a resume dropped before that (queue cleared, run stopped, session switched) is offered again.

[Chat export](chat-export.ts) (ATO-1054): one chat as Markdown (messages, replies, one line per tool step, delivered files; no reasoning or raw tool output), and HTML ([renderChatHtml](chat-export.ts), raw HTML shown as text, CSP blocks loads) or DOCX ([chat-export-docx.ts](chat-export-docx.ts), minimal OOXML zipped with JSZip) built from that Markdown. Used by `atomic-agent export` and `GET /api/sessions/{id}/export`.
[Chat export](chat-export.ts) (ATO-1054): one chat as Markdown (messages, replies, one line per tool step, delivered files; no reasoning or raw tool output), and HTML ([renderChatHtml](chat-export.ts), raw HTML shown as text, CSP blocks loads) DOCX ([chat-export-docx.ts](chat-export-docx.ts), minimal OOXML zipped with JSZip) or PDF ([chat-export-pdf.ts](chat-export-pdf.ts), text pages in the standard PDF fonts with no browser; text outside WinAnsi is transliterated or shown as `?`, and the file ends with a note saying so) built from that Markdown. Used by `atomic-agent export`, the TUI `/export` and `GET /api/sessions/{id}/export`.

[Archived chats](session-archived.ts) (ATO-1150): `metadata.archived: true` marks a chat the operator put away, with `metadata.archivedSetAt` stamping every archive and unarchive. `SessionStore.setSessionArchived` sets it; `save`, `finishTurn` and `checkpointTurn` keep the stored flag over a copy with no stamp or an older one, as for a renamed title. `SessionSummary.archived` carries it to the lists. Not the turn archive (`turn-archive.ts`), which is storage for compacted turns.

Expand Down
115 changes: 115 additions & 0 deletions src/session/chat-export-pdf.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { inflateSync } from "node:zlib";

import { describe, expect, it } from "vitest";

import { encodeWinAnsi, renderMarkdownPdf } from "./chat-export-pdf.js";

/** Every page's content stream, inflated, as latin1 text. */
function pageStreams(pdf: Buffer): string[] {
const text = pdf.toString("latin1");
const out: string[] = [];
const re = /<< \/Length (\d+) \/Filter \/FlateDecode >>\nstream\n/g;
for (let m = re.exec(text); m; m = re.exec(text)) {
const start = m.index + m[0].length;
out.push(inflateSync(pdf.subarray(start, start + Number(m[1]))).toString("latin1"));
}
return out;
}

/** The words a reader sees: strings within one text object joined, objects joined by a space. */
function shownText(stream: string): string {
return (stream.match(/BT [\s\S]*? ET/g) ?? [])
.map((obj) => (obj.match(/\(((?:\\.|[^\\)])*)\) Tj/g) ?? []).map((tj) => tj.slice(1, -4)).join(""))
.join(" ");
}

describe("chat export to PDF (ATO-1054)", () => {
it("writes a header, objects at the offsets the xref lists, and a trailer", () => {
const pdf = renderMarkdownPdf("# Hello\n\nWorld", "My chat", Date.UTC(2026, 10, 12));
const text = pdf.toString("latin1");
expect(text.startsWith("%PDF-1.4\n")).toBe(true);
expect(text.trimEnd().endsWith("%%EOF")).toBe(true);

const startxref = Number(/startxref\n(\d+)\n%%EOF\n$/.exec(text)?.[1]);
expect(text.slice(startxref, startxref + 5)).toBe("xref\n");
const xref = /xref\n0 (\d+)\n([\s\S]*?)trailer/.exec(text.slice(startxref));
expect(xref).not.toBeNull();
const count = Number(xref![1]);
const entries = xref![2]!.match(/.{20}/gs) ?? [];
expect(entries).toHaveLength(count);
expect(entries[0]).toBe("0000000000 65535 f \n");
entries.slice(1).forEach((entry, i) => {
const offset = Number(entry.slice(0, 10));
expect(text.slice(offset, offset + `${i + 1} 0 obj`.length)).toBe(`${i + 1} 0 obj`);
});
expect(text).toContain(`/Size ${count} /Root 1 0 R /Info 7 0 R`);
expect(text).toContain("/BaseFont /Helvetica /Encoding /WinAnsiEncoding");
expect(text).toContain("/CreationDate (D:20261112000000Z)");
// The title keeps any character: UTF-16BE with a byte order mark.
expect(text).toContain("/Title <FEFF004D007900200063006800610074>");
});

it("draws the text and numbers one page for a short chat", () => {
const pdf = renderMarkdownPdf("## You\n\nWhat is **Lisbon** like in `May`?", "Trip");
expect(pdf.toString("latin1")).toMatch(/\/Type \/Pages \/Kids \[8 0 R\] \/Count 1/);
const [page] = pageStreams(pdf);
expect(page).toContain("(You) Tj");
expect(page).toContain("(Lisbon) Tj");
expect(page).toContain("/F2 "); // bold
expect(page).toContain("/F4 "); // code in Courier
expect(page).toContain("(Page 1 of 1) Tj");
});

it("starts new pages for a long chat and counts them in the page tree", () => {
const long = Array.from({ length: 300 }, (_, i) => `Paragraph ${i + 1} of a long reply.`).join("\n\n");
const pdf = renderMarkdownPdf(long, "Long");
const pages = pageStreams(pdf);
expect(pages.length).toBeGreaterThan(3);
const tree = /\/Type \/Pages \/Kids \[([^\]]*)\] \/Count (\d+)/.exec(pdf.toString("latin1"));
expect(Number(tree![2])).toBe(pages.length);
expect(tree![1]!.split(" 0 R").filter((s) => s.trim()).length).toBe(pages.length);
expect((pdf.toString("latin1").match(/\/Type \/Page /g) ?? []).length).toBe(pages.length);
expect(pages[pages.length - 1]).toContain(`(Page ${pages.length} of ${pages.length}) Tj`);
expect(pages.join("\n")).toContain("(Paragraph 300 of a long reply.) Tj");
});

it("wraps long lines inside the margins and escapes PDF string syntax", () => {
const pdf = renderMarkdownPdf(`${"word ".repeat(200)}\n\nA (paren) and a \\ backslash`, "Wrap");
const page = pageStreams(pdf)[0]!;
const lines = page.match(/\(word[^)]*\) Tj/g) ?? [];
expect(lines.length).toBeGreaterThan(5);
expect(page).toContain("(A \\(paren\\) and a \\\\ backslash) Tj");
});

it("transliterates or replaces what WinAnsi lacks, and says so at the end", () => {
expect(encodeWinAnsi("Café “quoted” — €5")).toEqual({
text: "Café \u0093quoted\u0094 \u0097 \u00805",
changed: 0,
});
expect(encodeWinAnsi("Привет")).toEqual({ text: "Privet", changed: 6 });
expect(encodeWinAnsi("a → b")).toEqual({ text: "a -> b", changed: 1 });
expect(encodeWinAnsi("łódź")).toEqual({ text: "lódz", changed: 2 });
expect(encodeWinAnsi("你好 🚀")).toEqual({ text: "?? ?", changed: 3 });
expect(encodeWinAnsi("zero​width️")).toEqual({ text: "zerowidth", changed: 0 });

const clean = pageStreams(renderMarkdownPdf("Plain English.", "Clean")).join("\n");
expect(clean).not.toContain("standard PDF fonts");
const mixed = pageStreams(renderMarkdownPdf("Привет 你", "Mixed")).join("\n");
expect(mixed).toContain("(Privet ?) Tj");
expect(shownText(mixed)).toContain("7 characters were transliterated or shown as \"?\"");
});

it("keeps lists, code blocks, quotes and tables as text", () => {
const pdf = renderMarkdownPdf(
["- one", "- [x] done", "", "1. first", "", "> quoted", "", "```", " indented()", "```", "", "| A | B |", "|---|---|", "| 1 | 2 |"].join("\n"),
"Blocks",
);
const page = pageStreams(pdf)[0]!;
expect(page).toContain("(\u0095) Tj"); // the bullet, in WinAnsi
expect(page).toContain("([x]) Tj");
expect(page).toContain("(1.) Tj");
expect(page).toContain("(quoted) Tj");
expect(page).toContain("( indented\\(\\)) Tj");
expect(page).toMatch(/\(A\) Tj .*\( \| \) Tj .*\(B\) Tj/);
});
});
Loading
Loading