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
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,9 +101,10 @@ listed under [In progress](#in-progress), and what comes next under [Planned](#p
- **Answer your email.** Lens drafts a reply to an email a watched mailbox brought in, from what that email's
namespace holds: each fact cited to its excerpt, what the archive doesn't say marked for you to confirm, addressed
and threaded as a reply to it. Drafts wait for you to edit or set aside, and nothing is sent on its own; ask for one
through the API or MCP (agents list what waits and draft with your instructions), or add the reply step to a
pipeline to draft each new email, which skips mailing lists, no-reply senders and your own mail without a model
call. ([Email replies](docs/email-replies.md); [checks](docs/requirements.md#answer-your-email))
on the Replies page (Enter drafts the first, then copy it or open it in your mail app), through the API or MCP
(agents list what waits and draft with your instructions), or add the reply step to a pipeline to draft each new
email, which skips mailing lists, no-reply senders and your own mail without a model call.
([Email replies](docs/email-replies.md); [checks](docs/requirements.md#answer-your-email))
- **Work toward a goal in projects.** A project has a name, a goal in your words, instructions and the namespaces it
draws on. Its coordinator conversation looks at the project as a whole: it is told about every thread, starts threads
with a brief that the assistant answers there in the background, reads them and marks them done. Each thread is a
Expand Down
4 changes: 4 additions & 0 deletions changelog.d/replies-page.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
**The Replies page.** The email that waits for an answer, in the menu while any does: Enter drafts the first
one's reply, a draft shows with its sources and what's left to confirm, and Open in your mail app or Copy takes it
without its citations. Edits save with Ctrl+Enter; Set aside offers Undo. An email's More actions menu has Reply to
this email….
17 changes: 15 additions & 2 deletions docs/email-replies.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,22 @@ Lens never sends a reply on its own.
It works on any email Lens has imported: mail that a watched [Gmail or IMAP mailbox](processing.md#gmail-and-google-workspace) brought in, or an
`.eml` file you uploaded. It needs a language model (Settings › LLM provider).

## The Replies page

**Replies**, in the web app's menu while any email waits for an answer, lists that email, newest first, with the one
you were linked to (`/replies?email=42`, or **Reply to this email…** in an email's More actions menu) at the top. The
first email's field has focus: type what the reply should say, or nothing, and press Enter to draft it.

A draft shows under its email with To, Cc and Subject to change, and its sources below it, each `[n]` linking to the
moment or page it came from. What's left to confirm is said under the text. **Open in your mail app** starts the reply
in your own mail app, without its citations, for you to send; **Copy** copies the same text. Ctrl+Enter (⌘+Enter)
saves an edit, which Undo takes back. **Reply to all** adds who else the email was for to Cc. **Set aside** takes it
off the list at once, with Undo instead of a question; **Draft again…** writes a new one, with what it should say.
Viewers read the drafts; editors of the email's namespace draft and change them.

## Drafting a reply

Ask for one email's reply through the API or MCP, with what it should say if you like ("say yes, Tuesday works"):
Ask for one email's reply on the Replies page, or through the API or MCP, with what it should say if you like ("say yes, Tuesday works"):

```bash
curl -X POST "$LENS/api/v1/recordings/42/reply" -H "Authorization: Bearer $TOKEN" \
Expand Down Expand Up @@ -84,6 +97,6 @@ excerpt the model wasn't given is taken out. The draft says only what the email'

## Refine later

- Send a reply through the mailbox it came in to, after your yes, and a Replies page in the web app (in progress).
- Send a reply through the mailbox it came in to, after your yes (in progress).
- A signature in Settings; a decision model choosing which mail needs an answer; drafts from a whole thread rather than
its newest message; replies with attachments.
2 changes: 2 additions & 0 deletions docs/requirements.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,8 @@ request, to another check that proves the same thing; loosening a requirement or
| Drafts edited, set aside and brought back, the text before kept; the mail that waits for an answer listed, not mailing lists' | [test_replies.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_replies.py) `test_editing_setting_aside_and_listing` |
| A pipeline's reply step drafts each new email, skipping mailing lists, no-reply senders and the person's own mail without a model call | [test_replies.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_replies.py) `test_a_pipeline_drafts_only_mail_to_answer` |
| Agents list what waits, draft with instructions, read and edit replies through MCP | [test_replies.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_replies.py) `test_agents_draft_read_and_edit_replies` |
| The Replies page drafts the first email's reply with Enter from its focused field, shows a draft with its sources and what's left to confirm, and opens it in your mail app without citations | [replies-page.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/replies-page.test.tsx) `drafts a reply from the first field with Enter, saying what it should say`; [replies-page.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/replies-page.test.tsx) `shows a draft with its sources and what's left to confirm, and opens it in your mail app` |
| Drafts edited on the page (Ctrl+Enter saves, addresses checked) and set aside at once with Undo instead of a question | [replies-page.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/replies-page.test.tsx) `saves an edit with Ctrl+Enter, and won't save an address that isn't one`; [replies-page.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/replies-page.test.tsx) `sets a draft aside at once, with Undo instead of a question` |

## Work toward a goal in projects

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

import { Replies } from "@/app/openapi-client";
import type { Reply, ReplyEmail } from "@/app/openapi-client/types.gen";
import { NAV } from "@/components/app-shell/nav-config";
import { addresses, isEmail, mailtoHref, plainText, sourceHref, unconfirmed } from "@/components/replies/model";
import { RepliesPage } from "@/components/replies/replies-page";
import { ToastProvider } from "@/components/ui/toast";
import { TooltipProvider } from "@/components/ui/tooltip";

jest.mock("@/app/openapi-client", () => ({
Replies: { listReplies: jest.fn(), getReply: jest.fn(), draftReply: jest.fn(), editReply: jest.fn() },
}));
let search = "";
jest.mock("next/navigation", () => ({
useRouter: () => ({ push: jest.fn(), replace: jest.fn() }),
usePathname: () => "/replies",
useSearchParams: () => new URLSearchParams(search),
}));
jest.mock("next-auth/react", () => ({ useSession: () => ({ data: { accessToken: "t" } }) }));
let editor = true;
jest.mock("@/lib/hooks/session", () => ({
...jest.requireActual("@/lib/hooks/session"),
useArchive: () => ({ namespace: null, can: () => editor }),
}));

const ok = (data: unknown) => Promise.resolve({ data, response: { ok: true, status: 200 } });
const m = (f: unknown) => f as jest.Mock;

const DRAFT: Reply = {
status: "draft",
to: ["mara@example.org"],
cc: [],
others: ["tom@example.org"],
from: "me@example.org",
subject: "Re: Harbour report",
text: "Hi Mara,\n\nThe ships arrived at dawn [1]. We can meet on [to confirm: the date].",
gaps: ["the date to meet"],
unconfirmed: 1,
sources: [
{
n: 1,
recording_id: 3,
title: "keeper's log",
time: "0:01",
t0: 1000,
text: "The ships arrived at dawn.",
used: true,
},
],
drafted_at: "2026-10-18T06:00:00Z",
};

function email(id: number, reply: Reply = { status: "none" }, over: Partial<ReplyEmail> = {}): ReplyEmail {
return {
recording: id,
subject: `Harbour report ${id}`,
sender: "Mara <mara@example.org>",
from: "mara@example.org",
namespace: "pods",
received_at: "2026-10-17T10:00:00Z",
snippet: "When did the ships arrive?",
reply,
...over,
};
}

let emails: ReplyEmail[] = [];
function serve() {
m(Replies.listReplies).mockImplementation(() =>
ok({ emails, drafts: emails.filter((e) => e.reply.status === "draft").length }),
);
m(Replies.draftReply).mockImplementation(({ path }: { path: { rid: number } }) => {
emails = emails.map((e) => (e.recording === path.rid ? { ...e, reply: { status: "drafting", job: 9 } } : e));
return ok({ job: 9 });
});
m(Replies.editReply).mockImplementation(
({ path, body }: { path: { rid: number }; body: Record<string, unknown> }) => {
emails = emails.map((e) =>
e.recording === path.rid
? { ...e, reply: { ...e.reply, ...body, updated_at: new Date().toISOString() } as Reply }
: e,
);
return ok(emails.find((e) => e.recording === path.rid)?.reply);
},
);
}

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

beforeEach(() => {
search = "";
editor = true;
emails = [email(1), email(2, DRAFT)];
jest.clearAllMocks();
serve();
});

describe("the replies page", () => {
it("drafts a reply from the first field with Enter, saying what it should say", async () => {
wrap(<RepliesPage />);
const say = await screen.findByRole("textbox", { name: "What the reply should say" });
expect(say).toHaveFocus();
expect(screen.getByText("2 emails wait for an answer, 1 draft ready")).toBeInTheDocument();
fireEvent.change(say, { target: { value: "Say Tuesday works." } });
fireEvent.submit(say.closest("form") as HTMLFormElement);
await waitFor(() =>
expect(Replies.draftReply).toHaveBeenCalledWith(
expect.objectContaining({ path: { rid: 1 }, body: { instructions: "Say Tuesday works." } }),
),
);
expect(await screen.findByText("Drafting a reply from your archive…")).toBeInTheDocument();
});

it("shows a draft with its sources and what's left to confirm, and opens it in your mail app", async () => {
wrap(<RepliesPage />);
const card = await screen.findByRole("article", { name: "Harbour report 2" });
expect(within(card).getByText("Draft ready, 1 to confirm")).toBeInTheDocument();
expect(within(card).getByRole("link", { name: "keeper's log, 0:01" })).toHaveAttribute("href", "/resources/3?t=1");
expect(within(card).getByText(/the archive doesn’t say the date to meet/)).toBeInTheDocument();
const open = within(card).getByRole("link", { name: "Open in your mail app" });
expect(open.getAttribute("href")).toMatch(/^mailto:mara%40example\.org\?subject=Re%3A%20Harbour%20report&body=/);
expect(decodeURIComponent(open.getAttribute("href") as string)).not.toContain("[1]");
// reply to all puts the email's other recipients in Cc
fireEvent.click(within(card).getByRole("button", { name: "Reply to all" }));
expect(within(card).getByLabelText("Cc")).toHaveValue("tom@example.org");
});

it("saves an edit with Ctrl+Enter, and won't save an address that isn't one", async () => {
wrap(<RepliesPage />);
const card = await screen.findByRole("article", { name: "Harbour report 2" });
fireEvent.change(within(card).getByLabelText("To"), { target: { value: "not-an-address" } });
expect(within(card).getByRole("alert")).toHaveTextContent("“not-an-address” isn’t an email address.");
expect(within(card).getByRole("button", { name: "Save" })).toBeDisabled();
fireEvent.change(within(card).getByLabelText("To"), { target: { value: "mara@example.org" } });
const text = within(card).getByRole("textbox", { name: "The reply" });
fireEvent.change(text, { target: { value: "Hi Mara, Tuesday it is [1]." } });
fireEvent.keyDown(text, { key: "Enter", ctrlKey: true });
await waitFor(() =>
expect(Replies.editReply).toHaveBeenCalledWith(
expect.objectContaining({
path: { rid: 2 },
body: {
text: "Hi Mara, Tuesday it is [1].",
subject: "Re: Harbour report",
to: ["mara@example.org"],
cc: [],
},
}),
),
);
expect(await screen.findByText("Draft saved")).toBeInTheDocument();
});

it("sets a draft aside at once, with Undo instead of a question", async () => {
wrap(<RepliesPage />);
const card = await screen.findByRole("article", { name: "Harbour report 2" });
fireEvent.click(within(card).getByRole("button", { name: "Set aside" }));
await waitFor(() => expect(screen.queryByRole("article", { name: "Harbour report 2" })).not.toBeInTheDocument());
expect(Replies.editReply).toHaveBeenCalledWith(expect.objectContaining({ body: { status: "dismissed" } }));
fireEvent.click(await screen.findByRole("button", { name: "Undo" }));
await waitFor(() =>
expect(Replies.editReply).toHaveBeenLastCalledWith(expect.objectContaining({ body: { status: "draft" } })),
);
expect(await screen.findByRole("article", { name: "Harbour report 2" })).toBeInTheDocument();
});

it("brings the email it was sent for first, and viewers read without acting", async () => {
search = "email=2";
editor = false;
wrap(<RepliesPage />);
const cards = await screen.findAllByRole("article");
expect(cards[0]).toHaveAccessibleName("Harbour report 2");
expect(within(cards[0]).getByRole("textbox", { name: "The reply" })).toBeDisabled();
expect(within(cards[0]).queryByRole("button", { name: "Save" })).not.toBeInTheDocument();
expect(within(cards[1]).getByRole("button", { name: "Draft a reply" })).toHaveAttribute("aria-disabled", "true");
});

it("says where mail comes from when none waits", async () => {
emails = [];
wrap(<RepliesPage />);
expect(await screen.findByText("No email waits for an answer")).toBeInTheDocument();
expect(screen.getByRole("link", { name: "Watch a mailbox" })).toHaveAttribute("href", "/sources");
});
});

describe("the replies model", () => {
it("strips citations as the backend does, and counts what's left to confirm", () => {
expect(plainText("Hi [1]. Ships at dawn [2] , fog [3]!")).toBe("Hi. Ships at dawn, fog!");
expect(unconfirmed("On [to confirm: the date] at [To confirm: the time].")).toBe(2);
});

it("reads typed addresses and builds a mail app link", () => {
expect(addresses("a@x.io, b@y.org;c@z.net")).toEqual({ list: ["a@x.io", "b@y.org", "c@z.net"], wrong: null });
expect(addresses("a@x.io, nope").wrong).toBe("nope");
expect(mailtoHref({ to: ["a@x.io"], cc: ["b@y.org"], subject: "Re: Hi", text: "Yes [1]." })).toBe(
"mailto:a%40x.io?cc=b%40y.org&subject=Re%3A%20Hi&body=Yes.",
);
});

it("links a document's source to its page and anything else to its moment", () => {
expect(sourceHref({ recording_id: 4, page: 2, t0: 0 })).toBe("/resources/4?page=3");
expect(sourceHref({ recording_id: 4, page: null, t0: 61000 })).toBe("/resources/4?t=61");
});

it("knows an email resource, and the nav has Replies only while email waits", () => {
expect(isEmail({ email: { subject: "Hi" } })).toBe(true);
expect(isEmail({ path: "in/hello.EML" })).toBe(true);
expect(isEmail({ path: "talk.mp3" })).toBe(false);
expect(NAV.find((i) => i.href === "/replies")).toMatchObject({ countKey: "replies", whileCounted: true });
});
});
15 changes: 15 additions & 0 deletions nextjs-frontend/app/(app)/replies/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import type { Metadata } from "next";
import { Suspense } from "react";

import { RepliesPage } from "@/components/replies/replies-page";

export const metadata: Metadata = { title: "Replies" };

/** Email that may need an answer, each with its cited draft (backend: GET /api/v1/replies, docs/email-replies.md). */
export default function Page() {
return (
<Suspense>
<RepliesPage />
</Suspense>
);
}
3 changes: 3 additions & 0 deletions nextjs-frontend/components/app-shell/app-shell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { useApprovalCount } from "@/components/approvals/use-approvals";
import { BudgetMeter } from "@/components/costs/budget-meter";
import { WelcomeTour } from "@/components/home/welcome-tour";
import { PageChat } from "@/components/page-chat/page-chat";
import { useReplyCount } from "@/components/replies/use-replies";
import { SimilarOnSelect } from "@/components/similar/selection-popover";
import { Button, IconButton } from "@/components/ui/button";
import { EmptyState, Skeleton } from "@/components/ui/states";
Expand Down Expand Up @@ -122,11 +123,13 @@ export function AppShell({ user, children }: { user: SessionUser; children: Reac
queryFn: () => data(Feeds.listFeeds({ client })),
staleTime: 60_000,
});
const replies = useReplyCount();
const counts = {
recordings,
reviews: reviews.data,
approvals: approvals.data?.waiting || undefined,
feeds: feeds.data?.length || undefined,
replies: replies.data || undefined,
};
const canImport = can("editor", namespace);

Expand Down
7 changes: 5 additions & 2 deletions nextjs-frontend/components/app-shell/nav-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
NotebookPen,
Podcast,
RadioTower,
Reply,
Rss,
Search,
Settings,
Expand All @@ -32,8 +33,8 @@ export type NavItem = {
adminOnly?: boolean;
/** Only shown to people who aren't administrators (admins have it under another item). */
membersOnly?: boolean;
/** A count shown next to the label (library size, speakers to review in Settings, approvals waiting). */
countKey?: "recordings" | "reviews" | "approvals" | "feeds";
/** A count shown next to the label (library size, speakers to review in Settings, approvals and email waiting). */
countKey?: "recordings" | "reviews" | "approvals" | "feeds" | "replies";
/** Shown only while its count is above zero, or while its page is open, so the nav of a Lens with nothing there
* stays as short as it was (on a phone, every item more pushes the ones below off the screen). */
whileCounted?: boolean;
Expand All @@ -57,6 +58,8 @@ export const NAV: NavItem[] = [
{ label: "Search", href: "/search", icon: Search, group: "" },
{ label: "Chat", href: "/chat", icon: MessagesSquare, group: "" },
{ label: "Notes", href: "/notes", icon: NotebookPen, group: "" },
// email that may need an answer: in the nav while any does, so a Lens that reads no mail doesn't show it
{ label: "Replies", href: "/replies", icon: Reply, countKey: "replies", whileCounted: true, group: "" },
{ label: "Timeline", href: "/timeline", icon: History, group: "Explore" },
{ label: "Entities", href: "/entities", icon: Shapes, group: "Explore" },
{ label: "Topics", href: "/topics", icon: Tags, group: "Explore" },
Expand Down
2 changes: 1 addition & 1 deletion nextjs-frontend/components/app-shell/nav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export function Nav({
admin: boolean;
collapsed: boolean;
onToggle?: () => void;
counts: { recordings?: number; reviews?: number; approvals?: number; feeds?: number };
counts: { recordings?: number; reviews?: number; approvals?: number; feeds?: number; replies?: number };
onNavigate?: () => void;
className?: string;
top?: ReactNode;
Expand Down
Loading
Loading