inboxer 0.4.8 → 0.4.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  import type { HtmlEscapedString } from "hono/utils/html";
2
2
  import type { MessageView } from "../core/mail.ts";
3
- import type { Contact, Context, Message, Session, Thread } from "../types.ts";
3
+ import { type Contact, type Context, type Message, type Session, type Thread } from "../types.ts";
4
4
  export type View = HtmlEscapedString;
5
5
  export type Theme = "system" | "light" | "dark";
6
6
  export type Page = "drafts" | "inbox" | "devices" | "settings" | null;
@@ -8,8 +8,12 @@ export interface Mailbox {
8
8
  id: string;
9
9
  address: string;
10
10
  }
11
+ /** The accent hue of an instance, picked by a hash of its mail domains. */
12
+ export declare function accentHue(domains: string[]): number;
11
13
  export interface LayoutOptions {
12
14
  theme: Theme;
15
+ /** The accent's hue, from `accentHue`. */
16
+ hue: number;
13
17
  page: Page;
14
18
  signedIn: boolean;
15
19
  draftCount?: number;
@@ -50,20 +54,25 @@ export declare function draftEditor(d: Message, form: DraftForm, conflict: Messa
50
54
  export declare function draftFiles(d: Message, error: string | null): View;
51
55
  export declare function draftDone(id: string, text: string): View;
52
56
  /** Drafts waiting for review, listed like the inbox; each opens its thread. */
53
- export declare function draftList(drafts: Message[], current: string | null): View;
57
+ export declare function draftList(drafts: Message[], domains: string[], current: string | null): View;
54
58
  export interface InboxFilter {
55
59
  mailbox: string;
56
60
  status: string;
57
61
  }
58
62
  export declare function inboxQuery(filter: InboxFilter): string;
59
63
  /** The thread list; on a wide screen it stays beside the open thread. */
60
- export declare function threadList(threads: Thread[], opts: {
61
- mailboxes: string[];
64
+ export declare function threadList(threads: Thread[], opts: ThreadListOptions & {
62
65
  domains: string[];
66
+ }): View;
67
+ interface ThreadListOptions {
68
+ /** Mailbox ids and catch-all addresses, as filter values. */
69
+ accounts: string[];
70
+ accountOf: (t: Thread) => string;
71
+ addressOf: (account: string) => string;
63
72
  filter: InboxFilter;
64
- own: Set<string>;
73
+ own: (address: string) => boolean;
65
74
  current: string | null;
66
- }): View;
75
+ }
67
76
  /** The thread list and the open thread side by side; a phone shows one of the two. */
68
77
  export declare function inboxPage(list: View, thread: View | null): View;
69
78
  export interface ThreadEntry {
@@ -74,12 +83,14 @@ export interface ThreadEntry {
74
83
  export declare function threadView(thread: Thread, entries: ThreadEntry[], ctx: ContextView, opts: {
75
84
  back: string;
76
85
  filter: InboxFilter;
77
- own: Set<string>;
86
+ own: (address: string) => boolean;
87
+ account: string;
78
88
  reply: {
79
89
  allowed: boolean;
80
90
  replyAll: boolean;
81
91
  };
82
92
  }): View;
83
93
  export declare function archiveButton(thread: Thread): View;
84
- export declare function devicesPage(sessions: Session[], currentId: string): View;
94
+ export declare function devicesPage(sessions: Session[], currentId: string, addressOf: (account: string) => string): View;
85
95
  export declare function settingsPage(theme: Theme): View;
96
+ export {};
package/dist/ui/views.js CHANGED
@@ -1,5 +1,7 @@
1
+ import { crc32 } from "node:zlib";
1
2
  import { html, raw } from "hono/html";
2
3
  import { bareAddress } from "../core/address.js";
4
+ import {} from "../types.js";
3
5
  import { ASSETS } from "./assets.js";
4
6
  import { S } from "./strings.js";
5
7
  /** Views never await, so `html` returns a plain escaped string. */
@@ -62,25 +64,32 @@ function initials(address) {
62
64
  const words = (name.includes("@") ? name.split("@")[0] : name).split(/[\s._-]+/).filter(Boolean);
63
65
  return (words.length > 1 ? words[0][0] + words[1][0] : (words[0] ?? "?").slice(0, 2)).toUpperCase();
64
66
  }
67
+ /** Pastel hues (OKLCH degrees) for the accent, so several Inboxers tell apart at a glance. */
68
+ const ACCENT_HUES = [45, 75, 105, 145, 175, 205, 235, 265, 295, 325, 355];
69
+ /** The accent hue of an instance, picked by a hash of its mail domains. */
70
+ export function accentHue(domains) {
71
+ return ACCENT_HUES[crc32([...domains].sort().join(",")) % ACCENT_HUES.length];
72
+ }
65
73
  export function layout(title, body, opts) {
66
74
  const link = (page, href, label, name, extra = "") => h `<a href="${href}" ${raw(opts.page === page ? 'aria-current="page"' : "")}>${icon(name)}<span>${label}</span>${extra}</a>`;
67
75
  const count = opts.draftCount ? h `<span class="count">${opts.draftCount}</span>` : "";
68
76
  const canSend = !!opts.senders?.length;
69
77
  return h `<!doctype html>
70
- <html lang="en" ${raw(opts.theme === "system" ? "" : `data-theme="${opts.theme}"`)}>
78
+ <html lang="en" style="--hue: ${opts.hue}" ${raw(opts.theme === "system" ? "" : `data-theme="${opts.theme}"`)}>
71
79
  <head>
72
80
  <meta charset="utf-8">
73
81
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
74
82
  <title>${title} · ${S.appName}</title>
83
+ <meta name="htmx-config" content='{"historyCacheSize":0,"refreshOnHistoryMiss":true}'>
75
84
  <link rel="stylesheet" href="${ASSETS["style.css"].url}">
76
85
  <script src="${ASSETS["htmx.min.js"].url}" defer></script>
77
86
  <script src="${ASSETS["app.js"].url}" defer></script>
78
87
  </head>
79
- <body class="${opts.signedIn ? "app" : ""} ${opts.fullScreen ? "full" : ""}">
88
+ <body class="${opts.signedIn ? "app" : ""} ${opts.fullScreen ? "full" : ""}" hx-boost="true">
80
89
  ${when(opts.signedIn, () => h `<aside class="sidebar">
81
90
  <div class="brand">${S.appName}<span>.</span></div>
82
91
  ${when(canSend, () => h `<button type="button" class="primary new-mail" data-compose>${icon("plus")}${S.newMail}</button>`)}
83
- <nav class="side-nav" aria-label="${S.mainNav}">
92
+ <nav class="side-nav" id="side-nav" data-live aria-label="${S.mainNav}">
84
93
  ${link("drafts", "/", S.navDrafts, "drafts", count)}
85
94
  ${link("inbox", "/inbox", S.navInbox, "inbox")}
86
95
  ${link("devices", "/devices", S.navDevices, "devices")}
@@ -88,7 +97,7 @@ ${when(opts.signedIn, () => h `<aside class="sidebar">
88
97
  <nav class="side-nav side-end" aria-label="${S.navSettings}">${link("settings", "/settings", S.navSettings, "settings")}</nav>
89
98
  </aside>`)}
90
99
  <main>${body}</main>
91
- ${when(opts.signedIn, () => h `<nav class="tabbar" aria-label="${S.mainNav}">
100
+ ${when(opts.signedIn, () => h `<nav class="tabbar" id="tabbar" data-live aria-label="${S.mainNav}">
92
101
  ${link("drafts", "/", S.navDrafts, "drafts", count)}
93
102
  ${link("inbox", "/inbox", S.navInbox, "inbox")}
94
103
  ${when(canSend, () => h `<button type="button" class="tab-compose" data-compose aria-label="${S.newMail}"><span>${icon("plus")}</span></button>`)}
@@ -155,8 +164,15 @@ export function signIn(token, valid) {
155
164
  <form method="post" action="/auth/${token}"><button class="primary">${S.signInButton}</button></form>
156
165
  </div>`;
157
166
  }
158
- function mailboxBadge(mailbox) {
159
- return h `<span class="badge mailbox">${mailbox}</span>`;
167
+ function localPart(address) {
168
+ return address.includes("@") ? address.slice(0, address.lastIndexOf("@")) : address;
169
+ }
170
+ /** An account by the local part of the address it receives mail at. */
171
+ function mailboxBadge(address) {
172
+ return h `<span class="badge mailbox">${localPart(address)}</span>`;
173
+ }
174
+ function draftAccount(d) {
175
+ return bareAddress(d.from);
160
176
  }
161
177
  const PREVIEWABLE = new Set(["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif"]);
162
178
  /** Image types a browser renders without running code; SVG is left out on purpose. */
@@ -239,7 +255,7 @@ export function draftCard(d) {
239
255
  return h `<article class="card draft" id="draft-${d.id}">
240
256
  <div class="meta">
241
257
  <span class="badge draft">${S.draft}</span>
242
- ${mailboxBadge(d.mailbox)}
258
+ ${mailboxBadge(draftAccount(d))}
243
259
  <span>${d.edited_by_human ? S.editedByHuman : S.byAgent} · ${formatDate(d.created_at)}</span>
244
260
  </div>
245
261
  <div class="draft-head">
@@ -263,7 +279,7 @@ export function draftEditor(d, form, conflict) {
263
279
  <div class="grabber" aria-hidden="true"></div>
264
280
  <div class="drop-hint">${S.dropFiles}</div>
265
281
  <button type="button" class="icon-btn sheet-close" data-close aria-label="${S.close}">${icon("close")}</button>
266
- <div class="sheet-head"><span class="badge draft">${S.draft}</span>${mailboxBadge(d.mailbox)}</div>
282
+ <div class="sheet-head"><span class="badge draft">${S.draft}</span>${mailboxBadge(draftAccount(d))}</div>
267
283
  ${when(d.note, () => h `<div class="note">${d.note}</div>`)}
268
284
  ${when(conflict, () => h `<div class="sheet-conflict">
269
285
  <p class="warn">${S.conflictTitle}</p>
@@ -307,10 +323,16 @@ export function draftFiles(d, error) {
307
323
  export function draftDone(id, text) {
308
324
  return h `<article class="card notice" id="draft-${id}">${text}</article>`;
309
325
  }
326
+ /** A list's title: the session's sending domains, with the list's name beside them. */
327
+ function listTitle(domains, label) {
328
+ return domains.length
329
+ ? h `<h1>${domains.join(" · ")} <small>${label}</small></h1>`
330
+ : h `<h1>${label}</h1>`;
331
+ }
310
332
  /** Drafts waiting for review, listed like the inbox; each opens its thread. */
311
- export function draftList(drafts, current) {
312
- return h `<section class="list">
313
- <header class="list-head"><h1>${S.navDrafts}</h1></header>
333
+ export function draftList(drafts, domains, current) {
334
+ return h `<section class="list" id="list" data-live>
335
+ <header class="list-head">${listTitle(domains, S.navDrafts)}</header>
314
336
  ${drafts.length ? join(drafts.map(d => h `<a class="row" href="/drafts/${d.id}" ${raw(d.id === current ? 'aria-current="page"' : "")}>
315
337
  <span class="avatar" aria-hidden="true">${initials(d.to[0] ?? d.mailbox)}</span>
316
338
  <span class="row-main">
@@ -318,7 +340,7 @@ export function draftList(drafts, current) {
318
340
  <span class="row-subject">${d.subject || "—"}</span>
319
341
  <span class="row-snippet">${d.text}</span>
320
342
  <span class="row-tags">
321
- ${mailboxBadge(d.mailbox)}
343
+ ${mailboxBadge(draftAccount(d))}
322
344
  <span class="row-by">${d.edited_by_human ? S.editedByHuman : S.byAgent}</span>
323
345
  </span>
324
346
  </span>
@@ -331,16 +353,17 @@ export function inboxQuery(filter) {
331
353
  /** The thread list; on a wide screen it stays beside the open thread. */
332
354
  export function threadList(threads, opts) {
333
355
  const { filter } = opts;
356
+ const mailboxLabel = (m) => opts.domains.length === 1 ? localPart(opts.addressOf(m)) : opts.addressOf(m);
334
357
  const tab = (status, label) => h `<a class="chip" href="/inbox?${inboxQuery({ ...filter, status })}" ${raw(filter.status === status ? 'aria-current="page"' : "")}>${label}</a>`;
335
- return h `<section class="list">
358
+ return h `<section class="list" id="list" data-live>
336
359
  <header class="list-head">
337
- <h1>${opts.domains.length ? opts.domains.join(" · ") : S.navInbox}</h1>
360
+ ${listTitle(opts.domains, S.navInbox)}
338
361
  <form class="filters" method="get" action="/inbox">
339
362
  <input type="hidden" name="status" value="${filter.status}">
340
363
  <nav class="chips" aria-label="${S.filter}">${tab("unanswered", S.filterPending)}${tab("all", S.filterAll)}${tab("archived", S.filterArchived)}</nav>
341
- ${when(opts.mailboxes.length > 1, () => h `<span class="select"><select name="mailbox" aria-label="${S.allMailboxes}" onchange="this.form.submit()">
364
+ ${when(opts.accounts.length > 1, () => h `<span class="select"><select name="mailbox" aria-label="${S.allMailboxes}" onchange="this.form.requestSubmit()">
342
365
  <option value="">${S.allMailboxes}</option>
343
- ${join(opts.mailboxes.map(m => h `<option value="${m}" ${raw(m === filter.mailbox ? "selected" : "")}>${m}</option>`))}
366
+ ${join(opts.accounts.map(m => h `<option value="${m}" ${raw(m === filter.mailbox ? "selected" : "")}>${mailboxLabel(m)}</option>`))}
344
367
  </select></span>`)}
345
368
  </form>
346
369
  </header>
@@ -348,15 +371,15 @@ export function threadList(threads, opts) {
348
371
  </section>`;
349
372
  }
350
373
  function threadRow(t, opts) {
351
- const people = t.participants.filter(p => !opts.own.has(p));
374
+ const people = t.participants.filter(p => !opts.own(p));
352
375
  return h `<a class="row ${t.unread ? "unread" : ""}" href="/threads/${t.id}?${inboxQuery(opts.filter)}" ${raw(t.id === opts.current ? 'aria-current="page"' : "")}>
353
376
  <span class="avatar" aria-hidden="true">${initials(people[0] ?? t.mailbox)}</span>
354
377
  <span class="row-main">
355
378
  <span class="row-top"><span class="who">${people.join(", ") || t.mailbox}</span><time datetime="${t.last_at}">${formatDate(t.last_at)}</time></span>
356
379
  <span class="row-subject">${t.subject || "—"}</span>
357
- ${when(t.has_draft || opts.mailboxes.length > 1 || t.unread, () => h `<span class="row-tags">
380
+ ${when(t.has_draft || opts.accounts.length > 1 || t.unread, () => h `<span class="row-tags">
358
381
  ${when(t.has_draft, () => h `<span class="badge draft">${S.hasDraft}</span>`)}
359
- ${when(opts.mailboxes.length > 1, () => mailboxBadge(t.mailbox))}
382
+ ${when(opts.accounts.length > 1, () => mailboxBadge(opts.addressOf(opts.accountOf(t))))}
360
383
  ${when(t.unread, () => h `<span class="dot" title="${S.unread}"></span>`)}
361
384
  </span>`)}
362
385
  </span>
@@ -370,8 +393,8 @@ export function inboxPage(list, thread) {
370
393
  export function threadView(thread, entries, ctx, opts) {
371
394
  const query = inboxQuery(opts.filter);
372
395
  const rows = contextRows(ctx);
373
- const people = thread.participants.filter(p => !opts.own.has(p));
374
- const title = h `<span class="thread-subject">${thread.subject || "—"}</span><span class="thread-meta">${[...people, thread.mailbox].join(" · ")}</span>`;
396
+ const people = thread.participants.filter(p => !opts.own(p));
397
+ const title = h `<span class="thread-subject">${thread.subject || "—"}</span><span class="thread-meta">${[...people, opts.account].join(" · ")}</span>`;
375
398
  const items = [];
376
399
  let day = "";
377
400
  for (const entry of entries) {
@@ -390,7 +413,7 @@ export function threadView(thread, entries, ctx, opts) {
390
413
  ${when(rows.length, () => h `<button type="button" class="context-btn" data-context-toggle aria-controls="context">${S.context}</button>`)}
391
414
  ${archiveButton(thread)}
392
415
  </header>
393
- <div class="messages" data-scroll-end>${join(items)}</div>
416
+ <div class="messages" id="messages" data-live data-scroll-end>${join(items)}</div>
394
417
  ${when(opts.reply.allowed, () => h `<form class="composer" method="post" action="/threads/${thread.id}/reply?${query}">
395
418
  ${when(opts.reply.replyAll, () => h `<label class="reply-all"><input type="checkbox" name="reply_all" value="1">${S.replyAll}</label>`)}
396
419
  <button type="button" class="icon-btn" aria-label="${S.fullReply}" title="${S.fullReply}" hx-get="/threads/${thread.id}/reply/full?${query}" hx-include="closest form" hx-target="#edit-sheet" hx-swap="innerHTML">${icon("plus")}</button>
@@ -412,7 +435,7 @@ export function archiveButton(thread) {
412
435
  <button class="icon-btn" aria-label="${label}" title="${label}">${icon(thread.archived ? "unarchive" : "archive")}</button>
413
436
  </form>`;
414
437
  }
415
- export function devicesPage(sessions, currentId) {
438
+ export function devicesPage(sessions, currentId, addressOf) {
416
439
  return h `<section class="list">
417
440
  <header class="list-head"><h1>${S.navDevices}</h1></header>
418
441
  ${sessions.length ? join(sessions.map(s => h `<div class="row device" id="session-${s.id}">
@@ -422,18 +445,20 @@ export function devicesPage(sessions, currentId) {
422
445
  ${when(s.label && s.user_agent, () => h `<span class="row-subject">${s.user_agent}</span>`)}
423
446
  <span class="row-tags">
424
447
  ${when(s.id === currentId, () => h `<span class="badge">${S.thisDevice}</span>`)}
425
- ${when(s.scope, () => join(s.scope.map(mailboxBadge)))}
448
+ ${when(s.scope, () => join(s.scope.map(m => mailboxBadge(addressOf(m)))))}
426
449
  <span class="row-by">${S.signedIn} ${formatDate(s.created_at)} · ${S.createdBy} ${s.created_by}</span>
427
450
  </span>
428
451
  </span>
429
- ${when(s.id !== currentId, () => h `<button class="danger" hx-post="/devices/${s.id}/revoke" hx-target="#session-${s.id}" hx-swap="delete">${S.revoke}</button>`)}
452
+ ${s.id === currentId
453
+ ? h `<form method="post" action="/logout"><button class="danger">${S.logout}</button></form>`
454
+ : h `<button class="danger" hx-post="/devices/${s.id}/revoke" hx-target="#session-${s.id}" hx-swap="delete">${S.revoke}</button>`}
430
455
  </div>`)) : h `<p class="empty">${S.devicesEmpty}</p>`}
431
456
  </section>`;
432
457
  }
433
458
  export function settingsPage(theme) {
434
459
  return h `<div class="page">
435
460
  <h1>${S.navSettings}</h1>
436
- <form class="setting" method="post" action="/theme">
461
+ <form class="setting" method="post" action="/theme" hx-boost="false">
437
462
  <label for="theme">${S.theme}</label>
438
463
  <span class="select"><select id="theme" name="theme" onchange="this.form.submit()">
439
464
  ${join(["system", "light", "dark"].map(t => h `<option value="${t}" ${raw(t === theme ? "selected" : "")}>${{ system: S.themeSystem, light: S.themeLight, dark: S.themeDark }[t]}</option>`))}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "inboxer",
3
- "version": "0.4.8",
3
+ "version": "0.4.10",
4
4
  "description": "A self-hosted mail layer for agents: persists every inbound and outbound email, exposes an MCP server, and ships a minimal UI to review drafts.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
package/src/core/mail.ts CHANGED
@@ -101,6 +101,8 @@ export class Mail {
101
101
  private readonly domains: Set<string>;
102
102
  private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();
103
103
  private readonly files: AttachmentFiles;
104
+ /** Fires "change" after every write, so open pages can refresh. */
105
+ readonly changes = new EventTarget();
104
106
 
105
107
  constructor(store: Store, provider: MailProvider, cfg: InboxerConfig) {
106
108
  this.store = store;
@@ -111,6 +113,13 @@ export class Mail {
111
113
  this.files = new AttachmentFiles(cfg.dataDir);
112
114
  }
113
115
 
116
+ /** Runs `fn` in the store's write queue, then announces the change. */
117
+ private async write<T>(fn: () => Promise<T>): Promise<T> {
118
+ const result = await this.store.serialize(fn);
119
+ this.changes.dispatchEvent(new Event("change"));
120
+ return result;
121
+ }
122
+
114
123
  listMailboxes(scope: Scope): { id: string; address: string; name: string }[] {
115
124
  return [
116
125
  ...Object.entries(this.cfg.mailboxes).map(([id, m]) => ({ id, address: m.address, name: m.name })),
@@ -134,6 +143,12 @@ export class Mail {
134
143
  return thread.mailbox === CATCHALL ? this.catchAllAddress(thread.participants) ?? CATCHALL : thread.mailbox;
135
144
  }
136
145
 
146
+ /** The address an account receives mail at: a configured mailbox's address, or the catch-all address itself. */
147
+ addressOf(account: string): string {
148
+ const mailbox = this.cfg.mailboxes[account];
149
+ return mailbox ? bareAddress(mailbox.address) : account;
150
+ }
151
+
137
152
  /** Mailboxes in scope, with the catch-all split into the addresses it has received mail for. */
138
153
  async listAccounts(scope: Scope): Promise<string[]> {
139
154
  const mailboxes = this.listMailboxes(scope).map(m => m.id).filter(id => id !== CATCHALL);
@@ -202,7 +217,7 @@ export class Mail {
202
217
  }
203
218
 
204
219
  private storeInbound(providerId: string, inbound: Awaited<ReturnType<MailProvider["getInbound"]>>): Promise<string> {
205
- return this.store.serialize(async () => {
220
+ return this.write(async () => {
206
221
  const existing = await this.store.lookupProviderId(this.provider.name, providerId);
207
222
  if (existing) return existing;
208
223
 
@@ -271,7 +286,7 @@ export class Mail {
271
286
 
272
287
  /** Status updates never move backwards: a late `sent` does not overwrite `delivered`. */
273
288
  applyStatus(providerId: string, status: DeliveryStatus, messageId: string | null): Promise<void> {
274
- return this.store.serialize(async () => {
289
+ return this.write(async () => {
275
290
  const id = await this.store.lookupProviderId(this.provider.name, providerId);
276
291
  if (!id) return;
277
292
  const message = await this.store.requireMessage(id);
@@ -359,7 +374,7 @@ export class Mail {
359
374
  const bare = bareAddress(address);
360
375
  if (!bare.includes("@")) throw new InvalidRequestError(`"${address}" is not an email address`);
361
376
  await this.requireContactAccess(bare, actor.scope);
362
- return this.store.serialize(async () => {
377
+ return this.write(async () => {
363
378
  const contact: Contact = { address: bare, ...this.merge(await this.store.getContact(bare), patch, actor) };
364
379
  await this.store.putContact(contact);
365
380
  await this.store.audit("contact.update", actor, bare, { ...patch });
@@ -368,7 +383,7 @@ export class Mail {
368
383
  }
369
384
 
370
385
  setThreadContext(threadId: string, patch: ContextPatch, actor: Actor): Promise<Context> {
371
- return this.store.serialize(async () => {
386
+ return this.write(async () => {
372
387
  await this.requireThread(threadId, actor.scope);
373
388
  const context = this.merge(await this.store.getThreadContext(threadId), patch, actor);
374
389
  await this.store.putThreadContext(threadId, context);
@@ -403,7 +418,7 @@ export class Mail {
403
418
  }
404
419
 
405
420
  private updateMessages(ids: string[], actor: Actor, action: string, change: (m: Message) => void): Promise<number> {
406
- return this.store.serialize(async () => {
421
+ return this.write(async () => {
407
422
  const messageIds = await this.resolveMessageIds(ids, actor.scope);
408
423
  const threads = new Set<string>();
409
424
  for (const id of messageIds) {
@@ -435,7 +450,7 @@ export class Mail {
435
450
  // Drafts and sending
436
451
 
437
452
  createDraft(input: CreateDraftInput, actor: Actor): Promise<Message> {
438
- return this.store.serialize(() => this.createDraftUnlocked(input, actor));
453
+ return this.write(() => this.createDraftUnlocked(input, actor));
439
454
  }
440
455
 
441
456
  /** Who a reply to `replyToId` goes to and its subject, without creating anything. */
@@ -537,7 +552,7 @@ export class Mail {
537
552
  * human edited unless it passes `force`. A UI edit regenerates the HTML from the text at send time.
538
553
  */
539
554
  updateDraft(id: string, version: number, patch: DraftPatch, actor: Actor, force = false): Promise<Message> {
540
- return this.store.serialize(async () => {
555
+ return this.write(async () => {
541
556
  const draft = await this.requireDraft(id, actor.scope);
542
557
  if (draft.version !== version) throw new ConflictError(draft);
543
558
  if (draft.pending) throw new InvalidRequestError(`Draft ${id} is about to ${draft.pending.action}; undo it first`);
@@ -559,7 +574,7 @@ export class Mail {
559
574
  }
560
575
 
561
576
  discardDraft(id: string, actor: Actor): Promise<void> {
562
- return this.store.serialize(() => this.discardDraftUnlocked(id, actor));
577
+ return this.write(() => this.discardDraftUnlocked(id, actor));
563
578
  }
564
579
 
565
580
  private async discardDraftUnlocked(id: string, actor: Actor): Promise<void> {
@@ -574,7 +589,7 @@ export class Mail {
574
589
 
575
590
  /** Attaching does not change `version`: it never conflicts with text edits in flight. */
576
591
  attach(id: string, file: { filename: string; contentType: string; body: Uint8Array }, actor: Actor): Promise<Message> {
577
- return this.store.serialize(async () => {
592
+ return this.write(async () => {
578
593
  const draft = await this.requireDraft(id, actor.scope);
579
594
  if (draft.pending) throw new InvalidRequestError(`Draft ${id} is about to ${draft.pending.action}; undo it first`);
580
595
  const meta: AttachmentMeta = {
@@ -594,7 +609,7 @@ export class Mail {
594
609
  }
595
610
 
596
611
  detach(id: string, attachmentId: string, actor: Actor): Promise<Message> {
597
- return this.store.serialize(async () => {
612
+ return this.write(async () => {
598
613
  const draft = await this.requireDraft(id, actor.scope);
599
614
  if (draft.pending) throw new InvalidRequestError(`Draft ${id} is about to ${draft.pending.action}; undo it first`);
600
615
  const index = draft.attachments.findIndex(a => a.id === attachmentId);
@@ -610,7 +625,7 @@ export class Mail {
610
625
 
611
626
  /** Starts the undo window for a send or discard. Calling it again keeps the first one. */
612
627
  schedule(id: string, action: PendingAction["action"], actor: Actor): Promise<Message> {
613
- return this.store.serialize(async () => {
628
+ return this.write(async () => {
614
629
  const draft = await this.requireDraft(id, actor.scope);
615
630
  if (!draft.pending) {
616
631
  draft.pending = { action, at: new Date(Date.now() + this.cfg.ui.undoSec * 1000).toISOString(), by: actor.name };
@@ -623,7 +638,7 @@ export class Mail {
623
638
  }
624
639
 
625
640
  undo(id: string, actor: Actor): Promise<Message> {
626
- return this.store.serialize(async () => {
641
+ return this.write(async () => {
627
642
  const draft = await this.requireDraft(id, actor.scope);
628
643
  clearTimeout(this.timers.get(id));
629
644
  this.timers.delete(id);
@@ -661,7 +676,7 @@ export class Mail {
661
676
  /** A failed send leaves a plain pending draft, so the reviewer sees it was not sent. */
662
677
  private runPending(id: string): Promise<void> {
663
678
  this.timers.delete(id);
664
- return this.store.serialize(async () => {
679
+ return this.write(async () => {
665
680
  const draft = await this.store.getMessage(id);
666
681
  if (!draft || draft.status !== "draft" || !draft.pending) return;
667
682
  const { action, by } = draft.pending;
@@ -674,7 +689,7 @@ export class Mail {
674
689
  }
675
690
 
676
691
  sendDraft(id: string, actor: Actor): Promise<Message> {
677
- return this.store.serialize(() => this.sendDraftUnlocked(id, actor));
692
+ return this.write(() => this.sendDraftUnlocked(id, actor));
678
693
  }
679
694
 
680
695
  /**
@@ -729,7 +744,7 @@ export class Mail {
729
744
 
730
745
  /** Direct send. If the provider fails, the message stays as a pending draft. */
731
746
  send(input: CreateDraftInput, actor: Actor): Promise<Message> {
732
- return this.store.serialize(async () => {
747
+ return this.write(async () => {
733
748
  const draft = await this.createDraftUnlocked(input, actor);
734
749
  return this.sendDraftUnlocked(draft.id, actor);
735
750
  });
package/src/ui/routes.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { Context, Hono } from "hono";
2
2
  import { deleteCookie, getCookie, getSignedCookie, setCookie, setSignedCookie } from "hono/cookie";
3
+ import { streamSSE } from "hono/streaming";
3
4
  import type { Access } from "../auth.ts";
4
5
  import { domainOf, splitAddresses } from "../core/address.ts";
5
6
  import { ConflictError, InvalidRequestError, toView, type Mail, type MessageView, type ThreadStatus } from "../core/mail.ts";
@@ -33,6 +34,7 @@ export function registerUi(app: Hono<UiEnv>, mail: Mail, access: Access, cfg: In
33
34
  const secret = cfg.ui.cookieSecret;
34
35
  const cookieOptions = { httpOnly: true, secure: true, sameSite: "Lax", path: "/", maxAge: COOKIE_MAX_AGE } as const;
35
36
 
37
+ const hue = V.accentHue([...new Set(Object.values(cfg.mailboxes).map(m => domainOf(m.address)))]);
36
38
  const own = (address: string): boolean => mail.isOwn(address);
37
39
  /** Recipients that are our own addresses are implied by the mailbox badge. */
38
40
  const shown = (m: MessageView): MessageView => ({
@@ -50,7 +52,7 @@ export function registerUi(app: Hono<UiEnv>, mail: Mail, access: Access, cfg: In
50
52
  const shell = session
51
53
  ? { draftCount: (await mail.listDrafts(undefined, session.scope)).length, senders: senders(session) }
52
54
  : {};
53
- return c.html(V.layout(title, body, { theme: theme(c), page: current, signedIn: !!session, fullScreen, ...shell }), status);
55
+ return c.html(V.layout(title, body, { theme: theme(c), hue, page: current, signedIn: !!session, fullScreen, ...shell }), status);
54
56
  };
55
57
 
56
58
  // Sign-in: GET only shows a button, so link previews and scanners do not burn the link.
@@ -83,7 +85,7 @@ export function registerUi(app: Hono<UiEnv>, mail: Mail, access: Access, cfg: In
83
85
  return c.redirect(path, 303);
84
86
  });
85
87
 
86
- const ui = ["/", "/inbox", "/threads/*", "/drafts/*", "/attachments/*", "/compose", "/devices", "/devices/*", "/settings", "/logout"];
88
+ const ui = ["/", "/inbox", "/threads/*", "/drafts/*", "/attachments/*", "/compose", "/devices", "/devices/*", "/settings", "/logout", "/events"];
87
89
  for (const path of ui) {
88
90
  app.use(path, async (c, next) => {
89
91
  const value = await getSignedCookie(c, secret, SESSION_COOKIE);
@@ -211,7 +213,7 @@ export function registerUi(app: Hono<UiEnv>, mail: Mail, access: Access, cfg: In
211
213
  const filter = inboxFilter(c);
212
214
  const threads = await mail.listThreads({ mailbox: filter.mailbox || undefined, status: filter.status as ThreadStatus, limit: 200 }, session.scope);
213
215
  const accounts = await mail.listAccounts(session.scope);
214
- return V.threadList(threads, { accounts, accountOf: t => mail.accountOf(t), domains: domainsOf(session), filter, own, current });
216
+ return V.threadList(threads, { accounts, accountOf: t => mail.accountOf(t), addressOf: a => mail.addressOf(a), domains: domainsOf(session), filter, own, current });
215
217
  };
216
218
 
217
219
  app.get("/inbox", async c => page(c, S.navInbox, V.inboxPage(await threadList(c, null), null), "inbox"));
@@ -339,9 +341,17 @@ export function registerUi(app: Hono<UiEnv>, mail: Mail, access: Access, cfg: In
339
341
 
340
342
  app.get("/devices", async c => {
341
343
  const session = c.get("session");
342
- return page(c, S.navDevices, V.devicesPage(await access.listSessions(session.scope), session.id), "devices");
344
+ return page(c, S.navDevices, V.devicesPage(await access.listSessions(session.scope), session.id, a => mail.addressOf(a)), "devices");
343
345
  });
344
346
 
347
+ // Every write pings open pages, which refetch their live regions; the stream carries no mail data.
348
+ app.get("/events", c => streamSSE(c, async stream => {
349
+ const ping = () => void stream.writeSSE({ event: "change", data: "1" });
350
+ mail.changes.addEventListener("change", ping);
351
+ await new Promise<void>(resolve => stream.onAbort(resolve));
352
+ mail.changes.removeEventListener("change", ping);
353
+ }));
354
+
345
355
  app.get("/settings", async c => page(c, S.navSettings, V.settingsPage(theme(c)), "settings"));
346
356
 
347
357
  app.post("/devices/:id/revoke", async c => {
@@ -353,6 +363,6 @@ export function registerUi(app: Hono<UiEnv>, mail: Mail, access: Access, cfg: In
353
363
  const session = c.get("session");
354
364
  await access.revokeSession(session.id, uiActor(session), "session.logout");
355
365
  deleteCookie(c, SESSION_COOKIE, { path: "/", secure: true });
356
- return c.html(V.layout(S.signedOut, V.message([S.signedOut]), { theme: theme(c), page: null, signedIn: false }));
366
+ return c.html(V.layout(S.signedOut, V.message([S.signedOut]), { theme: theme(c), hue, page: null, signedIn: false }));
357
367
  });
358
368
  }
@@ -33,11 +33,72 @@ document.addEventListener("keydown", event => {
33
33
  if (event.key === "Escape") document.body.classList.remove("context-open");
34
34
  });
35
35
 
36
- // A thread opens at its latest message.
37
- document.addEventListener("DOMContentLoaded", () => {
36
+ // Links and forms load the next page with htmx and swap only the body, so scripts and styles stay loaded.
37
+ // The body's classes come from the new page, and an error page shows instead of nothing.
38
+ // Back and forward reload the page (see htmx-config), so a page is never restored with stale mail.
39
+ document.addEventListener("htmx:beforeSwap", event => {
40
+ if (!event.detail.boosted) return;
41
+ if (event.detail.xhr.status >= 400) {
42
+ event.detail.shouldSwap = true;
43
+ event.detail.isError = false;
44
+ }
45
+ document.body.className = /<body[^>]*class="([^"]*)"/.exec(event.detail.serverResponse)?.[1] ?? "";
46
+ });
47
+
48
+ document.addEventListener("htmx:afterSwap", event => {
49
+ if (event.detail.boosted) pageShown();
50
+ });
51
+
52
+ document.addEventListener("DOMContentLoaded", pageShown);
53
+
54
+ // A thread opens at its latest message; a signed-in page listens for changes.
55
+ function pageShown() {
38
56
  const messages = document.querySelector("[data-scroll-end]");
39
57
  if (messages) messages.scrollTop = messages.scrollHeight;
40
- });
58
+ listen();
59
+ }
60
+
61
+ // The server reports every change to the mail; the page then refetches itself once and swaps in its
62
+ // [data-live] regions by id. A burst of changes waits for a short quiet spell.
63
+ const REFRESH_DELAY_MS = 300;
64
+ let source = null;
65
+ let timer = null;
66
+
67
+ function listen() {
68
+ const signedIn = document.body.classList.contains("app");
69
+ if (signedIn && !source) {
70
+ source = new EventSource("/events");
71
+ source.addEventListener("change", refreshSoon);
72
+ // After a reconnect, changes made while it was down are caught up.
73
+ let opened = false;
74
+ source.addEventListener("open", () => opened ? refreshSoon() : opened = true);
75
+ } else if (!signedIn && source) {
76
+ source.close();
77
+ source = null;
78
+ }
79
+ }
80
+
81
+ function refreshSoon() {
82
+ clearTimeout(timer);
83
+ timer = setTimeout(refresh, REFRESH_DELAY_MS);
84
+ }
85
+
86
+ async function refresh() {
87
+ if (!document.querySelector("[data-live]")) return;
88
+ const url = location.href;
89
+ const res = await fetch(url);
90
+ if (!res.ok || location.href !== url) return;
91
+ const next = new DOMParser().parseFromString(await res.text(), "text/html");
92
+ for (const region of document.querySelectorAll("[data-live]")) {
93
+ const fresh = next.getElementById(region.id);
94
+ if (!fresh || region.contains(document.activeElement?.closest("input, select, textarea"))) continue;
95
+ const atEnd = region.scrollHeight - region.scrollTop - region.clientHeight < 2;
96
+ const scrollTop = region.scrollTop;
97
+ region.replaceWith(fresh);
98
+ fresh.scrollTop = fresh.hasAttribute("data-scroll-end") && atEnd ? fresh.scrollHeight : scrollTop;
99
+ htmx.process(fresh);
100
+ }
101
+ }
41
102
 
42
103
  // Files dropped on a [data-drop] zone go to its file input, which uploads them through htmx.
43
104
  const zoneOf = event => event.target instanceof Element ? event.target.closest("[data-drop]") : null;
@@ -7,10 +7,11 @@
7
7
  --soft: light-dark(#f1f1ef, #1f1f1e);
8
8
  --chip: light-dark(#e9e9e6, #333331);
9
9
  --surface: light-dark(#ffffff, #2e2e2c);
10
- --mine: light-dark(#ffe6d6, #4a2e20);
11
- --mine-line: light-dark(#ffd2b8, #5e3a28);
12
- --accent: light-dark(#ff4d00, #ff7a3d);
13
- --accent-text: light-dark(#c43d00, #ff8f5c);
10
+ /* --hue is set per instance on <html>, from its mail domains. */
11
+ --mine: light-dark(oklch(0.95 0.03 var(--hue)), oklch(0.33 0.045 var(--hue)));
12
+ --mine-line: light-dark(oklch(0.89 0.055 var(--hue)), oklch(0.4 0.06 var(--hue)));
13
+ --accent: light-dark(oklch(0.75 0.13 var(--hue)), oklch(0.78 0.11 var(--hue)));
14
+ --accent-text: light-dark(oklch(0.5 0.13 var(--hue)), oklch(0.83 0.09 var(--hue)));
14
15
  --focus: light-dark(#0a0a0a, #a3a39e);
15
16
  --primary-bg: light-dark(#0a0a0a, #ececea);
16
17
  --primary-fg: light-dark(#fbfbfa, #1f1f1e);
@@ -31,7 +32,7 @@
31
32
  body { margin: 0; background: var(--bg); color: var(--fg); }
32
33
  a { color: inherit; text-decoration: none; }
33
34
  h1 { font-size: 2rem; line-height: 1.1; letter-spacing: -0.04em; font-weight: 700; margin: 0 0 24px; }
34
- ::selection { background: var(--accent); color: #fff; }
35
+ ::selection { background: var(--accent); color: #1f1f1e; }
35
36
  .icon { flex: none; }
36
37
 
37
38
  /* Shell: a tab bar on a phone, a sidebar on a wide screen */