dsh-bark-push 0.2.1 → 0.3.0

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/lib/client.js CHANGED
@@ -32,30 +32,31 @@ window.__ModuleLoader__.load({
32
32
  const API = {
33
33
  state: "/api/bark-push/state",
34
34
  toggle: "/api/bark-push/toggle",
35
+ browserEvents: "/api/bark-push/browser-events",
35
36
  };
36
37
 
37
38
  const COPY = {
38
39
  zh: {
39
- nav: "推送通知",
40
+ nav: "通知",
40
41
  mute: "静音推送通知",
41
42
  unmute: "取消静音推送通知",
42
43
  muted: "推送通知已静音",
43
44
  mutedWorkspace: "工作区推送通知已静音",
44
45
  unmuted: "推送通知已取消静音",
45
- settingsTitle: "推送通知",
46
- settingsIntro: "在下方管理推送渠道、通知规则与静音状态。",
46
+ settingsTitle: "通知",
47
+ settingsIntro: "在下方管理推送通知与浏览器通知;两套渠道可以独立开启。",
47
48
  unavailable: "管理接口不可用;请确认 Web 运行时与 client-connection 已加载。",
48
49
  failed: "操作失败",
49
50
  },
50
51
  en: {
51
- nav: "Push notifications",
52
+ nav: "Notifications",
52
53
  mute: "Mute push notifications",
53
54
  unmute: "Unmute push notifications",
54
55
  muted: "Push notifications muted",
55
56
  mutedWorkspace: "Workspace push notifications muted",
56
57
  unmuted: "Push notifications unmuted",
57
- settingsTitle: "Push notifications",
58
- settingsIntro: "Manage push channels, notification rules, and mute state below.",
58
+ settingsTitle: "Notifications",
59
+ settingsIntro: "Manage push notifications and browser notifications below; the two channels are independent.",
59
60
  unavailable: "Management API unavailable; check that the Web runtime and client-connection are mounted.",
60
61
  failed: "Action failed",
61
62
  },
@@ -85,6 +86,11 @@ window.__ModuleLoader__.load({
85
86
  sessionWorkspace: new Map(),
86
87
  /** Workspace id -> root path, used to infer a workspace from a Session cwd. */
87
88
  workspacePaths: new Map(),
89
+ /** Browser-notification switches mirrored from the latest state payload. */
90
+ browserConfig: {
91
+ enabled: false,
92
+ skipForeground: true,
93
+ },
88
94
  listeners: new Set(),
89
95
  };
90
96
 
@@ -159,6 +165,12 @@ window.__ModuleLoader__.load({
159
165
  if (!payload || !payload.mute) return;
160
166
  store.workspaces = new Set(Array.isArray(payload.mute.workspaces) ? payload.mute.workspaces : []);
161
167
  store.sessions = new Set(Array.isArray(payload.mute.sessions) ? payload.mute.sessions : []);
168
+ if (payload.config && typeof payload.config === "object") {
169
+ store.browserConfig = {
170
+ enabled: payload.config.browserNotifyEnabled === true,
171
+ skipForeground: payload.config.browserNotifySkipForeground !== false,
172
+ };
173
+ }
162
174
  if (payload.catalog && typeof payload.catalog === "object") {
163
175
  const catalog = payload.catalog;
164
176
  const paths = new Map();
@@ -454,6 +466,191 @@ window.__ModuleLoader__.load({
454
466
  );
455
467
  }
456
468
 
469
+ /** Browser Notification API from the top-level window, when available. */
470
+ function notificationApi() {
471
+ try {
472
+ if (typeof window !== "undefined" && typeof window.Notification === "function") return window.Notification;
473
+ } catch (_) {
474
+ // Fall through to the global for unusual test harnesses.
475
+ }
476
+ try {
477
+ return typeof Notification === "function" ? Notification : undefined;
478
+ } catch (_) {
479
+ return undefined;
480
+ }
481
+ }
482
+
483
+ /** Current main-view Session id, matching the DSH sidebar's own rule. */
484
+ function currentSessionId(ctx) {
485
+ try {
486
+ let sessions = ctx && ctx.sessions ? ctx.sessions : undefined;
487
+ if (!sessions && ctx && typeof ctx.get === "function") {
488
+ sessions = ctx.get("sessions");
489
+ }
490
+ const snapshot = sessions && sessions.list && typeof sessions.list.getSnapshot === "function"
491
+ ? sessions.list.getSnapshot()
492
+ : undefined;
493
+ if (!snapshot || !snapshot.byId) return undefined;
494
+ const row = Object.values(snapshot.byId).find((entry) => (entry?.retainedBy?.mainView ?? 0) > 0);
495
+ return row && typeof row.id === "string" ? row.id : undefined;
496
+ } catch (_) {
497
+ return undefined;
498
+ }
499
+ }
500
+
501
+ /** Whether a browser event should be shown under the foreground rule. */
502
+ function browserEventShouldDisplay(ctx, event) {
503
+ if (!event || typeof event !== "object") return false;
504
+ if (store.loaded && (!store.browserConfig || store.browserConfig.enabled !== true)) return false;
505
+ if (store.browserConfig.skipForeground === false) return true;
506
+ const focused = typeof document.hasFocus === "function" ? document.hasFocus() : true;
507
+ const foreground = document.visibilityState === "visible" && focused;
508
+ if (!foreground) return true;
509
+ const current = currentSessionId(ctx);
510
+ return current === undefined || event.sessionId !== current;
511
+ }
512
+
513
+ /** Open a Session from the top document after a notification click. */
514
+ function openSessionFromNotification(ctx, sessionId) {
515
+ if (typeof sessionId !== "string" || sessionId.length === 0) return;
516
+ try {
517
+ if (ctx && ctx.uiWorkspace && typeof ctx.uiWorkspace.openSession === "function") {
518
+ ctx.uiWorkspace.openSession(sessionId);
519
+ return;
520
+ }
521
+ } catch (_) {
522
+ // Fall through to the injected scope.
523
+ }
524
+ try {
525
+ ctx.inject(["uiWorkspace"], (scope) => {
526
+ try {
527
+ scope.uiWorkspace.openSession(sessionId);
528
+ } catch (_) {
529
+ // The workspace UI may be tearing down.
530
+ }
531
+ });
532
+ } catch (_) {
533
+ // No workspace UI in this composition.
534
+ }
535
+ }
536
+
537
+ /** Show one browser notification and wire its click-through. */
538
+ function showBrowserNotification(ctx, event) {
539
+ const Api = notificationApi();
540
+ if (!Api || Api.permission !== "granted") return false;
541
+ if (!browserEventShouldDisplay(ctx, event)) return false;
542
+ const title = typeof event.sessionTitle === "string" && event.sessionTitle.length > 0
543
+ ? event.sessionTitle
544
+ : "当前会话";
545
+ const body = typeof event.body === "string" ? event.body : (event.status || "");
546
+ try {
547
+ const notification = new Api(title, {
548
+ body,
549
+ tag: `dsh-bark:${event.kind || "notice"}:${event.sessionId || ""}`,
550
+ renotify: true,
551
+ requireInteraction: event.kind !== "reply",
552
+ data: { sessionId: event.sessionId, kind: event.kind },
553
+ });
554
+ notification.onclick = () => {
555
+ try {
556
+ window.focus();
557
+ } catch (_) {
558
+ // A background tab may not be focusable.
559
+ }
560
+ openSessionFromNotification(ctx, event.sessionId);
561
+ try {
562
+ notification.close();
563
+ } catch (_) {
564
+ // Already closed.
565
+ }
566
+ };
567
+ return true;
568
+ } catch (_) {
569
+ return false;
570
+ }
571
+ }
572
+
573
+ /** Request permission from the top document for the settings iframe. */
574
+ function requestTopNotificationPermission() {
575
+ const Api = notificationApi();
576
+ if (!Api || typeof Api.requestPermission !== "function") return Promise.resolve("unsupported");
577
+ try {
578
+ return Promise.resolve(Api.requestPermission());
579
+ } catch (_) {
580
+ return Promise.resolve("denied");
581
+ }
582
+ }
583
+
584
+ /** Show a test notification from the top document. */
585
+ function showTopTestNotification() {
586
+ const Api = notificationApi();
587
+ if (!Api || Api.permission !== "granted") return false;
588
+ try {
589
+ new Api("DSH 浏览器通知测试", { body: "浏览器通知已开启。" });
590
+ return true;
591
+ } catch (_) {
592
+ return false;
593
+ }
594
+ }
595
+
596
+ /**
597
+ * Connect the browser-notification SSE stream. A leader lock keeps multiple
598
+ * DSH tabs from showing the same notification twice.
599
+ */
600
+ function installBrowserNotifications(ctx) {
601
+ let source = null;
602
+ let started = false;
603
+ let releaseLeader;
604
+ const start = () => {
605
+ if (started) return;
606
+ const EventSourceCtor = typeof window !== "undefined" ? window.EventSource : undefined;
607
+ if (typeof EventSourceCtor !== "function") return;
608
+ started = true;
609
+ try {
610
+ source = new EventSourceCtor(API.browserEvents);
611
+ source.addEventListener("browser-notify", (message) => {
612
+ try {
613
+ const event = JSON.parse(message.data);
614
+ showBrowserNotification(ctx, event);
615
+ } catch (_) {
616
+ // Malformed events must not break the stream.
617
+ }
618
+ });
619
+ } catch (_) {
620
+ started = false;
621
+ source = null;
622
+ }
623
+ };
624
+ const stop = () => {
625
+ if (source && typeof source.close === "function") source.close();
626
+ source = null;
627
+ };
628
+
629
+ try {
630
+ const locks = typeof navigator !== "undefined" ? navigator.locks : undefined;
631
+ if (locks && typeof locks.request === "function") {
632
+ const hold = new Promise((resolve) => { releaseLeader = resolve; });
633
+ locks.request("dsh-bark-push:browser-notify-leader", { mode: "exclusive" }, async () => {
634
+ start();
635
+ await hold;
636
+ }).catch(() => start());
637
+ } else {
638
+ start();
639
+ }
640
+ } catch (_) {
641
+ start();
642
+ }
643
+
644
+ try {
645
+ ctx.effect(() => () => {
646
+ releaseLeader?.();
647
+ stop();
648
+ }, "bark-push: browser notification stream");
649
+ } catch (_) {
650
+ // Non-DOM test harnesses can still call showBrowserNotification directly.
651
+ }
652
+ }
653
+
457
654
  function BarkSettings() {
458
655
  const [failed, setFailed] = React.useState(false);
459
656
  const frameRef = React.useRef(null);
@@ -464,9 +661,36 @@ window.__ModuleLoader__.load({
464
661
  if (event.origin !== window.location.origin) return;
465
662
  if (!frameRef.current || event.source !== frameRef.current.contentWindow) return;
466
663
  const data = event.data;
467
- if (!data || data.type !== "dsh-bark-push:height") return;
468
- const height = Number(data.height);
469
- if (Number.isFinite(height)) setFrameHeight(Math.max(480, Math.min(4000, Math.ceil(height))));
664
+ if (!data) return;
665
+ if (data.type === "dsh-bark-push:height") {
666
+ const height = Number(data.height);
667
+ if (Number.isFinite(height)) setFrameHeight(Math.max(480, Math.min(4000, Math.ceil(height))));
668
+ return;
669
+ }
670
+ if (data.type === "dsh-bark-push:browser-permission-request") {
671
+ void requestTopNotificationPermission().then((permission) => {
672
+ try {
673
+ frameRef.current?.contentWindow?.postMessage(
674
+ { type: "dsh-bark-push:browser-permission-result", permission },
675
+ window.location.origin,
676
+ );
677
+ } catch (_) {
678
+ // The iframe may have been closed while the prompt was open.
679
+ }
680
+ });
681
+ return;
682
+ }
683
+ if (data.type === "dsh-bark-push:browser-test") {
684
+ showTopTestNotification();
685
+ return;
686
+ }
687
+ if (data.type === "dsh-bark-push:config-updated") {
688
+ const config = data.config && typeof data.config === "object" ? data.config : {};
689
+ store.browserConfig = {
690
+ enabled: config.browserNotifyEnabled === true,
691
+ skipForeground: config.browserNotifySkipForeground !== false,
692
+ };
693
+ }
470
694
  };
471
695
  window.addEventListener("message", onMessage);
472
696
  return () => window.removeEventListener("message", onMessage);
@@ -496,6 +720,7 @@ window.__ModuleLoader__.load({
496
720
  src: "/api/bark-push/ui?embed=1",
497
721
  style: frameStyle,
498
722
  title: COPY.zh.settingsTitle,
723
+ allow: "notifications",
499
724
  onError: () => setFailed(true),
500
725
  }),
501
726
  );
@@ -551,7 +776,7 @@ window.__ModuleLoader__.load({
551
776
  }
552
777
  }
553
778
 
554
- const inject = ["slots"];
779
+ const inject = ["slots", "sessions"];
555
780
 
556
781
  function apply(ctx) {
557
782
  propsContext = ctx;
@@ -614,6 +839,8 @@ window.__ModuleLoader__.load({
614
839
  // No window (non-web composition): notices stay local to the iframe.
615
840
  }
616
841
 
842
+ installBrowserNotifications(ctx);
843
+
617
844
  if (!ctx.slots) return;
618
845
 
619
846
  // Frame-wide overlay entry hosted by the layout shell (top document,
@@ -790,7 +1017,24 @@ window.__ModuleLoader__.load({
790
1017
 
791
1018
  exports.apply = apply;
792
1019
  exports.inject = inject;
793
- exports.__internals = { store, toastStore, request, toggle, adopt, useMuted, COPY, NS, BELL_PATHS };
1020
+ exports.__internals = {
1021
+ store,
1022
+ toastStore,
1023
+ request,
1024
+ toggle,
1025
+ adopt,
1026
+ useMuted,
1027
+ COPY,
1028
+ NS,
1029
+ BELL_PATHS,
1030
+ browser: {
1031
+ currentSessionId,
1032
+ shouldDisplay: browserEventShouldDisplay,
1033
+ show: showBrowserNotification,
1034
+ requestTopPermission: requestTopNotificationPermission,
1035
+ showTopTest: showTopTestNotification,
1036
+ },
1037
+ };
794
1038
  return module.exports;
795
1039
  },
796
1040
  });
package/lib/config.js CHANGED
@@ -27,6 +27,27 @@ export const MAX_DEVICE_KEYS = 20;
27
27
  /** Hard safety bound for one device key. Bark keys are short; longer input is a mistake. */
28
28
  export const MAX_DEVICE_KEY_LENGTH = 256;
29
29
 
30
+ /** Default body templates for the independent browser-notification channel. */
31
+ export const BROWSER_BODY_TEMPLATES = Object.freeze({
32
+ reply: '{status} · {summary}',
33
+ approval: '{status} · {tool} · {reason}',
34
+ question: '{status} · {question}',
35
+ });
36
+
37
+ /** Config key for each browser-notification body template. */
38
+ export const BROWSER_TEMPLATE_KEYS = Object.freeze({
39
+ reply: 'browserNotifyReplyBody',
40
+ approval: 'browserNotifyApprovalBody',
41
+ question: 'browserNotifyQuestionBody',
42
+ });
43
+
44
+ /** Placeholders accepted by each browser-notification body template. */
45
+ export const BROWSER_TEMPLATE_PLACEHOLDERS = Object.freeze({
46
+ reply: Object.freeze(['status', 'session', 'summary', 'turn', 'description']),
47
+ approval: Object.freeze(['status', 'session', 'tool', 'reason', 'description']),
48
+ question: Object.freeze(['status', 'session', 'question', 'questionCount', 'description']),
49
+ });
50
+
30
51
  /** Every configurable key, in the order the management page renders them. */
31
52
  export const CONFIG_KEYS = Object.freeze([
32
53
  'enabled',
@@ -55,6 +76,16 @@ export const CONFIG_KEYS = Object.freeze([
55
76
  'linkToSession',
56
77
  'publicBaseUrl',
57
78
  'trace',
79
+ 'browserNotifyEnabled',
80
+ 'browserNotifyOnReply',
81
+ 'browserNotifyOnApproval',
82
+ 'browserNotifyOnQuestion',
83
+ 'browserNotifySkipForeground',
84
+ 'browserNotifyUsePushMutes',
85
+ 'browserNotifyReplyBody',
86
+ 'browserNotifyApprovalBody',
87
+ 'browserNotifyQuestionBody',
88
+ 'browserNotifyMaxBodyLength',
58
89
  ...LEGACY_CONFIG_KEYS,
59
90
  ]);
60
91
 
@@ -86,6 +117,16 @@ export const DEFAULTS = Object.freeze({
86
117
  linkToSession: true,
87
118
  publicBaseUrl: '',
88
119
  trace: false,
120
+ browserNotifyEnabled: false,
121
+ browserNotifyOnReply: true,
122
+ browserNotifyOnApproval: true,
123
+ browserNotifyOnQuestion: true,
124
+ browserNotifySkipForeground: true,
125
+ browserNotifyUsePushMutes: true,
126
+ browserNotifyReplyBody: BROWSER_BODY_TEMPLATES.reply,
127
+ browserNotifyApprovalBody: BROWSER_BODY_TEMPLATES.approval,
128
+ browserNotifyQuestionBody: BROWSER_BODY_TEMPLATES.question,
129
+ browserNotifyMaxBodyLength: 200,
89
130
  soundNormal: '',
90
131
  soundImportant: '',
91
132
  levelNormal: 'active',
@@ -384,6 +425,16 @@ function normalizeFields(raw, base, warnings) {
384
425
  linkToSession: booleanOf(raw.linkToSession, base.linkToSession),
385
426
  publicBaseUrl: normalizePublicBaseUrl(raw.publicBaseUrl, base.publicBaseUrl),
386
427
  trace: booleanOf(raw.trace, base.trace),
428
+ browserNotifyEnabled: booleanOf(raw.browserNotifyEnabled, base.browserNotifyEnabled),
429
+ browserNotifyOnReply: booleanOf(raw.browserNotifyOnReply, base.browserNotifyOnReply),
430
+ browserNotifyOnApproval: booleanOf(raw.browserNotifyOnApproval, base.browserNotifyOnApproval),
431
+ browserNotifyOnQuestion: booleanOf(raw.browserNotifyOnQuestion, base.browserNotifyOnQuestion),
432
+ browserNotifySkipForeground: booleanOf(raw.browserNotifySkipForeground, base.browserNotifySkipForeground),
433
+ browserNotifyUsePushMutes: booleanOf(raw.browserNotifyUsePushMutes, base.browserNotifyUsePushMutes),
434
+ browserNotifyReplyBody: textOf(raw.browserNotifyReplyBody, base.browserNotifyReplyBody, 300),
435
+ browserNotifyApprovalBody: textOf(raw.browserNotifyApprovalBody, base.browserNotifyApprovalBody, 300),
436
+ browserNotifyQuestionBody: textOf(raw.browserNotifyQuestionBody, base.browserNotifyQuestionBody, 300),
437
+ browserNotifyMaxBodyLength: integerInRange(raw.browserNotifyMaxBodyLength, base.browserNotifyMaxBodyLength, 32, 500),
387
438
  };
388
439
  }
389
440
 
package/lib/events.js CHANGED
@@ -70,11 +70,12 @@ export function turnEndKind(reason) {
70
70
  * @param {object} ctx - host Cordis context.
71
71
  * @param {object} options - bridge dependencies.
72
72
  * @param {object} options.notifier - notifier with `reply`/`approval` methods.
73
+ * @param {object} [options.browserNotifier] - independent browser notification sink.
73
74
  * @param {() => Record<string, unknown>} options.getConfig - current config.
74
75
  * @param {{ info: Function, warn: Function, error: Function, debug: Function }} options.logger - logger.
75
76
  * @returns {() => void} disposer.
76
77
  */
77
- export function installSessionBridge(ctx, { notifier, getConfig, logger }) {
78
+ export function installSessionBridge(ctx, { notifier, browserNotifier, getConfig, logger }) {
78
79
  /** @type {Map<string, { turn: number, text: string }>} */
79
80
  const pending = new Map();
80
81
  /** @type {Map<string, string>} */
@@ -129,13 +130,20 @@ export function installSessionBridge(ctx, { notifier, getConfig, logger }) {
129
130
  text: record.text,
130
131
  sessionTitle: titleOf(id),
131
132
  });
133
+ browserNotifier?.reply?.({
134
+ session,
135
+ sessionId: id,
136
+ turn,
137
+ text: record.text,
138
+ sessionTitle: titleOf(id),
139
+ });
132
140
  return;
133
141
  }
134
142
 
135
143
  if (event.type === 'approval/asked') {
136
144
  const requestId = typeof event.data?.id === 'string' ? event.data.id : '';
137
145
  if (requestId.length === 0) return;
138
- notifier.approval({
146
+ const input = {
139
147
  session,
140
148
  sessionId: id,
141
149
  requestId,
@@ -143,7 +151,9 @@ export function installSessionBridge(ctx, { notifier, getConfig, logger }) {
143
151
  reason: typeof event.data?.reason === 'string' ? event.data.reason : '',
144
152
  callId: typeof event.data?.callId === 'string' ? event.data.callId : undefined,
145
153
  sessionTitle: titleOf(id),
146
- });
154
+ };
155
+ notifier.approval(input);
156
+ browserNotifier?.approval?.(input);
147
157
  }
148
158
  };
149
159
 
@@ -180,15 +190,21 @@ export function installSessionBridge(ctx, { notifier, getConfig, logger }) {
180
190
  * @param {object} ctx - host Cordis context.
181
191
  * @param {object} options - observer dependencies.
182
192
  * @param {object} options.notifier - notifier with `question` method.
193
+ * @param {object} [options.browserNotifier] - independent browser notification sink.
183
194
  * @param {{ warn: Function }} options.logger - logger.
184
195
  * @returns {() => void} disposer.
185
196
  */
186
- export function installQuestionBridge(ctx, { notifier, logger }) {
197
+ export function installQuestionBridge(ctx, { notifier, browserNotifier, logger }) {
187
198
  const off = ctx.on('user-questions/request', (request, next) => {
188
199
  try {
189
200
  notifier.question(request);
190
201
  } catch (error) {
191
- logger.warn(`bark-push: 选择请求处理失败:${error?.message ?? String(error)}`);
202
+ logger.warn(`bark-push: 选择请求推送失败:${error?.message ?? String(error)}`);
203
+ }
204
+ try {
205
+ browserNotifier?.question?.(request);
206
+ } catch (error) {
207
+ logger.warn(`bark-push: 选择请求浏览器通知失败:${error?.message ?? String(error)}`);
192
208
  }
193
209
  return typeof next === 'function' ? next() : Promise.reject(new Error('bark-push: missing waterfall delegate'));
194
210
  });