diff --git a/README.md b/README.md index 37c55fd..5af693e 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,8 @@ CI runs `pnpm lint` and `pnpm test` on every PR. The build emits absolute URLs (`/assets/…`, `/config.json`, `/manifest.json`), so the same `index.html` works at any client-side route the server falls back to it for, such as the journal's `/u//` tracker links. To serve `webapp/` from a sub-path instead of the root, set `PUBLIC_PATH` when building, e.g. `PUBLIC_PATH=/chat/ pnpm build`. +The service worker is emitted as `sw.js` and registers only when that URL is served from the app’s own origin with a JavaScript MIME type. Serve it with a short cache policy, for example `Cache-Control: no-cache`, to avoid delaying worker updates. Web Push requires HTTPS and a VAPID key configured in the journal; see the journal README for setup. + `config.json` is copied into the build output, so edit it before `pnpm build` (or edit `webapp/config.json` after). `config.sample.json` shows the full key set; see [docs/config.md](docs/config.md) for the complete runtime configuration surface. ## License diff --git a/scripts/perf/budget.json b/scripts/perf/budget.json index 13f6fbc..2a8b8ab 100644 --- a/scripts/perf/budget.json +++ b/scripts/perf/budget.json @@ -5,7 +5,7 @@ "max": 304 }, "totalGzipKB": { - "max": 858 + "max": 860 } }, "cold": { diff --git a/src/journal/api.ts b/src/journal/api.ts index c23629c..ec0c865 100644 --- a/src/journal/api.ts +++ b/src/journal/api.ts @@ -998,6 +998,14 @@ export class JournalApi { return this.json("/notify"); } + public async webPushVapidKey(): Promise { + return this.json("/push/web/vapid-key"); + } + + public async registerWebPush(body: Record): Promise { + return this.json("/push/web/register", { method: "POST", body }); + } + /** * PUT /notify — changes any part of the settings: `mode`, `events`, this device's * `device_level`, or one conversation's `convo` level or mute (an explicit null clears it). diff --git a/src/journal/client.ts b/src/journal/client.ts index 5f3c825..43f254f 100644 --- a/src/journal/client.ts +++ b/src/journal/client.ts @@ -21,6 +21,7 @@ import { import type { Contact, ContactInvite, InviteAskAnswer, InviteAskDecision, InviteOpened } from "./contacts"; import { shareableInviteLink } from "./contact-link"; import { JournalConnection } from "./connection"; +import { viewingConvoId, watchTabFocus } from "./viewing"; import { effectiveUnread, makeIdSetStore, type IdSetStore } from "./conversation-flags"; import { parseCoordinatorConsent, resetSessionStops, spawnConsentRowsIn } from "./coordinator-consent"; import { JournalDatabase } from "./database"; @@ -625,6 +626,9 @@ export class MatronJournalClient { private globalSearchAbort?: AbortController; private database?: JournalDatabase; private connection?: JournalConnection; + private stopWatchingFocus?: () => void; + private lastViewing?: string | null; + private suspendGuard?: () => boolean; // Read state: which timeline rows and tracker items were actually on screen, reported as // `seen` / `item_seen` over the socket. Separate from read_marker and the unread badge. public readonly seen = new SeenTracker({ send: (op) => this.connection?.send(op) ?? false }); @@ -822,6 +826,14 @@ export class MatronJournalClient { return this.sessionGen; } + /** + * Web push supplies a guard that returns true once a subscription is registered for the session. + * Without a guard, the socket is never closed while hidden. + */ + public setSuspendGuard(guard: (() => boolean) | undefined): void { + this.suspendGuard = guard; + } + private allStorageHealthy(): boolean { return Object.values(this.storeHydrated).every(Boolean) && Object.values(this.storeWritable).every(Boolean); } @@ -1015,6 +1027,8 @@ export class MatronJournalClient { this.pendingFiles.clear(); this.transientAttachmentErrors.clear(); this.seen.reset(); + this.stopWatchingFocus?.(); + this.stopWatchingFocus = undefined; this.connection?.stop(); this.connection = undefined; if (this.storageListener) { @@ -1414,7 +1428,7 @@ export class MatronJournalClient { await history; return; } - this.connection?.send({ op: "viewing", convo_id: conversationId }); + this.sendViewing(conversationId); const conversation = this.state.conversations.find((candidate) => candidate.id === conversationId); if (conversation?.unread_count) this.scheduleRead(conversationId, conversation.last_seq, 0); @@ -1426,7 +1440,7 @@ export class MatronJournalClient { // Find in chat belongs to the conversation being left: a search still in flight must not // reopen it, nor answer a bar opened there later. this.endChatSearch(); - this.connection?.send({ op: "viewing", convo_id: null }); + this.sendViewing(null); if (this.state.session) storeSelectedConversation(this.state.session, undefined); this.patch({ selectedConversationId: undefined, events: [], pendingMessages: [] }); } @@ -2731,6 +2745,7 @@ export class MatronJournalClient { // user has since left. this.focusToken += 1; this.patch({ trackerView: next, ...(this.state.focusTarget ? { focusTarget: undefined } : {}) }); + this.sendViewing(); } // Memories view entry points: a name opens that memory's editor, "" opens the new-memory form, @@ -2755,6 +2770,7 @@ export class MatronJournalClient { this.trackerMissionGen += 1; this.trackerProjectGen += 1; this.patch({ trackerView: undefined, trackerItem: null, trackerMission: null, trackerProject: null }); + this.sendViewing(); } // Deep-link / row-tap entry points: select the row (last-tap-wins) and switch to its view. @@ -5261,6 +5277,8 @@ export class MatronJournalClient { this.dismissedAttachments.clear(); this.pendingFiles.clear(); this.transientAttachmentErrors.clear(); + this.stopWatchingFocus?.(); + this.stopWatchingFocus = undefined; this.connection?.stop(); this.database?.close(); this.defaultsServer = undefined; @@ -5457,7 +5475,9 @@ export class MatronJournalClient { // journal, and an unbound revoke would sign the new account out. const connectionGen = this.sessionGen; const current = (): boolean => this.sessionGen === connectionGen; + this.lastViewing = undefined; this.connection = new JournalConnection(session.serverUrl, session.token, { + canSuspend: () => this.suspendGuard?.() ?? false, cursor: async () => (await this.database?.cursor()) ?? cursor ?? 0, archiveSince: () => readArchiveSince(session) ?? 0, onFrame: async (frame) => { @@ -5478,7 +5498,11 @@ export class MatronJournalClient { onState: (connection, error) => { if (current()) this.patch({ connection, connectionError: error }); }, + onSuspend: () => { + if (current()) this.suspendLiveStreams(); + }, }); + this.stopWatchingFocus = watchTabFocus(window, document, () => this.onTabViewChange()); this.connection.start(); // Purge expired live tool logs once the session is up, not before the first paint: it walks // every cached row, and the store holds every row this device has received, so awaiting it @@ -5926,6 +5950,24 @@ export class MatronJournalClient { else if (this.state.session) storeSelectedConversation(this.state.session, undefined); } + /** The tab was shown, hidden, focused or blurred. Only showing and hiding change what is viewed. */ + private onTabViewChange(): void { + const before = this.lastViewing; + this.sendViewing(); + // A hidden tab stops receiving the open chat's live updates, so what they showed can no + // longer be trusted to end: the idle frame would not arrive. Showing the tab again re-views + // the chat, and the journal replays the tool output. + if (before && this.lastViewing === null) this.suspendLiveStreams(); + } + + private sendViewing(selectedId = this.state.selectedConversationId ?? null): void { + // The tracker covers the open chat's transcript: it is not being viewed. + const convoId = viewingConvoId(this.state.trackerView?.open ? null : selectedId); + if (convoId !== this.lastViewing && this.connection?.send({ op: "viewing", convo_id: convoId })) { + this.lastViewing = convoId; + } + } + private async handleReady(hello?: JournalControlFrame): Promise { // hello_ok carries the pin list on a journal with pins; its absence means an older journal. if (hello !== undefined) this.applyJournalPins(pinsFromContainer(hello)); @@ -5983,9 +6025,19 @@ export class MatronJournalClient { await this.refreshSelectedConversation(message.convoId, db, gen); if (!ownsReplay()) return; } + // Rows another tab stored while this one was suspended or offline are not replayed here: the + // cursor is the shared one. Reload what the views show from the store, not from the cursor. + await this.refreshConversations(); + if (!ownsReplay()) return; + const viewedId = this.state.selectedConversationId; + if (viewedId) { + await this.refreshSelectedConversation(viewedId, db, gen); + if (!ownsReplay()) return; + } for (const message of kept) this.sendPendingMessage(message, connection); + this.lastViewing = undefined; + this.sendViewing(); if (this.state.selectedConversationId) { - connection.send({ op: "viewing", convo_id: this.state.selectedConversationId }); const conversation = this.selectedConversation(); if (conversation?.unread_count) this.scheduleRead(conversation.id, conversation.last_seq, 0); } @@ -6358,6 +6410,8 @@ export class MatronJournalClient { offset: payload.offset ?? 0, headTruncated: false, }; + // An offset-less chunk would continue across whatever the closed socket missed. + if (current.stale && payload.offset === undefined) return; const offset = payload.offset ?? current.offset; if (offset <= current.offset) { const addition = trimUtf8Prefix(chunk, current.offset - offset); @@ -6371,6 +6425,23 @@ export class MatronJournalClient { this.toolStreams.set(frame.convo_id, streams); } + /** + * The tab's socket was closed while hidden, which ends the journal's live tool output for + * this device. Keep the text shown, mark it as no longer live, and let the snapshot the next + * connection's `viewing` draws replace it; never append to it. + */ + private suspendLiveStreams(): void { + for (const streams of this.toolStreams.values()) { + // New objects, so a view memoised on the stream re-renders. + for (const [ref, stream] of Object.entries(streams)) streams[ref] = { ...stream, stale: true }; + } + // An activity indicator is cleared only by the frame that ends it, which a closed socket + // cannot deliver; drop it rather than leave "thinking" shown after the agent went idle. + this.activities.clear(); + const selectedId = this.state.selectedConversationId; + if (selectedId !== undefined) this.refreshEphemeralState(selectedId); + } + private refreshEphemeralState(conversationId: string): void { this.patch({ activity: this.activities.get(conversationId), diff --git a/src/journal/components.tsx b/src/journal/components.tsx index cccafe1..4a1c06c 100644 --- a/src/journal/components.tsx +++ b/src/journal/components.tsx @@ -5895,6 +5895,7 @@ export function ToolStream({ stream }: { stream: ToolStreamState }): React.React > {nodes} + {stream.stale &&
live output no longer available
} diff --git a/src/journal/connection.ts b/src/journal/connection.ts index d38a600..d8e6745 100644 --- a/src/journal/connection.ts +++ b/src/journal/connection.ts @@ -33,8 +33,16 @@ interface JournalConnectionCallbacks { onSnapshotRequired(): Promise; onRevoked(): void; onState(state: ConnectionState, error?: string): void; + /** Whether an active push subscription permits closing the hidden tab's socket. Defaults to false. */ + canSuspend?(): boolean; + /** The socket was closed because the tab stayed hidden: views fed by the live socket (tool + * output) no longer update, and the next reconnect's snapshot replaces what they show. */ + onSuspend?(): void; } +// A hidden tab checks at this interval whether push permits closing its socket. +// Becoming visible again reconnects from the stored cursor. +export const HIDDEN_CLOSE_MS = 60_000; const RETRY_DELAYS_MS = [0, 1_000, 2_000, 4_000, 8_000, 15_000, 30_000]; // Upper bound on one coalesced journal run: keeps a single IndexedDB transaction and the render // after it bounded, and lets the UI paint between runs during a long replay. @@ -43,6 +51,9 @@ export const MAX_JOURNAL_BATCH = 500; export class JournalConnection { private socket?: WebSocket; private retryTimer?: number; + private hiddenTimer?: number; + // Closed on purpose because the tab was hidden: no retries until it is visible again. + private suspended = false; private retryAttempt = 0; private stopped = true; private welcomed = false; @@ -80,6 +91,9 @@ export class JournalConnection { this.stopped = false; window.addEventListener("online", this.onOnline); window.addEventListener("offline", this.onOffline); + document.addEventListener("visibilitychange", this.onVisibility); + this.suspended = false; + if (document.visibilityState === "hidden") this.armHiddenTimer(); this.open(); } @@ -91,6 +105,11 @@ export class JournalConnection { this.retryTimer = undefined; window.removeEventListener("online", this.onOnline); window.removeEventListener("offline", this.onOffline); + document.removeEventListener("visibilitychange", this.onVisibility); + this.clearHiddenTimer(); + this.suspended = false; + // Its remaining frames must not apply on a connection started later. + if (this.socket) this.abandonedSockets.add(this.socket); this.socket?.close(1000, "client stopped"); this.socket = undefined; for (const [requestId, pending] of this.pendingRpc) { @@ -151,9 +170,59 @@ export class JournalConnection { } private readonly onOnline = (): void => { - if (!this.stopped && !this.socket) this.scheduleReconnect(0); + if (!this.stopped && !this.suspended && !this.socket) this.scheduleReconnect(0); }; + private readonly onVisibility = (): void => { + if (this.stopped) return; + if (document.visibilityState === "hidden") { + this.armHiddenTimer(); + return; + } + this.clearHiddenTimer(); + if (!this.suspended) return; + this.suspended = false; + this.retryAttempt = 0; + // A snapshot reload in flight reopens the socket itself once the new cursor is stored. + if (this.replacingSnapshot) return; + // At once, not on a timer: the user is looking at the tab. Offline, the online event retries. + this.open(); + }; + + private armHiddenTimer(): void { + this.clearHiddenTimer(); + this.hiddenTimer = window.setTimeout(() => { + this.hiddenTimer = undefined; + if (this.stopped || this.suspended || document.visibilityState !== "hidden") return; + if (this.callbacks.canSuspend?.()) this.suspendForHidden(); + else this.armHiddenTimer(); + }, HIDDEN_CLOSE_MS); + } + + private clearHiddenTimer(): void { + if (this.hiddenTimer !== undefined) window.clearTimeout(this.hiddenTimer); + this.hiddenTimer = undefined; + } + + // Close the socket and stop retrying until the tab is visible again. + private suspendForHidden(): void { + if (this.stopped || this.suspended) return; + this.suspended = true; + if (this.retryTimer !== undefined) window.clearTimeout(this.retryTimer); + this.retryTimer = undefined; + const socket = this.socket; + this.socket = undefined; + this.welcomed = false; + // Frames this socket already delivered but the queue has not applied must not run now: + // the cursor replays them on the next connection. + if (socket) this.abandonedSockets.add(socket); + for (const [requestId, pending] of this.pendingRpc) { + this.resolveRpc(requestId, pending, { ok: false, origin: "relay", code: "not_connected" }); + } + socket?.close(1000, "tab hidden"); + this.callbacks.onSuspend?.(); + } + private readonly onOffline = (): void => { this.callbacks.onState("offline", "No network connection"); this.socket?.close(); @@ -200,9 +269,12 @@ export class JournalConnection { }; socket.onclose = (event) => { - if (this.socket === socket) this.socket = undefined; + // A socket that was replaced (a suspended one whose close handshake finishes after the tab + // opened its successor) must not touch the current connection's state or retry. + if (this.socket !== socket) return; + this.socket = undefined; this.welcomed = false; - if (this.stopped || this.replacingSnapshot) return; + if (this.stopped || this.suspended || this.replacingSnapshot) return; const reason = event.code === 1000 ? undefined : event.reason || "Connection interrupted"; this.callbacks.onState(navigator.onLine ? "connecting" : "offline", reason); this.scheduleReconnect(); @@ -332,12 +404,19 @@ export class JournalConnection { this.abandonedSockets.add(socket); this.replacingSnapshot = true; socket.close(1000, "replacing snapshot"); + let failure: { error: unknown } | undefined; try { await this.callbacks.onSnapshotRequired(); + } catch (error) { + failure = { error }; } finally { this.replacingSnapshot = false; } - this.scheduleReconnect(0); + // The socket's close event returned early while the snapshot was being replaced, so this is + // the only retry: it must happen on failure too, and also when the tab was shown meanwhile + // (the visibility handler left the reopening to this path). + this.scheduleReconnect(failure ? undefined : 0); + if (failure) throw failure.error; } private async handleJournalBatch(frames: JournalEvent[], socket: WebSocket): Promise { @@ -372,7 +451,10 @@ export class JournalConnection { // Runs already queued on this socket must not apply and move the cursor past the rows that // just failed: those rows would never be replayed. this.abandonedSockets.add(socket); - this.callbacks.onState("offline", error instanceof Error ? error.message : "Sync failed"); + // A socket that is no longer current reports nothing: its successor owns the state. + if (socket === this.socket) { + this.callbacks.onState("offline", error instanceof Error ? error.message : "Sync failed"); + } socket.close(); } @@ -427,7 +509,7 @@ export class JournalConnection { } private scheduleReconnect(delayOverride?: number): void { - if (this.stopped || this.retryTimer !== undefined || !navigator.onLine) return; + if (this.stopped || this.suspended || this.retryTimer !== undefined || !navigator.onLine) return; const baseDelay = delayOverride ?? RETRY_DELAYS_MS[Math.min(this.retryAttempt++, RETRY_DELAYS_MS.length - 1)]; const delay = delayOverride === undefined ? Math.round(baseDelay * (0.8 + Math.random() * 0.4)) : baseDelay; this.retryTimer = window.setTimeout(() => { diff --git a/src/journal/journal.pcss b/src/journal/journal.pcss index be23b84..2705164 100644 --- a/src/journal/journal.pcss +++ b/src/journal/journal.pcss @@ -5533,3 +5533,9 @@ li.mj_EventTile[data-layout="bubble"].mj_EventTile_systemNotice { .mj_EventTile_systemNotice[data-self="false"] .mj_EventTile_line { padding: 0; } + +.mj_LiveTool_stale { + margin-top: 4px; + font-size: 12px; + opacity: 0.7; +} diff --git a/src/journal/notifications.ts b/src/journal/notifications.ts index 2af22ad..0e318e3 100644 --- a/src/journal/notifications.ts +++ b/src/journal/notifications.ts @@ -6,9 +6,8 @@ Please see LICENSE files in the repository root for full details. */ /* - * Desktop notifications and the unread badge, while a tab is open (no service worker, no Web - * Push). The phone and Mac apps are told what to show by the journal's push pipeline; a browser - * tab is not a push target, so this module makes the same decision locally from the journal + * Desktop notifications and the unread badge, while a tab is open. Web Push covers hidden and closed tabs + * through the service worker; this module makes the local decision from the journal * events the tab already receives: * * - which switch an event falls under (the journal's push classification: prompts, questions, @@ -33,6 +32,10 @@ Please see LICENSE files in the repository root for full details. */ import { JournalApi, JournalApiError } from "./api"; +import { notificationTag, parseConvoHash } from "./push-shared"; +import { WebPushRegistrar } from "./web-push"; +import { isTabFocused, isTabVisible, watchTabFocus } from "./viewing"; + import type { LiveListener, MatronJournalClient } from "./client"; import { effectiveUnread } from "./conversation-flags"; import { isJoinedRoom } from "./conversation-rooms"; @@ -46,6 +49,8 @@ import { type Session, } from "./types"; +export { notificationTag } from "./push-shared"; + // ── Settings model (journal src/notify.js) ────────────────────────────────────────────────── export type NotifyMode = "coordinator" | "all" | "custom"; @@ -528,6 +533,12 @@ export interface NotifySettingsState { /** Everything the notifier touches outside itself; tests pass fakes. */ export interface NotifierEnvironment { + webPush?: { + sync(session: Session, wanted: boolean): Promise; + unregister(session: Session): Promise; + /** True once a push subscription is registered for the session. */ + active?(session: Session): boolean; + }; Notification?: NotificationConstructorLike; channel?: () => ChannelLike | undefined; storage?: Storage; @@ -556,6 +567,7 @@ function defaultEnvironment(): NotifierEnvironment { storage = undefined; } return { + webPush: new WebPushRegistrar(), Notification: typeof Notification === "undefined" ? undefined : (Notification as NotificationConstructorLike), channel: () => (typeof BroadcastChannel === "undefined" ? undefined : new BroadcastChannel(CHANNEL)), storage, @@ -569,7 +581,10 @@ function defaultEnvironment(): NotifierEnvironment { } interface PeerView { + /** On screen and holding focus: only one document at a time. */ focused: boolean; + /** On screen, focused or not: the journal counts such a tab as viewing its chat. */ + visible: boolean; convoId: string | null; } @@ -596,6 +611,8 @@ export class DesktopNotifier { private readonly open = new Map(); private coordinatorId: string | null = null; private sessionKey?: string; + private pushSession?: Session; + private hashRead = false; // Moves on every live `notify` frame and session change: a GET sent before is older news. private settingsEpoch = 0; // Moves on every session change: an answer for the previous session is dropped. @@ -730,6 +747,10 @@ export class DesktopNotifier { // ── Lifecycle ── private attach(): void { + this.client.setSuspendGuard(() => { + const s = this.client.getSnapshot().session; + return !!s && !!this.env.webPush?.active?.(s); + }); const doc = this.env.document; this.baseTitle = (doc?.title ?? "Matron").replace(TITLE_COUNT, ""); const live: LiveListener = { @@ -740,23 +761,37 @@ export class DesktopNotifier { this.teardown.push(this.client.subscribe(() => this.onClientChange())); const win = this.env.window; + const worker = win?.navigator?.serviceWorker; + if (worker) { + const onMessage = (event: MessageEvent): void => { + const data = event.data; + if ( + !data || + data.type !== "matron-open-convo" || + typeof data.convoId !== "string" || + !data.convoId || + data.convoId.length > 128 + ) + return; + win?.focus(); + void this.client.selectConversation(data.convoId).catch(() => undefined); + }; + worker.addEventListener("message", onMessage); + this.teardown.push(() => worker.removeEventListener("message", onMessage)); + } if (win) { const onFocusChange = (): void => { - // Only one document has focus: no other tab can have a conversation on screen. - if (this.ownView().focused) this.peers.clear(); + // Only one document has focus: no other tab holds it. + if (this.ownView().focused) this.releasePeerFocus(); this.refresh(); this.announce(); }; - const onHide = (): void => this.post({ type: "view", tab: this.tabId, focused: false, convoId: null }); - win.addEventListener("focus", onFocusChange); - win.addEventListener("blur", onFocusChange); + const onHide = (): void => + this.post({ type: "view", tab: this.tabId, focused: false, visible: false, convoId: null }); + this.teardown.push(watchTabFocus(win, doc, onFocusChange)); win.addEventListener("pagehide", onHide); - doc?.addEventListener("visibilitychange", onFocusChange); this.teardown.push(() => { - win.removeEventListener("focus", onFocusChange); - win.removeEventListener("blur", onFocusChange); win.removeEventListener("pagehide", onHide); - doc?.removeEventListener("visibilitychange", onFocusChange); }); } @@ -775,7 +810,12 @@ export class DesktopNotifier { } private detach(): void { - this.post({ type: "view", tab: this.tabId, focused: false, convoId: null }); + this.client.setSuspendGuard(undefined); + if (this.pushSession) void this.env.webPush?.unregister(this.pushSession); + this.pushSession = undefined; + this.sessionKey = undefined; + this.lastConnection = undefined; + this.post({ type: "view", tab: this.tabId, focused: false, visible: false, convoId: null }); for (const stop of this.teardown.splice(0)) stop(); this.channel?.close(); this.channel = undefined; @@ -807,6 +847,8 @@ export class DesktopNotifier { const session = state.phase === "signed-in" ? state.session : undefined; const key = session ? `${session.serverUrl}|${session.userId}|${session.token}` : undefined; if (key !== this.sessionKey) { + if (this.pushSession) void this.env.webPush?.unregister(this.pushSession); + this.pushSession = session; this.sessionKey = key; this.view = undefined; this.sessionStates.clear(); @@ -818,11 +860,23 @@ export class DesktopNotifier { this.settingsError = null; this.emitSettings(); } + if (session && !this.hashRead) { + this.hashRead = true; + const win = this.env.window; + const convoId = parseConvoHash(win?.location?.hash ?? ""); + if (convoId && win) { + void this.client.selectConversation(convoId).catch(() => undefined); + win.history.replaceState(win.history.state, "", win.location.pathname + win.location.search); + } + } // The `notify` frame is never replayed, so each (re)connect reads the settings again. Read // even with desktop notifications off: Settings and the chat header edit them. if (session && state.connection !== this.lastConnection) { this.lastConnection = state.connection; - if (state.connection === "online") void this.loadSettings(); + if (state.connection === "online") { + this.syncWebPush(); + void this.loadSettings(); + } } } @@ -941,9 +995,30 @@ export class DesktopNotifier { view === undefined ? NEEDS_ME.has(key) : shouldNotify(key, event.type, event.convo_id, view, now); if (!allowed) return; if (this.isOnScreen(event.convo_id)) return; + // With a push subscription registered, the alert is left to the push when one will + // arrive (the journal sends it for an open socket too, and both would sound, since a + // replacing notification re-alerts). It will not arrive while a tab of this browser has + // focus (the worker stays quiet) or shows the conversation (the journal sees it viewed and + // sends none): then this tab, the only one that applied the event, alerts for itself. + const session = this.client.getSnapshot().session; + if (session && this.env.webPush?.active?.(session) && this.pushWillAlert(event.convo_id)) return; this.show(event, previous, cls); } + /** Whether the journal's push for this conversation will show a notification. */ + private pushWillAlert(convoId: string): boolean { + const own = this.ownView(); + if (own.focused || (own.visible && own.convoId === convoId)) return false; + for (const peer of this.peers.values()) { + if (peer.focused || (peer.visible && peer.convoId === convoId)) return false; + } + return true; + } + + private releasePeerFocus(): void { + for (const [tab, peer] of this.peers) this.peers.set(tab, { ...peer, focused: false }); + } + private isOnScreen(convoId: string): boolean { const own = this.ownView(); if (own.focused && own.convoId === convoId) return true; @@ -961,7 +1036,7 @@ export class DesktopNotifier { body: notificationBody(event), // One notification per conversation: a newer one replaces it. What needs the user // alerts again; routine activity updates quietly. - tag: `matron:${conversationId}`, + tag: notificationTag(conversationId), renotify: cls.kind !== "activity", silent: !this.snapshot.sound, data: { convo_id: conversationId, seq: event.seq }, @@ -983,16 +1058,17 @@ export class DesktopNotifier { private ownView(): PeerView { const doc = this.env.document; - const focused = Boolean(doc && doc.visibilityState === "visible" && doc.hasFocus()); + const focused = !!doc && isTabFocused(doc); + const visible = !!doc && isTabVisible(doc); const state = this.client.getSnapshot(); const convoId = state.trackerView?.open ? null : (state.selectedConversationId ?? null); - return { focused, convoId }; + return { focused, visible, convoId }; } private announce(): void { if (!this.channel) return; const view = this.ownView(); - const key = `${view.focused}|${view.convoId ?? ""}`; + const key = `${view.focused}|${view.visible}|${view.convoId ?? ""}`; if (key === this.lastAnnounced) return; this.lastAnnounced = key; this.post({ type: "view", tab: this.tabId, ...view }); @@ -1000,18 +1076,25 @@ export class DesktopNotifier { private onPeerMessage(data: unknown): void { if (!data || typeof data !== "object") return; - const message = data as { type?: unknown; tab?: unknown; focused?: unknown; convoId?: unknown }; + const message = data as { + type?: unknown; + tab?: unknown; + focused?: unknown; + visible?: unknown; + convoId?: unknown; + }; if (message.type === "query") { this.lastAnnounced = ""; this.announce(); return; } if (message.type !== "view" || typeof message.tab !== "string" || message.tab === this.tabId) return; - if (message.focused === true) { - // Only one document has focus: whichever tab had it before no longer does. - this.peers.clear(); + const focused = message.focused === true; + if (focused) this.releasePeerFocus(); + if (focused || message.visible === true) { this.peers.set(message.tab, { - focused: true, + focused, + visible: true, convoId: typeof message.convoId === "string" ? message.convoId : null, }); } else { @@ -1098,11 +1181,26 @@ export class DesktopNotifier { }; } + private syncWebPush(): void { + const state = this.client.getSnapshot(); + if (state.phase !== "signed-in" || !state.session) return; + // Notifications off: only a subscription this page knows of is removed (sync does that), + // so a reconnect never costs a request for someone who never turned push on. + // The preference is shared by every tab through storage, and this tab's snapshot moves only on + // focus changes: read it again so a tab another tab turned push off for never re-subscribes. + const enabled = this.computeSnapshot().enabled; + if (!enabled) void this.env.webPush?.sync(state.session, false); + else if (state.connection === "online") void this.env.webPush?.sync(state.session, true); + } + private refresh(): void { const next = this.computeSnapshot(); const prev = this.snapshot; if (prev.permission === next.permission && prev.enabled === next.enabled && prev.sound === next.sound) return; this.snapshot = next; + const session = this.client.getSnapshot().session; + if (prev.enabled && !next.enabled && session) void this.env.webPush?.unregister(session); + else this.syncWebPush(); if (next.enabled && !prev.enabled && this.client.getSnapshot().connection === "online") void this.loadSettings(); for (const listener of this.listeners) listener(); diff --git a/src/journal/push-shared.ts b/src/journal/push-shared.ts new file mode 100644 index 0000000..56f6a8b --- /dev/null +++ b/src/journal/push-shared.ts @@ -0,0 +1,20 @@ +/* +Copyright 2026 Matron Contributors. + +SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only +Please see LICENSE files in the repository root for full details. +*/ + +export function notificationTag(convoId: string): string { + return `matron:${convoId}`; +} + +export function parseConvoHash(hash: string): string | null { + if (!hash.startsWith("#convo=") || hash.length > 7 + 128 * 12) return null; + try { + const id = decodeURIComponent(hash.slice(7)); + return id.length > 0 && id.length <= 128 ? id : null; + } catch { + return null; + } +} diff --git a/src/journal/push-sw.ts b/src/journal/push-sw.ts new file mode 100644 index 0000000..d0da193 --- /dev/null +++ b/src/journal/push-sw.ts @@ -0,0 +1,230 @@ +/* +Copyright 2026 Matron Contributors. + +SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only +Please see LICENSE files in the repository root for full details. +*/ + +import { notificationTag } from "./push-shared"; +export { notificationTag, parseConvoHash } from "./push-shared"; + +export type PushKind = "attention" | "done" | "activity"; +export interface PushContent { + v: 1; + title: string; + subtitle?: string; + body: string; + convo_id: string; + seq: number; + kind: PushKind; + item?: { id: string; num: number; kind: string; actions: string[]; reply_to?: string }; +} +export interface WindowClientLike { + url: string; + focused: boolean; + visibilityState: string; + focus(): Promise; + postMessage(message: unknown): void; +} +export interface WorkerEventLike { + data?: { json(): unknown } | null; + notification?: { data?: { convo_id?: string; seq?: number } | null; close(): void }; + waitUntil(promise: Promise): void; +} +export interface ServiceWorkerScopeLike { + registration: { + scope: string; + showNotification(title: string, options: NotificationOptions & { renotify?: boolean }): Promise; + }; + clients: { + matchAll(options: { type: "window"; includeUncontrolled?: boolean }): Promise; + openWindow(url: string): Promise; + claim(): Promise; + }; + skipWaiting(): Promise; + addEventListener(type: string, listener: (event: WorkerEventLike) => void): void; +} +function boundedString(value: unknown, cap: number): value is string { + return typeof value === "string" && value.length <= cap; +} + +function validConvoId(value: unknown): value is string { + return boundedString(value, 128) && value.length > 0; +} + +export function parsePushPayload(raw: unknown): PushContent | null { + try { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; + const obj = raw as Record; + if ( + obj.v !== 1 || + !boundedString(obj.title, 256) || + obj.title.length === 0 || + !boundedString(obj.body, 4096) || + !validConvoId(obj.convo_id) || + typeof obj.seq !== "number" || + !Number.isFinite(obj.seq) || + !Number.isInteger(obj.seq) || + !["attention", "done", "activity"].includes(obj.kind as string) + ) + return null; + const content: PushContent = { + v: 1, + title: obj.title, + body: obj.body, + convo_id: obj.convo_id, + seq: obj.seq, + kind: obj.kind as PushKind, + }; + if (obj.subtitle !== undefined) { + if (!boundedString(obj.subtitle, 256)) return null; + content.subtitle = obj.subtitle; + } + if (obj.item !== undefined) { + if (!obj.item || typeof obj.item !== "object" || Array.isArray(obj.item)) return null; + const item = obj.item as Record; + if ( + !boundedString(item.id, 128) || + !boundedString(item.kind, 128) || + typeof item.num !== "number" || + !Number.isSafeInteger(item.num) || + !Array.isArray(item.actions) || + item.actions.length > 32 || + !item.actions.every((action) => boundedString(action, 128)) || + (item.reply_to !== undefined && !boundedString(item.reply_to, 128)) + ) + return null; + content.item = { id: item.id, num: item.num, kind: item.kind, actions: [...item.actions] }; + if (typeof item.reply_to === "string") content.item.reply_to = item.reply_to; + } + return content; + } catch { + return null; + } +} + +export function fallbackContent(kind?: PushKind): { title: string; body: string } { + return { + title: "Matron", + body: + kind === "attention" + ? "Your agent needs you" + : kind === "done" + ? "Your agent finished its turn" + : "New activity from your agent", + }; +} + +export function decidePushDisplay(windows: { visibilityState: string; focused: boolean }[]): "show" | "skip" { + return windows.some((win) => win.visibilityState === "visible" && win.focused) ? "skip" : "show"; +} + +export function buildNotification(content: PushContent | null): { + title: string; + options: NotificationOptions & { renotify?: boolean }; +} { + if (!content) { + const fallback = fallbackContent(); + return { title: fallback.title, options: { body: fallback.body } }; + } + return { + title: content.title, + options: { + body: content.body, + tag: notificationTag(content.convo_id), + renotify: content.kind !== "activity", + data: { convo_id: content.convo_id, seq: content.seq }, + }, + }; +} + +/** Whether a window is one of the app's own pages: same origin, under the worker's scope. */ +function inScope(url: string, scope: URL): boolean { + try { + const parsed = new URL(url); + return parsed.origin === scope.origin && parsed.pathname.startsWith(scope.pathname); + } catch { + return false; + } +} + +export function routeNotificationClick(input: { + convoId: string | null; + windows: { url: string; focused: boolean }[]; + scope: string; +}): + | { action: "focus"; index: number; message?: { type: "matron-open-convo"; convoId: string } } + | { action: "open"; url: string } + | null { + try { + const scope = new URL(input.scope); + // A notification without a usable conversation (the generic wake hint) still opens the app. + const convoId = validConvoId(input.convoId) ? input.convoId : null; + const candidates = input.windows + .map((win, index) => ({ ...win, index })) + .filter((win) => inScope(win.url, scope)); + const target = candidates.find((win) => win.focused) ?? candidates[0]; + if (target) + return convoId + ? { action: "focus", index: target.index, message: { type: "matron-open-convo", convoId } } + : { action: "focus", index: target.index }; + return { action: "open", url: convoId ? input.scope + "#convo=" + encodeURIComponent(convoId) : input.scope }; + } catch { + return null; + } +} + +export function installPushHandlers(scope: ServiceWorkerScopeLike): void { + // Pages of the same origin outside the app (an admin page, say) have no notifier, so only the + // app's own windows can cover a push. + const appWindows = async (): Promise => { + const all = await scope.clients.matchAll({ type: "window", includeUncontrolled: true }); + const appScope = new URL(scope.registration.scope); + return all.filter((win) => inScope(win.url, appScope)); + }; + const show = async (content: PushContent | null): Promise => { + const built = buildNotification(content); + await scope.registration.showNotification(built.title, built.options); + }; + scope.addEventListener("push", (event) => { + event.waitUntil( + (async () => { + try { + const content = parsePushPayload(event.data?.json()); + const windows = await appWindows(); + if (decidePushDisplay(windows) === "show") await show(content); + } catch { + // Even an unreadable payload or failed lookup must produce a visible wake hint. + try { + await show(null); + } catch { + /* The browser may refuse notifications. */ + } + } + })(), + ); + }); + scope.addEventListener("notificationclick", (event) => { + event.notification?.close(); + event.waitUntil( + (async () => { + try { + const windows = await scope.clients.matchAll({ type: "window", includeUncontrolled: true }); + const route = routeNotificationClick({ + convoId: event.notification?.data?.convo_id ?? null, + windows, + scope: scope.registration.scope, + }); + if (route?.action === "focus") { + await windows[route.index].focus(); + if (route.message) windows[route.index].postMessage(route.message); + } else if (route?.action === "open") await scope.clients.openWindow(route.url); + } catch { + /* A closed window or denied navigation needs no further action. */ + } + })(), + ); + }); + scope.addEventListener("install", (event) => event.waitUntil(scope.skipWaiting())); + scope.addEventListener("activate", (event) => event.waitUntil(scope.clients.claim())); +} diff --git a/src/journal/sw.ts b/src/journal/sw.ts new file mode 100644 index 0000000..1cb87dd --- /dev/null +++ b/src/journal/sw.ts @@ -0,0 +1,10 @@ +/* +Copyright 2026 Matron Contributors. + +SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only +Please see LICENSE files in the repository root for full details. +*/ + +import { installPushHandlers, type ServiceWorkerScopeLike } from "./push-sw"; + +installPushHandlers(self as unknown as ServiceWorkerScopeLike); diff --git a/src/journal/types.ts b/src/journal/types.ts index a50cc3f..8bb564a 100644 --- a/src/journal/types.ts +++ b/src/journal/types.ts @@ -615,6 +615,9 @@ export interface ToolStreamState { content: string; offset: number; headTruncated: boolean; + /** The socket feeding it was closed (hidden tab) and no snapshot has come since: the text is + * what was last shown, not live. A snapshot replaces it; the command's final row retires it. */ + stale?: boolean; } export interface PendingMessage { diff --git a/src/journal/viewing.ts b/src/journal/viewing.ts new file mode 100644 index 0000000..51bf4f6 --- /dev/null +++ b/src/journal/viewing.ts @@ -0,0 +1,45 @@ +/* +Copyright 2026 Matron Contributors. + +SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only +Please see LICENSE files in the repository root for full details. +*/ + +type FocusDocument = Pick; + +/** Whether the page is on screen, focused or not (a window beside an editor, a second monitor). */ +export function isTabVisible( + doc: Pick | undefined = typeof document === "undefined" ? undefined : document, +): boolean { + return !!doc && doc.visibilityState === "visible"; +} + +export function isTabFocused( + doc: FocusDocument | undefined = typeof document === "undefined" ? undefined : document, +): boolean { + return !!doc && doc.visibilityState === "visible" && doc.hasFocus(); +} + +/** + * The conversation this page tells the journal it is viewing. The journal also sends a viewed + * conversation's live updates (streaming text, tool output, activity), so this follows what is + * on screen, not what has focus: a visible but unfocused window keeps its live updates, and only + * a hidden page stops viewing. + */ +export function viewingConvoId( + selectedId: string | null | undefined, + doc?: Pick, +): string | null { + return isTabVisible(doc) ? selectedId || null : null; +} + +export function watchTabFocus(win: Window, doc: Document | undefined, onChange: () => void): () => void { + win.addEventListener("focus", onChange); + win.addEventListener("blur", onChange); + doc?.addEventListener("visibilitychange", onChange); + return () => { + win.removeEventListener("focus", onChange); + win.removeEventListener("blur", onChange); + doc?.removeEventListener("visibilitychange", onChange); + }; +} diff --git a/src/journal/web-push.ts b/src/journal/web-push.ts new file mode 100644 index 0000000..011441d --- /dev/null +++ b/src/journal/web-push.ts @@ -0,0 +1,223 @@ +/* +Copyright 2026 Matron Contributors. + +SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only +Please see LICENSE files in the repository root for full details. +*/ + +import { JournalApi, JournalApiError } from "./api"; +import type { Session } from "./types"; + +export interface WebPushSubscriptionLike { + endpoint: string; + options: { applicationServerKey: ArrayBuffer | null }; + toJSON(): { endpoint?: string; keys?: Record }; + unsubscribe(): Promise; +} +/** The part of a service worker the registrar watches while a first install finishes. */ +export interface WorkerLike { + state: string; + addEventListener(type: "statechange", listener: () => void): void; + removeEventListener(type: "statechange", listener: () => void): void; +} +export interface WebPushEnvironment { + serviceWorker?: { + /** The page's existing registration, if any: it may hold a subscription an earlier page made. */ + getRegistration?(): Promise< + { pushManager: { getSubscription(): Promise } } | undefined + >; + register( + url: string, + options: { scope: string }, + ): Promise<{ + /** Set once a worker controls the registration; on a first visit it is still installing. */ + active?: unknown; + installing?: WorkerLike | null; + waiting?: WorkerLike | null; + pushManager: { + getSubscription(): Promise; + subscribe(options: { + userVisibleOnly: boolean; + applicationServerKey: Uint8Array; + }): Promise; + }; + }>; + }; + PushManager?: unknown; + Notification?: { permission: NotificationPermission }; + api(session: Session): { + webPushVapidKey(): Promise; + registerWebPush(body: Record): Promise; + }; + scope: string; +} +/** + * The worker's scope for a build's public path, or null when the assets are served from another + * origin: a worker script and its scope must be on the page's own origin, so push is then off. + */ +export function pushScope(publicPath: string): string | null { + if (/^[a-z][a-z0-9+.-]*:|^\/\//i.test(publicPath)) return null; + return ("/" + publicPath.replace(/^\/+/, "")).replace(/\/*$/, "/"); +} + +function defaultEnvironment(): WebPushEnvironment { + const scope = pushScope(process.env.PUBLIC_PATH || "/"); + return { + serviceWorker: + typeof navigator === "undefined" || !navigator.serviceWorker || scope === null + ? undefined + : { + getRegistration: () => navigator.serviceWorker.getRegistration(scope), + // Resolve against the app scope even when the page is on a nested route. + register: (url, options) => + navigator.serviceWorker.register( + new URL(url, new URL(options.scope, location.href)).href, + options, + ), + }, + PushManager: typeof PushManager === "undefined" ? undefined : PushManager, + Notification: typeof Notification === "undefined" ? undefined : Notification, + api: (session) => new JournalApi(session.serverUrl, session.token), + scope: scope ?? "/", + }; +} + +/** + * Resolves once the registration has an active worker. On a first visit `register()` returns while + * the worker is still installing, and `subscribe()` then fails with an InvalidStateError. + */ +async function untilActive(registration: { + active?: unknown; + installing?: WorkerLike | null; + waiting?: WorkerLike | null; +}) { + if (registration.active) return; + const worker = registration.installing ?? registration.waiting; + if (!worker) return; + await new Promise((resolve, reject) => { + const check = (): void => { + if (worker.state !== "activated" && worker.state !== "redundant") return; + worker.removeEventListener("statechange", check); + if (worker.state === "activated") resolve(); + else reject(new Error("Service worker did not install")); + }; + worker.addEventListener("statechange", check); + check(); + }); +} + +function sessionKey(session: Session): string { + return JSON.stringify([session.serverUrl, session.token]); +} + +export class WebPushRegistrar { + public lastError: string | null = null; + private readonly env: WebPushEnvironment; + private readonly off = new Set(); + private readonly posted = new Map(); + private subscription: WebPushSubscriptionLike | null = null; + private pending: Promise = Promise.resolve(); + + public constructor(env: WebPushEnvironment = defaultEnvironment()) { + this.env = env; + } + + // Serialize browser subscription changes with sign-out and preference changes. + private enqueue(work: () => Promise): Promise { + this.pending = this.pending.then(async () => { + try { + this.lastError = null; + await work(); + } catch (error) { + this.lastError = error instanceof Error ? error.message : "Web Push unavailable"; + } + }); + return this.pending; + } + + /** Whether this page has registered a subscription for the session (the journal covers it). */ + public active(session: Session): boolean { + // The registered endpoint must be the browser's live subscription: after the old one is + // dropped for a new key and the replacement fails, the journal still holds an endpoint the + // browser no longer delivers to. + const endpoint = this.posted.get(sessionKey(session)); + return endpoint !== undefined && endpoint === this.subscription?.endpoint; + } + + /** The browser's own subscription, which outlives a page: an earlier page may have made it. */ + private async existing(): Promise { + if (this.subscription) return this.subscription; + try { + const registration = await this.env.serviceWorker?.getRegistration?.(); + return (await registration?.pushManager.getSubscription()) ?? null; + } catch { + return null; + } + } + + public sync(session: Session, wanted: boolean): Promise { + return this.enqueue(async () => { + const key = sessionKey(session); + const env = this.env; + if (!wanted || !env.serviceWorker || !env.PushManager || env.Notification?.permission !== "granted") { + if (this.posted.has(key) || (await this.existing())) await this.remove(session); + return; + } + if (this.off.has(key)) return; + let raw: unknown; + try { + raw = await env.api(session).webPushVapidKey(); + } catch (error) { + if (error instanceof JournalApiError && error.status === 404) { + this.off.add(key); + return; + } + throw error; + } + const publicKey = (raw as { public_key?: unknown } | null)?.public_key; + if (typeof publicKey !== "string" || !/^[A-Za-z0-9_-]+$/.test(publicKey)) + throw new Error("Invalid Web Push key"); + const encoded = publicKey.replace(/-/g, "+").replace(/_/g, "/"); + const bytes = Uint8Array.from(atob(encoded.padEnd(Math.ceil(encoded.length / 4) * 4, "=")), (c) => + c.charCodeAt(0), + ); + if (bytes.length !== 65 || bytes[0] !== 4) throw new Error("Invalid Web Push key"); + const workerUrl = env.scope === "/" ? "sw.js" : env.scope.replace(/\/*$/, "/") + "sw.js"; + const registration = await env.serviceWorker.register(workerUrl, { scope: env.scope }); + await untilActive(registration); + let subscription = await registration.pushManager.getSubscription(); + if (subscription) { + const old = subscription.options.applicationServerKey; + if (!old || old.byteLength !== bytes.length || !new Uint8Array(old).every((b, i) => b === bytes[i])) { + await subscription.unsubscribe(); + subscription = null; + this.subscription = null; + } + } + subscription ??= await registration.pushManager.subscribe({ + userVisibleOnly: true, + applicationServerKey: bytes, + }); + this.subscription = subscription; + if (this.posted.get(key) === subscription.endpoint) return; + const body = subscription.toJSON(); + await env.api(session).registerWebPush({ endpoint: body.endpoint, keys: body.keys }); + this.posted.set(key, subscription.endpoint); + }); + } + + private async remove(session: Session): Promise { + const subscription = await this.existing(); + this.subscription = null; + this.posted.delete(sessionKey(session)); + try { + await this.env.api(session).registerWebPush({ endpoint: null }); + } finally { + if (subscription) await subscription.unsubscribe(); + } + } + + public unregister(session: Session): Promise { + return this.enqueue(() => this.remove(session)); + } +} diff --git a/test/fixtures/webpush-payload.json b/test/fixtures/webpush-payload.json new file mode 100644 index 0000000..d5aa577 --- /dev/null +++ b/test/fixtures/webpush-payload.json @@ -0,0 +1,8 @@ +{ + "v": 1, + "title": "convo one", + "body": "permission: needs you", + "convo_id": "c1", + "seq": 1, + "kind": "attention" +} diff --git a/test/unit-tests/journal/briefing-client-test.ts b/test/unit-tests/journal/briefing-client-test.ts index 417ec8e..cf51248 100644 --- a/test/unit-tests/journal/briefing-client-test.ts +++ b/test/unit-tests/journal/briefing-client-test.ts @@ -250,6 +250,7 @@ describe("MatronJournalClient briefing live frame", () => { internals.api!.latestBriefing.mockResolvedValue(latest()); internals.database = { outbox: jest.fn().mockResolvedValue([]), + conversations: jest.fn().mockResolvedValue([]), deleteOutboxRows: jest.fn(), cursor: jest.fn().mockResolvedValue(undefined), }; diff --git a/test/unit-tests/journal/client-test.ts b/test/unit-tests/journal/client-test.ts index e61eaa2..8f98b98 100644 --- a/test/unit-tests/journal/client-test.ts +++ b/test/unit-tests/journal/client-test.ts @@ -1125,6 +1125,18 @@ describe("MatronJournalClient state handling", () => { expect(newSend).not.toHaveBeenCalled(); }); + it("reloads the conversation list and the open chat from the store when a connection resumes", async () => { + const client = new MatronJournalClient(); + const state = internals(client); + const database = fakeDatabase(); + state.state = signedInState(client); + state.database = database; + state.connection = { send: jest.fn().mockReturnValue(true) }; + await state.handleReady(); + expect(database.conversations).toHaveBeenCalled(); + expect(database.events).toHaveBeenCalledWith("c1"); + }); + it("does not acknowledge a cursor after the replay connection changes", async () => { const client = new MatronJournalClient(); const state = internals(client); @@ -1148,6 +1160,7 @@ describe("MatronJournalClient state handling", () => { resolveCursor(10); await ready; + // The replay lost its connection while it reloaded the views: nothing more goes out on either one. expect(oldSend).not.toHaveBeenCalled(); expect(newSend).not.toHaveBeenCalled(); }); @@ -5216,3 +5229,103 @@ describe("MatronJournalClient session guards", () => { expect(database.conversations).not.toHaveBeenCalled(); }); }); + +describe("focused conversation reporting", () => { + afterEach(() => jest.restoreAllMocks()); + + it("reports no chat while the tracker covers it, and the chat again when it closes", async () => { + localStorage.clear(); + jest.spyOn(document, "visibilityState", "get").mockReturnValue("visible"); + jest.spyOn(JournalDatabase, "open").mockResolvedValue(fakeDatabase() as unknown as JournalDatabase); + jest.spyOn(JournalConnection.prototype, "start").mockImplementation(() => undefined); + jest.spyOn(JournalApi.prototype, "messages").mockResolvedValue({ events: [] }); + const send = jest.fn().mockReturnValue(true); + const client = new MatronJournalClient(); + const state = internals(client); + try { + await state.startSession(SESSION); + state.connection!.send = send; + await client.selectConversation("c1"); + expect(send).toHaveBeenLastCalledWith({ op: "viewing", convo_id: "c1" }); + client.openTrackerView({ view: "inbox" }); + expect(send).toHaveBeenLastCalledWith({ op: "viewing", convo_id: null }); + send.mockClear(); + // A blur or focus while the tracker is open changes nothing. + window.dispatchEvent(new Event("blur")); + window.dispatchEvent(new Event("focus")); + expect(send).not.toHaveBeenCalled(); + client.closeTrackerView(); + expect(send).toHaveBeenLastCalledWith({ op: "viewing", convo_id: "c1" }); + client.openTrackerView({ view: "inbox" }); + await client.selectConversation("c1"); + expect(send).toHaveBeenLastCalledWith({ op: "viewing", convo_id: "c1" }); + } finally { + await client.logout(); + } + }); + + it("follows visibility, not focus, retries failed sends, replays after reconnect and disposes on logout", async () => { + localStorage.clear(); + const focused = jest.spyOn(document, "hasFocus").mockReturnValue(true); + const visibility = jest.spyOn(document, "visibilityState", "get").mockReturnValue("visible"); + jest.spyOn(JournalDatabase, "open").mockResolvedValue(fakeDatabase() as unknown as JournalDatabase); + jest.spyOn(JournalConnection.prototype, "start").mockImplementation(() => undefined); + jest.spyOn(JournalApi.prototype, "messages").mockResolvedValue({ events: [] }); + const send = jest.fn().mockReturnValue(true); + const client = new MatronJournalClient(); + const state = internals(client); + try { + await state.startSession(SESSION); + state.connection!.send = send; + await client.selectConversation("c1"); + expect(send).toHaveBeenLastCalledWith({ op: "viewing", convo_id: "c1" }); + send.mockClear(); + window.dispatchEvent(new Event("focus")); + expect(send).not.toHaveBeenCalled(); + // Blur with the tab still visible (the address bar, another app beside it): still viewing. + focused.mockReturnValue(false); + window.dispatchEvent(new Event("blur")); + expect(send).not.toHaveBeenCalled(); + // Hidden: a failed send is retried by the next change. + visibility.mockReturnValue("hidden"); + send.mockReturnValueOnce(false); + document.dispatchEvent(new Event("visibilitychange")); + document.dispatchEvent(new Event("visibilitychange")); + expect(send.mock.calls).toEqual([[{ op: "viewing", convo_id: null }], [{ op: "viewing", convo_id: null }]]); + send.mockClear(); + await state.handleReady(); + expect(send).toHaveBeenCalledWith({ op: "viewing", convo_id: null }); + send.mockClear(); + // Shown again, still unfocused: viewing resumes without focus. + visibility.mockReturnValue("visible"); + document.dispatchEvent(new Event("visibilitychange")); + expect(send).toHaveBeenLastCalledWith({ op: "viewing", convo_id: "c1" }); + focused.mockReturnValue(true); + window.dispatchEvent(new Event("focus")); + expect(send).toHaveBeenCalledTimes(1); + visibility.mockReturnValue("hidden"); + document.dispatchEvent(new Event("visibilitychange")); + expect(send).toHaveBeenLastCalledWith({ op: "viewing", convo_id: null }); + visibility.mockReturnValue("visible"); + document.dispatchEvent(new Event("visibilitychange")); + expect(send).toHaveBeenLastCalledWith({ op: "viewing", convo_id: "c1" }); + client.clearSelection(); + expect(send).toHaveBeenLastCalledWith({ op: "viewing", convo_id: null }); + await state.startSession(SESSION); + const nextSend = jest.fn().mockReturnValue(true); + state.connection!.send = nextSend; + await client.selectConversation("c1"); + expect(nextSend).toHaveBeenCalledWith({ op: "viewing", convo_id: "c1" }); + nextSend.mockClear(); + visibility.mockReturnValue("hidden"); + document.dispatchEvent(new Event("visibilitychange")); + expect(nextSend.mock.calls).toEqual([[{ op: "viewing", convo_id: null }]]); + } finally { + await client.logout(); + } + send.mockClear(); + window.dispatchEvent(new Event("blur")); + document.dispatchEvent(new Event("visibilitychange")); + expect(send).not.toHaveBeenCalled(); + }); +}); diff --git a/test/unit-tests/journal/hidden-tab-lifecycle-test.ts b/test/unit-tests/journal/hidden-tab-lifecycle-test.ts new file mode 100644 index 0000000..1a34b5d --- /dev/null +++ b/test/unit-tests/journal/hidden-tab-lifecycle-test.ts @@ -0,0 +1,693 @@ +/* +Copyright 2026 Matron Contributors. + +SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only +Please see LICENSE files in the repository root for full details. +*/ + +// Connection lifecycle for a hidden tab with an active push subscription: the socket is closed +// 60 s after the tab hides, a tab that comes back first keeps it, and a tab that comes back +// after reconnects from the stored cursor and replaces what its live tool output showed. +// All timing runs on fake timers; nothing waits in real time. +// +// The catch-up test replays the rows of the shared recovery fixture 19a (events while +// away) when the pinned conformance package is available (MATRON_CONFORMANCE_TARBALL or +// MATRON_CONFORMANCE_DIR, as for the other conformance tests), and is skipped without it. + +import "fake-indexeddb/auto"; +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import React, { act } from "react"; +import { createRoot } from "react-dom/client"; +import { IDBFactory } from "fake-indexeddb"; + +import { MatronJournalClient } from "../../../src/journal/client"; +import { ToolStream } from "../../../src/journal/components"; +import { JournalConnection } from "../../../src/journal/connection"; +import { JournalDatabase } from "../../../src/journal/database"; +import type { JournalEphemeralFrame, JournalEvent, ToolStreamState } from "../../../src/journal/types"; + +jest.mock("../../../res/matron-logo-simple.svg", () => "matron-logo.svg"); + +const HIDDEN_CLOSE_MS = 60_000; + +class FakeSocket { + public static readonly CONNECTING = 0; + public static readonly OPEN = 1; + public static readonly CLOSING = 2; + public static readonly CLOSED = 3; + public static instances: FakeSocket[] = []; + + public readyState = 0; + public sent: Array> = []; + public closedWith?: { code?: number; reason?: string }; + /** When set, close() starts the handshake only; finishClose() completes it later. */ + public deferClose = false; + public onopen: (() => void) | null = null; + public onmessage: ((message: { data: string }) => void) | null = null; + public onerror: (() => void) | null = null; + public onclose: ((event: { code: number; reason: string }) => void) | null = null; + + public constructor(public readonly url: string) { + FakeSocket.instances.push(this); + } + + public send(data: string): void { + this.sent.push(JSON.parse(data) as Record); + } + + public close(code?: number, reason?: string): void { + if (this.readyState === FakeSocket.CLOSED) return; + this.closedWith = { code, reason }; + if (this.deferClose) { + this.readyState = FakeSocket.CLOSING; + return; + } + this.finishClose(); + } + + /** The close handshake completes: the socket is closed and its close event fires. */ + public finishClose(): void { + this.readyState = FakeSocket.CLOSED; + this.onclose?.({ code: this.closedWith?.code ?? 1005, reason: this.closedWith?.reason ?? "" }); + } + + public open(): void { + this.readyState = FakeSocket.OPEN; + this.onopen?.(); + } + + public receive(frame: unknown): void { + this.onmessage?.({ data: JSON.stringify(frame) }); + } + + public get hello(): Record | undefined { + return this.sent.find((frame) => frame.op === "hello"); + } +} + +let visibility: "visible" | "hidden" = "visible"; +function setVisibility(next: "visible" | "hidden"): void { + visibility = next; + document.dispatchEvent(new Event("visibilitychange")); +} + +const settle = async (): Promise => { + // Runs due timers (storage schedules its work on them) and the microtasks they release; no time passes. + for (let i = 0; i < 6; i++) await jest.advanceTimersByTimeAsync(0); +}; + +beforeAll(() => { + Object.defineProperty(document, "visibilityState", { configurable: true, get: () => visibility }); + Object.defineProperty(document, "hidden", { configurable: true, get: () => visibility === "hidden" }); +}); + +let realWebSocket: typeof WebSocket; +beforeEach(() => { + realWebSocket = globalThis.WebSocket; + FakeSocket.instances = []; + (globalThis as { WebSocket: unknown }).WebSocket = FakeSocket; + visibility = "visible"; + jest.useFakeTimers(); +}); + +const started: JournalConnection[] = []; +afterEach(() => { + // A failed assertion must not leave a connection listening to the next test's visibility changes. + for (const connection of started.splice(0)) connection.stop(); + jest.useRealTimers(); + (globalThis as { WebSocket: unknown }).WebSocket = realWebSocket; +}); + +function callbacks(cursor = 0) { + return { + canSuspend: jest.fn(() => true), + cursor: jest.fn().mockImplementation(async () => cursor), + onFrame: jest.fn().mockResolvedValue(undefined), + onReady: jest.fn().mockResolvedValue(undefined), + onSnapshotRequired: jest.fn().mockResolvedValue(undefined), + onRevoked: jest.fn(), + onState: jest.fn(), + onSuspend: jest.fn(), + }; +} + +const HELLO_OK = { + kind: "control", + op: "hello_ok", + seq: 0, + device_id: 1, + name: "web", + settings: { notices: true, auto_archive_days: 30 }, + pins: [], +}; + +/** A connection started and welcomed on its first socket. */ +async function online( + cb: Omit, "canSuspend"> & { canSuspend?: () => boolean } = callbacks(), +) { + const connection = new JournalConnection("https://journal.example", "token", cb); + started.push(connection); + connection.start(); + const socket = FakeSocket.instances[0]; + socket.open(); + await settle(); + socket.receive(HELLO_OK); + await settle(); + return { connection, cb, socket }; +} + +describe("hidden tab closes its socket", () => { + it.each(["false", "absent"])("keeps the hidden socket open when canSuspend is %s", async (guard) => { + const { canSuspend: _canSuspend, ...cb } = callbacks(); + const { socket } = await online({ ...cb, ...(guard === "false" ? { canSuspend: () => false } : {}) }); + cb.onState.mockClear(); + setVisibility("hidden"); + jest.advanceTimersByTime(HIDDEN_CLOSE_MS); + expect(socket.readyState).toBe(FakeSocket.OPEN); + expect(socket.closedWith).toBeUndefined(); + expect(cb.onSuspend).not.toHaveBeenCalled(); + expect(cb.onState).not.toHaveBeenCalled(); + setVisibility("visible"); + jest.advanceTimersByTime(HIDDEN_CLOSE_MS); + expect(socket.readyState).toBe(FakeSocket.OPEN); + expect(cb.onSuspend).not.toHaveBeenCalled(); + expect(cb.onState).not.toHaveBeenCalled(); + }); + + it("closes at 120 s when the suspension guard becomes true after the first tick", async () => { + const cb = callbacks(); + cb.canSuspend.mockReturnValue(false); + const { socket } = await online(cb); + cb.onState.mockClear(); + setVisibility("hidden"); + jest.advanceTimersByTime(HIDDEN_CLOSE_MS); + expect(socket.readyState).toBe(FakeSocket.OPEN); + expect(cb.onSuspend).not.toHaveBeenCalled(); + cb.canSuspend.mockReturnValue(true); + jest.advanceTimersByTime(HIDDEN_CLOSE_MS - 1); + expect(socket.readyState).toBe(FakeSocket.OPEN); + jest.advanceTimersByTime(1); + expect(socket.closedWith).toEqual({ code: 1000, reason: "tab hidden" }); + expect(cb.canSuspend).toHaveBeenCalledTimes(2); + expect(cb.onSuspend).toHaveBeenCalledTimes(1); + expect(cb.onState).not.toHaveBeenCalled(); + }); + + it("keeps the socket after 59 s hidden", async () => { + const { connection, socket } = await online(); + setVisibility("hidden"); + jest.advanceTimersByTime(HIDDEN_CLOSE_MS - 1_000); + expect(socket.readyState).toBe(FakeSocket.OPEN); + expect(socket.closedWith).toBeUndefined(); + connection.stop(); + }); + + it("closes the socket at 60 s hidden, cleanly, and does not retry while hidden", async () => { + const { connection, cb, socket } = await online(); + setVisibility("hidden"); + jest.advanceTimersByTime(HIDDEN_CLOSE_MS); + expect(socket.readyState).toBe(FakeSocket.CLOSED); + expect(socket.closedWith?.code).toBe(1000); + expect(cb.onSuspend).toHaveBeenCalledTimes(1); + // No backoff reconnect for as long as the tab stays hidden. + jest.advanceTimersByTime(10 * 60_000); + await settle(); + expect(FakeSocket.instances).toHaveLength(1); + connection.stop(); + }); + + it("a tab visible again at 59 s cancels the close", async () => { + const { connection, cb, socket } = await online(); + setVisibility("hidden"); + jest.advanceTimersByTime(HIDDEN_CLOSE_MS - 1_000); + setVisibility("visible"); + jest.advanceTimersByTime(HIDDEN_CLOSE_MS * 2); + expect(socket.readyState).toBe(FakeSocket.OPEN); + expect(FakeSocket.instances).toHaveLength(1); + expect(cb.onSuspend).not.toHaveBeenCalled(); + connection.stop(); + }); + + it("hiding again restarts the 60 s count from the new hide", async () => { + const { connection, socket } = await online(); + setVisibility("hidden"); + jest.advanceTimersByTime(40_000); + setVisibility("visible"); + setVisibility("hidden"); + jest.advanceTimersByTime(40_000); + expect(socket.readyState).toBe(FakeSocket.OPEN); + jest.advanceTimersByTime(20_000); + expect(socket.readyState).toBe(FakeSocket.CLOSED); + connection.stop(); + }); + + it("reconnects on visible from the stored cursor", async () => { + const cb = callbacks(7); + const { connection, socket } = await online(cb); + cb.onState.mockClear(); + setVisibility("hidden"); + jest.advanceTimersByTime(HIDDEN_CLOSE_MS); + expect(socket.readyState).toBe(FakeSocket.CLOSED); + expect(cb.onState).not.toHaveBeenCalled(); + cb.cursor.mockImplementation(async () => 9); + setVisibility("visible"); + expect(FakeSocket.instances).toHaveLength(2); + expect(cb.onState.mock.calls).toEqual([["connecting"]]); + const next = FakeSocket.instances[1]; + next.open(); + await settle(); + expect(next.hello).toMatchObject({ op: "hello", token: "token", cursor: 9 }); + next.receive(HELLO_OK); + await settle(); + expect(cb.onState.mock.calls).toEqual([["connecting"], ["online"]]); + connection.stop(); + }); + + it("an online event while the tab is hidden and closed does not reopen the socket", async () => { + const { connection } = await online(); + setVisibility("hidden"); + jest.advanceTimersByTime(HIDDEN_CLOSE_MS); + window.dispatchEvent(new Event("online")); + jest.advanceTimersByTime(60_000); + expect(FakeSocket.instances).toHaveLength(1); + connection.stop(); + }); + + it("a connection waiting in backoff when the tab is hidden stops retrying", async () => { + const { connection, socket } = await online(); + socket.close(1006, "network"); // drops: a retry is scheduled + setVisibility("hidden"); + jest.advanceTimersByTime(HIDDEN_CLOSE_MS + 60_000); + const attempts = FakeSocket.instances.length; + // Whatever the retry opened before the close is closed, and nothing more is tried. + expect(FakeSocket.instances[attempts - 1].readyState).toBe(FakeSocket.CLOSED); + jest.advanceTimersByTime(10 * 60_000); + expect(FakeSocket.instances).toHaveLength(attempts); + setVisibility("visible"); + expect(FakeSocket.instances).toHaveLength(attempts + 1); + connection.stop(); + }); + + it("a tab that starts hidden closes the socket 60 s in", async () => { + visibility = "hidden"; + const connection = new JournalConnection("https://journal.example", "token", callbacks()); + started.push(connection); + connection.start(); + const socket = FakeSocket.instances[0]; + socket.open(); + await settle(); + jest.advanceTimersByTime(HIDDEN_CLOSE_MS); + expect(socket.readyState).toBe(FakeSocket.CLOSED); + connection.stop(); + }); + + it("settles a pending request as not connected when the socket closes", async () => { + const { connection } = await online(); + const reply = connection.agentRequest(7, "go", {}, 10 * 60_000); + setVisibility("hidden"); + jest.advanceTimersByTime(HIDDEN_CLOSE_MS); + await expect(reply).resolves.toEqual({ ok: false, origin: "relay", code: "not_connected" }); + }); + + describe("a close event from a replaced socket", () => { + async function suspendedWithSlowClose() { + const cb = callbacks(); + const { connection, socket: old } = await online(cb); + old.deferClose = true; + setVisibility("hidden"); + jest.advanceTimersByTime(HIDDEN_CLOSE_MS); + expect(old.readyState).toBe(FakeSocket.CLOSING); + setVisibility("visible"); + expect(FakeSocket.instances).toHaveLength(2); + return { connection, cb, old, next: FakeSocket.instances[1] }; + } + + it("leaves a welcomed successor usable when it arrives late", async () => { + const { connection, cb, old, next } = await suspendedWithSlowClose(); + next.open(); + await settle(); + next.receive(HELLO_OK); + await settle(); + cb.onState.mockClear(); + old.finishClose(); + await settle(); + jest.advanceTimersByTime(60_000); + await settle(); + expect(cb.onState).not.toHaveBeenCalled(); + expect(FakeSocket.instances).toHaveLength(2); + expect(connection.send({ op: "viewing", convo_id: "c1" })).toBe(true); + expect(next.sent.at(-1)).toMatchObject({ op: "viewing" }); + connection.stop(); + }); + + it("leaves a successor that is still connecting unharmed when it arrives early", async () => { + const { connection, cb, old, next } = await suspendedWithSlowClose(); + cb.onState.mockClear(); + old.finishClose(); + await settle(); + jest.advanceTimersByTime(60_000); + await settle(); + expect(cb.onState).not.toHaveBeenCalled(); + expect(FakeSocket.instances).toHaveLength(2); + next.open(); + await settle(); + next.receive(HELLO_OK); + await settle(); + expect(cb.onState.mock.calls).toEqual([["online"]]); + expect(connection.send({ op: "viewing", convo_id: "c1" })).toBe(true); + connection.stop(); + }); + + it("still reconnects when the current socket closes", async () => { + const { connection, old, next } = await suspendedWithSlowClose(); + next.open(); + await settle(); + next.receive(HELLO_OK); + await settle(); + old.finishClose(); + next.close(1006, "lost"); + await settle(); + jest.advanceTimersByTime(60_000); + await settle(); + expect(FakeSocket.instances.length).toBeGreaterThan(2); + connection.stop(); + }); + + it("does not let a stopped connection's late frames welcome a restarted one", async () => { + const cb = callbacks(); + const { connection, socket: first } = await online(cb); + first.deferClose = true; + connection.stop(); + connection.start(); + expect(FakeSocket.instances).toHaveLength(2); + cb.onReady.mockClear(); + first.receive(HELLO_OK); + await settle(); + expect(cb.onReady).not.toHaveBeenCalled(); + expect(connection.send({ op: "viewing", convo_id: "c1" })).toBe(false); + connection.stop(); + }); + }); + + describe("a snapshot replacement that fails", () => { + const SNAPSHOT_REQUIRED = { kind: "control", op: "snapshot_required", seq: 0 }; + + it("retries the connection", async () => { + const cb = callbacks(); + cb.onSnapshotRequired.mockRejectedValueOnce(new Error("snapshot failed")); + const { connection, socket } = await online(cb); + socket.receive(SNAPSHOT_REQUIRED); + await settle(); + jest.advanceTimersByTime(60_000); + await settle(); + expect(FakeSocket.instances.length).toBeGreaterThan(1); + connection.stop(); + }); + + it("retries when the tab was hidden and shown while the replacement was pending", async () => { + const cb = callbacks(); + let fail!: (error: Error) => void; + cb.onSnapshotRequired.mockImplementationOnce( + () => + new Promise((_resolve, reject) => { + fail = reject; + }), + ); + const { connection, socket } = await online(cb); + socket.receive(SNAPSHOT_REQUIRED); + await settle(); + setVisibility("hidden"); + jest.advanceTimersByTime(HIDDEN_CLOSE_MS); + setVisibility("visible"); + // The reopening is left to the replacement, which has not finished. + expect(FakeSocket.instances).toHaveLength(1); + fail(new Error("snapshot failed")); + await settle(); + jest.advanceTimersByTime(60_000); + await settle(); + expect(FakeSocket.instances.length).toBeGreaterThan(1); + connection.stop(); + }); + }); + + it("stop() removes the visibility handling", async () => { + const { connection, cb } = await online(); + connection.stop(); + FakeSocket.instances[0].readyState = FakeSocket.OPEN; + setVisibility("hidden"); + jest.advanceTimersByTime(HIDDEN_CLOSE_MS * 2); + expect(cb.onSuspend).not.toHaveBeenCalled(); + expect(FakeSocket.instances).toHaveLength(1); + }); +}); + +// ── Live tool output across a hidden tab ── + +interface ClientInternals { + toolStreams: Map>; + handleEphemeral(frame: JournalEphemeralFrame): void; + suspendLiveStreams?(): void; + handleJournal(event: JournalEvent): Promise; +} + +function toolFrame(payload: JournalEphemeralFrame["tool_stream"]): JournalEphemeralFrame { + return { kind: "ephemeral", convo_id: "c1", message_ref: "tu1", tool_stream: payload }; +} + +describe("tool output across a hidden tab", () => { + function liveClient() { + const client = new MatronJournalClient(); + const internals = client as unknown as ClientInternals; + internals.handleEphemeral( + toolFrame({ event: "append", offset: 0, chunk: "a\nb\n", meta: { tool: "Bash", command: "make" } }), + ); + internals.handleEphemeral(toolFrame({ event: "append", offset: 4, chunk: "c\n" })); + return { client, internals }; + } + + it("suspending marks what was shown as no longer live, keeping the text", () => { + const { internals } = liveClient(); + expect(internals.toolStreams.get("c1")?.tu1.content).toBe("a\nb\nc\n"); + internals.suspendLiveStreams?.(); + expect(internals.toolStreams.get("c1")?.tu1).toMatchObject({ content: "a\nb\nc\n", stale: true }); + }); + + it("a snapshot after the hidden period replaces the shown output and is live again", () => { + const { internals } = liveClient(); + internals.suspendLiveStreams?.(); + // The journal's snapshot holds more than the tab showed; none of the old text is kept twice. + internals.handleEphemeral( + toolFrame({ + event: "sync", + offset: 0, + content: "a\nb\nc\nd\ne\n", + head_truncated: false, + meta: { tool: "Bash", command: "make" }, + }), + ); + const stream = internals.toolStreams.get("c1")?.tu1; + expect(stream?.content).toBe("a\nb\nc\nd\ne\n"); + expect(stream?.stale).toBeFalsy(); + expect(stream?.offset).toBe(10); + }); + + it("a snapshot that starts after byte 0 is marked trimmed", () => { + const { internals } = liveClient(); + internals.suspendLiveStreams?.(); + internals.handleEphemeral( + toolFrame({ + event: "sync", + offset: 2048, + content: "tail\n", + head_truncated: true, + meta: { tool: "Bash", command: "make" }, + }), + ); + expect(internals.toolStreams.get("c1")?.tu1).toMatchObject({ content: "tail\n", headTruncated: true }); + }); + + it("an offset-less chunk is not appended to a card that is no longer live", () => { + const { internals } = liveClient(); + internals.suspendLiveStreams?.(); + internals.handleEphemeral(toolFrame({ event: "append", chunk: "late\n" })); + expect(internals.toolStreams.get("c1")?.tu1.content).toBe("a\nb\nc\n"); + }); + + it("a stream the journal no longer has stays marked until its final row retires it", async () => { + const { internals } = liveClient(); + internals.suspendLiveStreams?.(); + // Reconnected, but no snapshot comes for tu1: it stays shown as no longer live. + expect(internals.toolStreams.get("c1")?.tu1.stale).toBe(true); + internals.handleEphemeral(toolFrame({ event: "end" })); + expect(internals.toolStreams.get("c1")?.tu1).toBeUndefined(); + }); + + it("suspending drops the activity indicator the closed socket can no longer end", () => { + const client = new MatronJournalClient(); + const internals = client as unknown as ClientInternals & { + activities: Map; + state: { selectedConversationId?: string; activity?: unknown }; + }; + internals.state.selectedConversationId = "c1"; + internals.handleEphemeral({ kind: "ephemeral", convo_id: "c1", activity: { state: "thinking" } }); + expect(internals.state.activity).toMatchObject({ state: "thinking" }); + internals.suspendLiveStreams?.(); + expect(internals.activities.size).toBe(0); + expect(internals.state.activity).toBeUndefined(); + }); + + it("hiding the tab while its socket stays open marks the open chat's live output stale", () => { + const { internals } = liveClient(); + const client = internals as unknown as { + lastViewing?: string | null; + activities: Map; + onTabViewChange(): void; + connection?: { send(operation: unknown): boolean }; + state: { selectedConversationId?: string }; + }; + client.state.selectedConversationId = "c1"; + client.connection = { send: () => true }; + client.lastViewing = "c1"; + client.activities.set("c1", { state: "thinking" }); + Object.defineProperty(document, "visibilityState", { configurable: true, get: () => "hidden" }); + try { + client.onTabViewChange(); + } finally { + Object.defineProperty(document, "visibilityState", { configurable: true, get: () => visibility }); + } + expect(client.lastViewing).toBeNull(); + expect(client.activities.size).toBe(0); + expect(internals.toolStreams.get("c1")?.tu1).toMatchObject({ stale: true }); + }); + + it("a blur that leaves the tab visible keeps live output live", () => { + const { internals } = liveClient(); + const client = internals as unknown as { + lastViewing?: string | null; + onTabViewChange(): void; + connection?: { send(operation: unknown): boolean }; + state: { selectedConversationId?: string }; + }; + client.state.selectedConversationId = "c1"; + client.connection = { send: () => true }; + client.lastViewing = "c1"; + client.onTabViewChange(); + expect(client.lastViewing).toBe("c1"); + expect(internals.toolStreams.get("c1")?.tu1.stale).toBeUndefined(); + }); + + it("shows 'live output no longer available' on a card that is no longer live, and not on a live one", async () => { + (globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const container = document.createElement("div"); + const root = createRoot(container); + const stream: ToolStreamState = { + messageRef: "tu1", + command: "make", + content: "a\n", + offset: 2, + headTruncated: false, + }; + await act(async () => { + root.render(React.createElement(ToolStream, { stream })); + }); + expect(container.textContent).not.toContain("live output no longer available"); + await act(async () => { + root.render(React.createElement(ToolStream, { stream: { ...stream, stale: true } })); + }); + expect(container.textContent).toContain("live output no longer available"); + await act(async () => root.unmount()); + }); +}); + +// ── Cursor catch-up on top of the shared recovery fixture ── + +function fixtureRows(): JournalEvent[] | undefined { + let dir = process.env.MATRON_CONFORMANCE_DIR; + const tarball = process.env.MATRON_CONFORMANCE_TARBALL; + if (!dir && tarball) { + dir = fs.mkdtempSync(path.join(os.tmpdir(), "matron-conformance-")); + execFileSync("tar", ["-xzf", tarball, "-C", dir, "--strip-components=1"]); + } + if (!dir) return undefined; + const fixture = JSON.parse(fs.readFileSync(path.join(dir, "19a_recovery_events_while_away.json"), "utf8")) as { + steps: Array<{ role: string; kind: string; frame?: Record }>; + }; + const resolveNode = (node: unknown): unknown => { + if (Array.isArray(node)) return node.map(resolveNode); + if (node && typeof node === "object") { + const record = node as Record; + if ("$type" in record) return 1_700_000_000_000; + if ("$ref" in record) return 7; + return Object.fromEntries(Object.entries(record).map(([key, value]) => [key, resolveNode(value)])); + } + return node; + }; + const bySeq = new Map(); + for (const step of fixture.steps) { + if (step.role === "client" && step.kind === "ws_expect" && step.frame?.kind === "journal") { + const row = resolveNode(step.frame) as unknown as JournalEvent; + if (!bySeq.has(row.seq)) bySeq.set(row.seq, row); + } + } + return [...bySeq.values()].sort((a, b) => a.seq - b.seq); +} + +const rows = fixtureRows(); +const itWithFixture = rows ? it : it.skip; + +describe("cursor catch-up after a hidden-tab close (recovery fixture 19a)", () => { + itWithFixture("replays the rows missed while hidden from the stored cursor, in order, once", async () => { + (globalThis as { indexedDB: IDBFactory }).indexedDB = new IDBFactory(); + const database = await JournalDatabase.open("https://journal.example", 1, "alice"); + await database.replaceWithSnapshot({ conversations: [], seq: 0 } as never); + const journal = rows!; // seq 1, 2 held before the tab hid; 3 and 4 arrive while it was hidden + const available = [...journal.filter((row) => row.seq <= 2)]; + + const cb = { + ...callbacks(), + cursor: async () => (await database.cursor()) ?? 0, + onJournalBatch: async (frames: JournalEvent[]) => { + for (const frame of frames) await database.applyJournal(frame); + }, + }; + const connection = new JournalConnection("https://journal.example", "token", cb); + started.push(connection); + const serve = (socket: FakeSocket): void => { + const hello = socket.hello!; + const cursor = hello.cursor as number; + const head = Math.max(...available.map((row) => row.seq)); + socket.receive({ ...HELLO_OK, seq: head }); + for (const row of available.filter((candidate) => candidate.seq > cursor)) socket.receive(row); + }; + + connection.start(); + const first = FakeSocket.instances[0]; + first.open(); + await settle(); + serve(first); + await settle(); + expect(await database.cursor()).toBe(2); + + setVisibility("hidden"); + jest.advanceTimersByTime(HIDDEN_CLOSE_MS); + expect(first.readyState).toBe(FakeSocket.CLOSED); + available.push(...journal.filter((row) => row.seq > 2)); // the agent journals while the tab is hidden + + setVisibility("visible"); + expect(FakeSocket.instances).toHaveLength(2); + const second = FakeSocket.instances[1]; + second.open(); + await settle(); + expect(second.hello?.cursor).toBe(2); + serve(second); + await settle(); + + expect((await database.events("c1")).map((event) => event.seq)).toEqual([1, 2, 3, 4]); + expect(await database.cursor()).toBe(4); + connection.stop(); + database.close(); + }); +}); diff --git a/test/unit-tests/journal/notifications-test.ts b/test/unit-tests/journal/notifications-test.ts index 26dbd6c..4069412 100644 --- a/test/unit-tests/journal/notifications-test.ts +++ b/test/unit-tests/journal/notifications-test.ts @@ -661,6 +661,59 @@ describe("DesktopNotifier", () => { deliver(background.client, event({ convo_id: "c3", type: "prompt" })); expect(background.notification.shown).toHaveLength(1); }); + + describe("with an active push subscription", () => { + const webPush = () => ({ + active: jest.fn(() => true), + sync: jest.fn().mockResolvedValue(undefined), + unregister: jest.fn().mockResolvedValue(undefined), + }); + + it("alerts for itself when another visible tab has the conversation open, because the journal sends no push", async () => { + const bus = channelBus(); + const background = setup({ focused: false, env: { channel: bus, webPush: webPush() } }); + background.notifier.start(); + await flush(); + // A visible, unfocused tab of this browser shows c2; the hidden one applies the event. + bus().postMessage({ type: "view", tab: "side-by-side", focused: false, visible: true, convoId: "c2" }); + Object.defineProperty(background.doc, "visibilityState", { configurable: true, value: "hidden" }); + deliver(background.client, event({ convo_id: "c2", type: "prompt" })); + expect(background.notification.shown).toHaveLength(1); + }); + + it("alerts for itself when another tab has focus on a different conversation, because the worker stays quiet", async () => { + const bus = channelBus(); + const background = setup({ focused: false, env: { channel: bus, webPush: webPush() } }); + const front = setup({ focused: true, env: { channel: bus } }); + signedIn(front.client, { selectedConversationId: "c9" }); + background.notifier.start(); + front.notifier.start(); + await flush(); + deliver(background.client, event({ convo_id: "c2", type: "prompt" })); + expect(background.notification.shown).toHaveLength(1); + }); + + it("leaves the alert to the push when no tab has focus or shows the conversation", async () => { + const bus = channelBus(); + const background = setup({ focused: false, env: { channel: bus, webPush: webPush() } }); + background.notifier.start(); + await flush(); + bus().postMessage({ type: "view", tab: "other", focused: false, visible: true, convoId: "c9" }); + deliver(background.client, event({ convo_id: "c2", type: "prompt" })); + expect(background.notification.shown).toHaveLength(0); + }); + + it("forgets a tab that reports itself hidden", async () => { + const bus = channelBus(); + const background = setup({ focused: false, env: { channel: bus, webPush: webPush() } }); + background.notifier.start(); + await flush(); + bus().postMessage({ type: "view", tab: "other", focused: false, visible: true, convoId: "c2" }); + bus().postMessage({ type: "view", tab: "other", focused: false, visible: false, convoId: null }); + deliver(background.client, event({ convo_id: "c2", type: "prompt" })); + expect(background.notification.shown).toHaveLength(0); + }); + }); }); describe("Settings → Notifications", () => { diff --git a/test/unit-tests/journal/push-notifier-test.ts b/test/unit-tests/journal/push-notifier-test.ts new file mode 100644 index 0000000..091471d --- /dev/null +++ b/test/unit-tests/journal/push-notifier-test.ts @@ -0,0 +1,253 @@ +/* +Copyright 2026 Matron Contributors. + +SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only +Please see LICENSE files in the repository root for full details. +*/ + +import { type LiveListener, MatronJournalClient } from "../../../src/journal/client"; +import { DesktopNotifier, notificationTag, type NotificationConstructorLike } from "../../../src/journal/notifications"; +import { viewingConvoId } from "../../../src/journal/viewing"; +import type { ClientState, Session } from "../../../src/journal/types"; + +const session: Session = { + serverUrl: "https://example.com", + token: "alice-token", + userId: 1, + deviceId: 1, + username: "alice", +}; +const settle = async (): Promise => { + for (let i = 0; i < 10; i++) await Promise.resolve(); +}; +const stops: (() => void)[] = []; +let originalServiceWorker: PropertyDescriptor | undefined; +beforeEach(() => { + jest.useFakeTimers(); + localStorage.clear(); + originalServiceWorker = Object.getOwnPropertyDescriptor(navigator, "serviceWorker"); +}); +afterEach(() => { + for (const stop of stops.splice(0)) stop(); + jest.useRealTimers(); + jest.restoreAllMocks(); + localStorage.clear(); + window.history.replaceState(null, "", "/"); + if (originalServiceWorker) Object.defineProperty(navigator, "serviceWorker", originalServiceWorker); + else Reflect.deleteProperty(navigator, "serviceWorker"); +}); +function setup(permission: NotificationPermission = "granted", signedIn = true) { + const client = new MatronJournalClient(); + const internals = client as unknown as { state: ClientState; emit(): void }; + function state(patch: Partial = {}) { + internals.state = { ...client.getSnapshot(), phase: "signed-in", session, connection: "online", ...patch }; + internals.emit(); + } + if (signedIn) state(); + const select = jest.spyOn(client, "selectConversation").mockResolvedValue(undefined); + const worker = new EventTarget(); + Object.defineProperty(navigator, "serviceWorker", { configurable: true, value: worker }); + const focus = jest.spyOn(window, "focus").mockImplementation(() => {}); + const webPush = { + active: jest.fn((_session: Session) => false), + sync: jest.fn().mockResolvedValue(undefined), + unregister: jest.fn().mockResolvedValue(undefined), + }; + const shown: NotificationOptions[] = []; + class FakeNotification { + constructor(_title: string, options: NotificationOptions = {}) { + shown.push(options); + } + static permission = permission; + static requestPermission = jest.fn().mockResolvedValue(permission); + onclick = null; + close() {} + } + const notifier = new DesktopNotifier(client, { + Notification: FakeNotification as NotificationConstructorLike, + webPush, + window, + document, + storage: localStorage, + channel: () => undefined, + now: () => 1000, + api: () => ({ + notifySettings: jest.fn().mockResolvedValue({ mode: "all", events: {}, convos: [], device_level: "all" }), + updateNotify: jest.fn().mockResolvedValue(null), + coordinator: jest.fn().mockResolvedValue({ convo_id: null }), + }), + }); + const stop = notifier.start(); + stops.push(stop); + return { notifier, webPush, select, worker, focus, state, stop, shown, client, notification: FakeNotification }; +} +it("enabling while signed in and online syncs the enabled snapshot", async () => { + const f = setup(); + await f.notifier.enable(); + await settle(); + expect(f.webPush.sync).toHaveBeenCalledWith(session, true); +}); +it("disabling unregisters the previous registration", async () => { + const f = setup(); + await f.notifier.enable(); + await settle(); + f.notifier.disable(); + await settle(); + expect(f.webPush.unregister).toHaveBeenCalledWith(session); +}); +it("reconnect syncs enabled notifications and sign-out unregisters the old session", async () => { + const f = setup(); + await f.notifier.enable(); + await settle(); + f.webPush.sync.mockClear(); + f.state({ connection: "connecting" }); + f.state({ connection: "online" }); + await settle(); + expect(f.webPush.sync).toHaveBeenCalledWith(session, true); + f.state({ phase: "signed-out", session: undefined }); + await settle(); + expect(f.webPush.unregister).toHaveBeenCalledWith(session); +}); +it("worker messages focus and select a conversation, and detach removes the listener", async () => { + const f = setup(); + f.worker.dispatchEvent(new MessageEvent("message", { data: { type: "matron-open-convo", convoId: "c1" } })); + expect(f.focus).toHaveBeenCalledTimes(1); + expect(f.select).toHaveBeenCalledWith("c1"); + f.stop(); + f.select.mockClear(); + f.focus.mockClear(); + f.worker.dispatchEvent(new MessageEvent("message", { data: { type: "matron-open-convo", convoId: "c2" } })); + expect(f.select).not.toHaveBeenCalled(); + expect(f.focus).not.toHaveBeenCalled(); + await settle(); + expect(f.webPush.unregister).toHaveBeenCalledWith(session); +}); +it("reads and clears the conversation hash once on first sign-in", async () => { + window.history.replaceState(null, "", "/#convo=c1"); + const f = setup("granted", false); + expect(f.select).not.toHaveBeenCalled(); + f.state(); + await settle(); + expect(f.select).toHaveBeenCalledWith("c1"); + expect(window.location.hash).toBe(""); + window.history.replaceState(null, "", "/#convo=c2"); + f.state(); + await settle(); + expect(f.select).toHaveBeenCalledTimes(1); +}); +it("denied permission never requests registration, then granted permission enables sync", async () => { + const f = setup("denied"); + await f.notifier.enable(); + await settle(); + expect(f.webPush.sync.mock.calls.some(([, wanted]) => wanted === true)).toBe(false); + f.notification.permission = "granted"; + await f.notifier.enable(); + await settle(); + expect(f.webPush.sync).toHaveBeenCalledWith(session, true); +}); + +it("shares the actual in-page notification tag with the worker contract", async () => { + const f = setup(); + await f.notifier.enable(); + await settle(); + const internals = f.client as unknown as { emitLive(call: (listener: LiveListener) => void): void }; + internals.emitLive((listener) => + listener.journalEvent?.( + { + kind: "journal", + seq: 7, + convo_id: "c1", + ts: 1000, + sender: "agent:1", + type: "prompt", + payload: { text: "Needs you" }, + }, + undefined, + ), + ); + expect(f.shown).toHaveLength(1); + expect(f.shown[0].tag).toBe(notificationTag("c1")); +}); + +function promptEvent(convoId: string, seq: number): Parameters>[0] { + return { + kind: "journal", + seq, + convo_id: convoId, + ts: 1000, + sender: "agent:1", + type: "prompt", + payload: { text: "Needs you" }, + }; +} + +function emitPrompt(client: MatronJournalClient, convoId: string, seq: number): void { + const internals = client as unknown as { emitLive(call: (listener: LiveListener) => void): void }; + internals.emitLive((listener) => listener.journalEvent?.(promptEvent(convoId, seq), undefined)); +} + +it("alerts for the open conversation of a visible but unfocused tab, which the journal does not push for", async () => { + jest.spyOn(document, "visibilityState", "get").mockReturnValue("visible"); + jest.spyOn(document, "hasFocus").mockReturnValue(false); + const f = setup(); + f.webPush.active.mockReturnValue(true); + f.state({ selectedConversationId: "c1" }); + await f.notifier.enable(); + await settle(); + // The page still reports the chat as viewed, so the journal sends no push for it. + expect(viewingConvoId(f.client.getSnapshot().selectedConversationId, document)).toBe("c1"); + emitPrompt(f.client, "c1", 8); + expect(f.shown).toHaveLength(1); + expect(f.shown[0].tag).toBe(notificationTag("c1")); +}); + +it("leaves another conversation's alert to push when the visible tab is unfocused", async () => { + jest.spyOn(document, "visibilityState", "get").mockReturnValue("visible"); + jest.spyOn(document, "hasFocus").mockReturnValue(false); + const f = setup(); + f.webPush.active.mockReturnValue(true); + f.state({ selectedConversationId: "c1" }); + await f.notifier.enable(); + await settle(); + emitPrompt(f.client, "c2", 9); + expect(f.webPush.active).toHaveBeenCalledWith(session); + expect(f.shown).toHaveLength(0); +}); + +it("leaves the open conversation's alert to push when the tab is hidden", async () => { + jest.spyOn(document, "visibilityState", "get").mockReturnValue("hidden"); + jest.spyOn(document, "hasFocus").mockReturnValue(false); + const f = setup(); + f.webPush.active.mockReturnValue(true); + f.state({ selectedConversationId: "c1" }); + await f.notifier.enable(); + await settle(); + expect(viewingConvoId(f.client.getSnapshot().selectedConversationId, document)).toBeNull(); + emitPrompt(f.client, "c1", 10); + expect(f.shown).toHaveLength(0); +}); + +it("alerts itself without a push subscription, hidden or not", async () => { + jest.spyOn(document, "visibilityState", "get").mockReturnValue("hidden"); + const f = setup(); + f.state({ selectedConversationId: "c1" }); + await f.notifier.enable(); + await settle(); + emitPrompt(f.client, "c1", 11); + expect(f.shown).toHaveLength(1); +}); + +it("guards suspension only for an active subscription for the current session, and clears on detach", async () => { + const f = setup(); + const internals = f.client as unknown as { suspendGuard?: () => boolean }; + expect(internals.suspendGuard?.()).toBe(false); + f.webPush.active.mockImplementation((s) => s.token === session.token); + expect(internals.suspendGuard?.()).toBe(true); + f.state({ session: { ...session, token: "other-token" } }); + expect(internals.suspendGuard?.()).toBe(false); + f.state({ session: undefined }); + expect(internals.suspendGuard?.()).toBe(false); + f.stop(); + expect(internals.suspendGuard).toBeUndefined(); + await settle(); +}); diff --git a/test/unit-tests/journal/push-review-test.ts b/test/unit-tests/journal/push-review-test.ts new file mode 100644 index 0000000..f8d2bc0 --- /dev/null +++ b/test/unit-tests/journal/push-review-test.ts @@ -0,0 +1,264 @@ +/* +Copyright 2026 Matron Contributors. + +SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only +Please see LICENSE files in the repository root for full details. +*/ + +// Review follow-ups for Web Push: one alert per event, cleanup of subscriptions the page no +// longer knows about, notifications that open the app even without a conversation, and windows +// outside the app's scope never swallowing a push. + +import { type LiveListener, MatronJournalClient } from "../../../src/journal/client"; +import { DesktopNotifier, type NotificationConstructorLike } from "../../../src/journal/notifications"; +import { + installPushHandlers, + parsePushPayload, + routeNotificationClick, + type ServiceWorkerScopeLike, + type WorkerEventLike, +} from "../../../src/journal/push-sw"; +import type { ClientState, JournalEvent, Session } from "../../../src/journal/types"; +import { pushScope, WebPushRegistrar, type WebPushEnvironment } from "../../../src/journal/web-push"; + +const session: Session = { + serverUrl: "https://example.com", + token: "alice-token", + userId: 1, + deviceId: 1, + username: "alice", +}; +const scopeUrl = "https://example.com/app/"; +const settle = async (): Promise => { + for (let i = 0; i < 10; i++) await Promise.resolve(); +}; + +beforeEach(() => { + jest.useFakeTimers(); + localStorage.clear(); +}); +afterEach(() => { + jest.useRealTimers(); + jest.restoreAllMocks(); + localStorage.clear(); +}); + +// ── the worker ── + +function worker(windows: Partial<{ url: string; focused: boolean; visibilityState: string }>[] = [{}]) { + const listeners = new Map void>(); + const clients = windows.map((win) => ({ + url: scopeUrl, + focused: false, + visibilityState: "hidden", + focus: jest.fn().mockResolvedValue(undefined), + postMessage: jest.fn(), + ...win, + })); + const scope = { + registration: { scope: scopeUrl, showNotification: jest.fn().mockResolvedValue(undefined) }, + clients: { + matchAll: jest.fn().mockResolvedValue(clients), + openWindow: jest.fn().mockResolvedValue(undefined), + claim: jest.fn().mockResolvedValue(undefined), + }, + skipWaiting: jest.fn().mockResolvedValue(undefined), + addEventListener: (type: string, listener: (event: WorkerEventLike) => void) => { + listeners.set(type, listener); + }, + } satisfies ServiceWorkerScopeLike; + installPushHandlers(scope); + async function fire(type: string, fields: Partial = {}) { + const pending: Promise[] = []; + listeners.get(type)?.({ ...fields, waitUntil: (promise) => void pending.push(promise) }); + await Promise.all(pending); + } + return { scope, clients, fire }; +} +const valid = { v: 1, title: "Chat", body: "Needs you", convo_id: "c1", seq: 7, kind: "attention" }; + +it("a focused page outside the app's scope does not swallow a push", async () => { + const { scope, fire } = worker([{ url: "https://example.com/admin/", focused: true, visibilityState: "visible" }]); + await fire("push", { data: { json: () => valid } }); + expect(scope.registration.showNotification).toHaveBeenCalledTimes(1); +}); +it("a focused page inside the scope still covers the push", async () => { + const { scope, fire } = worker([{ focused: true, visibilityState: "visible" }]); + await fire("push", { data: { json: () => valid } }); + expect(scope.registration.showNotification).not.toHaveBeenCalled(); +}); +it("clicking a fallback notification (no conversation) focuses the app without a message", async () => { + const { clients, fire } = worker(); + await fire("notificationclick", { notification: { data: undefined as never, close: jest.fn() } }); + expect(clients[0].focus).toHaveBeenCalledTimes(1); + expect(clients[0].postMessage).not.toHaveBeenCalled(); +}); +it("clicking a fallback notification with no window opens the app scope", async () => { + const { scope, fire } = worker([]); + await fire("notificationclick", { notification: { data: undefined as never, close: jest.fn() } }); + expect(scope.clients.openWindow).toHaveBeenCalledWith(scopeUrl); +}); +it("routeNotificationClick without a conversation never builds a hash", () => { + expect(routeNotificationClick({ convoId: null, windows: [], scope: scopeUrl })).toEqual({ + action: "open", + url: scopeUrl, + }); + expect( + routeNotificationClick({ convoId: "", windows: [{ url: scopeUrl, focused: false }], scope: scopeUrl }), + ).toEqual({ action: "focus", index: 0 }); +}); +it("a payload with an empty title is not trusted", () => { + expect(parsePushPayload({ ...valid, title: "" })).toBeNull(); +}); + +// ── the registrar ── + +const keyBytes = Uint8Array.from([4, ...Array.from({ length: 64 }, (_, i) => i + 1)]); +function registrar(existing: boolean) { + const subscription = { + endpoint: "https://push.example.com/alice", + options: { applicationServerKey: keyBytes.buffer }, + toJSON: jest.fn(() => ({ endpoint: "https://push.example.com/alice", keys: { p256dh: "k", auth: "a" } })), + unsubscribe: jest.fn().mockResolvedValue(true), + }; + const pushManager = { + getSubscription: jest.fn().mockResolvedValue(existing ? subscription : null), + subscribe: jest.fn().mockResolvedValue(subscription), + }; + const api = { + webPushVapidKey: jest.fn().mockResolvedValue({ public_key: Buffer.from(keyBytes).toString("base64url") }), + registerWebPush: jest.fn().mockResolvedValue({ ok: true }), + }; + const env: WebPushEnvironment = { + serviceWorker: { + register: jest.fn().mockResolvedValue({ pushManager }), + getRegistration: jest.fn().mockResolvedValue({ pushManager }), + }, + PushManager: {}, + Notification: { permission: "granted" }, + api: () => api, + scope: "/", + }; + return { registrar: new WebPushRegistrar(env), api, subscription, pushManager }; +} + +it("turning push off after a reload removes a subscription an earlier page created", async () => { + const f = registrar(true); + await f.registrar.sync(session, false); + expect(f.api.registerWebPush).toHaveBeenCalledWith({ endpoint: null }); + expect(f.subscription.unsubscribe).toHaveBeenCalledTimes(1); +}); +it("turning push off with no subscription costs no request", async () => { + const f = registrar(false); + await f.registrar.sync(session, false); + expect(f.api.registerWebPush).not.toHaveBeenCalled(); +}); +it("signing out unsubscribes the browser subscription even when this page never synced", async () => { + const f = registrar(true); + f.api.registerWebPush.mockRejectedValue(new Error("401")); + await f.registrar.unregister(session); + expect(f.subscription.unsubscribe).toHaveBeenCalledTimes(1); +}); +it("an absolute public path (assets on another origin) has no usable scope", () => { + expect(pushScope("/")).toBe("/"); + expect(pushScope("/app")).toBe("/app/"); + expect(pushScope("https://cdn.example.com/app/")).toBeNull(); +}); + +// ── the notifier ── + +function notifier(options: { active: boolean; focused: boolean }) { + const client = new MatronJournalClient(); + const internals = client as unknown as { state: ClientState; emit(): void }; + const state = (patch: Partial = {}) => { + internals.state = { ...client.getSnapshot(), phase: "signed-in", session, connection: "online", ...patch }; + internals.emit(); + }; + state(); + const shown: string[] = []; + class FakeNotification { + constructor(title: string) { + shown.push(title); + } + static permission = "granted" as NotificationPermission; + static requestPermission = jest.fn().mockResolvedValue("granted"); + onclick = null; + close() {} + } + const webPush = { + sync: jest.fn().mockResolvedValue(undefined), + unregister: jest.fn().mockResolvedValue(undefined), + active: jest.fn(() => options.active), + }; + const doc = { + title: "Matron", + visibilityState: "visible", + hasFocus: () => options.focused, + addEventListener: jest.fn(), + removeEventListener: jest.fn(), + } as unknown as Document; + const n = new DesktopNotifier(client, { + Notification: FakeNotification as unknown as NotificationConstructorLike, + webPush, + window: { focus: jest.fn(), addEventListener: jest.fn(), removeEventListener: jest.fn() } as unknown as Window, + document: doc, + storage: localStorage, + channel: () => undefined, + now: () => 1000, + api: () => ({ + notifySettings: jest.fn().mockResolvedValue({ mode: "all", events: {}, convos: [], device_level: "all" }), + updateNotify: jest.fn().mockResolvedValue(null), + coordinator: jest.fn().mockResolvedValue({ convo_id: null }), + }), + }); + const stop = n.start(); + const prompt = (): JournalEvent => ({ + kind: "journal", + seq: 5, + convo_id: "c2", + ts: 1000, + sender: "agent:3", + type: "permission_request", + payload: { description: "ok?" }, + }); + const deliver = () => + (client as unknown as { emitLive(call: (l: LiveListener) => void): void }).emitLive((l) => + l.journalEvent?.(prompt(), undefined), + ); + return { n, webPush, shown, deliver, state, stop }; +} + +it("an unfocused tab leaves the alert to the push once the push is registered", async () => { + const f = notifier({ active: true, focused: false }); + f.deliver(); + await settle(); + expect(f.shown).toEqual([]); + f.stop(); +}); +it("an unfocused tab still alerts in-page when no push is registered", async () => { + const f = notifier({ active: false, focused: false }); + f.deliver(); + await settle(); + expect(f.shown).toHaveLength(1); + f.stop(); +}); +it("a focused tab on another conversation still alerts in-page (the worker stays quiet for it)", async () => { + const f = notifier({ active: true, focused: true }); + f.deliver(); + await settle(); + expect(f.shown).toHaveLength(1); + f.stop(); +}); +it("a stale tab re-reads the shared preference before it syncs push", async () => { + const f = notifier({ active: false, focused: false }); + await f.n.enable(); + await settle(); + f.webPush.sync.mockClear(); + localStorage.setItem("matron_desktop_notifications_v1", JSON.stringify({ enabled: false })); + f.state({ connection: "connecting" }); + f.state({ connection: "online" }); + await settle(); + expect(f.webPush.sync).not.toHaveBeenCalledWith(session, true); + expect(f.webPush.sync).toHaveBeenCalledWith(session, false); + f.stop(); +}); diff --git a/test/unit-tests/journal/push-sw-test.ts b/test/unit-tests/journal/push-sw-test.ts new file mode 100644 index 0000000..44889c7 --- /dev/null +++ b/test/unit-tests/journal/push-sw-test.ts @@ -0,0 +1,244 @@ +/* +Copyright 2026 Matron Contributors. + +SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only +Please see LICENSE files in the repository root for full details. +*/ + +import { parseConvoHash } from "../../../src/journal/push-shared"; +import fixture from "../../fixtures/webpush-payload.json"; +import { notificationTag } from "../../../src/journal/notifications"; +import { + parsePushPayload, + fallbackContent, + decidePushDisplay, + buildNotification, + routeNotificationClick, + installPushHandlers, + type PushContent, + type ServiceWorkerScopeLike, + type WorkerEventLike, +} from "../../../src/journal/push-sw"; + +const content: PushContent = { v: 1, title: "Chat", body: "Needs you", convo_id: "c1", seq: 7, kind: "attention" }; +const scopeUrl = "https://example.com/app/"; + +beforeEach(() => jest.useFakeTimers()); +afterEach(() => { + jest.useRealTimers(); + jest.restoreAllMocks(); +}); + +it("accepts every field of the sender fixture", () => { + expect(parsePushPayload(fixture)).toEqual(fixture); +}); +it("preserves subtitle and item fields", () => { + const item = { id: "i1", num: 3, kind: "question", actions: ["reply"], reply_to: "i0" }; + const raw = { ...content, subtitle: "alice", item }; + expect(parsePushPayload(raw)).toEqual(raw); +}); +it("rejects malformed and hostile payloads while accepting a valid control", () => { + const invalid: unknown[] = [ + undefined, + null, + [], + "text", + 42, + {}, + { ...content, v: 2 }, + { ...content, convo_id: undefined }, + { ...content, convo_id: "" }, + { ...content, convo_id: "x".repeat(129) }, + { ...content, title: 1 }, + { ...content, body: false }, + { ...content, title: "x".repeat(1_000_000) }, + { ...content, body: "x".repeat(1_000_000) }, + { ...content, seq: 1.5 }, + { ...content, seq: Infinity }, + { ...content, seq: NaN }, + { ...content, seq: "1" }, + { ...content, kind: "unknown" }, + ]; + for (const raw of invalid) { + expect(() => parsePushPayload(raw)).not.toThrow(); + expect(parsePushPayload(raw)).toBeNull(); + } + expect(parsePushPayload(content)).toEqual(content); +}); +it("skips only when a visible focused window covers the push", () => { + const focused = { visibilityState: "visible", focused: true }; + const hidden = { visibilityState: "hidden", focused: true }; + expect( + [[], [focused], [{ ...focused, focused: false }], [hidden], [hidden, focused]].map(decidePushDisplay), + ).toEqual(["show", "skip", "show", "show", "skip"]); +}); +it.each(["attention", "done", "activity"] as const)("builds safe options and a shared tag for %s", (kind) => { + const built = buildNotification({ ...content, kind }); + expect(built).toEqual({ + title: "Chat", + options: { + body: "Needs you", + tag: "matron:c1", + renotify: kind !== "activity", + data: { convo_id: "c1", seq: 7 }, + }, + }); + expect(notificationTag("c1")).toBe("matron:c1"); + expect(built.options.tag).toBe(notificationTag("c1")); + expect(buildNotification(parsePushPayload({ ...content, title: { url: "https://example.com/evil" } }))).toEqual( + buildNotification(null), + ); +}); +it("uses fixed fallback text for missing content and every kind", () => { + expect(fallbackContent()).toEqual({ title: "Matron", body: "New activity from your agent" }); + expect(fallbackContent("attention").body).toBe("Your agent needs you"); + expect(fallbackContent("done").body).toBe("Your agent finished its turn"); + expect(fallbackContent("activity").body).toBe("New activity from your agent"); + expect(buildNotification(null)).toMatchObject({ + title: "Matron", + options: { body: "New activity from your agent" }, + }); +}); +it("focuses a same-scope window, preferring focused then first", () => { + const windows = [ + { url: scopeUrl, focused: false }, + { url: scopeUrl + "#old", focused: true }, + ]; + expect(routeNotificationClick({ convoId: "c1", windows, scope: scopeUrl })).toEqual({ + action: "focus", + index: 1, + message: { type: "matron-open-convo", convoId: "c1" }, + }); + windows[1].focused = false; + expect(routeNotificationClick({ convoId: "c1", windows, scope: scopeUrl })).toMatchObject({ + action: "focus", + index: 0, + }); +}); +it("opens inside scope, ignores other origins and paths, and round-trips hostile ids", () => { + const convoId = "/../?#%雪"; + const windows = [ + { url: "https://other.example.com/app/", focused: true }, + { url: "https://example.com/application/", focused: true }, + ]; + const result = routeNotificationClick({ convoId, windows, scope: scopeUrl }); + expect(result).toEqual({ action: "open", url: scopeUrl + "#convo=" + encodeURIComponent(convoId) }); + expect(routeNotificationClick({ convoId, windows: [], scope: scopeUrl })).toEqual(result); + const url = new URL(result?.action === "open" ? result.url : scopeUrl); + expect(url.origin + url.pathname).toBe(scopeUrl.slice(0, -1) + "/"); + expect(parseConvoHash(url.hash)).toBe(convoId); +}); +it("decodes only bounded conversation hashes", () => { + for (const hash of ["", "#other=c1", "#convo=%", "#convo=", "#convo=" + "x".repeat(129)]) + expect(parseConvoHash(hash)).toBeNull(); + expect(parseConvoHash("#convo=c1")).toBe("c1"); +}); + +function worker() { + const listeners = new Map void>(); + const win = { + url: scopeUrl, + focused: false, + visibilityState: "hidden", + focus: jest.fn().mockResolvedValue(undefined), + postMessage: jest.fn(), + }; + const scope = { + registration: { scope: scopeUrl, showNotification: jest.fn().mockResolvedValue(undefined) }, + clients: { + matchAll: jest.fn().mockResolvedValue([win]), + openWindow: jest.fn().mockResolvedValue(undefined), + claim: jest.fn().mockResolvedValue(undefined), + }, + skipWaiting: jest.fn().mockResolvedValue(undefined), + addEventListener: (type: string, listener: (event: WorkerEventLike) => void) => { + listeners.set(type, listener); + }, + } satisfies ServiceWorkerScopeLike; + installPushHandlers(scope); + async function fire(type: string, fields: Partial = {}) { + const pending: Promise[] = []; + listeners.get(type)?.({ + ...fields, + waitUntil: (promise) => { + pending.push(promise); + }, + }); + await Promise.all(pending); + } + return { scope, win, listeners, fire }; +} +it("a valid push shows exactly one built notification", async () => { + const { scope, fire } = worker(); + await fire("push", { data: { json: () => content } }); + expect(scope.registration.showNotification).toHaveBeenCalledTimes(1); + const built = buildNotification(content); + expect(scope.registration.showNotification).toHaveBeenCalledWith(built.title, built.options); +}); +it.each(["invalid JSON", "missing data"])("shows fallback for %s", async (mode) => { + const { scope, fire } = worker(); + await fire("push", { + data: + mode === "missing data" + ? null + : { + json: () => { + throw new Error("invalid JSON"); + }, + }, + }); + expect(scope.registration.showNotification).toHaveBeenCalledTimes(1); + expect(scope.registration.showNotification).toHaveBeenCalledWith( + "Matron", + expect.objectContaining({ body: "New activity from your agent" }), + ); +}); +it("suppresses covered pushes and resumes after focus is lost", async () => { + const { scope, win, fire } = worker(); + win.focused = true; + win.visibilityState = "visible"; + await fire("push", { data: { json: () => content } }); + expect(scope.registration.showNotification).not.toHaveBeenCalled(); + win.focused = false; + await fire("push", { data: { json: () => content } }); + expect(scope.registration.showNotification).toHaveBeenCalledTimes(1); +}); +it("contains display failures without rejecting the event lifetime", async () => { + const { scope, fire } = worker(); + scope.registration.showNotification.mockRejectedValue(new Error("display failed")); + await expect(fire("push", { data: { json: () => content } })).resolves.toBeUndefined(); + expect(scope.registration.showNotification).toHaveBeenCalled(); +}); +it("a failed window lookup still shows fallback", async () => { + const { scope, fire } = worker(); + scope.clients.matchAll.mockRejectedValue(new Error("lookup failed")); + await expect(fire("push", { data: { json: () => content } })).resolves.toBeUndefined(); + expect(scope.registration.showNotification).toHaveBeenCalledWith( + "Matron", + expect.objectContaining({ body: "New activity from your agent" }), + ); +}); +it("click closes, focuses and posts to the existing window", async () => { + const { win, fire } = worker(); + const close = jest.fn(); + await fire("notificationclick", { notification: { data: { convo_id: "c1" }, close } }); + expect(close).toHaveBeenCalledTimes(1); + expect(win.focus).toHaveBeenCalledTimes(1); + expect(win.postMessage).toHaveBeenCalledWith({ type: "matron-open-convo", convoId: "c1" }); +}); +it("click opens a window when there are none", async () => { + const { scope, fire } = worker(); + scope.clients.matchAll.mockResolvedValue([]); + const close = jest.fn(); + await fire("notificationclick", { notification: { data: { convo_id: "c1" }, close } }); + expect(close).toHaveBeenCalledTimes(1); + expect(scope.clients.openWindow).toHaveBeenCalledWith(scopeUrl + "#convo=c1"); +}); +it("installs and activates immediately without fetch or caching handlers", async () => { + const { scope, listeners, fire } = worker(); + await fire("install"); + await fire("activate"); + expect(scope.skipWaiting).toHaveBeenCalledTimes(1); + expect(scope.clients.claim).toHaveBeenCalledTimes(1); + expect([...listeners.keys()].sort()).toEqual(["activate", "install", "notificationclick", "push"]); +}); diff --git a/test/unit-tests/journal/readonly-egress-test.ts b/test/unit-tests/journal/readonly-egress-test.ts index 288392f..a107108 100644 --- a/test/unit-tests/journal/readonly-egress-test.ts +++ b/test/unit-tests/journal/readonly-egress-test.ts @@ -32,6 +32,7 @@ interface FakeDatabase { addToOutbox: jest.MockedFunction<(message: PendingMessage) => Promise>; deleteOutboxRows: jest.MockedFunction<(localIds: string[]) => Promise>; events: jest.MockedFunction<(conversationId: string) => Promise<[]>>; + conversations: jest.MockedFunction<() => Promise<[]>>; cursor: jest.MockedFunction<() => Promise>; } @@ -77,6 +78,7 @@ function fakeDatabase(initial: PendingMessage[] = []): { database: FakeDatabase; for (const localId of localIds) rows.delete(localId); }), events: jest.fn().mockResolvedValue([]), + conversations: jest.fn().mockResolvedValue([]), cursor: jest.fn().mockResolvedValue(undefined), }; return { database, rows }; diff --git a/test/unit-tests/journal/subchat-select-test.ts b/test/unit-tests/journal/subchat-select-test.ts index 2c48837..1f11a41 100644 --- a/test/unit-tests/journal/subchat-select-test.ts +++ b/test/unit-tests/journal/subchat-select-test.ts @@ -78,6 +78,9 @@ describe("subchat automatic selection", () => { beforeEach(() => { localStorage.clear(); jest.spyOn(JournalConnection.prototype, "start").mockImplementation(() => undefined); + // The page reports the open chat only while the tab is focused; jsdom has no focus of its own. + jest.spyOn(document, "hasFocus").mockReturnValue(true); + jest.spyOn(document, "visibilityState", "get").mockReturnValue("visible"); }); afterEach(() => jest.restoreAllMocks()); diff --git a/test/unit-tests/journal/tracker-client-test.ts b/test/unit-tests/journal/tracker-client-test.ts index 250367e..3e35c06 100644 --- a/test/unit-tests/journal/tracker-client-test.ts +++ b/test/unit-tests/journal/tracker-client-test.ts @@ -1940,7 +1940,11 @@ describe("MatronJournalClient notices and user settings", () => { it("on (re)connect takes the settings from hello_ok and loads the inbox for the badge", async () => { const { client, state } = makeClient(); const internal = state as SettingsInternals; - internal.database = { outbox: jest.fn().mockResolvedValue([]), cursor: jest.fn().mockResolvedValue(undefined) }; + internal.database = { + outbox: jest.fn().mockResolvedValue([]), + conversations: jest.fn().mockResolvedValue([]), + cursor: jest.fn().mockResolvedValue(undefined), + }; internal.connection = { send: jest.fn() }; internal.api = { items: jest.fn().mockResolvedValue({ items: [item()], next_cursor: null }) }; diff --git a/test/unit-tests/journal/viewing-test.ts b/test/unit-tests/journal/viewing-test.ts new file mode 100644 index 0000000..23c1937 --- /dev/null +++ b/test/unit-tests/journal/viewing-test.ts @@ -0,0 +1,29 @@ +import { isTabFocused, viewingConvoId, watchTabFocus } from "../../../src/journal/viewing"; + +it.each([ + ["visible", true, "c1"], + ["visible", false, "c1"], + ["hidden", true, null], + ["hidden", false, null], +] as const)("reports viewing for visibility %s and focus %s", (visibilityState, focused, expected) => { + const doc = { visibilityState, hasFocus: () => focused }; + expect(isTabFocused(doc)).toBe(visibilityState === "visible" && focused); + expect(viewingConvoId("c1", doc)).toBe(expected); + expect(viewingConvoId(undefined, doc)).toBeNull(); + expect(viewingConvoId("", doc)).toBeNull(); +}); + +it("watches focus, blur and visibility changes and removes every listener", () => { + const changed = jest.fn(); + const stop = watchTabFocus(window, document, changed); + const fire = () => { + window.dispatchEvent(new Event("blur")); + window.dispatchEvent(new Event("focus")); + document.dispatchEvent(new Event("visibilitychange")); + }; + fire(); + expect(changed).toHaveBeenCalledTimes(3); + stop(); + fire(); + expect(changed).toHaveBeenCalledTimes(3); +}); diff --git a/test/unit-tests/journal/web-push-test.ts b/test/unit-tests/journal/web-push-test.ts new file mode 100644 index 0000000..5b0ab48 --- /dev/null +++ b/test/unit-tests/journal/web-push-test.ts @@ -0,0 +1,225 @@ +/* +Copyright 2026 Matron Contributors. + +SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only +Please see LICENSE files in the repository root for full details. +*/ + +import { JournalApi, JournalApiError } from "../../../src/journal/api"; +import { WebPushRegistrar, type WebPushEnvironment } from "../../../src/journal/web-push"; +import type { Session } from "../../../src/journal/types"; + +const session: Session = { + serverUrl: "https://example.com", + token: "alice-token", + userId: 1, + deviceId: 1, + username: "alice", +}; +// A deterministic uncompressed P-256 public point, encoded as the journal sends it. +const keyBytes = Uint8Array.from([4, ...Array.from({ length: 64 }, (_, i) => i + 1)]); +const publicKey = Buffer.from(keyBytes).toString("base64url"); +function setup(patch: Partial = {}) { + const body = { endpoint: "https://example.com/push/alice", keys: { p256dh: "key", auth: "auth" } }; + const subscription = { + endpoint: body.endpoint, + options: { applicationServerKey: keyBytes.buffer }, + toJSON: jest.fn(() => body), + unsubscribe: jest.fn().mockResolvedValue(true), + }; + const pushManager = { + getSubscription: jest.fn().mockResolvedValue(null), + subscribe: jest.fn().mockResolvedValue(subscription), + }; + const register = jest.fn().mockResolvedValue({ pushManager }); + const api = { + webPushVapidKey: jest.fn().mockResolvedValue({ public_key: publicKey }), + registerWebPush: jest.fn().mockResolvedValue({ ok: true }), + }; + const env: WebPushEnvironment = { + serviceWorker: { register }, + PushManager: {}, + Notification: { permission: "granted" }, + api: () => api, + scope: "/", + ...patch, + }; + return { registrar: new WebPushRegistrar(env), api, register, pushManager, subscription, body, env }; +} + +beforeEach(() => jest.useFakeTimers()); +afterEach(() => { + jest.useRealTimers(); + jest.restoreAllMocks(); +}); + +it.each(["serviceWorker", "PushManager", "Notification"] as const)( + "ignores unsupported %s and can register on a supported browser", + async (feature) => { + const unsupported = setup({ [feature]: undefined }); + await expect(unsupported.registrar.sync(session, true)).resolves.toBeUndefined(); + expect(unsupported.api.webPushVapidKey).not.toHaveBeenCalled(); + expect(unsupported.register).not.toHaveBeenCalled(); + const supported = setup(); + await supported.registrar.sync(session, true); + expect(supported.api.registerWebPush).toHaveBeenCalledWith(supported.body); + }, +); +it.each(["denied", "default"] as const)("waits for permission %s to become granted", async (permission) => { + const f = setup({ Notification: { permission } }); + await expect(f.registrar.sync(session, true)).resolves.toBeUndefined(); + expect(f.pushManager.subscribe).not.toHaveBeenCalled(); + expect(f.api.registerWebPush).not.toHaveBeenCalled(); + f.env.Notification!.permission = "granted"; + await f.registrar.sync(session, true); + expect(f.api.registerWebPush).toHaveBeenCalledWith(f.body); +}); +it("remembers a disabled sender for one session and retries for a new token", async () => { + const f = setup(); + f.api.webPushVapidKey.mockRejectedValueOnce(new JournalApiError("off", 404, "web_push_disabled")); + await expect(f.registrar.sync(session, true)).resolves.toBeUndefined(); + await f.registrar.sync(session, true); + expect(f.register).not.toHaveBeenCalled(); + expect(f.api.registerWebPush).not.toHaveBeenCalled(); + expect(f.registrar.lastError).toBeNull(); + expect(f.api.webPushVapidKey).toHaveBeenCalledTimes(1); + await f.registrar.sync({ ...session, token: "bob-token" }, true); + expect(f.api.registerWebPush).toHaveBeenCalledWith(f.body); +}); +it("registers a worker, decodes the key and posts only endpoint and keys", async () => { + const f = setup(); + await f.registrar.sync(session, true); + expect(f.register).toHaveBeenCalledWith("sw.js", { scope: "/" }); + expect(f.pushManager.subscribe).toHaveBeenCalledWith({ userVisibleOnly: true, applicationServerKey: keyBytes }); + expect(f.api.registerWebPush).toHaveBeenCalledTimes(1); + expect(f.api.registerWebPush).toHaveBeenCalledWith(f.body); +}); +it("posts once per session token and endpoint across repeated syncs", async () => { + const f = setup(); + await f.registrar.sync(session, true); + await f.registrar.sync(session, true); + expect(f.api.registerWebPush).toHaveBeenCalledTimes(1); + await f.registrar.sync({ ...session, token: "bob-token" }, true); + expect(f.api.registerWebPush).toHaveBeenCalledTimes(2); +}); +it("reuses an existing subscription with the same server key", async () => { + const f = setup(); + f.pushManager.getSubscription.mockResolvedValue(f.subscription); + await f.registrar.sync(session, true); + expect(f.pushManager.subscribe).not.toHaveBeenCalled(); + expect(f.subscription.unsubscribe).not.toHaveBeenCalled(); + expect(f.api.registerWebPush).toHaveBeenCalledWith(f.body); +}); +it("replaces an existing subscription with a different server key", async () => { + const f = setup(); + const previous = { + ...f.subscription, + options: { applicationServerKey: new Uint8Array([0]).buffer }, + unsubscribe: jest.fn().mockResolvedValue(true), + }; + f.pushManager.getSubscription.mockResolvedValue(previous); + await f.registrar.sync(session, true); + expect(previous.unsubscribe).toHaveBeenCalledTimes(1); + expect(f.pushManager.subscribe).toHaveBeenCalledWith({ userVisibleOnly: true, applicationServerKey: keyBytes }); + expect(f.api.registerWebPush).toHaveBeenCalledWith(f.body); +}); +function installingWorker(state = "installing") { + const listeners = new Set<() => void>(); + return { + state, + addEventListener: (_type: "statechange", listener: () => void) => listeners.add(listener), + removeEventListener: (_type: "statechange", listener: () => void) => listeners.delete(listener), + become(next: string) { + this.state = next; + for (const listener of [...listeners]) listener(); + }, + }; +} +it("waits for a first-visit worker to activate before subscribing", async () => { + const f = setup(); + const worker = installingWorker(); + f.register.mockResolvedValue({ pushManager: f.pushManager, active: null, installing: worker }); + const done = f.registrar.sync(session, true); + for (let i = 0; i < 20; i++) await Promise.resolve(); + expect(f.pushManager.subscribe).not.toHaveBeenCalled(); + worker.become("installed"); + for (let i = 0; i < 20; i++) await Promise.resolve(); + expect(f.pushManager.subscribe).not.toHaveBeenCalled(); + worker.become("activated"); + await done; + expect(f.pushManager.subscribe).toHaveBeenCalledTimes(1); + expect(f.api.registerWebPush).toHaveBeenCalledWith(f.body); + expect(f.registrar.active(session)).toBe(true); + expect(f.registrar.lastError).toBeNull(); +}); +it("subscribes at once when a worker is already active", async () => { + const f = setup(); + f.register.mockResolvedValue({ pushManager: f.pushManager, active: {}, installing: installingWorker() }); + await f.registrar.sync(session, true); + expect(f.pushManager.subscribe).toHaveBeenCalledTimes(1); +}); +it("records an error and does not subscribe when the worker fails to install, then recovers on the next sync", async () => { + const f = setup(); + const worker = installingWorker(); + f.register.mockResolvedValueOnce({ pushManager: f.pushManager, active: null, installing: worker }); + const done = f.registrar.sync(session, true); + for (let i = 0; i < 20; i++) await Promise.resolve(); + worker.become("redundant"); + await done; + expect(f.pushManager.subscribe).not.toHaveBeenCalled(); + expect(f.registrar.lastError).not.toBeNull(); + await f.registrar.sync(session, true); + expect(f.pushManager.subscribe).toHaveBeenCalledTimes(1); + expect(f.registrar.active(session)).toBe(true); +}); +it("stops reporting active when the old subscription was dropped and its replacement failed", async () => { + const f = setup(); + await f.registrar.sync(session, true); + expect(f.registrar.active(session)).toBe(true); + const otherKey = Uint8Array.from([4, ...Array.from({ length: 64 }, (_, i) => 100 + i)]); + f.api.webPushVapidKey.mockResolvedValue({ public_key: Buffer.from(otherKey).toString("base64url") }); + f.pushManager.getSubscription.mockResolvedValue(f.subscription); + f.pushManager.subscribe.mockRejectedValueOnce(new Error("subscribe failed")); + await f.registrar.sync(session, true); + expect(f.subscription.unsubscribe).toHaveBeenCalledTimes(1); + expect(f.registrar.active(session)).toBe(false); + // The journal registration is still removed when notifications are turned off. + await f.registrar.sync(session, false); + expect(f.api.registerWebPush).toHaveBeenLastCalledWith({ endpoint: null }); +}); +it("turning wanted off unregisters the endpoint and browser subscription", async () => { + const f = setup(); + await f.registrar.sync(session, true); + await f.registrar.sync(session, false); + expect(f.api.registerWebPush).toHaveBeenLastCalledWith({ endpoint: null }); + expect(f.subscription.unsubscribe).toHaveBeenCalledTimes(1); +}); +it("explicit unregister is best effort even if the POST fails", async () => { + const f = setup(); + await f.registrar.sync(session, true); + f.api.registerWebPush.mockRejectedValue(new Error("offline")); + await expect(f.registrar.unregister(session)).resolves.toBeUndefined(); + expect(f.subscription.unsubscribe).toHaveBeenCalledTimes(1); + expect(f.api.registerWebPush).toHaveBeenLastCalledWith({ endpoint: null }); +}); +it.each(["subscribe", "POST", "worker", "vapid"])("contains %s failures and records a quiet error", async (failure) => { + const f = setup(); + const error = new Error("push failed"); + if (failure === "subscribe") f.pushManager.subscribe.mockRejectedValue(error); + if (failure === "POST") f.api.registerWebPush.mockRejectedValue(error); + if (failure === "worker") f.register.mockRejectedValue(error); + if (failure === "vapid") f.api.webPushVapidKey.mockRejectedValue(error); + await expect(f.registrar.sync(session, true)).resolves.toBeUndefined(); + expect(f.registrar.lastError).toEqual(expect.any(String)); + expect(f.registrar.lastError).not.toBe(""); +}); +it("API methods use the authenticated key and registration routes", async () => { + const api = new JournalApi(session.serverUrl, session.token); + const json = jest + .spyOn(api as unknown as { json(path: string, options?: unknown): Promise }, "json") + .mockResolvedValue({ ok: true }); + await api.webPushVapidKey(); + await api.registerWebPush({ endpoint: null }); + expect(json).toHaveBeenNthCalledWith(1, "/push/web/vapid-key"); + expect(json).toHaveBeenNthCalledWith(2, "/push/web/register", { method: "POST", body: { endpoint: null } }); +}); diff --git a/webpack.config.mjs b/webpack.config.mjs index f74c2dc..46aa2dd 100644 --- a/webpack.config.mjs +++ b/webpack.config.mjs @@ -97,7 +97,10 @@ export default (_environment, arguments_) => { mode: development ? "development" : "production", bail: true, devtool: development ? "inline-source-map" : "source-map", - entry: "./src/journal/index.tsx", + entry: { + main: "./src/journal/index.tsx", + sw: { import: "./src/journal/sw.ts", filename: "sw.js" }, + }, output: { path: path.join(root, "webapp"), publicPath, @@ -161,7 +164,7 @@ export default (_environment, arguments_) => { }, plugins: [ new MiniCssExtractPlugin({ filename: "assets/[name].[contenthash:8].css" }), - new HtmlWebpackPlugin({ template: "./src/index.html", minify: !development }), + new HtmlWebpackPlugin({ template: "./src/index.html", minify: !development, chunks: ["main"] }), // Bundles served from another origin (an absolute PUBLIC_PATH) must be allowed too. new ContentSecurityPolicyPlugin(/^https?:\/\//.test(publicPath) ? [new URL(publicPath).origin] : []), new CopyWebpackPlugin({