From 10c735a91f13b82bf9e9cb6fefe787f8d479020b Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Sun, 18 Oct 2026 06:53:30 +0000 Subject: [PATCH] feat(replies): a Replies page to draft, edit and copy email replies The email that waits for an answer, in the nav while any does: Enter drafts the first one's reply, a draft shows with To, Cc, Subject, its sources and what's left to confirm, and Open in your mail app or Copy takes it without citations. Ctrl+Enter saves an edit with Undo; Set aside offers Undo. An email's More actions menu links to it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Xa7Hz2SLg6sNrGksMEzBaz --- README.md | 7 +- changelog.d/replies-page.md | 4 + docs/email-replies.md | 17 +- docs/requirements.md | 2 + .../__tests__/replies-page.test.tsx | 224 +++++++++ nextjs-frontend/app/(app)/replies/page.tsx | 15 + .../components/app-shell/app-shell.tsx | 3 + .../components/app-shell/nav-config.ts | 7 +- nextjs-frontend/components/app-shell/nav.tsx | 2 +- .../components/recording/header.tsx | 10 + nextjs-frontend/components/replies/model.ts | 81 ++++ .../components/replies/replies-page.tsx | 454 ++++++++++++++++++ .../components/replies/use-replies.ts | 28 ++ 13 files changed, 846 insertions(+), 8 deletions(-) create mode 100644 changelog.d/replies-page.md create mode 100644 nextjs-frontend/__tests__/replies-page.test.tsx create mode 100644 nextjs-frontend/app/(app)/replies/page.tsx create mode 100644 nextjs-frontend/components/replies/model.ts create mode 100644 nextjs-frontend/components/replies/replies-page.tsx create mode 100644 nextjs-frontend/components/replies/use-replies.ts diff --git a/README.md b/README.md index ade2e069c..49f6d85e2 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/changelog.d/replies-page.md b/changelog.d/replies-page.md new file mode 100644 index 000000000..9a25b4c0e --- /dev/null +++ b/changelog.d/replies-page.md @@ -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…. diff --git a/docs/email-replies.md b/docs/email-replies.md index 1e4a736c2..6c17bcca4 100644 --- a/docs/email-replies.md +++ b/docs/email-replies.md @@ -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" \ @@ -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. diff --git a/docs/requirements.md b/docs/requirements.md index 15e25fea6..b9e5c2e31 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -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 diff --git a/nextjs-frontend/__tests__/replies-page.test.tsx b/nextjs-frontend/__tests__/replies-page.test.tsx new file mode 100644 index 000000000..1e8714266 --- /dev/null +++ b/nextjs-frontend/__tests__/replies-page.test.tsx @@ -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 { + return { + recording: id, + subject: `Harbour report ${id}`, + sender: "Mara ", + 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 }) => { + 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( + + + {ui} + + , + ); +} + +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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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 }); + }); +}); diff --git a/nextjs-frontend/app/(app)/replies/page.tsx b/nextjs-frontend/app/(app)/replies/page.tsx new file mode 100644 index 000000000..4df070d5b --- /dev/null +++ b/nextjs-frontend/app/(app)/replies/page.tsx @@ -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 ( + + + + ); +} diff --git a/nextjs-frontend/components/app-shell/app-shell.tsx b/nextjs-frontend/components/app-shell/app-shell.tsx index 2462fee88..f1796cdfc 100644 --- a/nextjs-frontend/components/app-shell/app-shell.tsx +++ b/nextjs-frontend/components/app-shell/app-shell.tsx @@ -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"; @@ -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); diff --git a/nextjs-frontend/components/app-shell/nav-config.ts b/nextjs-frontend/components/app-shell/nav-config.ts index f3dcdd93b..8b99a00ec 100644 --- a/nextjs-frontend/components/app-shell/nav-config.ts +++ b/nextjs-frontend/components/app-shell/nav-config.ts @@ -11,6 +11,7 @@ import { NotebookPen, Podcast, RadioTower, + Reply, Rss, Search, Settings, @@ -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; @@ -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" }, diff --git a/nextjs-frontend/components/app-shell/nav.tsx b/nextjs-frontend/components/app-shell/nav.tsx index 842874a4c..d3609038a 100644 --- a/nextjs-frontend/components/app-shell/nav.tsx +++ b/nextjs-frontend/components/app-shell/nav.tsx @@ -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; diff --git a/nextjs-frontend/components/recording/header.tsx b/nextjs-frontend/components/recording/header.tsx index 610149f77..97d95c28c 100644 --- a/nextjs-frontend/components/recording/header.tsx +++ b/nextjs-frontend/components/recording/header.tsx @@ -24,6 +24,7 @@ import { Pencil, Podcast, RefreshCw, + Reply, RotateCw, ScrollText, Workflow, @@ -51,6 +52,7 @@ import { Tooltip } from "@/components/ui/tooltip"; import { absolute, shortDate, tc } from "@/lib/format"; import { EXPORTS, failureImpact, sourceLabel } from "@/components/recording/labels"; import { specAction } from "@/components/recording/spec-model"; +import { isEmail } from "@/components/replies/model"; import { needRole } from "@/lib/hooks/session"; import { cn } from "@/lib/utils"; @@ -429,6 +431,14 @@ function MoreMenu({ compact }: { compact?: boolean }) { } disabled={sa.disabled} onSelect={startSpec}> {sa.write} + {isEmail(r.rec) && ( + + + + Reply to this email… + + + )} {compact && ( <> {!r.paged && ( diff --git a/nextjs-frontend/components/replies/model.ts b/nextjs-frontend/components/replies/model.ts new file mode 100644 index 000000000..17fa556ea --- /dev/null +++ b/nextjs-frontend/components/replies/model.ts @@ -0,0 +1,81 @@ +import type { Reply, ReplyEmail, ReplySource } from "@/app/openapi-client/types.gen"; +import { recordingHref } from "@/components/search/links"; + +/** A draft's citations, as the backend writes them (responder.CITE_RX). */ +const CITE_RX = /\s?\[(\d+)\]/g; +const CONFIRM_RX = /\[to confirm:[^\]\n]*\]/gi; +const ADDRESS_RX = /^[^\s@<>,;]+@[^\s@<>,;]+\.[^\s@<>,;]+$/; + +/** The draft as it would be sent: without its citations (they open your archive, which the person you answer can't); + * what responder.plain does, so Copy and the mail app get what the API's `plain` would say for an edit not saved yet. */ +export function plainText(text: string): string { + return text + .replace(CITE_RX, "") + .replace(/[ \t]+([.,;:!?])/g, "$1") + .trim(); +} + +/** How many "[to confirm: …]" marks are still in the draft. */ +export function unconfirmed(text: string): number { + return (text.match(CONFIRM_RX) ?? []).length; +} + +/** The addresses typed in a To or Cc box ("a@x.io, b@y.org"), and the first that isn't one. */ +export function addresses(typed: string): { list: string[]; wrong: string | null } { + const list = typed + .split(/[,;\s]+/) + .map((a) => a.trim()) + .filter(Boolean); + return { list, wrong: list.find((a) => !ADDRESS_RX.test(a)) ?? null }; +} + +/** Your mail app, with the reply in it: the plain text, to, cc and subject. Sending it is yours. */ +export function mailtoHref(r: { to: string[]; cc: string[]; subject: string; text: string }): string { + const q = [ + r.cc.length ? `cc=${encodeURIComponent(r.cc.join(","))}` : "", + `subject=${encodeURIComponent(r.subject)}`, + `body=${encodeURIComponent(plainText(r.text))}`, + ].filter(Boolean); + return `mailto:${r.to.map(encodeURIComponent).join(",")}?${q.join("&")}`; +} + +/** Where a source opens in the archive: a document's page, or a moment. */ +export function sourceHref(s: Pick): string { + return s.page != null ? `/resources/${s.recording_id}?page=${s.page + 1}` : recordingHref(s.recording_id, s.t0); +} + +/** A job is on it, so the page looks again until it's done. */ +export function busy(r: Pick | undefined): boolean { + return r?.status === "drafting"; +} + +/** The email asked for first (`?email=`), then the rest, newest first, as listed. */ +export function ordered(emails: ReplyEmail[], first: number | null, hidden: Set): ReplyEmail[] { + const left = emails.filter((e) => !hidden.has(e.recording)); + return first ? [...left.filter((e) => e.recording === first), ...left.filter((e) => e.recording !== first)] : left; +} + +/** Whether a resource is an email Lens can draft a reply to (responder.is_email). */ +export function isEmail(rec: { email?: unknown; mail?: unknown; path?: string | null } | undefined): boolean { + return Boolean(rec && (rec.email || rec.mail || /\.eml$/i.test(rec.path ?? ""))); +} + +/** One line on where a reply stands, under its email. */ +export function statusLine(r: Reply): string { + switch (r.status) { + case "drafting": + return "Drafting a reply from your archive…"; + case "failed": + return `Couldn’t draft it${r.error ? `: ${r.error}` : "."}`; + case "skipped": + return `Not drafted, as mail not to answer${r.why ? ` (${r.why})` : ""}.`; + case "dismissed": + return "Set aside."; + case "sent": + return "Sent."; + case "draft": + return r.unconfirmed ? `Draft ready, ${r.unconfirmed} to confirm` : "Draft ready"; + default: + return "No reply yet"; + } +} diff --git a/nextjs-frontend/components/replies/replies-page.tsx b/nextjs-frontend/components/replies/replies-page.tsx new file mode 100644 index 000000000..de0c6c30c --- /dev/null +++ b/nextjs-frontend/components/replies/replies-page.tsx @@ -0,0 +1,454 @@ +"use client"; + +import { useMutation, useQuery } from "@tanstack/react-query"; +import { Copy, Mail, Reply as ReplyIcon, RotateCw, Undo2 } from "lucide-react"; +import Link from "next/link"; +import { useSearchParams } from "next/navigation"; +import { useCallback, useMemo, useState, type FormEvent, type KeyboardEvent } from "react"; + +import { Replies } from "@/app/openapi-client"; +import type { Reply, ReplyEdit, ReplyEmail } from "@/app/openapi-client/types.gen"; +import { + addresses, + busy, + mailtoHref, + ordered, + plainText, + sourceHref, + statusLine, + unconfirmed, +} from "@/components/replies/model"; +import { REPLIES_KEY, useRepliesChanged } from "@/components/replies/use-replies"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Input, Textarea } from "@/components/ui/field"; +import { DateTime, EmptyState, PageHeader, SkeletonRows } from "@/components/ui/states"; +import { useToast } from "@/components/ui/toast"; +import { ApiError, data, useApiClient } from "@/lib/api/browser"; +import { plural } from "@/lib/format"; +import { needRole, useArchive } from "@/lib/hooks/session"; + +/** How long the notice that offers Undo stays. */ +export const UNDO_MS = 6000; + +const why = (e: unknown) => (e instanceof ApiError ? e.message : "Please try again."); + +/** Email replies (docs/email-replies.md): the mail that may need an answer, newest first, each with its draft. A draft + * is written from your archive, cited [n] to the excerpts below it, with what the archive doesn't say marked to + * confirm; you edit it, copy it or open it in your mail app. Lens sends nothing. `?email=` brings that email first. */ +export function RepliesPage() { + const client = useApiClient(); + const toast = useToast(); + const changed = useRepliesChanged(); + const asked = Number(useSearchParams().get("email")) || null; + const { namespace } = useArchive(); + + const list = useQuery({ + queryKey: [...REPLIES_KEY, "list", namespace], + queryFn: () => data(Replies.listReplies({ client, query: { limit: 200, ...(namespace ? { namespace } : {}) } })), + refetchInterval: (q) => (q.state.data?.emails.some((e) => busy(e.reply)) ? 3000 : false), + }); + const inList = Boolean(asked && list.data?.emails.some((e) => e.recording === asked)); + // the email you were sent here for, when it isn't one that waits (set aside, automatic, sent) + const one = useQuery({ + queryKey: [...REPLIES_KEY, "one", asked], + enabled: asked != null && list.isSuccess && !inList, + queryFn: () => data(Replies.getReply({ client, path: { rid: asked as number } })), + refetchInterval: (q) => (busy(q.state.data) ? 3000 : false), + retry: false, + }); + + const [hidden, setHidden] = useState>(() => new Set()); + const hide = useCallback((id: number, on: boolean) => { + setHidden((h) => { + const out = new Set(h); + if (on) out.add(id); + else out.delete(id); + return out; + }); + }, []); + // set aside at once, out of the list, with Undo (which brings it back as a draft) instead of a question; done here, + // not in the card, which leaves the page as it's hidden + const setAside = useCallback( + (e: ReplyEmail) => { + const edit = (status: "draft" | "dismissed") => + data(Replies.editReply({ client, path: { rid: e.recording }, body: { status } })); + hide(e.recording, true); + edit("dismissed") + .then(changed) + .catch((err: unknown) => { + hide(e.recording, false); + toast({ tone: "red", title: "Couldn’t set it aside", body: why(err) }); + }); + toast({ + title: `Set aside “${e.subject || "the email"}”`, + body: "It isn’t waiting any more.", + duration: UNDO_MS, + action: { + label: "Undo", + onClick: () => + void edit("draft") + .then(() => { + hide(e.recording, false); + changed(); + }) + .catch((err: unknown) => toast({ tone: "red", title: "Couldn’t bring it back", body: why(err) })), + }, + }); + }, + [client, changed, hide, toast], + ); + + const emails = useMemo(() => { + const all = list.data?.emails ?? []; + const extra: ReplyEmail[] = + asked && !inList && one.data + ? [ + { + recording: asked, + subject: (one.data.subject ?? "").replace(/^\s*re\s*:\s*/i, ""), + from: one.data.to?.[0] ?? null, + reply: one.data, + }, + ] + : []; + return ordered([...extra, ...all], asked, hidden); + }, [list.data, asked, inList, one.data, hidden]); + const drafts = list.data?.drafts ?? 0; + + return ( +
+ +

+ Drafts are written from your archive, each fact cited to where it came from. Nothing is sent: copy a draft, or + open it in your mail app. +

+
+ {list.isPending ? ( + + ) : list.isError ? ( + + {list.error.message} + + ) : emails.length === 0 ? ( + } title="No email waits for an answer"> + Email a watched Gmail or IMAP mailbox brings in shows here, with a reply drafted when you ask for one.{" "} + + Watch a mailbox + + + ) : ( +
    + {emails.map((e, i) => ( +
  • + +
  • + ))} +
+ )} +
+ ); +} + +function EmailCard({ e, first, onSetAside }: { e: ReplyEmail; first: boolean; onSetAside: (e: ReplyEmail) => void }) { + const client = useApiClient(); + const toast = useToast(); + const changed = useRepliesChanged(); + const { can } = useArchive(); + const canAct = can("editor", e.namespace); + const r = e.reply; + const [say, setSay] = useState(""); + const [again, setAgain] = useState(false); + + const draft = useMutation({ + mutationFn: (instructions: string) => + data( + Replies.draftReply({ + client, + path: { rid: e.recording }, + body: instructions.trim() ? { instructions: instructions.trim() } : {}, + }), + ), + onSuccess: () => { + setSay(""); + setAgain(false); + changed(); + }, + onError: (err) => toast({ tone: "red", title: "Couldn’t draft a reply", body: why(err) }), + }); + const edit = useMutation({ + mutationFn: (body: ReplyEdit) => data(Replies.editReply({ client, path: { rid: e.recording }, body })), + onSuccess: changed, + }); + + const ask = (ev: FormEvent) => { + ev.preventDefault(); + if (canAct && !draft.isPending) draft.mutate(say); + }; + const drafted = r.status === "draft" || r.status === "dismissed" || r.status === "sent"; + const asking = drafted ? again : r.status !== "drafting"; + + return ( +
+
+
+ + {e.subject || "(no subject)"} + + {e.automatic && {e.automatic}} +
+

+ {e.sender || e.from || "Unknown sender"} + {e.namespace && · {e.namespace}} + {e.received_at && ( + + · + + )} +

+ {e.snippet &&

{e.snippet}

} +
+ + {r.status !== "none" && ( +

+ {statusLine(r)} +

+ )} + + {drafted && } + + {asking && ( +
+ setSay(ev.target.value)} + disabled={!canAct} + autoFocus={first && !drafted} + className="sm:flex-1" + /> + +
+ )} + + {(drafted || r.status === "drafting" || r.status === "failed") && canAct && ( +
+ {drafted && !again && ( + + )} + {r.status !== "dismissed" && ( + + )} + {r.status === "dismissed" && ( + + )} +
+ )} +
+ ); +} + +function DraftEditor({ + e, + r, + canAct, + edit, +}: { + e: ReplyEmail; + r: Reply; + canAct: boolean; + edit: { + mutate: (b: ReplyEdit, o?: { onSuccess?: (r: Reply) => void; onError?: (e: Error) => void }) => void; + isPending: boolean; + }; +}) { + const toast = useToast(); + const [to, setTo] = useState((r.to ?? []).join(", ")); + const [cc, setCc] = useState((r.cc ?? []).join(", ")); + const [subject, setSubject] = useState(r.subject ?? ""); + const [text, setText] = useState(r.text ?? ""); + const toList = addresses(to); + const ccList = addresses(cc); + const wrong = toList.wrong ?? ccList.wrong; + const dirty = + text !== (r.text ?? "") || + subject !== (r.subject ?? "") || + toList.list.join(",") !== (r.to ?? []).join(",") || + ccList.list.join(",") !== (r.cc ?? []).join(","); + const left = unconfirmed(text); + const others = (r.others ?? []).filter((a) => !ccList.list.includes(a) && !toList.list.includes(a)); + + const save = () => { + if (!dirty || wrong || !canAct) return; + const before = r.text ?? ""; + edit.mutate( + { text, subject, to: toList.list, cc: ccList.list }, + { + onSuccess: () => + toast({ + tone: "green", + title: "Draft saved", + duration: UNDO_MS, + action: text !== before ? { label: "Undo", onClick: () => edit.mutate({ text: before }) } : undefined, + }), + onError: (err) => toast({ tone: "red", title: "Couldn’t save the draft", body: why(err) }), + }, + ); + }; + const copy = async () => { + try { + await navigator.clipboard.writeText(plainText(text)); + toast({ tone: "green", title: "Reply copied", body: "Without its citations, as it would be sent." }); + } catch { + toast({ tone: "red", title: "Couldn’t copy" }); + } + }; + const keys = (ev: KeyboardEvent) => { + if (ev.key === "Enter" && (ev.metaKey || ev.ctrlKey)) { + ev.preventDefault(); + save(); + } + }; + const cited = new Set(Array.from(text.matchAll(/\[(\d+)\]/g), (m) => Number(m[1]))); + + return ( +
+
+ + setTo(ev.target.value)} + invalid={Boolean(toList.wrong)} + disabled={!canAct} + className="h-9" + /> + + setCc(ev.target.value)} + invalid={Boolean(ccList.wrong)} + disabled={!canAct} + className="h-9" + /> + + setSubject(ev.target.value)} + disabled={!canAct} + className="h-9" + /> +
+ {others.length > 0 && canAct && ( +

+ Also sent to {others.join(", ")}.{" "} + +

+ )} + {wrong && ( +

+ “{wrong}” isn’t an email address. +

+ )} +