dsh-bark-push 0.2.2 → 0.3.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.
- package/CHANGELOG.md +15 -0
- package/README.md +55 -12
- package/cordis.patch.yml +12 -0
- package/docs/browser-notifications-design.md +691 -0
- package/docs/settings-0.3.0.png +0 -0
- package/docs/settings-browser-persistence-mobile.png +0 -0
- package/docs/settings-browser-persistence.png +0 -0
- package/lib/browser-notify.js +396 -0
- package/lib/client.js +270 -11
- package/lib/config.js +60 -0
- package/lib/events.js +21 -5
- package/lib/http.js +33 -4
- package/lib/index.js +25 -5
- package/lib/state.js +51 -7
- package/lib/ui.js +885 -182
- package/package.json +6 -4
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host-side browser notification event bus.
|
|
3
|
+
*
|
|
4
|
+
* The browser channel is deliberately independent from Bark: it owns its own
|
|
5
|
+
* switches, mute policy, templates, and in-memory SSE subscribers. A missing
|
|
6
|
+
* Bark server or Device Key therefore never suppresses a browser notification.
|
|
7
|
+
*
|
|
8
|
+
* @module dsh-bark-push/browser-notify
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import {
|
|
12
|
+
BROWSER_BODY_TEMPLATES,
|
|
13
|
+
BROWSER_TEMPLATE_KEYS,
|
|
14
|
+
} from './config.js';
|
|
15
|
+
import { markdownToText, summarize, truncate } from './format.js';
|
|
16
|
+
import { hashValue } from './notifier.js';
|
|
17
|
+
import { TtlSet } from './ttl-set.js';
|
|
18
|
+
|
|
19
|
+
/** Browser notification status labels used by the default templates. */
|
|
20
|
+
export const BROWSER_STATUS = Object.freeze({
|
|
21
|
+
reply: '回复完成',
|
|
22
|
+
approval: '需要批准',
|
|
23
|
+
question: '等待选择',
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
/** Placeholder syntax accepted by browser notification body templates. */
|
|
27
|
+
const PLACEHOLDER_PATTERN = /\{([A-Za-z][A-Za-z0-9]*)\}/g;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Replace known `{name}` placeholders in one body template. Unknown
|
|
31
|
+
* placeholders stay literal so a typo is visible instead of silently dropping
|
|
32
|
+
* the surrounding text.
|
|
33
|
+
* @param {string} template - body template.
|
|
34
|
+
* @param {Record<string, string>} values - replacement values.
|
|
35
|
+
* @returns {string} rendered body.
|
|
36
|
+
*/
|
|
37
|
+
export function renderBrowserTemplate(template, values) {
|
|
38
|
+
return String(template ?? '').replace(PLACEHOLDER_PATTERN, (match, name) =>
|
|
39
|
+
Object.prototype.hasOwnProperty.call(values, name) ? String(values[name] ?? '') : match,
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Whether a Session is a delegated child.
|
|
45
|
+
* @param {unknown} session - Session-like object.
|
|
46
|
+
* @returns {boolean} true for subagent Sessions.
|
|
47
|
+
*/
|
|
48
|
+
function isSubagentSession(session) {
|
|
49
|
+
const header = session !== null && typeof session === 'object' ? session.header : undefined;
|
|
50
|
+
if (header === null || typeof header !== 'object') return false;
|
|
51
|
+
if (header.origin === 'subagent') return true;
|
|
52
|
+
return Number.isFinite(header.delegationDepth) && Number(header.delegationDepth) > 0;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Pick a bounded, readable first question from a question batch.
|
|
57
|
+
* @param {unknown} questions - question array.
|
|
58
|
+
* @returns {string} question text.
|
|
59
|
+
*/
|
|
60
|
+
function firstQuestionText(questions) {
|
|
61
|
+
const list = Array.isArray(questions) ? questions : [];
|
|
62
|
+
for (const item of list) {
|
|
63
|
+
if (item === null || typeof item !== 'object') continue;
|
|
64
|
+
const question = typeof item.question === 'string' ? item.question.trim() : '';
|
|
65
|
+
if (question.length > 0) return question.replace(/\s+/g, ' ');
|
|
66
|
+
const header = typeof item.header === 'string' ? item.header.trim() : '';
|
|
67
|
+
if (header.length > 0) return header.replace(/\s+/g, ' ');
|
|
68
|
+
}
|
|
69
|
+
return '需要你的选择';
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Build one browser-notification event.
|
|
74
|
+
* @param {'reply'|'approval'|'question'} kind - event kind.
|
|
75
|
+
* @param {object} input - event material.
|
|
76
|
+
* @param {Record<string, unknown>} config - effective config.
|
|
77
|
+
* @param {object} notifier - Notifier helper facade.
|
|
78
|
+
* @returns {object|null} event payload, or null when no usable session id exists.
|
|
79
|
+
*/
|
|
80
|
+
export function buildBrowserNotification(kind, input, config, notifier) {
|
|
81
|
+
const sessionId = typeof input?.sessionId === 'string' ? input.sessionId : '';
|
|
82
|
+
if (sessionId.length === 0) return null;
|
|
83
|
+
const session = input.session;
|
|
84
|
+
if (isSubagentSession(session)) return null;
|
|
85
|
+
|
|
86
|
+
const status = BROWSER_STATUS[kind];
|
|
87
|
+
const sessionTitle = truncate(
|
|
88
|
+
notifier?.sessionTitleFor?.(session ?? { header: { id: sessionId } }, input.sessionTitle) || '当前会话',
|
|
89
|
+
120,
|
|
90
|
+
);
|
|
91
|
+
|
|
92
|
+
let summary = '';
|
|
93
|
+
let tool = '';
|
|
94
|
+
let reason = '';
|
|
95
|
+
let question = '';
|
|
96
|
+
let questionCount = '';
|
|
97
|
+
let description = '';
|
|
98
|
+
|
|
99
|
+
if (kind === 'reply') {
|
|
100
|
+
summary = summarize(markdownToText(input.text), 60) || '已生成回复';
|
|
101
|
+
description = summary;
|
|
102
|
+
} else if (kind === 'approval') {
|
|
103
|
+
tool = truncate(String(input.toolName ?? '').trim() || '未知工具', 120);
|
|
104
|
+
reason = truncate(String(input.reason ?? '').trim().replace(/\s+/g, ' ') || '无说明', 80);
|
|
105
|
+
description = `${tool} · ${reason}`;
|
|
106
|
+
} else if (kind === 'question') {
|
|
107
|
+
const list = Array.isArray(input.questions) ? input.questions : [];
|
|
108
|
+
question = truncate(firstQuestionText(list), 80);
|
|
109
|
+
questionCount = String(list.length);
|
|
110
|
+
description = question;
|
|
111
|
+
} else {
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const templateKey = BROWSER_TEMPLATE_KEYS[kind];
|
|
116
|
+
const fallback = BROWSER_BODY_TEMPLATES[kind];
|
|
117
|
+
const template = typeof config[templateKey] === 'string' && config[templateKey].trim().length > 0
|
|
118
|
+
? config[templateKey]
|
|
119
|
+
: fallback;
|
|
120
|
+
const values = {
|
|
121
|
+
status,
|
|
122
|
+
session: sessionTitle,
|
|
123
|
+
summary,
|
|
124
|
+
turn: String(input.turn ?? ''),
|
|
125
|
+
tool,
|
|
126
|
+
reason,
|
|
127
|
+
question,
|
|
128
|
+
questionCount,
|
|
129
|
+
description,
|
|
130
|
+
};
|
|
131
|
+
let body = renderBrowserTemplate(template, values).trim();
|
|
132
|
+
if (body.length === 0) body = renderBrowserTemplate(fallback, values).trim();
|
|
133
|
+
const maxLength = Number.isFinite(config.browserNotifyMaxBodyLength)
|
|
134
|
+
? config.browserNotifyMaxBodyLength
|
|
135
|
+
: 200;
|
|
136
|
+
body = truncate(body, maxLength);
|
|
137
|
+
|
|
138
|
+
return {
|
|
139
|
+
kind,
|
|
140
|
+
sessionId,
|
|
141
|
+
sessionTitle,
|
|
142
|
+
status,
|
|
143
|
+
body,
|
|
144
|
+
at: Date.now(),
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* In-memory browser notification hub plus an authenticated SSE responder.
|
|
150
|
+
*/
|
|
151
|
+
export class BrowserNotifyHub {
|
|
152
|
+
/**
|
|
153
|
+
* @param {object} options - hub options.
|
|
154
|
+
* @param {() => Record<string, unknown>} options.getConfig - current effective config.
|
|
155
|
+
* @param {object} options.state - StateStore with push/browser mute methods.
|
|
156
|
+
* @param {object} options.notifier - Notifier helper for workspace/title resolution.
|
|
157
|
+
* @param {(sessionId: string) => unknown} [options.getSession] - live Session lookup.
|
|
158
|
+
* @param {{ warn: Function }} options.logger - logger facade.
|
|
159
|
+
*/
|
|
160
|
+
constructor({ getConfig, state, notifier, getSession, logger }) {
|
|
161
|
+
this.getConfig = getConfig;
|
|
162
|
+
this.state = state;
|
|
163
|
+
this.notifier = notifier;
|
|
164
|
+
this.getSession = typeof getSession === 'function' ? getSession : () => undefined;
|
|
165
|
+
this.logger = logger;
|
|
166
|
+
this.subscribers = new Set();
|
|
167
|
+
this.buffer = [];
|
|
168
|
+
this.nextId = 1;
|
|
169
|
+
this.closed = false;
|
|
170
|
+
this.seen = new TtlSet({ ttlMs: 30 * 60 * 1000, capacity: 1024 });
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Publish a completed reply.
|
|
175
|
+
* @param {object} input - reply input.
|
|
176
|
+
* @returns {void}
|
|
177
|
+
*/
|
|
178
|
+
reply(input) {
|
|
179
|
+
this.#schedule('reply', input);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Publish an approval request.
|
|
184
|
+
* @param {object} input - approval input.
|
|
185
|
+
* @returns {void}
|
|
186
|
+
*/
|
|
187
|
+
approval(input) {
|
|
188
|
+
this.#schedule('approval', input);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Publish a user-question request.
|
|
193
|
+
* @param {object} input - question input.
|
|
194
|
+
* @returns {void}
|
|
195
|
+
*/
|
|
196
|
+
question(input) {
|
|
197
|
+
const sessionId = typeof input?.agent?.id === 'string' ? input.agent.id : '';
|
|
198
|
+
this.#schedule('question', {
|
|
199
|
+
sessionId,
|
|
200
|
+
session: this.getSession(sessionId),
|
|
201
|
+
questions: input?.questions,
|
|
202
|
+
callId: input?.wait?.callId,
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Schedule one kind after checking the browser channel switches and dedupe.
|
|
208
|
+
* @param {'reply'|'approval'|'question'} kind - event kind.
|
|
209
|
+
* @param {object} input - event material.
|
|
210
|
+
* @returns {void}
|
|
211
|
+
*/
|
|
212
|
+
#schedule(kind, input) {
|
|
213
|
+
if (this.closed) return;
|
|
214
|
+
const config = this.getConfig();
|
|
215
|
+
if (!this.#kindEnabled(kind, config)) return;
|
|
216
|
+
const key = this.#dedupeKey(kind, input);
|
|
217
|
+
if (!this.seen.add(key)) return;
|
|
218
|
+
void this.#publish(kind, input, config).catch((error) => {
|
|
219
|
+
this.logger?.warn?.(`bark-push: 浏览器通知处理失败:${error?.message ?? String(error)}`);
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Whether one kind is enabled in the browser channel.
|
|
225
|
+
* @param {'reply'|'approval'|'question'} kind - event kind.
|
|
226
|
+
* @param {Record<string, unknown>} config - effective config.
|
|
227
|
+
* @returns {boolean} enabled.
|
|
228
|
+
*/
|
|
229
|
+
#kindEnabled(kind, config) {
|
|
230
|
+
if (config.browserNotifyEnabled !== true) return false;
|
|
231
|
+
if (kind === 'reply') return config.browserNotifyOnReply === true;
|
|
232
|
+
if (kind === 'approval') return config.browserNotifyOnApproval === true;
|
|
233
|
+
if (kind === 'question') return config.browserNotifyOnQuestion === true;
|
|
234
|
+
return false;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Dedupe key for one event.
|
|
239
|
+
* @param {'reply'|'approval'|'question'} kind - event kind.
|
|
240
|
+
* @param {object} input - event material.
|
|
241
|
+
* @returns {string} dedupe key.
|
|
242
|
+
*/
|
|
243
|
+
#dedupeKey(kind, input) {
|
|
244
|
+
if (kind === 'reply') return `reply:${input?.sessionId ?? ''}:${input?.turn ?? ''}`;
|
|
245
|
+
if (kind === 'approval') return `approval:${input?.requestId ?? ''}`;
|
|
246
|
+
return `question:${input?.sessionId ?? 'unknown'}:${input?.callId || hashValue(input?.questions)}`;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Resolve mute state and publish one event.
|
|
251
|
+
* @param {'reply'|'approval'|'question'} kind - event kind.
|
|
252
|
+
* @param {object} input - event material.
|
|
253
|
+
* @param {Record<string, unknown>} config - effective config.
|
|
254
|
+
* @returns {Promise<void>} completion.
|
|
255
|
+
*/
|
|
256
|
+
async #publish(kind, input, config) {
|
|
257
|
+
if (this.closed) return;
|
|
258
|
+
const sessionId = typeof input?.sessionId === 'string' ? input.sessionId : '';
|
|
259
|
+
if (sessionId.length === 0) return;
|
|
260
|
+
|
|
261
|
+
// Re-read a shared state file immediately before deciding, mirroring the
|
|
262
|
+
// Bark path so a mute written by another DSH process is not forgotten.
|
|
263
|
+
this.state.refreshSync?.();
|
|
264
|
+
let workspaceKey;
|
|
265
|
+
try {
|
|
266
|
+
workspaceKey = await this.notifier.workspaceKeyFor(sessionId, input.session, true);
|
|
267
|
+
} catch {
|
|
268
|
+
workspaceKey = undefined;
|
|
269
|
+
}
|
|
270
|
+
const usePushMutes = config.browserNotifyUsePushMutes !== false;
|
|
271
|
+
const muted = usePushMutes
|
|
272
|
+
? this.state.isMuted?.({ sessionId, workspaceKey }) === true
|
|
273
|
+
: this.state.isBrowserMuted?.({ sessionId, workspaceKey }) === true;
|
|
274
|
+
if (muted) {
|
|
275
|
+
this.logger?.debug?.(`bark-push: 浏览器通知 ${kind} 已被静音,跳过`);
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const session = input.session ?? this.getSession(sessionId);
|
|
280
|
+
const event = buildBrowserNotification(kind, { ...input, session }, config, this.notifier);
|
|
281
|
+
if (event === null) return;
|
|
282
|
+
this.#broadcast(event);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* Append one event to the short replay buffer and send it to every subscriber.
|
|
287
|
+
* @param {object} event - formatted event without an id.
|
|
288
|
+
* @returns {void}
|
|
289
|
+
*/
|
|
290
|
+
#broadcast(event) {
|
|
291
|
+
const now = Date.now();
|
|
292
|
+
this.buffer = this.buffer.filter((entry) => entry.at >= now - 30_000);
|
|
293
|
+
const message = { ...event, id: this.nextId++ };
|
|
294
|
+
this.buffer.push(message);
|
|
295
|
+
if (this.buffer.length > 50) this.buffer.splice(0, this.buffer.length - 50);
|
|
296
|
+
for (const subscriber of [...this.subscribers]) {
|
|
297
|
+
try {
|
|
298
|
+
subscriber.send(message);
|
|
299
|
+
} catch {
|
|
300
|
+
this.subscribers.delete(subscriber);
|
|
301
|
+
try {
|
|
302
|
+
subscriber.close?.();
|
|
303
|
+
} catch {
|
|
304
|
+
// The stream is already gone.
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Create one `text/event-stream` response for an authenticated browser.
|
|
312
|
+
* @param {Request} request - Fetch request.
|
|
313
|
+
* @returns {Response} streaming response.
|
|
314
|
+
*/
|
|
315
|
+
subscribe(request) {
|
|
316
|
+
const encoder = new TextEncoder();
|
|
317
|
+
const state = this;
|
|
318
|
+
let controller;
|
|
319
|
+
let heartbeat;
|
|
320
|
+
let closed = false;
|
|
321
|
+
const cleanup = () => {
|
|
322
|
+
if (closed) return;
|
|
323
|
+
closed = true;
|
|
324
|
+
if (heartbeat !== undefined) clearInterval(heartbeat);
|
|
325
|
+
if (controller) {
|
|
326
|
+
try {
|
|
327
|
+
controller.close();
|
|
328
|
+
} catch {
|
|
329
|
+
// The stream may already be closed by the carrier.
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
if (subscriber) state.subscribers.delete(subscriber);
|
|
333
|
+
};
|
|
334
|
+
const subscriber = {
|
|
335
|
+
send(event) {
|
|
336
|
+
if (closed) return;
|
|
337
|
+
const chunk = `id: ${event.id}\nevent: browser-notify\ndata: ${JSON.stringify(event)}\n\n`;
|
|
338
|
+
controller.enqueue(encoder.encode(chunk));
|
|
339
|
+
},
|
|
340
|
+
close: cleanup,
|
|
341
|
+
};
|
|
342
|
+
|
|
343
|
+
const stream = new ReadableStream({
|
|
344
|
+
start(inner) {
|
|
345
|
+
controller = inner;
|
|
346
|
+
state.subscribers.add(subscriber);
|
|
347
|
+
controller.enqueue(encoder.encode('retry: 3000\n\nevent: ready\ndata: {"version":1}\n\n'));
|
|
348
|
+
const lastId = Number(request.headers.get('last-event-id') ?? 0);
|
|
349
|
+
if (Number.isFinite(lastId) && lastId > 0) {
|
|
350
|
+
for (const event of state.buffer) {
|
|
351
|
+
if (event.id > lastId) subscriber.send(event);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
heartbeat = setInterval(() => {
|
|
355
|
+
try {
|
|
356
|
+
controller.enqueue(encoder.encode(': heartbeat\n\n'));
|
|
357
|
+
} catch {
|
|
358
|
+
cleanup();
|
|
359
|
+
}
|
|
360
|
+
}, 20_000);
|
|
361
|
+
request.signal?.addEventListener('abort', cleanup, { once: true });
|
|
362
|
+
},
|
|
363
|
+
cancel() {
|
|
364
|
+
cleanup();
|
|
365
|
+
},
|
|
366
|
+
});
|
|
367
|
+
|
|
368
|
+
return new Response(stream, {
|
|
369
|
+
status: 200,
|
|
370
|
+
headers: {
|
|
371
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
372
|
+
'cache-control': 'no-cache',
|
|
373
|
+
'x-accel-buffering': 'no',
|
|
374
|
+
'x-content-type-options': 'nosniff',
|
|
375
|
+
},
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* Close all SSE streams and reject future events.
|
|
381
|
+
* @returns {void}
|
|
382
|
+
*/
|
|
383
|
+
dispose() {
|
|
384
|
+
if (this.closed) return;
|
|
385
|
+
this.closed = true;
|
|
386
|
+
for (const subscriber of [...this.subscribers]) {
|
|
387
|
+
try {
|
|
388
|
+
subscriber.close?.();
|
|
389
|
+
} catch {
|
|
390
|
+
// Ignore a subscriber already gone.
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
this.subscribers.clear();
|
|
394
|
+
this.buffer = [];
|
|
395
|
+
}
|
|
396
|
+
}
|