Files
webmail/lib/offline/state.ts
T
Linus Rath 687e7cc012 feat: move offline mode onto the encrypted local store
The IndexedDB cache, its crypto, the responder and the page-side sync
go. lib/offline keeps its structure, policy, wipes, sign-out gates and
notices; answers, the outbox and sync now live in lib/store, in a worker
behind lib/store/client/api.ts.

What users get besides that:
- every folder is kept, not just the Inbox and opened ones
- delete for good and empty trash work offline
- a change the server refuses, or that meets a message changed on
  another device, is shown instead of dropped
- a send whose response got lost is looked up by a Message-ID fixed when
  it was queued, then finished, submitted or sent again
- with the store on, a start paints from the local copy, then connects

An account the app drops by itself no longer wipes its data: only a
sign-out or an explicit removal does. The outbox of the old database
moves over once, in lib/offline/migrate-legacy.ts, and the old database
goes only after the store committed. `isNetworkFailure` now counts
timeouts and proxy 5xx. Sends and outbox requests are never answered
from the device.

Tests moved with the code: cache.test.ts and responder.test.ts are
replaced by lib/store/__tests__/, and review-fixes.test.ts, outbox.test.ts
and client-fallback.test.ts now run the real engine on node:sqlite.
Changed assertions: an uncertain send is looked up rather than left alone
forever, destroy and empty trash are queued rather than refused, and #9
(opened folders) became "a folder the server deleted goes", since all
folders are kept.
2026-11-03 05:54:39 +01:00

105 lines
3.5 KiB
TypeScript

/**
* What offline mode (#523) shows: which accounts keep mail on this device,
* whether the browser is offline, what waits in the outbox, how much the
* local store uses. The switch itself ("Keep mail on this device") is per account
* and per browser, in localStorage, never synced: it is off until the user
* turns it on here.
*/
import { create } from 'zustand';
import type { ConflictEntry, OutboxEntry, OutboxError } from './queue';
/** localStorage: the local account ids that keep mail on this device. */
export const OFFLINE_ACCOUNTS_KEY = 'bulwark-offline-accounts';
export interface OutboxRow {
id: number;
account: string;
createdAt: number;
subject: string;
to: string[];
status: OutboxEntry['status'];
error?: OutboxError;
}
interface OfflineState {
/** Accounts with "Keep mail on this device" on. */
enabled: string[];
/** The browser says it has no network. */
browserOffline: boolean;
/** Mail servers (their URLs) that couldn't be reached at the last request. */
downServers: string[];
/** The app started without the server, from the mail on this device. */
startedOffline: boolean;
outbox: OutboxRow[];
pendingChanges: number;
/** Changes the server refused, or that met a message changed on another device. */
conflicts: ConflictEntry[];
usageBytes: number;
/** Accounts whose mail is being brought onto the device right now. */
syncing: string[];
lastSyncedAt: Record<string, number>;
}
function readEnabled(): string[] {
try {
const raw = typeof localStorage === 'undefined' ? null : localStorage.getItem(OFFLINE_ACCOUNTS_KEY);
const parsed = raw ? JSON.parse(raw) : [];
return Array.isArray(parsed) ? parsed.filter((id): id is string => typeof id === 'string') : [];
} catch {
return [];
}
}
export const useOfflineStore = create<OfflineState>()(() => ({
enabled: readEnabled(),
browserOffline: typeof navigator !== 'undefined' && navigator.onLine === false,
downServers: [],
startedOffline: false,
outbox: [],
pendingChanges: 0,
conflicts: [],
usageBytes: 0,
syncing: [],
lastSyncedAt: {},
}));
export function writeEnabled(enabled: string[]): void {
useOfflineStore.setState({ enabled });
try {
if (enabled.length) localStorage.setItem(OFFLINE_ACCOUNTS_KEY, JSON.stringify(enabled));
else localStorage.removeItem(OFFLINE_ACCOUNTS_KEY);
} catch {
/* storage unavailable */
}
}
export function serverKey(url: string): string {
return url.replace(/\/+$/, '').toLowerCase();
}
/** The browser is offline, or this mail server (any, without one) couldn't be reached. */
export function isOfflineNow(serverUrl?: string): boolean {
const { browserOffline, downServers } = useOfflineStore.getState();
if (browserOffline) return true;
return serverUrl ? downServers.includes(serverKey(serverUrl)) : downServers.length > 0;
}
export function setServerDown(serverUrl: string, down: boolean): boolean {
const key = serverKey(serverUrl);
const { downServers } = useOfflineStore.getState();
const was = downServers.includes(key);
if (was !== down) useOfflineStore.setState({ downServers: down ? [...downServers, key] : downServers.filter((s) => s !== key) });
return was;
}
/** The switch as another tab left it (it changed in localStorage there). */
export function readEnabledFrom(raw: string | null): string[] {
try {
const parsed = raw ? JSON.parse(raw) : [];
return Array.isArray(parsed) ? parsed.filter((id): id is string => typeof id === 'string') : [];
} catch {
return [];
}
}