Diffinery

homeflare/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

1041 lines · 66.1 KBRaw History
1/**
2 * Email templates. Each email is a list of blocks rendered twice: as HTML
3 * (table layout and inline styles that hold up in Gmail, Outlook and Apple
4 * Mail, light and dark) and as plain text. The look follows the site: Kumo's
5 * neutral palette, blue for actions and the orange mark.
6 */
7import { escapeHtml, renderMarkdown, stripHtmlComments } from "../web/markdown.js";
8import type { DigestData, MailJob, Reason, RunData, ThreadData } from "./types.js";
9
10export type Inline = string | { b: string } | { a: string; href: string } | { code: string };
11
12export type Block =
13 | { p: Inline[]; muted?: boolean }
14 | { md: string; base?: { owner: string; repo: string; ref: string } }
15 | { kv: Array<[string, Inline[] | string]> }
16 | { button: { label: string; url: string }; secondary?: { label: string; url: string } }
17 | { callout: Inline[]; tone: "info" | "warn" | "danger" }
18 | { code: string }
19 | { items: Array<{ mark: "ok" | "fail" | "skip" | "dot"; text: Inline[]; url?: string }> }
20 | { quote: Inline[] }
21 /** Plain text exactly as someone typed it, lines kept, never read as Markdown or HTML. */
22 | { plain: string };
23
24export interface Email {
25 subject: string;
26 /** Hidden preview line shown by mail clients next to the subject. */
27 preheader: string;
28 /** Small label above the title (e.g. "Security", "Pull request"). */
29 eyebrow?: { text: string; tone: "neutral" | "blue" | "green" | "red" | "amber" | "purple" };
30 title: Inline[];
31 blocks: Block[];
32 /** Display name on the From address, e.g. the person who commented. */
33 fromName?: string;
34 /** Repository the email is about, shown next to the logo and used for List-Id. */
35 context?: { label: string; url: string };
36 /** Thread id for In-Reply-To / References, e.g. "owner/repo/issues/12". */
37 thread?: string;
38 /** Main link (also "View it on Diffinery" in the footer). */
39 url?: string;
40 /** Where the recipient's reply goes, when it isn't to us (a contact message's confirmed sender). */
41 replyTo?: { email: string; name?: string };
42}
43
44export interface RenderCtx {
45 publicUrl: string;
46 /** The recipient's login, when they have an account. */
47 login?: string;
48 reason: Reason;
49 /** Footer links: unsubscribe (thread, watch or settings group) and settings. */
50 unsubscribe?: Array<{ label: string; url: string }>;
51 settingsUrl?: string;
52}
53
54// ---------------------------------------------------------------- palette (Kumo, as hex for mail clients)
55
56const C = {
57 canvas: "#f4f4f5",
58 card: "#ffffff",
59 border: "#e4e4e7",
60 fg: "#18181b",
61 fg2: "#52525b",
62 fg3: "#71717a",
63 accent: "#1447e6",
64 brand: "#f6821f",
65 codeBg: "#f4f4f5",
66 tones: {
67 neutral: ["#f4f4f5", "#3f3f46"],
68 blue: ["#e6edfd", "#1447e6"],
69 green: ["#e3f6ec", "#007a55"],
70 red: ["#fdecec", "#c10007"],
71 amber: ["#fdf3dc", "#a65f00"],
72 purple: ["#f3e8ff", "#8200db"],
73 } as Record<string, [string, string]>,
74};
75const FONT = `-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif`;
76const MONO = `ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,'Liberation Mono',monospace`;
77
78// ---------------------------------------------------------------- rendering
79
80const esc = escapeHtml;
81
82function inlineHtml(parts: Inline[] | string): string {
83 const list = typeof parts === "string" ? [parts] : parts;
84 return list
85 .map((x) => {
86 if (typeof x === "string") return esc(x);
87 if ("b" in x) return `<strong style="font-weight:600">${esc(x.b)}</strong>`;
88 if ("code" in x) return `<code class="code" style="font-family:${MONO};font-size:12.5px;background:${C.codeBg};border-radius:4px;padding:1px 5px">${esc(x.code)}</code>`;
89 return `<a href="${esc(x.href)}" style="color:${C.accent};text-decoration:none">${esc(x.a)}</a>`;
90 })
91 .join("");
92}
93
94function inlineText(parts: Inline[] | string): string {
95 const list = typeof parts === "string" ? [parts] : parts;
96 return list.map((x) => (typeof x === "string" ? x : "b" in x ? x.b : "code" in x ? `\`${x.code}\`` : `${x.a} (${x.href})`)).join("");
97}
98
99/** Markdown from issues and comments, with relative links made absolute. */
100function markdownHtml(md: string, publicUrl: string, base?: { owner: string; repo: string; ref: string }): string {
101 const html = renderMarkdown(md.length > 20_000 ? `${md.slice(0, 20_000)}\n\n…` : md, base ? { base: { ...base, dir: "" } } : {});
102 const abs = html.replace(/(href|src)="\/(?!\/)/g, `$1="${publicUrl}/`).replace(/href="#/g, `href="${publicUrl}/#`);
103 // Images from other hosts become links: an email that loads them would tell whoever wrote the comment when and where it was read.
104 return abs.replace(/<img\b[^>]*>/gi, (tag) => {
105 const src = /\ssrc="([^"]*)"/i.exec(tag)?.[1] ?? "";
106 if (src.startsWith(`${publicUrl}/`)) return tag;
107 const alt = /\salt="([^"]*)"/i.exec(tag)?.[1] || "image";
108 return src ? `<a href="${src}">[${alt}]</a>` : "";
109 });
110}
111
112function blockHtml(b: Block, ctx: RenderCtx): string {
113 const P = `margin:0 0 14px;font-size:15px;line-height:1.6;color:${C.fg}`;
114 if ("p" in b) return `<p class="${b.muted ? "muted" : "fg"}" style="${P}${b.muted ? `;color:${C.fg3};font-size:13px` : ""}">${inlineHtml(b.p)}</p>`;
115 if ("md" in b)
116 return `<div class="md box" style="margin:0 0 16px;padding:14px 16px;border:1px solid ${C.border};border-radius:8px;font-size:14px;line-height:1.6;color:${C.fg};overflow-wrap:anywhere">${markdownHtml(b.md, ctx.publicUrl, b.base) || `<span style="color:${C.fg3}">No description provided.</span>`}</div>`;
117 if ("kv" in b)
118 return `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" class="box" style="margin:0 0 16px;border:1px solid ${C.border};border-radius:8px;border-collapse:separate">${b.kv
119 .map(
120 ([k, v], i) =>
121 `<tr><td class="muted" style="padding:9px 14px;${i ? `border-top:1px solid ${C.border};` : ""}font-size:13px;color:${C.fg3};width:130px;vertical-align:top">${esc(k)}</td><td class="fg" style="padding:9px 14px;${i ? `border-top:1px solid ${C.border};` : ""}font-size:13px;color:${C.fg};overflow-wrap:anywhere">${inlineHtml(v)}</td></tr>`,
122 )
123 .join("")}</table>`;
124 if ("button" in b) {
125 const btn = (l: { label: string; url: string }, primary: boolean) =>
126 `<a href="${esc(l.url)}" style="display:inline-block;padding:10px 18px;border-radius:8px;font-size:14px;font-weight:600;text-decoration:none;${primary ? `background:${C.accent};color:#ffffff;border:1px solid ${C.accent}` : `background:${C.card};color:${C.fg};border:1px solid ${C.border}`}" class="${primary ? "" : "btn2"}">${esc(l.label)}</a>`;
127 return `<p style="margin:6px 0 18px">${btn(b.button, true)}${b.secondary ? `&nbsp;&nbsp;${btn(b.secondary, false)}` : ""}</p>`;
128 }
129 if ("callout" in b) {
130 const [bg, fg] = C.tones[b.tone === "info" ? "blue" : b.tone === "warn" ? "amber" : "red"]!;
131 return `<div style="margin:0 0 16px;padding:12px 14px;border-radius:8px;background:${bg};color:${fg};font-size:13.5px;line-height:1.55">${inlineHtml(b.callout)}</div>`;
132 }
133 if ("code" in b)
134 return `<pre class="md" style="margin:0 0 16px;padding:12px 14px;border-radius:8px;background:${C.codeBg};font-family:${MONO};font-size:12.5px;line-height:1.55;color:${C.fg};white-space:pre-wrap;overflow-wrap:anywhere">${esc(b.code)}</pre>`;
135 if ("quote" in b) return `<div class="muted" style="margin:0 0 16px;padding:2px 0 2px 14px;border-left:3px solid ${C.border};color:${C.fg2};font-size:14px;line-height:1.6">${inlineHtml(b.quote)}</div>`;
136 if ("plain" in b)
137 return `<div class="md box" style="margin:0 0 16px;padding:14px 16px;border:1px solid ${C.border};border-radius:8px;font-size:14px;line-height:1.6;color:${C.fg};white-space:pre-wrap;overflow-wrap:anywhere">${esc(b.plain)}</div>`;
138 const marks = { ok: ["✓", C.tones.green![1]], fail: ["✕", C.tones.red![1]], skip: ["–", C.fg3], dot: ["•", C.fg3] } as const;
139 return `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" class="box" style="margin:0 0 16px;border:1px solid ${C.border};border-radius:8px;border-collapse:separate">${b.items
140 .map(
141 (it, i) =>
142 `<tr><td style="padding:8px 0 8px 14px;${i ? `border-top:1px solid ${C.border};` : ""}width:18px;font-size:14px;font-weight:700;color:${marks[it.mark][1]};vertical-align:top">${marks[it.mark][0]}</td><td class="fg" style="padding:8px 14px 8px 8px;${i ? `border-top:1px solid ${C.border};` : ""}font-size:13.5px;color:${C.fg};overflow-wrap:anywhere">${it.url ? `<a href="${esc(it.url)}" style="color:${C.fg};text-decoration:none">${inlineHtml(it.text)}</a>` : inlineHtml(it.text)}</td></tr>`,
143 )
144 .join("")}</table>`;
145}
146
147function blockText(b: Block): string {
148 if ("p" in b) return inlineText(b.p);
149 if ("md" in b) return (stripHtmlComments(b.md).trim() || "No description provided.").split("\n").map((l) => `> ${l}`.trimEnd()).join("\n");
150 if ("kv" in b) return b.kv.map(([k, v]) => `${k}: ${inlineText(v)}`).join("\n");
151 if ("button" in b) return `${b.button.label}: ${b.button.url}${b.secondary ? `\n${b.secondary.label}: ${b.secondary.url}` : ""}`;
152 if ("callout" in b) return `! ${inlineText(b.callout)}`;
153 if ("code" in b) return b.code.split("\n").map((l) => ` ${l}`).join("\n");
154 if ("quote" in b) return `> ${inlineText(b.quote)}`;
155 if ("plain" in b) return b.plain.split("\n").map((l) => `> ${l}`.trimEnd()).join("\n");
156 const marks = { ok: "[ok]", fail: "[failed]", skip: "[skipped]", dot: "-" };
157 return b.items.map((it) => `${marks[it.mark]} ${inlineText(it.text)}${it.url ? ` <${it.url}>` : ""}`).join("\n");
158}
159
160export const REASON_TEXT: Record<Reason, string> = {
161 author: "You are receiving this because you opened this thread.",
162 comment: "You are receiving this because you commented.",
163 mention: "You are receiving this because you were mentioned.",
164 assign: "You are receiving this because you were assigned.",
165 review_requested: "You are receiving this because your review was requested.",
166 manual: "You are receiving this because you subscribed to this thread.",
167 state_change: "You are receiving this because you changed this thread's state.",
168 subscribed: "You are receiving this because you are watching this repository.",
169 ci_activity: "You are receiving this because this workflow run was triggered by you, or you watch this repository.",
170 security_alert: "This is a security notice about your Diffinery account. These can't be turned off.",
171 your_activity: "You are receiving this because of something you did on Diffinery.",
172 invitation: "You are receiving this because someone invited this email address to Diffinery. If you weren't expecting it, you can ignore this email.",
173 admin: "You are receiving this because you are an administrator.",
174 account: "You are receiving this because you have a Diffinery account.",
175 signup: "You are receiving this because someone asked to create a Diffinery account with this email address. If it wasn't you, you can ignore this email.",
176 early_access: "You are receiving this because someone asked for early access to Diffinery with this email address. If it wasn't you, you can ignore this email.",
177 contact: "You are receiving this because someone sent a message through Diffinery's contact form with this email address. If it wasn't you, you can ignore this email.",
178 digest: "You are receiving this because you turned on the morning digest in your notification settings.",
179};
180
181const LOGO = (url: string) => `${url}/icon-512.png`;
182
183/** Full HTML document. */
184export function toHtml(e: Email, ctx: RenderCtx): string {
185 const tone = e.eyebrow ? C.tones[e.eyebrow.tone]! : null;
186 const footerLinks = [
187 ...(e.url ? [{ label: "View it on Diffinery", url: e.url }] : []),
188 ...(ctx.unsubscribe ?? []),
189 ...(ctx.settingsUrl ? [{ label: "Notification settings", url: ctx.settingsUrl }] : []),
190 ];
191 return `<!doctype html>
192<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light dark"><meta name="supported-color-schemes" content="light dark"><title>${esc(e.subject)}</title>
193<style>
194body{margin:0;padding:0;-webkit-text-size-adjust:100%}
195.md p{margin:0 0 10px}.md p:last-child{margin-bottom:0}
196.md pre{background:${C.codeBg};padding:10px 12px;border-radius:6px;overflow:auto;font-family:${MONO};font-size:12.5px;line-height:1.5;white-space:pre-wrap}
197.md code{background:${C.codeBg};border-radius:4px;padding:1px 4px;font-family:${MONO};font-size:12.5px}
198.md pre code{padding:0;background:none}
199.md blockquote{margin:0 0 10px;padding:0 12px;border-left:3px solid ${C.border};color:${C.fg3}}
200.md table{border-collapse:collapse;margin:0 0 10px}.md td,.md th{border:1px solid ${C.border};padding:4px 8px}
201.md img{max-width:100%;height:auto}.md a{color:${C.accent}}.md h1,.md h2,.md h3{font-size:16px;margin:12px 0 8px}
202.md ul,.md ol{padding-left:22px;margin:0 0 10px}
203@media (prefers-color-scheme:dark){
204.bg{background:#0a0a0a !important}.card{background:#171717 !important;border-color:#2e2e2e !important}
205.fg,.fg a,h1.fg{color:#f4f4f5 !important}.muted{color:#a3a3a3 !important}.box{border-color:#2e2e2e !important}
206.box td{border-color:#2e2e2e !important}.md,.md td,.md th{color:#e4e4e7 !important}.md pre,.md code,pre.md,code.code{background:#262626 !important;color:#f4f4f5 !important}
207.btn2{background:#262626 !important;color:#f4f4f5 !important;border-color:#3f3f46 !important}}
208@media (max-width:620px){.card{border-radius:0 !important;padding:22px 18px !important}.outer{padding:0 !important}}
209</style></head>
210<body class="bg" style="margin:0;padding:0;background:${C.canvas}">
211<div style="display:none;max-height:0;overflow:hidden;opacity:0;color:transparent">${esc(e.preheader)}${"&#8199;&#65279;&#847; ".repeat(30)}</div>
212<table role="presentation" width="100%" cellpadding="0" cellspacing="0" class="bg" style="background:${C.canvas};font-family:${FONT}">
213<tr><td align="center" class="outer" style="padding:28px 12px">
214<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:600px">
215<tr><td style="padding:0 4px 14px">
216<table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tr>
217<td style="vertical-align:middle"><a href="${esc(ctx.publicUrl)}" style="text-decoration:none"><img src="${esc(LOGO(ctx.publicUrl))}" width="26" height="26" alt="" style="vertical-align:middle;border:0;border-radius:6px"> <span class="fg" style="vertical-align:middle;font-size:16px;font-weight:650;color:${C.fg};letter-spacing:-.01em">Diffinery</span></a></td>
218${e.context ? `<td align="right" style="vertical-align:middle;font-size:13px"><a href="${esc(e.context.url)}" class="muted" style="color:${C.fg3};text-decoration:none">${esc(e.context.label)}</a></td>` : ""}
219</tr></table>
220</td></tr>
221<tr><td class="card" style="background:${C.card};border:1px solid ${C.border};border-radius:12px;padding:28px 32px">
222${e.eyebrow && tone ? `<div style="margin:0 0 12px"><span style="display:inline-block;padding:3px 9px;border-radius:999px;background:${tone[0]};color:${tone[1]};font-size:12px;font-weight:600">${esc(e.eyebrow.text)}</span></div>` : ""}
223<h1 class="fg" style="margin:0 0 16px;font-size:20px;line-height:1.35;font-weight:650;color:${C.fg};letter-spacing:-.01em">${inlineHtml(e.title)}</h1>
224${e.blocks.map((b) => blockHtml(b, ctx)).join("\n")}
225</td></tr>
226<tr><td class="muted" style="padding:18px 8px 0;font-size:12px;line-height:1.6;color:${C.fg3}">
227<p style="margin:0 0 6px">${esc(REASON_TEXT[ctx.reason])}</p>
228${footerLinks.length ? `<p style="margin:0 0 6px">${footerLinks.map((l) => `<a href="${esc(l.url)}" style="color:${C.fg3};text-decoration:underline">${esc(l.label)}</a>`).join(" &middot; ")}</p>` : ""}
229<p style="margin:0">Diffinery &middot; Code hosting and CI on Cloudflare &middot; <a href="${esc(ctx.publicUrl)}" style="color:${C.fg3}">${esc(new URL(ctx.publicUrl).host)}</a></p>
230</td></tr>
231</table>
232</td></tr></table>
233</body></html>`;
234}
235
236export function toText(e: Email, ctx: RenderCtx): string {
237 const lines = [inlineText(e.title), "", ...e.blocks.map(blockText).flatMap((t) => [t, ""])];
238 lines.push("--", REASON_TEXT[ctx.reason]);
239 if (e.url) lines.push(`View it on Diffinery: ${e.url}`);
240 for (const u of ctx.unsubscribe ?? []) lines.push(`${u.label}: ${u.url}`);
241 if (ctx.settingsUrl) lines.push(`Notification settings: ${ctx.settingsUrl}`);
242 return lines.join("\n").replace(/\n{3,}/g, "\n\n").trim() + "\n";
243}
244
245// ---------------------------------------------------------------- the emails
246
247const at = (iso: string) => new Date(iso).toUTCString().replace("GMT", "UTC");
248const day = (iso: string) => new Date(iso).toLocaleDateString("en-US", { dateStyle: "long", timeZone: "UTC" });
249const user = (login: string) => `@${login}`;
250const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
251const ROLE_TEXT: Record<string, string> = { read: "read", triage: "triage", write: "write", maintain: "maintain", admin: "admin", member: "member", owner: "owner" };
252const roleText = (r: string) => ROLE_TEXT[r] ?? r;
253const mib = (n: number) => (n < 1024 * 1024 ? `${Math.max(1, Math.round(n / 1024))} KB` : `${(n / 1024 / 1024).toFixed(1)} MB`);
254const article = (w: string) => (/^[aeiou]/i.test(w) ? "an" : "a");
255
256/** The domain email is sent from: MAIL_FROM's, else PUBLIC_URL's host. */
257function mailDomain(pub: string, mailFrom?: string): string {
258 const at = mailFrom?.lastIndexOf("@") ?? -1;
259 if (mailFrom && at >= 0) return mailFrom.slice(at + 1).replace(/>.*$/, "").trim();
260 try {
261 return new URL(pub).hostname;
262 } catch {
263 return pub;
264 }
265}
266
267function repoContext(pub: string, repo: string) {
268 return { label: repo, url: `${pub}/${repo}` };
269}
270
271function threadEmail(d: ThreadData, pub: string, login?: string): Email {
272 const isPull = d.kind === "pull";
273 const noun = isPull ? "pull request" : "issue";
274 const tag = `${isPull ? "PR" : "Issue"} #${d.number}`;
275 const threadUrl = `${pub}/${d.repo}/${isPull ? "pull" : "issues"}/${d.number}`;
276 const [owner, name] = d.repo.split("/") as [string, string];
277 const mdBase = { owner, repo: name, ref: d.base ?? "HEAD" };
278 const subject = `${d.event === "opened" ? "" : "Re: "}[${d.repo}] ${d.title} (${tag})`;
279 const me = (l: string) => !!login && l.toLowerCase() === login.toLowerCase();
280 let title: Inline[];
281 let eyebrow: Email["eyebrow"] = { text: isPull ? "Pull request" : "Issue", tone: isPull ? "purple" : "green" };
282 const blocks: Block[] = [];
283 const ref: Inline = { a: `${d.repo}#${d.number}`, href: threadUrl };
284 switch (d.event) {
285 case "opened":
286 title = isPull ? [user(d.actor), " wants to merge ", { code: d.head ?? "" }, " into ", { code: d.base ?? "" }] : [user(d.actor), " opened ", ref];
287 blocks.push({ p: [{ b: d.title }] });
288 if (isPull && d.intent) blocks.push({ callout: [{ b: "Intent: " }, d.intent], tone: "info" });
289 blocks.push({ md: d.body ?? "", base: mdBase });
290 if (d.commits?.length) blocks.push({ items: d.commits.slice(0, 10).map((c) => ({ mark: "dot" as const, text: [{ code: c.sha.slice(0, 7) }, " ", c.message.split("\n")[0]!.slice(0, 120)] })) });
291 if (d.reviewers?.length) blocks.push({ p: ["Review requested from ", d.reviewers.map(user).join(", "), "."], muted: true });
292 if (d.assignees?.length) blocks.push({ p: ["Assigned to ", d.assignees.map(user).join(", "), "."], muted: true });
293 blocks.push({ button: { label: `View ${noun}`, url: threadUrl }, ...(isPull ? { secondary: { label: "Files changed", url: `${threadUrl}/files` } } : {}) });
294 break;
295 case "comment":
296 title = [user(d.actor), " commented on ", ref];
297 blocks.push({ md: d.body ?? "", base: mdBase }, { button: { label: "Reply on Diffinery", url: d.url } });
298 break;
299 case "review": {
300 const s = d.state ?? "COMMENTED";
301 title = s === "APPROVED" ? [user(d.actor), " approved ", ref] : s === "CHANGES_REQUESTED" ? [user(d.actor), " requested changes on ", ref] : [user(d.actor), " reviewed ", ref];
302 eyebrow = s === "APPROVED" ? { text: "Approved", tone: "green" } : s === "CHANGES_REQUESTED" ? { text: "Changes requested", tone: "red" } : { text: "Review", tone: "purple" };
303 if (d.body?.trim()) blocks.push({ md: d.body, base: mdBase });
304 blocks.push({ button: { label: "View review", url: d.url }, secondary: { label: "Files changed", url: `${threadUrl}/files` } });
305 break;
306 }
307 case "closed":
308 title = [user(d.actor), " closed ", ref, d.stateReason === "not_planned" ? " as not planned" : isPull ? "" : " as completed"];
309 eyebrow = { text: "Closed", tone: isPull ? "red" : "purple" };
310 blocks.push({ p: [{ b: d.title }] }, { button: { label: `View ${noun}`, url: threadUrl } });
311 break;
312 case "merged":
313 title = [user(d.actor), " merged ", ref, " into ", { code: d.base ?? "" }];
314 eyebrow = { text: "Merged", tone: "purple" };
315 blocks.push({ p: [{ b: d.title }] }, { button: { label: "View pull request", url: threadUrl } });
316 break;
317 case "reopened":
318 title = [user(d.actor), " reopened ", ref];
319 eyebrow = { text: "Reopened", tone: "green" };
320 blocks.push({ p: [{ b: d.title }] }, { button: { label: `View ${noun}`, url: threadUrl } });
321 break;
322 case "assigned": {
323 const who = d.assignees ?? [];
324 title = who.some(me) ? [user(d.actor), " assigned you to ", ref] : [user(d.actor), " assigned ", who.map(user).join(", "), " to ", ref];
325 blocks.push({ p: [{ b: d.title }] }, { button: { label: `View ${noun}`, url: threadUrl } });
326 break;
327 }
328 case "review_requested": {
329 const who = d.reviewers ?? [];
330 title = who.some(me) ? [user(d.actor), " requested your review on ", ref] : [user(d.actor), " requested a review from ", who.map(user).join(", "), " on ", ref];
331 eyebrow = { text: "Review requested", tone: "amber" };
332 blocks.push({ p: [{ b: d.title }] });
333 if (d.intent) blocks.push({ callout: [{ b: "Intent: " }, d.intent], tone: "info" });
334 blocks.push({ button: { label: "Review changes", url: `${threadUrl}/files` }, secondary: { label: "View pull request", url: threadUrl } });
335 break;
336 }
337 case "pushed": {
338 const n = d.commits?.length ?? 0;
339 title = [user(d.actor), ` pushed ${n ? plural(n, "commit") : "new commits"} to `, { code: d.head ?? "" }];
340 blocks.push({ p: [ref, " ", { b: d.title }] });
341 if (n) blocks.push({ items: d.commits!.slice(-10).map((c) => ({ mark: "dot" as const, text: [{ code: c.sha.slice(0, 7) }, " ", c.message.split("\n")[0]!.slice(0, 120)], url: `${pub}/${d.repo}/commit/${c.sha}` })) });
342 blocks.push({ button: { label: "View changes", url: `${threadUrl}/files` } });
343 break;
344 }
345 }
346 return { subject, preheader: stripHtmlComments(d.body ?? "").trim().slice(0, 140) || `${inlineText(title)}`, eyebrow, title, blocks, fromName: d.actor, context: repoContext(pub, d.repo), thread: `${d.repo}/${isPull ? "pull" : "issues"}/${d.number}`, url: d.url };
347}
348
349function runEmail(d: RunData, pub: string): Email {
350 const failed = d.conclusion === "failure" || d.conclusion === "timed_out";
351 const sha = d.sha.slice(0, 7);
352 const word = failed ? "failed" : d.conclusion === "success" ? "succeeded" : d.conclusion;
353 return {
354 subject: `[${d.repo}] Run ${word}: ${d.workflow} - ${d.branch} (${sha})`,
355 preheader: `${d.workflow} #${d.runNumber} ${word} on ${d.branch}: ${d.title}`,
356 eyebrow: failed ? { text: "Workflow run failed", tone: "red" } : { text: `Workflow run ${word}`, tone: d.conclusion === "success" ? "green" : "neutral" },
357 title: [{ b: d.workflow }, ` #${d.runNumber} ${word} on `, { code: d.branch }],
358 blocks: [
359 {
360 kv: [
361 ["Repository", [{ a: d.repo, href: `${pub}/${d.repo}` }]],
362 ["Commit", [{ a: sha, href: `${pub}/${d.repo}/commit/${d.sha}` }, " ", d.title]],
363 ["Triggered by", `${d.event} by @${d.actor}`],
364 ],
365 },
366 { items: d.jobs.slice(0, 20).map((j) => ({ mark: j.conclusion === "success" ? ("ok" as const) : j.conclusion === "failure" || j.conclusion === "timed_out" ? ("fail" as const) : ("skip" as const), text: [j.name, j.failure ? ` — ${j.failure.slice(0, 160)}` : j.conclusion && !["success", "failure", "skipped"].includes(j.conclusion) ? ` (${j.conclusion.replace(/_/g, " ")})` : ""], url: j.url })) },
367 { button: { label: "View workflow run", url: d.url } },
368 ],
369 context: repoContext(pub, d.repo),
370 url: d.url,
371 };
372}
373
374/** Build the email for a job. `login` is the recipient's login when they have an account. */
375/** `mailFrom`: the sender (MAIL_FROM), named in the test email; without it, PUBLIC_URL's host. */
376export function compose(job: MailJob, pub: string, login?: string, mailFrom?: string): Email {
377 const settings = `${pub}/settings/security`;
378 const securityTip: Block = { callout: ["If this wasn't you, sign out of every other browser and remove any passkey or token you don't recognize under ", { a: "Passkeys and sessions", href: settings }, ", then tell a site administrator."], tone: "warn" };
379 switch (job.kind) {
380 case "thread":
381 return threadEmail(job.data, pub, login);
382 case "run":
383 return runEmail(job.data, pub);
384 case "signin_new": {
385 const d = job.data;
386 const how = d.method === "access" ? "email recovery" : d.method === "link" ? "a one-time sign-in link" : `the passkey “${d.passkey ?? "passkey"}”`;
387 return {
388 subject: "[Diffinery] New sign-in to your account",
389 preheader: `Signed in with ${how} on ${d.device}.`,
390 eyebrow: { text: "Security", tone: "red" },
391 title: ["New sign-in to ", { b: user(login ?? "your account") }],
392 blocks: [
393 { p: [`Your Diffinery account was just signed in to from a browser or device it hasn't seen before, using ${how}.`] },
394 { kv: [["When", at(job.at)], ["Device", d.device], ...(d.location ? ([["Location", d.location]] as Array<[string, string]>) : []), ...(d.ip ? ([["IP address", d.ip]] as Array<[string, string]>) : [])] },
395 securityTip,
396 { button: { label: "Review passkeys and sessions", url: settings } },
397 ],
398 url: settings,
399 };
400 }
401 case "passkey_added":
402 return {
403 subject: "[Diffinery] A passkey was added to your account",
404 preheader: `The passkey “${job.data.name}” can now sign in to your account.`,
405 eyebrow: { text: "Security", tone: "red" },
406 title: ["A passkey was added to your account"],
407 blocks: [
408 { p: ["The passkey ", { b: `“${job.data.name}”` }, job.data.via === "signin-link" ? " was added with a one-time sign-in link from an administrator." : " was added to your account.", " It can now sign you in."] },
409 { kv: [["When", at(job.at)], ["Passkey", job.data.name]] },
410 securityTip,
411 { button: { label: "Review passkeys", url: settings } },
412 ],
413 url: settings,
414 };
415 case "passkey_removed":
416 return {
417 subject: "[Diffinery] A passkey was removed from your account",
418 preheader: `The passkey “${job.data.name}” can no longer sign in.`,
419 eyebrow: { text: "Security", tone: "red" },
420 title: ["A passkey was removed from your account"],
421 blocks: [{ p: ["The passkey ", { b: `“${job.data.name}”` }, " was removed and can no longer sign in. Browsers it signed in were signed out."] }, { kv: [["When", at(job.at)]] }, securityTip, { button: { label: "Review passkeys", url: settings } }],
422 url: settings,
423 };
424 case "token_created": {
425 const d = job.data;
426 const page = d.agent ? `${pub}/settings/agents` : `${pub}/settings/tokens`;
427 return {
428 subject: d.agent ? `[Diffinery] A token was created for the agent ${d.agent}` : "[Diffinery] A personal access token was added to your account",
429 preheader: `“${d.name}” with ${d.scopes.join(", ")} access.`,
430 eyebrow: { text: "Security", tone: "red" },
431 title: d.agent ? ["A token was created for ", { b: user(d.agent) }] : ["A personal access token was added to your account"],
432 blocks: [
433 { p: [d.agent ? "Anything holding this token can act as the agent, within its policy." : "Anything holding this token can use Git, the API, the CLI and MCP as you, within its scopes."] },
434 { kv: [["Name", d.name], ["Scopes", d.scopes.join(", ")], ["When", at(job.at)]] },
435 { callout: ["If you didn't create this token, revoke it now."], tone: "warn" },
436 { button: { label: d.agent ? "Review agents" : "Review tokens", url: page } },
437 ],
438 url: page,
439 };
440 }
441 case "token_expiring": {
442 const d = job.data;
443 const page = d.agent ? `${pub}/settings/agents` : `${pub}/settings/tokens`;
444 return {
445 subject: `[Diffinery] Your token “${d.name}” expires on ${day(d.expiresAt)}`,
446 preheader: "Create a new token before then so Git, CI and agents keep working.",
447 eyebrow: { text: "Token expiring", tone: "amber" },
448 title: ["Your token ", { b: `“${d.name}”` }, ` expires on ${day(d.expiresAt)}`],
449 blocks: [
450 { p: [d.agent ? `The token for the agent @${d.agent}` : "This personal access token", " stops working then. Create a new one and swap it in wherever the old one is used (Git credentials, CI secrets, MCP clients)."] },
451 { kv: [["Name", d.name], ["Starts with", [{ code: `${d.prefix}…` }]], ["Expires", at(d.expiresAt)]] },
452 { button: { label: "Create a new token", url: page } },
453 ],
454 url: page,
455 };
456 }
457 case "agent_created":
458 return {
459 subject: `[Diffinery] A new agent was added: ${job.data.agent}`,
460 preheader: `The agent @${job.data.agent} can act on your behalf once it has a token.`,
461 eyebrow: { text: "Security", tone: "red" },
462 title: ["A new agent was added: ", { b: user(job.data.agent) }],
463 blocks: [
464 { p: ["Agents act on behalf of their owner, capped by their policy. They can't push to protected branches, and their pull requests need a human approval."] },
465 { kv: [["Agent", user(job.data.agent)], ["When", at(job.at)]] },
466 { callout: ["If you didn't add this agent, disable it now."], tone: "warn" },
467 { button: { label: "Review agents", url: `${pub}/settings/agents` } },
468 ],
469 url: `${pub}/settings/agents`,
470 };
471 case "model_key_added": {
472 const d = job.data;
473 if (d.org) {
474 const page = `${pub}/${d.org}?tab=settings#model-keys`;
475 return {
476 subject: `[Diffinery] An ${d.provider} API key was added to ${d.org}`,
477 preheader: `Agents in ${d.org}'s repositories can now run on the organization's ${d.provider} key.`,
478 eyebrow: { text: "Security", tone: "red" },
479 title: [`An ${d.provider} API key was added to `, { b: d.org }],
480 blocks: [
481 { p: [`Agent runs that ${d.org}'s policy lets the organization pay for will use this key, and the provider bills the organization's account. Diffinery never shows the key again. You get this email because you're an owner of ${d.org}.`] },
482 { kv: [["Organization", d.org], ["Provider", d.provider], ["Ends with", [{ code: `…${d.hint}` }]], ...(d.by ? ([["Added by", user(d.by)]] as Array<[string, string]>) : []), ["When", at(job.at)]] },
483 { callout: ["If nobody in the organization added this key, delete it here and revoke it with the provider."], tone: "warn" },
484 { button: { label: "Review the organization's model keys", url: page } },
485 ],
486 url: page,
487 };
488 }
489 const page = `${pub}/settings/model-access`;
490 return {
491 subject: `[Diffinery] Your ${d.provider} API key was added to Diffinery`,
492 preheader: `Agent tasks you start can now use your ${d.provider} key.`,
493 eyebrow: { text: "Security", tone: "red" },
494 title: [`Your ${d.provider} API key was added to Diffinery`],
495 blocks: [
496 { p: ["Agent tasks you start will use this key, and the provider bills your account for them. Diffinery never shows the key again."] },
497 { kv: [["Provider", d.provider], ["Ends with", [{ code: `…${d.hint}` }]], ["When", at(job.at)]] },
498 { callout: ["If you didn't add this key, delete it here and revoke it with the provider."], tone: "warn" },
499 { button: { label: "Review model access", url: page } },
500 ],
501 url: page,
502 };
503 }
504 case "review_limit_reached": {
505 const d = job.data;
506 const page = `${pub}/${d.repo}/settings/agent-review`;
507 return {
508 subject: `[${d.repo}] Agent review reached its daily limit`,
509 preheader: `${d.limit} reviews ran with your model key in the last 24 hours, so new ones wait.`,
510 eyebrow: { text: "Agent review", tone: "amber" },
511 title: ["Agent review on ", { a: d.repo, href: `${pub}/${d.repo}` }, " reached its daily limit"],
512 blocks: [
513 { p: [`Agent reviews on this repository use your model key. ${d.limit} ran in the last 24 hours, the daily limit you set, so pull requests get an action-required check instead of a review until older reviews fall out of the 24 hours. Then reviews run again when someone asks or pushes.`] },
514 { kv: [["Repository", d.repo], ["Daily limit", String(d.limit)], ["Last pull request", [{ a: `#${d.pr}`, href: `${pub}/${d.repo}/pull/${d.pr}` }]], ["When", at(job.at)]] },
515 { callout: ["If this is more reviews than you expected, look at which pull requests ran them on the Tasks tab. Something may be pushing often, or asking for reviews."], tone: "warn" },
516 { button: { label: "Agent review settings", url: page } },
517 ],
518 context: repoContext(pub, d.repo),
519 url: page,
520 };
521 }
522 case "deployment_review_requested": {
523 const d = job.data;
524 return {
525 subject: `[${d.repo}] Deployment to ${d.environment} is waiting for your review`,
526 preheader: `${d.requestor}'s ${d.workflow} run #${d.runNumber} on ${d.branch} waits for a required reviewer before it deploys to ${d.environment}.`,
527 eyebrow: { text: "Deployment review", tone: "amber" },
528 title: ["Deploy to ", { b: d.environment }, " in ", { a: d.repo, href: `${pub}/${d.repo}` }, "?"],
529 blocks: [
530 { p: [`You're a required reviewer for the ${d.environment} environment. Its jobs in this run wait, with no runner started and no secret handed out, until a reviewer approves or rejects them. One approval is enough.`] },
531 { kv: [["Run", [{ a: `${d.workflow} #${d.runNumber}`, href: d.url }]], ["Title", d.title || d.workflow], ["Branch", [{ code: d.branch }]], ["Commit", [{ code: d.sha.slice(0, 12) }]], ["Started by", d.requestor], ["When", at(job.at)]] },
532 { button: { label: "Review deployment", url: d.url } },
533 ],
534 context: repoContext(pub, d.repo),
535 url: d.url,
536 };
537 }
538 case "push_bypassed": {
539 const d = job.data;
540 return {
541 subject: `[${d.repo}] Push protection was bypassed`,
542 preheader: `@${d.pusher} pushed ${d.kinds.join(", ")} past push protection: ${d.reason}`,
543 eyebrow: { text: "Push protection bypassed", tone: "amber" },
544 title: [user(d.pusher), " pushed possible secrets to ", { a: d.repo, href: `${pub}/${d.repo}` }],
545 blocks: [
546 { p: ["Push protection found possible secrets, and a repository admin pushed anyway with a reason. The bypass is in the audit log."] },
547 { kv: [["Pushed by", user(d.pusher)], ["Secrets", d.kinds.join(", ")], ["Reason", d.reason], ...(d.refs?.length ? ([["Refs", d.refs.join(", ")]] as Array<[string, string]>) : []), ["When", at(job.at)]] },
548 { callout: ["If any of these are real credentials, rotate them now: removing them from Git history doesn't make them safe again."], tone: "danger" },
549 { button: { label: "View repository", url: `${pub}/${d.repo}` } },
550 ],
551 context: repoContext(pub, d.repo),
552 url: `${pub}/${d.repo}`,
553 };
554 }
555 case "push_blocked": {
556 const d = job.data;
557 // A commit made without git (web editor, API or MCP) carries the files it was refused for.
558 if (d.paths)
559 return {
560 subject: `[${d.repo}] Your commit was blocked: possible secrets`,
561 preheader: `Found ${d.kinds.join(", ")}. Nothing was committed.`,
562 eyebrow: { text: "Push protection", tone: "red" },
563 title: ["Your commit to ", { a: d.repo, href: `${pub}/${d.repo}` }, " was blocked"],
564 blocks: [
565 { p: ["Push protection found what look like secrets in the files you tried to commit, so nothing was committed."] },
566 { kv: [["Found", d.kinds.join(", ")], ...(d.paths.length ? ([["Files", d.paths.join(", ")]] as Array<[string, string]>) : []), ["When", at(job.at)]] },
567 { p: ["Remove the secret and commit again. If it was a real credential, rotate it. For a test fixture, add a ", { code: "diffinery:allow-secret" }, " comment to the file."] },
568 ],
569 context: repoContext(pub, d.repo),
570 url: `${pub}/${d.repo}`,
571 };
572 return {
573 subject: `[${d.repo}] Your push was blocked: possible secrets`,
574 preheader: `Found ${d.kinds.join(", ")}. Nothing from the push was kept.`,
575 eyebrow: { text: "Push protection", tone: "red" },
576 title: ["Your push to ", { a: d.repo, href: `${pub}/${d.repo}` }, " was blocked"],
577 blocks: [
578 { p: ["Push protection found what look like secrets in your commits, so nothing from this push was kept."] },
579 { kv: [["Found", d.kinds.join(", ")], ...(d.refs?.length ? ([["Refs", d.refs.join(", ")]] as Array<[string, string]>) : []), ["When", at(job.at)]] },
580 { p: ["Remove the secret from your commits (for example with ", { code: "git commit --amend" }, " or an interactive rebase) and push again. If it was a real credential, rotate it. For a test fixture, add a ", { code: "diffinery:allow-secret" }, " comment to the file. A repository admin can push past the check with ", { code: "git push -o allow-secrets=<reason>" }, ", which is audited."] },
581 ],
582 context: repoContext(pub, d.repo),
583 url: `${pub}/${d.repo}`,
584 };
585 }
586 case "account_status":
587 if (job.data.status === "suspended")
588 return {
589 subject: "[Diffinery] Your account was suspended",
590 preheader: "You can't sign in, and your tokens, agents and runners don't work while it lasts.",
591 eyebrow: { text: "Account", tone: "red" },
592 title: ["Your Diffinery account was suspended"],
593 blocks: [
594 { p: ["A site administrator suspended your account. While it is suspended you can't sign in, your access tokens, agents and runners don't work, and your repositories, profile and comments are hidden from other people."] },
595 ...(job.data.reason ? [{ kv: [["Reason", job.data.reason]] as Array<[string, string]> }] : []),
596 { p: ["If you think this is a mistake, contact an administrator of this Diffinery instance."], muted: true },
597 ],
598 };
599 if (job.data.status === "unsuspended")
600 return {
601 subject: "[Diffinery] Your account is no longer suspended",
602 preheader: "You can sign in again; your tokens work again.",
603 eyebrow: { text: "Account", tone: "green" },
604 title: ["Your Diffinery account is no longer suspended"],
605 blocks: [{ p: ["A site administrator lifted the suspension of your account. Sign in with your passkey; your access tokens, agents and runners work again, and your repositories and comments are visible again."] }, { button: { label: "Sign in", url: `${pub}/login` } }],
606 url: `${pub}/login`,
607 };
608 return job.data.status === "disabled"
609 ? {
610 subject: "[Diffinery] Your account was disabled",
611 preheader: "You can't sign in, and your tokens were revoked.",
612 eyebrow: { text: "Account", tone: "red" },
613 title: ["Your Diffinery account was disabled"],
614 blocks: [{ p: ["A site administrator disabled your account. You can't sign in, and every access token you had was revoked."] }, { p: ["If you think this is a mistake, contact an administrator of this Diffinery instance."], muted: true }],
615 }
616 : {
617 subject: "[Diffinery] Your account was enabled",
618 preheader: "You can sign in with your passkey again.",
619 eyebrow: { text: "Account", tone: "green" },
620 title: ["Your Diffinery account was enabled"],
621 blocks: [{ p: ["A site administrator enabled your account again. Sign in with your passkey, and create new access tokens: the old ones were revoked when the account was disabled."] }, { button: { label: "Sign in", url: `${pub}/login` } }],
622 url: `${pub}/login`,
623 };
624 case "account_deleted":
625 return {
626 subject: "[Diffinery] Your account was deleted",
627 preheader: `@${job.data.login} and its repositories are gone.`,
628 eyebrow: { text: "Account", tone: "red" },
629 title: ["Your Diffinery account ", { b: user(job.data.login) }, " was deleted"],
630 blocks: [
631 { p: [job.data.by ? `A site administrator, ${user(job.data.by)}, deleted your account.` : "You deleted your account.", " Your repositories, container images, access tokens, passkeys and settings are gone, and every browser was signed out. Issues, pull requests and comments you wrote in other people's repositories stay, shown as written by ", { b: "ghost" }, "."] },
632 { p: [`Your username can be used again, by anyone, ${job.data.cooldownDays} days from now. This is the last email you get from this Diffinery instance.`], muted: true },
633 ],
634 };
635 case "site_admin":
636 return job.data.granted
637 ? {
638 subject: "[Diffinery] You are now a site administrator",
639 preheader: `${user(job.data.by)} made you a site administrator.`,
640 eyebrow: { text: "Security", tone: "amber" },
641 title: ["You are now a site administrator"],
642 blocks: [
643 { p: [user(job.data.by), " made you a site administrator of this Diffinery instance. You have admin on every repository and organization, and the Site administration pages in Settings."] },
644 { button: { label: "Open Site administration", url: `${pub}/settings/admin` } },
645 { callout: ["If you didn't expect this, tell another site administrator."], tone: "warn" },
646 ],
647 url: `${pub}/settings/admin`,
648 }
649 : {
650 subject: "[Diffinery] You are no longer a site administrator",
651 preheader: `${user(job.data.by)} removed your site administration.`,
652 eyebrow: { text: "Security", tone: "amber" },
653 title: ["You are no longer a site administrator"],
654 blocks: [{ p: [user(job.data.by), " removed you from the site administrators of this Diffinery instance. Your own repositories and organizations are unchanged."] }],
655 };
656 case "export_ready":
657 return {
658 subject: "[Diffinery] Your account export is ready",
659 preheader: `Download it before ${day(job.data.expiresAt)}.`,
660 eyebrow: { text: "Account", tone: "green" },
661 title: ["Your account export is ready"],
662 blocks: [
663 { p: [`The archive of your account (${mib(job.data.size)}) is ready: your profile and settings, your repositories as Git bundles, and the issues, pull requests and comments you wrote. Download it from Settings → Account before `, at(job.data.expiresAt), "."] },
664 { button: { label: "Download your export", url: job.data.url } },
665 { p: ["You'll be asked to sign in again before the download starts. If you didn't ask for an export, sign out your other browsers and tell a site administrator."], muted: true },
666 ],
667 url: job.data.url,
668 };
669 case "invite": {
670 const d = job.data;
671 const what = d.org ? `join the ${d.org} organization` : d.repo ? `collaborate on ${d.repo}` : "join Diffinery";
672 return {
673 subject: d.org ? `@${d.inviter} invited you to join the ${d.org} organization on Diffinery` : d.repo ? `@${d.inviter} invited you to collaborate on ${d.repo}` : `@${d.inviter} invited you to Diffinery`,
674 preheader: d.existing ? `Accept or decline it in Diffinery by ${day(d.expiresAt)}.` : `Accept by ${day(d.expiresAt)}. You'll sign in with a passkey, no password needed.`,
675 eyebrow: { text: "Invitation", tone: "blue" },
676 title: [{ b: user(d.inviter) }, ` invited you to ${what}`],
677 blocks: [
678 { p: ["Diffinery is where the team keeps its code: Git repositories, pull requests, issues and GitHub Actions–compatible CI, with AI agents as first-class collaborators."] },
679 { kv: [["Invited by", user(d.inviter)], ...(d.org ? ([["Organization", d.org]] as Array<[string, string]>) : []), ...(d.repo ? ([["Repository", d.repo]] as Array<[string, string]>) : []), ...(d.org || d.repo ? ([["Role", roleText(d.role)]] as Array<[string, string]>) : []), ["Expires", day(d.expiresAt)]] },
680 { button: { label: d.existing ? "View invitation" : "Accept invitation", url: d.url } },
681 d.existing
682 ? { p: ["You'll have access once you accept. Sign in to accept or decline it; if you don't recognize this, decline it or let it expire."], muted: true }
683 : { p: ["You'll pick a username and create a passkey with your fingerprint, face or screen lock. This invitation only works for this email address."], muted: true },
684 ],
685 url: d.url,
686 };
687 }
688 case "invite_accepted": {
689 const d = job.data;
690 const where = d.org ? `the ${d.org} organization` : d.repo ? d.repo : "Diffinery";
691 return {
692 subject: `[Diffinery] @${d.login} accepted your invitation`,
693 preheader: `${d.email || `@${d.login}`} joined ${where}.`,
694 eyebrow: { text: "Invitation accepted", tone: "green" },
695 title: [{ b: user(d.login) }, ` accepted your invitation to ${where}`],
696 blocks: [{ kv: [["Username", user(d.login)], ...(d.email ? ([["Email", d.email]] as Array<[string, string]>) : [])] }, { button: { label: "View profile", url: `${pub}/${d.login}` } }],
697 url: `${pub}/${d.login}`,
698 };
699 }
700 case "welcome":
701 return {
702 subject: `Welcome to Diffinery, @${job.data.login}`,
703 preheader: "Your account is ready. Here's how to get going.",
704 eyebrow: { text: "Welcome", tone: "blue" },
705 title: ["Welcome to Diffinery, ", { b: user(job.data.login) }],
706 blocks: [
707 { p: ["Your account is ready, and you sign in with the passkey you just created. A few things worth doing first:"] },
708 {
709 items: [
710 { mark: "dot", text: [{ b: "Add a second passkey" }, " on another device, or keep it in a password manager that syncs."], url: `${pub}/settings/security` },
711 { mark: "dot", text: [{ b: "Create an access token" }, " for Git over HTTPS, the CLI and MCP clients."], url: `${pub}/settings/tokens` },
712 { mark: "dot", text: [{ b: "Create a repository" }, " or push an existing one. Workflows in .github/workflows run as they do on GitHub."], url: `${pub}/new` },
713 { mark: "dot", text: [{ b: "Choose your notifications" }, ": which emails you get, and which repositories you watch."], url: `${pub}/settings/notifications` },
714 ],
715 },
716 { button: { label: "Go to your dashboard", url: pub } },
717 ],
718 url: pub,
719 };
720 case "signin_link":
721 return {
722 subject: "[Diffinery] Your one-time sign-in link",
723 preheader: `Add a new passkey before ${day(job.data.expiresAt)}.`,
724 eyebrow: { text: "Account recovery", tone: "amber" },
725 title: ["Add a new passkey to your account"],
726 blocks: [
727 { p: [user(job.data.admin), " created a one-time link so you can add a new passkey and sign in again. It works once and expires ", at(job.data.expiresAt), "."] },
728 { button: { label: "Add a passkey", url: job.data.url } },
729 { callout: ["Anyone with this link can add a passkey to your account. Don't forward this email. If you didn't ask for it, tell a site administrator."], tone: "warn" },
730 ],
731 url: job.data.url,
732 };
733 case "signup_code":
734 return {
735 // The code stays out of the subject, which the email log keeps.
736 subject: "[Diffinery] Your sign-up code",
737 preheader: `Your code is ${job.data.code}. It expires in 10 minutes.`,
738 eyebrow: { text: "Sign-up", tone: "blue" },
739 title: ["Confirm your email address"],
740 blocks: [
741 { p: ["Enter this code on the Diffinery sign-up page to confirm your email address. Then you pick a username and create a passkey."] },
742 { code: job.data.code },
743 { p: ["It works once and expires ", at(job.data.expiresAt), ". If you didn't ask to sign up, ignore this email: nothing happens without the code."], muted: true },
744 ],
745 };
746 case "email_verify":
747 return {
748 subject: "[Diffinery] Confirm your email address to get email again",
749 preheader: `Confirm before ${day(job.data.expiresAt)} and Diffinery emails you again.`,
750 eyebrow: { text: "Account", tone: "blue" },
751 title: ["Confirm your email address"],
752 blocks: [
753 { p: ["Diffinery stopped emailing ", { b: job.data.email }, " after a bounce or a spam report. You asked to get email here again: confirm that this inbox is yours and works."] },
754 { button: { label: "Confirm and get email again", url: job.data.url } },
755 { p: ["The link works while you're signed in to Diffinery as ", ...(login ? [{ b: user(login) }] : ["yourself"]), " and expires ", at(job.data.expiresAt), ". If you didn't ask for it, ignore this email: nothing changes."], muted: true },
756 ],
757 url: job.data.url,
758 };
759 case "signup_attempt":
760 return {
761 subject: "[Diffinery] Someone tried to sign up with your email address",
762 preheader: "No new account was created. Sign in with your passkey instead.",
763 eyebrow: { text: "Account", tone: "amber" },
764 title: ["Someone tried to sign up with your email address"],
765 blocks: [
766 { p: ["Someone asked to create a new Diffinery account for ", { b: job.data.email }, ", which already belongs to your account", ...(login ? [" ", { b: user(login) }] : []), ". No account was created and no code was sent."] },
767 { p: ["If it was you, sign in with your passkey. If you lost it, the sign-in page shows how to recover your account."] },
768 { button: { label: "Sign in", url: `${pub}/login` } },
769 { p: ["If it wasn't you, you can ignore this email: nobody can sign up with your address without reading your mail."], muted: true },
770 ],
771 url: `${pub}/login`,
772 };
773 case "early_access_confirm":
774 return {
775 subject: "[Diffinery] Confirm your early access request",
776 preheader: `Confirm before ${day(job.data.expiresAt)} to join the list. Nothing happens without it.`,
777 eyebrow: { text: "Early access", tone: "blue" },
778 title: ["Confirm your early access request"],
779 blocks: [
780 { p: ["Thanks for asking for early access to Diffinery. Confirm that this is your email address and your request joins the list the team reviews."] },
781 { button: { label: "Confirm my request", url: job.data.url } },
782 { p: ["When there's a place for you, we'll email you an invitation to pick a username and create a passkey. There are no passwords."] },
783 { p: ["The link works once and expires ", at(job.data.expiresAt), ". If you didn't ask for early access, ignore this email: nothing is kept unless the link is opened, and the unconfirmed request is deleted after a week."], muted: true },
784 ],
785 url: job.data.url,
786 };
787 case "early_access_remove":
788 return {
789 subject: "[Diffinery] Remove your early access request",
790 preheader: `Remove it before ${day(job.data.expiresAt)}. Nothing changes unless you do.`,
791 eyebrow: { text: "Early access", tone: "amber" },
792 title: ["Remove your early access request"],
793 blocks: [
794 { p: ["Someone asked to remove the early access request for this email address. Open the link and press the button to delete it and everything stored about it."] },
795 { button: { label: "Remove my request", url: job.data.url } },
796 { p: ["The link works once and expires ", at(job.data.expiresAt), ". If you didn't ask for this, ignore this email: your request stays as it is."], muted: true },
797 ],
798 url: job.data.url,
799 };
800 case "early_access_known": {
801 const d = job.data;
802 if (d.variant === "account")
803 return {
804 subject: "[Diffinery] You already have a Diffinery account",
805 preheader: "No request was needed. Sign in with your passkey instead.",
806 eyebrow: { text: "Early access", tone: "blue" },
807 title: ["You already have an account"],
808 blocks: [
809 { p: ["Someone asked for early access to Diffinery with this email address, which already belongs to your account", ...(login ? [" ", { b: user(login) }] : []), ". Nothing changed and no request was stored."] },
810 { button: { label: "Sign in", url: `${pub}/login` } },
811 { p: ["If you lost your passkey, the sign-in page shows how to recover your account. If it wasn't you, you can ignore this email."], muted: true },
812 ],
813 url: `${pub}/login`,
814 };
815 if (d.variant === "invited")
816 return {
817 subject: "[Diffinery] You're already invited",
818 preheader: `We sent your invitation on ${day(d.since)}. Look for it in this inbox.`,
819 eyebrow: { text: "Early access", tone: "green" },
820 title: ["You're already invited"],
821 blocks: [
822 { p: ["You asked for early access again, but we already sent this address an invitation on ", { b: day(d.since) }, ". Look for an email titled \"invited you to Diffinery\", and check your spam folder too."] },
823 { p: ["Opening its link lets you pick a username and create a passkey. Invitations expire after 14 days; if yours has, let the person named in it know and they can send a new one."], muted: true },
824 ],
825 };
826 return {
827 subject: "[Diffinery] We already have your early access request",
828 preheader: "There's nothing else to do. We'll email you when there's a place.",
829 eyebrow: { text: "Early access", tone: "blue" },
830 title: ["We already have your request"],
831 blocks: [
832 { p: ["You asked for early access to Diffinery again. Your request from ", { b: day(d.since) }, " is already on the list, so there's nothing else to do."] },
833 { p: ["When there's a place for you, we'll email you an invitation to pick a username and create a passkey."] },
834 { p: ["If it wasn't you who asked again, you can ignore this email."], muted: true },
835 ],
836 };
837 }
838 case "access_request":
839 return {
840 subject: `[Diffinery] ${job.data.email} asked for access`,
841 preheader: job.data.note ? job.data.note.slice(0, 140) : `@${job.data.login} is waiting for an invite.`,
842 eyebrow: { text: "Access request", tone: "blue" },
843 title: [{ b: job.data.email }, " asked for access to Diffinery"],
844 blocks: [
845 { kv: [["Username", user(job.data.login)], ["Email", job.data.email], ["When", at(job.at)]] },
846 ...(job.data.note ? [{ quote: [job.data.note] } as Block] : []),
847 { button: { label: "Review access requests", url: `${pub}/settings/admin` } },
848 ],
849 url: `${pub}/settings/admin`,
850 };
851 case "contact_confirm": {
852 // Nothing typed into the form: the address isn't confirmed yet, so this must not carry anyone's words.
853 const d = job.data;
854 return {
855 subject: "[Diffinery] Confirm your message to the Diffinery team",
856 preheader: `Confirm before ${day(d.expiresAt)} and it goes to the team. Nothing is sent without it.`,
857 eyebrow: { text: "Contact", tone: "blue" },
858 title: ["Confirm your message"],
859 blocks: [
860 { p: ["Thanks for writing to us. We received a message sent with this email address through the contact form, under the topic ", { b: d.topic }, ". Confirm that it's yours and it goes to the team, who reply to this address."] },
861 { button: { label: "Confirm my message", url: d.url } },
862 { p: ["The link works once and expires ", at(d.expiresAt), ". If you didn't write to us, ignore this email: the message is never read and is deleted after a week. Please don't reply to this email; replies aren't read."], muted: true },
863 ],
864 url: d.url,
865 };
866 }
867 case "contact_received": {
868 const d = job.data;
869 return {
870 subject: "[Diffinery] We got your message",
871 preheader: `Topic: ${d.topic}. The team replies to this address.`,
872 eyebrow: { text: "Contact", tone: "green" },
873 title: ["We got your message"],
874 blocks: [
875 { p: ["Thanks for writing to us. The team reads every message and replies to this address. Here is a copy of what you sent, under the topic ", { b: d.topic }, ":"] },
876 { plain: d.message },
877 { p: ["Reference ", { code: d.id }, ". Please don't reply to this email; replies aren't read. To add something, send another message."], muted: true },
878 ],
879 };
880 }
881 case "contact_message": {
882 const d = job.data;
883 const url = `${pub}/settings/admin/contact/${d.id}`;
884 return {
885 subject: `[Diffinery] Contact: ${d.topic} from ${d.name}`,
886 preheader: d.message.replace(/\s+/g, " ").slice(0, 140),
887 eyebrow: { text: "Contact message", tone: "blue" },
888 title: ["New message from ", { b: d.name }],
889 blocks: [
890 { kv: [["From", d.login ? [d.name, " (", { b: user(d.login) }, ")"] : d.name], ["Email", d.email], ["Topic", d.topic], ["When", at(job.at)]] },
891 { plain: d.message },
892 { button: { label: "Open in Diffinery", url } },
893 { p: [`Reply to this email to answer ${d.email} from your own mailbox, then mark the message handled in Site administration → Contact messages. The address ${d.login ? "belongs to the sender's account" : "was confirmed through an emailed link"}.`], muted: true },
894 ],
895 url,
896 replyTo: { email: d.email, name: d.name },
897 };
898 }
899 case "security_report": {
900 // Only the summary: the details stay in Diffinery, behind a site administrator's sign-in.
901 const url = `${pub}/settings/admin/security-reports/${job.data.id}`;
902 return {
903 subject: "[Diffinery] New security report",
904 preheader: "Someone reported a security problem. Read it in Site administration.",
905 eyebrow: { text: "Security report", tone: "red" },
906 title: ["New security report"],
907 blocks: [
908 { p: ["Someone sent a private security report through ", { a: "/security/report", href: `${pub}/security/report` }, ". Its summary, as the reporter wrote it:"] },
909 { quote: [job.data.summary] },
910 { button: { label: "Read the report", url } },
911 { p: ["The details are only in Site administration → Security reports. Reply to the reporter from your own mailbox, and don't forward this email beyond the people who handle security."], muted: true },
912 ],
913 url,
914 };
915 }
916 case "org_membership": {
917 const d = job.data;
918 const url = `${pub}/${d.org}`;
919 const title: Inline[] = !d.role ? ["You were removed from the ", { b: d.org }, " organization"] : d.previous ? ["Your role in ", { b: d.org }, ` changed to ${roleText(d.role)}`] : ["You're now ", article(roleText(d.role)), " ", roleText(d.role), " of ", { b: d.org }];
920 return {
921 subject: `[Diffinery] ${inlineText(title)}`,
922 preheader: d.role ? `You can see ${d.org}'s repositories according to your role.` : `You no longer have access to ${d.org}'s private repositories.`,
923 eyebrow: { text: "Organization", tone: d.role ? "blue" : "neutral" },
924 title,
925 blocks: [
926 { kv: [["Organization", d.org], ["Role", d.role ? roleText(d.role) : "none"], ...(d.previous ? ([["Previously", roleText(d.previous)]] as Array<[string, string]>) : []), ...(d.by ? ([[d.role && !d.previous ? "Added by" : "Changed by", d.by]] as Array<[string, string]>) : [])] },
927 ...(d.role ? [{ button: { label: `Open ${d.org}`, url } } as Block] : []),
928 ],
929 context: { label: d.org, url },
930 url: d.role ? url : undefined,
931 };
932 }
933 case "repo_access": {
934 const d = job.data;
935 const url = `${pub}/${d.repo}`;
936 const title: Inline[] = d.role ? (d.previous ? ["Your access to ", { b: d.repo }, ` changed to ${roleText(d.role)}`] : ["You now have ", roleText(d.role), " access to ", { b: d.repo }]) : ["Your access to ", { b: d.repo }, " was removed"];
937 return {
938 subject: `[${d.repo}] ${inlineText(title)}`,
939 preheader: d.role ? `Open ${d.repo} on Diffinery.` : "You can no longer see it unless it's public.",
940 eyebrow: { text: "Repository access", tone: d.role ? "blue" : "neutral" },
941 title,
942 blocks: [{ kv: [["Repository", d.repo], ["Role", d.role ? roleText(d.role) : "none"], ...(d.previous ? ([["Previously", roleText(d.previous)]] as Array<[string, string]>) : [])] }, ...(d.role ? [{ button: { label: "Open repository", url } } as Block] : [])],
943 context: repoContext(pub, d.repo),
944 url: d.role ? url : undefined,
945 };
946 }
947 case "repo_created": {
948 const d = job.data;
949 const url = `${pub}/${d.repo}`;
950 const mine = job.reason === "your_activity";
951 return {
952 subject: `[${d.repo}] New ${d.visibility} repository`,
953 preheader: mine ? `Push your code to ${url}.git` : `@${d.creator} created ${d.repo}.`,
954 eyebrow: { text: "New repository", tone: "green" },
955 title: mine ? ["Your repository ", { b: d.repo }, " is ready"] : [user(d.creator), " created ", { b: d.repo }],
956 blocks: [
957 ...(d.description ? [{ p: [d.description] } as Block] : []),
958 { kv: [["Repository", [{ a: d.repo, href: url }]], ["Visibility", d.visibility], ["Default branch", d.defaultBranch], ["Created by", user(d.creator)]] },
959 ...(mine
960 ? [
961 { p: ["Push an existing repository from the command line:"] } as Block,
962 { code: `git remote add origin ${url}.git\ngit push -u origin ${d.defaultBranch}` } as Block,
963 { p: ["Use an ", { a: "access token", href: `${pub}/settings/tokens` }, " as the password. Workflows in .github/workflows start running on the first push."], muted: true } as Block,
964 ]
965 : []),
966 { button: { label: "Open repository", url } },
967 ],
968 context: repoContext(pub, d.repo),
969 url,
970 };
971 }
972 case "repo_deleted":
973 return {
974 subject: `[${job.data.repo}] Repository deleted`,
975 preheader: `@${job.data.actor} deleted ${job.data.repo}.`,
976 eyebrow: { text: "Repository deleted", tone: "red" },
977 title: [user(job.data.actor), " deleted ", { b: job.data.repo }],
978 blocks: [{ p: ["The repository, its issues, pull requests, workflow runs and settings are gone."] }, { kv: [["Repository", job.data.repo], ["Deleted by", user(job.data.actor)], ["When", at(job.at)]] }],
979 };
980 case "repo_transferred": {
981 const d = job.data;
982 const url = `${pub}/${d.to}`;
983 return {
984 subject: `[${d.to}] Repository transferred from ${d.from}`,
985 preheader: `@${d.actor} moved ${d.from} to ${d.to}.`,
986 eyebrow: { text: "Repository transferred", tone: "blue" },
987 title: [user(d.actor), " transferred ", { b: d.from }, " to ", { b: d.to }],
988 blocks: [
989 { p: ["Its history, issues, pull requests, workflow runs, secrets and settings moved with it. Links, clones and API calls that use the old name keep working for people who can still read it; update your remotes when you can:"] },
990 { code: `git remote set-url origin ${url}.git` },
991 { kv: [["From", d.from], ["To", [{ a: d.to, href: url }]], ["Transferred by", user(d.actor)], ["When", at(job.at)]] },
992 { button: { label: "Open repository", url } },
993 ],
994 context: repoContext(pub, d.to),
995 url,
996 };
997 }
998 case "digest":
999 return digestEmail(job.data, pub);
1000 case "test":
1001 return {
1002 subject: "[Diffinery] Test email",
1003 preheader: "Email from Diffinery works.",
1004 eyebrow: { text: "Test", tone: "green" },
1005 title: ["Email from Diffinery works"],
1006 blocks: [{ p: [user(job.data.by), " sent this test email at ", at(job.at), `. It came from Cloudflare Email Sending, signed with DKIM for ${mailDomain(pub, mailFrom)}.`] }, { button: { label: "Notification settings", url: `${pub}/settings/notifications` } }],
1007 url: `${pub}/settings/notifications`,
1008 };
1009 }
1010}
1011
1012// ---------------------------------------------------------------- the morning digest (phase 5c)
1013
1014/** Today by email: what needs you, your agents, and what happened since the last digest (agentic/digest.ts). */
1015function digestEmail(d: DigestData, pub: string): Email {
1016 const today = `${pub}/`;
1017 const s = d.summary;
1018 if (!s) {
1019 // deliver() always fills the summary in; this only shows if something sends the job without it.
1020 return { subject: "[Diffinery] Your morning digest", preheader: "Open Today on Diffinery.", eyebrow: { text: "Today", tone: "blue" }, title: ["Your morning digest"], blocks: [{ button: { label: "Open Today", url: today } }], url: today };
1021 }
1022 const c = s.counts;
1023 const parts = [c.needsYou ? `${c.needsYou} need${c.needsYou === 1 ? "s" : ""} you` : "", c.agents ? plural(c.agents, "agent pull request") : "", c.merged ? `${c.merged} merged` : "", c.failed ? plural(c.failed, "failed run") : ""].filter(Boolean);
1024 const headline = parts.length ? parts.join(", ") : "nothing needs you";
1025 const blocks: Block[] = [];
1026 if (!s.sections.length) blocks.push({ p: ["Nothing needs you, your agents have no open pull requests, and nothing merged, released or failed since the last digest."] });
1027 for (const sec of s.sections) {
1028 blocks.push({ p: [{ b: sec.title }, sec.total > sec.items.length ? ` · ${sec.items.length} of ${sec.total}` : ` · ${sec.total}`] });
1029 blocks.push({ items: sec.items.map((it) => ({ mark: it.mark, text: [{ b: it.title }, ` ${it.where} · ${it.note}`], url: it.url })) });
1030 }
1031 blocks.push({ button: { label: "Open Today", url: today } });
1032 blocks.push({ p: [`Since ${at(d.since)}, across ${plural(s.repositories, "active repository", "active repositories")}${s.incomplete ? " (some were left out; Today shows the most recently active)" : ""}.`], muted: true });
1033 return {
1034 subject: `[Diffinery] Today: ${headline}`,
1035 preheader: s.sections.length ? s.sections.map((x) => `${x.title}: ${x.total}`).join(" · ") : "A quiet morning.",
1036 eyebrow: { text: s.date, tone: c.needsYou ? "purple" : "blue" },
1037 title: [c.needsYou ? `${c.needsYou} ${c.needsYou === 1 ? "thing needs" : "things need"} you today` : "Your morning digest"],
1038 blocks,
1039 url: today,
1040 };
1041}