commit
Add some live email refreshing
diff --git a/src/web/App.svelte b/src/web/App.svelte
index 9104cfc..94c59f9 100644
--- a/src/web/App.svelte
+++ b/src/web/App.svelte
@@ -7,13 +7,16 @@
import Sidebar from "./components/Sidebar.svelte";
import ThreadList from "./components/ThreadList.svelte";
import ThreadView from "./components/ThreadView.svelte";
+ import { startLive } from "./lib/live";
import { isDemo, router } from "./lib/router.svelte";
import { composer, loadSession, session } from "./lib/state.svelte";
import Admin from "./pages/Admin.svelte";
import Settings from "./pages/Settings.svelte";
let error = $state("");
- loadSession().catch((e: Error) => (error = e.message));
+ loadSession()
+ .then(() => !isDemo && startLive())
+ .catch((e: Error) => (error = e.message));
const route = $derived(router.route);
const reading = $derived(route.name === "folder" && route.threadId !== null);
diff --git a/src/web/components/ThreadView.svelte b/src/web/components/ThreadView.svelte
index 1a63e50..2cdd200 100644
--- a/src/web/components/ThreadView.svelte
+++ b/src/web/components/ThreadView.svelte
@@ -17,7 +17,7 @@
import { api } from "../lib/api";
import { bareAddress, displayName, fmtSize, fmtTime } from "../lib/format";
import { router } from "../lib/router.svelte";
- import { changed, composeDraft, composeForward, composeReply, composer } from "../lib/state.svelte";
+ import { changed, composeDraft, composeForward, composeReply, composer, session } from "../lib/state.svelte";
import EmailFrame from "./EmailFrame.svelte";
/** `bin`: showing the part of the thread that's in the Bin. */
@@ -53,6 +53,29 @@
return () => (stale = true);
});
+ // New mail arrived in this thread while it's open: fetch it again in place.
+ let seenLive = session.liveThread?.n ?? 0;
+ $effect(() => {
+ const live = session.liveThread;
+ if (!live || live.n === seenLive) return;
+ seenLive = live.n;
+ if (live.id !== id || !thread) return;
+ const threadId = id;
+ api.thread(threadId, bin).then(
+ (t) => {
+ if (threadId !== id) return;
+ thread = t;
+ if (t.messages.some((m) => !m.read)) {
+ api.markThread(threadId, true).then(
+ (r) => changed(r.unread),
+ (e: Error) => console.warn("Could not mark thread read", e),
+ );
+ }
+ },
+ (e: Error) => console.warn("Could not refresh thread", e),
+ );
+ });
+
const last = $derived(thread?.messages.filter((m) => m.folder !== "drafts").at(-1) ?? thread?.messages.at(-1));
const hasInbound = $derived(thread?.messages.some((m) => m.folder === "inbox") ?? false);
diff --git a/src/web/lib/live.ts b/src/web/lib/live.ts
new file mode 100644
index 0000000..a82cb28
--- /dev/null
+++ b/src/web/lib/live.ts
@@ -0,0 +1,66 @@
+import { changed, session } from "./state.svelte";
+
+const PING_MS = 30_000;
+const MAX_BACKOFF_MS = 60_000;
+
+/**
+ * Keeps a WebSocket to /api/live open and reloads the lists when new mail
+ * lands. Reconnects with backoff, and catches up on anything missed while it
+ * was down.
+ */
+export function startLive() {
+ let ws: WebSocket | null = null;
+ let retry: ReturnType<typeof setTimeout> | undefined;
+ let backoff = 1000;
+ let dropped = false;
+
+ function connect() {
+ clearTimeout(retry);
+ if (ws || document.hidden) return;
+ const socket = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/api/live`);
+ ws = socket;
+ let ping: ReturnType<typeof setInterval> | undefined;
+
+ socket.onopen = () => {
+ backoff = 1000;
+ // Cloudflare drops idle sockets after ~100s; the server answers without waking.
+ ping = setInterval(() => socket.send("ping"), PING_MS);
+ if (dropped) changed();
+ };
+ socket.onmessage = (e) => {
+ if (e.data === "pong") return;
+ try {
+ const event = JSON.parse(e.data as string) as { type: string; threadId?: string };
+ if (event.type !== "mail") return;
+ if (event.threadId) session.liveThread = { id: event.threadId, n: (session.liveThread?.n ?? 0) + 1 };
+ changed();
+ } catch {
+ // Not ours; ignore.
+ }
+ };
+ socket.onclose = () => {
+ clearInterval(ping);
+ if (ws !== socket) return;
+ ws = null;
+ dropped = true;
+ if (document.hidden) return;
+ retry = setTimeout(connect, backoff);
+ backoff = Math.min(backoff * 2, MAX_BACKOFF_MS);
+ };
+ }
+
+ // A background tab doesn't need a socket; reconnect (and catch up) on return.
+ document.addEventListener("visibilitychange", () => {
+ if (!document.hidden) return connect();
+ clearTimeout(retry);
+ if (ws) {
+ const socket = ws;
+ ws = null;
+ dropped = true;
+ socket.close();
+ }
+ });
+ addEventListener("online", connect);
+
+ connect();
+}
diff --git a/src/web/lib/state.svelte.ts b/src/web/lib/state.svelte.ts
index de32078..b199985 100644
--- a/src/web/lib/state.svelte.ts
+++ b/src/web/lib/state.svelte.ts
@@ -7,6 +7,8 @@ export const session = $state({
unread: {} as Record<string, number>,
/** Bumped after anything that changes the lists, so they reload. */
version: 0,
+ /** The thread the latest live update was for; `n` makes repeats distinct. */
+ liveThread: null as { id: string; n: number } | null,
});
export async function loadSession() {
diff --git a/src/worker/index.ts b/src/worker/index.ts
index cdd62dd..390129f 100644
--- a/src/worker/index.ts
+++ b/src/worker/index.ts
@@ -7,6 +7,7 @@ import { mail } from "./routes/mail";
import { webhook } from "./routes/webhook";
import { sweepOrphanUploads } from "./services/attachments";
import { syncDomains } from "./services/domains";
+import { LiveHub } from "./services/live";
import { purgeBin } from "./services/messages";
import { sweepExpired } from "./services/sessions";
@@ -18,6 +19,15 @@ const app = new Hono<AppEnv>()
.use(sameOrigin)
.route("/auth", auth)
.use("/api/*", requireUser)
+ .get("/api/live", async (c) => {
+ if (c.req.header("upgrade")?.toLowerCase() !== "websocket") return c.json({ error: "Expected a WebSocket" }, 426);
+ // Browsers send cookies on cross-site WebSocket handshakes and sameOrigin
+ // lets GETs through, so check the origin here.
+ if (c.req.header("origin") !== new URL(c.req.url).origin) return c.json({ error: "Cross-site request refused" }, 403);
+ const res = await c.env.LIVE.getByName(c.get("user").username.toLowerCase()).fetch(c.req.raw);
+ // Re-wrapped: the stub's response has immutable headers, which secureHeaders needs to set.
+ return new Response(null, { status: res.status, webSocket: res.webSocket });
+ })
.route("/api/admin", admin)
.route("/api", mail)
.notFound((c) => c.json({ error: "Not found" }, 404))
@@ -26,6 +36,8 @@ const app = new Hono<AppEnv>()
return c.json({ error: "Something went wrong." }, 500);
});
+export { LiveHub };
+
export default {
fetch: app.fetch,
async scheduled(_event, env, ctx) {
diff --git a/src/worker/services/inbound.ts b/src/worker/services/inbound.ts
index 62c0888..870fcee 100644
--- a/src/worker/services/inbound.ts
+++ b/src/worker/services/inbound.ts
@@ -1,6 +1,7 @@
import { bareAddress } from "../lib/address";
import { cleanContentId, inboundKey, insertAttachmentStatement } from "./attachments";
import { routeRecipients } from "./directory";
+import { notifyLive } from "./live";
import { insertMessageStatement, resolveThread } from "./messages";
import { notifyUser } from "./push";
import { resend } from "./resend";
@@ -100,6 +101,7 @@ export async function receiveEmail(env: Env, emailId: string): Promise<{ stored:
]);
if (!message?.meta.changes) continue;
stored++;
+ await notifyLive(env, owner, { type: "mail", threadId });
try {
await notifyUser(env, owner, {
@@ -176,6 +178,7 @@ export async function receiveBounce(env: Env, bounce: Bounce): Promise<{ stored:
env.DB.prepare("UPDATE threads SET last_at = MAX(last_at, ?) WHERE id = ?").bind(sentAt, sent.thread_id),
]);
if (!inserted?.meta.changes) return { stored: 0 };
+ await notifyLive(env, sent.owner, { type: "mail", threadId: sent.thread_id });
try {
await notifyUser(env, sent.owner, {
diff --git a/src/worker/services/live.ts b/src/worker/services/live.ts
new file mode 100644
index 0000000..3aa6b64
--- /dev/null
+++ b/src/worker/services/live.ts
@@ -0,0 +1,43 @@
+import { DurableObject } from "cloudflare:workers";
+
+export type LiveEvent = { type: "mail"; threadId: string };
+
+/**
+ * One per user: holds the WebSockets of their open tabs so new mail can be
+ * pushed to them as it lands. Uses the hibernation API, so an idle socket
+ * costs nothing; the client's keep-alive pings are answered without waking it.
+ */
+export class LiveHub extends DurableObject<Env> {
+ constructor(ctx: DurableObjectState, env: Env) {
+ super(ctx, env);
+ ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair("ping", "pong"));
+ }
+
+ override async fetch(): Promise<Response> {
+ const [client, server] = Object.values(new WebSocketPair());
+ this.ctx.acceptWebSocket(server!);
+ return new Response(null, { status: 101, webSocket: client });
+ }
+
+ broadcast(event: LiveEvent): number {
+ const data = JSON.stringify(event);
+ const sockets = this.ctx.getWebSockets();
+ for (const ws of sockets) {
+ try {
+ ws.send(data);
+ } catch {
+ // Already closing; it'll be dropped from getWebSockets() shortly.
+ }
+ }
+ return sockets.length;
+ }
+}
+
+/** Tells `username`'s open tabs something changed. Never throws: it's best effort. */
+export async function notifyLive(env: Env, username: string, event: LiveEvent): Promise<void> {
+ try {
+ await env.LIVE.getByName(username.toLowerCase()).broadcast(event);
+ } catch (err) {
+ console.error("Live update failed", err);
+ }
+}
diff --git a/src/worker/worker-configuration.d.ts b/src/worker/worker-configuration.d.ts
index 3e2474a..36a1208 100644
--- a/src/worker/worker-configuration.d.ts
+++ b/src/worker/worker-configuration.d.ts
@@ -1,5 +1,5 @@
/* eslint-disable */
-// Generated by Wrangler by running `wrangler types --env-file=.dev.vars.example src/worker/worker-configuration.d.ts` (hash: 44bdd63a47ff5fe3d16675d380f69210)
+// Generated by Wrangler by running `wrangler types --env-file=.dev.vars.example src/worker/worker-configuration.d.ts` (hash: 6d0c47eb9c2dd92f118cd97ff14ec68e)
// Runtime types generated with [email protected] 2026-10-01 nodejs_compat
interface __BaseEnv_Env {
BUCKET: R2Bucket;
@@ -17,10 +17,12 @@ interface __BaseEnv_Env {
COOKIE_SECURE: string;
OIDC_REDIRECT_URI: string;
OIDC_POST_LOGOUT_REDIRECT_URI: string;
+ LIVE: DurableObjectNamespace<import("./index").LiveHub>;
}
declare namespace Cloudflare {
interface GlobalProps {
mainModule: typeof import("./index");
+ durableNamespaces: "LiveHub";
}
interface Env extends __BaseEnv_Env {}
}
diff --git a/test/live.test.ts b/test/live.test.ts
new file mode 100644
index 0000000..f9675a2
--- /dev/null
+++ b/test/live.test.ts
@@ -0,0 +1,55 @@
+import { env, exports } from "cloudflare:workers";
+import { beforeAll, describe, expect, it } from "vitest";
+import { notifyLive } from "../src/worker/services/live";
+
+const ORIGIN = "https://mail.test";
+
+let token: string;
+
+beforeAll(async () => {
+ const now = Date.now();
+ await env.DB.prepare("INSERT INTO users (username, sub, is_admin, created_at, last_login_at) VALUES (?, ?, 0, ?, ?)")
+ .bind("clove", "sub-clove", now, now)
+ .run();
+ token = crypto.randomUUID();
+ const ts = Math.floor(now / 1000);
+ const session = { username: "clove", sub: "sub-clove", refreshToken: null, idToken: null, createdAt: ts, verifiedAt: ts, checkedAt: ts };
+ await env.DB.prepare("INSERT INTO sessions (token, data, expires_at) VALUES (?, ?, ?)")
+ .bind(token, JSON.stringify(session), ts + 3600)
+ .run();
+});
+
+function open(headers: Record<string, string> = {}) {
+ return exports.default.fetch(
+ new Request(`${ORIGIN}/api/live`, {
+ headers: { upgrade: "websocket", cookie: `session=${token}`, origin: ORIGIN, ...headers },
+ }),
+ );
+}
+
+function nextMessage(ws: WebSocket): Promise<string> {
+ return new Promise((resolve) => ws.addEventListener("message", (e) => resolve(e.data as string), { once: true }));
+}
+
+describe("live updates", () => {
+ it("pushes new mail to the owner's open sockets", async () => {
+ const res = await open();
+ expect(res.status).toBe(101);
+ const ws = res.webSocket!;
+ ws.accept();
+
+ ws.send("ping");
+ expect(await nextMessage(ws)).toBe("pong");
+
+ const got = nextMessage(ws);
+ await notifyLive(env, "Clove", { type: "mail", threadId: "t1" });
+ expect(JSON.parse(await got)).toEqual({ type: "mail", threadId: "t1" });
+ ws.close();
+ });
+
+ it("refuses cross-site handshakes and signed-out users", async () => {
+ expect((await open({ origin: "https://evil.test" })).status).toBe(403);
+ expect((await open({ cookie: "" })).status).toBe(401);
+ expect((await open({ upgrade: "" })).status).toBe(426);
+ });
+});
diff --git a/wrangler.jsonc b/wrangler.jsonc
index f48b287..96347ea 100644
--- a/wrangler.jsonc
+++ b/wrangler.jsonc
@@ -28,6 +28,23 @@
"migrations_dir": "migrations"
}
],
+ // One LiveHub per user holds their open tabs' WebSockets for live updates.
+ "durable_objects": {
+ "bindings": [
+ {
+ "name": "LIVE",
+ "class_name": "LiveHub"
+ }
+ ]
+ },
+ "migrations": [
+ {
+ "tag": "v1",
+ "new_sqlite_classes": [
+ "LiveHub"
+ ]
+ }
+ ],
"r2_buckets": [
{
"binding": "BUCKET",