@soffits/dsh-notify-inbox 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js ADDED
@@ -0,0 +1,526 @@
1
+ /*
2
+ * Browser half of dsh-notify-inbox: the Inbox entry in the sidebar (with the
3
+ * unread count), its page, turning Web Push on for this browser, and the
4
+ * buttons on each notification.
5
+ *
6
+ * Plain JavaScript in DSH's Client module format (no build step); React comes
7
+ * from the page's module table. Everything the page shows comes from the
8
+ * plugin's /api/notify-inbox routes, which decide per request who is asking.
9
+ * A link with ?notify-inbox=<id> opens the page on that notification.
10
+ */
11
+ window.__ModuleLoader__.load({
12
+ id: '@soffits/dsh-notify-inbox',
13
+ factory(require) {
14
+ const React = require('react')
15
+ const h = React.createElement
16
+ const { useState, useEffect, useCallback, useSyncExternalStore } = React
17
+
18
+ const NS = 'dsh-notify-inbox'
19
+ const PANEL = 'dsh-notify-inbox'
20
+ const LINK_PARAM = 'notify-inbox'
21
+ const STYLE_ID = 'dsh-notify-inbox-style'
22
+ const PENDING_MS = 2 * 60 * 1000
23
+ const api = path => new URL(`api/notify-inbox/${path}`, document.baseURI).href
24
+
25
+ const en = {
26
+ panel: 'Inbox',
27
+ title: 'Inbox',
28
+ 'filter.unread': 'Unread',
29
+ 'filter.all': 'All',
30
+ 'markAll': 'Mark all read',
31
+ 'empty.unread': 'Nothing unread.',
32
+ 'empty.all': 'No notifications yet.',
33
+ 'loadMore': 'Show older',
34
+ 'urgent': 'Urgent',
35
+ 'test': 'Test',
36
+ 'alsoSent': 'Also sent to',
37
+ 'notSent': 'Not sent anywhere else',
38
+ 'files': 'Attachments',
39
+ 'notStored': 'not kept: {reason}',
40
+ 'press.pending': 'Sent, waiting…',
41
+ 'press.unhandled': 'Nobody picked this up yet',
42
+ 'press.done': 'Marked done',
43
+ 'press.snoozed': 'Will remind you {time}',
44
+ 'push.title': 'Notifications on this device',
45
+ 'push.on': 'On',
46
+ 'push.off': 'Off',
47
+ 'push.enable': 'Turn on',
48
+ 'push.disable': 'Turn off',
49
+ 'push.test': 'Send a test',
50
+ 'push.testSent': 'Test sent to {n} device(s).',
51
+ 'push.denied': 'Notifications are blocked for this site in the browser settings.',
52
+ 'push.unsupported': 'This browser can’t receive push notifications here.',
53
+ 'push.ios': 'On iPhone or iPad, add this site to the Home Screen and open it from there to turn notifications on.',
54
+ 'error': 'Couldn’t load: {message}',
55
+ 'time.locale': 'en-US',
56
+ }
57
+ const zh = {
58
+ panel: '收件箱',
59
+ title: '收件箱',
60
+ 'filter.unread': '未读',
61
+ 'filter.all': '全部',
62
+ 'markAll': '全部已读',
63
+ 'empty.unread': '没有未读通知。',
64
+ 'empty.all': '还没有通知。',
65
+ 'loadMore': '更早的',
66
+ 'urgent': '紧急',
67
+ 'test': '测试',
68
+ 'alsoSent': '同时发到',
69
+ 'notSent': '没有发到别处',
70
+ 'files': '附件',
71
+ 'notStored': '未保存:{reason}',
72
+ 'press.pending': '已发出,等待处理…',
73
+ 'press.unhandled': '暂时没有人处理',
74
+ 'press.done': '已标为完成',
75
+ 'press.snoozed': '会在{time}再提醒',
76
+ 'push.title': '本设备的通知',
77
+ 'push.on': '已开启',
78
+ 'push.off': '未开启',
79
+ 'push.enable': '开启',
80
+ 'push.disable': '关闭',
81
+ 'push.test': '发一条测试',
82
+ 'push.testSent': '测试已发到 {n} 台设备。',
83
+ 'push.denied': '浏览器设置里禁止了这个网站的通知。',
84
+ 'push.unsupported': '这个浏览器在这里收不到推送通知。',
85
+ 'push.ios': 'iPhone 或 iPad 上,先把这个网站添加到主屏幕,再从主屏幕打开,才能开启通知。',
86
+ 'error': '加载失败:{message}',
87
+ 'time.locale': 'zh-CN',
88
+ }
89
+
90
+ const CSS = `
91
+ .nib-page{width:100%;min-width:0;height:100%;min-height:0;display:flex;flex-direction:column;overflow:hidden;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-base);font-size:14px;line-height:1.6}
92
+ .nib-scroll{flex:1;min-height:0;overflow:auto;scrollbar-gutter:stable}
93
+ .nib-content{max-width:820px;margin:0 auto;padding:0 clamp(16px,4vw,48px) 48px}
94
+ .nib-head{display:flex;align-items:center;flex-wrap:wrap;gap:8px 12px;padding-top:28px;margin-bottom:16px}
95
+ [data-platform=darwin] .nib-head{padding-top:calc(28px + var(--dsh-frame-top-clearance,0px))}
96
+ .nib-head h1{margin:0;font-size:20px;font-weight:500;line-height:28px;flex:1;min-width:0}
97
+ .nib-count{color:var(--dsw-alias-label-tertiary);font-size:13px;margin-left:8px;font-weight:400}
98
+ .nib-tabs{display:inline-flex;gap:2px;padding:2px;border-radius:10px;background:var(--dsw-alias-bg-layer-1,var(--dsw-alias-interactive-bg-hover))}
99
+ .nib-tab{border:none;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:13px;padding:2px 12px;border-radius:8px;cursor:pointer}
100
+ .nib-tab[aria-pressed=true]{background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);box-shadow:0 0 0 .5px var(--dsw-alias-border-l3)}
101
+ .nib-btn{box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;gap:4px;height:28px;padding:0 10px;border:none;border-radius:var(--dsw-radius-sm,8px);background:transparent;color:var(--dsw-alias-label-primary);font:inherit;font-size:12px;line-height:18px;cursor:pointer;box-shadow:inset 0 0 0 var(--dsh-hairline-width,.5px) var(--dsh-button-outline-color,var(--dsw-alias-border-l3));text-decoration:none;white-space:nowrap}
102
+ .nib-btn:disabled{cursor:not-allowed;opacity:.4}
103
+ @media (hover:hover){.nib-btn:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover)}.nib-item:hover{background:var(--dsw-alias-interactive-bg-hover)}}
104
+ .nib-primary{background:var(--dsw-alias-state-business-primary);color:var(--dsw-alias-label-on-color,#fff);box-shadow:none}
105
+ .nib-push{display:flex;align-items:center;flex-wrap:wrap;gap:8px;padding:10px 12px;margin-bottom:16px;border-radius:12px;box-shadow:inset 0 0 0 .5px var(--dsw-alias-border-l3);color:var(--dsw-alias-label-secondary);font-size:13px}
106
+ .nib-push strong{font-weight:500;color:var(--dsw-alias-label-primary)}
107
+ .nib-push .nib-grow{flex:1;min-width:120px}
108
+ .nib-hint{width:100%;color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px}
109
+ .nib-list{display:flex;flex-direction:column;gap:2px;margin:0;padding:0;list-style:none}
110
+ .nib-item{border-radius:12px;padding:10px 12px;position:relative}
111
+ .nib-item.nib-open{background:var(--dsw-alias-bg-layer-1,var(--dsw-alias-interactive-bg-hover))}
112
+ .nib-row{display:flex;gap:10px;align-items:flex-start;width:100%;border:none;background:transparent;color:inherit;font:inherit;text-align:left;padding:0;cursor:pointer}
113
+ .nib-dot{flex:none;width:8px;height:8px;border-radius:50%;margin-top:8px;background:transparent}
114
+ .nib-unread .nib-dot{background:var(--dsw-alias-state-business-primary)}
115
+ .nib-unread.nib-urgent .nib-dot{background:var(--dsw-alias-state-error-primary)}
116
+ .nib-main{flex:1;min-width:0}
117
+ .nib-titleLine{display:flex;align-items:baseline;gap:8px;min-width:0}
118
+ .nib-title{flex:1;min-width:0;font-weight:400;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--dsw-alias-label-secondary)}
119
+ .nib-unread .nib-title{font-weight:600;color:var(--dsw-alias-label-primary)}
120
+ .nib-open .nib-title{white-space:normal;overflow-wrap:anywhere}
121
+ .nib-time{flex:none;color:var(--dsw-alias-label-caption);font-size:12px}
122
+ .nib-spoken{color:var(--dsw-alias-label-tertiary);font-size:13px;line-height:20px;overflow:hidden;text-overflow:ellipsis;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow-wrap:anywhere}
123
+ .nib-chip{display:inline-block;flex:none;padding:0 6px;border-radius:6px;font-size:11px;line-height:18px;font-weight:500;color:var(--dsw-alias-state-error-primary);box-shadow:inset 0 0 0 .5px currentColor}
124
+ .nib-chip.nib-muted{color:var(--dsw-alias-label-tertiary)}
125
+ .nib-body{margin:8px 0 0 18px;display:flex;flex-direction:column;gap:10px}
126
+ .nib-text{white-space:pre-wrap;overflow-wrap:anywhere;font-size:14px;line-height:22px}
127
+ .nib-links{display:flex;flex-direction:column;gap:2px;font-size:13px}
128
+ .nib-links a{color:var(--dsw-alias-state-business-primary);overflow-wrap:anywhere}
129
+ .nib-meta{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px}
130
+ .nib-route{display:inline-flex;gap:3px;margin-right:10px}
131
+ .nib-ok{color:var(--dsw-alias-state-success-primary)}
132
+ .nib-bad{color:var(--dsw-alias-state-error-primary)}
133
+ .nib-actions{display:flex;flex-wrap:wrap;gap:6px;align-items:center}
134
+ .nib-status{color:var(--dsw-alias-label-tertiary);font-size:12px}
135
+ .nib-empty{color:var(--dsw-alias-label-tertiary);padding:24px 12px}
136
+ .nib-error{color:var(--dsw-alias-state-error-primary);padding:12px}
137
+ .nib-more{margin:12px auto 0;display:flex}
138
+ .nib-icon{position:relative;display:inline-flex}
139
+ .nib-badge{position:absolute;top:-5px;right:-8px;min-width:14px;height:14px;padding:0 3px;box-sizing:border-box;border-radius:7px;background:var(--dsw-alias-state-error-primary);color:#fff;font-size:9px;font-weight:600;line-height:14px;text-align:center;pointer-events:none}
140
+ @media (width<=640px){.nib-content{padding-inline:12px}.nib-head{padding-top:16px}.nib-body{margin-left:0}.nib-item{padding:10px 8px}}
141
+ `
142
+
143
+ // ---- shared state: the unread count and a version that bumps when anything changes ----
144
+
145
+ const shared = { unread: 0, version: 0, pollSeconds: 30, linked: null }
146
+ const listeners = new Set()
147
+ const emit = () => { for (const listener of listeners) listener() }
148
+ const subscribe = listener => { listeners.add(listener); return () => listeners.delete(listener) }
149
+ const useShared = select => useSyncExternalStore(subscribe, () => select(shared))
150
+
151
+ async function call(path, value) {
152
+ const init = value === undefined
153
+ ? { credentials: 'same-origin', headers: { accept: 'application/json' } }
154
+ : { method: 'POST', credentials: 'same-origin', headers: { 'content-type': 'application/json', accept: 'application/json' }, body: JSON.stringify(value) }
155
+ const response = await fetch(api(path), init)
156
+ const body = await response.json().catch(() => ({}))
157
+ if (!response.ok) throw new Error(body.error || `HTTP ${response.status}`)
158
+ return body
159
+ }
160
+
161
+ let lastSummary = ''
162
+ async function refreshSummary() {
163
+ try {
164
+ const summary = await call('summary')
165
+ shared.pollSeconds = summary.pollSeconds || 30
166
+ const key = `${summary.unread}|${summary.latest}|${summary.total}`
167
+ if (key !== lastSummary) {
168
+ lastSummary = key
169
+ shared.unread = summary.unread
170
+ shared.version += 1
171
+ emit()
172
+ }
173
+ } catch {
174
+ // Signed out or DSH restarting; try again at the next tick.
175
+ }
176
+ }
177
+ const changed = () => { lastSummary = ''; refreshSummary() }
178
+
179
+ // ---- time ----
180
+
181
+ function relative(iso, t) {
182
+ const seconds = (Date.parse(iso) - Date.now()) / 1000
183
+ const format = new Intl.RelativeTimeFormat(t('time.locale'), { numeric: 'auto', style: 'short' })
184
+ const abs = Math.abs(seconds)
185
+ if (abs < 60) return format.format(Math.round(seconds), 'second')
186
+ if (abs < 3600) return format.format(Math.round(seconds / 60), 'minute')
187
+ if (abs < 86400) return format.format(Math.round(seconds / 3600), 'hour')
188
+ if (abs < 86400 * 7) return format.format(Math.round(seconds / 86400), 'day')
189
+ return new Date(iso).toLocaleDateString(t('time.locale'), { month: 'short', day: 'numeric' })
190
+ }
191
+ const absolute = (iso, t) => new Date(iso).toLocaleString(t('time.locale'), { dateStyle: 'medium', timeStyle: 'short' })
192
+
193
+ /** What happened to this item's latest press, in words, or null. */
194
+ function pressStatus(item, t) {
195
+ const press = item.presses[item.presses.length - 1]
196
+ if (press === undefined) return null
197
+ const handled = item.handled.find(row => row.press === press.press)
198
+ if (handled !== undefined) {
199
+ if (handled.result === 'snoozed' && handled.until) return t('press.snoozed', { time: absolute(handled.until, t) })
200
+ if (handled.result === 'done') return t('press.done')
201
+ return handled.result
202
+ }
203
+ return Date.now() - Date.parse(press.at) < PENDING_MS ? t('press.pending') : t('press.unhandled')
204
+ }
205
+
206
+ // ---- the buttons: the shared action bar (client.actions.js, also used by the card board) ----
207
+
208
+ let actionsModule
209
+ const loadActions = () => (actionsModule ??= require.async('./client.actions.js'))
210
+
211
+ /** The server's view of each button's last press: pending, done or unhandled. */
212
+ function pressStates(item) {
213
+ const states = {}
214
+ for (const press of item.presses) {
215
+ const action = item.actions.find(row => row.kind === press.action) ?? { id: press.action }
216
+ const handled = item.handled.some(row => row.press === press.press)
217
+ states[action.id] = handled ? 'done' : Date.now() - Date.parse(press.at) < PENDING_MS ? 'pending' : 'unhandled'
218
+ }
219
+ return states
220
+ }
221
+
222
+ function Actions({ item, t, ui }) {
223
+ if (ui === null) return null
224
+ const declared = item.actions.some(action => action.kind === 'chat') ? item.actions : [{ kind: 'chat', id: 'chat', payload: {} }, ...item.actions]
225
+ const chat = action => ui.startChat({
226
+ text: ui.chatText({ prompt: action.payload?.prompt ?? '', title: item.title || item.spoken, lines: (item.text || item.spoken).split('\n'),
227
+ context: { notification: item.id, time: item.time, lane: item.lane, domain: item.domain || undefined, links: item.links.length ? item.links : undefined } }),
228
+ session: action.payload?.session,
229
+ })
230
+ const onPress = async (action, extra) => {
231
+ await call('action', { record: item.id, action: action.id, ...(extra?.until ? { until: extra.until } : {}) })
232
+ changed()
233
+ }
234
+ const status = pressStatus(item, t)
235
+ return h('div', { className: 'nib-actions' }, h(ui.ActionBar, { actions: declared, states: pressStates(item), chat, onPress }),
236
+ status && h('span', { className: 'nib-status' }, status))
237
+ }
238
+
239
+ // ---- one notification ----
240
+
241
+ function Item({ item, t, open, onToggle, ui }) {
242
+ const urgent = item.lane === 'interrupt'
243
+ const className = ['nib-item', item.read ? '' : 'nib-unread', urgent ? 'nib-urgent' : '', open ? 'nib-open' : ''].filter(Boolean).join(' ')
244
+ const title = item.title || item.spoken || item.text.slice(0, 80)
245
+ const sub = item.spoken && item.spoken !== title ? item.spoken : item.text !== title ? item.text : ''
246
+ return h('li', { className, id: `nib-${item.id}` },
247
+ h('button', { type: 'button', className: 'nib-row', 'aria-expanded': open, onClick: () => onToggle(item) },
248
+ h('span', { className: 'nib-dot', 'aria-hidden': true }),
249
+ h('span', { className: 'nib-main' },
250
+ h('span', { className: 'nib-titleLine' },
251
+ urgent && h('span', { className: 'nib-chip' }, t('urgent')),
252
+ item.test && h('span', { className: 'nib-chip nib-muted' }, t('test')),
253
+ h('span', { className: 'nib-title' }, title),
254
+ h('span', { className: 'nib-time', title: absolute(item.time, t) }, relative(item.time, t))),
255
+ !open && sub && h('span', { className: 'nib-spoken' }, sub))),
256
+ open && h('div', { className: 'nib-body' },
257
+ item.text && item.text !== title && h('div', { className: 'nib-text' }, item.text),
258
+ item.links.length > 0 && h('div', { className: 'nib-links' },
259
+ item.links.map(link => h('a', { key: link, href: link, target: '_blank', rel: 'noopener noreferrer' }, link))),
260
+ item.files.length > 0 && h('div', { className: 'nib-links' },
261
+ h('span', { className: 'nib-meta' }, t('files')),
262
+ item.files.map(file => file.stored
263
+ ? h('a', { key: file.name, href: api(`file?id=${encodeURIComponent(item.id)}&name=${encodeURIComponent(file.name)}`), target: '_blank', rel: 'noopener' }, file.name)
264
+ : h('span', { key: file.name, className: 'nib-meta' }, `${file.name} (${t('notStored', { reason: file.reason || '?' })})`))),
265
+ h(Actions, { item, t, ui }),
266
+ h('div', { className: 'nib-meta' },
267
+ item.routed.length === 0 ? t('notSent') : h(React.Fragment, null, `${t('alsoSent')}: `,
268
+ item.routed.map(row => h('span', { key: row.destination, className: 'nib-route', title: row.detail || '' },
269
+ row.destination, h('span', { className: row.ok ? 'nib-ok' : 'nib-bad' }, row.ok ? '✓' : '✗'),
270
+ !row.ok && row.detail ? ` ${row.detail}` : ''))),
271
+ ` · ${absolute(item.time, t)}`)))
272
+ }
273
+
274
+ // ---- push on this device ----
275
+
276
+ const pushSupported = () => typeof navigator !== 'undefined' && 'serviceWorker' in navigator && typeof window.PushManager === 'function' && typeof window.Notification === 'function'
277
+ const isIos = () => /iPad|iPhone|iPod/.test(navigator.userAgent) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)
278
+ const standalone = () => window.matchMedia?.('(display-mode: standalone)').matches || navigator.standalone === true
279
+ const keyBytes = base64url => {
280
+ const base64 = base64url.replaceAll('-', '+').replaceAll('_', '/')
281
+ return Uint8Array.from(atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, '=')), c => c.charCodeAt(0))
282
+ }
283
+ const deviceLabel = () => {
284
+ const ua = navigator.userAgent
285
+ const os = /iPhone|iPad/.test(ua) ? 'iOS' : /Android/.test(ua) ? 'Android' : /Mac OS X/.test(ua) ? 'macOS' : /Windows/.test(ua) ? 'Windows' : /Linux/.test(ua) ? 'Linux' : ''
286
+ const browser = /Edg\//.test(ua) ? 'Edge' : /Firefox\//.test(ua) ? 'Firefox' : /Chrome\//.test(ua) ? 'Chrome' : /Safari\//.test(ua) ? 'Safari' : 'Browser'
287
+ return [browser, os].filter(Boolean).join(' on ')
288
+ }
289
+
290
+ async function currentSubscription() {
291
+ const registration = await navigator.serviceWorker.getRegistration(api(''))
292
+ return (await registration?.pushManager.getSubscription()) ?? null
293
+ }
294
+
295
+ function PushControl({ t }) {
296
+ const supported = pushSupported()
297
+ const [state, setState] = useState('checking')
298
+ const [note, setNote] = useState(null)
299
+ const [busy, setBusy] = useState(false)
300
+ useEffect(() => {
301
+ if (!supported) return
302
+ let live = true
303
+ currentSubscription()
304
+ .then(async sub => (sub === null ? false : (await call('push/state', { endpoint: sub.endpoint })).subscribed))
305
+ .then(on => { if (live) setState(on ? 'on' : 'off') }, () => { if (live) setState('off') })
306
+ return () => { live = false }
307
+ }, [supported])
308
+ if (!supported) {
309
+ return h('div', { className: 'nib-push' }, h('span', { className: 'nib-grow' }, h('strong', null, t('push.title'))),
310
+ h('span', { className: 'nib-hint' }, isIos() && !standalone() ? t('push.ios') : t('push.unsupported')))
311
+ }
312
+ const run = task => async () => {
313
+ setBusy(true)
314
+ setNote(null)
315
+ try {
316
+ await task()
317
+ } catch (reason) {
318
+ setNote(reason.message)
319
+ } finally {
320
+ setBusy(false)
321
+ }
322
+ }
323
+ const enable = run(async () => {
324
+ const permission = await Notification.requestPermission()
325
+ if (permission !== 'granted') {
326
+ setNote(t('push.denied'))
327
+ return
328
+ }
329
+ const { publicKey } = await call('push/config')
330
+ const registration = await navigator.serviceWorker.register(api('sw.js'), { scope: api('') })
331
+ const worker = registration.installing ?? registration.waiting ?? registration.active
332
+ if (worker && worker.state !== 'activated') {
333
+ await new Promise(resolve => worker.addEventListener('statechange', () => { if (worker.state === 'activated') resolve() }))
334
+ }
335
+ let sub = await registration.pushManager.getSubscription()
336
+ sub ??= await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: keyBytes(publicKey) })
337
+ await call('push/subscribe', { subscription: sub.toJSON(), label: deviceLabel() })
338
+ setState('on')
339
+ })
340
+ const disable = run(async () => {
341
+ const sub = await currentSubscription()
342
+ if (sub !== null) {
343
+ await call('push/unsubscribe', { endpoint: sub.endpoint })
344
+ await sub.unsubscribe()
345
+ }
346
+ setState('off')
347
+ })
348
+ const test = run(async () => {
349
+ const result = await call('push/test', {})
350
+ setNote(t('push.testSent', { n: result.sent }))
351
+ })
352
+ return h('div', { className: 'nib-push' },
353
+ h('span', { className: 'nib-grow' }, h('strong', null, t('push.title')), ' · ', state === 'on' ? t('push.on') : state === 'off' ? t('push.off') : '…'),
354
+ state === 'on' && h('button', { type: 'button', className: 'nib-btn', disabled: busy, onClick: test }, t('push.test')),
355
+ state === 'on' && h('button', { type: 'button', className: 'nib-btn', disabled: busy, onClick: disable }, t('push.disable')),
356
+ state === 'off' && h('button', { type: 'button', className: 'nib-btn nib-primary', disabled: busy, onClick: enable }, t('push.enable')),
357
+ note && h('span', { className: 'nib-hint' }, note))
358
+ }
359
+
360
+ // ---- the page ----
361
+
362
+ function InboxPage({ translate: t, makeActions }) {
363
+ const version = useShared(s => s.version)
364
+ const unread = useShared(s => s.unread)
365
+ const linked = useShared(s => s.linked)
366
+ const [filter, setFilter] = useState(() => (shared.linked ? 'all' : 'unread'))
367
+ const [items, setItems] = useState(null)
368
+ const [more, setMore] = useState(false)
369
+ const [error, setError] = useState(null)
370
+ const [open, setOpen] = useState(() => shared.linked)
371
+ const [ui, setUi] = useState(null)
372
+ useEffect(() => {
373
+ let live = true
374
+ makeActions(t('time.locale')).then(made => { if (live) setUi(made) }, reason => { if (live) setError(reason.message) })
375
+ return () => { live = false }
376
+ }, [])
377
+
378
+ const load = useCallback(async (append) => {
379
+ try {
380
+ const params = new URLSearchParams()
381
+ if (filter === 'unread') params.set('unread', '1')
382
+ if (append && items?.length) params.set('before', items[items.length - 1].id)
383
+ const page = await call(`items?${params}`)
384
+ setItems(previous => (append && previous ? [...previous, ...page.items] : page.items))
385
+ setMore(page.more)
386
+ setError(null)
387
+ } catch (reason) {
388
+ setError(reason.message)
389
+ }
390
+ }, [filter, items])
391
+
392
+ useEffect(() => { load(false) }, [filter, version])
393
+ useEffect(() => {
394
+ if (!linked) return
395
+ setFilter('all')
396
+ setOpen(linked)
397
+ shared.linked = null
398
+ call('read', { ids: [linked] }).then(changed, () => {})
399
+ setTimeout(() => document.getElementById(`nib-${linked}`)?.scrollIntoView({ block: 'center' }), 300)
400
+ }, [linked])
401
+
402
+ const toggle = item => {
403
+ const next = open === item.id ? null : item.id
404
+ setOpen(next)
405
+ if (next !== null && !item.read) {
406
+ setItems(list => list.map(row => (row.id === item.id ? { ...row, read: true } : row)))
407
+ call('read', { ids: [item.id] }).then(changed, () => {})
408
+ }
409
+ }
410
+ const markAll = () => call('read', { all: true }).then(changed, reason => setError(reason.message))
411
+
412
+ return h('div', { className: 'nib-page' },
413
+ h('div', { className: 'nib-scroll' },
414
+ h('div', { className: 'nib-content' },
415
+ h('div', { className: 'nib-head' },
416
+ h('h1', null, t('title'), unread > 0 && h('span', { className: 'nib-count' }, unread)),
417
+ h('div', { className: 'nib-tabs', role: 'group' },
418
+ ['unread', 'all'].map(key => h('button', { key, type: 'button', className: 'nib-tab', 'aria-pressed': filter === key, onClick: () => setFilter(key) }, t(`filter.${key}`)))),
419
+ h('button', { type: 'button', className: 'nib-btn', disabled: unread === 0, onClick: markAll }, t('markAll'))),
420
+ h(PushControl, { t }),
421
+ error && h('p', { className: 'nib-error', role: 'alert' }, t('error', { message: error })),
422
+ items !== null && items.length === 0 && h('p', { className: 'nib-empty' }, t(filter === 'unread' ? 'empty.unread' : 'empty.all')),
423
+ items !== null && h('ul', { className: 'nib-list' },
424
+ items.map(item => h(Item, { key: item.id, item, t, open: open === item.id, onToggle: toggle, ui }))),
425
+ more && h('button', { type: 'button', className: 'nib-btn nib-more', onClick: () => load(true) }, t('loadMore')))))
426
+ }
427
+
428
+ function SidebarIcon({ size }) {
429
+ const unread = useShared(s => s.unread)
430
+ const stroke = { stroke: 'currentColor', strokeWidth: 1.2, strokeLinecap: 'round', strokeLinejoin: 'round' }
431
+ return h('span', { className: 'nib-icon' },
432
+ h('svg', { width: size, height: size, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': true, focusable: 'false' },
433
+ h('path', { d: 'M8 2.2c-2.3 0-3.9 1.8-3.9 4v2.3L3 10.4c-.2.4.1.9.5.9h9c.4 0 .7-.5.5-.9l-1.1-1.9V6.2c0-2.2-1.6-4-3.9-4Z', ...stroke }),
434
+ h('path', { d: 'M6.5 13.2c.3.7.9 1.1 1.5 1.1s1.2-.4 1.5-1.1', ...stroke })),
435
+ unread > 0 && h('span', { className: 'nib-badge' }, unread > 99 ? '99+' : String(unread)))
436
+ }
437
+
438
+ return {
439
+ inject: ['slots', 'locale'],
440
+ apply(ctx) {
441
+ ctx.effect(() => {
442
+ const disposers = [ctx.locale.register(NS, 'en', en), ctx.locale.register(NS, 'zh', zh)]
443
+ return () => { for (const dispose of disposers) dispose() }
444
+ }, 'notify-inbox: dictionaries')
445
+ const t = ctx.locale.bind(NS)
446
+
447
+ ctx.effect(() => {
448
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return () => {}
449
+ const tag = document.createElement('style')
450
+ tag.id = STYLE_ID
451
+ tag.textContent = CSS
452
+ document.head.appendChild(tag)
453
+ return () => tag.remove()
454
+ }, 'notify-inbox: styles')
455
+
456
+ const makeActions = locale => loadActions().then(module => module.createActions({ React, ctx, locale }))
457
+
458
+ ctx.slots.inject('main', () => ctx.slots.register({
459
+ name: 'main',
460
+ key: PANEL,
461
+ locale: NS,
462
+ inject: () => ({ translate: t, makeActions }),
463
+ }, InboxPage))
464
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
465
+ name: 'sidebar.panellist',
466
+ id: PANEL,
467
+ order: 11,
468
+ locale: NS,
469
+ label: () => t('panel'),
470
+ }, SidebarIcon))
471
+
472
+ // The unread count: checked while the page is visible, and right away when it becomes visible.
473
+ ctx.effect(() => {
474
+ let timer
475
+ const tick = () => {
476
+ clearTimeout(timer)
477
+ if (document.visibilityState === 'visible') refreshSummary()
478
+ timer = setTimeout(tick, shared.pollSeconds * 1000)
479
+ }
480
+ const onVisible = () => { if (document.visibilityState === 'visible') tick() }
481
+ document.addEventListener('visibilitychange', onVisible)
482
+ tick()
483
+ return () => { clearTimeout(timer); document.removeEventListener('visibilitychange', onVisible) }
484
+ }, 'notify-inbox: unread count')
485
+
486
+ // ?notify-inbox=<id> (a tapped push, a shared link) opens the page on that notification.
487
+ const openLinked = id => {
488
+ shared.linked = id || null
489
+ emit()
490
+ let tries = 0
491
+ const timer = setInterval(() => {
492
+ const layout = ctx.get('layout')
493
+ try {
494
+ layout?.selectPanel(PANEL)
495
+ if (layout) clearInterval(timer)
496
+ } catch {
497
+ // The main slot entry is not registered yet.
498
+ }
499
+ if (++tries > 50) clearInterval(timer)
500
+ }, 100)
501
+ }
502
+ ctx.effect(() => {
503
+ const params = new URLSearchParams(location.search)
504
+ if (params.has(LINK_PARAM)) {
505
+ const id = params.get(LINK_PARAM)
506
+ params.delete(LINK_PARAM)
507
+ const query = params.toString()
508
+ history.replaceState(history.state, '', `${location.pathname}${query ? `?${query}` : ''}${location.hash}`)
509
+ openLinked(id)
510
+ }
511
+ const onMessage = event => {
512
+ if (event.data?.type !== 'notify-inbox/open') return
513
+ try {
514
+ openLinked(new URL(event.data.url, location.href).searchParams.get(LINK_PARAM))
515
+ } catch {
516
+ // Not one of ours.
517
+ }
518
+ }
519
+ navigator.serviceWorker?.addEventListener('message', onMessage)
520
+ navigator.serviceWorker?.startMessages?.()
521
+ return () => navigator.serviceWorker?.removeEventListener('message', onMessage)
522
+ }, 'notify-inbox: links')
523
+ },
524
+ }
525
+ },
526
+ })
@@ -0,0 +1,9 @@
1
+ # Bundle layer for @soffits/dsh-notify-inbox: one Host row serving the inbox
2
+ # to the Web UI. Set dataDir (the folder your notification router files into)
3
+ # and, for a DSH several people sign in to, people / peopleFile in a profile
4
+ # override of this row.
5
+ - insert:
6
+ - id: notify-inbox
7
+ name: '@soffits/dsh-notify-inbox'
8
+ config:
9
+ dataDir: ~/.dsh/notify-inbox
package/icon.svg ADDED
@@ -0,0 +1,6 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64" fill="none">
2
+ <rect width="64" height="64" rx="14" fill="#4D6BFE"/>
3
+ <path d="M32 14c-7.2 0-12 5.4-12 12.4v7.4l-3.6 6.2c-.7 1.2.2 2.7 1.6 2.7h28c1.4 0 2.3-1.5 1.6-2.7L44 33.8v-7.4C44 19.4 39.2 14 32 14Z" stroke="#fff" stroke-width="3.5" stroke-linejoin="round"/>
4
+ <path d="M27 47.5c.9 2.3 2.8 3.7 5 3.7s4.1-1.4 5-3.7" stroke="#fff" stroke-width="3.5" stroke-linecap="round"/>
5
+ <circle cx="45" cy="18" r="6" fill="#FF6B5B" stroke="#4D6BFE" stroke-width="2.5"/>
6
+ </svg>
package/index.js ADDED
@@ -0,0 +1,90 @@
1
+ /**
2
+ * DeepSeek Harness Host plugin: a notification inbox.
3
+ *
4
+ * A notification router outside DSH files each message as one JSON line per
5
+ * person (`<dataDir>/<person>/inbox.jsonl`). This plugin shows each signed-in
6
+ * person their own inbox with read and unread, sends Web Push to the browsers
7
+ * they subscribed, and turns presses on a notification's buttons into events.
8
+ * It holds no credentials but its own VAPID key and contacts nothing but the
9
+ * push services the subscribed browsers chose.
10
+ */
11
+ import { readFileSync } from 'node:fs'
12
+ import { homedir } from 'node:os'
13
+ import { isAbsolute, join, resolve } from 'node:path'
14
+ import z from '@deepseek-ai/schemastery'
15
+ import { createPeople, expandHome } from './src/access.js'
16
+ import { createActions } from './src/actions.js'
17
+ import { createPush } from './src/push.js'
18
+ import { createRoutes } from './src/routes.js'
19
+ import { createStore } from './src/store.js'
20
+
21
+ export const name = 'dsh-notify-inbox'
22
+ export const inject = ['connection']
23
+
24
+ const serviceWorker = readFileSync(new URL('./src/sw.js', import.meta.url), 'utf8')
25
+
26
+ export const Config = z.object({
27
+ dataDir: z.string().required()
28
+ .description('The folder the notification router files into: <dataDir>/<person>/inbox.jsonl. Read marks, the action log and push subscriptions are kept in it too. A leading ~/ means the home folder.'),
29
+ people: z.dict(z.string()).default({})
30
+ .description('Verified user id (from the sign-in plugin, such as an OIDC sub) → person id (the inbox folder name). With any mapping configured, each person sees only their own inbox.'),
31
+ peopleFile: z.string().default('')
32
+ .description('A JSON file with more of the same mapping, re-read when it changes. Entries in people win.'),
33
+ peopleKey: z.string().default('')
34
+ .description('The top-level key in peopleFile that holds the mapping. Empty means the whole file is the mapping.'),
35
+ vapidFile: z.string().default('')
36
+ .description('Where the Web Push (VAPID) key pair is kept; made on first start, mode 600. Default: .push/vapid.json in dataDir.'),
37
+ vapidSubject: z.string().default('mailto:admin@example.invalid')
38
+ .description('A mailto: or https: contact that push services can reach about this server.'),
39
+ pollSeconds: z.natural().min(2).max(3600).default(5)
40
+ .description('How often new records are looked for (to push them), and how often an open page refreshes its count (at least 15 s).'),
41
+ })
42
+
43
+ /**
44
+ * @param {import('@deepseek-ai/cordis').Context} ctx
45
+ * @param {{ dataDir: string, people: Record<string, string>, peopleFile: string, peopleKey: string, vapidFile: string, vapidSubject: string, pollSeconds: number }} config
46
+ */
47
+ export function apply(ctx, config) {
48
+ const logger = ctx.logger('notify-inbox')
49
+ const home = homedir()
50
+ const absolute = path => {
51
+ const expanded = expandHome(path, home)
52
+ return isAbsolute(expanded) ? expanded : resolve(expanded)
53
+ }
54
+ const dataDir = absolute(config.dataDir)
55
+ const warn = message => logger.warn(message)
56
+ const people = createPeople({
57
+ people: config.people ?? {},
58
+ peopleFile: config.peopleFile ? absolute(config.peopleFile) : '',
59
+ peopleKey: config.peopleKey ?? '',
60
+ }, { warn })
61
+ const store = createStore(dataDir)
62
+ const push = createPush({
63
+ dataDir,
64
+ vapidFile: config.vapidFile ? absolute(config.vapidFile) : join(dataDir, '.push', 'vapid.json'),
65
+ subject: config.vapidSubject,
66
+ perPerson: () => people.enabled,
67
+ warn,
68
+ })
69
+ const actions = createActions({ dataDir, events: () => ctx.get('cronJobs'), warn })
70
+ const pollSeconds = config.pollSeconds ?? 5
71
+ const routes = createRoutes({ store, people, push, actions, identity: () => ctx.get('requestIdentity'), serviceWorker, pollSeconds: Math.max(pollSeconds, 15) })
72
+ for (const route of routes) ctx.connection.fetch.register(route)
73
+
74
+ let stopped = false
75
+ let timer
76
+ const scan = async () => {
77
+ try {
78
+ await push.scan(await store.persons())
79
+ } catch (error) {
80
+ warn(`push scan failed: ${error.message}`)
81
+ }
82
+ if (!stopped) timer = setTimeout(scan, pollSeconds * 1000)
83
+ }
84
+ push.vapid().then(() => scan(), error => logger.error(`Web Push keys unusable, push is off: ${error.message}`))
85
+ ctx.on('dispose', () => {
86
+ stopped = true
87
+ clearTimeout(timer)
88
+ })
89
+ logger.info(`inbox at ${dataDir} (${people.enabled ? 'per person' : 'single owner'})`)
90
+ }
package/locale/en.json ADDED
@@ -0,0 +1 @@
1
+ { "meta": { "title": "Notification Inbox", "description": "One inbox for the notifications your assistant and scripts send: read and unread per person, Web Push to phones and browsers, and buttons to act on each one." } }
package/locale/zh.json ADDED
@@ -0,0 +1 @@
1
+ { "meta": { "title": "通知收件箱", "description": "助手和脚本发出的通知都收在这里:每个人各看各的、分已读未读,推送到手机和浏览器,每条通知都能直接操作。" } }