@idoall/dsh-notify 0.2.2

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/dist/client.js ADDED
@@ -0,0 +1,1195 @@
1
+ window.__ModuleLoader__.load({
2
+ id: "@idoall/dsh-notify",
3
+ factory: (require) => {
4
+ var module = { exports: {} };
5
+ var exports = module.exports;
6
+ "use strict";
7
+ var __create = Object.create;
8
+ var __defProp = Object.defineProperty;
9
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
+ var __getOwnPropNames = Object.getOwnPropertyNames;
11
+ var __getProtoOf = Object.getPrototypeOf;
12
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
13
+ var __export = (target, all) => {
14
+ for (var name in all)
15
+ __defProp(target, name, { get: all[name], enumerable: true });
16
+ };
17
+ var __copyProps = (to, from, except, desc) => {
18
+ if (from && typeof from === "object" || typeof from === "function") {
19
+ for (let key of __getOwnPropNames(from))
20
+ if (!__hasOwnProp.call(to, key) && key !== except)
21
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
22
+ }
23
+ return to;
24
+ };
25
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
26
+ // If the importer is in node compatibility mode or this is not an ESM
27
+ // file that has been converted to a CommonJS file using a Babel-
28
+ // compatible transform (i.e. "__esModule" has not been set), then set
29
+ // "default" to the CommonJS "module.exports" for node compatibility.
30
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
31
+ mod
32
+ ));
33
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
34
+
35
+ // src/client.js
36
+ var client_exports = {};
37
+ __export(client_exports, {
38
+ CLIENT_COMPOSITION: () => CLIENT_COMPOSITION,
39
+ CLIENT_CSS: () => CLIENT_CSS,
40
+ NotificationSelfTests: () => NotificationSelfTests,
41
+ SELF_TEST_BATCH: () => SELF_TEST_BATCH,
42
+ SELF_TEST_STEP_MS: () => SELF_TEST_STEP_MS,
43
+ SETTINGS_CSS: () => SETTINGS_CSS,
44
+ TOAST_CSS: () => TOAST_CSS,
45
+ TOAST_EXIT_MS: () => TOAST_EXIT_MS,
46
+ TOAST_QUEUE_MAX: () => TOAST_QUEUE_MAX,
47
+ TOAST_STACK_GAP: () => TOAST_STACK_GAP,
48
+ TOAST_STACK_PEEK: () => TOAST_STACK_PEEK,
49
+ TOAST_STACK_VISIBLE: () => TOAST_STACK_VISIBLE,
50
+ TOAST_STACK_VISIBLE_NARROW: () => TOAST_STACK_VISIBLE_NARROW,
51
+ TOAST_SUCCESS_MS: () => TOAST_SUCCESS_MS,
52
+ answerBatch: () => answerBatch,
53
+ apply: () => apply,
54
+ createAttentionIndicator: () => createAttentionIndicator,
55
+ createLocalSelfTestBatch: () => createLocalSelfTestBatch,
56
+ createLocalSelfTestRecord: () => createLocalSelfTestRecord,
57
+ createSoundPlayer: () => createSoundPlayer,
58
+ inject: () => inject,
59
+ installAudioUnlock: () => installAudioUnlock,
60
+ installClientStyles: () => installClientStyles,
61
+ layoutFor: () => layoutFor,
62
+ mountNotifyClient: () => mountNotifyClient,
63
+ navigateNotificationRecord: () => navigateNotificationRecord,
64
+ pendingInteractionFor: () => pendingInteractionFor,
65
+ publishLocalSelfTest: () => publishLocalSelfTest,
66
+ queueCards: () => queueCards,
67
+ resultTone: () => resultTone,
68
+ revealTurn: () => revealTurn,
69
+ sessionLabel: () => sessionLabel,
70
+ setToastConfig: () => setToastConfig,
71
+ stackWindow: () => stackWindow,
72
+ statusTone: () => statusTone,
73
+ toastAnchor: () => toastAnchor,
74
+ toastAnchorWatchTargets: () => toastAnchorWatchTargets,
75
+ toastAnswer: () => toastAnswer,
76
+ toastIcon: () => toastIcon,
77
+ toastOrder: () => toastOrder,
78
+ toastStackPlan: () => toastStackPlan,
79
+ toastTime: () => toastTime,
80
+ toastTone: () => toastTone,
81
+ watchToastAnchor: () => watchToastAnchor
82
+ });
83
+ module.exports = __toCommonJS(client_exports);
84
+ var import_react = __toESM(require("react"), 1);
85
+
86
+ // src/sound-choices.js
87
+ var BUILTIN_SOUNDS = Object.freeze(["chime", "ping", "alert", "none"]);
88
+ var SOUND_BYTES = 1024 * 1024;
89
+ var EXTENSIONS = Object.freeze({ ".mp3": "audio/mpeg", ".m4a": "audio/mp4", ".aac": "audio/aac", ".wav": "audio/wav", ".ogg": "audio/ogg", ".oga": "audio/ogg", ".flac": "audio/flac", ".webm": "audio/webm" });
90
+ var NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
91
+ function extensionOf(name) {
92
+ const index = typeof name === "string" ? name.lastIndexOf(".") : -1;
93
+ if (index <= 0) return void 0;
94
+ return EXTENSIONS[name.slice(index).toLowerCase()];
95
+ }
96
+ function validSoundName(name) {
97
+ if (typeof name !== "string" || !NAME_PATTERN.test(name) || name.includes("..") || name.includes("/") || name.includes("\\")) return false;
98
+ return extensionOf(name) !== void 0;
99
+ }
100
+ function parseSoundChoice(value) {
101
+ if (typeof value !== "string" || value.length === 0) return { kind: "builtin", id: "chime" };
102
+ if (value.startsWith("custom:")) {
103
+ const name = value.slice("custom:".length);
104
+ return validSoundName(name) ? { kind: "custom", name } : { kind: "builtin", id: "chime" };
105
+ }
106
+ return { kind: "builtin", id: BUILTIN_SOUNDS.includes(value) ? value : "chime" };
107
+ }
108
+ var SOUND_PRESETS = Object.freeze({
109
+ chime: Object.freeze([{ freq: 880, at: 0, dur: 0.14, gain: 0.16, type: "sine" }, { freq: 1318.5, at: 0.11, dur: 0.22, gain: 0.12, type: "sine" }]),
110
+ ping: Object.freeze([{ freq: 1318.5, at: 0, dur: 0.16, gain: 0.15, type: "sine" }]),
111
+ alert: Object.freeze([{ freq: 660, at: 0, dur: 0.11, gain: 0.2, type: "triangle" }, { freq: 660, at: 0.17, dur: 0.11, gain: 0.2, type: "triangle" }]),
112
+ none: Object.freeze([])
113
+ });
114
+ var SOUND_LABELS = Object.freeze({ chime: "\u53EE\u549A\uFF08\u9ED8\u8BA4\uFF09", ping: "\u8F7B\u63D0\u793A", alert: "\u53CC\u54CD\u63D0\u9192", none: "\u9759\u97F3" });
115
+
116
+ // src/client.js
117
+ var BASE = "/plugins/dsh-notify";
118
+ var LOCAL_TEST_EVENT = "dsh-notify:self-test-local";
119
+ var inject = ["slots"];
120
+ function toastAnchor({ document: doc = globalThis.document, innerWidth = globalThis.innerWidth, fallbackContentWidth = 720 } = {}) {
121
+ const rect = doc?.querySelector?.("[data-conversation-scroll]")?.getBoundingClientRect?.();
122
+ const right = rect && rect.width > 0 ? Math.min(rect.right, innerWidth) : null;
123
+ return right === null ? Math.max(16, (innerWidth - fallbackContentWidth) / 2 + 16) : Math.max(16, innerWidth - right + 16);
124
+ }
125
+ function toastAnchorWatchTargets(doc = globalThis.document) {
126
+ const nodes = [];
127
+ const seen = /* @__PURE__ */ new Set();
128
+ const add = (node) => {
129
+ if (node && !seen.has(node)) {
130
+ seen.add(node);
131
+ nodes.push(node);
132
+ }
133
+ };
134
+ add(doc?.querySelector?.("[data-conversation-scroll]"));
135
+ add(doc?.querySelector?.("[data-conversation-content]"));
136
+ const frame = doc?.querySelector?.("[data-rightbar-col]")?.parentElement ?? doc?.querySelector?.("[data-conversation-content]")?.parentElement;
137
+ add(frame);
138
+ return nodes;
139
+ }
140
+ var TOAST_ANCHOR_FOLLOW_MS = 450;
141
+ function watchToastAnchor(onChange, { document: doc = globalThis.document, window: win = globalThis } = {}) {
142
+ if (typeof onChange !== "function") return () => {
143
+ };
144
+ let raf = 0;
145
+ let followingUntil = 0;
146
+ const observed = /* @__PURE__ */ new Set();
147
+ const measure = () => onChange(toastAnchor({ document: doc, innerWidth: win.innerWidth }));
148
+ const tick = () => {
149
+ measure();
150
+ const now = typeof win.performance?.now === "function" ? win.performance.now() : Date.now();
151
+ raf = now < followingUntil && typeof win.requestAnimationFrame === "function" ? win.requestAnimationFrame(tick) : 0;
152
+ };
153
+ const follow = () => {
154
+ const now = typeof win.performance?.now === "function" ? win.performance.now() : Date.now();
155
+ followingUntil = now + TOAST_ANCHOR_FOLLOW_MS;
156
+ if (!raf && typeof win.requestAnimationFrame === "function") raf = win.requestAnimationFrame(tick);
157
+ else if (!raf) measure();
158
+ };
159
+ const observer = typeof win.ResizeObserver === "function" ? new win.ResizeObserver(() => {
160
+ measure();
161
+ follow();
162
+ }) : null;
163
+ const mo = typeof win.MutationObserver === "function" ? new win.MutationObserver(() => {
164
+ retarget();
165
+ measure();
166
+ follow();
167
+ }) : null;
168
+ const styleTargets = /* @__PURE__ */ new Set();
169
+ const frameOf = () => doc?.querySelector?.("[data-rightbar-col]")?.parentElement ?? doc?.querySelector?.("[data-conversation-content]")?.parentElement;
170
+ const retarget = () => {
171
+ for (const node of toastAnchorWatchTargets(doc)) {
172
+ if (observer && !observed.has(node)) {
173
+ observer.observe(node);
174
+ observed.add(node);
175
+ }
176
+ }
177
+ const frame = frameOf();
178
+ if (mo && frame && !styleTargets.has(frame)) {
179
+ mo.observe(frame, { attributes: true, attributeFilter: ["style", "data-sidebar-collapsed", "data-rightbar-collapsed", "data-rightbar-fullscreen"] });
180
+ styleTargets.add(frame);
181
+ }
182
+ };
183
+ const update = () => {
184
+ retarget();
185
+ measure();
186
+ follow();
187
+ };
188
+ win.addEventListener?.("resize", update);
189
+ doc.addEventListener?.("transitionstart", update, true);
190
+ doc.addEventListener?.("transitionend", update, true);
191
+ mo?.observe(doc.documentElement, { subtree: true, attributes: true, attributeFilter: ["data-sidebar-collapsed", "data-rightbar-collapsed", "data-rightbar-fullscreen"] });
192
+ retarget();
193
+ measure();
194
+ return () => {
195
+ win.removeEventListener?.("resize", update);
196
+ doc.removeEventListener?.("transitionstart", update, true);
197
+ doc.removeEventListener?.("transitionend", update, true);
198
+ observer?.disconnect();
199
+ mo?.disconnect();
200
+ if (raf && typeof win.cancelAnimationFrame === "function") win.cancelAnimationFrame(raf);
201
+ };
202
+ }
203
+ var SETTINGS_CSS = `.dsh-notify-settings{display:grid;gap:14px;max-width:640px;min-width:0;padding:4px 0;color:var(--dsw-alias-label-primary)}
204
+ .dsh-notify-heading{font-size:16px;font-weight:650;margin:0}
205
+ .dsh-notify-card{background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);border-radius:12px;min-width:0;padding:16px 18px}
206
+ /* The rhythm inside a card. It has to be scoped to the settings section, because as a bare
207
+ .dsh-notify-card>*+* selector it had the same specificity as the .dsh-notify-hint{margin:0} reset
208
+ further down and lost to it \u2014 the reset comes later \u2014 so every paragraph in a card sat flush against
209
+ the control above it. The gaps inside \u63D0\u793A\u901A\u9053 measured 10, 0, 10, 0, 0: only text was affected, which
210
+ is exactly what made the card look crammed. */
211
+ .dsh-notify-settings .dsh-notify-card>*+*{margin-top:10px}
212
+ /* A note belongs to the control it explains rather than to the next block, so it sits closer to that
213
+ control. Written out per case instead of as one class-equals-hint rule, so the lead sentence of a card
214
+ \u2014 the hint that follows the title \u2014 and the gap between two separate notes both keep the full 10px. */
215
+ .dsh-notify-settings .dsh-notify-card>.dsh-notify-field+.dsh-notify-hint,
216
+ .dsh-notify-settings .dsh-notify-card>.dsh-notify-toggle+.dsh-notify-hint,
217
+ .dsh-notify-settings .dsh-notify-card>.dsh-notify-actions+.dsh-notify-hint{margin-top:6px}
218
+ .dsh-notify-card-title{font-size:13px;font-weight:650;margin:0}
219
+ .dsh-notify-hint{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:1.6;margin:0}
220
+ .dsh-notify-status{align-items:center;display:flex;gap:8px;font-size:12px;line-height:1.45;margin:0;color:var(--dsw-alias-label-secondary)}
221
+ .dsh-notify-status::before{background:var(--dsw-alias-label-tertiary,#98a1ad);border-radius:50%;content:"";flex:none;height:8px;width:8px}
222
+ .dsh-notify-status[data-tone=ok]::before{background:var(--dsw-alias-state-success-primary,#16a36a)}
223
+ .dsh-notify-status[data-tone=warn]::before{background:var(--dsw-alias-state-warn-primary,#d97706)}
224
+ .dsh-notify-status[data-tone=error]::before{background:var(--dsw-alias-state-error-primary,#dc2626)}
225
+ .dsh-notify-toggle{align-items:flex-start;cursor:pointer;display:flex;font-size:13px;gap:10px;line-height:1.45}
226
+ /* The host's mobile stylesheet (bridge-mobile-styles, max-width 767px) stretches every input and select
227
+ inside the settings options pane to width:100%. That is right for our select and wrong for the
228
+ checkbox, which took the whole row and pushed its label past the card edge \u2014 the host's selector is
229
+ div[class*=...] input, which outranks a bare .dsh-notify-toggle input. Scoping the rule to the
230
+ settings section wins the cascade back, and the size is pinned three ways (width, max-width and a
231
+ flex basis) so no width rule from outside can stretch it again. The label may shrink, so a cramped
232
+ pane wraps the text rather than overflowing. */
233
+ .dsh-notify-settings .dsh-notify-toggle input{accent-color:var(--dsw-alias-state-business-primary);flex:0 0 18px;height:18px;margin:1px 0 0;max-width:18px;min-height:18px;min-width:18px;width:18px}
234
+ .dsh-notify-settings .dsh-notify-toggle>span{min-width:0;overflow-wrap:anywhere}
235
+ .dsh-notify-field{display:grid;font-size:13px;font-weight:600;gap:8px;min-width:0}
236
+ .dsh-notify-select{background:var(--dsw-specific-input-major,var(--dsw-alias-bg-layer-2));border:1px solid var(--dsw-alias-border-l2);border-radius:8px;color:inherit;font:inherit;font-weight:400;max-width:100%;min-height:36px;min-width:0;padding:0 10px;width:100%}
237
+ .dsh-notify-actions{align-items:center;display:flex;flex-wrap:wrap;gap:8px;min-width:0}
238
+ .dsh-notify-action{background:var(--dsw-alias-button-floating-fill);border:1px solid var(--dsw-alias-border-l2);border-radius:8px;color:inherit;cursor:pointer;font:inherit;font-size:12px;line-height:30px;max-width:100%;min-height:32px;padding:0 10px;touch-action:manipulation}
239
+ .dsh-notify-action:hover:not(:disabled){background:var(--dsw-alias-button-floating-hover)}
240
+ .dsh-notify-action:disabled{cursor:not-allowed;opacity:.55}
241
+ .dsh-notify-action[data-variant=danger]{background:transparent;border-color:var(--dsw-alias-state-error-primary,#dc2626);color:var(--dsw-alias-state-error-primary,#dc2626)}
242
+ .dsh-notify-action:focus-visible,.dsh-notify-select:focus-visible,.dsh-notify-toggle input:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:2px}
243
+ .dsh-notify-result{color:var(--dsw-alias-label-secondary);font-size:11px;line-height:1.6;margin:0;overflow-wrap:anywhere}
244
+ .dsh-notify-result[data-tone=passed]{color:var(--dsw-alias-state-success-primary,#16a36a)}
245
+ .dsh-notify-result[data-tone=failed]{color:var(--dsw-alias-state-error-primary,#dc2626)}
246
+ .dsh-notify-result[data-tone=active]{color:var(--dsw-alias-state-business-primary)}
247
+ @media (hover:none) and (pointer:coarse){.dsh-notify-action{line-height:42px;min-height:44px}.dsh-notify-select{min-height:44px}.dsh-notify-settings .dsh-notify-toggle input{flex:0 0 22px;height:22px;max-width:22px;min-height:22px;min-width:22px;width:22px}}`;
248
+ var TOAST_CSS = `.dsh-notify-frame{position:fixed;z-index:1100}
249
+ .dsh-notify-stack{height:100%;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;scrollbar-width:thin}
250
+ .dsh-notify-stack-inner{pointer-events:none;position:relative}
251
+ .dsh-notify-slot{inset-inline:0;pointer-events:none;position:absolute;top:0;transform-origin:top center;transition:transform 320ms cubic-bezier(.22,1,.36,1)}
252
+ .dsh-notify-count{background:var(--dsw-alias-interactive-bg-hover-solid,var(--dsw-alias-bg-layer-3,rgb(0 0 0 / 6%)));border:0;border-radius:999px;color:var(--dsw-alias-label-secondary);cursor:pointer;font:inherit;font-size:11px;inset-inline-end:35px;line-height:18px;padding:0 8px;position:absolute;top:13px;z-index:2}
253
+ .dsh-notify-count:hover{color:var(--dsw-alias-label-primary)}
254
+ .dsh-notify-toast{align-items:flex-start;animation:dsh-notify-card-in 380ms cubic-bezier(.21,1.02,.73,1);background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);border-radius:10px;box-shadow:var(--dsw-elevation-panel,0 6px 20px rgb(0 0 0 / 18%));box-sizing:border-box;color:var(--dsw-alias-label-primary);cursor:pointer;display:flex;gap:10px;margin:0;overflow:hidden;padding:12px 34px 12px 12px;pointer-events:auto;position:relative;width:100%}
255
+ .dsh-notify-toast[data-leaving=true]{animation:dsh-notify-card-out 200ms ease-in forwards;pointer-events:none}
256
+ @keyframes dsh-notify-card-in{0%{opacity:0;transform:translateY(-10px) scale(.9)}62%{opacity:1;transform:translateY(0) scale(1.02)}100%{opacity:1;transform:none}}
257
+ @keyframes dsh-notify-card-out{to{opacity:0;transform:translateX(115%)}}
258
+ @keyframes dsh-notify-spin{to{transform:rotate(360deg)}}
259
+ .dsh-notify-toast-icon{color:var(--dsw-alias-label-tertiary,#7a8494);flex:none;margin-top:1px}
260
+ .dsh-notify-toast-icon[data-spin=true]{animation:dsh-notify-spin .9s linear infinite}
261
+ .dsh-notify-toast[data-tone=success] .dsh-notify-toast-icon{color:var(--dsw-alias-state-success-primary,#16a36a)}
262
+ .dsh-notify-toast[data-tone=error] .dsh-notify-toast-icon{color:var(--dsw-alias-state-error-primary,#dc2626)}
263
+ .dsh-notify-toast[data-tone=warning] .dsh-notify-toast-icon{color:var(--dsw-alias-state-warn-primary,#d97706)}
264
+ .dsh-notify-toast[data-tone=info] .dsh-notify-toast-icon{color:var(--dsw-alias-state-business-primary,#2563eb)}
265
+ .dsh-notify-toast-body{display:grid;gap:2px;min-width:0;flex:1 1 auto}
266
+ .dsh-notify-toast-head{align-items:center;display:flex;gap:6px;min-width:0}
267
+ .dsh-notify-toast-source{color:var(--dsw-alias-label-tertiary,#7a8494);flex:1 1 auto;font-size:11px;line-height:1.4;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
268
+ .dsh-notify-toast-time{color:var(--dsw-alias-label-tertiary,#7a8494);flex:none;font-size:11px;font-variant-numeric:tabular-nums;line-height:1.4;white-space:nowrap}
269
+ .dsh-notify-toast-title{font-size:13px;font-weight:650;line-height:1.45}
270
+ .dsh-notify-toast-text{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:1.5;margin:0;overflow-wrap:anywhere}
271
+ .dsh-notify-toast-answers{align-items:center;display:flex;flex-wrap:wrap;gap:6px;margin-top:2px}
272
+ .dsh-notify-toast-answer{background:var(--dsw-alias-button-floating-fill);border:1px solid var(--dsw-alias-border-l2);border-radius:8px;color:inherit;cursor:pointer;font:inherit;font-size:12px;line-height:26px;max-width:100%;min-height:28px;overflow:hidden;padding:0 10px;text-overflow:ellipsis;touch-action:manipulation;white-space:nowrap}
273
+ .dsh-notify-toast-answer:hover{background:var(--dsw-alias-button-floating-hover)}
274
+ .dsh-notify-toast-answer:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:2px}
275
+ .dsh-notify-toast-answer[data-variant=quiet]{background:transparent;color:var(--dsw-alias-label-secondary)}
276
+ .dsh-notify-toast-answer:disabled{cursor:progress;opacity:.6}
277
+ .dsh-notify-toast-error{color:var(--dsw-alias-state-error-primary,#dc2626);font-size:11px;line-height:1.45}
278
+ .dsh-notify-toast-hint{color:var(--dsw-alias-label-secondary);font-size:11px;line-height:1.45}
279
+ .dsh-notify-toast-close{align-items:center;background:transparent;border:0;border-radius:6px;color:var(--dsw-alias-label-secondary);cursor:pointer;display:inline-flex;font-size:15px;height:22px;inset-inline-end:6px;justify-content:center;line-height:1;padding:0;position:absolute;top:6px;width:22px}
280
+ .dsh-notify-toast-close:hover{background:var(--dsw-alias-button-floating-hover);color:var(--dsw-alias-label-primary)}
281
+ .dsh-notify-toast-close:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:2px}
282
+ @media (hover:none) and (pointer:coarse){.dsh-notify-toast{padding:12px 44px 12px 12px}.dsh-notify-toast-close{font-size:17px;height:32px;width:32px}}
283
+ @media (prefers-reduced-motion:reduce){.dsh-notify-toast{animation:none}.dsh-notify-toast[data-leaving=true]{animation:none}.dsh-notify-slot{transition:none}.dsh-notify-toast-icon[data-spin=true]{animation:none}}`;
284
+ var CLIENT_CSS = `${SETTINGS_CSS}
285
+ ${TOAST_CSS}`;
286
+ function installClientStyles({ document: doc = globalThis.document } = {}) {
287
+ const head = doc?.head;
288
+ if (!head?.append || !doc.createElement) return () => {
289
+ };
290
+ const style = doc.createElement("style");
291
+ style.dataset.plugin = "dsh-notify";
292
+ style.textContent = CLIENT_CSS;
293
+ head.append(style);
294
+ return () => style.remove();
295
+ }
296
+ function layoutFor({ width = 1024, coarse = false } = {}) {
297
+ return { narrow: width < 760, hitTarget: coarse ? 44 : 32 };
298
+ }
299
+ function createLocalSelfTestRecord({ now = Date.now(), randomUUID = () => globalThis.crypto?.randomUUID?.() || Math.random().toString(36).slice(2) } = {}) {
300
+ const id = `self-test:${randomUUID()}`;
301
+ return { eventId: id, mergeKey: id, kind: "test", title: "\u81EA\u6D4B\uFF1A\u9875\u9762\u6D6E\u5C42", body: "\u53EA\u663E\u793A\u5728\u5F53\u524D\u9875\u9762\uFF0C\u4E0D\u4F1A\u53D1\u9001\u7CFB\u7EDF\u901A\u77E5", at: now, phase: "settled", localOnly: true };
302
+ }
303
+ var SELF_TEST_BATCH = Object.freeze([
304
+ { kind: "completed", title: "\u4EFB\u52A1\u5B8C\u6210", body: "\u4FEE\u590D\u63D2\u4EF6\u672C\u673A\u8BBF\u95EE\u5E03\u5C40\u95EE\u9898" },
305
+ { kind: "approval", title: "\u9700\u8981\u5BA1\u6279", body: "escalate sandbox to danger-full-access" },
306
+ { kind: "question", title: "\u9700\u8981\u56DE\u590D", body: "\u901A\u9053\u8303\u56F4\uFF1A\u6D4F\u89C8\u5668\u901A\u77E5\u8981\u600E\u4E48\u5904\u7406\uFF1F" },
307
+ { kind: "failed", title: "\u8FD0\u884C\u5931\u8D25", body: "OpenAI API error (503): Service temporarily unavailable" },
308
+ { kind: "job-end", title: "\u540E\u53F0\u4EFB\u52A1\u7ED3\u675F", body: "pnpm build" },
309
+ { kind: "subagent-end", title: "\u5B50\u4EFB\u52A1\u7ED3\u675F", body: "\u5BA1\u8BA1 test/client-dom.test.js \u7684\u60AC\u6D6E\u884C\u4E3A" },
310
+ { kind: "workflow-end", title: "\u5DE5\u4F5C\u6D41\u7ED3\u675F", body: "3 \u4E2A\u9636\u6BB5\uFF0C8 \u4E2A\u6587\u4EF6\uFF0C0 \u4E2A\u5931\u8D25" },
311
+ { kind: "plan-review", title: "\u8BA1\u5212\u5F85\u786E\u8BA4", body: "\u8FC1\u79FB\u6267\u884C\u8BA1\u5212\uFF1A5 \u6B65\uFF0C\u542B\u56DE\u6EDA" }
312
+ ]);
313
+ var SELF_TEST_STEP_MS = 6e3;
314
+ function createLocalSelfTestBatch({ count = SELF_TEST_BATCH.length, now = Date.now(), randomUUID = () => globalThis.crypto?.randomUUID?.() || Math.random().toString(36).slice(2) } = {}) {
315
+ const wanted = Math.max(1, Math.min(SELF_TEST_BATCH.length, Math.trunc(Number(count)) || SELF_TEST_BATCH.length));
316
+ return SELF_TEST_BATCH.slice(0, wanted).map((entry, index) => {
317
+ const id = `self-test:${randomUUID()}-${index}`;
318
+ return { ...entry, eventId: id, mergeKey: id, at: now - (wanted - 1 - index) * SELF_TEST_STEP_MS, phase: "settled", localOnly: true };
319
+ });
320
+ }
321
+ function publishLocalSelfTest(record, dispatch = (event) => globalThis.dispatchEvent(event)) {
322
+ dispatch(typeof CustomEvent === "function" ? new CustomEvent(LOCAL_TEST_EVENT, { detail: record }) : { type: LOCAL_TEST_EVENT, detail: record });
323
+ }
324
+ function validSessionId(value) {
325
+ return typeof value === "string" && value.length > 0 && value.length <= 256 && /^[A-Za-z0-9._:-]+$/.test(value);
326
+ }
327
+ function revealTurn(turn, { document: doc = globalThis.document, attempts = 24, intervalMs = 80, timers = {} } = {}) {
328
+ const setTimer = timers.setTimeout ?? globalThis.setTimeout;
329
+ const clearTimer = timers.clearTimeout ?? globalThis.clearTimeout;
330
+ if (!doc?.querySelector || typeof setTimer !== "function" || !Number.isSafeInteger(turn) || turn <= 0) return () => {
331
+ };
332
+ let done = false;
333
+ let timer = null;
334
+ let left = attempts;
335
+ const clear = () => {
336
+ if (timer !== null) {
337
+ clearTimer(timer);
338
+ timer = null;
339
+ }
340
+ done = true;
341
+ };
342
+ const attempt = () => {
343
+ if (done) return;
344
+ const element = doc.querySelector(`[data-chat-turn="${turn}"]`);
345
+ if (element) {
346
+ try {
347
+ element.scrollIntoView({ block: "center", behavior: "smooth" });
348
+ } catch {
349
+ }
350
+ element.setAttribute("data-dsh-notify-turn", "highlight");
351
+ timer = setTimer(() => {
352
+ try {
353
+ element.removeAttribute("data-dsh-notify-turn");
354
+ } catch {
355
+ }
356
+ }, 2400);
357
+ done = true;
358
+ return;
359
+ }
360
+ if (--left <= 0) {
361
+ done = true;
362
+ return;
363
+ }
364
+ timer = setTimer(attempt, intervalMs);
365
+ };
366
+ timer = setTimer(attempt, 0);
367
+ return clear;
368
+ }
369
+ function isMainView(sessions, sessionId) {
370
+ const snap = sessions?.list?.getSnapshot?.();
371
+ if (snap?.current === sessionId) return true;
372
+ return (snap?.byId?.[sessionId]?.retainedBy?.mainView ?? 0) > 0;
373
+ }
374
+ async function navigateNotificationRecord(record, { sessions, uiWorkspace, acknowledge } = {}) {
375
+ const sessionId = record?.sessionId;
376
+ const snapshot = sessions?.list?.getSnapshot?.();
377
+ const goneFromList = Boolean(snapshot?.byId) && !snapshot.byId[sessionId];
378
+ if (!validSessionId(sessionId) || goneFromList) {
379
+ await acknowledge?.(record);
380
+ return { status: "acknowledged-without-session" };
381
+ }
382
+ try {
383
+ if (typeof uiWorkspace?.openSession === "function") uiWorkspace.openSession(sessionId);
384
+ else if (typeof sessions?.open === "function") {
385
+ const opened = sessions.open(sessionId);
386
+ if (opened === false) return { status: "navigation-failed" };
387
+ if (opened && typeof opened.then === "function") await opened;
388
+ } else if (!isMainView(sessions, sessionId) && !sessions?.binding?.(sessionId)) {
389
+ return { status: "navigation-failed" };
390
+ }
391
+ if (!isMainView(sessions, sessionId)) return { status: "navigation-failed" };
392
+ if (Number.isSafeInteger(record.turn) && record.turn > 0) revealTurn(record.turn);
393
+ await acknowledge?.(record);
394
+ return { status: "acknowledged" };
395
+ } catch (error) {
396
+ return { status: "failed", error };
397
+ }
398
+ }
399
+ function installAudioUnlock({ document: doc = globalThis.document, player = soundPlayer } = {}) {
400
+ if (!doc?.addEventListener) return () => {
401
+ };
402
+ const unlock = () => {
403
+ void player.unlock();
404
+ };
405
+ doc.addEventListener("pointerdown", unlock, { passive: true });
406
+ doc.addEventListener("keydown", unlock);
407
+ return () => {
408
+ doc.removeEventListener("pointerdown", unlock);
409
+ doc.removeEventListener("keydown", unlock);
410
+ };
411
+ }
412
+ async function fetchJson(path, init) {
413
+ const response = await fetch(`${BASE}${path}`, { credentials: "same-origin", ...init });
414
+ if (!response.ok) {
415
+ const error = new Error(`notify request failed: ${response.status}`);
416
+ error.status = response.status;
417
+ throw error;
418
+ }
419
+ return response.json();
420
+ }
421
+ var navigateRecord = (record, { sessions, uiWorkspace } = {}) => record?.localOnly ? Promise.resolve({ status: "local" }) : navigateNotificationRecord(record, { sessions, uiWorkspace });
422
+ function mergeRecords(previous, items) {
423
+ const merged = new Map(previous.map((record) => [record.eventId, record]));
424
+ for (const record of items) if (record?.eventId) merged.set(record.eventId, record);
425
+ return [...merged.values()].sort((a, b) => Number(b.at || 0) - Number(a.at || 0)).slice(0, RECORD_MEMORY);
426
+ }
427
+ var RECORD_MEMORY = 60;
428
+ function useNotificationState() {
429
+ const [state, setState] = import_react.default.useState({ records: [], seq: 0, primed: false, offline: false, revision: 0 });
430
+ const warned = import_react.default.useRef(false);
431
+ import_react.default.useEffect(() => {
432
+ const local = (event) => {
433
+ const record = event?.detail;
434
+ if (record?.localOnly) setState((old) => ({ ...old, records: mergeRecords(old.records, [record]), revision: old.revision + 1 }));
435
+ };
436
+ globalThis.addEventListener?.(LOCAL_TEST_EVENT, local);
437
+ return () => globalThis.removeEventListener?.(LOCAL_TEST_EVENT, local);
438
+ }, []);
439
+ import_react.default.useEffect(() => {
440
+ let alive = true;
441
+ const pull = async () => {
442
+ try {
443
+ const data = await fetchJson(`/pull?since=${state.seq}`);
444
+ if (!alive) return;
445
+ if (!Number.isSafeInteger(data?.seq) && !warned.current) {
446
+ warned.current = true;
447
+ globalThis.console?.warn?.("[dsh-notify] the host did not report a delivery sequence \u2014 restart DSH so the current plugin is loaded; until then this page only sees records it has not seen before.");
448
+ }
449
+ const seq = Number.isSafeInteger(data?.seq) ? data.seq : state.seq;
450
+ setState((old) => ({ records: mergeRecords(old.records, Array.isArray(data?.items) ? data.items : []), seq, primed: true, offline: false, revision: old.revision + 1 }));
451
+ } catch {
452
+ if (alive) setState((old) => ({ ...old, offline: true }));
453
+ }
454
+ };
455
+ pull();
456
+ const timer = setInterval(pull, 1500);
457
+ return () => {
458
+ alive = false;
459
+ clearInterval(timer);
460
+ };
461
+ }, [state.seq]);
462
+ return state;
463
+ }
464
+ function toastOrder(records = []) {
465
+ return [...records.filter((record) => record?.phase === "open"), ...records.filter((record) => record?.phase !== "open")];
466
+ }
467
+ var TOAST_TONE_BY_KIND = Object.freeze({ approval: "warning", question: "info", "plan-review": "info", completed: "success", failed: "error", "job-end": "neutral", "workflow-end": "neutral", test: "neutral" });
468
+ function toastTone(kind) {
469
+ return TOAST_TONE_BY_KIND[kind] ?? "neutral";
470
+ }
471
+ function toastIcon(tone, status = "idle") {
472
+ const shared = { "aria-hidden": true, focusable: false, width: 20, height: 20, viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", strokeWidth: 1.8, strokeLinecap: "round", strokeLinejoin: "round", className: "dsh-notify-toast-icon" };
473
+ if (status === "loading") return import_react.default.createElement("svg", { ...shared, "data-spin": "true" }, import_react.default.createElement("path", { d: "M10 3.4a6.6 6.6 0 1 1-6.6 6.6", opacity: ".9" }));
474
+ if (status === "success") return import_react.default.createElement("svg", shared, import_react.default.createElement("path", { d: "M4.5 10.4l3.6 3.6 7.4-8" }));
475
+ if (status === "error") return import_react.default.createElement("svg", shared, import_react.default.createElement("circle", { cx: 10, cy: 10, r: 7 }), import_react.default.createElement("path", { d: "M10 6.4v4.4M10 13.6h.01" }));
476
+ if (tone === "success") return import_react.default.createElement("svg", shared, import_react.default.createElement("path", { d: "M4.5 10.4l3.6 3.6 7.4-8" }));
477
+ if (tone === "error") return import_react.default.createElement("svg", shared, import_react.default.createElement("path", { d: "M5.6 5.6l8.8 8.8M14.4 5.6l-8.8 8.8" }));
478
+ if (tone === "warning") return import_react.default.createElement("svg", shared, import_react.default.createElement("path", { d: "M10 3.6l7 12.4H3z" }), import_react.default.createElement("path", { d: "M10 8.6v3.1M10 14.3h.01" }));
479
+ if (tone === "info") return import_react.default.createElement("svg", shared, import_react.default.createElement("circle", { cx: 10, cy: 10, r: 7 }), import_react.default.createElement("path", { d: "M10 9.2v4M10 6.7h.01" }));
480
+ return import_react.default.createElement("svg", shared, import_react.default.createElement("path", { d: "M10 3.2a4.3 4.3 0 0 0-4.3 4.3c0 3.2-1.2 4.2-1.2 4.2h11s-1.2-1-1.2-4.2A4.3 4.3 0 0 0 10 3.2z" }), import_react.default.createElement("path", { d: "M8.6 14.4a1.6 1.6 0 0 0 2.8 0" }));
481
+ }
482
+ var toastConfig = { toastPosition: "conversation", toastEnabled: true, soundEnabled: true, sound: "chime" };
483
+ function createSoundPlayer({ audio = globalThis, AudioContextClass, AudioElementClass } = {}) {
484
+ let context = null;
485
+ let unlocked = false;
486
+ const elements = /* @__PURE__ */ new Set();
487
+ const contextClass = () => AudioContextClass ?? audio?.AudioContext ?? audio?.webkitAudioContext;
488
+ const elementClass = () => AudioElementClass ?? audio?.Audio;
489
+ const create = () => {
490
+ if (context) return context;
491
+ const Klass = contextClass();
492
+ if (typeof Klass !== "function") return null;
493
+ try {
494
+ context = new Klass();
495
+ } catch {
496
+ context = null;
497
+ }
498
+ return context;
499
+ };
500
+ const unlock = async () => {
501
+ const target = create();
502
+ if (!target) return false;
503
+ try {
504
+ if (target.state === "suspended") await target.resume();
505
+ } catch {
506
+ return false;
507
+ }
508
+ unlocked = target.state === "running";
509
+ return unlocked;
510
+ };
511
+ const playPreset = (id) => {
512
+ const notes = SOUND_PRESETS[id] ?? SOUND_PRESETS.chime;
513
+ if (notes.length === 0) return { played: false, reason: "silent" };
514
+ const target = create();
515
+ if (!target) return { played: false, reason: "unsupported" };
516
+ if (target.state !== "running") return { played: false, reason: "locked" };
517
+ try {
518
+ const start = target.currentTime;
519
+ for (const note of notes) {
520
+ const oscillator = target.createOscillator();
521
+ const gain = target.createGain();
522
+ oscillator.type = note.type;
523
+ oscillator.frequency.value = note.freq;
524
+ gain.gain.setValueAtTime(0, start + note.at);
525
+ gain.gain.linearRampToValueAtTime(note.gain, start + note.at + 0.01);
526
+ gain.gain.exponentialRampToValueAtTime(1e-4, start + note.at + note.dur);
527
+ oscillator.connect(gain);
528
+ gain.connect(target.destination);
529
+ oscillator.start(start + note.at);
530
+ oscillator.stop(start + note.at + note.dur + 0.02);
531
+ }
532
+ return { played: true, reason: "played" };
533
+ } catch {
534
+ return { played: false, reason: "failed" };
535
+ }
536
+ };
537
+ const playCustom = async (name) => {
538
+ const Klass = elementClass();
539
+ if (typeof Klass !== "function") return { played: false, reason: "unsupported" };
540
+ try {
541
+ const element = new Klass(`${BASE}/sound?name=${encodeURIComponent(name)}`);
542
+ elements.add(element);
543
+ element.addEventListener?.("ended", () => elements.delete(element), { once: true });
544
+ await element.play();
545
+ return { played: true, reason: "played" };
546
+ } catch (error) {
547
+ return { played: false, reason: error?.name === "NotAllowedError" ? "locked" : "failed" };
548
+ }
549
+ };
550
+ return {
551
+ unlock,
552
+ get unlocked() {
553
+ return unlocked;
554
+ },
555
+ get locked() {
556
+ return Boolean(create()) && !unlocked;
557
+ },
558
+ /**
559
+ * Play the configured sound. This deliberately plays while the page is in the background: the
560
+ * whole point of the cue is the case where the user is in another app (a movie, an editor) and
561
+ * cannot see the tab title flash or a browser banner. Muting a hidden page made the cue useless
562
+ * exactly when it mattered, so visibility is no longer part of the decision.
563
+ */
564
+ async play(choice = toastConfig.sound, { enabled = toastConfig.soundEnabled } = {}) {
565
+ if (!enabled) return { played: false, reason: "disabled" };
566
+ const parsed = parseSoundChoice(choice);
567
+ return parsed.kind === "custom" ? playCustom(parsed.name) : playPreset(parsed.id);
568
+ },
569
+ stop() {
570
+ for (const element of elements) {
571
+ try {
572
+ element.pause?.();
573
+ } catch {
574
+ }
575
+ }
576
+ elements.clear();
577
+ }
578
+ };
579
+ }
580
+ var soundPlayer = createSoundPlayer();
581
+ var ATTENTION_DOT = `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><circle cx="8" cy="8" r="7" fill="#e5484d"/></svg>')}`;
582
+ function createAttentionIndicator({ document: doc = globalThis.document, timers = {}, intervalMs = 900, reducedMotion = globalThis.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches === true } = {}) {
583
+ const setTimer = timers.setInterval ?? globalThis.setInterval;
584
+ const clearTimer = timers.clearInterval ?? globalThis.clearInterval;
585
+ let timer = null;
586
+ let active = false;
587
+ let baseTitle = null;
588
+ let baseIcon = null;
589
+ let iconNode = null;
590
+ let phase = false;
591
+ const paint = () => {
592
+ const marked = active && phase;
593
+ if (doc && baseTitle !== null) doc.title = marked ? `\u{1F514} ${baseTitle}` : baseTitle;
594
+ if (iconNode) iconNode.href = marked ? ATTENTION_DOT : baseIcon;
595
+ };
596
+ const stop = () => {
597
+ if (timer !== null) {
598
+ clearTimer(timer);
599
+ timer = null;
600
+ }
601
+ if (!active) return;
602
+ active = false;
603
+ phase = false;
604
+ if (doc && baseTitle !== null) doc.title = baseTitle;
605
+ if (iconNode && baseIcon !== null) iconNode.href = baseIcon;
606
+ if (iconNode && baseIcon === null) {
607
+ try {
608
+ iconNode.remove();
609
+ } catch {
610
+ }
611
+ }
612
+ iconNode = null;
613
+ baseTitle = null;
614
+ baseIcon = null;
615
+ };
616
+ return {
617
+ get active() {
618
+ return active;
619
+ },
620
+ /** Flashing is worth it only for a background tab with something still unread. */
621
+ update({ unread = 0, visible = true } = {}) {
622
+ const wanted = Boolean(unread > 0 && !visible);
623
+ if (wanted === active) return;
624
+ if (!wanted) {
625
+ stop();
626
+ return;
627
+ }
628
+ if (!doc) return;
629
+ baseTitle = doc.title ?? "";
630
+ iconNode = doc.querySelector?.('link[rel~="icon"]') ?? null;
631
+ if (iconNode) baseIcon = iconNode.getAttribute?.("href") ?? iconNode.href ?? null;
632
+ active = true;
633
+ phase = true;
634
+ paint();
635
+ if (reducedMotion || typeof setTimer !== "function") return;
636
+ timer = setTimer(() => {
637
+ phase = !phase;
638
+ paint();
639
+ }, intervalMs);
640
+ },
641
+ stop
642
+ };
643
+ }
644
+ var attentionIndicator = createAttentionIndicator();
645
+ function setToastConfig(config = {}) {
646
+ toastConfig = { ...toastConfig, ...config };
647
+ globalThis.dispatchEvent?.(new Event("dsh-notify:toast-config"));
648
+ }
649
+ var TOAST_STACK_VISIBLE = 5;
650
+ var TOAST_STACK_VISIBLE_NARROW = 3;
651
+ var TOAST_STACK_GAP = 12;
652
+ var TOAST_STACK_PEEK = 10;
653
+ var TOAST_QUEUE_MAX = 50;
654
+ var TOAST_EXIT_MS = 200;
655
+ var TOAST_SUCCESS_MS = 900;
656
+ function queueCards(cards = [], max = TOAST_QUEUE_MAX) {
657
+ const pending = cards.filter((card) => card?.record?.phase === "open");
658
+ const finished = cards.filter((card) => card?.record?.phase !== "open");
659
+ return [...pending, ...finished].slice(0, Math.max(1, max));
660
+ }
661
+ function toastTime(at, now = Date.now()) {
662
+ const stamp = Number(at);
663
+ if (!Number.isFinite(stamp) || stamp <= 0) return null;
664
+ const date = new Date(stamp);
665
+ if (Number.isNaN(date.getTime())) return null;
666
+ const pad = (value) => String(value).padStart(2, "0");
667
+ const clock = `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
668
+ const today = new Date(Number.isFinite(Number(now)) ? Number(now) : Date.now());
669
+ const sameDay = date.getFullYear() === today.getFullYear() && date.getMonth() === today.getMonth() && date.getDate() === today.getDate();
670
+ return { label: sameDay ? clock : `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${clock.slice(0, 5)}`, title: `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${clock}`, iso: date.toISOString() };
671
+ }
672
+ function toastStackPlan({ heights = [], gap = TOAST_STACK_GAP } = {}) {
673
+ let cursor = 0;
674
+ return heights.map((height) => {
675
+ const plan = { offsetY: cursor };
676
+ cursor += (Number(height) || 0) + gap;
677
+ return plan;
678
+ });
679
+ }
680
+ function stackWindow({ heights = [], visible = TOAST_STACK_VISIBLE, gap = TOAST_STACK_GAP, peek = TOAST_STACK_PEEK } = {}) {
681
+ const list = (Array.isArray(heights) ? heights : []).map((height) => Number(height) || 0);
682
+ const count = Math.max(1, visible);
683
+ const onScreen = list.slice(0, count);
684
+ const sum = (values) => values.reduce((total, height) => total + height, 0) + gap * Math.max(0, values.length - 1);
685
+ const hidden = Math.max(0, list.length - onScreen.length);
686
+ const windowHeight = sum(onScreen);
687
+ return { total: list.length, hidden, windowHeight: windowHeight + (hidden > 0 ? peek : 0), contentHeight: sum(list), overflow: hidden > 0 };
688
+ }
689
+ function ToastOverlay({ sessions, uiWorkspace, pendingInteractions } = {}) {
690
+ const state = useNotificationState();
691
+ const [, refresh] = import_react.default.useState(0);
692
+ const [cards, setCards] = import_react.default.useState([]);
693
+ const [anchor, setAnchor] = import_react.default.useState(() => toastAnchor());
694
+ const [, rerender] = import_react.default.useState(0);
695
+ const toasted = import_react.default.useRef(/* @__PURE__ */ new Set());
696
+ const primed = import_react.default.useRef(false);
697
+ const pendingStore = import_react.default.useMemo(() => ({ subscribe: (listener) => pendingInteractions?.subscribe?.(listener) ?? (() => {
698
+ }), getSnapshot: () => pendingInteractions?.getSnapshot?.() ?? null }), [pendingInteractions]);
699
+ const pending = import_react.default.useSyncExternalStore(pendingStore.subscribe, pendingStore.getSnapshot, () => null);
700
+ const frameRef = import_react.default.useRef(null);
701
+ const stackRef = import_react.default.useRef(null);
702
+ const exits = import_react.default.useRef(/* @__PURE__ */ new Map());
703
+ const successes = import_react.default.useRef(/* @__PURE__ */ new Map());
704
+ const heights = import_react.default.useRef(/* @__PURE__ */ new Map());
705
+ const nodes = import_react.default.useRef(/* @__PURE__ */ new Map());
706
+ const slots = import_react.default.useRef(/* @__PURE__ */ new Map());
707
+ const unseen = import_react.default.useRef(/* @__PURE__ */ new Set());
708
+ const sawPending = import_react.default.useRef(/* @__PURE__ */ new Set());
709
+ const cardsRef = import_react.default.useRef(cards);
710
+ const anyCard = cards.length > 0;
711
+ const rerenderNow = () => rerender((value) => value + 1);
712
+ const commit = (next) => {
713
+ cardsRef.current = next;
714
+ setCards(next);
715
+ };
716
+ const forget = (eventId) => {
717
+ heights.current.delete(eventId);
718
+ };
719
+ const retire = (eventId) => {
720
+ const previous = exits.current.get(eventId);
721
+ if (previous) clearTimeout(previous);
722
+ exits.current.set(eventId, setTimeout(() => {
723
+ exits.current.delete(eventId);
724
+ forget(eventId);
725
+ commit(cardsRef.current.filter((card) => card.record.eventId !== eventId));
726
+ }, TOAST_EXIT_MS));
727
+ };
728
+ const dismiss = (eventId, { animate = true } = {}) => {
729
+ const success = successes.current.get(eventId);
730
+ if (success) {
731
+ clearTimeout(success);
732
+ successes.current.delete(eventId);
733
+ }
734
+ if (!animate) {
735
+ forget(eventId);
736
+ commit(cardsRef.current.filter((card) => card.record.eventId !== eventId));
737
+ return;
738
+ }
739
+ commit(cardsRef.current.map((card) => card.record.eventId === eventId ? { ...card, leaving: true } : card));
740
+ retire(eventId);
741
+ };
742
+ const patchCard = (eventId, patch) => commit(cardsRef.current.map((card) => card.record.eventId === eventId ? { ...card, ...patch } : card));
743
+ const measureOne = (eventId, node) => {
744
+ const height = Math.ceil(node.offsetHeight || node.getBoundingClientRect?.().height || 0);
745
+ if (!height || heights.current.get(eventId) === height) return false;
746
+ heights.current.set(eventId, height);
747
+ return true;
748
+ };
749
+ const measure = (eventId) => (node) => {
750
+ if (!node) {
751
+ nodes.current.delete(eventId);
752
+ return;
753
+ }
754
+ nodes.current.set(eventId, node);
755
+ if (measureOne(eventId, node)) rerenderNow();
756
+ };
757
+ const measureAll = () => {
758
+ let changed = false;
759
+ for (const [eventId, node] of nodes.current) if (measureOne(eventId, node)) changed = true;
760
+ if (changed) rerenderNow();
761
+ };
762
+ import_react.default.useEffect(() => {
763
+ const onConfig = () => refresh((n) => n + 1);
764
+ globalThis.addEventListener?.("dsh-notify:toast-config", onConfig);
765
+ return () => globalThis.removeEventListener?.("dsh-notify:toast-config", onConfig);
766
+ }, []);
767
+ import_react.default.useEffect(() => watchToastAnchor((next) => setAnchor((prev) => prev === next ? prev : next)), []);
768
+ import_react.default.useEffect(() => {
769
+ setAnchor(toastAnchor());
770
+ }, [cards.length]);
771
+ import_react.default.useEffect(() => () => {
772
+ for (const id of exits.current.values()) clearTimeout(id);
773
+ for (const id of successes.current.values()) clearTimeout(id);
774
+ }, []);
775
+ import_react.default.useLayoutEffect(() => {
776
+ const element = frameRef.current;
777
+ if (!anyCard || !element) return void 0;
778
+ if (typeof element.showPopover === "function") {
779
+ try {
780
+ if (!element.hasAttribute("popover")) element.setAttribute("popover", "manual");
781
+ if (!element.matches?.(":popover-open")) element.showPopover();
782
+ } catch {
783
+ }
784
+ }
785
+ measureAll();
786
+ return () => {
787
+ try {
788
+ element.hidePopover?.();
789
+ } catch {
790
+ }
791
+ };
792
+ }, [anyCard]);
793
+ const showToast = (record) => {
794
+ if (!record?.eventId) return;
795
+ if (globalThis.document?.hidden) unseen.current.add(record.eventId);
796
+ toasted.current.add(record.eventId);
797
+ const incoming = [{ record, status: "idle", error: null, lastLabel: null, leaving: false }, ...cardsRef.current.filter((card) => card.record.eventId !== record.eventId)];
798
+ const next = queueCards(incoming);
799
+ for (const card of incoming) if (!next.includes(card)) forget(card.record.eventId);
800
+ commit(next);
801
+ void soundPlayer.play();
802
+ };
803
+ import_react.default.useEffect(() => {
804
+ const local = (event) => {
805
+ if (event?.detail?.localOnly) showToast(event.detail);
806
+ };
807
+ globalThis.addEventListener?.(LOCAL_TEST_EVENT, local);
808
+ return () => globalThis.removeEventListener?.(LOCAL_TEST_EVENT, local);
809
+ }, []);
810
+ const scrollWindow = () => {
811
+ const element = stackRef.current;
812
+ if (!element || typeof element.scrollTo !== "function") return;
813
+ const atEnd = element.scrollTop + element.clientHeight >= (element.scrollHeight ?? 0) - 2;
814
+ element.scrollTo({ top: atEnd ? 0 : element.scrollHeight, behavior: "smooth" });
815
+ };
816
+ import_react.default.useEffect(() => {
817
+ const open = new Set(cards.map((card) => card.record.eventId));
818
+ for (const id of sawPending.current) if (!open.has(id)) sawPending.current.delete(id);
819
+ for (const card of cards) {
820
+ if (card.leaving || card.record.phase !== "open") continue;
821
+ if (pendingInteractionFor(pending, card.record.sessionId)) {
822
+ sawPending.current.add(card.record.eventId);
823
+ continue;
824
+ }
825
+ if (sawPending.current.has(card.record.eventId)) dismiss(card.record.eventId);
826
+ }
827
+ }, [pending, cards]);
828
+ import_react.default.useEffect(() => {
829
+ if (!state.primed) return;
830
+ const seen = toasted.current;
831
+ const ids = new Set(state.records.map((record) => record.eventId));
832
+ for (const id of seen) if (!ids.has(id)) seen.delete(id);
833
+ if (!primed.current) {
834
+ primed.current = true;
835
+ for (const id of ids) seen.add(id);
836
+ return;
837
+ }
838
+ for (const card of cardsRef.current) {
839
+ const live = state.records.find((record) => record.eventId === card.record.eventId);
840
+ if (!live || live === card.record) continue;
841
+ const wasWaiting = card.record.phase === "open";
842
+ patchCard(card.record.eventId, { record: live });
843
+ if (wasWaiting && live.phase !== "open") dismiss(card.record.eventId);
844
+ }
845
+ const fresh = toastOrder(state.records).filter((record) => !seen.has(record.eventId));
846
+ for (const record of fresh.reverse()) showToast(record);
847
+ }, [state.records, state.primed]);
848
+ import_react.default.useEffect(() => {
849
+ const sync = () => {
850
+ const hidden = Boolean(globalThis.document?.hidden);
851
+ if (!hidden) unseen.current.clear();
852
+ attentionIndicator.update({ unread: hidden && toastConfig.toastPosition !== "off" ? unseen.current.size : 0, visible: !hidden });
853
+ };
854
+ sync();
855
+ globalThis.document?.addEventListener?.("visibilitychange", sync);
856
+ return () => globalThis.document?.removeEventListener?.("visibilitychange", sync);
857
+ }, [cards.length, state.records]);
858
+ if (!anyCard || !toastConfig.toastEnabled || toastConfig.toastPosition === "off") return null;
859
+ const narrow = layoutFor({ width: globalThis.innerWidth }).narrow;
860
+ const activate = async (card) => {
861
+ const eventId = card.record.eventId;
862
+ const result = await navigateRecord(card.record, { sessions, uiWorkspace });
863
+ if (result?.status === "acknowledged" || result?.status === "local") {
864
+ dismiss(eventId);
865
+ return;
866
+ }
867
+ const error = !validSessionId(card.record.sessionId) ? "\u8FD9\u6761\u901A\u77E5\u6CA1\u6709\u53EF\u4EE5\u6253\u5F00\u7684\u4F1A\u8BDD" : result?.status === "acknowledged-without-session" ? "\u8FD9\u4E2A\u4F1A\u8BDD\u5DF2\u7ECF\u4E0D\u5728\u4E86\uFF0C\u65E0\u6CD5\u6253\u5F00" : "\u6CA1\u80FD\u6253\u5F00\u8FD9\u4E2A\u4F1A\u8BDD\uFF0C\u518D\u70B9\u4E00\u6B21\u8BD5\u8BD5";
868
+ patchCard(eventId, { status: "error", error, lastLabel: null });
869
+ };
870
+ const submitAnswer = async (card, label) => {
871
+ const interaction = pendingInteractionFor(pending, card.record.sessionId);
872
+ const answer = toastAnswer(card.record, interaction);
873
+ if (!answer) {
874
+ patchCard(card.record.eventId, { status: "error", error: "\u8FD9\u6761\u5DF2\u7ECF\u4E0D\u80FD\u5728\u8FD9\u91CC\u56DE\u7B54\u4E86\uFF0C\u8BF7\u5230\u4F1A\u8BDD\u91CC\u5904\u7406", lastLabel: label });
875
+ return;
876
+ }
877
+ patchCard(card.record.eventId, { status: "loading", error: null, lastLabel: label });
878
+ try {
879
+ await interaction.answer(answerBatch(answer.id, label));
880
+ patchCard(card.record.eventId, { status: "success", error: null });
881
+ const previous = successes.current.get(card.record.eventId);
882
+ if (previous) clearTimeout(previous);
883
+ successes.current.set(card.record.eventId, setTimeout(() => {
884
+ successes.current.delete(card.record.eventId);
885
+ dismiss(card.record.eventId);
886
+ }, TOAST_SUCCESS_MS));
887
+ } catch (error) {
888
+ patchCard(card.record.eventId, { status: "error", error: error?.message || "\u56DE\u7B54\u5931\u8D25\uFF0C\u8BF7\u5230\u4F1A\u8BDD\u91CC\u56DE\u7B54", lastLabel: label });
889
+ }
890
+ };
891
+ const actionRow = (card) => {
892
+ const record = card.record;
893
+ const busy = card.status === "loading";
894
+ const buttons = [];
895
+ if (record.kind === "question" || record.kind === "plan-review") {
896
+ const answer = toastAnswer(record, pendingInteractionFor(pending, record.sessionId));
897
+ if (answer) for (const option of answer.options) buttons.push(import_react.default.createElement("button", { key: option.label, type: "button", className: "dsh-notify-toast-answer", title: option.description, disabled: busy, onClick: (event) => {
898
+ event.stopPropagation();
899
+ void submitAnswer(card, option.label);
900
+ } }, option.label));
901
+ buttons.push(import_react.default.createElement("button", { key: "session", type: "button", className: "dsh-notify-toast-answer", "data-variant": "quiet", disabled: busy, onClick: (event) => {
902
+ event.stopPropagation();
903
+ void activate(card);
904
+ } }, "\u53BB\u4F1A\u8BDD\u91CC\u56DE\u7B54"));
905
+ }
906
+ if (card.status === "error" && card.lastLabel) buttons.push(import_react.default.createElement("button", { key: "retry", type: "button", className: "dsh-notify-toast-answer", onClick: (event) => {
907
+ event.stopPropagation();
908
+ void submitAnswer(card, card.lastLabel);
909
+ } }, "\u91CD\u8BD5"));
910
+ const note = card.status === "error" ? import_react.default.createElement("span", { className: "dsh-notify-toast-error", role: "status" }, card.error || "\u64CD\u4F5C\u5931\u8D25") : card.status === "loading" ? import_react.default.createElement("span", { className: "dsh-notify-toast-hint", role: "status" }, "\u6B63\u5728\u63D0\u4EA4\u2026") : card.status === "success" ? import_react.default.createElement("span", { className: "dsh-notify-toast-hint", role: "status" }, "\u5DF2\u5B8C\u6210") : null;
911
+ if (!buttons.length && !note) return null;
912
+ return import_react.default.createElement("div", { className: "dsh-notify-toast-answers" }, buttons, note);
913
+ };
914
+ const cardView = (card, plan) => {
915
+ const record = card.record;
916
+ const status = card.status;
917
+ const tone = status === "error" ? "error" : status === "success" ? "success" : toastTone(record.kind);
918
+ const source = sessionLabel(sessions, record.sessionId);
919
+ const stamp = toastTime(record.at);
920
+ const slotStyle = { transform: `translateY(${plan.offsetY}px)` };
921
+ return import_react.default.createElement(
922
+ "div",
923
+ { key: record.eventId, className: "dsh-notify-slot", style: slotStyle },
924
+ import_react.default.createElement(
925
+ "aside",
926
+ {
927
+ ref: measure(record.eventId),
928
+ role: "status",
929
+ "aria-live": "polite",
930
+ className: "dsh-notify-toast",
931
+ "data-tone": tone,
932
+ "data-status": status,
933
+ "data-leaving": card.leaving ? "true" : "false",
934
+ onClick: () => {
935
+ if (!card.leaving) void activate(card);
936
+ }
937
+ },
938
+ toastIcon(tone, status),
939
+ import_react.default.createElement(
940
+ "div",
941
+ { className: "dsh-notify-toast-body" },
942
+ import_react.default.createElement(
943
+ "span",
944
+ { className: "dsh-notify-toast-head" },
945
+ // The time leads the metadata row the session name already occupies: no new line, no third
946
+ // column, and fixed-width digits line the clocks up down the stack. It must not take the
947
+ // right end of that row — the `+N` chip and the close button live there, and the chip is
948
+ // pinned to the corner rather than to a card, so anything right-aligned would slide under it.
949
+ stamp ? import_react.default.createElement("time", { className: "dsh-notify-toast-time", dateTime: stamp.iso, title: stamp.title }, stamp.label) : null,
950
+ source ? import_react.default.createElement("span", { className: "dsh-notify-toast-source", title: record.sessionId }, source) : null
951
+ ),
952
+ import_react.default.createElement("strong", { className: "dsh-notify-toast-title" }, record.title),
953
+ record.body ? import_react.default.createElement("p", { className: "dsh-notify-toast-text" }, record.body) : null,
954
+ actionRow(card)
955
+ ),
956
+ import_react.default.createElement("button", { type: "button", className: "dsh-notify-toast-close", "aria-label": "\u5173\u95ED\u901A\u77E5", onClick: (event) => {
957
+ event.stopPropagation();
958
+ dismiss(record.eventId);
959
+ } }, "\xD7")
960
+ )
961
+ );
962
+ };
963
+ const liveCards = cards.filter((card) => !card.leaving);
964
+ const liveHeights = liveCards.map((card) => heights.current.get(card.record.eventId) ?? 0);
965
+ const plans = toastStackPlan({ heights: liveHeights });
966
+ const frame = stackWindow({ heights: liveHeights, visible: narrow ? TOAST_STACK_VISIBLE_NARROW : TOAST_STACK_VISIBLE });
967
+ const planById = new Map(liveCards.map((card, index) => [card.record.eventId, plans[index]]));
968
+ for (const [eventId, plan] of planById) slots.current.set(eventId, plan);
969
+ const queueCount = frame.overflow ? frame.total : 0;
970
+ const onScreenCount = Math.max(0, frame.total - frame.hidden);
971
+ const rendered = [...liveCards, ...cards.filter((card) => card.leaving)];
972
+ return import_react.default.createElement(
973
+ "div",
974
+ {
975
+ ref: frameRef,
976
+ popover: "manual",
977
+ className: "dsh-notify-frame",
978
+ style: { inset: "auto", insetInlineEnd: narrow ? 12 : toastConfig.toastPosition === "viewport" ? 16 : anchor, insetInlineStart: "auto", bottom: "auto", top: "calc(env(safe-area-inset-top, 0px) + var(--dsh-toast-top-offset, 56px))", width: narrow ? "calc(100vw - 24px)" : "min(360px, calc(100vw - 32px))", height: `${frame.windowHeight}px`, margin: 0, padding: 0, border: 0, background: "transparent", overflow: "visible" }
979
+ },
980
+ queueCount > 0 ? import_react.default.createElement("button", { type: "button", className: "dsh-notify-count", "aria-label": `\u672C\u9875\u5171 ${queueCount} \u6761\u901A\u77E5`, title: `\u5171 ${queueCount} \u6761\uFF0C\u5DF2\u663E\u793A ${onScreenCount} \u6761\uFF0C\u70B9\u51FB\u5728\u961F\u5217\u4E24\u7AEF\u4E4B\u95F4\u8DF3\u8F6C`, onClick: (event) => {
981
+ event.stopPropagation();
982
+ scrollWindow();
983
+ } }, `+${queueCount}`) : null,
984
+ import_react.default.createElement(
985
+ "div",
986
+ { ref: stackRef, className: "dsh-notify-stack", "data-overflow": frame.overflow ? "true" : "false" },
987
+ import_react.default.createElement(
988
+ "div",
989
+ { className: "dsh-notify-stack-inner", style: { height: `${frame.contentHeight}px` } },
990
+ rendered.map((card) => cardView(card, planById.get(card.record.eventId) ?? slots.current.get(card.record.eventId) ?? { offsetY: frame.contentHeight }))
991
+ )
992
+ )
993
+ );
994
+ }
995
+ function sessionLabel(sessions, sessionId) {
996
+ if (typeof sessionId !== "string" || sessionId === "") return null;
997
+ try {
998
+ const summary = sessions?.list?.getSnapshot?.()?.byId?.[sessionId];
999
+ const title = summary && summary.blank !== true && typeof summary.displayTitle === "string" ? summary.displayTitle.trim() : "";
1000
+ if (title) return title;
1001
+ } catch {
1002
+ }
1003
+ return sessionId.length > 12 ? `${sessionId.slice(0, 8)}\u2026` : sessionId;
1004
+ }
1005
+ function pendingInteractionFor(pending, sessionId) {
1006
+ if (!pending || typeof pending.get !== "function" || typeof sessionId !== "string") return null;
1007
+ return pending.get(sessionId) ?? null;
1008
+ }
1009
+ function toastAnswer(record, interaction) {
1010
+ if (!interaction || typeof interaction.answer !== "function") return null;
1011
+ if (record?.kind !== "question" && record?.kind !== "plan-review") return null;
1012
+ const questions = Array.isArray(interaction.questions) ? interaction.questions : [];
1013
+ if (questions.length !== 1) return null;
1014
+ const question = questions[0] ?? {};
1015
+ if (question.multiSelect === true) return null;
1016
+ const options = (Array.isArray(question.options) ? question.options : []).filter((option) => option && typeof option.label === "string" && option.label);
1017
+ if (options.length === 0 || options.length > 4) return null;
1018
+ return { id: typeof question.id === "string" ? question.id : String(question.id ?? ""), options: options.map((option) => ({ label: option.label, description: typeof option.description === "string" ? option.description : void 0 })) };
1019
+ }
1020
+ function answerBatch(questionId, label) {
1021
+ return { answers: [{ id: questionId, selected: [label] }] };
1022
+ }
1023
+ function statusTone(text = "") {
1024
+ const value = String(text);
1025
+ if (/失败|错误/.test(value)) return "error";
1026
+ if (/不可用|未配置/.test(value)) return "warn";
1027
+ if (/已连接|已保存|已清空|已订阅|已退订/.test(value)) return "ok";
1028
+ return "idle";
1029
+ }
1030
+ function resultTone(status) {
1031
+ if (status === "passed") return "passed";
1032
+ if (status === "failed") return "failed";
1033
+ if (status === "running" || status === "submitted") return "active";
1034
+ return "idle";
1035
+ }
1036
+ var action = (label, onClick, extra = {}) => import_react.default.createElement("button", { className: "dsh-notify-action", type: "button", onClick, ...extra }, label);
1037
+ var hint = (children) => import_react.default.createElement("p", { className: "dsh-notify-hint" }, children);
1038
+ function NotificationSelfTests() {
1039
+ const [state, setState] = import_react.default.useState(null);
1040
+ const fireOne = () => {
1041
+ publishLocalSelfTest(createLocalSelfTestRecord());
1042
+ setState({ status: "passed", reason: "\u9875\u9762\u6D6E\u5C42\u5DF2\u6E32\u67D3\uFF08\u4E00\u6761\uFF09" });
1043
+ };
1044
+ const fire = (count) => {
1045
+ for (const record of createLocalSelfTestBatch({ count })) publishLocalSelfTest(record);
1046
+ setState({ status: "passed", reason: `\u9875\u9762\u6D6E\u5C42\u5DF2\u6E32\u67D3\uFF08${Math.min(count, SELF_TEST_BATCH.length)} \u6761\uFF09` });
1047
+ };
1048
+ return import_react.default.createElement(
1049
+ "section",
1050
+ { className: "dsh-notify-card", "aria-label": "\u901A\u77E5\u81EA\u6D4B" },
1051
+ import_react.default.createElement("h3", { className: "dsh-notify-card-title" }, "\u81EA\u6D4B"),
1052
+ hint("\u53EA\u6709\u9875\u9762\u91CC\u8FD9\u4E00\u6761\u901A\u9053\uFF1A\u53F3\u4E0A\u89D2\u6D6E\u5C42 + \u63D0\u793A\u97F3 + \u540E\u53F0\u6807\u7B7E\u9875\u95EA\u52A8\u3002\u8FD9\u91CC\u53D1\u51FA\u7684\u5361\u7247\u53EA\u6E32\u67D3\u5728\u5F53\u524D\u9875\u9762\uFF0C\u4E0D\u4F1A\u5916\u53D1\u7CFB\u7EDF\u901A\u77E5\u3002"),
1053
+ import_react.default.createElement(
1054
+ "div",
1055
+ { className: "dsh-notify-actions" },
1056
+ action("\u6D4B\u8BD5\u4E00\u6761", fireOne),
1057
+ action(`\u6D4B\u8BD5 ${TOAST_STACK_VISIBLE} \u6761`, () => fire(TOAST_STACK_VISIBLE)),
1058
+ action(`\u6D4B\u8BD5 ${SELF_TEST_BATCH.length} \u6761`, () => fire(SELF_TEST_BATCH.length))
1059
+ ),
1060
+ hint(`\u300C\u6D4B\u8BD5 ${TOAST_STACK_VISIBLE} \u6761\u300D\u6B63\u597D\u586B\u6EE1\u89D2\u4E0A\u90A3\u4E00\u7A97\uFF1B\u300C\u6D4B\u8BD5 ${SELF_TEST_BATCH.length} \u6761\u300D\u591A\u51FA ${SELF_TEST_BATCH.length - TOAST_STACK_VISIBLE} \u6761\uFF0C\u89D2\u4E0A\u4ECD\u7136\u53EA\u5360\u4E00\u7A97\u7684\u9AD8\u5EA6\uFF0C\u524D\u9762\u90A3\u5F20\u5361\u53F3\u4E0A\u89D2\u663E\u793A\u603B\u6570\u300C+${SELF_TEST_BATCH.length}\u300D\uFF0C\u5728\u901A\u77E5\u533A\u91CC\u5411\u4E0B\u6EDA\u52A8\u5C31\u80FD\u770B\u5230\u5269\u4E0B\u7684 ${SELF_TEST_BATCH.length - TOAST_STACK_VISIBLE} \u6761\u3002`),
1061
+ state ? import_react.default.createElement("p", { className: "dsh-notify-result", role: "status", "data-tone": resultTone(state.status) }, `${state.status}: ${state.reason}`) : null
1062
+ );
1063
+ }
1064
+ function SettingsSection() {
1065
+ const [config, setConfig] = import_react.default.useState(null);
1066
+ const [status, setStatus] = import_react.default.useState("\u6B63\u5728\u52A0\u8F7D\u2026");
1067
+ const [customSounds, setCustomSounds] = import_react.default.useState([]);
1068
+ const [soundNotice, setSoundNotice] = import_react.default.useState(null);
1069
+ const loadSounds = () => fetchJson("/sounds").then((value) => setCustomSounds(Array.isArray(value?.custom) ? value.custom : [])).catch(() => setCustomSounds([]));
1070
+ const uploadSound = async (file) => {
1071
+ setSoundNotice(`\u6B63\u5728\u4E0A\u4F20 ${file.name}\u2026`);
1072
+ try {
1073
+ const bytes = await file.arrayBuffer();
1074
+ const result = await fetchJson("/sounds", { method: "POST", headers: { "x-sound-name": file.name, "content-type": "application/octet-stream" }, body: bytes });
1075
+ setSoundNotice(result?.ok ? `\u5DF2\u4E0A\u4F20 ${result.name}` : `\u4E0A\u4F20\u5931\u8D25\uFF08${result?.error || "unknown"}\uFF09`);
1076
+ await loadSounds();
1077
+ } catch (error) {
1078
+ setSoundNotice(error?.status === 413 ? "\u6587\u4EF6\u8D85\u8FC7 1 MB" : "\u4E0A\u4F20\u5931\u8D25\uFF1A\u4EC5\u652F\u6301 mp3 / m4a / aac / wav / ogg / flac\uFF0C\u4E14\u4E0D\u80FD\u8D85\u8FC7 1 MB");
1079
+ }
1080
+ };
1081
+ const removeSound = async (name) => {
1082
+ try {
1083
+ await fetchJson("/sounds/delete", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ confirm: true, name }) });
1084
+ setSoundNotice(`\u5DF2\u5220\u9664 ${name}`);
1085
+ } catch {
1086
+ setSoundNotice("\u5220\u9664\u5931\u8D25");
1087
+ }
1088
+ await loadSounds();
1089
+ };
1090
+ import_react.default.useEffect(() => {
1091
+ fetchJson("/config").then((value) => {
1092
+ setConfig(value);
1093
+ setToastConfig(value ?? {});
1094
+ setStatus(value?.storage?.preferences === "session" ? "\u901A\u77E5\u5DF2\u8FDE\u63A5\uFF08\u8BBE\u7F6E\u4E0D\u843D\u76D8\uFF09" : "\u901A\u77E5\u5DF2\u8FDE\u63A5");
1095
+ }).catch(() => setStatus("\u901A\u77E5\u540C\u6B65\u4E0D\u53EF\u7528"));
1096
+ void loadSounds();
1097
+ }, []);
1098
+ const update = async (patch) => {
1099
+ setToastConfig(patch);
1100
+ try {
1101
+ const next = await fetchJson("/config", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(patch) });
1102
+ setConfig(next);
1103
+ setStatus("\u8BBE\u7F6E\u5DF2\u4FDD\u5B58");
1104
+ } catch {
1105
+ setStatus("\u8BBE\u7F6E\u4FDD\u5B58\u5931\u8D25");
1106
+ }
1107
+ };
1108
+ return import_react.default.createElement(
1109
+ "section",
1110
+ { className: "dsh-notify-settings", "aria-label": "\u901A\u77E5\u8BBE\u7F6E" },
1111
+ import_react.default.createElement("h2", { className: "dsh-notify-heading" }, "\u901A\u77E5"),
1112
+ import_react.default.createElement("p", { className: "dsh-notify-status", role: "status", "data-tone": statusTone(status) }, status),
1113
+ config && import_react.default.createElement(
1114
+ "div",
1115
+ { className: "dsh-notify-card" },
1116
+ import_react.default.createElement("h3", { className: "dsh-notify-card-title" }, "\u63D0\u793A\u901A\u9053"),
1117
+ import_react.default.createElement("label", { className: "dsh-notify-field" }, import_react.default.createElement("span", null, "Toast\u4F4D\u7F6E"), import_react.default.createElement("select", { className: "dsh-notify-select", "aria-label": "Toast\u4F4D\u7F6E", value: config.toastPosition || "conversation", onChange: (event) => update({ toastPosition: event.target.value }) }, import_react.default.createElement("option", { value: "conversation" }, "\u4F1A\u8BDD\u533A\u53F3\u4E0A\uFF08\u9ED8\u8BA4\uFF09"), import_react.default.createElement("option", { value: "viewport" }, "\u5C4F\u5E55\u53F3\u4E0A"), import_react.default.createElement("option", { value: "off" }, "\u5173\u95ED\uFF08\u4EC0\u4E48\u90FD\u4E0D\u63D0\u793A\uFF09"))),
1118
+ hint("\u6D6E\u5C42\u53EA\u662F\u9875\u5185\u63D0\u793A\u3002\u5173\u6389\u4E4B\u540E\u4E0D\u518D\u5F39\u5361\u3001\u4E5F\u4E0D\u518D\u95EA\u52A8\u6807\u7B7E\u9875\u2014\u2014\u300C\u4EFB\u52A1\u5B8C\u6210\u65F6\u544A\u8BC9\u6211\u300D\u8FD9\u4EF6\u4E8B\u5C31\u6CA1\u6709\u522B\u7684\u901A\u9053\u4E86\u3002"),
1119
+ import_react.default.createElement("label", { className: "dsh-notify-toggle" }, import_react.default.createElement("input", { type: "checkbox", checked: Boolean(config.subtaskNotify), onChange: (event) => update({ subtaskNotify: event.target.checked }) }), import_react.default.createElement("span", null, "\u5B50\u4EFB\u52A1 / \u540E\u53F0\u4EFB\u52A1\u5B8C\u6210\u65F6\u901A\u77E5")),
1120
+ hint("\u9ED8\u8BA4\u5173\u95ED\uFF1A\u6BCF\u4E2A\u5B50\u4EE3\u7406\u3001\u540E\u53F0\u4EFB\u52A1\u7ED3\u675F\u90FD\u4F1A\u5404\u5F39\u4E00\u6761\uFF08\u6807\u9898\u5E38\u5E38\u662F\u547D\u4EE4\u539F\u6587\uFF09\uFF0C\u5F00\u4E45\u4E86\u4F1A\u5F88\u4E71\u3002\u9700\u8981\u65F6\u518D\u6253\u5F00\u3002"),
1121
+ hint("\u4E0D\u4FDD\u5B58\u5386\u53F2\uFF1A\u5361\u7247\u5C31\u662F\u4F60\u770B\u5230\u7684\u90A3\u4E00\u6761\uFF0C\u5173\u6389\u5373\u7ED3\u675F\u3002\u9875\u9762\u6CA1\u6253\u5F00\u65F6\u53D1\u751F\u7684\u901A\u77E5\u4E0D\u4F1A\u8865\u53D1\u2014\u2014\u8FD9\u662F\u53BB\u6389\u5B58\u50A8\u6362\u6765\u7684\u7B80\u5316\u3002")
1122
+ ),
1123
+ config && import_react.default.createElement(NotificationSelfTests),
1124
+ config && import_react.default.createElement(
1125
+ "div",
1126
+ { className: "dsh-notify-card" },
1127
+ import_react.default.createElement("h3", { className: "dsh-notify-card-title" }, "\u63D0\u793A\u97F3"),
1128
+ import_react.default.createElement("label", { className: "dsh-notify-toggle" }, import_react.default.createElement("input", { type: "checkbox", checked: config.soundEnabled !== false, onChange: (event) => update({ soundEnabled: event.target.checked }) }), import_react.default.createElement("span", null, "\u9875\u5185\u63D0\u793A\u97F3\uFF08\u7A97\u53E3\u4E0D\u5728\u6700\u524D\u4E5F\u4F1A\u54CD\uFF09")),
1129
+ import_react.default.createElement(
1130
+ "label",
1131
+ { className: "dsh-notify-field" },
1132
+ import_react.default.createElement("span", null, "\u58F0\u97F3"),
1133
+ import_react.default.createElement(
1134
+ "select",
1135
+ { className: "dsh-notify-select", "aria-label": "\u63D0\u793A\u97F3", value: config.sound || "chime", onChange: (event) => update({ sound: event.target.value }) },
1136
+ BUILTIN_SOUNDS.map((id) => import_react.default.createElement("option", { key: id, value: id }, SOUND_LABELS[id] ?? id)),
1137
+ ...customSounds.map((sound) => import_react.default.createElement("option", { key: `custom:${sound.name}`, value: `custom:${sound.name}` }, `\u81EA\u5B9A\u4E49\uFF1A${sound.name}`))
1138
+ )
1139
+ ),
1140
+ import_react.default.createElement(
1141
+ "div",
1142
+ { className: "dsh-notify-actions" },
1143
+ import_react.default.createElement("button", { className: "dsh-notify-action", type: "button", onClick: () => {
1144
+ void soundPlayer.unlock().then(() => soundPlayer.play(config.sound || "chime", { enabled: true })).then((result) => setSoundNotice(result?.reason === "locked" ? "\u6D4F\u89C8\u5668\u8981\u6C42\u5148\u70B9\u4E00\u4E0B\u9875\u9762\u624D\u80FD\u51FA\u58F0\uFF1A\u8BF7\u518D\u70B9\u4E00\u6B21\u300C\u8BD5\u542C\u300D" : result?.played ? "\u5DF2\u8BD5\u542C" : `\u6CA1\u51FA\u58F0\uFF08${result?.reason || "unknown"}\uFF09`));
1145
+ } }, "\u8BD5\u542C"),
1146
+ import_react.default.createElement("label", { className: "dsh-notify-action", style: { cursor: "pointer" } }, "\u4E0A\u4F20\u58F0\u97F3\u2026", import_react.default.createElement("input", { type: "file", accept: "audio/*,.mp3,.m4a,.wav,.ogg,.flac", style: { display: "none" }, onChange: (event) => {
1147
+ const file = event.target.files?.[0];
1148
+ event.target.value = "";
1149
+ if (file) void uploadSound(file);
1150
+ } }))
1151
+ ),
1152
+ hint("\u7A97\u53E3\u4E0D\u5728\u6700\u524D\u3001\u6807\u7B7E\u5728\u540E\u53F0\u65F6\u4E5F\u4F1A\u54CD\u2014\u2014\u8FD9\u662F\u300C\u6D4F\u89C8\u5668\u88AB\u522B\u7684\u5E94\u7528\u6321\u4F4F\u300D\u65F6\u552F\u4E00\u80FD\u63D0\u9192\u4F60\u7684\u65B9\u5F0F\u3002\u5185\u7F6E\u97F3\u7531\u6D4F\u89C8\u5668\u5408\u6210\uFF08\u4E0D\u4E0B\u8F7D\u4EFB\u4F55\u6587\u4EF6\uFF09\uFF1B\u81EA\u5B9A\u4E49\u97F3\u4E0A\u4F20\u5230\u672C profile \u7684\u6570\u636E\u76EE\u5F55\uFF0C\u91CD\u88C5\u63D2\u4EF6\u4E0D\u4F1A\u4E22\u3002\u4E0A\u4F20\u4E0A\u9650 1 MB\uFF0C\u4EC5\u652F\u6301 mp3 / m4a / aac / wav / ogg / flac\u3002"),
1153
+ soundNotice ? import_react.default.createElement("p", { className: "dsh-notify-result", role: "status" }, soundNotice) : null,
1154
+ customSounds.length > 0 && import_react.default.createElement("div", { className: "dsh-notify-actions" }, customSounds.map((sound) => import_react.default.createElement("button", { key: sound.name, type: "button", className: "dsh-notify-action", "data-variant": "danger", onClick: () => void removeSound(sound.name) }, `\u5220\u9664 ${sound.name}`)))
1155
+ )
1156
+ );
1157
+ }
1158
+ var CLIENT_COMPOSITION = Object.freeze({ service: "slots", modules: Object.freeze(["@deepseek-ai/dsh-client-ui-renderer", "@deepseek-ai/dsh-client-ui-layout", "@deepseek-ai/dsh-client-ui-settings", "@deepseek-ai/dsh-client-ui-settings-general"]), seats: Object.freeze(["settings.section", "shell.overlay"]) });
1159
+ function mountNotifyClient({ slots, sessions, uiWorkspace, getSessions, getUiSession, getUiWorkspace } = {}) {
1160
+ const status = { service: slots?.inject && slots?.register ? "available" : "unavailable", seats: {} };
1161
+ if (status.service === "unavailable") return { status, destroy() {
1162
+ } };
1163
+ const pendingInteractions = () => getUiSession?.()?.pendingInteractions;
1164
+ const disposers = [installClientStyles(), installAudioUnlock()];
1165
+ const activate = (name, options, Component) => {
1166
+ status.seats[name] = "active";
1167
+ const dispose = slots.register({ name, ...options }, Component);
1168
+ return () => {
1169
+ status.seats[name] = "waiting";
1170
+ dispose?.();
1171
+ };
1172
+ };
1173
+ status.seats["settings.section"] = "waiting";
1174
+ try {
1175
+ disposers.push(slots.inject("settings.section", () => activate("settings.section", { id: "dsh-notify", order: 100, label: "\u901A\u77E5", inject: () => ({ sessions: sessions ?? getSessions?.() }) }, SettingsSection)));
1176
+ } catch {
1177
+ status.seats["settings.section"] = "unavailable";
1178
+ }
1179
+ status.seats["shell.overlay"] = "waiting";
1180
+ try {
1181
+ disposers.push(slots.inject("shell.overlay", () => activate("shell.overlay", { id: "dsh-notify-toast", order: 100, inject: () => ({ sessions: sessions ?? getSessions?.(), uiWorkspace: uiWorkspace ?? getUiWorkspace?.(), pendingInteractions: pendingInteractions() }) }, ToastOverlay)));
1182
+ } catch {
1183
+ status.seats["shell.overlay"] = "unavailable";
1184
+ }
1185
+ return { status, destroy() {
1186
+ for (const dispose of disposers.reverse()) dispose?.();
1187
+ } };
1188
+ }
1189
+ function apply(ctx) {
1190
+ return mountNotifyClient({ slots: ctx?.slots, getSessions: () => ctx?.get?.("sessions"), getUiSession: () => ctx?.get?.("uiSession"), getUiWorkspace: () => ctx?.get?.("uiWorkspace") });
1191
+ }
1192
+
1193
+ return module.exports;
1194
+ },
1195
+ });