@pi-chamber/web 1.0.0 → 1.0.2-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +3 -1
  2. package/bin/cli.js +7 -32
  3. package/bin/dev-server.js +185 -0
  4. package/bin/dev-server.test.js +252 -0
  5. package/bin/lib/DOCUMENTATION.md +19 -0
  6. package/bin/lib/cli-startup.js +9 -1
  7. package/bin/lib/cli-startup.test.js +30 -0
  8. package/bin/lib/commands-serve.js +9 -5
  9. package/bin/lib/server-runtime.js +6 -0
  10. package/bin/lib/server-runtime.test.js +313 -0
  11. package/dist/assets/{DiagramView-CbSxUe1D.js → DiagramView-GUJij-1P.js} +1 -1
  12. package/dist/assets/{DiffView-VyBf4ilo.js → DiffView-BZ487Bhh.js} +1 -1
  13. package/dist/assets/{FileSaveConflictDialog-BCvbQ234.js → FileSaveConflictDialog-Ci6WdSiS.js} +1 -1
  14. package/dist/assets/{FilesView-DasA5EU2.js → FilesView-DBiWEo71.js} +1 -1
  15. package/dist/assets/{GitView-DU3mOECp.js → GitView-DVyhqN5s.js} +3 -3
  16. package/dist/assets/{JsonTreeView-xZiWDwua.js → JsonTreeView-BaU7aAUq.js} +1 -1
  17. package/dist/assets/{MarkdownRendererImpl-BBwdI2OF.js → MarkdownRendererImpl-6NBJLtEr.js} +1 -1
  18. package/dist/assets/{PatchDiff-BhKm_JPT.js → PatchDiff-CvptevA2.js} +1 -1
  19. package/dist/assets/{SessionSwitcherContent-DTGSP_RB.js → SessionSwitcherContent-Cqp5FVCP.js} +1 -1
  20. package/dist/assets/{SessionSwitcherDropdown-CedOB-xC.js → SessionSwitcherDropdown-CRVJU16x.js} +2 -2
  21. package/dist/assets/{SessionUnreadDot-CZSNKram.js → SessionUnreadDot-CsFxImPI.js} +1 -1
  22. package/dist/assets/SettingsView-ppaIrPry.js +2 -0
  23. package/dist/assets/{SettingsWindow-y33YrpBE.js → SettingsWindow-geMUhnxd.js} +1 -1
  24. package/dist/assets/{ToolOutputDialog-JqIXJWAH.js → ToolOutputDialog-BLGl2mNt.js} +1 -1
  25. package/dist/assets/{ToolPartDiffPreview-CRi_33jE.js → ToolPartDiffPreview-BVeL1IuE.js} +1 -1
  26. package/dist/assets/{VirtualizedFileDiff-ehLQSR5W.js → VirtualizedFileDiff-9kAZ96se.js} +1 -1
  27. package/dist/assets/{collapsible-Vypq-nMP.js → collapsible-BencOwkW.js} +1 -1
  28. package/dist/assets/{computeVirtualFileMetrics-BTfrj_fR.js → computeVirtualFileMetrics-C8vH0vcM.js} +1 -1
  29. package/dist/assets/{contextFileOpenGuard-Dl6mFfD1.js → contextFileOpenGuard-B6e3cTcl.js} +1 -1
  30. package/dist/assets/{gitStatusPredicates-LAsJAhCL.js → gitStatusPredicates-B6w5GMNU.js} +1 -1
  31. package/dist/assets/{index-OveFsNBm.js → index-BifnX1Mp.js} +1 -1
  32. package/dist/assets/{index-DvNeSFO9.js → index-CpSdU-d4.js} +7 -7
  33. package/dist/assets/index-Dwz16owi.css +1 -0
  34. package/dist/assets/{isDiffPlainText-CNZohQ4q.js → isDiffPlainText-BepQ1JHv.js} +1 -1
  35. package/dist/assets/{isFilePlainText-Dz8UubRT.js → isFilePlainText-CA1KFaTm.js} +1 -1
  36. package/dist/assets/{main-BsDkATRV.js → main-TzeSIx1W.js} +3 -3
  37. package/dist/assets/{main-C393Ywhx.js → main-dhVDQIHu.js} +2 -2
  38. package/dist/assets/{markdownCore-Bz9-Y75q.js → markdownCore-BztwD2c9.js} +1 -1
  39. package/dist/assets/{miniChat-CWEerp3c.js → miniChat-smqdx0Y7.js} +2 -2
  40. package/dist/assets/{mobile-YxV9KcxF.js → mobile-BV-WCEiE.js} +2 -2
  41. package/dist/assets/{renderElectronMiniChatApp-GrLmBQRb.js → renderElectronMiniChatApp-DKmb9oa7.js} +2 -2
  42. package/dist/assets/renderMobileApp-D3dtjeaE.js +11 -0
  43. package/dist/assets/runtimeEndpointReset-C1EENUlq.js +53 -0
  44. package/dist/assets/{runtimeSurface-DUXw4-oa.js → runtimeSurface-Bm6cRkok.js} +1 -1
  45. package/dist/assets/{useAppFontEffects-ad-lZJ6o.js → useAppFontEffects-Dq7xKVjh.js} +77 -77
  46. package/dist/assets/{useFilesViewSearch-C4oOHPml.js → useFilesViewSearch-Bvlo7C3a.js} +1 -1
  47. package/dist/assets/{usePushVisibilityBeacon-xd8Q10cI.js → usePushVisibilityBeacon-BY4xtozp.js} +1 -1
  48. package/dist/assets/{useSwitcherItems-B6VC7tug.js → useSwitcherItems-CkE242zK.js} +1 -1
  49. package/dist/assets/{vendor-codemirror-language-data-B4j3gkaT.js → vendor-codemirror-language-data-Bv6kN79m.js} +2 -2
  50. package/dist/assets/{web-components-B0RFakat.js → web-components-CCiRgoOw.js} +1 -1
  51. package/dist/index.html +4 -4
  52. package/dist/mini-chat.html +3 -3
  53. package/dist/mobile.html +3 -3
  54. package/package.json +8 -3
  55. package/server/index.js +48 -6
  56. package/server/lib/notifications/DOCUMENTATION.md +39 -0
  57. package/server/lib/notifications/delivery-runtime.js +314 -0
  58. package/server/lib/notifications/delivery-runtime.test.js +85 -0
  59. package/server/lib/notifications/pi-notification-watcher.js +154 -0
  60. package/server/lib/notifications/pi-notification-watcher.test.js +84 -0
  61. package/server/lib/notifications/routes.js +74 -0
  62. package/server/lib/package-manager.js +3 -2
  63. package/server/lib/package-manager.test.js +7 -2
  64. package/server/lib/pi/routes.test.js +24 -0
  65. package/server/lib/pi/session-daemon/DOCUMENTATION.md +1 -0
  66. package/server/lib/pi/session-daemon/pi-runtime-smoke.test.js +466 -0
  67. package/server/lib/pi/ui-settings-store.js +15 -2
  68. package/server/lib/pi/ui-settings-store.test.js +47 -1
  69. package/server/lib/server/core-routes.js +18 -0
  70. package/server/lib/server/linux-distribution.js +47 -0
  71. package/server/lib/server/linux-distribution.test.js +22 -0
  72. package/server/lib/server/runtime-requirements.js +193 -0
  73. package/server/lib/server/runtime-requirements.test.js +295 -0
  74. package/server/lib/server/tunnel-service.DOCUMENTATION.md +1 -1
  75. package/dist/assets/SettingsView-B5nmu8x4.js +0 -2
  76. package/dist/assets/index-BXX8l7mM.css +0 -1
  77. package/dist/assets/renderMobileApp-C29wquBe.js +0 -11
  78. package/dist/assets/runtimeEndpointReset-DHARMv9w.js +0 -53
package/server/index.js CHANGED
@@ -3,7 +3,9 @@ import compression from 'compression';
3
3
  import express from 'express';
4
4
  import fs from 'node:fs';
5
5
  import http from 'node:http';
6
+ import crypto from 'node:crypto';
6
7
  import os from 'node:os';
8
+ import webPush from 'web-push';
7
9
  import path from 'node:path';
8
10
  import { fileURLToPath } from 'node:url';
9
11
 
@@ -13,6 +15,11 @@ import { createRevocationCoordinator } from './lib/client-auth/principal-tracker
13
15
  import { resolvePiChamberDataDir } from './lib/pichamber-data-dir.js';
14
16
  import { createTunnelService } from './lib/server/tunnel-service.js';
15
17
  import { registerPiRuntimeRoutes } from './lib/pi/routes.js';
18
+ import { createDockerInitialLocalSettings, createPiUiSettingsStore } from './lib/pi/ui-settings-store.js';
19
+ import { detectLinuxDistribution } from './lib/server/linux-distribution.js';
20
+ import { createNotificationDeliveryRuntime } from './lib/notifications/delivery-runtime.js';
21
+ import { createPiNotificationWatcher } from './lib/notifications/pi-notification-watcher.js';
22
+ import { registerNotificationRoutes } from './lib/notifications/routes.js';
16
23
  import { registerWorkspaceIntegrations } from './lib/workspace/host.js';
17
24
  import { createPiSessionDaemonSupervisor } from './lib/pi/session-daemon/supervisor.js';
18
25
  import {
@@ -31,6 +38,7 @@ import {
31
38
  } from './lib/server/core-routes.js';
32
39
  import { createTunnelAuth } from './lib/server/tunnel-auth.js';
33
40
  import { createUiAuth } from './lib/ui-auth/ui-auth.js';
41
+ import { assertCurrentRuntimeSupported as defaultAssertCurrentRuntimeSupported } from './lib/server/runtime-requirements.js';
34
42
 
35
43
  const __filename = fileURLToPath(import.meta.url);
36
44
  const __dirname = path.dirname(__filename);
@@ -104,6 +112,11 @@ export async function gracefulShutdown({ exitProcess = false } = {}) {
104
112
  }
105
113
 
106
114
  export async function startWebUiServer(options = {}) {
115
+ // Enforce the actual current runtime before any resource allocation so
116
+ // direct CLI foreground and Electron in-process hosts are checked via the
117
+ // real process versions. Never probe an external Node binary here: under
118
+ // Bun `process.version` emulates Node and must not mask an old Bun.
119
+ defaultAssertCurrentRuntimeSupported();
107
120
  warnIgnoredTunnelOptions(options);
108
121
  const port = Number.isInteger(options.port) && options.port >= 0 ? options.port : DEFAULT_PORT;
109
122
  const host = typeof options.host === 'string' && options.host.trim() ? options.host.trim() : (process.env.PICHAMBER_HOST || '127.0.0.1');
@@ -139,6 +152,18 @@ export async function startWebUiServer(options = {}) {
139
152
  // listen so the profile key uses the bound port; routes observe it through
140
153
  // the getter and report unavailable until it exists.
141
154
  let piSessionDaemonRuntime = null;
155
+ let notificationWatcher = null;
156
+ const uiSettingsStore = createPiUiSettingsStore({
157
+ initialLocalSettings: process.env.PICHAMBER_DEPLOYMENT_KIND === 'docker'
158
+ ? createDockerInitialLocalSettings()
159
+ : {},
160
+ });
161
+ const notificationDelivery = createNotificationDeliveryRuntime({
162
+ dataDir: PICHAMBER_DATA_DIR,
163
+ webPush,
164
+ crypto,
165
+ onDesktopNotification: options.onDesktopNotification,
166
+ });
142
167
  const tunnelService = createTunnelService({
143
168
  dataDir: PICHAMBER_DATA_DIR,
144
169
  getPort: () => {
@@ -174,6 +199,9 @@ export async function startWebUiServer(options = {}) {
174
199
  process,
175
200
  pichamberVersion: PICHAMBER_VERSION,
176
201
  runtimeName: process.env.PICHAMBER_RUNTIME || 'web',
202
+ deploymentKind: process.env.PICHAMBER_DEPLOYMENT_KIND === 'docker' ? 'docker' : 'host',
203
+ serverPlatform: process.platform,
204
+ serverDistribution: detectLinuxDistribution(),
177
205
  serverStartedAt,
178
206
  gracefulShutdown,
179
207
  getHealthSnapshot: () => ({ pi: { state: 'ready' }, apiOnly }),
@@ -201,7 +229,11 @@ export async function startWebUiServer(options = {}) {
201
229
  getServerId: async () => null,
202
230
  getServerLabel: () => os.hostname() || 'PiChamber',
203
231
  });
204
- const piRuntimeRoutes = registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => piSessionDaemonRuntime });
232
+ const piRuntimeRoutes = registerPiRuntimeRoutes(app, {
233
+ getPiSessionDaemonRuntime: () => piSessionDaemonRuntime,
234
+ uiSettingsStore,
235
+ });
236
+ registerNotificationRoutes(app, { uiAuthController, delivery: notificationDelivery });
205
237
  // Cloudflare Tunnel external access (manual token + quick modes).
206
238
  const requireTunnelAuth = (req, res, next) => uiAuthController.requireAuth(req, res, next);
207
239
  app.get('/api/pichamber/tunnel/status', requireTunnelAuth, async (_req, res) => {
@@ -242,12 +274,21 @@ export async function startWebUiServer(options = {}) {
242
274
  profileKey: piSessionDaemonRuntime.paths.profileKey,
243
275
  });
244
276
  }
245
- // Warm the detached daemon as soon as HTTP is listening. Requests arriving
246
- // during cold start share the supervisor's startPromise; server readiness
247
- // itself never waits for provider/model initialization in the child.
248
- void piSessionDaemonRuntime.start().catch((error) => {
249
- console.warn(`[PiSessionDaemon] unavailable: ${error?.code ?? 'DAEMON_UNAVAILABLE'}`);
277
+ // Warm startup creates the daemon credential before subscriptions can read
278
+ // it. The watcher then owns transport retries independently of browsers so
279
+ // native background push keeps working after reconnects.
280
+ notificationWatcher = createPiNotificationWatcher({
281
+ supervisor: piSessionDaemonRuntime,
282
+ uiSettingsStore,
283
+ delivery: notificationDelivery,
250
284
  });
285
+ void piSessionDaemonRuntime.start()
286
+ .catch((error) => {
287
+ console.warn(`[PiSessionDaemon] unavailable: ${error?.code ?? 'DAEMON_UNAVAILABLE'}`);
288
+ })
289
+ .finally(() => {
290
+ if (!stopped) return notificationWatcher?.start();
291
+ });
251
292
  const controller = {
252
293
  expressApp: app,
253
294
  httpServer: server,
@@ -268,6 +309,7 @@ export async function startWebUiServer(options = {}) {
268
309
  liveRevocation.dispose();
269
310
  piRuntimeRoutes.closeEventStreams();
270
311
  await Promise.allSettled([
312
+ notificationWatcher?.stop(),
271
313
  workspaceRuntime.shutdown(),
272
314
  piSessionDaemonRuntime ? piSessionDaemonRuntime.stop() : Promise.resolve(),
273
315
  close(server),
@@ -0,0 +1,39 @@
1
+ # Notifications
2
+
3
+ ## Ownership
4
+
5
+ This module owns server-side notification delivery for Pi session completion and terminal errors.
6
+ It does not model OpenCode questions, permissions, subagents, or tool completion.
7
+
8
+ `pi-notification-watcher.js` maintains one server-owned subscription to the Pi session daemon. A live `busy` or `retry` lifecycle, or an assistant start, opens a turn. The first terminal `idle` emits a completion notification and the first `session.error` or terminal `error` emits an error notification. Duplicate terminal boundaries do nothing. Bootstrap snapshots seed activity but never notify for old settled work. User interruption settles without notifying.
9
+
10
+ The watcher reads `/api/pi/ui-settings` storage before delivery. Notifications require `nativeNotificationsEnabled`; `notifyOnCompletion` and `notifyOnError` gate their respective events.
11
+
12
+ `delivery-runtime.js` fans one generic payload out to:
13
+
14
+ - Electron's native callback when the web server runs inside the desktop app.
15
+ - Browser Web Push subscriptions.
16
+ - Capacitor device tokens through the PiChamber push relay.
17
+
18
+ Payloads contain a fixed completion/error title, the session title when known, an opaque session ID for navigation, and a stable event tag. They never contain prompts, assistant output, tool input/output, provider credentials, or error details.
19
+
20
+ ## Routes
21
+
22
+ `routes.js` registers authenticated endpoints:
23
+
24
+ - `GET /api/push/vapid-public-key`
25
+ - `POST` and `DELETE /api/push/subscribe`
26
+ - `POST` and `DELETE /api/push/apns-token`
27
+ - `POST /api/push/visibility`
28
+
29
+ The persisted `notifications.json` file contains VAPID private material, relay signing keys, browser subscriptions, and native device tokens. It is written atomically with owner-only permissions under the PiChamber data directory. Never log its contents.
30
+
31
+ ## Mobile relay
32
+
33
+ Native iOS and Android registration uses `@capacitor/push-notifications`. The server binds each token to its per-server signing key and sends signed requests to `https://api.pichamber.dev/v1/push/send` by default. Override with `PICHAMBER_PUSH_RELAY_URL`; set `PICHAMBER_PUSH_RELAY_DISABLED=true` to disable native relay delivery.
34
+
35
+ The app suppresses foreground native banners. A recent visible desktop or browser client suppresses native mobile fanout, avoiding a second device alert while the user is already watching the session.
36
+
37
+ ## Failure behavior
38
+
39
+ One failed delivery channel does not block the others. Dead Web Push endpoints are removed after HTTP 404/410. Registration failure is visible to the client. The watcher reconnects to the daemon with its sequence and stream epoch, so replayed terminal events remain deduplicated by the active-turn state.
@@ -0,0 +1,314 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { chmod, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
3
+ import { dirname, join } from 'node:path';
4
+
5
+ import { withCrossProcessLock } from '../server/cross-process-lock.js';
6
+ import { signRelayMessage } from '../relay/signing-key.js';
7
+
8
+ const STORE_VERSION = 1;
9
+ const MAX_ENTRIES_PER_CLIENT = 10;
10
+ const MAX_STORED_ENTRIES = 1_000;
11
+ const VISIBILITY_TTL_MS = 30_000;
12
+ const DEFAULT_RELAY_URL = 'https://api.pichamber.dev/v1/push/send';
13
+
14
+ const emptyStore = () => ({
15
+ version: STORE_VERSION,
16
+ subscriptionsByClient: {},
17
+ nativeTokensByClient: {},
18
+ });
19
+
20
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
21
+
22
+ const boundEntriesByClient = (entriesByClient) => {
23
+ const newest = Object.entries(entriesByClient)
24
+ .flatMap(([clientId, entries]) => (Array.isArray(entries)
25
+ ? entries.map((entry) => ({ clientId, entry }))
26
+ : []))
27
+ .filter(({ entry }) => isRecord(entry))
28
+ .sort((left, right) => (right.entry.updatedAt ?? 0) - (left.entry.updatedAt ?? 0))
29
+ .slice(0, MAX_STORED_ENTRIES);
30
+ const bounded = {};
31
+ for (const { clientId, entry } of newest) {
32
+ (bounded[clientId] ??= []).push(entry);
33
+ }
34
+ return bounded;
35
+ };
36
+
37
+ export const createNotificationDeliveryRuntime = ({
38
+ dataDir,
39
+ webPush,
40
+ crypto,
41
+ fetch: fetchImpl = globalThis.fetch,
42
+ storeFile = join(dataDir, 'notifications.json'),
43
+ relayUrl = process.env.PICHAMBER_PUSH_RELAY_URL || DEFAULT_RELAY_URL,
44
+ onDesktopNotification,
45
+ }) => {
46
+ const visibilityByClient = new Map();
47
+ let initializedWebPush = false;
48
+
49
+ const readStore = async () => {
50
+ try {
51
+ const parsed = JSON.parse(await readFile(storeFile, 'utf8'));
52
+ if (!isRecord(parsed) || parsed.version !== STORE_VERSION) return emptyStore();
53
+ return {
54
+ version: STORE_VERSION,
55
+ subscriptionsByClient: isRecord(parsed.subscriptionsByClient) ? parsed.subscriptionsByClient : {},
56
+ nativeTokensByClient: isRecord(parsed.nativeTokensByClient) ? parsed.nativeTokensByClient : {},
57
+ ...(isRecord(parsed.vapidKeys) ? { vapidKeys: parsed.vapidKeys } : {}),
58
+ ...(isRecord(parsed.relaySigningKey) ? { relaySigningKey: parsed.relaySigningKey } : {}),
59
+ };
60
+ } catch (error) {
61
+ if (error?.code === 'ENOENT') return emptyStore();
62
+ throw error;
63
+ }
64
+ };
65
+
66
+ const writeStore = async (store) => {
67
+ await mkdir(dirname(storeFile), { recursive: true, mode: 0o700 });
68
+ const temporary = `${storeFile}.tmp-${process.pid}-${randomUUID()}`;
69
+ await writeFile(temporary, `${JSON.stringify(store, null, 2)}\n`, { mode: 0o600 });
70
+ await rename(temporary, storeFile);
71
+ if (process.platform !== 'win32') await chmod(storeFile, 0o600);
72
+ };
73
+
74
+ const mutateStore = (mutate) => withCrossProcessLock(`${storeFile}.lock`, async () => {
75
+ const next = await mutate(await readStore());
76
+ await writeStore(next);
77
+ return next;
78
+ });
79
+
80
+ const getOrCreateVapidKeys = async () => {
81
+ const current = await readStore();
82
+ if (typeof current.vapidKeys?.publicKey === 'string' && typeof current.vapidKeys?.privateKey === 'string') {
83
+ return current.vapidKeys;
84
+ }
85
+ const generated = webPush.generateVAPIDKeys();
86
+ const next = await mutateStore((store) => ({ ...store, vapidKeys: store.vapidKeys ?? generated }));
87
+ return next.vapidKeys;
88
+ };
89
+
90
+ const ensureWebPush = async () => {
91
+ if (initializedWebPush) return;
92
+ const keys = await getOrCreateVapidKeys();
93
+ webPush.setVapidDetails('mailto:pichamber@localhost', keys.publicKey, keys.privateKey);
94
+ initializedWebPush = true;
95
+ };
96
+
97
+ const addWebSubscription = async (clientId, input) => {
98
+ await ensureWebPush();
99
+ await mutateStore((store) => {
100
+ const existing = Array.isArray(store.subscriptionsByClient[clientId])
101
+ ? store.subscriptionsByClient[clientId]
102
+ : [];
103
+ const entries = existing.filter((entry) => entry?.endpoint !== input.endpoint);
104
+ entries.unshift({ ...input, updatedAt: Date.now() });
105
+ return {
106
+ ...store,
107
+ subscriptionsByClient: boundEntriesByClient({
108
+ ...store.subscriptionsByClient,
109
+ [clientId]: entries.slice(0, MAX_ENTRIES_PER_CLIENT),
110
+ }),
111
+ };
112
+ });
113
+ };
114
+
115
+ const removeWebSubscription = async (clientId, endpoint) => {
116
+ await mutateStore((store) => {
117
+ const existing = Array.isArray(store.subscriptionsByClient[clientId])
118
+ ? store.subscriptionsByClient[clientId]
119
+ : [];
120
+ const entries = existing.filter((entry) => entry?.endpoint !== endpoint);
121
+ const subscriptionsByClient = { ...store.subscriptionsByClient };
122
+ if (entries.length > 0) subscriptionsByClient[clientId] = entries;
123
+ else delete subscriptionsByClient[clientId];
124
+ return { ...store, subscriptionsByClient };
125
+ });
126
+ };
127
+
128
+ const getOrCreateRelayKey = async () => {
129
+ const current = await readStore();
130
+ if (isRecord(current.relaySigningKey?.privateJwk) && isRecord(current.relaySigningKey?.publicJwk)) {
131
+ return {
132
+ privateKey: crypto.createPrivateKey({ key: current.relaySigningKey.privateJwk, format: 'jwk' }),
133
+ publicJwk: current.relaySigningKey.publicJwk,
134
+ };
135
+ }
136
+ const pair = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' });
137
+ const generated = {
138
+ privateJwk: pair.privateKey.export({ format: 'jwk' }),
139
+ publicJwk: pair.publicKey.export({ format: 'jwk' }),
140
+ };
141
+ const next = await mutateStore((store) => ({ ...store, relaySigningKey: store.relaySigningKey ?? generated }));
142
+ return {
143
+ privateKey: crypto.createPrivateKey({ key: next.relaySigningKey.privateJwk, format: 'jwk' }),
144
+ publicJwk: next.relaySigningKey.publicJwk,
145
+ };
146
+ };
147
+
148
+ const relayPublicJwk = (jwk) => ({ kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y });
149
+
150
+ const registerNativeTokenWithRelay = async (token, platform) => {
151
+ if (!relayUrl || process.env.PICHAMBER_PUSH_RELAY_DISABLED === 'true') return;
152
+ const { privateKey, publicJwk } = await getOrCreateRelayKey();
153
+ const ts = Date.now();
154
+ const sig = signRelayMessage({ crypto }, privateKey, `${ts}.${token}.${platform}`);
155
+ const response = await fetchImpl(relayUrl.replace(/\/send$/, '/register-token'), {
156
+ method: 'POST',
157
+ headers: { 'content-type': 'application/json' },
158
+ body: JSON.stringify({ token, platform, publicKeyJwk: relayPublicJwk(publicJwk), ts, sig }),
159
+ });
160
+ if (!response.ok) throw new Error(`PUSH_RELAY_REGISTRATION_FAILED_${response.status}`);
161
+ };
162
+
163
+ const addNativeToken = async (clientId, input) => {
164
+ await mutateStore((store) => {
165
+ const existing = Array.isArray(store.nativeTokensByClient[clientId])
166
+ ? store.nativeTokensByClient[clientId]
167
+ : [];
168
+ const entries = existing.filter((entry) => entry?.token !== input.token);
169
+ entries.unshift({ ...input, updatedAt: Date.now() });
170
+ return {
171
+ ...store,
172
+ nativeTokensByClient: boundEntriesByClient({
173
+ ...store.nativeTokensByClient,
174
+ [clientId]: entries.slice(0, MAX_ENTRIES_PER_CLIENT),
175
+ }),
176
+ };
177
+ });
178
+ await registerNativeTokenWithRelay(input.token, input.platform);
179
+ };
180
+
181
+ const removeNativeToken = async (clientId, token) => {
182
+ await mutateStore((store) => {
183
+ const existing = Array.isArray(store.nativeTokensByClient[clientId])
184
+ ? store.nativeTokensByClient[clientId]
185
+ : [];
186
+ const entries = existing.filter((entry) => entry?.token !== token);
187
+ const nativeTokensByClient = { ...store.nativeTokensByClient };
188
+ if (entries.length > 0) nativeTokensByClient[clientId] = entries;
189
+ else delete nativeTokensByClient[clientId];
190
+ return { ...store, nativeTokensByClient };
191
+ });
192
+ };
193
+
194
+ const removeNativeTokenFromAllClients = async (token) => {
195
+ await mutateStore((store) => {
196
+ const nativeTokensByClient = {};
197
+ for (const [clientId, entries] of Object.entries(store.nativeTokensByClient)) {
198
+ const kept = Array.isArray(entries) ? entries.filter((entry) => entry?.token !== token) : [];
199
+ if (kept.length > 0) nativeTokensByClient[clientId] = kept;
200
+ }
201
+ return { ...store, nativeTokensByClient };
202
+ });
203
+ };
204
+
205
+ const updateVisibility = (clientId, visible, platform) => {
206
+ visibilityByClient.set(clientId, { visible, platform, updatedAt: Date.now() });
207
+ };
208
+
209
+ const isAnyInteractiveClientVisible = () => {
210
+ const now = Date.now();
211
+ for (const [clientId, state] of visibilityByClient) {
212
+ if (now - state.updatedAt > VISIBILITY_TTL_MS) {
213
+ visibilityByClient.delete(clientId);
214
+ continue;
215
+ }
216
+ if (state.visible && state.platform !== 'ios' && state.platform !== 'android') return true;
217
+ }
218
+ return false;
219
+ };
220
+
221
+ const removeDeadWebEndpoint = async (endpoint) => {
222
+ await mutateStore((store) => {
223
+ const subscriptionsByClient = {};
224
+ for (const [clientId, entries] of Object.entries(store.subscriptionsByClient)) {
225
+ const kept = Array.isArray(entries) ? entries.filter((entry) => entry?.endpoint !== endpoint) : [];
226
+ if (kept.length > 0) subscriptionsByClient[clientId] = kept;
227
+ }
228
+ return { ...store, subscriptionsByClient };
229
+ });
230
+ };
231
+
232
+ const sendWebPush = async (payload) => {
233
+ await ensureWebPush();
234
+ const store = await readStore();
235
+ const byEndpoint = new Map();
236
+ for (const entries of Object.values(store.subscriptionsByClient)) {
237
+ for (const entry of Array.isArray(entries) ? entries : []) {
238
+ if (typeof entry?.endpoint === 'string') byEndpoint.set(entry.endpoint, entry);
239
+ }
240
+ }
241
+ await Promise.all([...byEndpoint.values()].map(async (entry) => {
242
+ try {
243
+ await webPush.sendNotification({
244
+ endpoint: entry.endpoint,
245
+ keys: { p256dh: entry.p256dh, auth: entry.auth },
246
+ }, JSON.stringify(payload));
247
+ } catch (error) {
248
+ if (error?.statusCode === 404 || error?.statusCode === 410) {
249
+ await removeDeadWebEndpoint(entry.endpoint);
250
+ return;
251
+ }
252
+ console.warn(`[Push] delivery failed with status ${error?.statusCode ?? 'unknown'}`);
253
+ }
254
+ }));
255
+ };
256
+
257
+ const sendNativePush = async (payload) => {
258
+ if (!relayUrl || process.env.PICHAMBER_PUSH_RELAY_DISABLED === 'true') return;
259
+ if (isAnyInteractiveClientVisible()) return;
260
+ const store = await readStore();
261
+ const tokens = new Set();
262
+ for (const entries of Object.values(store.nativeTokensByClient)) {
263
+ for (const entry of Array.isArray(entries) ? entries : []) {
264
+ if (typeof entry?.token === 'string') tokens.add(entry.token);
265
+ }
266
+ }
267
+ if (tokens.size === 0) return;
268
+ const list = [...tokens].slice(0, 100);
269
+ const { privateKey, publicJwk } = await getOrCreateRelayKey();
270
+ const ts = Date.now();
271
+ const sig = signRelayMessage({ crypto }, privateKey, `${ts}.${[...list].sort().join(',')}.${payload.title}`);
272
+ const response = await fetchImpl(relayUrl, {
273
+ method: 'POST',
274
+ headers: { 'content-type': 'application/json' },
275
+ body: JSON.stringify({
276
+ tokens: list,
277
+ title: payload.title,
278
+ body: payload.body,
279
+ collapseId: payload.tag?.slice(0, 64),
280
+ data: payload.data,
281
+ publicKeyJwk: relayPublicJwk(publicJwk),
282
+ ts,
283
+ sig,
284
+ }),
285
+ });
286
+ if (!response.ok) {
287
+ console.warn(`[Push relay] delivery failed with status ${response.status}`);
288
+ return;
289
+ }
290
+ const result = await response.json().catch(() => null);
291
+ for (const entry of Array.isArray(result?.results) ? result.results : []) {
292
+ if (entry?.drop === true && typeof entry.token === 'string') {
293
+ await removeNativeTokenFromAllClients(entry.token);
294
+ }
295
+ }
296
+ };
297
+
298
+ const send = async (payload) => {
299
+ const desktop = typeof onDesktopNotification === 'function'
300
+ ? Promise.resolve().then(() => onDesktopNotification(payload))
301
+ : Promise.resolve();
302
+ await Promise.allSettled([desktop, sendWebPush(payload), sendNativePush(payload)]);
303
+ };
304
+
305
+ return {
306
+ getOrCreateVapidKeys,
307
+ addWebSubscription,
308
+ removeWebSubscription,
309
+ addNativeToken,
310
+ removeNativeToken,
311
+ updateVisibility,
312
+ send,
313
+ };
314
+ };
@@ -0,0 +1,85 @@
1
+ import { mkdtemp, readFile, rm, stat } from 'node:fs/promises';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import crypto from 'node:crypto';
5
+ import { afterEach, describe, expect, it, vi } from 'vitest';
6
+
7
+ import { createNotificationDeliveryRuntime } from './delivery-runtime.js';
8
+
9
+ const directories = [];
10
+ afterEach(async () => {
11
+ await Promise.all(directories.splice(0).map((directory) => rm(directory, { recursive: true, force: true })));
12
+ });
13
+
14
+ const setup = async () => {
15
+ const dataDir = await mkdtemp(join(tmpdir(), 'pichamber-notifications-'));
16
+ directories.push(dataDir);
17
+ const sendNotification = vi.fn(async () => undefined);
18
+ const fetch = vi.fn(async () => new Response(JSON.stringify({ results: [] }), { status: 200 }));
19
+ const webPush = {
20
+ generateVAPIDKeys: vi.fn(() => ({ publicKey: 'public-key', privateKey: 'private-key' })),
21
+ setVapidDetails: vi.fn(),
22
+ sendNotification,
23
+ };
24
+ return {
25
+ dataDir,
26
+ fetch,
27
+ sendNotification,
28
+ runtime: createNotificationDeliveryRuntime({ dataDir, webPush, crypto, fetch }),
29
+ };
30
+ };
31
+
32
+ describe('notification delivery runtime', () => {
33
+ it('persists subscriptions privately and fans out one terminal event', async () => {
34
+ const { dataDir, fetch, runtime, sendNotification } = await setup();
35
+ await runtime.addWebSubscription('client-1', {
36
+ endpoint: 'https://push.example/subscription',
37
+ p256dh: 'p256dh',
38
+ auth: 'auth',
39
+ platform: 'web',
40
+ });
41
+ await runtime.addNativeToken('client-1', {
42
+ token: 'native-token',
43
+ platform: 'ios',
44
+ environment: 'production',
45
+ });
46
+
47
+ await runtime.send({
48
+ title: 'Work completed',
49
+ body: 'Session',
50
+ tag: 'pichamber:completion:s1:7',
51
+ data: { type: 'completion', sessionId: 's1' },
52
+ });
53
+
54
+ expect(sendNotification).toHaveBeenCalledTimes(1);
55
+ expect(fetch).toHaveBeenCalledTimes(2);
56
+ expect(fetch.mock.calls[0][0]).toMatch(/register-token$/);
57
+ expect(fetch.mock.calls[1][0]).toMatch(/\/send$/);
58
+ const stored = JSON.parse(await readFile(join(dataDir, 'notifications.json'), 'utf8'));
59
+ expect(stored.subscriptionsByClient['client-1']).toHaveLength(1);
60
+ expect(stored.nativeTokensByClient['client-1']).toHaveLength(1);
61
+ if (process.platform !== 'win32') {
62
+ expect((await stat(join(dataDir, 'notifications.json'))).mode & 0o777).toBe(0o600);
63
+ }
64
+ });
65
+
66
+ it('suppresses native fanout while an interactive client is visible', async () => {
67
+ const { fetch, runtime } = await setup();
68
+ await runtime.addNativeToken('mobile', {
69
+ token: 'native-token',
70
+ platform: 'ios',
71
+ environment: 'production',
72
+ });
73
+ runtime.updateVisibility('desktop', true, 'desktop');
74
+
75
+ await runtime.send({
76
+ title: 'Work failed',
77
+ body: 'Session',
78
+ tag: 'pichamber:error:s1:9',
79
+ data: { type: 'error', sessionId: 's1' },
80
+ });
81
+
82
+ expect(fetch).toHaveBeenCalledTimes(1);
83
+ expect(fetch.mock.calls[0][0]).toMatch(/register-token$/);
84
+ });
85
+ });