@lelouchhe/webagent 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  // Image attach, preview, and paste handling
2
2
 
3
- import { state, dom } from './state.mmk25uhc.js';
3
+ import { state, dom } from './state.mmlj9sk2.js';
4
4
 
5
5
  function readFileAsBase64(file) {
6
6
  return new Promise((resolve) => {
@@ -3,10 +3,14 @@
3
3
  import {
4
4
  state, dom, setBusy, sendCancel,
5
5
  getConfigOption, getConfigValue, updateNewBtnVisibility,
6
- } from './state.mmk25uhc.js';
7
- import { addMessage, addSystem, addBashBlock, showWaiting } from './render.mmk25uhc.js';
8
- import { handleSlashCommand, hideSlashMenu, handleSlashMenuKey, updateSlashMenu } from './commands.mmk25uhc.js';
9
- import { renderAttachPreview } from './images.mmk25uhc.js';
6
+ } from './state.mmlj9sk2.js';
7
+ import { addMessage, addSystem, addBashBlock, showWaiting } from './render.mmlj9sk2.js';
8
+ import { handleSlashCommand, hideSlashMenu, handleSlashMenuKey, updateSlashMenu } from './commands.mmlj9sk2.js';
9
+ import { renderAttachPreview } from './images.mmlj9sk2.js';
10
+
11
+ function wsReady() {
12
+ return state.ws && state.ws.readyState === 1;
13
+ }
10
14
 
11
15
  // Wire up cancel-timeout feedback (state.js cannot import render.js directly)
12
16
  state._onCancelTimeout = () => addSystem('warn: Agent not responding to cancel');
@@ -32,6 +36,10 @@ function sendMessage() {
32
36
  addSystem('warn: Session not ready yet, please wait…');
33
37
  return;
34
38
  }
39
+ if (!wsReady()) {
40
+ addSystem('warn: Not connected, please retry');
41
+ return;
42
+ }
35
43
  dom.input.value = '';
36
44
  dom.input.style.height = 'auto';
37
45
  dom.inputArea.classList.remove('bash-mode');
@@ -55,6 +63,11 @@ function sendMessage() {
55
63
  return;
56
64
  }
57
65
 
66
+ if (!wsReady()) {
67
+ addSystem('warn: Not connected, please retry');
68
+ return;
69
+ }
70
+
58
71
  // Show user message with image thumbnails
59
72
  const msgEl = addMessage('user', text || '(image)');
60
73
  for (const img of state.pendingImages) {
@@ -77,6 +90,12 @@ function sendMessage() {
77
90
  body: JSON.stringify({ data: img.data, mimeType: img.mimeType }),
78
91
  }).then(r => r.json()).then(j => ({ data: img.data, mimeType: img.mimeType, path: j.path }))
79
92
  )).then(uploaded => {
93
+ if (!wsReady()) {
94
+ msgEl.remove();
95
+ addSystem('warn: Not connected, please retry');
96
+ setBusy(false);
97
+ return;
98
+ }
80
99
  state.ws.send(JSON.stringify({ type: 'prompt', sessionId: state.sessionId, text: text || 'What is in this image?', images: uploaded }));
81
100
  });
82
101
  } else {
@@ -1,6 +1,6 @@
1
1
  // Rendering functions, theme, markdown, bash UI
2
2
 
3
- import { dom, state } from './state.mmk25uhc.js';
3
+ import { dom, state } from './state.mmlj9sk2.js';
4
4
 
5
5
  // --- Markdown ---
6
6
  marked.setOptions({ breaks: true, gfm: true });
@@ -43,6 +43,7 @@ export const state = {
43
43
  lastEventSeq: 0,
44
44
  replayInProgress: false,
45
45
  replayQueue: [],
46
+ unconfirmedPermissions: new Map(),
46
47
  };
47
48
 
48
49
  const CONNECTION_STATUS_CLASSES = {
@@ -112,6 +113,7 @@ export function resetSessionUI() {
112
113
  state.followMessages = true;
113
114
  state.pendingToolCallIds.clear();
114
115
  state.pendingPermissionRequestIds.clear();
116
+ state.unconfirmedPermissions.clear();
115
117
  state.pendingPromptDone = false;
116
118
  state.turnEnded = false;
117
119
  state._cancelTimerId = null;
package/dist/sw.js CHANGED
@@ -1,5 +1,51 @@
1
- // Minimal service worker for PWA installability.
1
+ // Minimal service worker for PWA installability + push notifications.
2
2
  // No offline caching — app requires WebSocket connection.
3
3
 
4
4
  self.addEventListener('install', () => self.skipWaiting());
5
5
  self.addEventListener('activate', (e) => e.waitUntil(self.clients.claim()));
6
+
7
+ // --- Push notifications ---
8
+
9
+ self.addEventListener('push', (e) => {
10
+ if (!e.data) return;
11
+
12
+ let payload;
13
+ try {
14
+ payload = e.data.json();
15
+ } catch {
16
+ return;
17
+ }
18
+
19
+ const { title, body, data } = payload;
20
+ e.waitUntil(
21
+ self.registration.showNotification(title || 'WebAgent', {
22
+ body: body || '',
23
+ icon: '/icon-192.png',
24
+ badge: '/icon-192.png',
25
+ tag: data?.sessionId || 'default',
26
+ data: data || {},
27
+ })
28
+ );
29
+ });
30
+
31
+ self.addEventListener('notificationclick', (e) => {
32
+ e.notification.close();
33
+
34
+ const sessionId = e.notification.data?.sessionId;
35
+ const urlHash = sessionId ? `/#${sessionId}` : '/';
36
+
37
+ e.waitUntil(
38
+ self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clients) => {
39
+ // Focus existing window if open
40
+ for (const client of clients) {
41
+ if (client.url.includes(self.location.origin)) {
42
+ client.focus();
43
+ client.postMessage({ type: 'navigate', sessionId });
44
+ return;
45
+ }
46
+ }
47
+ // Otherwise open a new window
48
+ return self.clients.openWindow(urlHash);
49
+ })
50
+ );
51
+ });
package/lib/config.js CHANGED
@@ -16,6 +16,11 @@ const ConfigSchema = z.object({
16
16
  image_upload: 10_485_760,
17
17
  cancel_timeout: 10_000,
18
18
  }),
19
+ push: z.object({
20
+ vapid_subject: z.string().default("mailto:webagent@localhost"),
21
+ }).default({
22
+ vapid_subject: "mailto:webagent@localhost",
23
+ }),
19
24
  });
20
25
  let _config = null;
21
26
  function parseArgs() {
package/lib/daemon.js ADDED
@@ -0,0 +1,278 @@
1
+ import { spawn } from "node:child_process";
2
+ import { closeSync, existsSync, openSync, readFileSync, unlinkSync, writeFileSync, } from "node:fs";
3
+ import { dirname, isAbsolute, join, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ const __dirname = dirname(fileURLToPath(import.meta.url));
6
+ // ---------------------------------------------------------------------------
7
+ // Constants
8
+ // ---------------------------------------------------------------------------
9
+ const PID_FILE = "webagent.pid";
10
+ const LOG_FILE = "webagent.log";
11
+ const RESTART_DELAY_INITIAL = 1_000;
12
+ const RESTART_DELAY_MAX = 30_000;
13
+ const STABLE_THRESHOLD_MS = 60_000;
14
+ const KILL_GRACE_MS = 5_000;
15
+ const SUBCOMMANDS = ["start", "stop", "status", "restart"];
16
+ /** Read and validate the PID file at `filePath`. Returns null if missing or stale. */
17
+ export function readPidInfo(filePath) {
18
+ if (!existsSync(filePath))
19
+ return null;
20
+ try {
21
+ const info = JSON.parse(readFileSync(filePath, "utf8"));
22
+ if (typeof info.pid !== "number" || !Number.isFinite(info.pid))
23
+ return null;
24
+ process.kill(info.pid, 0); // existence check — throws if dead
25
+ return info;
26
+ }
27
+ catch {
28
+ // Process is dead or file corrupt — clean up
29
+ try {
30
+ unlinkSync(filePath);
31
+ }
32
+ catch { /* ignore */ }
33
+ return null;
34
+ }
35
+ }
36
+ /** Write PID info to `filePath`. */
37
+ export function writePidInfo(filePath, info) {
38
+ writeFileSync(filePath, JSON.stringify(info) + "\n");
39
+ }
40
+ // ---------------------------------------------------------------------------
41
+ // Arg helpers
42
+ // ---------------------------------------------------------------------------
43
+ export function isSubcommand(arg) {
44
+ return SUBCOMMANDS.includes(arg);
45
+ }
46
+ /** Resolve relative `--config` values to absolute paths (based on cwd). */
47
+ export function resolveArgs(args) {
48
+ const result = [...args];
49
+ for (let i = 0; i < result.length; i++) {
50
+ if (result[i] === "--config" && i + 1 < result.length && !isAbsolute(result[i + 1])) {
51
+ result[i + 1] = resolve(result[i + 1]);
52
+ }
53
+ }
54
+ return result;
55
+ }
56
+ // ---------------------------------------------------------------------------
57
+ // Command dispatch
58
+ // ---------------------------------------------------------------------------
59
+ export async function run(command, args) {
60
+ const pidFile = join(process.cwd(), PID_FILE);
61
+ const logFile = join(process.cwd(), LOG_FILE);
62
+ switch (command) {
63
+ case "start": return cmdStart(pidFile, logFile, args);
64
+ case "stop": return cmdStop(pidFile);
65
+ case "status": return cmdStatus(pidFile, logFile);
66
+ case "restart": return cmdRestart(pidFile, logFile);
67
+ }
68
+ }
69
+ // ---------------------------------------------------------------------------
70
+ // Commands
71
+ // ---------------------------------------------------------------------------
72
+ async function cmdStart(pidFile, logFile, args) {
73
+ const existing = readPidInfo(pidFile);
74
+ if (existing) {
75
+ console.log(`webagent is already running (pid ${existing.pid})`);
76
+ process.exitCode = 1;
77
+ return;
78
+ }
79
+ const serverJs = join(__dirname, "server.js");
80
+ if (!existsSync(serverJs)) {
81
+ console.error(`server not found: ${serverJs}`);
82
+ console.error('run "npx tsc -p tsconfig.build.json" first if developing from source');
83
+ process.exitCode = 1;
84
+ return;
85
+ }
86
+ const resolved = resolveArgs(args);
87
+ const daemonJs = join(__dirname, "daemon.js");
88
+ const log = openSync(logFile, "a");
89
+ const child = spawn(process.execPath, [daemonJs, "__supervisor", ...resolved], { detached: true, stdio: ["ignore", log, log], cwd: process.cwd() });
90
+ child.unref();
91
+ closeSync(log);
92
+ // Poll for PID file (supervisor writes it on startup)
93
+ for (let i = 0; i < 6; i++) {
94
+ await sleep(500);
95
+ const info = readPidInfo(pidFile);
96
+ if (info) {
97
+ console.log(`webagent started (pid ${info.pid})`);
98
+ console.log(`log: ${logFile}`);
99
+ return;
100
+ }
101
+ }
102
+ console.error("webagent failed to start");
103
+ console.error(`check log: ${logFile}`);
104
+ process.exitCode = 1;
105
+ }
106
+ async function cmdStop(pidFile) {
107
+ const info = readPidInfo(pidFile);
108
+ if (!info) {
109
+ console.log("webagent is not running");
110
+ return;
111
+ }
112
+ try {
113
+ process.kill(info.pid, "SIGTERM");
114
+ }
115
+ catch {
116
+ console.log("webagent is not running (stale pid file removed)");
117
+ try {
118
+ unlinkSync(pidFile);
119
+ }
120
+ catch { /* ignore */ }
121
+ return;
122
+ }
123
+ // Wait for exit
124
+ const deadline = Date.now() + 10_000;
125
+ while (Date.now() < deadline) {
126
+ await sleep(300);
127
+ try {
128
+ process.kill(info.pid, 0);
129
+ }
130
+ catch {
131
+ // Gone — supervisor cleans up PID file, but be safe
132
+ try {
133
+ unlinkSync(pidFile);
134
+ }
135
+ catch { /* ignore */ }
136
+ console.log("webagent stopped");
137
+ return;
138
+ }
139
+ }
140
+ console.error(`webagent (pid ${info.pid}) did not stop within 10s`);
141
+ console.error(`try: kill -9 ${info.pid}`);
142
+ process.exitCode = 1;
143
+ }
144
+ async function cmdStatus(pidFile, logFile) {
145
+ const info = readPidInfo(pidFile);
146
+ if (!info) {
147
+ console.log("webagent is not running");
148
+ return;
149
+ }
150
+ const uptimeMs = Date.now() - new Date(info.started).getTime();
151
+ const h = Math.floor(uptimeMs / 3_600_000);
152
+ const m = Math.floor((uptimeMs % 3_600_000) / 60_000);
153
+ console.log(`webagent is running (pid ${info.pid})`);
154
+ console.log(` started: ${info.started}`);
155
+ console.log(` uptime: ${h}h ${m}m`);
156
+ console.log(` args: ${info.args.join(" ") || "(none)"}`);
157
+ console.log(` log: ${logFile}`);
158
+ }
159
+ async function cmdRestart(pidFile, logFile) {
160
+ const info = readPidInfo(pidFile);
161
+ if (!info) {
162
+ console.log("webagent is not running");
163
+ process.exitCode = 1;
164
+ return;
165
+ }
166
+ if (process.platform === "win32") {
167
+ // No SIGHUP on Windows — fall back to stop + start (non-atomic)
168
+ await cmdStop(pidFile);
169
+ await cmdStart(pidFile, logFile, info.args);
170
+ return;
171
+ }
172
+ // Unix: atomic restart via SIGHUP to supervisor
173
+ try {
174
+ process.kill(info.pid, "SIGHUP");
175
+ }
176
+ catch {
177
+ console.error(`failed to signal webagent (pid ${info.pid})`);
178
+ process.exitCode = 1;
179
+ return;
180
+ }
181
+ // Wait briefly and verify
182
+ await sleep(2000);
183
+ const newInfo = readPidInfo(pidFile);
184
+ if (newInfo) {
185
+ console.log(`webagent restarted (pid ${newInfo.pid})`);
186
+ }
187
+ else {
188
+ console.error("webagent may have failed to restart");
189
+ console.error(`check log: ${logFile}`);
190
+ process.exitCode = 1;
191
+ }
192
+ }
193
+ // ---------------------------------------------------------------------------
194
+ // Supervisor (internal — launched by `start` as a detached process)
195
+ // ---------------------------------------------------------------------------
196
+ function runSupervisor(serverArgs) {
197
+ const serverJs = join(__dirname, "server.js");
198
+ const pidFile = join(process.cwd(), PID_FILE);
199
+ writePidInfo(pidFile, { pid: process.pid, args: serverArgs, started: new Date().toISOString() });
200
+ let child = null;
201
+ let stopping = false;
202
+ let lastStart = 0;
203
+ let delay = RESTART_DELAY_INITIAL;
204
+ let timer = null;
205
+ function spawnServer() {
206
+ lastStart = Date.now();
207
+ child = spawn(process.execPath, [serverJs, ...serverArgs], { stdio: "inherit" });
208
+ child.on("exit", onChildExit);
209
+ }
210
+ function onChildExit(code, signal) {
211
+ child = null;
212
+ if (stopping)
213
+ return;
214
+ if (Date.now() - lastStart > STABLE_THRESHOLD_MS) {
215
+ delay = RESTART_DELAY_INITIAL;
216
+ }
217
+ else {
218
+ delay = Math.min(delay * 2, RESTART_DELAY_MAX);
219
+ }
220
+ console.log(`[supervisor] server exited (code=${code} signal=${signal}), restarting in ${delay}ms`);
221
+ timer = setTimeout(spawnServer, delay);
222
+ }
223
+ function killChild() {
224
+ if (timer) {
225
+ clearTimeout(timer);
226
+ timer = null;
227
+ }
228
+ return new Promise((resolve) => {
229
+ if (!child) {
230
+ resolve();
231
+ return;
232
+ }
233
+ const c = child;
234
+ c.once("exit", () => resolve());
235
+ c.kill("SIGTERM");
236
+ setTimeout(() => { try {
237
+ c.kill("SIGKILL");
238
+ }
239
+ catch { /* ignore */ } }, KILL_GRACE_MS);
240
+ });
241
+ }
242
+ async function shutdown() {
243
+ if (stopping)
244
+ return;
245
+ stopping = true;
246
+ await killChild();
247
+ try {
248
+ unlinkSync(pidFile);
249
+ }
250
+ catch { /* ignore */ }
251
+ process.exit(0);
252
+ }
253
+ process.on("SIGTERM", () => { shutdown(); });
254
+ process.on("SIGINT", () => { shutdown(); });
255
+ if (process.platform !== "win32") {
256
+ process.on("SIGHUP", async () => {
257
+ console.log("[supervisor] SIGHUP received, restarting server");
258
+ delay = RESTART_DELAY_INITIAL;
259
+ await killChild();
260
+ if (!stopping)
261
+ spawnServer();
262
+ });
263
+ }
264
+ console.log(`[supervisor] started (pid ${process.pid})`);
265
+ spawnServer();
266
+ }
267
+ // ---------------------------------------------------------------------------
268
+ // Utility
269
+ // ---------------------------------------------------------------------------
270
+ function sleep(ms) {
271
+ return new Promise((r) => setTimeout(r, ms));
272
+ }
273
+ // ---------------------------------------------------------------------------
274
+ // Direct execution: node daemon.js __supervisor [server args...]
275
+ // ---------------------------------------------------------------------------
276
+ if (process.argv[2] === "__supervisor") {
277
+ runSupervisor(process.argv.slice(3));
278
+ }
@@ -0,0 +1,95 @@
1
+ import { broadcast } from "./ws-handler.js";
2
+ export function handleAgentEvent(event, sessions, store, wss, bridge, config, pushService) {
3
+ if ("sessionId" in event && event.sessionId && sessions.restoringSessions.has(event.sessionId))
4
+ return;
5
+ switch (event.type) {
6
+ case "connected":
7
+ event.cancelTimeout = config.cancelTimeout;
8
+ break;
9
+ case "session_created":
10
+ if (event.configOptions?.length)
11
+ sessions.cachedConfigOptions = event.configOptions;
12
+ for (const opt of event.configOptions ?? []) {
13
+ store.updateSessionConfig(event.sessionId, opt.id, opt.currentValue);
14
+ }
15
+ break;
16
+ case "config_option_update":
17
+ if (event.configOptions?.length)
18
+ sessions.cachedConfigOptions = event.configOptions;
19
+ for (const opt of event.configOptions ?? []) {
20
+ store.updateSessionConfig(event.sessionId, opt.id, opt.currentValue);
21
+ }
22
+ break;
23
+ case "message_chunk":
24
+ sessions.flushThinkingBuffer(event.sessionId);
25
+ sessions.appendAssistant(event.sessionId, event.text);
26
+ break;
27
+ case "thought_chunk":
28
+ sessions.flushAssistantBuffer(event.sessionId);
29
+ sessions.appendThinking(event.sessionId, event.text);
30
+ break;
31
+ case "tool_call":
32
+ sessions.flushBuffers(event.sessionId);
33
+ store.saveEvent(event.sessionId, event.type, { id: event.id, title: event.title, kind: event.kind, rawInput: event.rawInput });
34
+ break;
35
+ case "tool_call_update":
36
+ store.saveEvent(event.sessionId, event.type, { id: event.id, status: event.status, content: event.content });
37
+ break;
38
+ case "plan":
39
+ sessions.flushBuffers(event.sessionId);
40
+ store.saveEvent(event.sessionId, event.type, { entries: event.entries });
41
+ break;
42
+ case "permission_request": {
43
+ sessions.flushBuffers(event.sessionId);
44
+ store.saveEvent(event.sessionId, event.type, {
45
+ requestId: event.requestId, title: event.title, options: event.options,
46
+ });
47
+ // Auto-approve permissions in autopilot mode (allow_once only to avoid persisting across mode switches)
48
+ const mode = store.getSession(event.sessionId)?.mode ?? "";
49
+ if (mode.includes("#autopilot")) {
50
+ const opt = event.options.find((o) => o.kind === "allow_once");
51
+ if (opt) {
52
+ bridge.resolvePermission(event.requestId, opt.optionId);
53
+ const optionName = opt.label ?? opt.optionId;
54
+ store.saveEvent(event.sessionId, "permission_response", {
55
+ requestId: event.requestId, optionName, denied: false,
56
+ });
57
+ broadcast(wss, {
58
+ type: "permission_resolved",
59
+ sessionId: event.sessionId,
60
+ requestId: event.requestId,
61
+ optionName,
62
+ denied: false,
63
+ });
64
+ return;
65
+ }
66
+ }
67
+ break;
68
+ }
69
+ case "prompt_done":
70
+ sessions.activePrompts.delete(event.sessionId);
71
+ sessions.flushBuffers(event.sessionId);
72
+ store.saveEvent(event.sessionId, event.type, { stopReason: event.stopReason });
73
+ break;
74
+ case "error":
75
+ if (event.sessionId) {
76
+ sessions.activePrompts.delete(event.sessionId);
77
+ }
78
+ break;
79
+ }
80
+ broadcast(wss, event);
81
+ // Push notification check (after broadcast so WS clients get the event first)
82
+ if (pushService && "sessionId" in event && event.sessionId) {
83
+ const session = store.getSession(event.sessionId);
84
+ const eventData = {};
85
+ if (event.type === "permission_request") {
86
+ eventData.description = event.title;
87
+ }
88
+ if (pushService.maybeNotify(event.sessionId, session?.title ?? null, event.type, eventData)) {
89
+ const notification = pushService.formatNotification(event.sessionId, session?.title ?? null, event.type, eventData);
90
+ pushService.sendToAll(notification).catch((err) => {
91
+ console.error("[push] failed to send:", err);
92
+ });
93
+ }
94
+ }
95
+ }
@@ -0,0 +1,112 @@
1
+ import webpush from "web-push";
2
+ import { chmodSync, existsSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ const VAPID_FILE = "vapid.json";
5
+ export class PushService {
6
+ store;
7
+ vapidKeys;
8
+ clientVisibility = new Map(); // clientId → visible
9
+ constructor(store, dataDir, vapidSubject) {
10
+ this.store = store;
11
+ this.vapidKeys = this.loadOrGenerateKeys(dataDir);
12
+ webpush.setVapidDetails(vapidSubject, this.vapidKeys.publicKey, this.vapidKeys.privateKey);
13
+ }
14
+ // ---------------------------------------------------------------------------
15
+ // VAPID keys
16
+ // ---------------------------------------------------------------------------
17
+ loadOrGenerateKeys(dataDir) {
18
+ const filePath = join(dataDir, VAPID_FILE);
19
+ if (existsSync(filePath)) {
20
+ chmodSync(filePath, 0o600);
21
+ const keys = JSON.parse(readFileSync(filePath, "utf8"));
22
+ console.log("[push] loaded VAPID keys");
23
+ return keys;
24
+ }
25
+ const keys = webpush.generateVAPIDKeys();
26
+ writeFileSync(filePath, JSON.stringify(keys, null, 2) + "\n", { mode: 0o600 });
27
+ console.log("[push] generated new VAPID keys");
28
+ return keys;
29
+ }
30
+ getPublicKey() {
31
+ return this.vapidKeys.publicKey;
32
+ }
33
+ // ---------------------------------------------------------------------------
34
+ // Notification formatting
35
+ // ---------------------------------------------------------------------------
36
+ formatNotification(sessionId, sessionTitle, eventType, eventData) {
37
+ const title = sessionTitle ? `WebAgent · ${sessionTitle}` : "WebAgent";
38
+ let body;
39
+ switch (eventType) {
40
+ case "permission_request":
41
+ body = `⚿ ${eventData.description ?? "Permission requested"}`;
42
+ break;
43
+ case "prompt_done":
44
+ body = "✓ Task complete";
45
+ break;
46
+ case "bash_done": {
47
+ const cmd = eventData.command ?? "command";
48
+ const code = eventData.exitCode ?? "?";
49
+ body = `$ ${cmd} — exit ${code}`;
50
+ break;
51
+ }
52
+ default:
53
+ body = eventType;
54
+ }
55
+ return { title, body, data: { sessionId } };
56
+ }
57
+ // ---------------------------------------------------------------------------
58
+ // Client visibility tracking
59
+ // ---------------------------------------------------------------------------
60
+ setClientVisibility(clientId, visible) {
61
+ this.clientVisibility.set(clientId, visible);
62
+ }
63
+ removeClient(clientId) {
64
+ this.clientVisibility.delete(clientId);
65
+ }
66
+ hasVisibleClient() {
67
+ for (const visible of this.clientVisibility.values()) {
68
+ if (visible)
69
+ return true;
70
+ }
71
+ return false;
72
+ }
73
+ // ---------------------------------------------------------------------------
74
+ // High-level: decide whether to push, and if so, send
75
+ // ---------------------------------------------------------------------------
76
+ static NOTIFIABLE = new Set(["permission_request", "prompt_done", "bash_done"]);
77
+ /**
78
+ * Check if this event should trigger a push notification.
79
+ * Returns true if a notification was queued (caller should then call sendToAll).
80
+ */
81
+ maybeNotify(sessionId, sessionTitle, eventType, eventData) {
82
+ if (!PushService.NOTIFIABLE.has(eventType))
83
+ return false;
84
+ if (this.hasVisibleClient())
85
+ return false;
86
+ return true;
87
+ }
88
+ // ---------------------------------------------------------------------------
89
+ // Send push to all subscriptions
90
+ // ---------------------------------------------------------------------------
91
+ async sendToAll(notification) {
92
+ const subs = this.store.getAllSubscriptions();
93
+ if (subs.length === 0)
94
+ return;
95
+ const payload = JSON.stringify(notification);
96
+ const results = await Promise.allSettled(subs.map((sub) => webpush.sendNotification({ endpoint: sub.endpoint, keys: { auth: sub.auth, p256dh: sub.p256dh } }, payload)));
97
+ for (let i = 0; i < results.length; i++) {
98
+ const result = results[i];
99
+ if (result.status === "rejected") {
100
+ const err = result.reason;
101
+ if (err.statusCode === 410) {
102
+ // Subscription expired — clean up
103
+ this.store.removeSubscription(subs[i].endpoint);
104
+ console.log(`[push] removed expired subscription: ${subs[i].endpoint}`);
105
+ }
106
+ else {
107
+ console.error(`[push] send failed for ${subs[i].endpoint}:`, result.reason);
108
+ }
109
+ }
110
+ }
111
+ }
112
+ }