From f8dd4bd5fcacf094afbe17925b33b74245d5515e Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Mon, 26 Oct 2026 16:09:12 -0400 Subject: [PATCH] Self-host email: Settings, Emails, the install guide's email choice, and Admin, Self-host - Settings, Emails (self-hosted installs, install admins): optional emails (off until turned on), essential emails with why, and Send email through the install's own Amazon SES or through CoderHelm with what CoderHelm sees. The Setup checklist gains an optional item. - Install guide: a "Send email" choice with neither option picked for you, the From field only for SES, and one line that optional emails start off. - Admin, Self-host (platform admins): hybrid installs, the parts each one uses, relay and email numbers, a 7-day trend, and each install's audit log with pause and revoke. Counts only, no addresses. --- dashboard/e2e/emails.spec.ts | 233 ++++++++++++++++ dashboard/e2e/selfhost.spec.ts | 3 +- dashboard/e2e/wide-data/settings.ts | 27 ++ dashboard/src/app/admin/self-host/page.tsx | 283 ++++++++++++++++++++ dashboard/src/app/settings/emails/page.tsx | 248 +++++++++++++++++ dashboard/src/components/settings-items.tsx | 1 + dashboard/src/lib/api.ts | 95 +++++++ dashboard/src/lib/capabilities.ts | 2 + dashboard/src/lib/install.ts | 17 +- dashboard/src/lib/nav.ts | 12 +- dashboard/src/lib/routes.ts | 2 + docs/components/install/wizard.tsx | 31 ++- docs/e2e/install.spec.ts | 28 +- docs/lib/install/core.ts | 38 ++- docs/scripts/install-core.test.mjs | 14 +- 15 files changed, 1013 insertions(+), 21 deletions(-) create mode 100644 dashboard/e2e/emails.spec.ts create mode 100644 dashboard/src/app/admin/self-host/page.tsx create mode 100644 dashboard/src/app/settings/emails/page.tsx diff --git a/dashboard/e2e/emails.spec.ts b/dashboard/e2e/emails.spec.ts new file mode 100644 index 00000000..a5fbe24d --- /dev/null +++ b/dashboard/e2e/emails.spec.ts @@ -0,0 +1,233 @@ +import { expect, test, type Page, type Route } from "@playwright/test"; +import fs from "node:fs"; +import path from "node:path"; + +// Settings, Emails on a self-hosted install, and Admin, Self-host for the +// platform admins. Every API call is answered here; all names, emails and +// ids are invented. + +const SHOTS_DIR = process.env.E2E_SHOTS_DIR || path.join("test-results", "shots"); +const PLATFORM_ADMIN = "admin@coderhelm.com"; + +const ESSENTIAL = [ + { id: "sign_in", label: "Sign-up codes and password resets", why: "People can't verify their address or get back into their account without them." }, + { id: "team_invite", label: "Team invites", why: "The only way an invited person learns how to join." }, + { id: "plugin_approval", label: "Plugin approval requests", why: "A named approver must approve a plugin draft before it publishes." }, +]; + +const TRUST = + "CoderHelm sees each recipient's address, the template id and its parameters (names, PR titles and run links in the weekly summary), and keeps only delivery metadata after sending."; + +function emails(state: { weekly: boolean; welcome: boolean; transport: "ses" | "coderhelm"; registered: boolean }) { + return { + self_hosted: true, + optional: [ + { id: "weekly_summary", label: "Weekly summary", description: "A Monday email to each person with their team's week.", on: state.weekly }, + { id: "welcome", label: "Welcome email", description: "A short hello with a link to get started, sent once when someone signs up.", on: state.welcome }, + ], + essential: ESSENTIAL, + transport: state.transport, + ses: { from: "helm@example.org", check: "email", note: "Sending uses this install's own Amazon SES, which needs SES production access." }, + relay: { + available: state.registered, + registered: state.registered, + turned_off: false, + trust: TRUST, + status: state.transport === "coderhelm" ? { paused: null, sent_today: 12, quota: 500, display_name: "acme-example.coderhelm.com via CoderHelm", from: "notifications@notify.coderhelm.com" } : null, + }, + }; +} + +async function shot(page: Page, name: string) { + fs.mkdirSync(SHOTS_DIR, { recursive: true }); + await page.addStyleTag({ content: "nextjs-portal{display:none!important}" }); + for (const width of [1440, 390]) { + await page.setViewportSize({ width, height: 900 }); + await page.evaluate(() => window.scrollTo(0, 0)); + await page.waitForTimeout(250); + const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + expect(overflow, `${name} scrolls sideways at ${width}px`).toBeLessThanOrEqual(0); + await page.screenshot({ path: path.join(SHOTS_DIR, `${name}-${width}.png`), fullPage: true }); + } + await page.setViewportSize({ width: 1280, height: 800 }); +} + +const json = (route: Route, body: unknown, status = 200) => route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) }); + +async function selfHostInstall(page: Page, opts: { registered?: boolean; platformAdmin?: boolean } = {}) { + const state = { weekly: false, welcome: false, transport: "ses" as "ses" | "coderhelm", registered: opts.registered ?? true }; + const puts: Record[] = []; + await page.route((url) => url.pathname === "/runtime-config.js", (route) => + route.fulfill({ contentType: "text/javascript", body: `window.__CODERHELM_CONFIG__ = ${JSON.stringify({ selfHosted: true })};` }), + ); + await page.route((url) => !["localhost", "127.0.0.1"].includes(url.hostname), (route) => route.abort()); + await page.route((url) => ["localhost", "127.0.0.1"].includes(url.hostname) && /^\/(api|auth)\//.test(url.pathname), async (route) => { + const req = route.request(); + const p = new URL(req.url()).pathname; + if (p === "/api/me") { + return json(route, { user_id: "u_1", team_id: "t_1", github_login: null, email: "owner@example.org", avatar_url: "", role: "owner", auth_provider: "email", mfa_enabled: false, platform_admin: opts.platformAdmin ?? true }); + } + if (p === "/api/usage") return json(route, { month: "2026-10", total_tokens: 0, tokens_in: 0, tokens_out: 0, total_runs: 0, max_tokens: 0 }); + if (p === "/api/banners") return json(route, { banners: [] }); + if (p === "/api/teams") return json(route, { teams: [{ team_id: "t_1", org: "acme-example", status: "active", current: true }] }); + if (p === "/api/system/emails") { + if (req.method() === "PUT") { + const body = JSON.parse(req.postData() || "{}"); + puts.push(body); + if (body.optional?.weekly_summary !== undefined) state.weekly = body.optional.weekly_summary; + if (body.optional?.welcome !== undefined) state.welcome = body.optional.welcome; + if (body.transport) state.transport = body.transport; + } + return json(route, emails(state)); + } + return json(route, { error: `Not mocked: ${p}` }, 404); + }); + return { state, puts }; +} + +test("Settings, Emails: optional emails start off, essential ones are listed, the admin turns one on", async ({ page }) => { + const { puts } = await selfHostInstall(page); + await page.goto("/settings/emails"); + await expect(page.getByRole("heading", { name: "Emails", level: 1 })).toBeVisible(); + + const weekly = page.getByTestId("optional-weekly_summary").getByRole("switch"); + const welcome = page.getByTestId("optional-welcome").getByRole("switch"); + await expect(weekly).toHaveAttribute("aria-checked", "false"); + await expect(welcome).toHaveAttribute("aria-checked", "false"); + for (const e of ESSENTIAL) { + await expect(page.getByTestId(`essential-${e.id}`)).toContainText(e.label); + await expect(page.getByTestId(`essential-${e.id}`)).toContainText("Always on"); + await expect(page.getByTestId(`essential-${e.id}`).getByRole("switch")).toHaveCount(0); + } + // Own SES by default, with the setup check linked; the CoderHelm option says what it sees. + await expect(page.getByTestId("transport-ses").getByRole("radio")).toBeChecked(); + await expect(page.getByTestId("transport-ses").getByRole("link", { name: "Check email setup" })).toHaveAttribute("href", /\/settings\/setup\/?#email/); + await expect(page.getByTestId("transport-ses")).toContainText("SES production access"); + await expect(page.getByTestId("relay-trust")).toContainText("template id"); + await shot(page, "settings-emails"); + + await weekly.click(); + await expect(weekly).toHaveAttribute("aria-checked", "true"); + expect(puts).toEqual([{ optional: { weekly_summary: true } }]); +}); + +test("Settings, Emails: choosing Coderhelm's mail service, and the status it shows", async ({ page }) => { + const { puts } = await selfHostInstall(page); + await page.goto("/settings/emails"); + await page.getByTestId("transport-coderhelm").getByRole("radio").check(); + await expect(page.getByTestId("relay-status")).toContainText("acme-example.coderhelm.com via CoderHelm"); + await expect(page.getByTestId("relay-status")).toContainText("12 of 500 sent today"); + expect(puts).toEqual([{ transport: "coderhelm" }]); + await shot(page, "settings-emails-relay"); +}); + +test("Settings, Emails: Coderhelm's mail service needs the install registered first", async ({ page }) => { + await selfHostInstall(page, { registered: false }); + await page.goto("/settings/emails"); + await expect(page.getByTestId("transport-coderhelm").getByRole("radio")).toBeDisabled(); + await expect(page.getByTestId("relay-trust").getByRole("link", { name: "System, Hybrid" })).toBeVisible(); +}); + +test("Settings, Emails is only for install admins", async ({ page }) => { + await selfHostInstall(page, { platformAdmin: false }); + await page.goto("/settings/emails"); + // Anyone else is sent back to Settings, and nothing is read. + await expect(page).toHaveURL(/\/settings\/?$/); + await expect(page.getByTestId("emails-page")).toHaveCount(0); +}); + +// ── Admin, Self-host ─────────────────────────────────────────────────────── + +const ROWS = [ + { + install_id: "ins_aaaaaaaaaaaaaaaaaaaaaaaa", name: "acme-example", hostname: "acme-example.coderhelm.com", cloudfront: "d1example.cloudfront.net", + version: "v0.7.1", registered_at: "2026-10-01T00:00:00Z", last_seen: "2026-10-26T09:00:00Z", status: "active", verified: true, name_live: true, + sharing: true, integrations: ["notion"], github_links: 2, relay_24h: 41, relay_7d: 310, relay_failed_7d: 3, broker_7d: 120, + email_opted_in: true, email_paused: false, emails_24h: 9, emails_7d: 64, bounced_7d: 1, complained_7d: 0, listed_recipients: 18, + parts: ["address", "github", "notion", "broker", "email", "sharing"], + }, + { + install_id: "ins_bbbbbbbbbbbbbbbbbbbbbbbb", name: null, hostname: null, cloudfront: "d2example.cloudfront.net", + version: "", registered_at: "2026-10-12T00:00:00Z", last_seen: "2026-10-20T00:00:00Z", status: "paused", verified: true, name_live: false, + sharing: false, integrations: [], github_links: 0, relay_24h: 0, relay_7d: 0, relay_failed_7d: 0, broker_7d: 0, + email_opted_in: true, email_paused: true, emails_24h: 0, emails_7d: 40, bounced_7d: 6, complained_7d: 1, listed_recipients: 7, + parts: ["email"], + }, +]; + +const SUMMARY = { + installs: { total: 2, active_7d: 2, revoked: 0 }, + address: { claimed: 1, live: 1 }, + github: { installs: 1, linked_installations: 2, relayed_24h: 41, relayed_7d: 310, failure_rate_7d: 0.0097 }, + integrations: { jira: 0, notion: 1, confluence: 0, google_drive: 0 }, + broker: { installs: 1, tokens_7d: 120, tokens_per_day: 17.1429 }, + email: { opted_in: 2, sent_24h: 9, sent_7d: 104, bounce_rate_7d: 0.0673, complaint_rate_7d: 0.0096, paused: 1, recipients: 25 }, + sharing: 1, + trend: ["20", "21", "22", "23", "24", "25", "26"].map((d, i) => ({ day: `2026-10-${d}`, events: 30 + i * 4, emails: 10 + i })), + rows: ROWS, + generated_at: "2026-10-26T10:00:00Z", +}; + +async function hostedAdmin(page: Page, email = PLATFORM_ADMIN) { + const calls: { method: string; path: string; body: unknown }[] = []; + await page.route((url) => url.hostname !== "localhost", (route) => route.abort()); + await page.route((url) => url.hostname === "localhost" && /^\/(api|auth)\//.test(url.pathname), async (route) => { + const req = route.request(); + const p = new URL(req.url()).pathname; + calls.push({ method: req.method(), path: p, body: req.postData() ? JSON.parse(req.postData() as string) : null }); + if (p === "/api/me") return json(route, { user_id: "u-1", team_id: "TEAM#ops", github_login: null, email, avatar_url: "", role: "owner" }); + if (p === "/api/usage") return json(route, { month: "2026-10", total_tokens: 0, tokens_in: 0, tokens_out: 0, total_runs: 0, max_tokens: 0 }); + if (p === "/api/banners") return json(route, { banners: [] }); + if (p === "/api/teams") return json(route, { teams: [{ team_id: "TEAM#ops", org: "ops", status: "active", current: true }] }); + if (p.startsWith("/api/admin/") && email !== PLATFORM_ADMIN) return json(route, { error: "Forbidden" }, 403); + if (p === "/api/admin/hybrid/summary") return json(route, SUMMARY); + if (p === "/api/admin/hybrid/ins_aaaaaaaaaaaaaaaaaaaaaaaa") { + return json(route, { + install: ROWS[0], + trend: SUMMARY.trend, + audit: [ + { action: "email_recipients", at: "2026-10-25T08:00:00Z", detail: '{"added":3,"by":"5f2c1a9e0b7d4c33","removed":0}' }, + { action: "verify", at: "2026-10-01T00:10:00Z", detail: "{}" }, + ], + }); + } + if (p.endsWith("/email/pause")) return json(route, { ok: true, paused: true }); + if (p === "/api/admin/beta-signups") return json(route, { signups: [], counts: { new: 0, invited: 0, joined: 0, total: 0 } }); + return json(route, { error: `Not mocked: ${p}` }, 404); + }); + return calls; +} + +test("Admin, Self-host: totals, each hosted part, a trend, and installs with their audit log", async ({ page }) => { + const calls = await hostedAdmin(page); + await page.goto("/admin/self-host"); + await expect(page.getByRole("heading", { name: "Self-host", level: 1 })).toBeVisible(); + const tiles = page.getByTestId("selfhost-tiles"); + await expect(tiles).toContainText("2 active in 7 days, 0 revoked"); + await expect(tiles).toContainText("310 in 7 days, 0.97% failed"); + await expect(tiles).toContainText("104 in 7 days, 6.7% bounced"); + await expect(tiles).toContainText("1 paused, 25 recipients"); + await expect(page.getByTestId("selfhost-trend").getByRole("listitem")).toHaveCount(7); + const rows = page.getByTestId("selfhost-rows").locator(":scope > li"); + await expect(rows).toHaveCount(2); + await expect(rows.first()).toContainText("acme-example.coderhelm.com"); + await expect(rows.nth(1)).toContainText("Email paused"); + // Counts only: no recipient address anywhere on the page. + for (const part of ["selfhost-tiles", "selfhost-rows", "selfhost-trend"]) { + expect(await page.getByTestId(part).innerText()).not.toMatch(/[a-z0-9._-]+@[a-z0-9.-]+\.[a-z]{2,}/i); + } + await shot(page, "admin-self-host"); + + await rows.first().getByRole("button").first().click(); + await expect(page.getByTestId("selfhost-audit")).toContainText("email recipients"); + await shot(page, "admin-self-host-detail"); + await page.getByRole("button", { name: "Pause email" }).click(); + await page.getByRole("alertdialog").getByRole("button", { name: "Pause email" }).click(); + await expect.poll(() => calls.some((c) => c.path.endsWith("/email/pause") && (c.body as { paused: boolean }).paused === true)).toBe(true); +}); + +test("Admin, Self-host is refused to anyone but a platform admin", async ({ page }) => { + await hostedAdmin(page, "someone@acme.test"); + await page.goto("/admin/self-host"); + await expect(page.getByText("Couldn't load the self-hosted installs")).toBeVisible(); +}); diff --git a/dashboard/e2e/selfhost.spec.ts b/dashboard/e2e/selfhost.spec.ts index d8458cf8..461e528d 100644 --- a/dashboard/e2e/selfhost.spec.ts +++ b/dashboard/e2e/selfhost.spec.ts @@ -294,7 +294,8 @@ for (const [name, viewport] of [["desktop", { width: 1280, height: 800 }], ["pho const { systemCalls } = await setup(page, SELF, { signedIn: true, provider: "bedrock" }); await page.goto("/settings/setup/"); const list = page.getByTestId("setup-checklist"); - await expect(list.locator("li")).toHaveCount(8); + await expect(list.locator("li")).toHaveCount(9); + await expect(list.locator("#emails")).toContainText("Optional"); await expect(list.locator("#domain")).toContainText("Optional"); await expect(list.locator("#domain").getByRole("link", { name: "Add a domain" })).toHaveAttribute("href", /\/settings\/system\/?#domain$/); await expect(list.locator("#github")).toHaveAttribute("data-done", "yes"); diff --git a/dashboard/e2e/wide-data/settings.ts b/dashboard/e2e/wide-data/settings.ts index 088fc9fc..30b017ba 100644 --- a/dashboard/e2e/wide-data/settings.ts +++ b/dashboard/e2e/wide-data/settings.ts @@ -339,6 +339,33 @@ export const settingsData: Handler = ({ method, path, url }) => { if (p === "/api/activity/summary") { return { days: Number(url.searchParams.get("days") || 7), since: iso(60 * 24 * 7), skills: { reads: 1204, asks: 12, read_problems: 3, ask_problems: 1, applies: 4 }, lookups: { total: 980, ok: 960, refused: 12, failed: 8 } }; } + // Settings, Emails and Admin, Self-host: long addresses and host names. + if (p === "/api/system/emails") { + return { + self_hosted: true, + optional: [{ id: "weekly_summary", label: "Weekly summary", description: SENTENCE, on: true }], + essential: [{ id: "team_invite", label: "Team invites", why: SENTENCE }], + transport: "coderhelm", + ses: { from: EMAIL, check: "email", note: SENTENCE }, + relay: { available: true, registered: true, turned_off: false, trust: SENTENCE, status: { paused: null, sent_today: 12, quota: 500, display_name: `${TOKEN}.cloudfront.net via CoderHelm`, from: EMAIL } }, + }; + } + if (p === "/api/admin/hybrid/summary") { + const row = { + install_id: "ins_aaaaaaaaaaaaaaaaaaaaaaaa", name: TOKEN.toLowerCase(), hostname: `${TOKEN.toLowerCase()}.coderhelm.com`, cloudfront: `${TOKEN.toLowerCase()}.cloudfront.net`, + version: "v0.7.0-rc.1+build.123456789", registered_at: iso(60 * 24 * 30), last_seen: iso(5), status: "active", verified: true, name_live: true, sharing: true, + integrations: ["jira", "notion", "confluence", "google_drive"], github_links: 12, relay_24h: 123456, relay_7d: 1234567, relay_failed_7d: 12, broker_7d: 123456, + email_opted_in: true, email_paused: false, emails_24h: 1234, emails_7d: 12345, bounced_7d: 12, complained_7d: 1, listed_recipients: 1234, + parts: ["address", "github", "jira", "notion", "confluence", "google_drive", "broker", "email", "sharing"], + }; + return { + installs: { total: 1234, active_7d: 1200, revoked: 34 }, address: { claimed: 1000, live: 990 }, + github: { installs: 900, linked_installations: 12345, relayed_24h: 1234567, relayed_7d: 12345678, failure_rate_7d: 0.0123 }, + integrations: { jira: 100, notion: 200, confluence: 300, google_drive: 400 }, broker: { installs: 800, tokens_7d: 1234567, tokens_per_day: 176366.7 }, + email: { opted_in: 500, sent_24h: 123456, sent_7d: 1234567, bounce_rate_7d: 0.0123, complaint_rate_7d: 0.0012, paused: 3, recipients: 123456 }, + sharing: 50, trend: Array.from({ length: 7 }, (_, i) => ({ day: `2026-01-0${i + 1}`, events: 100000 + i, emails: 20000 + i })), rows: [row], generated_at: iso(1), + }; + } // The install's setup checks and update readiness: long ids, URLs and // commands, so Settings, then Setup and System keep to the screen. if (p === "/api/system/checks" || p === "/api/system/preflight") { diff --git a/dashboard/src/app/admin/self-host/page.tsx b/dashboard/src/app/admin/self-host/page.tsx new file mode 100644 index 00000000..41539771 --- /dev/null +++ b/dashboard/src/app/admin/self-host/page.tsx @@ -0,0 +1,283 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { api, type SelfHostDetail, type SelfHostRow, type SelfHostSummary, type SelfHostTrendDay } from "@/lib/api"; +import { useToast } from "@/components/toast"; +import { useConfirm } from "@/components/confirm-dialog"; +import { Page, PageHeader, Section, cardClass } from "@/components/page"; +import { Callout } from "@/components/callout"; +import { Skeleton } from "@/components/skeleton"; +import { StatusPill } from "@/components/status-pill"; +import { secondaryButton, smallSecondaryButton } from "@/components/ui"; +import { formatDate } from "@/components/list"; + +const n = (v: number) => v.toLocaleString(); +const pct = (v: number) => `${(v * 100).toFixed(v > 0 && v < 0.01 ? 2 : 1)}%`; + +const PART_LABEL: Record = { + address: "Address", + github: "GitHub relay", + jira: "Jira", + notion: "Notion", + confluence: "Confluence", + google_drive: "Drive", + broker: "Token broker", + email: "Email", + sharing: "Sharing", +}; + +const STATUS_TONE = { active: "success", paused: "warning", revoked: "error" } as const; + +/** + * Admin, then Self-host (Coderhelm's platform admins, hosted deployment): + * every self-hosted install registered for hybrid, which hosted parts each + * uses, and the event relay and email relay numbers. Metadata only: no + * payloads, no email contents, recipients only as counts. + */ +export default function SelfHostAdminPage() { + const [data, setData] = useState(null); + const [failed, setFailed] = useState(null); + const [open, setOpen] = useState(null); + + const load = useCallback(() => { + setFailed(null); + api + .adminSelfHostSummary() + .then(setData) + .catch((e: unknown) => setFailed(e instanceof Error ? e.message : "Couldn't load.")); + }, []); + useEffect(load, [load]); + + const header = ( +
+ +
+ ); + + if (failed) { + return ( + + {header} + +

{failed}

+ +
+
+ ); + } + if (!data) { + return ( + + {header} +
+ + +
+
+ ); + } + + const tiles: { label: string; value: string; note: string }[] = [ + { label: "Installs", value: n(data.installs.total), note: `${n(data.installs.active_7d)} active in 7 days, ${n(data.installs.revoked)} revoked` }, + { label: "Coderhelm address", value: n(data.address.claimed), note: `${n(data.address.live)} live` }, + { + label: "GitHub relay", + value: n(data.github.installs), + note: `${n(data.github.linked_installations)} linked, ${n(data.github.relayed_24h)} events today, ${n(data.github.relayed_7d)} in 7 days, ${pct(data.github.failure_rate_7d)} failed`, + }, + { label: "Token broker", value: n(data.broker.installs), note: `${n(data.broker.tokens_7d)} tokens in 7 days, ${data.broker.tokens_per_day.toFixed(1)} a day` }, + { + label: "Email relay", + value: n(data.email.opted_in), + note: `${n(data.email.sent_24h)} sent today, ${n(data.email.sent_7d)} in 7 days, ${pct(data.email.bounce_rate_7d)} bounced, ${pct(data.email.complaint_rate_7d)} complaints, ${n(data.email.paused)} paused, ${n(data.email.recipients)} recipients`, + }, + { + label: "Integration apps", + value: n(Object.values(data.integrations).reduce((a, b) => a + b, 0)), + note: `Jira ${n(data.integrations.jira ?? 0)}, Notion ${n(data.integrations.notion ?? 0)}, Confluence ${n(data.integrations.confluence ?? 0)}, Drive ${n(data.integrations.google_drive ?? 0)}`, + }, + { label: "Sharing with support", value: n(data.sharing), note: "Installs that share failed-delivery data" }, + ]; + + return ( + + {header} +
    + {tiles.map((t) => ( +
  • +

    {t.label}

    +

    {t.value}

    +

    {t.note}

    +
  • + ))} +
+ +
+ +
+ +
+ {data.rows.length === 0 ? ( +

No self-hosted install has registered yet.

+ ) : ( +
    + {data.rows.map((r) => ( + setOpen(open === r.install_id ? null : r.install_id)} onChanged={load} /> + ))} +
+ )} +
+
+ ); +} + +/** Two bars a day: relay events and emails, each scaled to its own week. */ +function Trend({ days }: { days: SelfHostTrendDay[] }) { + const maxE = Math.max(1, ...days.map((d) => d.events)); + const maxM = Math.max(1, ...days.map((d) => d.emails)); + return ( +
+
+ + +
+
    + {days.map((d) => ( +
  1. +
  2. + ))} +
+
+ ); +} + +function InstallRow({ row, open, onToggle, onChanged }: { row: SelfHostRow; open: boolean; onToggle: () => void; onChanged: () => void }) { + const address = row.hostname ?? row.cloudfront; + return ( +
  • + + {open && } +
  • + ); +} + +function InstallDetail({ row, onChanged }: { row: SelfHostRow; onChanged: () => void }) { + const { toast } = useToast(); + const { confirm } = useConfirm(); + const [detail, setDetail] = useState(null); + const [failed, setFailed] = useState(false); + const [busy, setBusy] = useState(false); + + useEffect(() => { + api.adminSelfHostInstall(row.install_id).then(setDetail).catch(() => setFailed(true)); + }, [row.install_id]); + + const act = async (what: "pause" | "resume" | "revoke") => { + const ok = await confirm({ + title: what === "revoke" ? "Revoke this install?" : what === "pause" ? "Pause its email?" : "Resume its email?", + message: + what === "revoke" + ? "Its Coderhelm address, GitHub relay, integration apps, token broker and email stop working until it registers again." + : what === "pause" + ? "Coderhelm stops sending email for this install until you resume it. The install shows the pause in Setup." + : "Coderhelm sends this install's email again.", + confirmLabel: what === "revoke" ? "Revoke" : what === "pause" ? "Pause email" : "Resume email", + destructive: what !== "resume", + }); + if (!ok) return; + setBusy(true); + try { + if (what === "revoke") await api.adminRevokeInstall(row.install_id, "platform admin"); + else await api.adminPauseInstallEmail(row.install_id, what === "pause", "platform admin"); + toast(what === "revoke" ? "Revoked" : what === "pause" ? "Email paused" : "Email resumed", "success"); + onChanged(); + } catch { + toast("Couldn't do that. Try again.", "error"); + } finally { + setBusy(false); + } + }; + + const stats: [string, string][] = [ + ["GitHub installations linked", n(row.github_links)], + ["Events relayed, today and 7 days", `${n(row.relay_24h)} and ${n(row.relay_7d)}`], + ["Relay failures in 7 days", n(row.relay_failed_7d)], + ["Tokens minted in 7 days", n(row.broker_7d)], + ["Emails, today and 7 days", `${n(row.emails_24h)} and ${n(row.emails_7d)}`], + ["Bounces and complaints in 7 days", `${n(row.bounced_7d)} and ${n(row.complained_7d)}`], + ["Email recipients listed", n(row.listed_recipients)], + ["Shares delivery data", row.sharing ? "Yes" : "No"], + ]; + + return ( +
    +
    + {stats.map(([k, v]) => ( +
    +
    {k}
    +
    {v}
    +
    + ))} +
    +
    + {row.status !== "revoked" && row.email_opted_in && ( + + )} + {row.status !== "revoked" && ( + + )} +
    +
    +

    Audit log

    + {failed &&

    Couldn't load the audit log.

    } + {!detail && !failed && } + {detail && detail.audit.length === 0 &&

    Nothing recorded yet.

    } + {detail && detail.audit.length > 0 && ( +
      + {detail.audit.map((a, i) => ( +
    1. + {formatDate(a.at)} + {a.action.replace(/_/g, " ")} + {a.detail} +
    2. + ))} +
    + )} +
    +
    + ); +} diff --git a/dashboard/src/app/settings/emails/page.tsx b/dashboard/src/app/settings/emails/page.tsx new file mode 100644 index 00000000..3a0ef24e --- /dev/null +++ b/dashboard/src/app/settings/emails/page.tsx @@ -0,0 +1,248 @@ +"use client"; + +import Link from "next/link"; +import { useCallback, useEffect, useState } from "react"; +import { api, ApiError, type EmailTransport, type SystemEmails } from "@/lib/api"; +import { useInstallAdmin } from "@/lib/install"; +import { useToast } from "@/components/toast"; +import { Page, PageHeader } from "@/components/page"; +import { Callout } from "@/components/callout"; +import { Skeleton } from "@/components/skeleton"; +import { Redirect } from "@/components/redirect"; +import { StatusPill } from "@/components/status-pill"; +import { linkButton, secondaryButton } from "@/components/ui"; +import { SettingsRow, SettingsSection, Switch } from "@/components/settings"; + +/** + * Settings, then Emails (self-hosted installs, install admins): which + * optional emails the install sends (all off until an admin turns them on), + * the essential ones and why they are needed, and how email leaves: the + * install's own Amazon SES, or Coderhelm's mail service. Each person's own + * unsubscribe (Settings, Notifications) still applies on top. + */ +export default function EmailsPage() { + const { ready, allowed } = useInstallAdmin(); + if (!ready) return null; + if (!allowed) { + return ( + +
    + +
    +
    + ); + } + return ; +} + +const TRANSPORTS: { value: EmailTransport; label: string; help: string }[] = [ + { + value: "ses", + label: "Through my own Amazon SES", + help: "Email leaves from this install's AWS account and its sender address, once the sender is verified.", + }, + { + value: "coderhelm", + label: "Through Coderhelm (easiest)", + help: "No SES setup. Coderhelm sends from its own address with your install's name, only to your install's people and pending invites.", + }, +]; + +function Emails() { + const { toast } = useToast(); + const [data, setData] = useState(null); + const [failed, setFailed] = useState(false); + const [saving, setSaving] = useState(null); + + const load = useCallback(() => { + setFailed(false); + api.getSystemEmails().then(setData).catch(() => setFailed(true)); + }, []); + useEffect(load, [load]); + + const save = async (change: { optional?: Record; transport?: EmailTransport }, what: string) => { + setSaving(what); + const before = data; + // Show the choice at once; put it back if the save fails. + if (data) { + setData({ + ...data, + transport: change.transport ?? data.transport, + optional: data.optional.map((o) => (change.optional && o.id in change.optional ? { ...o, on: change.optional[o.id] } : o)), + }); + } + try { + const next = await api.setSystemEmails(change); + setData(next); + toast("Saved", "success"); + } catch (e) { + if (before) setData(before); + const msg = e instanceof ApiError ? e.message : "Couldn't save. Check your connection and try again."; + toast(msg, "error"); + } finally { + setSaving(null); + } + }; + + const header = ( +
    + +
    + ); + + if (failed) { + return ( + + {header} + + + + + ); + } + if (!data) { + return ( + + {header} +
    + + +
    +
    + ); + } + + const relayStatus = data.relay.status; + const relayError = relayStatus && "error" in relayStatus ? relayStatus : null; + const relayOk = relayStatus && !("error" in relayStatus) ? relayStatus : null; + + return ( + + {header} +
    + + {data.optional.map((o) => ( + ( + save({ optional: { [o.id]: on } }, o.id)} + /> + )} + /> + ))} + + +
    +

    Send email

    +

    + Applies to every email: invites, approvals, alerts, and the optional ones you turned on. Nothing falls back to the other way if the one you chose fails. +

    +
    + {TRANSPORTS.map((t) => { + const checked = data.transport === t.value; + const blocked = t.value === "coderhelm" && !data.relay.available && !checked; + return ( + + ); + })} +
    + {data.transport === "coderhelm" && relayError && ( +
    + +

    {relayError.message} Nothing is sent another way meanwhile; Deliveries lists each email that failed.

    +
    +
    + )} + {data.transport === "coderhelm" && relayOk?.paused && ( +
    + +

    Coderhelm paused email after too many {relayOk.paused.reason}. Fix the addresses in Deliveries, then ask Coderhelm support to resume, or switch to your own Amazon SES.

    +
    +
    + )} + {data.transport === "coderhelm" && relayOk && !relayOk.paused && ( +

    + Working{" "} + Sends as {relayOk.display_name}. {relayOk.sent_today} of {relayOk.quota} sent today. +

    + )} +
    + + + {data.essential.map((e) => ( +
    +
    + {e.label} + Always on +
    +

    {e.why}

    +
    + ))} +
    +
    +
    + ); +} diff --git a/dashboard/src/components/settings-items.tsx b/dashboard/src/components/settings-items.tsx index 89a015e8..3cff1380 100644 --- a/dashboard/src/components/settings-items.tsx +++ b/dashboard/src/components/settings-items.tsx @@ -89,6 +89,7 @@ export const SETTINGS_GROUPS: SettingsGroup[] = [ label: "This install", items: [ { href: "/settings/setup", title: "Setup", description: "What is left to set up, checked live: GitHub, repositories, models, email, updates.", icon: , view: "system", edit: "system", selfHostOnly: true }, + { href: "/settings/emails", title: "Emails", description: "Which optional emails this install sends, and whether email goes out through your own Amazon SES or Coderhelm.", icon: , view: "emails", edit: "emails", selfHostOnly: true }, { href: "/settings/system", title: "System", description: "Which version runs, updates and their history, automatic updates and roll back.", icon: , view: "system", edit: "system", selfHostOnly: true }, ], }, diff --git a/dashboard/src/lib/api.ts b/dashboard/src/lib/api.ts index 480a84b4..0c55bb4d 100644 --- a/dashboard/src/lib/api.ts +++ b/dashboard/src/lib/api.ts @@ -1202,6 +1202,20 @@ export const api = { setSystemDomain: (hostname: string) => request("/api/system/domain", { method: "PUT", body: JSON.stringify({ hostname }) }), removeSystemDomain: () => request("/api/system/domain", { method: "DELETE" }), + // Settings, Emails (self-hosted installs, install admins): optional emails and how the install sends. + getSystemEmails: () => request("/api/system/emails"), + setSystemEmails: (change: { optional?: Record; transport?: EmailTransport }) => + request("/api/system/emails", { method: "PUT", body: JSON.stringify(change) }), + // Self-hosted installs on Coderhelm's hosted parts (platform admins, hosted deployment). + adminSelfHostSummary: () => request("/api/admin/hybrid/summary"), + adminSelfHostInstall: (id: string) => request(`/api/admin/hybrid/${encodeURIComponent(id)}`), + adminPauseInstallEmail: (id: string, paused: boolean, reason = "") => + request<{ ok: boolean; paused: boolean }>(`/api/admin/hybrid/${encodeURIComponent(id)}/email/pause`, { + method: "POST", + body: JSON.stringify({ paused, reason }), + }), + adminRevokeInstall: (id: string, reason = "") => + request(`/api/admin/hybrid/${encodeURIComponent(id)}/revoke`, { method: "POST", body: JSON.stringify({ reason }) }), // Deliveries (team admins): every webhook and notice in and out, with why each failed. listDeliveries: (f: DeliveryFilter = {}) => { @@ -3938,3 +3952,84 @@ export interface HybridSettingsPatch { integrations?: string[]; sharing?: { enabled: boolean; payloads: boolean }; } + + +// ── Settings, Emails (self-hosted installs) ────────────────────────────── + +export type EmailTransport = "ses" | "coderhelm"; + +export interface SystemEmails { + self_hosted: true; + optional: { id: string; label: string; description: string; on: boolean }[]; + essential: { id: string; label: string; why: string }[]; + transport: EmailTransport; + ses: { from: string; check: string; note: string }; + relay: { + available: boolean; + registered: boolean; + turned_off: boolean; + /** What Coderhelm sees when email goes through it. */ + trust: string; + status: + | null + | { error: string; message: string } + | { paused: { reason: string; at: string } | null; sent_today: number; quota: number; display_name: string; from: string | null }; + }; + updated_by?: string; + updated_at?: string; +} + +// ── Self-host admin (platform admins) ───────────────────────────────────── + +export interface SelfHostRow { + install_id: string; + name: string | null; + hostname: string | null; + cloudfront: string; + version: string; + registered_at: string; + last_seen: string; + status: "active" | "paused" | "revoked"; + verified: boolean; + name_live: boolean; + sharing: boolean; + integrations: string[]; + github_links: number; + relay_24h: number; + relay_7d: number; + relay_failed_7d: number; + broker_7d: number; + email_opted_in: boolean; + email_paused: boolean; + emails_24h: number; + emails_7d: number; + bounced_7d: number; + complained_7d: number; + listed_recipients: number; + parts: string[]; +} + +export interface SelfHostTrendDay { + day: string; + events: number; + emails: number; +} + +export interface SelfHostSummary { + installs: { total: number; active_7d: number; revoked: number }; + address: { claimed: number; live: number }; + github: { installs: number; linked_installations: number; relayed_24h: number; relayed_7d: number; failure_rate_7d: number }; + integrations: Record; + broker: { installs: number; tokens_7d: number; tokens_per_day: number }; + email: { opted_in: number; sent_24h: number; sent_7d: number; bounce_rate_7d: number; complaint_rate_7d: number; paused: number; recipients: number }; + sharing: number; + trend: SelfHostTrendDay[]; + rows: SelfHostRow[]; + generated_at: string; +} + +export interface SelfHostDetail { + install: SelfHostRow; + trend: SelfHostTrendDay[]; + audit: { action: string; at: string; detail: string }[]; +} diff --git a/dashboard/src/lib/capabilities.ts b/dashboard/src/lib/capabilities.ts index 30d7cc0a..98243be9 100644 --- a/dashboard/src/lib/capabilities.ts +++ b/dashboard/src/lib/capabilities.ts @@ -53,6 +53,8 @@ const BUILT_IN_MIN: Record = { alerts: "admin", model_provider: "admin", system: "admin", + emails: "admin", + platform_admin: "admin", budget: "admin", support: "admin", "plugins.view": "viewer", diff --git a/dashboard/src/lib/install.ts b/dashboard/src/lib/install.ts index c4bc55a0..9db60692 100644 --- a/dashboard/src/lib/install.ts +++ b/dashboard/src/lib/install.ts @@ -23,7 +23,7 @@ export function useInstallAdmin(): { ready: boolean; allowed: boolean } { return state; } -export type SetupKey = "github" | "repos" | "models" | "email" | "domain" | "chat" | "updates" | "run"; +export type SetupKey = "github" | "repos" | "models" | "email" | "emails" | "domain" | "chat" | "updates" | "run"; export interface SetupCheck { key: SetupKey; @@ -49,14 +49,16 @@ function emailOk(): boolean { /** Every setup item, each from its own live call; one failing leaves its item unknown. */ export async function loadSetupChecks(): Promise { const settle = async (p: Promise): Promise => p.catch(() => null); - const [integrations, repos, model, system, runs, domain] = await Promise.all([ + const [integrations, repos, model, system, runs, domain, emails] = await Promise.all([ settle(api.getIntegrations()), settle(api.listRepos()), settle(api.getModelProvider()), settle(api.getSystemVersion()), settle(api.listRuns()), settle(api.getSystemDomain()), + settle(api.getSystemEmails()), ]); + const optionalOn = Array.isArray(emails?.optional) ? emails.optional.filter((o) => o.on) : []; const domainLive = domain?.available ? domain.code === "ok" : null; const item = (id: string) => integrations?.items.find((i) => i.id === id); const github = item("github"); @@ -109,6 +111,17 @@ export async function loadSetupChecks(): Promise { href: "/settings/system#domain", action: domain?.domain?.hostname ? "See its records" : "Add a domain", }, + { + key: "emails", + label: "Optional emails chosen", + optional: true, + done: Array.isArray(emails?.optional) ? optionalOn.length > 0 : null, + detail: optionalOn.length + ? `On: ${optionalOn.map((o) => o.label).join(", ")}.` + : "Optional: the weekly summary and the welcome email start off. Turn on the ones your team wants.", + href: "/settings/emails", + action: "Choose emails", + }, { key: "chat", label: "Jira, Slack or Teams connected", diff --git a/dashboard/src/lib/nav.ts b/dashboard/src/lib/nav.ts index f5f46068..42b178a8 100644 --- a/dashboard/src/lib/nav.ts +++ b/dashboard/src/lib/nav.ts @@ -102,7 +102,17 @@ export const NAV_SECTIONS: NavSection[] = [ /** Only for the install's platform admins. */ export const ADMIN_SECTIONS: NavSection[] = [ - { key: "admin", label: "Admin", icon: "admin", pages: [{ href: "/admin", label: "Platform admin" }], superAdminOnly: true, countKey: "betaSignups" }, + { + key: "admin", + label: "Admin", + icon: "admin", + pages: [ + { href: "/admin", label: "Platform admin" }, + { href: "/admin/self-host", label: "Self-host" }, + ], + superAdminOnly: true, + countKey: "betaSignups", + }, { key: "queue", label: "Support queue", icon: "queue", pages: [{ href: "/admin/tickets", label: "Support queue" }], superAdminOnly: true, countKey: "supportQueue" }, ]; diff --git a/dashboard/src/lib/routes.ts b/dashboard/src/lib/routes.ts index 1fc4e4c4..a276aa04 100644 --- a/dashboard/src/lib/routes.ts +++ b/dashboard/src/lib/routes.ts @@ -95,6 +95,7 @@ export const ROUTES: Record = { "/settings/budget": { label: "Token limit", parent: "/settings" }, "/settings/setup": { label: "Setup", parent: "/settings" }, "/settings/system": { label: "System", parent: "/settings" }, + "/settings/emails": { label: "Emails", parent: "/settings" }, "/settings/deliveries": { label: "Deliveries", parent: "/settings", tab: "Webhook deliveries" }, "/settings/webhooks": { label: "Webhooks", parent: "/settings" }, "/settings/integrations": { label: "Integrations", parent: "/settings" }, @@ -114,6 +115,7 @@ export const ROUTES: Record = { "/admin": { label: "Platform admin" }, "/admin/tickets": { label: "Support queue", parent: "/admin" }, + "/admin/self-host": { label: "Self-host", parent: "/admin" }, "/admin/queue": { label: "Shared queue", parent: "/admin", tab: "Shared failed-message queue" }, }; diff --git a/docs/components/install/wizard.tsx b/docs/components/install/wizard.tsx index be159a9f..cb5e5999 100644 --- a/docs/components/install/wizard.tsx +++ b/docs/components/install/wizard.tsx @@ -726,7 +726,7 @@ export function InstallWizard() { const [hyb, setHyb] = useState<{ error: { title: string; fix: string } | null; claimRefused: boolean; settingsSent: boolean; lastTry: number; busy: boolean }>({ error: null, claimRefused: false, settingsSent: false, lastTry: 0, busy: false }); const [newName, setNewName] = useState(''); const [hybridOutcome, setHybridOutcome] = useState(null); - const hybridWanted = !!s && (s.domainChoice === 'coderhelm' || s.githubChoice === 'hosted'); + const hybridWanted = !!s && (s.domainChoice === 'coderhelm' || s.githubChoice === 'hosted' || s.emailTransport === 'coderhelm'); useEffect(() => { if (!s || !hybridWanted || !s.url || !setup || !s.setupToken || hyb.busy) return; if (Date.now() - hyb.lastTry < timing('__CH_HYBRID_RETRY_MS', 8000)) return; @@ -954,9 +954,32 @@ export function InstallWizard() { ) : null} - - update({ emailFrom: e.target.value })} autoCapitalize="off" spellCheck={false} /> - +
    + Send email + {([ + ['coderhelm', 'Send email through CoderHelm (easiest)', 'No Amazon SES setup. CoderHelm sees each recipient’s address and the email’s details (such as names and PR titles), and keeps only delivery records. Needs your install registered with CoderHelm, which this page does.'], + ['ses', 'Through my own Amazon SES', 'Email leaves from your AWS account. Nothing passes through CoderHelm.'], + ] as const).map(([id, title, help]) => ( + + ))} + {s.emailTransport === '' ? ( +

    Not chosen: email goes through your own Amazon SES until you pick in Settings, Emails.

    + ) : null} + {s.emailTransport !== 'coderhelm' ? ( +
    + + update({ emailFrom: e.target.value })} autoCapitalize="off" spellCheck={false} /> + +
    + ) : null} +

    Optional emails such as the weekly summary start off; turn them on in Settings, Emails.

    +
    Let people from your company join

    This install is for one organization only: nobody else can sign up.

    diff --git a/docs/e2e/install.spec.ts b/docs/e2e/install.spec.ts index 115ca5c6..4cdb4ac2 100644 --- a/docs/e2e/install.spec.ts +++ b/docs/e2e/install.spec.ts @@ -389,6 +389,7 @@ test('more options: domain, sender, sign-up and updates go to AWS; a bad hostnam expect(q.get('param_AutoUpdate')).toBe('on'); expect(q.get('param_UpdateWindow')).toBe('daily 02:00'); expect(q.get('param_UpdateTimezone')).toBe('Europe/Berlin'); + expect(q.get('param_EmailTransport')).toBeNull(); // The steps now include the domain. await expect(page.getByRole('list', { name: 'Install steps' })).toContainText('Domain'); }); @@ -478,7 +479,9 @@ test('ready: the optional setup list, each with its check and one action', async await seeded(page, m, { url: INSTALL, region: 'eu-west-1' }); await expect(page.getByTestId('screen-ready')).toBeVisible(); const list = page.getByTestId('optional-setup'); - await expect(list.locator('[data-optional]')).toHaveCount(10); + await expect(list.locator('[data-optional]')).toHaveCount(11); + await expect(list.locator('[data-optional="optional_emails"]')).toContainText('Weekly summary email (off; turn on in Settings)'); + await expect(page.getByTestId('optional-optional_emails-action')).toHaveAttribute('href', `${INSTALL}/settings/emails/`); await expect(list.locator('[data-optional="domain"]')).toHaveAttribute('data-state', 'todo'); await expect(page.getByTestId('optional-domain-action')).toHaveAttribute('href', `${INSTALL}/settings/system/#domain`); await expect(list.locator('[data-optional="email"]')).toHaveAttribute('data-state', 'todo'); @@ -882,3 +885,26 @@ test('hybrid screenshots at 1440 and 390', async ({ page }) => { await at('25-github-hosted-refused'); } }); + + +test('email: through CoderHelm only when picked, and then no From address', async ({ page }) => { + const m = newMock(); + await mock(page, m); + await page.goto('/self-host/install/'); + await page.getByLabel('Your email').fill('ada@example.com'); + await page.getByRole('button', { name: 'More options' }).click(); + const choice = page.getByTestId('email-choice'); + // Neither is picked for you. + await expect(choice.getByRole('radio', { checked: true })).toHaveCount(0); + await expect(choice).toContainText('Not chosen'); + await expect(choice).toContainText('weekly summary start off'); + await expect(page.getByLabel('Send email from')).toBeVisible(); + await choice.getByLabel('Send email through CoderHelm (easiest)').check(); + await expect(page.getByLabel('Send email from')).toHaveCount(0); + await expect(choice).toContainText('keeps only delivery records'); + await page.getByTestId('launch').click(); + const [link] = await opened(page); + const q = new URLSearchParams(new URL(link).hash.split('?')[1]); + expect(q.get('param_EmailTransport')).toBe('coderhelm'); + expect(q.get('param_EmailFrom')).toBeNull(); +}); diff --git a/docs/lib/install/core.ts b/docs/lib/install/core.ts index 2fdf0f84..a485c018 100644 --- a/docs/lib/install/core.ts +++ b/docs/lib/install/core.ts @@ -165,7 +165,13 @@ export interface InstallState { hostname: string; /** They chose to finish on the AWS address and add the domain later. */ domainSkipped: boolean; - /** Who sends CoderHelm's email; empty uses their own address. */ + /** + * How the install sends email: its own Amazon SES, or CoderHelm's mail + * service (hybrid). Empty: not chosen yet, so the stack's default (SES) + * until an admin picks in Settings, Emails. + */ + emailTransport: '' | 'ses' | 'coderhelm'; + /** Who sends CoderHelm's email through SES; empty uses their own address. */ emailFrom: string; /** * Who may join the install's one organization besides the people its @@ -234,6 +240,7 @@ export function newState(over: Partial = {}): InstallState { sharing: false, hostname: '', domainSkipped: false, + emailTransport: '', emailFrom: '', joinDomain: false, signupDomain: '', @@ -266,7 +273,7 @@ export function validate(s: Pick & P if (!HOST_RE.test(h)) p.hostname = 'Enter a hostname such as coderhelm.example.com.'; else if (/\.(cloudfront\.net|amazonaws\.com)$/.test(h)) p.hostname = 'Enter a domain you own, not an AWS address.'; } - if (s.emailFrom && !EMAIL_RE.test(s.emailFrom.trim())) p.emailFrom = 'Enter an email address, or leave it empty to use yours.'; + if (s.emailTransport !== 'coderhelm' && s.emailFrom && !EMAIL_RE.test(s.emailFrom.trim())) p.emailFrom = 'Enter an email address, or leave it empty to use yours.'; if (joinsByDomain(s)) { const d = (s.signupDomain ?? '').trim().toLowerCase().replace(/^@/, ''); if (!d) p.signupDomain = 'Enter your company\'s email domain, such as example.com, or pick Only people I invite.'; @@ -313,7 +320,8 @@ export function quickCreateUrl(s: InstallState): string { ]; // The optional ones only when set, so the link stays short and older templates still open. if (s.domainChoice === 'own' && s.hostname) params.push(['param_Hostname', cleanHostname(s.hostname)]); - if (s.emailFrom?.trim()) params.push(['param_EmailFrom', s.emailFrom.trim().toLowerCase()]); + if (s.emailTransport === 'coderhelm') params.push(['param_EmailTransport', 'coderhelm']); + else if (s.emailFrom?.trim()) params.push(['param_EmailFrom', s.emailFrom.trim().toLowerCase()]); if (joinsByDomain(s) && s.signupDomain?.trim()) params.push(['param_SignupDomain', s.signupDomain.trim().toLowerCase().replace(/^@/, '')]); if (s.requireTwoFactor) params.push(['param_RequireTwoFactor', 'on']); if (s.autoUpdate) { @@ -912,7 +920,7 @@ export interface OptionalItem { } /** Everything else a person can set up, each with its check (when the install reports one) and one action. */ -export function optionalSetup(s: Pick, setup: SetupStatus | null): OptionalItem[] { +export function optionalSetup(s: Pick & Partial>, setup: SetupStatus | null): OptionalItem[] { const url = s.url.replace(/\/+$/, ''); const at = (path: string) => (url ? `${url}${path}` : path); const check = (id: string) => findCheck(setup, id); @@ -933,14 +941,22 @@ export function optionalSetup(s: Pick [i.id, i])); - assert.deepEqual(items.map((i) => i.id), ['domain', 'email', 'invite', 'chat', 'jira', 'google_sign_in', 'updates', 'hybrid_apps', 'deliveries', 'backups']); + assert.deepEqual(items.map((i) => i.id), ['domain', 'email', 'optional_emails', 'invite', 'chat', 'jira', 'google_sign_in', 'updates', 'hybrid_apps', 'deliveries', 'backups']); assert.equal(by.domain.state, 'todo'); assert.equal(by.domain.action.href, 'https://coderhelm.example.com/settings/system/#domain'); assert.equal(by.email.state, 'todo'); @@ -350,6 +357,11 @@ test('optional setup: each item has one action, its check where the install repo // An unverified sender links to the identities page. const unverified = c.optionalSetup(st, setup({ email: { status: 'warn', code: 'identity_unverified', required: false } })); assert.match(unverified.find((i) => i.id === 'email').action.href, /#\/identities$/); + // Optional emails start off and are turned on in Settings, Emails. + assert.equal(by.optional_emails.title, 'Weekly summary email (off; turn on in Settings)'); + assert.equal(by.optional_emails.action.href, 'https://coderhelm.example.com/settings/emails/'); + // Email through CoderHelm: no SES to set up, so no SES item. + assert.ok(!c.optionalSetup({ ...st, emailTransport: 'coderhelm' }, withChecks).some((i) => i.id === 'email')); }); test('setups: fully private and hybrid, each with what it gives and its trade-off', () => {