dsh-notification-focus 0.0.0-stage → 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/client.js ADDED
@@ -0,0 +1,988 @@
1
+ // origin: opencode-agent/hy4-flash-free | 2026-11-25 | client 半身:焦点上报(对齐已验证的 dsh-mobile-layout-fix 骨架)
2
+ //
3
+ // 重写说明(W3 承诺修好焦点):
4
+ // 旧版用 factory(require) + require('react') + inject:['uiSession','slots'],client 半身从未加载。
5
+ // 本机同型插件 @local/dsh-mobile-layout-fix 用「factory() 无参 + 不 require + inject:[]」能正常工作。
6
+ // 本版对齐该骨架:只做焦点上报(纯 DOM,不需要 react),会话 key 用 ctx.get() 惰性取。
7
+ // 验证期 CLIENT_DIAG=true;确认修好后改回 false。浮窗功能独立实验,仍不启用。
8
+
9
+ const FOCUS_ROUTE = '/api/dsh-notify/focus'
10
+ const DIAG_ROUTE = '/api/dsh-notify/diag'
11
+ const SNOOZE_ROUTE = '/api/dsh-notify/snooze'
12
+ const CONFIG_ROUTE = '/api/dsh-notify/config'
13
+ const TEST_ROUTE = '/api/dsh-notify/test'
14
+ const PREVIEW_ROUTE = '/api/dsh-notify/preview'
15
+ const IDLE_ROUTE = '/api/dsh-notify/idle'
16
+ const HISTORY_ROUTE = '/api/dsh-notify/history'
17
+ const NAVIGATE_ROUTE = '/api/dsh-notify/navigate'
18
+ const VOICES_ROUTE = '/api/dsh-notify/voices'
19
+ const RENDER_ERROR_ROUTE = '/api/dsh-notify/render-error'
20
+ const CLIENT_DIAG = false // 诊断默认关;排障时改 true 并重启 DSH
21
+ function cdiag(msg) {
22
+ if (!CLIENT_DIAG) return
23
+ try { void fetch(DIAG_ROUTE, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ msg: String(msg) }) }).catch(() => {}) } catch { /* ignore */ }
24
+ }
25
+ const IDLE_DEFAULT_MS = 3 * 60 * 1000
26
+ const IDLE_STORAGE_KEY = 'dsh-notification.idleMs'
27
+ const ACTIVITY_EVENTS = ['pointerdown', 'pointermove', 'keydown', 'wheel', 'touchstart']
28
+ const ALL_KINDS = ['success', 'approval', 'needs-input', 'error']
29
+ const KIND_LABELS = { success: '任务完成', approval: '需要批准', 'needs-input': '等你回答', error: '出错' }
30
+ // 保存提示里显示中文名,别把内部字段名(sounds / quietStart …)直接抛给用户
31
+ const FIELD_LABELS = {
32
+ enabled: '总开关', types: '提醒类型', sounds: '提示音', quiet: '静音时段', idleEnabled: '空闲提醒',
33
+ idleMs: '空闲时长', approvalGraceMs: '审批等待', alwaysNotify: '在场也提醒', clickEnabled: '点通知回 DSH',
34
+ approvalButtons: '审批按钮', approveEnabled: '允许批准一次', ttsEnabled: '语音播报', ttsVoice: '播报音色',
35
+ customSounds: '自定义音效', historyEnabled: '通知历史', mutedSessions: '会话免打扰', snoozeUntil: '临时静音',
36
+ }
37
+ const SOUND_LABELS = {
38
+ 'Notification.Default': '默认', 'Notification.IM': '消息', 'Notification.Mail': '邮件',
39
+ 'Notification.Reminder': '提醒', 'Notification.LoopingCall': '循环来电', 'Notification.LoopingAlarm': '循环闹钟',
40
+ 'Notification.LoopingAlarm2': '循环闹钟2', 'Notification.LoopingCall2': '循环来电2', 'None': '静音',
41
+ }
42
+
43
+ // 试听:在下拉里选中某个音效时让它立刻响一次,用户不用等真的通知才知道是什么声音。
44
+ // 只发请求不等待;失败静默(试听失败绝不能影响保存设置)。
45
+ function previewSound(sound) {
46
+ try {
47
+ void fetch(PREVIEW_ROUTE, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ sound: String(sound) }) }).catch(() => {})
48
+ } catch { /* ignore */ }
49
+ }
50
+
51
+ window.__ModuleLoader__.load({
52
+ id: 'dsh-notification-focus',
53
+ factory(require) {
54
+ cdiag('factory called')
55
+ // React 是宿主静态 seed,try/catch 防御;失败不影响焦点/静音等核心功能。
56
+ let React = null
57
+ // DSH 0.2.2 实测:rename 会按 80 UTF-8 字节静默截断(约 26 汉字)。
58
+ // 这里复刻一个预览用规范化,实时显示已用字节;真正写回仍交给 DSH Host。
59
+ const TITLE_MAX_BYTES = 80
60
+ const cleanTitle = (s) => String(s ?? '')
61
+ .replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g, '')
62
+ .replace(/\u001B\[[0-?]*[ -/]*[@-~]/g, '')
63
+ .replace(/\u001B[@-_]/g, '')
64
+ .replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/g, '')
65
+ .replace(/[\u200E\u200F\u202A-\u202E\u2066-\u206F]/g, '')
66
+ .replace(/\s+/gu, ' ').trim()
67
+ const previewTitleBytes = (s) => {
68
+ const clean = cleanTitle(s)
69
+ const enc = new TextEncoder()
70
+ let used = 0, out = ''
71
+ for (const ch of clean) {
72
+ const n = enc.encode(ch).length
73
+ if (used + n > TITLE_MAX_BYTES) break
74
+ out += ch; used += n
75
+ }
76
+ let total = 0
77
+ for (const ch of clean) total += enc.encode(ch).length
78
+ return { bytes: used, text: out.trimEnd(), over: total > TITLE_MAX_BYTES }
79
+ }
80
+
81
+ let viewCtx = null // 供设置页的"打开会话"调用 uiWorkspace.openSession
82
+ // uiWorkspace 不进 inject(硬门卫会让整个 client 停摆);惰性取,取不到只影响跳会话
83
+ function openSessionSafe(sessionId) {
84
+ try {
85
+ const ws = viewCtx?.get?.('uiWorkspace')
86
+ if (ws && typeof ws.openSession === 'function') { ws.openSession(sessionId); return true }
87
+ } catch { /* ignore */ }
88
+ return false
89
+ }
90
+ try { React = require('react') } catch { cdiag('react unavailable') }
91
+
92
+ // DSH 原生 UI 原语(Switch/Button);拿不到就回退美化过的原生控件,不白屏。
93
+ let P = null
94
+ try { P = require('@deepseek-ai/dsh-client-ui-primitives') } catch { cdiag('primitives unavailable') }
95
+
96
+ // 设置页样式:一次注入、带命名空间、全用 DSH token(跟随主题),不用逐元素 inline。
97
+ const SETTINGS_CSS_ID = 'dsh-notify-settings-css'
98
+ function injectSettingsCss() {
99
+ if (document.getElementById(SETTINGS_CSS_ID)) return
100
+ const style = document.createElement('style')
101
+ style.id = SETTINGS_CSS_ID
102
+ style.textContent = `
103
+ .dshnotify-wrap{display:flex;flex-direction:column;gap:12px;max-width:760px;color:var(--dsw-alias-label-primary,#0f1115);font-family:"Microsoft YaHei UI","Microsoft YaHei","PingFang SC","Hiragino Sans GB","Segoe UI",Arial,sans-serif;font-synthesis-weight:none}
104
+ .dshnotify-sec{font-size:12px;line-height:18px;font-weight:400;letter-spacing:.02em;color:var(--dsw-alias-label-secondary,#61666b)}
105
+ .dshnotify-row{display:flex;align-items:center;justify-content:space-between;gap:24px;padding:16px 0;border-bottom:.5px solid var(--dsw-alias-border-l2,rgba(0,0,0,.1))}
106
+ .dshnotify-row:last-child{border-bottom:none}
107
+ .dshnotify-rowtitle{font-size:14px;line-height:20px;color:var(--dsw-alias-label-primary,#0f1115)}
108
+ .dshnotify-rowdesc{margin-top:4px;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary,#61666b)}
109
+ .dshnotify-select{display:inline-flex;align-items:center;justify-content:space-between;gap:12px;min-width:130px;height:34px;padding:0 12px;border:.5px solid var(--dsw-alias-border-l4,rgba(0,0,0,.16));border-radius:var(--dsw-radius-md,12px);background:var(--dsw-alias-bg-layer-3,#fff);font:inherit;font-size:13px;line-height:1.5;color:var(--dsw-alias-label-primary,#0f1115);cursor:pointer}
110
+ .dshnotify-select:focus-visible{outline:none;border-color:var(--dsw-alias-state-business-primary,#4176e6)}
111
+ @media (hover:hover){.dshnotify-select:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(38,49,72,.06))}}
112
+ .dshnotify-save{height:34px;padding:0 16px;border:none;border-radius:var(--dsw-radius-md,12px);background:var(--dsw-alias-state-business-primary,#4176e6);color:#fff;font:inherit;font-size:13px;font-weight:400;cursor:pointer}
113
+ .dshnotify-save:hover{filter:brightness(1.08)}
114
+ .dshnotify-note{font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary,#81858c)}
115
+ .dshnotify-check{width:18px;height:18px;accent-color:var(--dsw-alias-state-business-primary,#4176e6);cursor:pointer}
116
+ .dshnotify-history{display:flex;flex-direction:column;gap:6px;max-height:220px;overflow:auto}
117
+ .dshnotify-hitem{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:8px 10px;border-radius:6px;background:var(--dsw-alias-bg-l2,rgba(127,127,127,.08));font-size:12px}
118
+ .dshnotify-hitem button{cursor:pointer;background:none;border:none;color:var(--dsw-alias-state-business-primary,#4176e6)}
119
+ .dshnotify-risk{font-size:11px;line-height:16px;color:var(--dsw-alias-state-warn-primary,#b26a00);opacity:.9}
120
+ .dshnotify-wsgroup{display:flex;align-items:center;gap:8px;min-height:28px;padding:8px 0 2px;border-bottom:2px solid var(--dsw-alias-border-l4,rgba(0,0,0,.16));cursor:pointer;font-size:14px;font-weight:400;line-height:22px;color:var(--dsw-alias-label-primary,#0f1115)}
121
+ .dshnotify-wsgroup-open{border-bottom:none;padding-bottom:0}
122
+ .dshnotify-mute-row{position:relative;padding-left:20px}
123
+ /* 子会话之间细线;每组最后一项用粗线分隔下一个工作区 */
124
+ .dshnotify-mute-row:not(.dshnotify-mute-row-last)::after{content:"";position:absolute;left:20px;right:0;bottom:0;height:1px;background:var(--dsw-alias-border-l3,rgba(0,0,0,.06))}
125
+ .dshnotify-mute-row-last::after{content:"";position:absolute;left:0;right:0;bottom:0;height:2px;background:var(--dsw-alias-border-l4,rgba(0,0,0,.16))}
126
+ .dshnotify-name-editor input{font-size:14px;line-height:22px}
127
+ .dshnotify-wsgroup-name{flex:0 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
128
+ .dshnotify-wsgroup-count{margin-left:auto;flex:none;text-align:right;font-size:12px;font-weight:400;line-height:16px;color:var(--dsw-alias-label-tertiary,#81858c);font-variant-numeric:tabular-nums}
129
+ .dshnotify-folder{display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;flex:none;color:var(--dsw-alias-label-tertiary,#81858c)}
130
+ .dshnotify-folder-active{color:var(--dsw-alias-state-business-primary,#4176e6)}
131
+ .dshnotify-chevron{flex:none;font-size:11px;color:var(--dsw-alias-label-tertiary,#81858c)}
132
+ .dshnotify-mute-title{font-size:14px;line-height:22px;font-weight:400;color:var(--dsw-alias-label-primary,#0f1115);word-break:break-word;overflow-wrap:anywhere}
133
+ .dshnotify-mute-line{position:relative;display:flex;align-items:baseline;gap:8px;flex-wrap:wrap;min-width:0}
134
+ .dshnotify-name-bubble{position:absolute;left:0;top:100%;margin-top:6px;z-index:5;max-width:280px;padding:6px 10px;border-radius:8px;background:var(--dsw-alias-bg-layer-3,#fff);border:.5px solid var(--dsw-alias-border-l4,rgba(0,0,0,.16));box-shadow:0 4px 14px rgba(0,0,0,.12);font-size:11px;line-height:16px;color:var(--dsw-alias-label-secondary,#61666b)}
135
+ .dshnotify-name-btn{flex:none;padding:0 2px;border:none;background:none;color:var(--dsw-alias-state-business-primary,#4176e6);font:inherit;font-size:11px;line-height:18px;cursor:pointer;opacity:.85}
136
+ .dshnotify-name-btn:hover{opacity:1;text-decoration:underline}
137
+ .dshnotify-name-editor{display:flex;align-items:center;gap:8px;flex:1;min-width:0}
138
+ .dshnotify-name-editor input{flex:1;min-width:0;height:28px;padding:0 10px;font:inherit;font-size:14px;line-height:22px;border:.5px solid var(--dsw-alias-border-l4,rgba(0,0,0,.16));border-radius:8px;background:var(--dsw-alias-bg-layer-3,#fff);color:var(--dsw-alias-label-primary,#0f1115)}
139
+ .dshnotify-mini{flex:none;min-width:0;height:28px;padding:0 10px;font:inherit;font-size:12px;line-height:20px;border:.5px solid var(--dsw-alias-border-l4,rgba(0,0,0,.16));border-radius:8px;background:var(--dsw-alias-bg-layer-3,#fff);color:var(--dsw-alias-label-primary,#0f1115);cursor:pointer}
140
+ .dshnotify-mini-save{border:none;background:var(--dsw-alias-state-business-primary,#4176e6);color:#fff}
141
+ .dshnotify-name-count{font-size:11px;line-height:16px;white-space:nowrap;color:var(--dsw-alias-label-tertiary,#81858c)}
142
+ `
143
+ document.head.appendChild(style)
144
+ }
145
+
146
+ // 🔔 会话免打扰:按「工作区目录名 → 底下各对话」分组。
147
+ // DSH 0.2.2 源码实证:session 行没有 header.title,标题走 s.title / s.displayTitle;
148
+ // 工作区可读名不在 session 上,要用 ctx.get('workspaces') 的 sessionIds 反查,
149
+ // 拿不到就用 s.cwd 的目录名回退。动态 get + try/catch,避免把 workspaces 加进 inject
150
+ // 触发硬门卫(那会让整个 client 停摆)。
151
+ function baseNameOf(path) {
152
+ if (typeof path !== 'string' || !path) return ''
153
+ const t = path.replace(/[/\\]+$/, '')
154
+ const i = Math.max(t.lastIndexOf('/'), t.lastIndexOf('\\'))
155
+ return t.slice(i + 1)
156
+ }
157
+ const MUTE_EXPANDED_KEY = 'dsh-notification.mute-expanded'
158
+ function readMuteExpanded() {
159
+ try {
160
+ const raw = window.localStorage.getItem(MUTE_EXPANDED_KEY)
161
+ const o = raw ? JSON.parse(raw) : {}
162
+ return o && typeof o === 'object' && !Array.isArray(o) ? o : {}
163
+ } catch { return {} }
164
+ }
165
+ function writeMuteExpanded(map) {
166
+ try { window.localStorage.setItem(MUTE_EXPANDED_KEY, JSON.stringify(map || {})) } catch { /* ignore */ }
167
+ }
168
+ // DSH 侧栏自己的视图偏好(用于读取 orderBy / 手动排序),读不到就用默认值。
169
+ function readWorkspaceView() {
170
+ try {
171
+ const raw = window.localStorage.getItem('dsh.workspace.view.v5')
172
+ const o = raw ? JSON.parse(raw) : {}
173
+ return o && typeof o === 'object' ? o : {}
174
+ } catch { return {} }
175
+ }
176
+
177
+ // 会话名从 session/title 事件取(这才是名字),绝不拿首条用户消息当名字。
178
+ // DSH 入库时会截断标题(回退 5 词/40 字节,用户改名上限 80 字节),这里能拿到事件里存的名字;
179
+ // 拿不到就退回 byId.title。用 sessions.retain 打开事件窗口,读完立刻释放。
180
+ async function loadSessionTitle(sessionId) {
181
+ let ref = null
182
+ try {
183
+ if (!viewCtx?.sessions?.retain || typeof sessionId !== 'string') return null
184
+ ref = viewCtx.sessions.retain(sessionId, { source: 'dsh-notification-mute' })
185
+ const binding = await ref.ready
186
+ const entries = binding?.eventSource?.getSnapshot?.()?.entries
187
+ if (!Array.isArray(entries)) return null
188
+ let name = null
189
+ for (const entry of entries) {
190
+ if (entry?.event?.type === 'session/title' && typeof entry.event.data?.title === 'string') {
191
+ name = entry.event.data.title // 取最后一条,即当前会话名
192
+ }
193
+ }
194
+ return name
195
+ } catch { return null } finally {
196
+ try { if (ref && typeof ref.release === 'function') ref.release() } catch { /* ignore */ }
197
+ }
198
+ }
199
+
200
+ // 🔴 用户点「保存」后才写回 DSH 的 session/title;ref.rename 是 0.2.2 实测 API。
201
+ async function renameSessionTitle(sessionId, title) {
202
+ let ref = null
203
+ try {
204
+ if (!viewCtx?.sessions?.retain || typeof title !== 'string' || !title.trim()) return null
205
+ ref = viewCtx.sessions.retain(sessionId, { source: 'dsh-notification-rename' })
206
+ await ref.ready
207
+ const res = await ref.rename?.(title)
208
+ return res && res.ok && res.value ? res.value : null
209
+ } catch { return null } finally {
210
+ try { if (ref && typeof ref.release === 'function') ref.release() } catch { /* ignore */ }
211
+ }
212
+ }
213
+
214
+ function listMuteSessions() {
215
+ const byId = viewCtx?.sessions?.list?.getSnapshot?.()?.byId
216
+ if (!byId || typeof byId !== 'object') return []
217
+
218
+ let wsSnap = null
219
+ try { wsSnap = viewCtx?.get?.('workspaces')?.list?.getSnapshot?.() } catch { /* 工作区服务不可用 */ }
220
+ const items = Array.isArray(wsSnap?.items) ? wsSnap.items : []
221
+ // 归档/置顶都是数组(DSH 源码实证),转成 Set 过滤
222
+ const archived = new Set(Array.isArray(wsSnap?.archivedSessionIds) ? wsSnap.archivedSessionIds : [])
223
+ const pinned = new Set(Array.isArray(wsSnap?.pinnedSessionIds) ? wsSnap.pinnedSessionIds : [])
224
+ const view = readWorkspaceView()
225
+ const manual = view.orderBy === 'manual'
226
+ const manualOrders = view.sessionOrderByAccount && typeof view.sessionOrderByAccount === 'object'
227
+ ? view.sessionOrderByAccount : {}
228
+ const currentId = Object.keys(byId).find(id => (byId[id]?.retainedBy?.mainView ?? 0) > 0)
229
+
230
+ const recency = (ids) => ids
231
+ .map(id => ({ id, at: Number(byId[id]?.updatedAt) || 0 }))
232
+ .sort((a, b) => (b.at - a.at) || (a.id < b.id ? -1 : 1))
233
+ .map(x => x.id)
234
+
235
+ const groups = []
236
+ const accounted = new Set()
237
+ // 工作区之间的顺序 = DSH 自己的 items 数组顺序(Host 持久化顺序),不按标题重排
238
+ for (const ws of items) {
239
+ const key = ws.workspaceId || ws.title || ''
240
+ const workspace = (typeof ws.title === 'string' && ws.title && ws.title !== 'default-workspace')
241
+ ? ws.title : (baseNameOf(ws.path) || '工作区')
242
+ let ids = Array.isArray(ws.sessionIds) ? ws.sessionIds.slice() : []
243
+ if (manual) {
244
+ const saved = Array.isArray(manualOrders[ws.workspaceId]) ? manualOrders[ws.workspaceId] : []
245
+ const ordered = []
246
+ for (const id of saved) if (ids.includes(id) && !ordered.includes(id)) ordered.push(id)
247
+ for (const id of pinned) if (ids.includes(id) && !ordered.includes(id)) ordered.push(id)
248
+ for (const id of recency(ids)) if (!ordered.includes(id)) ordered.push(id)
249
+ ids = ordered
250
+ } else {
251
+ const base = recency(ids)
252
+ const pins = base.filter(id => pinned.has(id) && !archived.has(id))
253
+ ids = [...pins, ...base.filter(id => !pins.includes(id))]
254
+ }
255
+ // 空白的当前会话永远置顶(DSH 的 pinCurrentBlank)
256
+ if (currentId && ids.includes(currentId) && byId[currentId]?.blank === true) {
257
+ ids = [currentId, ...ids.filter(id => id !== currentId)]
258
+ }
259
+ const sessions = []
260
+ for (const id of ids) {
261
+ const s = byId[id]
262
+ if (!s || accounted.has(id)) continue
263
+ accounted.add(id)
264
+ if (archived.has(id)) continue // 用户要求:归档会话不显示
265
+ if (s.origin === 'subagent') continue
266
+ if (s.blank === true && id !== currentId) continue
267
+ sessions.push({
268
+ id,
269
+ title: typeof s.title === 'string' && s.title.trim() ? s.title.trim()
270
+ : (typeof s.displayTitle === 'string' && s.displayTitle && s.displayTitle !== s.id ? s.displayTitle : '未命名对话'),
271
+ current: id === currentId,
272
+ })
273
+ }
274
+ groups.push({ key, workspace, sessions, containsCurrent: sessions.some(s => s.current) })
275
+ }
276
+ // 没有归属工作区的会话放最后,同样按 DSH 默认 recency 排
277
+ const strayIds = recency(Object.keys(byId).filter(id => !accounted.has(id)))
278
+ // 工作区服务不可用时,回退按会话 cwd 的目录名分组(DSH 源码的 workspaceLabel 做法)
279
+ const strayGroups = new Map()
280
+ for (const id of strayIds) {
281
+ const s = byId[id]
282
+ if (!s || archived.has(id) || s.origin === 'subagent' || (s.blank === true && id !== currentId)) continue
283
+ const label = baseNameOf(s.cwd) || '未分组'
284
+ if (!strayGroups.has(label)) strayGroups.set(label, [])
285
+ strayGroups.get(label).push({
286
+ id,
287
+ title: typeof s.title === 'string' && s.title.trim() ? s.title.trim()
288
+ : (typeof s.displayTitle === 'string' && s.displayTitle && s.displayTitle !== s.id ? s.displayTitle : '未命名对话'),
289
+ current: id === currentId,
290
+ })
291
+ }
292
+ for (const [label, sessions] of strayGroups) {
293
+ groups.push({ key: 'stray-' + label, workspace: label, sessions, containsCurrent: sessions.some(s => s.current) })
294
+ }
295
+ return groups.slice(0, 30)
296
+ }
297
+
298
+ // 设置页组件(React.createElement,不用 JSX)
299
+ function SettingsView() {
300
+ const [state, setState] = React.useState({ enabled: true, types: [], sounds: {}, choices: [], idleEnabled: false, idleSeconds: 60, quietStart: '', quietEnd: '', graceSeconds: 6, alwaysNotify: false, clickEnabled: false, pauseButtons: false, approvalButtons: false, approveEnabled: false, ttsEnabled: false, ttsVoice: '', voices: [], customSounds: {}, historyEnabled: true, historyItems: [], mutedSessions: [], muteExpanded: readMuteExpanded(), fullTitles: {}, renameDraft: null, renameNotice: null, loading: true, saved: false, saveError: '', autoStatus: '' })
301
+ // 自动保存定时器不能捕获旧 render 的 state;ref 永远指向最新值
302
+ // 🔴 必须是真正的 React.useRef:普通对象字面量每次 render 都重建,
303
+ // GET 写入的 ready/baseline 根本到不了用户改设置的那一轮 render(自动保存永不触发)。
304
+ const stateRef = React.useRef(state)
305
+ stateRef.current = state
306
+ const aliveFlag = React.useRef(true)
307
+ const dirtyRef = React.useRef(false) // 用户在启动 GET 返回前已改过,则 GET 不得覆盖
308
+ const noticeTimer = React.useRef(null)
309
+ // 命名反馈:只在名字旁边弹一个气泡,2.6 秒后自动消失,不占列表高度
310
+ const showRenameNotice = (sessionId, text) => {
311
+ if (noticeTimer.current) clearTimeout(noticeTimer.current)
312
+ setState(prev => ({ ...prev, renameNotice: { sessionId, text } }))
313
+ noticeTimer.current = setTimeout(() => {
314
+ noticeTimer.current = null
315
+ if (!aliveFlag.current) return
316
+ setState(prev => prev.renameNotice && prev.renameNotice.sessionId === sessionId
317
+ ? { ...prev, renameNotice: null } : prev)
318
+ }, 2600)
319
+ }
320
+ React.useEffect(() => () => {
321
+ aliveFlag.current = false
322
+ if (noticeTimer.current) clearTimeout(noticeTimer.current)
323
+ }, [])
324
+ React.useEffect(() => {
325
+ injectSettingsCss()
326
+ let alive = true
327
+ fetch(CONFIG_ROUTE, { headers: { accept: 'application/json' } })
328
+ .then(r => r.ok ? r.json() : null)
329
+ // 🔴 白屏根因:这里原来用 setState({...}) 整体替换 state,丢掉了 voices / historyItems,
330
+ // 导致 state.voices.map(...) 抛 "Cannot read properties of undefined (reading 'map')"。
331
+ // 必须合并进旧 state,并对两个异步字段做兜底。
332
+ .then(d => { if (alive && d) setState(s => {
333
+ const merged = {
334
+ ...s,
335
+ enabled: d.enabled !== false, types: d.types || [], sounds: d.sounds || {}, choices: d.choices || [],
336
+ idleEnabled: d.idleEnabled === true, idleSeconds: Math.max(1, Math.min(86400, Math.round(Number(d.idleMs) / 1000) || 60)),
337
+ quietStart: d.quietStart || '', quietEnd: d.quietEnd || '',
338
+ graceSeconds: Math.max(0, Math.min(60, Math.round(Number(d.approvalGraceMs) / 1000) || 0)),
339
+ alwaysNotify: d.alwaysNotify === true, clickEnabled: d.clickEnabled === true, pauseButtons: false,
340
+ approvalButtons: d.approvalButtons === true, approveEnabled: d.approveEnabled === true,
341
+ ttsEnabled: d.ttsEnabled === true, ttsVoice: d.ttsVoice || '', customSounds: d.customSounds || {},
342
+ historyEnabled: d.historyEnabled !== false,
343
+ // 🔔 免打扰列表随配置一起读回;合并式 setState 不能丢掉 voices/historyItems
344
+ mutedSessions: Array.isArray(d.mutedSessions) ? d.mutedSessions : (Array.isArray(s.mutedSessions) ? s.mutedSessions : []),
345
+ voices: Array.isArray(s.voices) ? s.voices : [],
346
+ historyItems: Array.isArray(s.historyItems) ? s.historyItems : [],
347
+ // 用户已在 GET 返回前改过这些字段,保留本地值
348
+ ...(dirtyRef.current ? { types: s.types, mutedSessions: s.mutedSessions } : {}),
349
+ loading: false, saved: false,
350
+ }
351
+ // 以磁盘值为自动保存基线,避免刚加载完就回写一次
352
+ baselineRef.current = configFields(merged)
353
+ autoSaveRef.current.last = configSignature(merged)
354
+ autoSaveRef.current.ready = true
355
+ return merged
356
+ }) })
357
+ .catch(() => { if (alive) setState(s => {
358
+ baselineRef.current = configFields(s)
359
+ autoSaveRef.current.last = configSignature(s)
360
+ autoSaveRef.current.ready = true
361
+ return { ...s, loading: false }
362
+ }) })
363
+ void fetch(VOICES_ROUTE, { headers: { accept: 'application/json' } })
364
+ .then(r => r.ok ? r.json() : null)
365
+ .then(d => { if (alive && d && Array.isArray(d.voices)) setState(s => ({ ...s, voices: d.voices })) })
366
+ .catch(() => {})
367
+ void fetch(HISTORY_ROUTE, { headers: { accept: 'application/json' } })
368
+ .then(r => r.ok ? r.json() : null)
369
+ .then(d => { if (alive && d && Array.isArray(d.items)) setState(s => ({ ...s, historyItems: d.items })) })
370
+ .catch(() => {})
371
+ return () => { alive = false }
372
+ }, [])
373
+ // 自动保存:只提交"相对磁盘基线真正变化"的字段。两个设置入口同时开着时,
374
+ // 未改过的那个实例不会用旧值覆盖另一个实例刚保存的新值(这是之前不生效的主因)。
375
+ const configFields = (s) => ({
376
+ enabled: s.enabled, types: s.types, sounds: s.sounds,
377
+ idleEnabled: s.idleEnabled, idleMs: Math.max(1000, Math.min(86400000, Math.round(s.idleSeconds) * 1000)),
378
+ quietStart: s.quietStart, quietEnd: s.quietEnd,
379
+ approvalGraceMs: Math.max(0, Math.min(60000, Math.round(s.graceSeconds) * 1000)),
380
+ alwaysNotify: s.alwaysNotify, clickEnabled: s.clickEnabled,
381
+ approvalButtons: s.approvalButtons, approveEnabled: s.approveEnabled,
382
+ ttsEnabled: s.ttsEnabled, ttsVoice: s.ttsVoice, customSounds: s.customSounds,
383
+ historyEnabled: s.historyEnabled, mutedSessions: s.mutedSessions,
384
+ })
385
+ const configSignature = (s) => JSON.stringify(configFields(s))
386
+ const baselineRef = React.useRef(null)
387
+ const autoSaveRef = React.useRef({ ready: false, last: '', timer: null })
388
+ const changedFields = () => {
389
+ const now = configFields(stateRef.current)
390
+ const base = baselineRef.current || {}
391
+ const changed = {}
392
+ for (const k of Object.keys(now)) {
393
+ if (JSON.stringify(now[k]) !== JSON.stringify(base[k])) changed[k] = now[k]
394
+ }
395
+ return changed
396
+ }
397
+ const save = () => {
398
+ const changed = changedFields()
399
+ const keys = Object.keys(changed)
400
+ if (!keys.length) return // 没改动就不 POST,避免旧实例覆盖新值
401
+ dirtyRef.current = true
402
+ fetch(CONFIG_ROUTE, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(changed) })
403
+ .then(r => {
404
+ if (!r.ok) throw new Error('HTTP ' + r.status)
405
+ baselineRef.current = { ...(baselineRef.current || {}), ...changed }
406
+ autoSaveRef.current.last = configSignature(stateRef.current)
407
+ setState(s => ({ ...s, saved: true, saveError: '',
408
+ autoStatus: '已保存 ' + keys.map(k => FIELD_LABELS[k] || k).join('、') + ' @ ' + new Date().toLocaleTimeString() }))
409
+ // 🔴 审计 #5:空闲提醒的开关/阈值只在页面加载时读过一次,改了不生效(等于默认失效)。
410
+ // 保存成功后广播一个本地事件,让焦点上报那半边立刻重读 config。
411
+ try { window.dispatchEvent(new window.Event('dsh-notification:config-saved')) } catch { /* ignore */ }
412
+ })
413
+ .catch(() => setState(s => ({ ...s, saved: false, saveError: '保存失败,请重试', autoStatus: '保存失败' })))
414
+ }
415
+ React.useEffect(() => {
416
+ if (!autoSaveRef.current.ready) return
417
+ const sig = configSignature(stateRef.current)
418
+ if (sig === autoSaveRef.current.last) return
419
+ autoSaveRef.current.last = sig
420
+ if (autoSaveRef.current.timer) clearTimeout(autoSaveRef.current.timer)
421
+ autoSaveRef.current.timer = setTimeout(() => save(), 400)
422
+ })
423
+ // 自定义音效路径:本地绝对路径 + 合法扩展名;无效时立刻给可见反馈,不静默丢弃
424
+ const validAudioPath = (v) => typeof v === 'string' && v.length > 0 && v.length <= 4096
425
+ && /^[A-Za-z]:[\\\/]/.test(v) && !v.includes('://') && !v.startsWith('\\\\')
426
+ && !/[\u0000-\u001f\u007f*?"<>|]/.test(v)
427
+ && /\.(wav|mp3|m4a|wma|aac|flac)$/i.test(v)
428
+ const saveCustomSounds = (next) => {
429
+ dirtyRef.current = true
430
+ void fetch(CONFIG_ROUTE, {
431
+ method: 'POST', headers: { 'content-type': 'application/json' },
432
+ body: JSON.stringify({ customSounds: next }),
433
+ }).then(r => {
434
+ if (!r.ok) throw new Error('HTTP ' + r.status)
435
+ setState(s => ({ ...s, saveError: '' }))
436
+ }).catch(() => setState(s => ({ ...s, saveError: '自定义音效保存失败,请重试' })))
437
+ }
438
+ // 铃铛是即时开关:点一下就写盘,否则图标变了但通知照弹
439
+ const saveMuted = (list) => {
440
+ dirtyRef.current = true
441
+ void fetch(CONFIG_ROUTE, {
442
+ method: 'POST', headers: { 'content-type': 'application/json' },
443
+ body: JSON.stringify({ mutedSessions: list }),
444
+ }).then(r => {
445
+ if (!r.ok) throw new Error('HTTP ' + r.status)
446
+ }).catch(() => setState(s => ({ ...s, saveError: '免打扰设置保存失败,请重试' })))
447
+ }
448
+ // 内部约定:空数组 = 四类全开(Host 的 isTypeAllowed 就这么判)。
449
+ // UI 必须按这个语义渲染,否则默认"全开"会显示成四个都没勾,一勾就静默关掉另外三类。
450
+ const typesAll = (s) => Array.isArray(s.types) && s.types.length === 0
451
+ const toggle = (k) => setState(s => {
452
+ dirtyRef.current = true
453
+ const set = typesAll(s) ? new Set(ALL_KINDS) : new Set(s.types)
454
+ if (set.has(k)) set.delete(k); else set.add(k)
455
+ // 全选/全不选都归一为空数组(=全部提醒),避免误关三类
456
+ const next = set.size === 0 || set.size === ALL_KINDS.length ? [] : [...set]
457
+ return { ...s, types: next, saved: false }
458
+ })
459
+ const h = React.createElement
460
+ // DSH 原生文件夹图标(与侧栏同一套 primitives 导出),当前工作区用蓝色 token。
461
+ const folderIcon = (expanded, active) => {
462
+ const Icon = P && (expanded ? P.IconFolderOpenRegular : P.IconFolderCloseRegular)
463
+ return h('span', { className: 'dshnotify-folder' + (active ? ' dshnotify-folder-active' : '') },
464
+ Icon ? h(Icon, { size: 16 }) : h('span', null, '📁'))
465
+ }
466
+ // 展开工作区时懒加载完整首句(DSH 的 s.title 已在入库时被截断)
467
+ const toggleGroup = (g, expanded) => {
468
+ const cur = state.muteExpanded || {}
469
+ const next = { ...cur, [g.key]: !expanded }
470
+ writeMuteExpanded(next)
471
+ setState(prev => ({ ...prev, muteExpanded: next }))
472
+ if (!expanded) {
473
+ for (const s of g.sessions) {
474
+ if (state.fullTitles[s.id] !== undefined) continue
475
+ void loadSessionTitle(s.id).then(name => {
476
+ if (name && aliveFlag.current) {
477
+ setState(prev => ({ ...prev, fullTitles: { ...prev.fullTitles, [s.id]: name } }))
478
+ }
479
+ })
480
+ }
481
+ }
482
+ }
483
+ if (state.loading) return h('div', { className: 'dshnotify-note' }, '加载中…')
484
+ const Switch = P && P.Switch
485
+ const toggleSwitch = (checked, onChange) => Switch
486
+ ? h(Switch, { checked, label: '', onChange })
487
+ : h('input', { type: 'checkbox', className: 'dshnotify-check', checked, onChange })
488
+ return h('div', { className: 'dshnotify-wrap' },
489
+ // 总开关(一句说明,克制)
490
+ h('div', { className: 'dshnotify-row' },
491
+ h('div', { className: 'dshnotify-rowtitle' }, '启用通知提醒'),
492
+ toggleSwitch(state.enabled, () => setState(s => ({ ...s, enabled: !s.enabled, saved: false })))),
493
+ !state.enabled && h('div', { className: 'dshnotify-note', style: { color: 'var(--dsw-alias-state-warn-primary,#b26a00)' } }, '通知已关闭'),
494
+ // 自检入口:新用户装完不用等真实任务,点一下就能确认通知链路是否通
495
+ state.enabled && h('div', { className: 'dshnotify-row' },
496
+ h('div', null,
497
+ h('div', { className: 'dshnotify-rowtitle' }, '发送测试通知'),
498
+ h('div', { className: 'dshnotify-rowdesc' }, '立刻弹一条示例提醒,只用于确认通知链路')),
499
+ h('button', {
500
+ type: 'button', className: 'dshnotify-save',
501
+ onClick: () => {
502
+ void fetch(TEST_ROUTE, { method: 'POST' })
503
+ .then(r => {
504
+ if (!r.ok) throw new Error('HTTP ' + r.status)
505
+ setState(s => ({ ...s, saveError: '', autoStatus: '已发送测试通知 @ ' + new Date().toLocaleTimeString() }))
506
+ })
507
+ .catch(() => setState(s => ({ ...s, saveError: '测试通知发送失败' })))
508
+ },
509
+ }, '发送')),
510
+ // 类型 + 提示音合并成紧凑表格:一行 = 类型名 / 开关 / 提示音下拉(无重复说明文)
511
+ state.enabled && h('div', { className: 'dshnotify-sec' }, '提醒类型与提示音'),
512
+ state.enabled && h('div', { className: 'dshnotify-note' }, '⚠ 四类开关的语义是「关掉某一类才少一类」——把四个都关掉仍然是四类都提醒。要整体关闭请用上面的总开关'),
513
+ ...(state.enabled ? ALL_KINDS.map(k => h('div', { className: 'dshnotify-row', key: k },
514
+ h('div', { className: 'dshnotify-rowtitle' }, KIND_LABELS[k] || k),
515
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 12 } },
516
+ h('select', { className: 'dshnotify-select', value: state.sounds[k] || 'Notification.IM', onChange: (e) => { const sound = e.target.value; setState(s => ({ ...s, sounds: { ...s.sounds, [k]: sound }, saved: false })); previewSound(sound) } },
517
+ ...state.choices.map(c => h('option', { key: c, value: c }, SOUND_LABELS[c] || c))),
518
+ toggleSwitch(typesAll(state) || state.types.includes(k), () => toggle(k))))) : []),
519
+ // 静音时段 / 审批等待 / 在场也提醒:原来是环境变量,普通用户根本用不了,现在直接可配。
520
+ h('div', { className: 'dshnotify-sec' }, '提醒时机'),
521
+ h('div', { className: 'dshnotify-row' },
522
+ h('div', null,
523
+ h('div', { className: 'dshnotify-rowtitle' }, '静音时段'),
524
+ h('div', { className: 'dshnotify-rowdesc' }, '留空表示不静音;这段时间内不通知,结束后不补发')),
525
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 8 } },
526
+ h('input', { type: 'time', className: 'dshnotify-select', value: state.quietStart, onChange: (e) => setState(s => ({ ...s, quietStart: e.target.value, saved: false })) }),
527
+ h('span', { className: 'dshnotify-note' }, '至'),
528
+ h('input', { type: 'time', className: 'dshnotify-select', value: state.quietEnd, onChange: (e) => setState(s => ({ ...s, quietEnd: e.target.value, saved: false })) }))),
529
+ h('div', { className: 'dshnotify-row' },
530
+ h('div', null,
531
+ h('div', { className: 'dshnotify-rowtitle' }, '审批等待(秒)'),
532
+ h('div', { className: 'dshnotify-rowdesc' }, '请求审批后等几秒;期间你已处理就不弹通知')),
533
+ h('input', {
534
+ type: 'number', min: 0, max: 60, className: 'dshnotify-select', value: state.graceSeconds,
535
+ onChange: (e) => setState(s => ({ ...s, graceSeconds: Math.max(0, Math.min(60, Number(e.target.value) || 0)), saved: false })),
536
+ })),
537
+ h('div', { className: 'dshnotify-row' },
538
+ h('div', null,
539
+ h('div', { className: 'dshnotify-rowtitle' }, '在场也提醒'),
540
+ h('div', { className: 'dshnotify-rowdesc' }, '你正看着会话时也弹系统通知;静音时段仍优先')),
541
+ toggleSwitch(state.alwaysNotify, () => setState(s => ({ ...s, alwaysNotify: !s.alwaysNotify, saved: false })))),
542
+ // 空闲提醒:独立开关 + 等待秒数(每轮结束后最多提醒一次,用户活动只推迟计时)
543
+ h('div', { className: 'dshnotify-sec' }, '空闲提醒'),
544
+ h('div', { className: 'dshnotify-row' },
545
+ h('div', null,
546
+ h('div', { className: 'dshnotify-rowtitle' }, '启用空闲提醒'),
547
+ h('div', { className: 'dshnotify-rowdesc' }, '一轮结束后一直没回来时提醒一次')),
548
+ toggleSwitch(state.idleEnabled, () => setState(s => ({ ...s, idleEnabled: !s.idleEnabled, saved: false })))),
549
+ ...(state.idleEnabled ? [h('div', { className: 'dshnotify-row' },
550
+ h('div', { className: 'dshnotify-rowtitle' }, '等待时间(秒)'),
551
+ h('input', {
552
+ type: 'number', min: 1, max: 86400, className: 'dshnotify-select',
553
+ value: state.idleSeconds,
554
+ onChange: (e) => setState(s => ({ ...s, idleSeconds: Math.max(1, Math.min(86400, Number(e.target.value) || 1)), saved: false })),
555
+ }))] : []),
556
+ // 🔔 按会话免打扰:只做在设置页,不给 toast 加任何按钮
557
+ // (用户明确反对全局药丸控件和 toast 按钮太多)。
558
+ h('div', { className: 'dshnotify-sec' }, '🔔 会话免打扰'),
559
+ h('div', { className: 'dshnotify-note' }, '免打扰的会话不弹系统通知、不写历史、不播音效;应用内审批卡片不受影响'),
560
+ h('div', { className: 'dshnotify-risk' }, '点「✎ 命名」可编辑当前会话名,点保存才会写回 DSH(最长 80 字节,约 26 个汉字);这会覆盖原名字、DSH 不再自动改名,且无法撤销。不点不会改任何数据。'),
561
+ ...(() => {
562
+ const groups = listMuteSessions()
563
+ if (groups.length === 0) return [h('div', { className: 'dshnotify-row' },
564
+ h('div', { className: 'dshnotify-note' }, '暂未获取到会话'))]
565
+ const rows = []
566
+ for (const g of groups) {
567
+ // 工作区标题只显示目录名(用户选择),不显示完整路径;默认折叠,点击展开。
568
+ const expanded = !!(state.muteExpanded && state.muteExpanded[g.key])
569
+ rows.push(h('div', {
570
+ className: 'dshnotify-wsgroup' + (expanded ? ' dshnotify-wsgroup-open' : ''), key: 'ws-' + g.key,
571
+ role: 'button', tabIndex: 0,
572
+ onClick: () => toggleGroup(g, expanded),
573
+ },
574
+ h('span', { className: 'dshnotify-chevron' }, expanded ? '▾' : '▸'),
575
+ folderIcon(expanded, !!g.containsCurrent),
576
+ h('span', { className: 'dshnotify-wsgroup-name' }, g.workspace),
577
+ // 数量按 Apple/Huawei 惯例放行尾、灰色小字、无括号;静态总数显示精确值
578
+ h('span', {
579
+ className: 'dshnotify-wsgroup-count',
580
+ 'aria-label': '共 ' + g.sessions.length + ' 个对话',
581
+ }, String(g.sessions.length))))
582
+ if (!expanded) continue // 折叠时不渲染里面任何会话
583
+ for (const s of g.sessions) {
584
+ const isLast = s === g.sessions[g.sessions.length - 1]
585
+ const muted = Array.isArray(state.mutedSessions) && state.mutedSessions.includes(s.id)
586
+ const draft = state.renameDraft && state.renameDraft.sessionId === s.id ? state.renameDraft : null
587
+ const currentName = String(state.fullTitles[s.id] || s.title)
588
+ const notice = state.renameNotice && state.renameNotice.sessionId === s.id ? state.renameNotice.text : ''
589
+ const titleInfo = draft ? previewTitleBytes(draft.value) : null
590
+ // 预填当前会话名(真正的名字),用户自己编辑;不再从首条消息生成建议
591
+ const openDraft = () => setState(prev => ({
592
+ ...prev, renameDraft: { sessionId: s.id, value: currentName }, renameNotice: null,
593
+ }))
594
+ const saveDraft = () => {
595
+ const next = draft.value.trim()
596
+ if (!next) {
597
+ showRenameNotice(s.id, '名字不能为空,未修改 DSH')
598
+ return
599
+ }
600
+ // 用规范化后的值比较,避免输入一个会被截断成当前名的长文本还写一条新事件
601
+ if (previewTitleBytes(next).text === previewTitleBytes(currentName).text) {
602
+ setState(prev => ({ ...prev, renameDraft: null }))
603
+ showRenameNotice(s.id, '和当前名字相同,未写入 DSH')
604
+ return
605
+ }
606
+ void renameSessionTitle(s.id, next).then(res => {
607
+ if (!aliveFlag.current) return
608
+ if (res && res.title) {
609
+ setState(prev => ({ ...prev, fullTitles: { ...prev.fullTitles, [s.id]: res.title }, renameDraft: null }))
610
+ // DSH 可能静默截断;如实告知实际保存成什么
611
+ showRenameNotice(s.id, res.title === next
612
+ ? '已保存为 DSH 会话名'
613
+ : 'DSH 已按 80 字节截断,实际保存为:' + res.title)
614
+ } else {
615
+ setState(prev => ({ ...prev, renameDraft: null }))
616
+ showRenameNotice(s.id, '保存失败,未修改 DSH 会话名')
617
+ }
618
+ })
619
+ }
620
+ rows.push(h('div', {
621
+ className: 'dshnotify-row dshnotify-mute-row' + (isLast ? ' dshnotify-mute-row-last' : ''),
622
+ key: 'mute-' + s.id,
623
+ },
624
+ h('div', { style: { display: 'flex', flexDirection: 'column', gap: 6, flex: 1, minWidth: 0 } },
625
+ // 编辑态在同一行内替换名字:输入框 + 紧凑「保存/取消」,静音按钮保持在右侧原位
626
+ h('div', { className: 'dshnotify-mute-line' },
627
+ draft
628
+ ? h('div', { className: 'dshnotify-name-editor' },
629
+ h('input', {
630
+ type: 'text', value: draft.value,
631
+ onChange: (e) => setState(prev => ({ ...prev, renameDraft: { ...prev.renameDraft, value: e.target.value } })),
632
+ }),
633
+ h('button', { type: 'button', className: 'dshnotify-mini dshnotify-mini-save', onClick: saveDraft }, '保存'),
634
+ h('button', { type: 'button', className: 'dshnotify-mini', onClick: () => setState(prev => ({ ...prev, renameDraft: null })) }, '取消'),
635
+ titleInfo && h('span', {
636
+ className: 'dshnotify-name-count',
637
+ style: titleInfo.over ? { color: 'var(--dsw-alias-state-warn-primary,#b26a00)' } : undefined,
638
+ }, '已用 ' + titleInfo.bytes + '/80' + (titleInfo.over ? '(将截断)' : '')))
639
+ : h('span', { className: 'dshnotify-mute-title' }, currentName),
640
+ !draft && h('button', { type: 'button', className: 'dshnotify-name-btn', onClick: openDraft }, '✎ 命名'),
641
+ notice && h('span', { className: 'dshnotify-name-bubble', role: 'status' }, notice))),
642
+ h('button', {
643
+ type: 'button', className: 'dshnotify-select',
644
+ 'aria-pressed': muted ? 'true' : 'false',
645
+ onClick: () => setState(prev => {
646
+ const next = new Set(Array.isArray(prev.mutedSessions) ? prev.mutedSessions : [])
647
+ if (next.has(s.id)) next.delete(s.id); else next.add(s.id)
648
+ const list = [...next].slice(0, 200)
649
+ saveMuted(list)
650
+ return { ...prev, mutedSessions: list }
651
+ }),
652
+ }, muted ? '🔕 免打扰中' : '🔔 提醒中')))
653
+ }
654
+ }
655
+ return rows
656
+ })(),
657
+ // 实验功能:默认关。措辞克制,不承诺未真机验证的行为。
658
+ h('div', { className: 'dshnotify-sec' }, '其他'),
659
+ h('div', { className: 'dshnotify-row' },
660
+ h('div', null,
661
+ h('div', { className: 'dshnotify-rowtitle' }, '点通知回到 DSH'),
662
+ h('div', { className: 'dshnotify-rowdesc' }, '点击通知正文时把 DSH 窗口放到前面')),
663
+ toggleSwitch(state.clickEnabled, () => setState(s => ({ ...s, clickEnabled: !s.clickEnabled, saved: false })))),
664
+ h('div', { className: 'dshnotify-row' },
665
+ h('div', null,
666
+ h('div', { className: 'dshnotify-rowtitle' }, '审批通知显示操作按钮'),
667
+ h('div', { className: 'dshnotify-rowdesc' }, '开启后显示「拒绝 / 去 DSH 确认」;默认不含批准按钮')),
668
+ toggleSwitch(state.approvalButtons, () => setState(s => ({ ...s, approvalButtons: !s.approvalButtons, saved: false })))),
669
+ // 🔴 高级选项:批准默认关闭,单独开关;小字风险须知常驻这一栏。
670
+ h('div', { className: 'dshnotify-row' },
671
+ h('div', null,
672
+ h('div', { className: 'dshnotify-rowtitle' }, '允许通知内「批准一次」(高级)'),
673
+ h('div', { className: 'dshnotify-rowdesc' }, '默认关闭;开启后,能看到实际命令的通知才会出现批准按钮'),
674
+ h('div', { className: 'dshnotify-risk' }, '风险须知:批准令牌保存在系统通知记录中,同一账号下的其他程序可能读取并伪造点击;仅在你信任本机环境时开启。')),
675
+ toggleSwitch(state.approveEnabled, () => setState(s => ({ ...s, approveEnabled: !s.approveEnabled, saved: false })))),
676
+ // 缺口 6:语音播报 + 本地自定义音效(都不改系统通知的声音标识,失败静默降级)
677
+ h('div', { className: 'dshnotify-sec' }, '语音与自定义音'),
678
+ h('div', { className: 'dshnotify-note' }, '注意:上面下拉里的「循环2」等是内置系统音效;要用自己的音频文件,请在下面对应类型的「本地音频文件」框里填完整路径'),
679
+ h('div', { className: 'dshnotify-row' },
680
+ h('div', null,
681
+ h('div', { className: 'dshnotify-rowtitle' }, '语音播报'),
682
+ h('div', { className: 'dshnotify-rowdesc' }, '通知时用中文读出摘要;开启后系统提示音不重复播放')),
683
+ toggleSwitch(state.ttsEnabled, () => setState(s => ({ ...s, ttsEnabled: !s.ttsEnabled, saved: false })))),
684
+ h('div', { className: 'dshnotify-row' },
685
+ h('div', null,
686
+ h('div', { className: 'dshnotify-rowtitle' }, '朗读语音'),
687
+ h('div', { className: 'dshnotify-rowdesc' }, '留空使用系统默认中文语音')),
688
+ h('select', { className: 'dshnotify-select', value: state.ttsVoice, onChange: (e) => setState(s => ({ ...s, ttsVoice: e.target.value, saved: false })) },
689
+ h('option', { value: '' }, '系统默认'),
690
+ ...state.voices.map(v => h('option', { key: v, value: v }, v)))),
691
+ ...(state.enabled ? ALL_KINDS.map(k => h('div', { className: 'dshnotify-row', key: 'custom-' + k },
692
+ h('div', null,
693
+ h('div', { className: 'dshnotify-rowtitle' }, KIND_LABELS[k] + '·本地音频文件'),
694
+ h('div', { className: 'dshnotify-rowdesc' }, '填自己的 .wav/.mp3 完整路径(可含中文),例如 C:\\音效\\提示.wav;留空则用上面下拉里的内置音效,失焦即保存')),
695
+ h('input', {
696
+ type: 'text', className: 'dshnotify-select', placeholder: '留空用系统音',
697
+ value: state.customSounds[k] || '',
698
+ onChange: (e) => setState(s => ({ ...s, customSounds: { ...s.customSounds, [k]: e.target.value }, saved: false })),
699
+ onBlur: (e) => {
700
+ const v = e.target.value
701
+ if (!v) {
702
+ const next = { ...state.customSounds }; delete next[k]
703
+ setState(s => ({ ...s, customSounds: next }))
704
+ saveCustomSounds(next)
705
+ return
706
+ }
707
+ if (!validAudioPath(v)) {
708
+ setState(s => ({ ...s, saveError: '路径无效:需为本地绝对路径且以 .wav/.mp3/.m4a/.wma/.aac/.flac 结尾' }))
709
+ return
710
+ }
711
+ const next = { ...state.customSounds, [k]: v }
712
+ saveCustomSounds(next)
713
+ },
714
+ }))) : []),
715
+ // 缺口 4:通知历史(只存固定模板结果,不存原文;仅本机可见)
716
+ h('div', { className: 'dshnotify-sec' }, '通知历史'),
717
+ h('div', { className: 'dshnotify-row' },
718
+ h('div', null,
719
+ h('div', { className: 'dshnotify-rowtitle' }, '记录通知'),
720
+ h('div', { className: 'dshnotify-rowdesc' }, '只记录提醒摘要,不记录会话正文;最多 200 条、保留 7 天')),
721
+ toggleSwitch(state.historyEnabled, () => setState(s => ({ ...s, historyEnabled: !s.historyEnabled, saved: false })))),
722
+ h('div', { className: 'dshnotify-history' },
723
+ ...state.historyItems.slice(0, 20).map((it, i) => {
724
+ // 🔴 体验修复:标题本身已经带「任务完成 · …」「需要批准 · Bash」,再拼一次类型
725
+ // 会出现「任务完成 · 任务完成 · DSH」这种看着像拼接 bug 的行。
726
+ const label = KIND_LABELS[it.kind] || it.kind
727
+ const rawTitle = String(it.title || '').slice(0, 40)
728
+ const text = rawTitle.startsWith(label) ? rawTitle : label + ' · ' + rawTitle
729
+ return h('div', { className: 'dshnotify-hitem', key: (it.ts || 0) + '-' + i },
730
+ h('span', null, new Date(it.ts || Date.now()).toLocaleString() + ' · ' + text),
731
+ it.sessionId ? h('button', {
732
+ type: 'button',
733
+ onClick: () => { void openSessionSafe(it.sessionId) },
734
+ }, '打开') : null)
735
+ })),
736
+ h('div', { className: 'dshnotify-row' },
737
+ h('div', { className: 'dshnotify-note', style: { position: 'sticky', bottom: 0, background: 'var(--dsw-alias-bg-layout, #fff)', paddingTop: 4, paddingBottom: 4 } }, state.saveError || state.autoStatus || '设置改动会自动保存'),
738
+ h('div', { style: { display: 'flex', gap: 8 } },
739
+ h('button', {
740
+ type: 'button', className: 'dshnotify-save',
741
+ onClick: () => {
742
+ // 🔴 体验修复:清空历史原来一点就没、没有二次确认也没有撤销。
743
+ if (!state.clearPending) {
744
+ setState(s => ({ ...s, clearPending: true }))
745
+ setTimeout(() => { try { setState(s => ({ ...s, clearPending: false })) } catch { /* ignore */ } }, 4000)
746
+ return
747
+ }
748
+ setState(s => ({ ...s, clearPending: false }))
749
+ void fetch(HISTORY_ROUTE, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ op: 'clear' }) })
750
+ .then(r => {
751
+ if (!r.ok) throw new Error('HTTP ' + r.status)
752
+ setState(s => ({ ...s, historyItems: [], saveError: '' }))
753
+ })
754
+ .catch(() => setState(s => ({ ...s, saveError: '清空失败,请重试' })))
755
+ },
756
+ }, state.clearPending ? '再点一次确认清空' : '清空历史')))
757
+ )
758
+ }
759
+
760
+ // 设置页兜底:DSH 真实 React 环境里若某个子组件抛错,整个面板会白屏且无提示。
761
+ // 包一层 try/catch,把错误直接显示在面板上并写诊断,便于定位而不靠用户开 DevTools。
762
+ const SafeSettingsView = () => {
763
+ try {
764
+ return SettingsView()
765
+ } catch (err) {
766
+ const msg = '设置页渲染失败:' + String((err && err.message) || err)
767
+ try { console.error('[dsh-notification] settings render failed', err) } catch { /* ignore */ }
768
+ try { cdiag('settings render failed: ' + msg.slice(0, 300)) } catch { /* ignore */ }
769
+ try {
770
+ void fetch(RENDER_ERROR_ROUTE, {
771
+ method: 'POST', headers: { 'content-type': 'application/json' },
772
+ body: JSON.stringify({ msg: String(err && err.stack || msg).slice(0, 2000) }),
773
+ }).catch(() => {})
774
+ } catch { /* ignore */ }
775
+ return React.createElement('div', { className: 'dshnotify-wrap' },
776
+ React.createElement('div', { className: 'dshnotify-note', style: { color: '#b26a00' } }, msg))
777
+ }
778
+ }
779
+
780
+ return {
781
+ // 不含 uiSession / uiWorkspace:两者都是硬门卫,缺服务会让整个 client 停摆。
782
+ // uiWorkspace 改为惰性 ctx.get + try/catch,只影响"跳具体会话"。
783
+ inject: ['sessions', 'slots'],
784
+ apply(ctx) {
785
+ viewCtx = ctx
786
+ cdiag('apply called; effect=' + (ctx && typeof ctx.effect))
787
+ if (!ctx || typeof ctx.effect !== 'function') return
788
+
789
+ ctx.effect(() => {
790
+ cdiag('focus effect started')
791
+ let idleMs = IDLE_DEFAULT_MS
792
+ try {
793
+ const stored = Number(window.localStorage.getItem(IDLE_STORAGE_KEY))
794
+ if (Number.isFinite(stored) && stored >= 0) idleMs = stored
795
+ } catch { /* ignore */ }
796
+ let lastActivityAt = Date.now()
797
+ let idleTimer = null
798
+ let disposed = false
799
+ let lastReport = null
800
+ // 空闲提醒(默认由 Host 配置决定;Host 未开时这里完全不POST)
801
+ let idleNotifyMs = 60 * 1000
802
+ let idleNotifyEnabled = false
803
+ let idleNotifyTimer = null
804
+ let lastActivePost = 0
805
+ function currentSessionId() {
806
+ // 当前会话 = byId 里 retainedBy.mainView > 0 的项(0.2.2 起 `current` 字段已废弃,
807
+ // 见 dsh-web-mobile sessions_compat.currentSessionIdOf)。取不到返回 undefined → fail-open。
808
+ try {
809
+ const snap = ctx.sessions?.list?.getSnapshot?.()
810
+ const byId = snap?.byId
811
+ if (!byId || typeof byId !== 'object') return undefined
812
+ for (const key in byId) {
813
+ const s = byId[key]
814
+ if (!s || typeof s !== 'object') continue
815
+ const mv = s.retainedBy?.mainView
816
+ if (typeof mv === 'number' && mv > 0 && typeof s.id === 'string') return s.id
817
+ }
818
+ return undefined
819
+ } catch { return undefined }
820
+ }
821
+ function currentSessionTitle() {
822
+ try {
823
+ const byId = ctx.sessions?.list?.getSnapshot?.()?.byId
824
+ if (!byId || typeof byId !== 'object') return undefined
825
+ for (const key in byId) {
826
+ const s = byId[key]
827
+ // DSH 0.2.2 的 session 行没有 header.title;标题走 s.title / s.displayTitle
828
+ if (s?.retainedBy?.mainView > 0) {
829
+ if (typeof s.title === 'string' && s.title.trim()) return s.title
830
+ if (typeof s.displayTitle === 'string' && s.displayTitle) return s.displayTitle
831
+ }
832
+ }
833
+ } catch { /* ignore */ }
834
+ return undefined
835
+ }
836
+ function postIdle(payload) {
837
+ if (disposed) return
838
+ try {
839
+ void fetch(IDLE_ROUTE, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(payload) }).catch(() => {})
840
+ } catch { /* ignore */ }
841
+ }
842
+ function notifyActive() {
843
+ const now = Date.now()
844
+ if (now - lastActivePost < 1000) return // 节流:活动事件很密集
845
+ lastActivePost = now
846
+ postIdle({ active: true, at: now })
847
+ }
848
+ function rearmIdleNotify() {
849
+ if (idleNotifyTimer) clearTimeout(idleNotifyTimer)
850
+ if (!idleNotifyEnabled || idleNotifyMs <= 0) return
851
+ const remain = idleNotifyMs - (Date.now() - lastActivityAt)
852
+ idleNotifyTimer = setTimeout(() => {
853
+ if (disposed || !idleNotifyEnabled) return
854
+ postIdle({ active: false, at: Date.now(), sessionId: currentSessionId(), sessionTitle: currentSessionTitle() })
855
+ }, remain > 0 ? remain : 0)
856
+ }
857
+ function report() {
858
+ if (disposed) return
859
+ const hidden = document.hidden || document.visibilityState === 'hidden'
860
+ const focused = document.hasFocus ? document.hasFocus() : true
861
+ const idleExpired = idleMs > 0 && (Date.now() - lastActivityAt >= idleMs)
862
+ const away = hidden || !focused || idleExpired
863
+ const payload = { away, sessionId: currentSessionId(), idleExpired, hidden, focused, at: Date.now() }
864
+ const sig = JSON.stringify([away, payload.sessionId, idleExpired])
865
+ if (sig === lastReport) return
866
+ lastReport = sig
867
+ cdiag('report away=' + away + ' sid=' + payload.sessionId)
868
+ try {
869
+ void fetch(FOCUS_ROUTE, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(payload) }).catch(() => {})
870
+ } catch { /* ignore */ }
871
+ }
872
+ function onActivity() { lastActivityAt = Date.now(); report(); notifyActive(); rearmIdleNotify() }
873
+ function rearmIdleTimer() {
874
+ if (idleTimer) clearTimeout(idleTimer)
875
+ if (idleMs <= 0) return
876
+ const remain = idleMs - (Date.now() - lastActivityAt)
877
+ idleTimer = setTimeout(report, remain > 0 ? remain : 0)
878
+ }
879
+ for (const ev of ACTIVITY_EVENTS) document.addEventListener(ev, onActivity, { passive: true })
880
+ window.addEventListener('focus', onActivity)
881
+ window.addEventListener('blur', report)
882
+ document.addEventListener('visibilitychange', report)
883
+ // 🔴 关键:启动时 sessions 可能晚就绪,currentSessionId() 先返回 undefined;
884
+ // 若此时 sig 去重锁住,sessionId 之后变真实值也不会重报 → 焦点门控永远 fail-open(打开应用也弹)。
885
+ // 订阅 sessions.list + 延迟重试,确保 sessionId 一就绪就强制重报。
886
+ let unsubSessions = null
887
+ try {
888
+ unsubSessions = ctx.sessions?.list?.subscribe?.(() => { lastReport = null; report() })
889
+ } catch { /* ignore */ }
890
+ const retryTimers = []
891
+ for (const delay of [500, 1500, 3000]) {
892
+ retryTimers.push(setTimeout(() => { lastReport = null; report() }, delay))
893
+ }
894
+ // 空闲阈值/开关由 Host 下发,便于用 env 改小做快速验证;拿不到就保持默认关。
895
+ const refreshIdleConfig = () => {
896
+ if (disposed) return
897
+ void fetch(CONFIG_ROUTE, { headers: { accept: 'application/json' } })
898
+ .then(r => r.ok ? r.json() : null)
899
+ .then(d => {
900
+ if (disposed || !d) return
901
+ if (Number.isFinite(d.idleMs) && d.idleMs >= 1000) idleNotifyMs = d.idleMs
902
+ idleNotifyEnabled = d.idleEnabled === true
903
+ rearmIdleNotify()
904
+ })
905
+ .catch(() => {})
906
+ }
907
+ refreshIdleConfig()
908
+ // 🔴 审计 #5:设置页改完在同一个页面里立刻生效——保存成功会广播 config-saved 事件;
909
+ // 另外每 20 秒兜底重读一次(另一个窗口/远端改了设置也能跟上)。
910
+ const idleCfgTimer = setInterval(refreshIdleConfig, 20000)
911
+ const onCfgSaved = () => refreshIdleConfig()
912
+ window.addEventListener('dsh-notification:config-saved', onCfgSaved)
913
+ rearmIdleTimer()
914
+ report()
915
+ // 启动信标:同时重置 Host 空闲起点,也用于验证 client 半身是否真的加载
916
+ postIdle({ active: true, at: Date.now() })
917
+ return () => {
918
+ disposed = true
919
+ if (idleTimer) clearTimeout(idleTimer)
920
+ if (idleNotifyTimer) clearTimeout(idleNotifyTimer)
921
+ clearInterval(idleCfgTimer)
922
+ try { window.removeEventListener('dsh-notification:config-saved', onCfgSaved) } catch { /* ignore */ }
923
+ for (const t of retryTimers) clearTimeout(t)
924
+ try { if (typeof unsubSessions === 'function') unsubSessions() } catch { /* ignore */ }
925
+ for (const ev of ACTIVITY_EVENTS) document.removeEventListener(ev, onActivity)
926
+ window.removeEventListener('focus', onActivity)
927
+ window.removeEventListener('blur', report)
928
+ document.removeEventListener('visibilitychange', report)
929
+ }
930
+ }, 'dsh-notification: focus reporter')
931
+
932
+ // 缺口 3:点通知正文时 Host 记下目标会话,client 轮询后打开具体会话。
933
+ // openSession 是同步导航;失败只记诊断,绝不影响焦点上报等核心功能。
934
+ ctx.effect(() => {
935
+ let navDisposed = false
936
+ const poll = () => {
937
+ if (navDisposed) return
938
+ void fetch(NAVIGATE_ROUTE, { headers: { accept: 'application/json' } })
939
+ .then(r => r.ok ? r.json() : null)
940
+ .then(d => {
941
+ if (navDisposed || !d || typeof d.sessionId !== 'string' || !d.sessionId) return
942
+ if (!openSessionSafe(d.sessionId)) cdiag('uiWorkspace.openSession unavailable')
943
+ })
944
+ .catch(() => {})
945
+ }
946
+ const timer = setInterval(poll, 2000)
947
+ return () => { navDisposed = true; clearInterval(timer) }
948
+ }, 'dsh-notification: session navigation')
949
+
950
+ // 注册设置页(全局设置的 settings.section)+ 插件卡片配置按钮(plugins.row.config)。
951
+ // 竞品验证写法,inject 不含 uiSession。保存 disposer 并在 cleanup 释放(不再丢弃)。
952
+ if (React && ctx.slots) ctx.effect(() => {
953
+ cdiag('registering settings slots')
954
+ const disposeSection = ctx.slots.inject('settings.section', () => {
955
+ cdiag('settings.section callback fired')
956
+ return ctx.slots.register({
957
+ name: 'settings.section',
958
+ id: 'dsh-notification',
959
+ order: 100,
960
+ label: () => '通知提醒',
961
+ }, SafeSettingsView)
962
+ })
963
+ // 插件详情页内嵌配置表单(key = 完整包名):点进插件卡片后,描述与行列表之间显示。
964
+ const disposeBundle = ctx.slots.inject('plugins.bundle.config', () => {
965
+ cdiag('plugins.bundle.config callback fired')
966
+ const dispose = ctx.slots.register({
967
+ name: 'plugins.bundle.config',
968
+ key: 'dsh-notification-focus',
969
+ }, SafeSettingsView)
970
+ // 诊断打在 register 之后 + 打印真实账本,验证真的进了账本
971
+ try {
972
+ cdiag('bundle.config ledger=' + JSON.stringify(ctx.slots.entries('plugins.bundle.config').map(e => e.options.key)))
973
+ } catch (e) { cdiag('bundle.config ledger read failed') }
974
+ return dispose
975
+ })
976
+ cdiag('settings slots registered')
977
+ return () => {
978
+ try { if (typeof disposeBundle === 'function') disposeBundle() } catch { /* ignore */ }
979
+ try { if (typeof disposeSection === 'function') disposeSection() } catch { /* ignore */ }
980
+ }
981
+ }, 'dsh-notification: settings section')
982
+ },
983
+ }
984
+ },
985
+ })
986
+
987
+
988
+