Skip to content
Merged
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
6 changes: 4 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@ The backend (`fastapi_backend`) and the frontend (`nextjs-frontend`) are version
citations as footnotes linking back to the moment in Lens and the tools it used; the PDF is that Markdown printed by
Chromium, else anytopdf, else LibreOffice (409 when none can run); the JSON is OpenAI's chat message format in a tree
with Dublin Core terms, or `?format=messages` for one `{"messages": [...]}` line, checked against a published schema.
Agents use `list_chats`, `read_chat` and `export_chat` over MCP. The web app's copy and export buttons are in
progress ([Copy and export](docs/assistant.md#copy-and-export)).
Agents use `list_chats`, `read_chat` and `export_chat` over MCP. In the web app, an answer's copy button copies it as
Markdown or plain text and exports it, questions and code blocks have their own copy buttons, and the conversation's
header has Export; without a PDF printer on the server, the browser prints it instead
([Copy and export](docs/assistant.md#copy-and-export)).

## 0.14.0 <small>October 17, 2026</small> {id="0.14.0"}

Expand Down
10 changes: 8 additions & 2 deletions docs/assistant.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,8 +150,14 @@ Exports carry each tool call's arguments and summary, never its raw result, whic
export the same way over MCP: `list_chats`, `read_chat` and `export_chat` ([MCP](mcp.md)) work on the person's own
conversations.

The web app's copy buttons and Export menus are in progress. Planned: importing a conversation from its JSON,
exporting one to a note, and a styled PDF without Chromium.
In the web app, an answer's copy button offers **Copy as Markdown** (its citations as footnotes linking back to Lens,
as in the Markdown export) and **Copy text** (without Markdown or citation numbers), then exports that answer with
its question as Markdown, PDF or JSON. A question has its own copy button, shown on hover, and each code block in an
answer has one that copies the code as written. The download icon in a conversation's header exports the whole
conversation. When the server can't make a PDF, the browser's print dialog opens on the conversation (or that one
answer), without the app around it, so Save as PDF still works.

Planned: importing a conversation from its JSON, exporting one to a note, and a styled PDF without Chromium.

### Picking the namespace for a conversation over everything

Expand Down
191 changes: 191 additions & 0 deletions nextjs-frontend/__tests__/chat-copy-export.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import "@testing-library/jest-dom";

import { Chats } from "@/app/openapi-client";
import { answerMarkdown, plainText } from "@/components/chat/copy";
import { AnswerMenu, exportName, ExportMenu, useChatExport } from "@/components/chat/export";
import { parseBlocks, RichText } from "@/components/chat/rich-text";
import { UserBubble } from "@/components/chat/user-bubble";
import { saveBlob } from "@/components/recording/hooks";
import { ToastProvider } from "@/components/ui/toast";
import { TooltipProvider } from "@/components/ui/tooltip";

jest.mock("@/app/openapi-client", () => ({ Chats: { exportChat: jest.fn() } }));
jest.mock("next-auth/react", () => ({ useSession: () => ({ data: { accessToken: "t" } }) }));
jest.mock("@/components/recording/hooks", () => ({
...jest.requireActual("@/components/recording/hooks"),
saveBlob: jest.fn(),
}));
jest.mock("@/components/chat/attachments", () => ({ SentFiles: () => null }));

const ORIGIN = window.location.origin;
const PASSAGES = [
{
n: 1,
recording_id: 5,
title: "Episode one",
t0: 75_000,
time: "1:15",
speaker: "Ana",
text: "The ship\nleaves Friday.",
},
{ n: 2, recording_id: 7, title: "The call", t0: 0, time: "0:00", speaker: null, text: "It's late." },
{ n: 3, recording_id: 8, title: "Not cited", t0: 0, time: "0:00", speaker: null, text: "x" },
{
n: 4,
source: "web",
url: "https://example.org/ships",
title: "Ships",
site: "example.org",
recording_id: null,
text: "Ships are slow.",
},
];
const ANSWER =
"It leaves **on Friday** [1], late [2, 9]. Ships are slow [4]. See [the plan](https://example.org/plan).";

let writeText: jest.Mock;
beforeEach(() => {
jest.clearAllMocks();
writeText = jest.fn(() => Promise.resolve());
Object.assign(navigator, { clipboard: { writeText } });
});

function show(ui: React.ReactNode) {
const qc = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
return render(
<QueryClientProvider client={qc}>
<TooltipProvider>
<ToastProvider>{ui}</ToastProvider>
</TooltipProvider>
</QueryClientProvider>,
);
}

async function choose(button: string, item: string) {
fireEvent.keyDown(screen.getByRole("button", { name: button }), { key: "Enter" });
fireEvent.click(await screen.findByRole("menuitem", { name: item }));
}

describe("copying an answer", () => {
it("gives Markdown with citations as footnotes linking back to Lens, or plain text", () => {
expect(answerMarkdown(ANSWER, PASSAGES, ORIGIN)).toBe(
"It leaves **on Friday** [^1], late [^2][9]. Ships are slow [^4]. See [the plan](https://example.org/plan).\n\n" +
`[^1]: Episode one, 1:15, Ana: “The ship leaves Friday.” <${ORIGIN}/resources/5?t=75>\n` +
`[^2]: The call, 0:00: “It's late.” <${ORIGIN}/resources/7>\n` +
"[^4]: [Ships](https://example.org/ships), example.org: “Ships are slow.”\n",
);
expect(answerMarkdown("No citations here.", [], ORIGIN)).toBe("No citations here.\n");
expect(plainText(ANSWER)).toBe(
"It leaves on Friday, late. Ships are slow. See the plan (https://example.org/plan).",
);
expect(plainText("## Steps\n\n```bash\nls\n```")).toBe("Steps\n\nls");
});

it("copies from the answer's menu, and exports from it", async () => {
const onExport = jest.fn();
show(<AnswerMenu text={ANSWER} passages={PASSAGES} onExport={onExport} />);
await choose("Copy", "Copy as Markdown");
expect(writeText).toHaveBeenCalledWith(answerMarkdown(ANSWER, PASSAGES, ORIGIN));
expect(await screen.findByText("Copied as Markdown")).toBeInTheDocument();

await choose("Copy", "Copy text");
expect(writeText).toHaveBeenLastCalledWith(plainText(ANSWER));

await choose("Copy", "PDF");
await waitFor(() => expect(onExport).toHaveBeenCalledWith("pdf"));
});

it("says so when the browser won't copy", async () => {
writeText.mockImplementation(() => Promise.reject(new Error("denied")));
show(<AnswerMenu text="Hi" passages={[]} />);
await choose("Copy", "Copy text");
expect(await screen.findByText("Couldn’t copy")).toBeInTheDocument();
// not saved yet: nothing to export
fireEvent.keyDown(screen.getByRole("button", { name: "Copy" }), { key: "Enter" });
expect(await screen.findByRole("menuitem", { name: "Copy as Markdown" })).toBeInTheDocument();
expect(screen.queryByRole("menuitem", { name: "PDF" })).not.toBeInTheDocument();
});

it("copies a question", async () => {
show(<UserBubble text="When does it leave?" />);
fireEvent.click(screen.getByRole("button", { name: "Copy" }));
await waitFor(() => expect(writeText).toHaveBeenCalledWith("When does it leave?"));
});
});

describe("code blocks", () => {
it("parses fences, keeping the code as written", () => {
expect(parseBlocks("Run:\n\n```bash\nls -la\n cd x\n```\nDone [1].")).toEqual([
{ type: "p", text: "Run:" },
{ type: "code", lang: "bash", text: "ls -la\n cd x" },
{ type: "p", text: "Done [1]." },
]);
// one still being written ends with the text
expect(parseBlocks("~~~\n# not a heading\n- nor a list")).toEqual([
{ type: "code", lang: "", text: "# not a heading\n- nor a list" },
]);
});

it("copies a code block and says Copied", async () => {
show(<RichText text={"Try:\n```python\nprint('hi')\n```"} renderCite={() => null} />);
expect(screen.getByLabelText("python code")).toHaveTextContent("print('hi')");
fireEvent.click(screen.getByRole("button", { name: "Copy code" }));
await waitFor(() => expect(writeText).toHaveBeenCalledWith("print('hi')"));
expect(await screen.findByText("Copied")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Copied" })).toBeInTheDocument();
});
});

function Exporter({ onPrint }: { onPrint: (message?: number) => void }) {
const ex = useChatExport(4, "Shipping questions", onPrint);
return (
<>
<ExportMenu label="Export conversation" onExport={(fmt) => ex.mutate({ fmt })} />
<button type="button" onClick={() => ex.mutate({ fmt: "pdf", message: 9 })}>
one
</button>
</>
);
}

describe("exporting", () => {
it("downloads what the server makes, named as the server names it", async () => {
const blob = new Blob(["# x"]);
(Chats.exportChat as jest.Mock).mockResolvedValue({ data: blob, response: { ok: true, status: 200 } });
show(<Exporter onPrint={jest.fn()} />);
await choose("Export conversation", "Markdown");
await waitFor(() => expect(saveBlob).toHaveBeenCalledWith(blob, "shipping-questions.md"));
expect(Chats.exportChat).toHaveBeenCalledWith(
expect.objectContaining({ path: { cid: 4, fmt: "md" }, query: undefined, parseAs: "blob" }),
);
expect(exportName("Shipping questions", "json", 9)).toBe("shipping-questions-message-9.json");
expect(exportName(null, "pdf")).toBe("conversation.pdf");
});

it("prints in the browser when the server can't make the PDF", async () => {
(Chats.exportChat as jest.Mock).mockResolvedValue({
error: { detail: "a PDF needs Chromium, anytopdf or LibreOffice on the server" },
response: { ok: false, status: 409 },
});
const onPrint = jest.fn();
show(<Exporter onPrint={onPrint} />);
fireEvent.click(screen.getByRole("button", { name: "one" }));
await waitFor(() => expect(onPrint).toHaveBeenCalledWith(9));
expect(await screen.findByText("Printing it instead")).toBeInTheDocument();
expect(saveBlob).not.toHaveBeenCalled();
});

it("says what went wrong otherwise", async () => {
(Chats.exportChat as jest.Mock).mockResolvedValue({
error: { detail: "no such message in this conversation" },
response: { ok: false, status: 404 },
});
const onPrint = jest.fn();
show(<Exporter onPrint={onPrint} />);
await choose("Export conversation", "JSON");
expect(await screen.findByText("no such message in this conversation")).toBeInTheDocument();
expect(onPrint).not.toHaveBeenCalled();
});
});
10 changes: 10 additions & 0 deletions nextjs-frontend/__tests__/chat-versions.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,16 @@ jest.mock("@/lib/hooks/session", () => ({
useArchive: () => ({ can: () => true, namespaces: [], roleIn: () => "editor" }),
}));

// a saved answer's Details opens as a sheet on narrow screens, so it asks the screen's width
beforeAll(() => {
window.matchMedia = ((query: string) => ({
matches: false,
media: query,
addEventListener: () => {},
removeEventListener: () => {},
})) as unknown as typeof window.matchMedia;
});

// q1 → a1 → q2 → a2, a1 regenerated as b1 (→ q3 → a3), and q1 edited as e1 (→ f1)
const node = (id: number, parent: number | null, role: "user" | "assistant"): ChatNode => ({ id, parent, role });
const TREE = [
Expand Down
7 changes: 6 additions & 1 deletion nextjs-frontend/__tests__/chat.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,12 @@ describe("editing a question", () => {
});

it("can't be edited without a handler, e.g. while an answer is written", () => {
render(<UserBubble text="Hi" />);
render(
<TooltipProvider>
<UserBubble text="Hi" />
</TooltipProvider>,
);
expect(screen.queryByRole("button", { name: "Edit" })).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Copy" })).toBeInTheDocument();
});
});
4 changes: 2 additions & 2 deletions nextjs-frontend/components/app-shell/app-shell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ export function AppShell({ user, children }: { user: SessionUser; children: Reac
>
Skip to content
</a>
<div className="sticky top-0 hidden h-screen shrink-0 md:block">
<div className="sticky top-0 hidden h-screen shrink-0 md:block print:hidden!">
<Nav
admin={admin || user.admin}
collapsed={autoCollapse ? !peek : collapsed}
Expand All @@ -155,7 +155,7 @@ export function AppShell({ user, children }: { user: SessionUser; children: Reac
</div>
)}
<div className="flex min-w-0 flex-1 flex-col">
<header className="sticky top-0 z-40 flex h-16 items-center gap-3 border-b border-border bg-background px-3 md:px-4">
<header className="sticky top-0 z-40 flex h-16 items-center gap-3 border-b border-border bg-background px-3 md:px-4 print:hidden">
<IconButton label="Open navigation" className="md:hidden" onClick={() => setMobileOpen(true)}>
<MenuIcon />
</IconButton>
Expand Down
6 changes: 5 additions & 1 deletion nextjs-frontend/components/chat/answer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
} from "@/components/chat/cite";
import { CitationChip } from "@/components/chat/citation";
import { AnswerDetails } from "@/components/chat/details";
import { AnswerMenu, type ExportFormat } from "@/components/chat/export";
import { keywords } from "@/components/chat/keywords";
import { RichText } from "@/components/chat/rich-text";
import { scopeWords, type Scope } from "@/components/chat/scope";
Expand Down Expand Up @@ -158,6 +159,8 @@ export type AnswerProps = {
onChecked?: (c: AnswerCheck) => void;
/** What produced it (the answer's record); older answers have none. */
meta?: MessageRecord | null;
/** Export this answer, with its question (a saved answer's copy menu). */
onExport?: (fmt: ExportFormat) => void;
};

/** One answer: where it comes from, the tools used, approvals, the text with citations, and its error states. */
Expand Down Expand Up @@ -312,7 +315,7 @@ export function Answer(p: AnswerProps) {
</p>
)}

<div className="flex flex-wrap items-center gap-1.5">
<div className="flex flex-wrap items-center gap-1.5 print:hidden">
{streaming && p.onStop && (
<Button
size="sm"
Expand Down Expand Up @@ -361,6 +364,7 @@ export function Answer(p: AnswerProps) {
{check.isPending ? "Checking sources…" : "Check sources"}
</Button>
)}
{!streaming && !blank && !noModel && <AnswerMenu text={p.text} passages={p.passages} onExport={p.onExport} />}
</div>
{check.isError && (
<p role="alert" className="m-0 text-[13px] text-red-dark">
Expand Down
Loading
Loading