@soffits/dsh-notify-inbox 0.2.1 → 0.4.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/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.0
4
+
5
+ - Suggested next steps: a notification's `step` actions show as their own buttons (from @soffits/dsh-ui-actions 0.2.0). A tap is recorded here like done and snooze, as the event `ui.action.step` with who pressed it, then the step is sent to the assistant; the row says "Started".
6
+ - Button labels may be maps from language tag to text.
7
+ - Each press remembers which button it was, so several steps on one notification keep their own state.
8
+
9
+ ## 0.3.0
10
+
11
+ - The buttons come from [@soffits/dsh-ui-actions](https://github.com/soffits/dsh-ui-actions), installed as its own plugin, instead of a copy of the card board's chunk. "Ask" now opens a conversation with the notification attached as a card the person can remove and write beside; the sent message shows the same card, and the agent gets the notification as compact text with its id. Without the package the page works and shows no buttons.
12
+ - The buttons' words moved to that package; the page's locale files keep only its own.
13
+
3
14
  ## 0.2.1
4
15
 
5
16
  - Under Unread, a notification you open, mark done or snooze stays where it is, shown as read, until you leave the view or tap Unread again, so the list never moves under your finger. Mark all read works the same way.
package/README.md CHANGED
@@ -62,9 +62,11 @@ A line `{"v": 1, "type": "handled", "record": "<id>", "press": "<press id>", "ac
62
62
 
63
63
  ## Buttons
64
64
 
65
- Every notification gets **Ask about this**: it opens a new session with the notification quoted into the message box, ready to edit and send. Since the person sends it from the Web UI, the sign-in plugin records them as the sender.
65
+ The buttons come from [@soffits/dsh-ui-actions](https://github.com/soffits/dsh-ui-actions); install it as a plugin too (`dsh plugin --profile web add @soffits/dsh-ui-actions`). Without it the inbox works and shows no buttons.
66
66
 
67
- Declared `actions` add more: `done`, `snooze` (a small picker: in an hour, this evening, tomorrow morning; or a fixed `payload.until`), `event` (anything else) and `link` (`payload.url`). A press on `done`, `snooze` or `event` is checked on the server (the record must be the caller's and declare that button), appended to `<dataDir>/<person>/actions.jsonl`, and published on the event channel `ui.action.<kind>` when [dsh-cron-jobs](https://github.com/soffits/dsh-cron-jobs) is installed, so a job listening there can act on it:
67
+ Every notification gets **Ask**: it opens a new session with the notification attached to the message box as a card (removable), and the person writes their own words beside it. The sent message shows the same card; the agent gets the notification as a short quote with its id. Since the person sends it from the Web UI, the sign-in plugin records them as the sender.
68
+
69
+ Declared `actions` add more: `step` (a suggested next step whoever filed the notification knows, like "Pay it from the joint account": one tap records the press, then sends the step with the notification to the assistant as the person, at most three; `label` required, text or `{ "en": …, "zh": … }`), `done`, `snooze` (a small picker: in an hour, this evening, tomorrow morning; or a fixed `payload.until`), `event` (anything else) and `link` (`payload.url`). A press on `step`, `done`, `snooze` or `event` is checked on the server (the record must be the caller's and declare that button), appended to `<dataDir>/<person>/actions.jsonl`, and published on the event channel `ui.action.<kind>` when [dsh-cron-jobs](https://github.com/soffits/dsh-cron-jobs) is installed, so a job listening there can act on it:
68
70
 
69
71
  ```json
70
72
  {"action": "snooze", "id": "snooze", "payload": {"until": "2026-11-18T09:00:00-05:00"}, "person": "ana",
package/client.js CHANGED
@@ -82,7 +82,7 @@ window.__ModuleLoader__.load({
82
82
 
83
83
  // ---- shared state: the unread count and a version that bumps when anything changes ----
84
84
 
85
- const shared = { unread: 0, version: 0, pollSeconds: 30, linked: null }
85
+ const shared = { unread: 0, version: 0, pollSeconds: 30, linked: null, ui: null }
86
86
  const listeners = new Set()
87
87
  const emit = () => { for (const listener of listeners) listener() }
88
88
  const subscribe = listener => { listeners.add(listener); return () => listeners.delete(listener) }
@@ -134,6 +134,7 @@ window.__ModuleLoader__.load({
134
134
  function pressStatus(item, t) {
135
135
  const press = item.presses[item.presses.length - 1]
136
136
  if (press === undefined) return null
137
+ if (press.action === 'step') return t('press.started')
137
138
  const handled = item.handled.find(row => row.press === press.press)
138
139
  if (handled !== undefined) {
139
140
  if (handled.result === 'snoozed' && handled.until) return t('press.snoozed', { time: absolute(handled.until, t) })
@@ -143,16 +144,15 @@ window.__ModuleLoader__.load({
143
144
  return Date.now() - Date.parse(press.at) < PENDING_MS ? t('press.pending') : t('press.unhandled')
144
145
  }
145
146
 
146
- // ---- the buttons: the shared action bar (client.actions.js, also used by the card board) ----
147
+ // ---- the buttons: @soffits/dsh-ui-actions (ctx.uiActions), shared with other plugin pages ----
147
148
 
148
- let actionsModule
149
- const loadActions = () => (actionsModule ??= require.async('./client.actions.js').catch(error => { actionsModule = undefined; throw error }))
149
+ const OWNER = '@soffits/dsh-notify-inbox'
150
150
 
151
151
  /** The server's view of each button's last press: pending, done or unhandled. */
152
152
  function pressStates(item) {
153
153
  const states = {}
154
154
  for (const press of item.presses) {
155
- const action = item.actions.find(row => row.kind === press.action) ?? { id: press.action }
155
+ const action = item.actions.find(row => row.id === press.id) ?? item.actions.find(row => row.kind === press.action) ?? { id: press.action }
156
156
  const handled = item.handled.some(row => row.press === press.press)
157
157
  states[action.id] = handled ? 'done' : Date.now() - Date.parse(press.at) < PENDING_MS ? 'pending' : 'unhandled'
158
158
  }
@@ -162,20 +162,21 @@ window.__ModuleLoader__.load({
162
162
  function Actions({ item, t, ui, onMark }) {
163
163
  const markUnread = item.read && h('button', { type: 'button', className: 'nib-btn', onClick: () => onMark(item, false) }, t('markUnread'))
164
164
  if (ui === null) return markUnread ? h('div', { className: 'nib-actions' }, markUnread) : null
165
- const declared = item.actions.some(action => action.kind === 'chat') ? item.actions : [{ kind: 'chat', id: 'chat', payload: {} }, ...item.actions]
166
- const chat = action => ui.startChat({
167
- text: ui.chatText({ prompt: action.payload?.prompt ?? '', title: item.title || item.spoken, lines: (item.text || item.spoken).split('\n'),
168
- context: { notification: item.id, time: item.time, lane: item.lane, domain: item.domain || undefined, links: item.links.length ? item.links : undefined } }),
169
- session: action.payload?.session,
170
- })
165
+ // What "Ask" attaches to the conversation: the notification as a card, its ids for the agent.
166
+ const about = {
167
+ source: OWNER,
168
+ title: item.title || item.spoken || item.text,
169
+ lines: [item.title && item.spoken !== item.title ? item.spoken : '', ...(item.text || '').split('\n'), ...item.links].filter(line => line && line !== item.title),
170
+ context: { notification: item.id, time: item.time, lane: item.lane, domain: item.domain || undefined },
171
+ }
171
172
  const onPress = async (action, extra) => {
172
173
  await call('action', { record: item.id, action: action.id, ...(extra?.until ? { until: extra.until } : {}) })
173
174
  changed()
174
175
  }
175
176
  const status = pressStatus(item, t)
176
- return h('div', { className: 'nib-actions' }, h(ui.ActionBar, { actions: declared, states: pressStates(item), chat, onPress }),
177
+ return h('div', { className: 'nib-actions' }, h(ui.ActionBar, { actions: item.actions, states: pressStates(item), about, defaultChat: true, onPress },
177
178
  markUnread,
178
- status && h('span', { className: 'nib-status' }, status))
179
+ status && h('span', { className: 'nib-status' }, status)))
179
180
  }
180
181
 
181
182
  // ---- one notification ----
@@ -311,7 +312,7 @@ window.__ModuleLoader__.load({
311
312
 
312
313
  // ---- the page ----
313
314
 
314
- function InboxPage({ translate: t, makeActions }) {
315
+ function InboxPage({ translate: t }) {
315
316
  const version = useShared(s => s.version)
316
317
  const unread = useShared(s => s.unread)
317
318
  const linked = useShared(s => s.linked)
@@ -324,12 +325,7 @@ window.__ModuleLoader__.load({
324
325
  // so the list never moves under the person's finger; leaving the view (or tapping its tab again) lets them go.
325
326
  const shown = useRef(new Set())
326
327
  const [visit, setVisit] = useState(0)
327
- const [ui, setUi] = useState(null)
328
- useEffect(() => {
329
- let live = true
330
- makeActions().then(made => { if (live) setUi(made) }, reason => { console.warn('notify-inbox: buttons unavailable', reason) })
331
- return () => { live = false }
332
- }, [])
328
+ const ui = useShared(s => s.ui)
333
329
 
334
330
  const load = useCallback(async (append) => {
335
331
  try {
@@ -391,13 +387,17 @@ window.__ModuleLoader__.load({
391
387
  more && h('button', { type: 'button', className: 'nib-btn nib-more', onClick: () => load(true) }, t('loadMore')))))
392
388
  }
393
389
 
390
+ function BellIcon({ size }) {
391
+ const stroke = { stroke: 'currentColor', strokeWidth: 1.2, strokeLinecap: 'round', strokeLinejoin: 'round' }
392
+ return h('svg', { width: size, height: size, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': true, focusable: 'false' },
393
+ 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 }),
394
+ h('path', { d: 'M6.5 13.2c.3.7.9 1.1 1.5 1.1s1.2-.4 1.5-1.1', ...stroke }))
395
+ }
396
+
394
397
  function SidebarIcon({ size }) {
395
398
  const unread = useShared(s => s.unread)
396
- const stroke = { stroke: 'currentColor', strokeWidth: 1.2, strokeLinecap: 'round', strokeLinejoin: 'round' }
397
399
  return h('span', { className: 'nib-icon' },
398
- h('svg', { width: size, height: size, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': true, focusable: 'false' },
399
- 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 }),
400
- h('path', { d: 'M6.5 13.2c.3.7.9 1.1 1.5 1.1s1.2-.4 1.5-1.1', ...stroke })),
400
+ h(BellIcon, { size }),
401
401
  unread > 0 && h('span', { className: 'nib-badge' }, unread > 99 ? '99+' : String(unread)))
402
402
  }
403
403
 
@@ -425,13 +425,21 @@ window.__ModuleLoader__.load({
425
425
  return () => tag.remove()
426
426
  }, 'notify-inbox: styles')
427
427
 
428
- const makeActions = () => loadActions().then(module => module.createActions({ React, ctx, t: (key, params) => t(`action.${key}`, params) }))
428
+ // The buttons, when @soffits/dsh-ui-actions is installed; without it the page shows no buttons.
429
+ ctx.inject(['uiActions'], scope => {
430
+ scope.effect(() => {
431
+ shared.ui = scope.uiActions
432
+ emit()
433
+ const unregister = scope.uiActions.registerSource({ id: OWNER, name: () => t('panel'), icon: BellIcon })
434
+ return () => { unregister(); shared.ui = null; emit() }
435
+ }, 'notify-inbox: buttons')
436
+ })
429
437
 
430
438
  ctx.slots.inject('main', () => ctx.slots.register({
431
439
  name: 'main',
432
440
  key: PANEL,
433
441
  locale: NS,
434
- inject: () => ({ translate: t, makeActions }),
442
+ inject: () => ({ translate: t }),
435
443
  }, InboxPage))
436
444
  ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
437
445
  name: 'sidebar.panellist',
package/locale/en.json CHANGED
@@ -23,6 +23,7 @@
23
23
  "press.unhandled": "Nobody picked this up yet",
24
24
  "press.done": "Marked done",
25
25
  "press.snoozed": "Will remind you {time}",
26
+ "press.started": "Started",
26
27
  "push.title": "Notifications on this device",
27
28
  "push.on": "On",
28
29
  "push.off": "Off",
@@ -35,23 +36,6 @@
35
36
  "push.ios": "On iPhone or iPad, add this site to the Home Screen and open it from there to turn notifications on.",
36
37
  "error": "Couldn’t load: {message}",
37
38
  "time.locale": "en-US",
38
- "action.chat": "Ask",
39
- "action.chatAbout": "Chat about this",
40
- "action.done": "Done",
41
- "action.snooze": "Snooze",
42
- "action.event": "Go",
43
- "action.link": "Open",
44
- "action.in3h": "In 3 hours",
45
- "action.tomorrow": "Tomorrow 9:00",
46
- "action.pick": "Pick a time…",
47
- "action.set": "Snooze",
48
- "action.cancel": "Cancel",
49
- "action.sending": "Sending…",
50
- "action.pending": "Waiting for it to be picked up",
51
- "action.handled": "Done",
52
- "action.unhandled": "Nothing picked this up yet",
53
- "action.failed": "Didn’t go through: {message}",
54
- "action.noWorkspace": "Open a conversation once first, then try again.",
55
39
  "push.testTitle": "Inbox",
56
40
  "push.testBody": "Notifications reach this device."
57
41
  }
package/locale/fr.json CHANGED
@@ -23,6 +23,7 @@
23
23
  "press.unhandled": "Personne ne l’a encore pris en charge",
24
24
  "press.done": "Marqué comme fait",
25
25
  "press.snoozed": "Rappel {time}",
26
+ "press.started": "Lancé",
26
27
  "push.title": "Notifications sur cet appareil",
27
28
  "push.on": "Activées",
28
29
  "push.off": "Désactivées",
@@ -35,23 +36,6 @@
35
36
  "push.ios": "Sur iPhone ou iPad, ajoutez ce site à l’écran d’accueil et ouvrez-le depuis là pour activer les notifications.",
36
37
  "error": "Chargement impossible : {message}",
37
38
  "time.locale": "fr-FR",
38
- "action.chat": "Demander",
39
- "action.chatAbout": "En discuter",
40
- "action.done": "Fait",
41
- "action.snooze": "Plus tard",
42
- "action.event": "Lancer",
43
- "action.link": "Ouvrir",
44
- "action.in3h": "Dans 3 heures",
45
- "action.tomorrow": "Demain 9:00",
46
- "action.pick": "Choisir une heure…",
47
- "action.set": "Rappeler",
48
- "action.cancel": "Annuler",
49
- "action.sending": "Envoi…",
50
- "action.pending": "En attente de traitement",
51
- "action.handled": "Fait",
52
- "action.unhandled": "Personne ne l’a encore pris en charge",
53
- "action.failed": "Échec : {message}",
54
- "action.noWorkspace": "Ouvrez d’abord une conversation, puis réessayez.",
55
39
  "push.testTitle": "Notifications",
56
40
  "push.testBody": "Les notifications arrivent sur cet appareil."
57
41
  }
package/locale/zh.json CHANGED
@@ -23,6 +23,7 @@
23
23
  "press.unhandled": "暂时没有人处理",
24
24
  "press.done": "已标为完成",
25
25
  "press.snoozed": "会在{time}再提醒",
26
+ "press.started": "已开始",
26
27
  "push.title": "本设备的通知",
27
28
  "push.on": "已开启",
28
29
  "push.off": "未开启",
@@ -35,23 +36,6 @@
35
36
  "push.ios": "iPhone 或 iPad 上,先把这个网站添加到主屏幕,再从主屏幕打开,才能开启通知。",
36
37
  "error": "加载失败:{message}",
37
38
  "time.locale": "zh-CN",
38
- "action.chat": "问问",
39
- "action.chatAbout": "聊聊这个",
40
- "action.done": "完成",
41
- "action.snooze": "稍后提醒",
42
- "action.event": "执行",
43
- "action.link": "打开",
44
- "action.in3h": "3 小时后",
45
- "action.tomorrow": "明天 9:00",
46
- "action.pick": "选个时间…",
47
- "action.set": "稍后提醒",
48
- "action.cancel": "取消",
49
- "action.sending": "发送中…",
50
- "action.pending": "等待处理",
51
- "action.handled": "已处理",
52
- "action.unhandled": "还没有被处理",
53
- "action.failed": "没有成功:{message}",
54
- "action.noWorkspace": "请先打开一次对话,再试一次。",
55
39
  "push.testTitle": "收件箱",
56
40
  "push.testBody": "这台设备能收到通知了。"
57
41
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soffits/dsh-notify-inbox",
3
- "version": "0.2.1",
3
+ "version": "0.4.0",
4
4
  "description": "A notification inbox for DeepSeek Harness: each person sees their own notifications with read and unread, gets Web Push on their phone or browser, and can act on them.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -18,12 +18,11 @@
18
18
  "exports": {
19
19
  ".": "./index.js",
20
20
  "./client": "./client.js",
21
- "./client.actions.js": "./client.actions.js",
22
21
  "./locale/*.json": "./locale/*.json",
23
22
  "./icon": "./icon.svg",
24
23
  "./package.json": "./package.json"
25
24
  },
26
- "files": ["src", "client.js", "client.actions.js", "index.js", "cordis.patch.yml", "locale/*.json", "icon.svg", "README.md", "CHANGELOG.md", "LICENSE"],
25
+ "files": ["src", "client.js", "index.js", "cordis.patch.yml", "locale/*.json", "icon.svg", "README.md", "CHANGELOG.md", "LICENSE"],
27
26
  "dsh": {
28
27
  "bundle": {
29
28
  "patch": "./cordis.patch.yml"
@@ -33,13 +32,14 @@
33
32
  "immediately": true,
34
33
  "inject": [
35
34
  "@deepseek-ai/dsh-client-locale",
35
+ "@soffits/dsh-ui-actions",
36
36
  "@deepseek-ai/dsh-client-ui-layout",
37
37
  "@deepseek-ai/dsh-client-ui-sidebar"
38
38
  ]
39
39
  }
40
40
  },
41
41
  "scripts": {
42
- "check": "for f in index.js client.js client.actions.js src/*.js test/*.js; do node --check \"$f\" || exit 1; done",
42
+ "check": "for f in index.js client.js src/*.js test/*.js; do node --check \"$f\" || exit 1; done",
43
43
  "test": "node --test test/*.test.js"
44
44
  },
45
45
  "dependencies": {
package/src/actions.js CHANGED
@@ -12,7 +12,8 @@ import { appendFile, mkdir, readFile } from 'node:fs/promises'
12
12
  import { randomBytes } from 'node:crypto'
13
13
  import { join } from 'node:path'
14
14
 
15
- export const EMITTING = ['done', 'snooze', 'event']
15
+ /** Kinds whose press is recorded here: a step's press is the person's go-ahead for what its label says. */
16
+ export const EMITTING = ['step', 'done', 'snooze', 'event']
16
17
  const ACTIONS_LOG = 'actions.jsonl'
17
18
 
18
19
  /** The event a press becomes (same shape as the practice's actions spec). */
@@ -77,7 +78,7 @@ export function createActions({ dataDir, events, warn }) {
77
78
  const event = JSON.parse(line)
78
79
  const id = event?.source?.record
79
80
  if (typeof id !== 'string') continue
80
- out.set(id, [...(out.get(id) ?? []), { press: event.press, action: event.action, at: event.at, until: event.payload?.until }])
81
+ out.set(id, [...(out.get(id) ?? []), { press: event.press, action: event.action, id: event.id, at: event.at, until: event.payload?.until }])
81
82
  } catch {
82
83
  // A torn line is skipped.
83
84
  }
package/src/routes.js CHANGED
@@ -19,6 +19,7 @@
19
19
  import { readFile } from 'node:fs/promises'
20
20
  import { extname } from 'node:path'
21
21
  import { viewerOf } from './access.js'
22
+ import { EMITTING } from './actions.js'
22
23
  import { PERSON_PATTERN, RECORD_ID_PATTERN } from './store.js'
23
24
 
24
25
  export const PREFIX = '/api/notify-inbox'
@@ -144,7 +145,7 @@ export function createRoutes({ store, people, push, actions, identity, serviceWo
144
145
  if (record === undefined) return json(404, { error: 'No such notification.' })
145
146
  const declared = record.actions.find(row => row.id === value.action)
146
147
  if (declared === undefined) return json(400, { error: 'This notification has no such button.' })
147
- if (!['done', 'snooze', 'event'].includes(declared.kind)) return json(400, { error: 'This button acts in the page.' })
148
+ if (!EMITTING.includes(declared.kind)) return json(400, { error: 'This button acts in the page.' })
148
149
  const result = await actions.press(record.person, record, declared, { until: value.until })
149
150
  await store.setRead(record.person, [record.id], true)
150
151
  return json(200, { press: result.event.press, published: result.published, matched: result.matched ?? 0 })
package/src/store.js CHANGED
@@ -21,6 +21,8 @@ const READ = 'read.json'
21
21
 
22
22
  const text = value => (typeof value === 'string' ? value : '')
23
23
  const list = value => (Array.isArray(value) ? value : [])
24
+ /** Text a person reads: a string, or a map from language tag to text (the page picks the language). */
25
+ const words = value => (typeof value === 'string' ? value : value !== null && typeof value === 'object' && !Array.isArray(value) && Object.values(value).every(v => typeof v === 'string') ? value : '')
24
26
 
25
27
  /** A record as the page gets it, or undefined when the line is not one. */
26
28
  export function normalize(raw, person) {
@@ -48,7 +50,7 @@ export function normalize(raw, person) {
48
50
  actions: list(raw.actions).filter(action => typeof action?.kind === 'string' && typeof action?.id === 'string').map(action => ({
49
51
  kind: action.kind,
50
52
  id: action.id,
51
- label: text(action.label) || undefined,
53
+ label: words(action.label) || undefined,
52
54
  payload: typeof action.payload === 'object' && action.payload !== null && !Array.isArray(action.payload) ? action.payload : {},
53
55
  })),
54
56
  test: raw.test === true,
package/client.actions.js DELETED
@@ -1,234 +0,0 @@
1
- /*
2
- * Action buttons for DSH Web UI plugins: chat, done, snooze, event and link,
3
- * the same look and behaviour wherever an item offers them.
4
- *
5
- * A DSH client chunk: dsh-card-board's client loads it with
6
- * `require.async('./client.actions.js')`. Another plugin can ship a copy as
7
- * its own `client.actions.js`, changing OWNER below to its package name.
8
- *
9
- * DSH runs a chunk as a classic script, so everything sits inside one function
10
- * (a top-level `const` would clash with another plugin's copy and the second
11
- * chunk would never register).
12
- *
13
- * const { createActions } = await require.async('./client.actions.js')
14
- * const ui = createActions({ React, ctx, t, press })
15
- * h(ui.ActionBar, { actions, states, chat, onPress })
16
- *
17
- * `t(key, params)` gives the words in the person's language; the host plugin
18
- * keeps them in its one message table. The keys it must know are exported as
19
- * `KEYS`: chat, chatAbout, done, snooze, event, link, in3h, tomorrow, pick,
20
- * set, cancel, sending, pending, handled, unhandled, failed ({message}),
21
- * noWorkspace. `t` is called while rendering, so a language switch shows up
22
- * without building the buttons again.
23
- *
24
- * `press(action, extra)` is the plugin's own server call for done, snooze and
25
- * event (extra carries `until` for a snooze); it should resolve once the
26
- * server has accepted the press. `chat` and `link` never reach the server:
27
- * chat opens a conversation with a prefilled, editable draft through the Web
28
- * UI's own workspace service (so the person sends it themselves, signed in as
29
- * themselves), and link opens the URL.
30
- */
31
- (() => {
32
- const OWNER = '@soffits/dsh-notify-inbox'
33
-
34
- const KEYS = ['chat', 'chatAbout', 'done', 'snooze', 'event', 'link', 'in3h', 'tomorrow', 'pick', 'set', 'cancel', 'sending', 'pending', 'handled', 'unhandled', 'failed', 'noWorkspace']
35
-
36
- const CSS = `
37
- .ua-bar{display:flex;flex-wrap:wrap;gap:6px;align-items:center;min-width:0}
38
- .ua-btn{box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;gap:6px;min-height:32px;max-width:100%;padding:0 12px;border:0;border-radius:8px;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:12px;line-height:18px;cursor:pointer;text-decoration:none;box-shadow:inset 0 0 0 .5px var(--dsw-alias-border-l3)}
39
- .ua-btn span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
40
- .ua-btn svg{flex:none;width:14px;height:14px}
41
- .ua-btn:disabled{cursor:default;opacity:.7}
42
- @media (hover:hover){.ua-btn:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}}
43
- .ua-icon{width:32px;padding:0;box-shadow:none;color:var(--dsw-alias-label-tertiary)}
44
- .ua-btn[data-state=pending] svg,.ua-btn[data-state=sending] svg{animation:ua-pulse 1.2s ease-in-out infinite}
45
- .ua-btn[data-state=done]{color:var(--dsw-alias-state-success-primary)}
46
- .ua-btn[data-state=unhandled]{color:var(--dsw-alias-state-warn-label,var(--dsw-alias-state-warn-primary))}
47
- @keyframes ua-pulse{50%{opacity:.35}}
48
- .ua-wrap{position:relative;display:inline-flex;max-width:100%;flex-wrap:wrap;align-items:center;gap:4px 8px}
49
- .ua-menu{position:absolute;z-index:20;top:calc(100% + 4px);right:0;min-width:168px;padding:4px;border-radius:12px;background:var(--dsw-alias-bg-layer-2,var(--dsw-alias-bg-base));box-shadow:0 6px 24px #0000001f,inset 0 0 0 .5px var(--dsw-alias-border-l2);display:flex;flex-direction:column}
50
- .ua-menu button{display:flex;align-items:center;gap:8px;min-height:36px;padding:7px 10px;border:0;border-radius:8px;background:none;color:var(--dsw-alias-label-primary);font:inherit;font-size:13px;text-align:left;cursor:pointer}
51
- @media (hover:hover){.ua-menu button:hover{background:var(--dsw-alias-interactive-bg-hover)}}
52
- .ua-menu input{margin:4px 6px;min-height:36px;padding:6px 8px;border:.5px solid var(--dsw-alias-border-l3);border-radius:8px;background:transparent;color:inherit;font:inherit;font-size:16px}
53
- .ua-menuRow{display:flex;justify-content:flex-end;gap:4px;padding:2px 4px}
54
- .ua-error{flex-basis:100%;color:var(--dsw-alias-state-error-primary);font-size:12px;overflow-wrap:anywhere}
55
- @media (width<=768px),(pointer:coarse){
56
- .ua-btn{min-height:40px}
57
- .ua-icon{width:40px}
58
- .ua-menu{position:fixed;z-index:1000;top:auto;left:12px;right:12px;bottom:12px;max-height:60vh;overflow:auto;padding:8px;box-shadow:0 8px 40px #00000040,inset 0 0 0 .5px var(--dsw-alias-border-l2)}
59
- .ua-menu button{min-height:44px;font-size:15px}
60
- .ua-menu input{min-height:44px}
61
- }
62
- `
63
-
64
- const ICONS = {
65
- chat: 'M3 4.5A1.5 1.5 0 0 1 4.5 3h7A1.5 1.5 0 0 1 13 4.5v5A1.5 1.5 0 0 1 11.5 11H7l-3 2.5V11h.5A1.5 1.5 0 0 1 3 9.5z',
66
- done: 'M3.5 8.5l3 3 6-7',
67
- snooze: 'M8 4.5V8l2.2 1.4M13.5 8a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z',
68
- event: 'M8.8 2.5 4 9h4l-.8 4.5L12 7H8z',
69
- link: 'M6 3.5H3.5v9h9V10M9 3h4v4M13 3 7.5 8.5',
70
- pending: 'M8 8m-2 0a2 2 0 1 0 4 0a2 2 0 1 0-4 0',
71
- unhandled: 'M8 3.5v5.5M8 12v.5',
72
- }
73
-
74
- /** The next 09:00 after now, as an ISO string. */
75
- function tomorrowMorning(now = new Date()) {
76
- const date = new Date(now)
77
- date.setDate(date.getDate() + 1)
78
- date.setHours(9, 0, 0, 0)
79
- return date.toISOString()
80
- }
81
-
82
- /**
83
- * The draft for a chat about an item: the person's question goes first (a
84
- * prompt from the data, or nothing yet), then the item quoted, then its
85
- * context as JSON for the agent.
86
- */
87
- function chatText({ prompt = '', title, lines = [], context }) {
88
- const quote = [title ? `**${title}**` : null, ...lines].filter(Boolean).map(line => `> ${line}`).join('\n')
89
- const parts = [prompt, quote]
90
- if (context !== undefined) parts.push(`\`\`\`json\n${JSON.stringify(context, null, 2)}\n\`\`\``)
91
- return `${parts.filter(Boolean).join('\n\n')}\n`
92
- }
93
-
94
- /**
95
- * @param {object} options
96
- * @param {object} options.React - the page's React
97
- * @param {object} options.ctx - the plugin's client context (ctx.get reaches the Web UI's services)
98
- * @param {(key: string, params?: object) => string} options.t - the words in the person's language, one of KEYS
99
- * @param {(action: object, extra: object) => Promise<unknown>} [options.press] - the server call for done, snooze and event
100
- */
101
- function createActions({ React, ctx, t, press }) {
102
- const h = React.createElement
103
- const { useState, useEffect, useRef } = React
104
-
105
- if (typeof document !== 'undefined' && !document.getElementById('dsh-actions-ui-style')) {
106
- const style = document.createElement('style')
107
- style.id = 'dsh-actions-ui-style'
108
- style.dataset.plugin = OWNER
109
- style.textContent = CSS
110
- document.head.appendChild(style)
111
- }
112
-
113
- function Icon({ name }) {
114
- return h('svg', { viewBox: '0 0 16 16', fill: 'none', stroke: 'currentColor', strokeWidth: 1.4, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true }, h('path', { d: ICONS[name] ?? ICONS.event }))
115
- }
116
-
117
- /**
118
- * Open a conversation with `text` as its editable draft: a new one in the
119
- * current (or most recent) workspace, or the given session.
120
- */
121
- async function startChat({ text, session }) {
122
- const workspace = ctx.get('uiWorkspace')
123
- if (workspace === undefined) throw new Error(t('noWorkspace'))
124
- if (session === undefined || session === 'new') {
125
- workspace.startSession(undefined, { prompt: text, whenDraftExists: 'replace' })
126
- return
127
- }
128
- workspace.openSession(session)
129
- const sessions = ctx.get('sessions')
130
- const conversation = ctx.get('conversation')
131
- for (let i = 0; i < 30 && sessions && conversation; i += 1) {
132
- const binding = sessions.binding(session)
133
- if (binding !== undefined) {
134
- try {
135
- conversation.input.requestDraftInitialization(binding, { prompt: text, whenDraftExists: 'append' })
136
- } catch {
137
- // the session moved on before the draft landed; it is open, the person can type
138
- }
139
- return
140
- }
141
- await new Promise(resolve => setTimeout(resolve, 100))
142
- }
143
- }
144
-
145
- function SnoozeMenu({ onPick, onClose }) {
146
- const [picking, setPicking] = useState(false)
147
- const [value, setValue] = useState('')
148
- const ref = useRef(null)
149
- useEffect(() => {
150
- const away = event => { if (ref.current && !ref.current.contains(event.target)) onClose() }
151
- const escape = event => { if (event.key === 'Escape') onClose() }
152
- document.addEventListener('pointerdown', away)
153
- document.addEventListener('keydown', escape)
154
- return () => { document.removeEventListener('pointerdown', away); document.removeEventListener('keydown', escape) }
155
- }, [onClose])
156
- return h('div', { className: 'ua-menu', ref, role: 'menu' },
157
- !picking && h('button', { type: 'button', role: 'menuitem', onClick: () => onPick(new Date(Date.now() + 3 * 3600 * 1000).toISOString()) }, t('in3h')),
158
- !picking && h('button', { type: 'button', role: 'menuitem', onClick: () => onPick(tomorrowMorning()) }, t('tomorrow')),
159
- !picking && h('button', { type: 'button', role: 'menuitem', onClick: () => setPicking(true) }, t('pick')),
160
- picking && h('input', { type: 'datetime-local', value, autoFocus: true, onChange: event => setValue(event.target.value) }),
161
- picking && h('div', { className: 'ua-menuRow' },
162
- h('button', { type: 'button', onClick: onClose }, t('cancel')),
163
- h('button', { type: 'button', disabled: value === '', onClick: () => onPick(new Date(value).toISOString()) }, t('set'))))
164
- }
165
-
166
- /**
167
- * One action as a button. `state` is the server's view of the last press
168
- * (pending, done, unhandled); `compact` draws an icon only.
169
- */
170
- function ActionButton({ action, state, compact, chat, onPress }) {
171
- const [local, setLocal] = useState(null)
172
- const [error, setError] = useState(null)
173
- const [menu, setMenu] = useState(false)
174
- useEffect(() => { if (state) setLocal(null) }, [state])
175
- const shown = local ?? state
176
- const label = action.label ?? t(action.kind)
177
- const title = shown === 'sending' ? t('sending') : shown === 'pending' ? t('pending') : shown === 'done' ? t('handled') : shown === 'unhandled' ? t('unhandled') : error ?? label
178
- const icon = shown === 'done' ? 'done' : shown === 'unhandled' ? 'unhandled' : action.kind
179
- const className = `ua-btn${compact ? ' ua-icon' : ''}`
180
- const content = [h(Icon, { key: 'i', name: icon }), !compact && h('span', { key: 'l' }, label)]
181
-
182
- if (action.kind === 'link') {
183
- const url = action.payload?.url
184
- const external = /^https?:/i.test(url ?? '')
185
- return h('a', { className, href: url, title: label, 'aria-label': label, ...(external ? { target: '_blank', rel: 'noopener noreferrer' } : {}) }, content)
186
- }
187
- const send = async extra => {
188
- setMenu(false)
189
- setError(null)
190
- setLocal('sending')
191
- try {
192
- if (action.kind === 'chat') {
193
- await chat(action)
194
- setLocal(null)
195
- } else {
196
- await (onPress ?? press)(action, extra ?? {})
197
- setLocal('pending')
198
- }
199
- } catch (reason) {
200
- setLocal(null)
201
- setError(t('failed', { message: reason?.message ?? String(reason) }))
202
- }
203
- }
204
- const onClick = () => {
205
- if (action.kind === 'snooze' && action.payload?.until === undefined) setMenu(open => !open)
206
- else send()
207
- }
208
- const busy = shown === 'sending' || shown === 'pending'
209
- return h('span', { className: 'ua-wrap' },
210
- h('button', { type: 'button', className, title, 'aria-label': `${label}${title !== label ? ` (${title})` : ''}`, 'data-state': shown ?? undefined, disabled: busy, onClick }, content),
211
- menu && h(SnoozeMenu, { onPick: until => send({ until }), onClose: () => setMenu(false) }),
212
- error && !compact && h('span', { className: 'ua-error', role: 'alert' }, error))
213
- }
214
-
215
- /**
216
- * A row of action buttons.
217
- * @param {object} props
218
- * @param {object[]} props.actions - the item's actions, as the data declares them
219
- * @param {Record<string, string>} [props.states] - press state by action id
220
- * @param {boolean} [props.compact] - icons only (for rows)
221
- * @param {(action: object) => Promise<void>} props.chat - opens the chat for a chat action
222
- * @param {(action: object, extra: object) => Promise<unknown>} [props.onPress] - this bar's press call, instead of the one given to createActions
223
- */
224
- function ActionBar({ actions, states = {}, compact = false, chat, onPress }) {
225
- if (!actions || actions.length === 0) return null
226
- return h('div', { className: 'ua-bar' }, actions.map(action =>
227
- h(ActionButton, { key: action.id, action, state: states[action.id], compact, chat, onPress })))
228
- }
229
-
230
- return { ActionBar, ActionButton, Icon, startChat, chatText, t }
231
- }
232
-
233
- window.__ModuleLoader__.load({ id: OWNER, chunk: 'client.actions.js', factory: () => ({ createActions, chatText, KEYS }) })
234
- })()