From fa78fe7ccf2070c4f46fbb8a4c224d9fa277a88f Mon Sep 17 00:00:00 2001 From: Mateusz Pstrucha Date: Wed, 23 Sep 2026 18:55:43 +0200 Subject: [PATCH] Add live updates, new-mail alerts and notify rule actions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The shell now follows the server's event stream over a WebSocket, falling back to polling the same log (every 30 s) while it reconnects with backoff, and reloading everything when the server says the cursor can't be replayed. Lists, the outbox, sidebar and rules refresh on their own events; the open conversation only reloads when its message count changes, so flag and tag changes don't collapse it. Mail the server marks as notifying shows an in-page notice while the tab is in view, and otherwise counts in the tab title and — if the reader opted in — raises an OS notification. The rule editor gains Don't notify and Notify anyway. Co-Authored-By: Claude Opus 5.5 --- src/lib/MailShell.svelte | 215 +++++++++++++++++++++++++++++++++----- src/lib/RuleEditor.svelte | 6 +- src/lib/RulesView.svelte | 29 ++++- src/lib/api.ts | 40 +++++-- src/lib/live.ts | 157 ++++++++++++++++++++++++++++ src/lib/notify.ts | 54 ++++++++++ vite.config.ts | 3 +- 7 files changed, 465 insertions(+), 39 deletions(-) create mode 100644 src/lib/live.ts create mode 100644 src/lib/notify.ts diff --git a/src/lib/MailShell.svelte b/src/lib/MailShell.svelte index fc66462..55d2876 100644 --- a/src/lib/MailShell.svelte +++ b/src/lib/MailShell.svelte @@ -12,11 +12,12 @@ listOutbox, listTags, listThreads, - pollEvents, threadActions, + clearSessionToken, type Account, type Action, type Folder, + type LiveEvent, type MailView, type MessageDetail, type OutboxItem, @@ -31,12 +32,11 @@ import ActionMenu from './ActionMenu.svelte'; import Compose from './Compose.svelte'; import ShortcutHelp from './ShortcutHelp.svelte'; + import { startLive, type LiveStatus } from './live'; + import { alertState, disableAlerts, enableAlerts, showAlert, type AlertState } from './notify'; - // No WebSocket server-side yet (build order phase 7), so the open tab - // polls the delta endpoint. §3 keeps this as the fallback afterwards. - const POLL_INTERVAL_MS = 30_000; - // After sending, watch the outbox closely so the reader sees the message - // go out, rather than waiting for the next slow poll. + // After sending without a live connection, watch the outbox closely so + // the reader sees the message go out rather than waiting for a slow poll. const SEND_WATCH_INTERVAL_MS = 1_500; const SEND_WATCH_LIMIT_MS = 20_000; const TAG_COLORS = ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899', '#14b8a6', '#64748b']; @@ -61,7 +61,14 @@ let menu = $state<{ thread: ThreadSummary; at: { x: number; y: number } } | null>(null); let adding = $state<'folder' | 'tag' | null>(null); let newName = $state(''); - let eventCursor: string | null = null; + let liveStatus = $state('connecting'); + let alerts = $state(alertState()); + let rulesReloadKey = $state(0); + /** In-page notices for new mail; OS alerts replace them while the tab is hidden. */ + let toasts = $state<{ key: number; threadId: string | null; from: string; subject: string }[]>([]); + let toastSeq = 0; + /** New mail that notified while the reader was looking elsewhere — shown in the tab title. */ + let unseen = $state(0); const ownAddresses = $derived( accounts.flatMap((a) => [a.email_address, a.username]).filter((a): a is string => !!a && a.includes('@')), @@ -139,28 +146,109 @@ } } - onMount(() => { + function reloadAll() { refreshMeta().catch(() => {}); listAccounts().then((a) => (accounts = a)).catch(() => {}); - refresh(); + refreshList(); refreshOutbox(); + rulesReloadKey++; + } - const timer = setInterval(async () => { - try { - const events = await pollEvents(eventCursor); - eventCursor = events.cursor; - // Only re-fetch when something actually changed, so an idle tab - // isn't re-rendering the list every 30s. - if (events.changed_messages.length > 0) { - await refresh(); - threadReloadKey++; - } - } catch { - // A failed poll is not worth surfacing; the next tick retries. + /** + * Refreshes the list, and the open conversation only if it gained or lost + * messages — reloading it for a flag or tag change would collapse what + * the reader expanded and re-block images they'd allowed. + */ + async function refreshList() { + const before = selected?.message_count; + await refresh(); + if (selected && selected.message_count !== before) threadReloadKey++; + } + + function onEvents(events: LiveEvent[]) { + let mail = false; + let outboxChanged = false; + for (const e of events) { + switch (e.kind) { + case 'message_new': + mail = true; + if (e.data.notify) announce(e.data.thread_id, e.data.from ?? 'Unknown sender', e.data.subject ?? '(no subject)'); + break; + case 'mailbox_changed': + mail = true; + break; + case 'outbox_changed': + outboxChanged = true; + break; + case 'config_changed': + if (e.data.what === 'accounts') listAccounts().then((a) => (accounts = a)).catch(() => {}); + else if (e.data.what === 'rules') rulesReloadKey++; + else { + refreshMeta().catch(() => {}); + // Tag chips and folder names show in the list too. + mail = true; + } + break; } - }, POLL_INTERVAL_MS); + } + if (mail && section === 'mail') refreshList(); + if (outboxChanged) refreshOutbox(); + } - return () => clearInterval(timer); + function lookingAtTab(): boolean { + return document.visibilityState === 'visible' && document.hasFocus(); + } + + function announce(threadId: string | null, from: string, subject: string) { + if (lookingAtTab()) { + const key = ++toastSeq; + toasts = [...toasts.slice(-2), { key, threadId, from, subject }]; + setTimeout(() => (toasts = toasts.filter((t) => t.key !== key)), 8_000); + return; + } + unseen++; + showAlert(from, subject, threadId ?? subject, () => threadId && openThreadById(threadId)); + } + + function seen() { + if (lookingAtTab()) unseen = 0; + } + + $effect(() => { + document.title = unseen > 0 ? `(${unseen}) Tern` : 'Tern'; + }); + + /** Opens a conversation from a notification, wherever it's filed. */ + async function openThreadById(id: string) { + toasts = toasts.filter((t) => t.threadId !== id); + let i = section === 'mail' ? threads.findIndex((t) => t.thread_id === id) : -1; + if (i < 0) { + // Not in this view (e.g. a rule filed it into a folder): All mail + // shows it wherever it lives. + showView({ kind: 'all' }); + await refresh(); + i = threads.findIndex((t) => t.thread_id === id); + } + if (i >= 0) open(threads[i], i); + } + + async function toggleAlerts() { + alerts = alerts === 'on' ? disableAlerts() : await enableAlerts(); + } + + onMount(() => { + reloadAll(); + const stop = startLive({ + onEvents, + onReset: reloadAll, + onStatus: (s) => (liveStatus = s), + onUnauthorized: () => { + // Back to the sign-in screen rather than a UI that silently fails. + clearSessionToken(); + location.reload(); + }, + }); + return stop; }); function showView(v: MailView) { @@ -270,7 +358,8 @@ composeSeed = null; if (!changed) return; await refreshOutbox(); - if (sentId) watchSend(sentId); + // Live, the worker's own events report the send; this is the fallback. + if (sentId && liveStatus !== 'live') watchSend(sentId); } /** @@ -396,7 +485,8 @@ } - + +
{#if section === 'rules'}
- +
{:else}
@@ -523,6 +625,17 @@ (helpOpen = false)} /> +{#if toasts.length > 0} +
+ {#each toasts as t (t.key)} + + {/each} +
+{/if} +