From f8da9d3b618e8a9acb5920caca1e5f06335f2352 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Mon, 5 Oct 2026 09:59:07 +0000 Subject: [PATCH] feat(web): edit an email watch's routing rules, with a preview The watch dialog for an email account gains a Routing rules section: rules with conditions on sender, recipient, subject, list or mailbox, sent to a namespace or skipped, reordered and removed in place. Below them, where the latest messages would go under the rules as they stand. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01V3JT2ET8A1tXFMdidgek2S --- .../__tests__/mail-routes.test.tsx | 100 +++++++++ .../components/sources/route-model.ts | 64 ++++++ .../components/sources/routing-rules.tsx | 198 ++++++++++++++++++ .../components/sources/sources-page.tsx | 4 +- .../components/sources/watch-editor.tsx | 25 ++- 5 files changed, 386 insertions(+), 5 deletions(-) create mode 100644 nextjs-frontend/__tests__/mail-routes.test.tsx create mode 100644 nextjs-frontend/components/sources/route-model.ts create mode 100644 nextjs-frontend/components/sources/routing-rules.tsx diff --git a/nextjs-frontend/__tests__/mail-routes.test.tsx b/nextjs-frontend/__tests__/mail-routes.test.tsx new file mode 100644 index 000000000..8e2c38e61 --- /dev/null +++ b/nextjs-frontend/__tests__/mail-routes.test.tsx @@ -0,0 +1,100 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import "@testing-library/jest-dom"; +import { useState } from "react"; + +import { Sources } from "@/app/openapi-client"; +import { + blankRule, + move, + type RuleForm, + ruleProblem, + rulesFromWatch, + rulesToApi, + SKIP, +} from "@/components/sources/route-model"; +import { RoutingRules } from "@/components/sources/routing-rules"; +import { TooltipProvider } from "@/components/ui/tooltip"; + +jest.mock("@/app/openapi-client", () => ({ Sources: { previewRoutes: jest.fn() } })); +jest.mock("next-auth/react", () => ({ useSession: () => ({ data: { accessToken: "t" } }) })); + +const ok = (data: unknown) => Promise.resolve({ data, response: { ok: true, status: 200 } }); + +describe("routing rules model", () => { + it("round-trips saved rules, skips and deleted namespaces", () => { + const form = rulesFromWatch([ + { match: { from: ["*@acme.com", "boss@"], subject: ["invoice"] }, namespace: "finance", skip: false }, + { match: { list: ["news"] }, namespace: null, skip: true }, + { match: { to: ["support@"] }, namespace: null, skip: false }, // its namespace was deleted + ]); + expect(form[0].conditions).toEqual([ + { field: "from", patterns: "*@acme.com, boss@" }, + { field: "subject", patterns: "invoice" }, + ]); + expect(form[1].target).toBe(SKIP); + expect(ruleProblem(form[2])).toBe("Choose a namespace, or skip."); + expect(rulesToApi(form.slice(0, 2))).toEqual([ + { match: { from: ["*@acme.com", "boss@"], subject: ["invoice"] }, namespace: "finance" }, + { match: { list: ["news"] }, skip: true }, + ]); + }); + + it("needs a pattern, and moves rules within bounds", () => { + expect(ruleProblem(blankRule("finance"))).toBe("Add a pattern to match."); + expect(move([1, 2, 3], 2, 1)).toEqual([1, 3, 2]); + expect(move([1, 2, 3], 0, -1)).toEqual([1, 2, 3]); + }); +}); + +function Harness({ onRules }: { onRules: (r: RuleForm[]) => void }) { + const [rules, setRules] = useState([]); + return ( + { + setRules(r); + onRules(r); + }} + namespaces={["family", "finance"]} + home="family" + source={3} + path="INBOX" + showProblems + /> + ); +} + +describe("routing rules editor", () => { + it("adds a rule and shows where the latest messages would go", async () => { + (Sources.previewRoutes as jest.Mock).mockReset().mockImplementation(() => + ok([ + { path: "INBOX/7-1.eml", title: "Invoice 2231", namespace: "finance", skipped: false, rule: 1 }, + { path: "INBOX/7-2.eml", title: "Lunch?", namespace: "family", skipped: false, rule: null }, + ]), + ); + const seen = jest.fn(); + render( + + + + + , + ); + fireEvent.click(screen.getByRole("button", { name: "Add a rule" })); + expect(screen.getByRole("alert")).toHaveTextContent("Add a pattern to match."); + expect(screen.getByLabelText("Send to")).toHaveValue("finance"); // another namespace than the watch's + fireEvent.change(screen.getByLabelText("Patterns"), { target: { value: "*@acme.com" } }); + expect(rulesToApi(seen.mock.calls.at(-1)[0])).toEqual([{ match: { from: ["*@acme.com"] }, namespace: "finance" }]); + expect(await screen.findByText("→ finance")).toBeInTheDocument(); + expect(screen.getByText("rule 1")).toBeInTheDocument(); + await waitFor(() => + expect((Sources.previewRoutes as jest.Mock).mock.calls.at(-1)[0].body).toEqual({ + source: 3, + path: "INBOX", + namespace: "family", + routes: [{ match: { from: ["*@acme.com"] }, namespace: "finance" }], + }), + ); + }); +}); diff --git a/nextjs-frontend/components/sources/route-model.ts b/nextjs-frontend/components/sources/route-model.ts new file mode 100644 index 000000000..d6d9a4b3c --- /dev/null +++ b/nextjs-frontend/components/sources/route-model.ts @@ -0,0 +1,64 @@ +import type { Route, RouteView } from "@/app/openapi-client/types.gen"; +import { splitPatterns } from "@/components/sources/source-model"; + +/** What a routing rule can look at in a message, as the backend's mail_routes.FIELDS. */ +export const ROUTE_FIELDS = [ + { value: "from", label: "From", placeholder: "*@acme.com" }, + { value: "to", label: "Sent to", placeholder: "support@harbour.org" }, + { value: "subject", label: "Subject has", placeholder: "invoice, receipt" }, + { value: "list", label: "Mailing list", placeholder: "news.example.org" }, + { value: "mailbox", label: "Mailbox", placeholder: "Projects/*" }, +] as const; +export type RouteField = (typeof ROUTE_FIELDS)[number]["value"]; + +/** "" as a target: skip the message. */ +export const SKIP = ""; + +export type RuleCondition = { field: RouteField; patterns: string }; +export type RuleForm = { key: number; conditions: RuleCondition[]; target: string | null }; + +let next = 1; +const key = () => next++; + +export function blankRule(namespace: string | null = null): RuleForm { + return { key: key(), conditions: [{ field: "from", patterns: "" }], target: namespace }; +} + +/** Saved rules as the editor shows them. A rule whose namespace was deleted has no target until one is chosen. */ +export function rulesFromWatch(routes: RouteView[] | undefined): RuleForm[] { + return (routes ?? []).map((r) => ({ + key: key(), + conditions: Object.entries(r.match).map(([field, patterns]) => ({ + field: field as RouteField, + patterns: patterns.join(", "), + })), + target: r.skip ? SKIP : (r.namespace ?? null), + })); +} + +/** The editor's rules as the API takes them; conditions with no patterns are left out. */ +export function rulesToApi(rules: RuleForm[]): Route[] { + return rules.map((r) => { + const match: Record = {}; + for (const c of r.conditions) { + const p = splitPatterns(c.patterns); + if (p.length) match[c.field] = [...(match[c.field] ?? []), ...p]; + } + return r.target === SKIP ? { match, skip: true } : { match, namespace: r.target }; + }); +} + +/** What's wrong with a rule, or null: it needs a pattern and somewhere to send the mail. */ +export function ruleProblem(rule: RuleForm): string | null { + if (!rule.conditions.some((c) => splitPatterns(c.patterns).length)) return "Add a pattern to match."; + if (rule.target === null) return "Choose a namespace, or skip."; + return null; +} + +export function move(list: T[], from: number, to: number): T[] { + if (to < 0 || to >= list.length) return list; + const out = [...list]; + const [item] = out.splice(from, 1); + out.splice(to, 0, item); + return out; +} diff --git a/nextjs-frontend/components/sources/routing-rules.tsx b/nextjs-frontend/components/sources/routing-rules.tsx new file mode 100644 index 000000000..fbb2bb850 --- /dev/null +++ b/nextjs-frontend/components/sources/routing-rules.tsx @@ -0,0 +1,198 @@ +"use client"; + +import { useQuery } from "@tanstack/react-query"; +import { ArrowDown, ArrowUp, Plus, X } from "lucide-react"; +import { useEffect, useMemo, useState } from "react"; + +import { Sources } from "@/app/openapi-client"; +import { + blankRule, + move, + ROUTE_FIELDS, + type RouteField, + type RuleForm, + ruleProblem, + rulesToApi, + SKIP, +} from "@/components/sources/route-model"; +import { Button, IconButton } from "@/components/ui/button"; +import { Input, Select } from "@/components/ui/field"; +import { data, useApiClient } from "@/lib/api/browser"; + +function useDebounced(value: T, ms: number): T { + const [v, setV] = useState(value); + useEffect(() => { + const t = setTimeout(() => setV(value), ms); + return () => clearTimeout(t); + }, [value, ms]); + return v; +} + +/** An email watch's routing rules: the first rule that matches a new message sends it to a namespace, or skips it; + * the rest go to the watch's own namespace. Below them, where the latest messages would go. */ +export function RoutingRules({ + rules, + onChange, + namespaces, + home, + source, + path, + showProblems, +}: { + rules: RuleForm[]; + onChange: (rules: RuleForm[]) => void; + namespaces: string[]; + home: string; + source: number; + path: string; + showProblems: boolean; +}) { + const client = useApiClient(); + const update = (i: number, r: Partial) => onChange(rules.map((x, j) => (j === i ? { ...x, ...r } : x))); + const setCondition = (i: number, c: number, v: Partial<{ field: RouteField; patterns: string }>) => + update(i, { conditions: rules[i].conditions.map((x, k) => (k === c ? { ...x, ...v } : x)) }); + + const ready = rules.every((r) => !ruleProblem(r)); + const body = useDebounced( + useMemo(() => ({ source, path, namespace: home, routes: rulesToApi(rules) }), [source, path, home, rules]), + 600, + ); + const preview = useQuery({ + queryKey: ["route-preview", body], + queryFn: () => data(Sources.previewRoutes({ client, body })), + enabled: ready && rules.length > 0 && Boolean(home), + staleTime: 60_000, + retry: false, + }); + + const targets = [...namespaces.map((n) => ({ value: n, label: n })), { value: SKIP, label: "Skip: don’t import" }]; + + return ( +
+ + Routing rules + +

+ Send some messages to other namespaces. The first rule that matches decides; messages no rule matches go to{" "} + {home || "this watch’s namespace"}. Patterns are comma-separated and match anywhere, or use * for a pattern such + as *@acme.com. Rules apply to mail that arrives after you save. +

+ {rules.map((r, i) => { + const problem = showProblems ? ruleProblem(r) : null; + return ( +
+ {r.conditions.map((c, k) => ( +
+ {k ? "and" : "If"} + x.value === c.field)?.placeholder} + value={c.patterns} + onChange={(e) => setCondition(i, k, { patterns: e.target.value })} + /> + {r.conditions.length > 1 && ( + update(i, { conditions: r.conditions.filter((_, j) => j !== k) })} + > + + + )} +
+ ))} +
+ then +