@soffits/dsh-notify-inbox 0.5.0 → 0.7.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,21 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.0
4
+
5
+ - A reply is sent by the server: `POST /api/notify-inbox/reply` checks the item is yours and steers the session that asked, as you, with the ask quoted in. Before, the page sent it through the browser, which could stall on a long conversation and never arrive.
6
+ - The page's words are read from the language files for each request and never cached, so an update in place can't leave the page showing raw keys.
7
+
8
+ ## 0.6.1
9
+
10
+ - The reply box has a visible border (it used a colour token DSH doesn't define).
11
+
12
+ ## 0.6.0
13
+
14
+ - Asks: whatever keeps the person's list of open asks (a Todo) writes them to `<person>/asks.json`, and with that file there it alone decides **Needs you**. Each open ask is one item, with the notifications of its thread folded in; one that left the file shows as Handled ("Settled"). An ask's `points` show beside its title, and its own buttons, title and session win over its notifications'.
15
+ - Reply where you read: an ask (or a notification with `session`) has a reply box that sends your answer into the session that asked, as you, through `@soffits/dsh-ui-actions`' `start`, with the ask quoted in.
16
+ - **Breaking:** a new group **Urgent** on top: interrupts default to it (done and snooze move them on as before). `needs-you` is no longer a default for interrupts or for notifications with done or snooze buttons; it is for asks.
17
+ - No polling: the plugin watches the folders (`fs.watch`) for the page's change notices and pushes new records the moment the inbox file changes, and the Web UI follows the events stream for its counts instead of a timer. The `pollSeconds` option is gone (an old value is ignored).
18
+
3
19
  ## 0.5.0
4
20
 
5
21
  - A new page, built from DSH's own components and the shared [@soffits/dsh-ui-kit](https://github.com/soffits/dsh-ui-kit), which is now required. Notifications are grouped as Needs you, Live, Handled and To know, with the counts on top, an optional summary line (`summary.json`) and each domain's icon on a tinted tile (`domains` setting). [docs/ui.md](docs/ui.md) lists what is DSH's and what is the plugin's own.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  A notification inbox for [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (DSH). Something outside DSH (a notification router, a cron script, a watcher) files notifications as JSON lines, one folder per person. The plugin shows each signed-in person their own inbox in the Web UI, keeps read and unread per person on the server, pushes new ones to the browsers and installed home-screen apps they turned notifications on for, and gives every notification buttons: ask the agent about it, mark it done, remind me later.
4
4
 
5
- The page sorts notifications by what they ask of you: **Needs you**, **Live** (a flight's status, a running job, updated in place), **Handled** (what was done for you, in one quiet line) and **To know**. Notifications about one thing fold into one item with its history underneath, new ones appear while the page is open, and an optional line at the top says what matters now. It is built from DSH's own components, so it looks like the rest of the Web UI in light and dark ([docs/ui.md](docs/ui.md) says which few pieces aren't DSH's, and why).
5
+ The page sorts notifications by what they ask of you: **Urgent** (a leak, a door left open: on top until you deal with it), **Needs you** (what waits on your answer, which you can reply to right there), **Live** (a flight's status, a running job, updated in place), **Handled** (what was done for you, in one quiet line) and **To know**. Notifications about one thing fold into one item with its history underneath, new ones appear while the page is open, and an optional line at the top says what matters now. It is built from DSH's own components, so it looks like the rest of the Web UI in light and dark ([docs/ui.md](docs/ui.md) says which few pieces aren't DSH's, and why).
6
6
 
7
7
  The contract is files, so nothing gets lost while DSH restarts: the writer keeps appending, and the plugin pushes whatever arrived once it's back.
8
8
 
@@ -41,7 +41,6 @@ Restart `dsh web`. The inbox appears in the sidebar. Then set `dataDir` in a pro
41
41
  | `vapidSubject` | `mailto:admin@example.invalid` | A contact push services can reach. Set your own. |
42
42
  | `domains` | `{}` | How each `domain` is drawn, on top of the built-in defaults (`mail`, `money`, `health`, `travel`, `home`, `orders`...): `{ "legal": { "icon": "scale", "tone": "violet" } }`. `icon` is a [Lucide](https://lucide.dev) name the kit bundles; `tone` (`ok`, `warn`, `bad`, `accent`, `violet`, `muted`) is usually left out, since an item's colour says what it needs. |
43
43
  | `summaryHours` | `12` | How long the summary line is shown after it was written. |
44
- | `pollSeconds` | `5` | How often new lines are looked for (to push them). |
45
44
 
46
45
  **Who sees what.** With a mapping, every request is checked on the server: a person sees, marks and presses only their own inbox, and a request without a verified identity sees nothing. The identity comes from any plugin that provides a `requestIdentity` service (`current()` → `{ provider, issuer, id, name } | null`), such as [dsh-oidc](https://github.com/soffits/dsh-oidc) 0.3.0-alpha.9 or later. Without a mapping (a DSH only you use), you see every folder.
47
46
 
@@ -61,19 +60,39 @@ Append one JSON object per line to `<dataDir>/<person>/inbox.jsonl` (person ids
61
60
  {"destination": "phone", "type": "ntfy", "ok": false, "detail": "timed out"}]}
62
61
  ```
63
62
 
64
- - `id` (required, unique), `time` (required, ISO 8601). `lane: "interrupt"` makes it urgent (it needs you, a red tile, high push urgency).
63
+ - `id` (required, unique), `time` (required, ISO 8601). `lane: "interrupt"` makes it urgent (on top, a red tile, high push urgency).
65
64
  - `title`, `spoken` (one short line: the push body), `text` (the full text), `links` (http/https).
66
65
  - `files`: attachments the writer copied to `<dataDir>/<person>/files/<id>/<name>`; only those are served, and only to that person.
67
66
  - `push: false` files it without a push. `test: true` labels it as a test.
68
67
  - `routed`: where else the notification went and whether that worked; shown under the text.
69
68
  - `actions`: buttons, see below.
70
- - `attention`: the group, `needs-you`, `live`, `handled` or `info` ("To know"). Left out, it follows from the rest: `handled` when `handled` is set, `live` when `live` is, `needs-you` for an interrupt or a notification with `done` or `snooze` buttons, else `info`. A needs-you item the person marked done moves to Handled, a snoozed one waits under To know until it comes back.
69
+ - `attention`: the group, `urgent`, `needs-you`, `live`, `handled` or `info` ("To know"). Left out, it follows from the rest: `handled` when `handled` is set, `live` when `live` is, `urgent` for an interrupt, else `info`. An urgent item the person marked done moves to Handled, a snoozed one waits under To know until it comes back. `needs-you` is for asks (below).
70
+ - `session`: the session that asked, for a notification that waits on the person's answer; the item then has a reply box (below).
71
71
  - `thread`: notifications with the same thread are one item, the newest on top and the older ones as its history (three reminders about one task).
72
72
  - `live`: `{ "until"?, "progress"?: { "from", "to" } }`. The thread's newest notification replaces the item in place, shown as live until `until` (or six hours after its last update), with a bar from `from` to `to`.
73
73
  - `handled`: `{ "text", "at"? }`, what was done for the person, shown as one quiet line with a check.
74
74
 
75
75
  An optional `<dataDir>/<person>/summary.json`, `{ "text": "...", "at": "<ISO time>" }`, is the sentence shown above the items for `summaryHours`.
76
76
 
77
+ ## Asks
78
+
79
+ What waits on the person's answer (a decision, a pick, a small step for someone else's work) usually lives in a list of their own, such as a Todo. Whatever keeps that list writes the open ones to `<dataDir>/<person>/asks.json` each time it changes; with that file there, it alone says what shows under **Needs you**:
80
+
81
+ ```json
82
+ {"v": 1, "asks": [
83
+ {"id": "todo:1a2b3c4d", "title": "Pick the lamp", "text": "White or oak? The white one is 39.", "time": "2026-11-17T15:50:12Z",
84
+ "next": "2026-11-18", "due": "2026-11-20", "points": 3, "session": "<session id>", "domain": "todo",
85
+ "actions": [{"kind": "done", "id": "done", "payload": {"source": "todo", "uuid": "1a2b..."}, "inverse": {"kind": "reopen", "payload": {}}},
86
+ {"kind": "snooze", "id": "snooze", "payload": {"source": "todo", "uuid": "1a2b..."}}]}]}
87
+ ```
88
+
89
+ - Each open ask is one item, whether or not a notification was ever filed about it. Notifications whose `thread` is the ask's `id` fold into it, and the ask's own buttons, title and `session` win. When the ask leaves the file it was settled where it lives: its notifications show as Handled ("Settled").
90
+ - `points` (shown as a small "+3" beside the title) is what dealing with it earns where the list keeps such a game; leave it out otherwise. `next` and `due` are days.
91
+ - With a `session`, the opened item has a reply box. `POST /api/notify-inbox/reply` (`{ record, text }`) checks the item is the caller's, then puts the words, with the ask quoted in, into that session through DSH's own steering (a running session sees them at its next step, an idle or stored one starts a turn), sent as the verified person (their sign-in's principal) or as the owner without a mapping; the conversation that asked carries on with the answer, and the page offers to open it. A finished helper (subagent) session can't take a reply.
92
+ - An ask that is a question lists its `options`; the writer gives each its own button (a `done` whose payload carries the answer), so a press answers it. One that is a task has a plain done.
93
+ - A press on an ask's buttons is an action event like any other (`source.record` is the ask's id), for whatever keeps the list to act on.
94
+ - Without `asks.json` nothing changes: notifications keep the group they were filed with.
95
+
77
96
  A line `{"v": 1, "type": "handled", "record": "<id>", "press": "<press id>", "action": "done", "result": "done", "time": "..."}` tells the inbox that a press on that record was dealt with (`result: "snoozed"` with `until` shows when it comes back). Bad lines are skipped and counted.
78
97
 
79
98
  ## Buttons
@@ -104,7 +123,7 @@ Tapping a notification opens the inbox on it. A device whose subscription expire
104
123
 
105
124
  ## Live updates
106
125
 
107
- An open page follows `GET /api/notify-inbox/events`, a Server-Sent Events stream that says when the caller's inbox changed (records, read marks, presses or the summary), and fetches again; it polls while the stream is down. While anyone listens the plugin looks at those files every two seconds; nothing runs otherwise.
126
+ An open Web UI follows `GET /api/notify-inbox/events`, a Server-Sent Events stream that says when the caller's inbox changed (records, read marks, presses, the summary or the asks), and fetches again; the browser reconnects by itself when the stream drops. The plugin watches the data folder and each person's folder (`fs.watch`), so a change is noticed when the file changes, and new records are pushed the same moment; nothing polls. The data folder must be on a local file system for that (a network share may not report changes).
108
127
 
109
128
  ## Languages
110
129
 
package/client.js CHANGED
@@ -10,13 +10,19 @@
10
10
  * (ctx.uiActions); the little CSS of its own is in docs/ui.md, with why.
11
11
  * Everything the page shows comes from the plugin's /api/notify-inbox routes,
12
12
  * which decide per request who is asking. A link with ?notify-inbox=<id>
13
- * opens the page on that notification.
13
+ * opens the page on that notification. Counts follow the plugin's events
14
+ * stream (the inbox files' own changes), never a timer.
15
+ *
16
+ * An ask (a notification that waits on the person's answer, or an open ask
17
+ * from their list) shows its points and, when it names the session that
18
+ * asked, a reply box: the server puts the reply into that session as the
19
+ * person, with the ask quoted in.
14
20
  */
15
21
  window.__ModuleLoader__.load({
16
22
  id: '@soffits/dsh-notify-inbox',
17
23
  factory(require) {
18
24
  const React = require('react')
19
- const { Button, Pill, Menu, Tooltip, StateDot, IconCheckCircleOutlineRegular, IconEllipsisOutlineRegular } = require('@deepseek-ai/dsh-client-ui-primitives')
25
+ const { Button, Pill, Menu, Tooltip, StateDot, IconCheckCircleOutlineRegular, IconEllipsisOutlineRegular, IconSendOutlineRegular } = require('@deepseek-ai/dsh-client-ui-primitives')
20
26
  const h = React.createElement
21
27
  const { useState, useEffect, useCallback, useRef, useSyncExternalStore } = React
22
28
 
@@ -26,10 +32,10 @@ window.__ModuleLoader__.load({
26
32
  const LINK_PARAM = 'notify-inbox'
27
33
  const STYLE_ID = 'dsh-notify-inbox-style'
28
34
  const PENDING_MS = 2 * 60 * 1000
29
- const GROUPS = ['needs-you', 'live', 'handled', 'info']
35
+ const GROUPS = ['urgent', 'needs-you', 'live', 'handled', 'info']
30
36
  /** The colour an item's tile takes from what it needs, unless its domain names one. */
31
- const GROUP_TONE = { 'needs-you': 'accent', live: 'accent', handled: 'ok', info: 'muted' }
32
- const GROUP_ICON = { 'needs-you': 'circle-alert', live: 'activity', handled: 'circle-check', info: 'info' }
37
+ const GROUP_TONE = { urgent: 'bad', 'needs-you': 'accent', live: 'accent', handled: 'ok', info: 'muted' }
38
+ const GROUP_ICON = { urgent: 'triangle-alert', 'needs-you': 'circle-help', live: 'activity', handled: 'circle-check', info: 'info' }
33
39
  const api = path => new URL(`api/notify-inbox/${path}`, document.baseURI).href
34
40
 
35
41
  // Only what DSH's components don't cover: the page frame and row layout mirror DSH's own pages
@@ -48,6 +54,7 @@ window.__ModuleLoader__.load({
48
54
  .nib-counts>*+*::before{content:'·';padding:0 6px}
49
55
  .nib-counts b{font-weight:500;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums}
50
56
  .nib-counts b[data-group=needs-you]{color:var(--dsw-alias-state-business-primary)}
57
+ .nib-counts b[data-group=urgent]{color:var(--dsw-alias-state-error-primary)}
51
58
  .nib-filters{display:flex;flex-wrap:wrap;gap:8px;margin-bottom:20px}
52
59
  .nib-n{font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-tertiary)}
53
60
  .nib-group{display:flex;flex-direction:column;gap:4px;margin-bottom:24px}
@@ -63,7 +70,11 @@ window.__ModuleLoader__.load({
63
70
  .nib-titleLine{display:flex;align-items:flex-start;gap:8px;min-width:0;padding-top:4px}
64
71
  .nib-titleLine>.uk-newDot{margin-top:8px}
65
72
  .nib-title{flex:1;min-width:0;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;line-height:23px;overflow-wrap:anywhere;color:var(--dsw-alias-label-secondary)}
66
- .nib-unread .nib-title,.nib-group[data-group=needs-you] .nib-title,.nib-group[data-group=live] .nib-title{font-weight:500;color:var(--dsw-alias-label-primary)}
73
+ .nib-unread .nib-title,.nib-group[data-group=urgent] .nib-title,.nib-group[data-group=needs-you] .nib-title,.nib-group[data-group=live] .nib-title{font-weight:500;color:var(--dsw-alias-label-primary)}
74
+ .nib-points{flex:none;align-self:center;padding:0 6px;border-radius:9px;font-size:12px;line-height:18px;font-weight:500;font-variant-numeric:tabular-nums;color:var(--dsw-alias-state-business-primary);background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 12%,transparent)}
75
+ .nib-reply{display:flex;flex-direction:column;gap:6px;max-width:640px}
76
+ .nib-reply textarea{box-sizing:border-box;width:100%;min-height:64px;padding:8px 10px;border:1px solid var(--dsw-alias-border-l2);border-radius:10px;background:var(--dsw-alias-bg-base);color:inherit;font:inherit;resize:vertical}
77
+ .nib-replyBar{display:flex;flex-wrap:wrap;align-items:center;gap:8px}
67
78
  .nib-open .nib-title{-webkit-line-clamp:unset}
68
79
  .nib-when{flex:none;display:inline-flex;align-items:center;gap:6px;font-size:12px;line-height:23px;color:var(--dsw-alias-label-caption)}
69
80
  .nib-sub{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;font-size:13px;line-height:21px;color:var(--dsw-alias-label-tertiary);overflow-wrap:anywhere}
@@ -89,7 +100,7 @@ window.__ModuleLoader__.load({
89
100
 
90
101
  // ---- shared state: the counts and a version that bumps when anything changes ----
91
102
 
92
- const shared = { unread: 0, version: 0, pollSeconds: 30, linked: null, ui: null, kit: null, summary: null }
103
+ const shared = { unread: 0, version: 0, linked: null, ui: null, kit: null, summary: null, openSession: () => {} }
93
104
  const listeners = new Set()
94
105
  const emit = () => { for (const listener of listeners) listener() }
95
106
  const subscribe = listener => { listeners.add(listener); return () => listeners.delete(listener) }
@@ -109,7 +120,6 @@ window.__ModuleLoader__.load({
109
120
  async function refreshSummary() {
110
121
  try {
111
122
  const summary = await call('summary')
112
- shared.pollSeconds = summary.pollSeconds || 30
113
123
  const key = JSON.stringify([summary.unread, summary.latest, summary.total, summary.groups, summary.line])
114
124
  if (key !== lastSummary) {
115
125
  lastSummary = key
@@ -119,7 +129,7 @@ window.__ModuleLoader__.load({
119
129
  emit()
120
130
  }
121
131
  } catch {
122
- // Signed out or DSH restarting; try again at the next tick.
132
+ // Signed out or DSH restarting; the stream's next notice (or the page coming back) tries again.
123
133
  }
124
134
  }
125
135
  const changed = () => { lastSummary = ''; refreshSummary() }
@@ -159,18 +169,52 @@ window.__ModuleLoader__.load({
159
169
  source: OWNER,
160
170
  title: item.title || item.spoken || item.text,
161
171
  lines: [item.title && item.spoken !== item.title ? item.spoken : '', ...(item.text || '').split('\n'), ...item.links].filter(line => line && line !== item.title),
162
- context: { notification: item.id, time: item.time, lane: item.lane, domain: item.domain || undefined, thread: item.thread || undefined },
172
+ context: { notification: item.id, time: item.time, lane: item.lane, domain: item.domain || undefined, thread: item.thread || undefined, ask: item.ask?.id },
163
173
  })
164
174
 
175
+ /** A reply to an ask, sent into the session that asked as the person, with the ask quoted in. */
176
+ function Reply({ item, t, onSent }) {
177
+ const [text, setText] = useState('')
178
+ const [state, setState] = useState({ phase: 'idle' })
179
+ const send = async () => {
180
+ const words = text.trim()
181
+ if (words === '' || state.phase === 'sending') return
182
+ setState({ phase: 'sending' })
183
+ try {
184
+ const sent = await call('reply', { record: item.id, text: words })
185
+ setText('')
186
+ setState({ phase: 'sent', session: sent.session })
187
+ onSent()
188
+ } catch (reason) {
189
+ setState({ phase: 'failed', message: reason.message })
190
+ }
191
+ }
192
+ return h('div', { className: 'nib-reply' },
193
+ h('textarea', {
194
+ value: text,
195
+ rows: 2,
196
+ placeholder: t('reply.placeholder'),
197
+ 'aria-label': t('reply.label'),
198
+ onChange: event => setText(event.target.value),
199
+ onKeyDown: event => { if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) send() },
200
+ }),
201
+ h('div', { className: 'nib-replyBar' },
202
+ h(Button, { variant: 'outline', size: 'sm', disabled: text.trim() === '' || state.phase === 'sending', onClick: send },
203
+ h(IconSendOutlineRegular, null), ' ', t(state.phase === 'sending' ? 'reply.sending' : 'reply.send')),
204
+ state.phase === 'sent' && h('span', { className: 'nib-meta' }, t('reply.sent'), ' ',
205
+ h(Button, { variant: 'outline', size: 'sm', onClick: () => shared.openSession(state.session) }, t('reply.open'))),
206
+ state.phase === 'failed' && h('span', { className: 'nib-meta nib-bad', role: 'alert' }, t('reply.failed', { message: state.message }))))
207
+ }
208
+
165
209
  // ---- one item ----
166
210
 
167
211
  function Item({ item, group, kit, ui, t, domains, open, onToggle, onMark }) {
168
212
  const wash = kit.useWash(item.id, item.key)
169
213
  const domain = domains[item.domain] ?? {}
170
- const tone = domain.tone ?? (group === 'needs-you' && item.lane === 'interrupt' ? 'bad' : GROUP_TONE[group])
214
+ const tone = domain.tone ?? GROUP_TONE[group]
171
215
  const title = item.title || item.spoken || item.text.slice(0, 80)
172
216
  const sub = item.spoken && item.spoken !== title ? item.spoken : item.text !== title ? item.text : ''
173
- const doneText = item.handled?.text ?? (item.moved === 'done' ? t('moved.done') : null)
217
+ const doneText = item.handled?.text ?? (item.moved === 'done' ? t('moved.done') : item.moved === 'closed' ? t('moved.closed') : null)
174
218
  const status = item.moved === 'snoozed' ? pressStatus(item, t) : item.moved === 'ended' ? t('moved.ended') : null
175
219
  const history = !item.liveNow && item.history.length > 0 && item.history.map(row => ({ at: row.time, text: said(row.spoken, t) || said(row.title, t) }))
176
220
  const onPress = async (action, extra) => {
@@ -186,6 +230,7 @@ window.__ModuleLoader__.load({
186
230
  h('span', { className: 'nib-titleLine' },
187
231
  !item.read && h(kit.NewDot),
188
232
  h('span', { className: 'nib-title' }, title),
233
+ group === 'needs-you' && item.ask?.points && h('span', { className: 'nib-points' }, t('points', { n: item.ask.points })),
189
234
  h('span', { className: 'nib-when' },
190
235
  item.liveNow && h(StateDot, { state: 'done' }),
191
236
  h(kit.TimeAgo, { at: item.time }))),
@@ -214,6 +259,7 @@ window.__ModuleLoader__.load({
214
259
  ui !== null && h(ui.ActionBar, { actions: item.actions, states, about, defaultChat: true, part: 'buttons', onPress }),
215
260
  item.read && h(Button, { variant: 'outline', size: 'sm', onClick: () => onMark(item, false) }, t('markUnread')),
216
261
  status && h('span', { className: 'nib-meta' }, status)),
262
+ item.group === 'needs-you' && item.session && h(Reply, { item, t, onSent: () => { if (!item.read) onMark(item, true) } }),
217
263
  h(kit.Suggested, { actions: item.actions, about, states, onPress }),
218
264
  h('div', { className: 'nib-meta' },
219
265
  item.routed.length === 0 ? t('notSent') : h(React.Fragment, null, `${t('alsoSent')}: `,
@@ -517,19 +563,25 @@ window.__ModuleLoader__.load({
517
563
  label: () => t('panel'),
518
564
  }, SidebarIcon))
519
565
 
520
- // The counts: checked while the page is visible, right away when it becomes visible, and at
521
- // once when the events stream says something changed.
566
+ shared.openSession = id => ctx.get('uiWorkspace')?.openSession(id)
567
+
568
+ // The counts: read when the app shows, and again whenever the events stream says the inbox
569
+ // changed (the stream is open while the app is visible; EventSource reconnects by itself).
522
570
  ctx.effect(() => {
523
- let timer
524
- const tick = () => {
525
- clearTimeout(timer)
526
- if (document.visibilityState === 'visible') refreshSummary()
527
- timer = setTimeout(tick, shared.pollSeconds * 1000)
571
+ let source = null
572
+ const open = () => {
573
+ if (source !== null || typeof EventSource !== 'function') return
574
+ source = new EventSource(api('events'), { withCredentials: true })
575
+ source.onmessage = changed
576
+ source.onopen = changed
577
+ }
578
+ const close = () => { source?.close(); source = null }
579
+ const onVisible = () => {
580
+ if (document.visibilityState === 'visible') { open(); refreshSummary() } else close()
528
581
  }
529
- const onVisible = () => { if (document.visibilityState === 'visible') tick() }
530
582
  document.addEventListener('visibilitychange', onVisible)
531
- tick()
532
- return () => { clearTimeout(timer); document.removeEventListener('visibilitychange', onVisible) }
583
+ onVisible()
584
+ return () => { close(); document.removeEventListener('visibilitychange', onVisible) }
533
585
  }, 'notify-inbox: counts')
534
586
 
535
587
  // ?notify-inbox=<id> (a tapped push, a shared link) opens the page on that notification.
package/docs/ui.md CHANGED
@@ -12,7 +12,7 @@ From `@deepseek-ai/dsh-client-ui-primitives`, which DSH puts in every plugin's m
12
12
  | `Pill` | The Needs you / All filters, as on the Automation page |
13
13
  | `Menu`, `Tooltip` | The ⋯ menu: notifications on this device, a test push |
14
14
  | `StateDot` | The green dot on a live item |
15
- | `IconCheckCircleOutlineRegular`, `IconEllipsisOutlineRegular` | The handled check, the ⋯ trigger |
15
+ | `IconCheckCircleOutlineRegular`, `IconEllipsisOutlineRegular`, `IconSendOutlineRegular` | The handled check, the ⋯ trigger, the reply's Send |
16
16
  | Theme tokens (`--dsw-alias-*`) | Every colour, so light and dark follow the Web UI |
17
17
 
18
18
  The page's layout copies the numbers of DSH's own pages, since their CSS modules aren't shared: the frame (960 px column, 28 px top inset, `clamp(24px, 4vw, 48px)` sides) and rows (12 px radius, 8 px padding, 12 px gap, 13 px tertiary summary) of the Automation page, and the group headings (14 px medium title, count beside it) of the plugin manager.
@@ -25,11 +25,13 @@ From [@soffits/dsh-ui-kit](https://github.com/soffits/dsh-ui-kit) (`ctx.uiKit`),
25
25
 
26
26
  ## Ours
27
27
 
28
- About forty lines of CSS in `client.js`, only for layout DSH doesn't expose:
28
+ About fifty lines of CSS in `client.js`, only for layout DSH doesn't expose:
29
29
 
30
30
  - **The page frame, rows and group headings**, with the values above. A row is a disclosure (the header is a button, the details open below it), which no DSH primitive draws.
31
31
  - **Two-line titles and summaries** (`line-clamp`), so a phone shows the whole of a short title instead of cutting it.
32
- - **The counts line** (`Needs you 2 · Live 1 · …`), joined the way DSH joins row metadata.
32
+ - **The counts line** (`Urgent 1 · Needs you 2 · Live 1 · …`), joined the way DSH joins row metadata.
33
+ - **An ask's points** (`+3`): a small tinted label beside the title in the accent colour; DSH has no badge primitive for a row.
34
+ - **The reply box** under an opened ask: a native `textarea` with DSH's border, radius and background tokens, since DSH exports no multi-line input.
33
35
  - **The unread badge on the sidebar bell**: DSH's sidebar has no count badge for an entry.
34
36
  - **Phone sizes**: at 640 px and below, or with a touch pointer, every control is at least 40 px tall, as DSH's own controls are only on desktop.
35
37
 
package/index.js CHANGED
@@ -21,6 +21,7 @@ import { createPush } from './src/push.js'
21
21
  import { createRoutes } from './src/routes.js'
22
22
  import { createStore } from './src/store.js'
23
23
  import { readLocales, tables } from './src/locales.js'
24
+ import { send as sendReply } from './src/reply.js'
24
25
 
25
26
  export const name = 'dsh-notify-inbox'
26
27
  export const inject = ['connection']
@@ -47,13 +48,11 @@ export const Config = z.object({
47
48
  .description('How each domain (the record\'s domain field) is drawn, on top of the built-in defaults (mail, money, health, travel, home...).'),
48
49
  summaryHours: z.natural().min(1).max(168).default(12)
49
50
  .description('How long the summary line (<dataDir>/<person>/summary.json) is shown after it was written.'),
50
- pollSeconds: z.natural().min(2).max(3600).default(5)
51
- .description('How often new records are looked for (to push them), and how often an open page refreshes its count (at least 15 s).'),
52
51
  })
53
52
 
54
53
  /**
55
54
  * @param {import('@deepseek-ai/cordis').Context} ctx
56
- * @param {{ dataDir: string, people: Record<string, string>, peopleFile: string, peopleKey: string, vapidFile: string, vapidSubject: string, domains: Record<string, { icon: string, tone?: string }>, summaryHours: number, pollSeconds: number }} config
55
+ * @param {{ dataDir: string, people: Record<string, string>, peopleFile: string, peopleKey: string, vapidFile: string, vapidSubject: string, domains: Record<string, { icon: string, tone?: string }>, summaryHours: number }} config
57
56
  */
58
57
  export function apply(ctx, config) {
59
58
  const logger = ctx.logger('notify-inbox')
@@ -78,35 +77,65 @@ export function apply(ctx, config) {
78
77
  warn,
79
78
  })
80
79
  const actions = createActions({ dataDir, events: () => ctx.get('cronJobs'), warn })
81
- const pollSeconds = config.pollSeconds ?? 5
82
- const strings = readLocales(fileURLToPath(new URL('./locale/', import.meta.url))).then(tables)
83
- const changes = createChanges({ dataDir, persons: () => store.persons() })
80
+ const localeDir = fileURLToPath(new URL('./locale/', import.meta.url))
81
+ const strings = () => readLocales(localeDir).then(tables)
82
+ // Replies reach sessions through DSH's own services, looked up when one is sent.
83
+ const replyDeps = () => {
84
+ const agents = ctx.get('agents')
85
+ const controller = ctx.get('sessionController')
86
+ const query = ctx.get('sessionQuery')
87
+ if (agents === undefined || controller === undefined || query === undefined) return undefined
88
+ return {
89
+ liveAgent: id => agents.get(id),
90
+ resolveAgent: async id => {
91
+ const found = await controller.resolveAgent(id)
92
+ if ('error' in found) throw Object.assign(new Error('The conversation that asked could not be opened.'), { status: 404 })
93
+ return found.agent
94
+ },
95
+ readHeader: async id => (await query.readSession(id))?.session,
96
+ flush: session => ctx.get('sessions')?.flush?.(session) ?? Promise.resolve(true),
97
+ detached: fn => (agents.withoutInitiator ? agents.withoutInitiator(fn) : fn()),
98
+ }
99
+ }
100
+ const reply = async request => {
101
+ const deps = replyDeps()
102
+ if (deps === undefined) throw Object.assign(new Error('Replies need a DSH that lets plugins reach its sessions.'), { status: 503 })
103
+ return sendReply(deps, request)
104
+ }
105
+ // New records are pushed when the inbox file changes; one scan at a time, and one more if a change came meanwhile.
106
+ let scanning = null
107
+ let again = false
108
+ const scan = async () => {
109
+ if (scanning !== null) { again = true; return }
110
+ scanning = (async () => {
111
+ do {
112
+ again = false
113
+ try {
114
+ await push.scan(await store.persons())
115
+ } catch (error) {
116
+ warn(`push scan failed: ${error.message}`)
117
+ }
118
+ } while (again)
119
+ })()
120
+ await scanning
121
+ scanning = null
122
+ }
123
+ const changes = createChanges({ dataDir, persons: () => store.persons(), warn, onChange: (_person, file) => { if (file === 'inbox.jsonl') scan() } })
84
124
  const routes = createRoutes({
85
125
  store, people, push, actions, changes,
86
126
  identity: () => ctx.get('requestIdentity'),
87
127
  serviceWorker,
88
- strings: () => strings,
128
+ strings,
129
+ reply,
89
130
  domains: domainMap(config.domains ?? {}),
90
131
  summaryHours: config.summaryHours ?? 12,
91
- pollSeconds: Math.max(pollSeconds, 15),
92
132
  })
93
133
  for (const route of routes) ctx.connection.fetch.register(route)
94
134
 
95
- let stopped = false
96
- let timer
97
- const scan = async () => {
98
- try {
99
- await push.scan(await store.persons())
100
- } catch (error) {
101
- warn(`push scan failed: ${error.message}`)
102
- }
103
- if (!stopped) timer = setTimeout(scan, pollSeconds * 1000)
104
- }
105
- push.vapid().then(() => scan(), error => logger.error(`Web Push keys unusable, push is off: ${error.message}`))
106
- ctx.on('dispose', () => {
107
- stopped = true
108
- clearTimeout(timer)
109
- changes.stop()
135
+ push.vapid().then(() => changes.start().then(scan), error => {
136
+ logger.error(`Web Push keys unusable, push is off: ${error.message}`)
137
+ return changes.start()
110
138
  })
139
+ ctx.on('dispose', () => changes.stop())
111
140
  logger.info(`inbox at ${dataDir} (${people.enabled ? 'per person' : 'single owner'})`)
112
141
  }
package/locale/en.json CHANGED
@@ -45,6 +45,16 @@
45
45
  "more": "More",
46
46
  "push.off": "off",
47
47
  "push.unavailable": "not available here",
48
- "kitMissing": "This page needs the @soffits/dsh-ui-kit plugin."
48
+ "kitMissing": "This page needs the @soffits/dsh-ui-kit plugin.",
49
+ "group.urgent": "Urgent",
50
+ "points": "+{n} pts",
51
+ "reply.label": "Reply",
52
+ "reply.placeholder": "Your answer goes to the conversation that asked",
53
+ "reply.send": "Send",
54
+ "reply.sending": "Sending…",
55
+ "reply.sent": "Sent to the conversation.",
56
+ "reply.open": "Open it",
57
+ "reply.failed": "Couldn’t send: {message}",
58
+ "moved.closed": "Settled."
49
59
  }
50
60
  }
package/locale/fr.json CHANGED
@@ -45,6 +45,16 @@
45
45
  "more": "Plus",
46
46
  "push.off": "désactivées",
47
47
  "push.unavailable": "indisponibles ici",
48
- "kitMissing": "Cette page a besoin du plugin @soffits/dsh-ui-kit."
48
+ "kitMissing": "Cette page a besoin du plugin @soffits/dsh-ui-kit.",
49
+ "group.urgent": "Urgent",
50
+ "points": "+{n} pts",
51
+ "reply.label": "Répondre",
52
+ "reply.placeholder": "Votre réponse va dans la conversation qui a posé la question",
53
+ "reply.send": "Envoyer",
54
+ "reply.sending": "Envoi…",
55
+ "reply.sent": "Envoyé dans la conversation.",
56
+ "reply.open": "L’ouvrir",
57
+ "reply.failed": "Envoi impossible : {message}",
58
+ "moved.closed": "Réglé."
49
59
  }
50
60
  }
package/locale/zh.json CHANGED
@@ -45,6 +45,16 @@
45
45
  "more": "更多",
46
46
  "push.off": "已关闭",
47
47
  "push.unavailable": "这里不可用",
48
- "kitMissing": "这个页面需要 @soffits/dsh-ui-kit 插件。"
48
+ "kitMissing": "这个页面需要 @soffits/dsh-ui-kit 插件。",
49
+ "group.urgent": "紧急",
50
+ "points": "+{n} 分",
51
+ "reply.label": "回复",
52
+ "reply.placeholder": "回复会发到提问的那个对话里",
53
+ "reply.send": "发送",
54
+ "reply.sending": "正在发送…",
55
+ "reply.sent": "已经发到那个对话里了。",
56
+ "reply.open": "打开对话",
57
+ "reply.failed": "没发出去:{message}",
58
+ "moved.closed": "已经处理好了。"
49
59
  }
50
60
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soffits/dsh-notify-inbox",
3
- "version": "0.5.0",
3
+ "version": "0.7.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",
package/src/changes.js CHANGED
@@ -1,55 +1,85 @@
1
1
  /**
2
- * Change notices for open pages. While anyone listens, the files that make up
3
- * a person's inbox (records, read marks, presses, the summary line) are
4
- * looked at every `intervalMs`; when one changed, every listener allowed to
5
- * see that person hears a short notice and the page fetches again. A stat
6
- * per file is cheap and, unlike fs.watch, behaves the same on every file
7
- * system and through a replaced file. Nothing runs while nobody listens.
2
+ * Change notices. The data folder and each person's folder are watched
3
+ * (`fs.watch` on the directories, so a file replaced by a rename is seen as
4
+ * well as one appended to); when one of the files that make up a person's
5
+ * inbox (records, read marks, presses, the summary line, the asks) changes,
6
+ * every listener allowed to see that person hears a short notice and the page
7
+ * fetches again, and `onChange` runs (push looks for new records). No timer:
8
+ * the files' own changes are the signal. A folder that appears later is
9
+ * picked up when the data folder reports it.
8
10
  */
9
- import { stat } from 'node:fs/promises'
11
+ import { watch } from 'node:fs'
10
12
  import { join } from 'node:path'
11
13
 
12
- const FILES = ['inbox.jsonl', 'read.json', 'actions.jsonl', 'summary.json']
14
+ export const FILES = ['inbox.jsonl', 'read.json', 'actions.jsonl', 'summary.json', 'asks.json']
15
+ const SETTLE_MS = 50
13
16
 
14
17
  /**
15
18
  * @param {object} options
16
19
  * @param {string} options.dataDir
17
20
  * @param {() => Promise<string[]>} options.persons - every inbox folder there is
18
- * @param {number} [options.intervalMs]
21
+ * @param {(person: string, file: string) => void} [options.onChange] - also called for each change
22
+ * @param {(message: string) => void} [options.warn]
19
23
  */
20
- export function createChanges({ dataDir, persons, intervalMs = 2000 }) {
24
+ export function createChanges({ dataDir, persons, onChange = () => {}, warn = () => {} }) {
21
25
  const listeners = new Set()
22
- const seen = new Map() // person -> signature
23
- let running = false
24
- let timer
26
+ const watchers = new Map() // folder name ('' for the data folder) -> FSWatcher
27
+ const pending = new Map() // person -> { timer, files }
28
+ let stopped = false
25
29
 
26
- async function signature(person) {
27
- const parts = await Promise.all(FILES.map(name => stat(join(dataDir, person, name)).then(
28
- info => `${info.ino}:${info.size}:${info.mtimeMs}`,
29
- () => '-')))
30
- return parts.join('|')
30
+ function notify(person, file) {
31
+ const due = pending.get(person) ?? { timer: undefined, files: new Set() }
32
+ due.files.add(file)
33
+ clearTimeout(due.timer)
34
+ // Several writes in one go (an append and its status line, a rename) become one notice.
35
+ due.timer = setTimeout(() => {
36
+ pending.delete(person)
37
+ for (const listener of listeners) if (listener.folders === null || listener.folders.includes(person)) listener.send(person)
38
+ for (const name of due.files) onChange(person, name)
39
+ }, SETTLE_MS)
40
+ pending.set(person, due)
31
41
  }
32
42
 
33
- /** One look at every folder; the loop goes on while anyone listens and ends by itself after. */
34
- async function tick() {
43
+ function watchFolder(person) {
44
+ if (stopped || watchers.has(person)) return
35
45
  try {
36
- for (const person of await persons()) {
37
- const now = await signature(person)
38
- const before = seen.get(person)
39
- seen.set(person, now)
40
- if (before === undefined || before === now) continue
41
- for (const listener of listeners) if (listener.folders === null || listener.folders.includes(person)) listener.send(person)
42
- }
43
- } finally {
44
- if (listeners.size > 0) {
45
- timer = setTimeout(tick, intervalMs)
46
- } else {
47
- running = false
48
- seen.clear()
46
+ const watcher = watch(join(dataDir, person), (_event, name) => {
47
+ const file = name === null ? null : String(name)
48
+ if (file === null || FILES.includes(file)) notify(person, file ?? 'inbox.jsonl')
49
+ })
50
+ watcher.on('error', error => {
51
+ warn(`stopped watching ${person}: ${error.message}`)
52
+ watcher.close()
53
+ watchers.delete(person)
54
+ })
55
+ watchers.set(person, watcher)
56
+ } catch (error) {
57
+ if (error.code !== 'ENOENT') warn(`cannot watch ${person}: ${error.message}`)
58
+ }
59
+ }
60
+
61
+ async function sync() {
62
+ for (const person of await persons()) {
63
+ if (!watchers.has(person)) {
64
+ watchFolder(person)
65
+ notify(person, 'inbox.jsonl')
49
66
  }
50
67
  }
51
68
  }
52
69
 
70
+ /** Start watching: the data folder for new people, and every person's folder. */
71
+ async function start() {
72
+ if (stopped || watchers.has('')) return
73
+ try {
74
+ const top = watch(dataDir, () => { sync().catch(error => warn(`inbox folders not read: ${error.message}`)) })
75
+ top.on('error', error => warn(`stopped watching the inbox folder: ${error.message}`))
76
+ watchers.set('', top)
77
+ } catch (error) {
78
+ warn(`cannot watch ${dataDir}: ${error.message}`)
79
+ }
80
+ for (const person of await persons()) watchFolder(person)
81
+ }
82
+
53
83
  /**
54
84
  * Hear about changes to these folders (null: every folder, for an owner who sees them all).
55
85
  * @returns {() => void} stop listening
@@ -57,19 +87,18 @@ export function createChanges({ dataDir, persons, intervalMs = 2000 }) {
57
87
  function listen(folders, send) {
58
88
  const listener = { folders, send }
59
89
  listeners.add(listener)
60
- if (!running) {
61
- running = true
62
- timer = setTimeout(tick, 0)
63
- }
64
90
  return () => listeners.delete(listener)
65
91
  }
66
92
 
67
93
  /** Stop at once (the plugin is going away). */
68
94
  function stop() {
95
+ stopped = true
69
96
  listeners.clear()
70
- clearTimeout(timer)
71
- running = false
97
+ for (const watcher of watchers.values()) watcher.close()
98
+ watchers.clear()
99
+ for (const { timer } of pending.values()) clearTimeout(timer)
100
+ pending.clear()
72
101
  }
73
102
 
74
- return { listen, stop, tick }
103
+ return { start, listen, stop }
75
104
  }
package/src/reply.js ADDED
@@ -0,0 +1,75 @@
1
+ /**
2
+ * A reply to an ask, put into the session that asked.
3
+ *
4
+ * The page posts the person's words; the route has already checked the item is
5
+ * theirs and names a session. Here the words, with the item quoted in the
6
+ * format the UI actions package reads back as a card, go into that session
7
+ * through DSH's own steering: a running session sees them at its next step, an
8
+ * idle or stored one is loaded and starts a turn with them. The sender is the
9
+ * person the server verified (their sign-in's principal, the way the sign-in
10
+ * plugin stamps a message typed in the Web UI), or the owner when the inbox has
11
+ * no people mapping. Every DSH service comes in through `deps`, so the logic is
12
+ * tested without a host.
13
+ */
14
+ import { randomUUID } from 'node:crypto'
15
+
16
+ export const SOURCE_KIND = 'notify-inbox-reply'
17
+ export const MAX_REPLY = 8000
18
+ const QUOTED_LINES = 12
19
+ const LINE_MAX = 300
20
+
21
+ /**
22
+ * @typedef {object} Deps
23
+ * @property {(id: string) => any} liveAgent - the loaded Agent of a session, or undefined
24
+ * @property {(id: string) => Promise<any>} resolveAgent - load (resume) a stored session's Agent
25
+ * @property {(id: string) => Promise<{ origin?: string, parentSession?: string } | undefined>} readHeader - a stored session's header
26
+ * @property {(session: any) => Promise<boolean>} [flush] - wait until the session log has the message
27
+ * @property {<T>(fn: () => T) => T} [detached] - run outside whichever turn happens to be current
28
+ */
29
+
30
+ const oneLine = (value, max) => String(value ?? '').replace(/\s+/gu, ' ').trim().slice(0, max)
31
+
32
+ /** The item as quoted text: title, the source line, a few lines of text, its context. */
33
+ export function quote(item) {
34
+ const lines = [oneLine(item.title, 200) || '…', '[Item from Inbox (@soffits/dsh-notify-inbox)]']
35
+ for (const line of String(item.text ?? '').split('\n')) {
36
+ if (lines.length >= QUOTED_LINES) break
37
+ const text = oneLine(line, LINE_MAX)
38
+ if (text !== '') lines.push(text)
39
+ }
40
+ lines.push(`context: ${JSON.stringify({ notification: item.id, ask: item.ask, thread: item.thread || undefined })}`)
41
+ return lines.map(line => `> ${line}`).join('\n')
42
+ }
43
+
44
+ /** The sender of a reply: the verified person as their sign-in names them, or none (the owner). */
45
+ export function principalOf(identity) {
46
+ if (identity === null || identity === undefined || typeof identity.id !== 'string') return undefined
47
+ const principal = { kind: `${identity.provider || 'web'}-user`, channel: 'web', id: identity.id }
48
+ if (identity.name) principal.name = String(identity.name)
49
+ if (identity.issuer) principal.issuer = String(identity.issuer)
50
+ return principal
51
+ }
52
+
53
+ /**
54
+ * Put one reply into `session`. Returns `{ session, woke }`; throws with a message the page can show.
55
+ * @param {Deps} deps
56
+ */
57
+ export async function send(deps, { session, words, item, identity }) {
58
+ const text = String(words ?? '').trim()
59
+ if (text === '') throw Object.assign(new Error('Write a reply first.'), { status: 400 })
60
+ if (text.length > MAX_REPLY) throw Object.assign(new Error(`A reply is at most ${MAX_REPLY} characters.`), { status: 413 })
61
+ const live = deps.liveAgent(session)
62
+ const header = live?.session?.header ?? await deps.readHeader(session)
63
+ if (header === undefined) throw Object.assign(new Error('The conversation that asked is gone.'), { status: 404 })
64
+ if (header.origin === 'subagent') throw Object.assign(new Error('The conversation that asked was a helper that has finished; ask in a chat instead.'), { status: 409 })
65
+ const principal = principalOf(identity)
66
+ const source = principal === undefined ? { kind: SOURCE_KIND } : { kind: SOURCE_KIND, principal }
67
+ const run = async () => {
68
+ const agent = live ?? await deps.resolveAgent(session)
69
+ const woke = agent.status !== 'running'
70
+ agent.steer({ id: randomUUID(), role: 'user', content: [{ type: 'text', text: `${text}\n\n${quote(item)}` }], source })
71
+ if (deps.flush && !(await deps.flush(agent.session))) throw new Error('the conversation did not take the reply')
72
+ return { session, woke }
73
+ }
74
+ return deps.detached ? deps.detached(run) : run()
75
+ }
package/src/routes.js CHANGED
@@ -6,8 +6,10 @@
6
6
  * GET /api/notify-inbox/summary counts per group, unread, the summary line, the domain map
7
7
  * GET /api/notify-inbox/items?view=needs-you&keep=&before=&limit=
8
8
  * GET /api/notify-inbox/events text/event-stream: a notice whenever the caller's inbox changed
9
+ * POST /api/notify-inbox/reply { record, text } a reply to an ask, put into the session that asked
9
10
  * POST /api/notify-inbox/read { ids: [...], read?: false } or { all: true }
10
- * POST /api/notify-inbox/action { record, action, until? } a done/snooze/event press
11
+ * POST /api/notify-inbox/action { record, action, until? } a done/snooze/event press (record: a
12
+ * record id or an ask's id; an ask's own buttons win in its thread)
11
13
  * GET /api/notify-inbox/file?id=&name= a stored attachment
12
14
  * GET /api/notify-inbox/push/config { publicKey }
13
15
  * POST /api/notify-inbox/push/state { endpoint } → { subscribed }
@@ -66,13 +68,13 @@ async function body(request) {
66
68
  * @param {ReturnType<import('./actions.js').createActions>} options.actions
67
69
  * @param {() => object | undefined} options.identity - the requestIdentity service right now, if any
68
70
  * @param {string} options.serviceWorker - the service worker's source
69
- * @param {() => Promise<Record<string, Record<string, string>>>} [options.strings] - the page's words, complete per tag
71
+ * @param {() => Promise<Record<string, Record<string, string>>>} [options.strings] - the page's words, complete per tag, read for each request
72
+ * @param {(request: { session: string, words: string, item: object, identity: object | undefined }) => Promise<object>} [options.reply] - puts a reply into a session (src/reply.js)
70
73
  * @param {ReturnType<import('./changes.js').createChanges>} options.changes
71
74
  * @param {Record<string, { icon: string, tone?: string }>} options.domains - the domain map (src/domains.js)
72
75
  * @param {number} options.summaryHours - how long a summary line is shown
73
- * @param {number} options.pollSeconds
74
76
  */
75
- export function createRoutes({ store, people, push, actions, identity, serviceWorker, strings = async () => ({}), changes, domains, summaryHours, pollSeconds }) {
77
+ export function createRoutes({ store, people, push, actions, identity, serviceWorker, strings = async () => ({}), reply, changes, domains, summaryHours }) {
76
78
  /** Who is asking, as the inbox folders they may read; undefined with the response to send instead. */
77
79
  async function caller() {
78
80
  const viewer = await viewerOf(people, identity())
@@ -100,15 +102,15 @@ export function createRoutes({ store, people, push, actions, identity, serviceWo
100
102
 
101
103
  /** The caller's items, folded and grouped as of now. */
102
104
  async function itemsOf(who) {
103
- const { items: records, bad } = await store.view(who.folders)
104
- return { items: buildItems(records, Date.now()), bad }
105
+ const { items: records, asks, bad } = await store.view(who.folders)
106
+ return { items: buildItems(records, Date.now(), asks), bad }
105
107
  }
106
108
 
107
109
  const summary = handle(async (_request, who) => {
108
110
  const [{ items, bad }, line] = await Promise.all([itemsOf(who), store.summaryLine(who.folders, summaryHours)])
109
111
  const { groups, unread } = countItems(items)
110
112
  const latest = items.reduce((newest, item) => (newest === null || item.time > newest ? item.time : newest), null)
111
- return json(200, { mode: who.mode, person: who.person, unread, groups, total: items.length, latest, line, domains, problems: { badLines: bad }, pollSeconds })
113
+ return json(200, { mode: who.mode, person: who.person, unread, groups, total: items.length, latest, line, domains, problems: { badLines: bad } })
112
114
  })
113
115
 
114
116
  const list = handle(async (request, who) => {
@@ -168,12 +170,18 @@ export function createRoutes({ store, people, push, actions, identity, serviceWo
168
170
  })
169
171
  })
170
172
 
171
- /** The record with this id the caller may see, or undefined. */
173
+ /**
174
+ * The record (or open ask) with this id the caller may see, with the buttons it answers to: an open
175
+ * ask's own for the ask and every record in its thread. Undefined when there is none.
176
+ */
172
177
  async function recordOf(who, id) {
173
178
  if (typeof id !== 'string' || !RECORD_ID_PATTERN.test(id)) return undefined
174
179
  for (const person of who.folders) {
180
+ const { asks } = await store.asks(person)
175
181
  const record = (await store.records(person)).records.find(row => row.id === id)
176
- if (record !== undefined) return record
182
+ const ask = asks.find(row => row.id === id || row.id === record?.thread)
183
+ if (record !== undefined) return ask === undefined ? record : { ...record, session: ask.session ?? record.session, actions: [...record.actions.filter(a => a.kind !== 'done' && a.kind !== 'snooze'), ...ask.actions] }
184
+ if (ask !== undefined) return { ...ask, key: '', thread: ask.id }
177
185
  }
178
186
  return undefined
179
187
  }
@@ -203,6 +211,24 @@ export function createRoutes({ store, people, push, actions, identity, serviceWo
203
211
  return json(200, { press: result.event.press, published: result.published, matched: result.matched ?? 0 })
204
212
  })
205
213
 
214
+ /** A reply to an ask the caller sees, into the session the ask names (its own, else its notification's). */
215
+ const answer = handle(async (request, who) => {
216
+ const value = await body(request)
217
+ const record = await recordOf(who, value.record)
218
+ if (record === undefined) return json(404, { error: 'No such notification.' })
219
+ const session = record.session
220
+ if (typeof session !== 'string' || session === '') return json(400, { error: 'This notification names no conversation to reply to.' })
221
+ if (reply === undefined) return json(503, { error: 'Replies need a DSH that lets plugins reach its sessions.' })
222
+ const askId = (await store.asks(record.person)).asks.find(ask => ask.id === record.thread || ask.id === record.id)?.id
223
+ try {
224
+ const sent = await reply({ session, words: value.text, item: { id: record.id, title: record.title, text: record.text, thread: record.thread, ask: askId }, identity: identity()?.current?.() ?? undefined })
225
+ await store.setRead(record.person, [record.id], true)
226
+ return json(200, { ok: true, session: sent.session, woke: sent.woke })
227
+ } catch (error) {
228
+ return json(error.status ?? 502, { error: error.message })
229
+ }
230
+ })
231
+
206
232
  const file = handle(async (request, who) => {
207
233
  const params = new URL(request.url).searchParams
208
234
  const found = await store.file(who.folders, params.get('id') ?? '', params.get('name') ?? '')
@@ -244,7 +270,8 @@ export function createRoutes({ store, people, push, actions, identity, serviceWo
244
270
  })
245
271
  const pushTest = handle(async (request, who) => json(200, await push.test(who.person, await body(request))))
246
272
 
247
- const words = async () => json(200, { tables: await strings() }, { 'cache-control': 'private, max-age=300' })
273
+ // Read for each request and never cached: an update in place brings new words with no stale copy anywhere.
274
+ const words = async () => json(200, { tables: await strings() }, { 'cache-control': 'no-store' })
248
275
 
249
276
  const worker = async () => new Response(serviceWorker, {
250
277
  status: 200,
@@ -259,6 +286,7 @@ export function createRoutes({ store, people, push, actions, identity, serviceWo
259
286
  get('/events', events),
260
287
  post('/read', read),
261
288
  post('/action', action),
289
+ post('/reply', answer),
262
290
  get('/file', file),
263
291
  get('/push/config', pushConfig),
264
292
  post('/push/state', pushState),
package/src/store.js CHANGED
@@ -6,6 +6,8 @@
6
6
  * <dataDir>/<person>/files/<id>/<name> attachments the router copied in
7
7
  * <dataDir>/<person>/read.json read marks; written by this plugin only
8
8
  * <dataDir>/<person>/summary.json the line shown above the items; written by the router's side
9
+ * <dataDir>/<person>/asks.json what waits on the person's answer now; written by whatever keeps their
10
+ * list of asks (a Todo), read fresh each time
9
11
  *
10
12
  * Records are re-read incrementally: only the bytes appended since the last
11
13
  * look are parsed, and the whole file again when it shrank or was replaced
@@ -20,15 +22,16 @@ export const RECORD_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,79}$/
20
22
  const INBOX = 'inbox.jsonl'
21
23
  const READ = 'read.json'
22
24
  const SUMMARY = 'summary.json'
25
+ const ASKS = 'asks.json'
23
26
 
24
27
  const text = value => (typeof value === 'string' ? value : '')
25
28
  const list = value => (Array.isArray(value) ? value : [])
26
29
  /** Text a person reads: a string, or a map from language tag to text (the page picks the language). */
27
30
  const words = value => (typeof value === 'string' ? value : value !== null && typeof value === 'object' && !Array.isArray(value) && Object.values(value).every(v => typeof v === 'string') ? value : '')
28
31
 
29
- export const GROUPS = ['needs-you', 'live', 'handled', 'info']
30
- const ASKING = ['done', 'snooze']
32
+ export const GROUPS = ['urgent', 'needs-you', 'live', 'handled', 'info']
31
33
  const MAX_THREAD = 120
34
+ const MAX_ASK_TEXT = 8000
32
35
 
33
36
  const isoTime = value => {
34
37
  const at = Date.parse(text(value))
@@ -58,17 +61,46 @@ function handledOf(raw) {
58
61
 
59
62
  /**
60
63
  * The group a record belongs in. A writer usually says (`attention`); for a record that doesn't,
61
- * the same default the router documents: handled, then live, then needs-you for an interrupt or a
62
- * record with done or snooze buttons, else info.
64
+ * the same default the router documents: handled, then live, then urgent for an interrupt, else info.
65
+ * Needs-you is never a default: it is for asks (see `asks`).
63
66
  */
64
67
  export function attentionOf(record) {
65
68
  if (GROUPS.includes(record.attention)) return record.attention
66
69
  if (record.handled !== null) return 'handled'
67
70
  if (record.live !== null) return 'live'
68
- if (record.lane === 'interrupt' || record.actions.some(action => ASKING.includes(action.kind))) return 'needs-you'
71
+ if (record.lane === 'interrupt') return 'urgent'
69
72
  return 'info'
70
73
  }
71
74
 
75
+ const actionsOf = raw => list(raw).filter(action => typeof action?.kind === 'string' && typeof action?.id === 'string').map(action => ({
76
+ kind: action.kind,
77
+ id: action.id,
78
+ label: words(action.label) || undefined,
79
+ payload: typeof action.payload === 'object' && action.payload !== null && !Array.isArray(action.payload) ? action.payload : {},
80
+ ...(typeof action.inverse?.kind === 'string' ? { inverse: { kind: action.inverse.kind, payload: typeof action.inverse.payload === 'object' && action.inverse.payload !== null ? action.inverse.payload : {} } } : {}),
81
+ }))
82
+
83
+ /** One entry of `asks.json` as the page gets it, or undefined when it is not one. */
84
+ export function normalizeAsk(raw, person) {
85
+ if (typeof raw !== 'object' || raw === null || !RECORD_ID_PATTERN.test(text(raw.id))) return undefined
86
+ const time = isoTime(raw.time)
87
+ if (time === undefined || text(raw.title).trim() === '') return undefined
88
+ const day = value => (/^\d{4}-\d{2}-\d{2}$/.test(text(value)) ? value : undefined)
89
+ return {
90
+ id: raw.id,
91
+ person,
92
+ time,
93
+ title: text(raw.title),
94
+ text: text(raw.text).slice(0, MAX_ASK_TEXT),
95
+ domain: text(raw.domain),
96
+ next: day(raw.next),
97
+ due: day(raw.due),
98
+ points: Number.isFinite(raw.points) && raw.points > 0 ? Math.round(raw.points) : null,
99
+ session: /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(text(raw.session)) ? raw.session : null,
100
+ actions: actionsOf(raw.actions),
101
+ }
102
+ }
103
+
72
104
  /** A record as the page gets it, or undefined when the line is not one. */
73
105
  export function normalize(raw, person) {
74
106
  if (typeof raw !== 'object' || raw === null || !RECORD_ID_PATTERN.test(text(raw.id))) return undefined
@@ -92,16 +124,12 @@ export function normalize(raw, person) {
92
124
  })),
93
125
  source: text(raw.source),
94
126
  key: text(raw.key),
95
- actions: list(raw.actions).filter(action => typeof action?.kind === 'string' && typeof action?.id === 'string').map(action => ({
96
- kind: action.kind,
97
- id: action.id,
98
- label: words(action.label) || undefined,
99
- payload: typeof action.payload === 'object' && action.payload !== null && !Array.isArray(action.payload) ? action.payload : {},
100
- })),
127
+ actions: actionsOf(raw.actions),
101
128
  attention: text(raw.attention),
102
129
  thread: text(raw.thread).trim().slice(0, MAX_THREAD),
103
130
  live: liveOf(raw.live),
104
131
  handled: handledOf(raw.handled),
132
+ session: /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(text(raw.session)) ? raw.session : null,
105
133
  test: raw.test === true,
106
134
  push: raw.push !== false,
107
135
  routed: list(raw.routed).filter(row => typeof row?.destination === 'string').map(row => ({
@@ -241,6 +269,20 @@ export function createStore(dataDir) {
241
269
  return { records: entry.records, handled: entry.handled, bad: entry.bad }
242
270
  }
243
271
 
272
+ /**
273
+ * What waits on this person now, read fresh from `<person>/asks.json`: `{ present, asks }`. Without the
274
+ * file nothing is said about asks and records keep their own groups; with it, it alone says what needs them.
275
+ */
276
+ async function asks(person) {
277
+ let value
278
+ try {
279
+ value = JSON.parse(await readFile(join(dataDir, person, ASKS), 'utf8'))
280
+ } catch {
281
+ return { present: false, asks: [] }
282
+ }
283
+ return { present: true, asks: list(value?.asks).map(raw => normalizeAsk(raw, person)).filter(Boolean) }
284
+ }
285
+
244
286
  async function marks(person) {
245
287
  try {
246
288
  const value = JSON.parse(await readFile(join(dataDir, person, READ), 'utf8'))
@@ -261,7 +303,7 @@ export function createStore(dataDir) {
261
303
  * Each list keeps only what the watermark doesn't already say.
262
304
  */
263
305
  async function setRead(person, ids, value) {
264
- const byId = new Map((await records(person)).records.map(record => [record.id, record]))
306
+ const byId = new Map([...(await asks(person)).asks, ...(await records(person)).records].map(row => [row.id, row]))
265
307
  const current = await marks(person)
266
308
  const read = new Set(current.read)
267
309
  const unread = new Set(current.unread)
@@ -287,19 +329,24 @@ export function createStore(dataDir) {
287
329
  await saveMarks(person, { readBefore, read: current.read.filter(id => byId.has(id) && byId.get(id).time > readBefore), unread: [] })
288
330
  }
289
331
 
290
- /** The records of these people, newest first, each with `read` and the `outcomes` of presses on it. */
332
+ /**
333
+ * The records of these people, newest first, each with `read` and the `outcomes` of presses on it, and
334
+ * their asks by person (`{ present, asks }`, each ask with `read`).
335
+ */
291
336
  async function view(people) {
292
337
  const out = []
338
+ const asking = new Map()
293
339
  let bad = 0
294
340
  for (const person of people) {
295
- const [{ records: rows, handled, bad: skipped }, marked] = await Promise.all([records(person), marks(person)])
341
+ const [{ records: rows, handled, bad: skipped }, marked, open] = await Promise.all([records(person), marks(person), asks(person)])
296
342
  bad += skipped
297
343
  const byRecord = new Map()
298
344
  for (const status of handled) byRecord.set(status.record, [...(byRecord.get(status.record) ?? []), status])
299
345
  for (const record of rows) out.push({ ...record, read: isRead(marked, record), outcomes: byRecord.get(record.id) ?? [] })
346
+ asking.set(person, { present: open.present, asks: open.asks.map(ask => ({ ...ask, read: isRead(marked, ask), outcomes: byRecord.get(ask.id) ?? [] })) })
300
347
  }
301
348
  out.sort((a, b) => (a.time === b.time ? 0 : a.time < b.time ? 1 : -1))
302
- return { items: out, bad }
349
+ return { items: out, asks: asking, bad }
303
350
  }
304
351
 
305
352
  /**
@@ -334,5 +381,5 @@ export function createStore(dataDir) {
334
381
  return undefined
335
382
  }
336
383
 
337
- return { persons, records, marks, setRead, markAllRead, view, summaryLine, file }
384
+ return { persons, records, asks, marks, setRead, markAllRead, view, summaryLine, file }
338
385
  }
package/src/view.js CHANGED
@@ -3,9 +3,14 @@
3
3
  * `thread` fold into one item, the newest on top and the older ones as its
4
4
  * history; a live thread's newest record simply replaces the item. Each item
5
5
  * gets the group it shows in now, which can differ from what its writer said:
6
- * a needs-you item the person marked done is handled, a snoozed one waits
7
- * under info until it comes back as a new record, and a live item whose time
8
- * is over is info.
6
+ * an urgent item the person marked done is handled, a snoozed one waits under
7
+ * info until it comes back as a new record, and a live item whose time is over
8
+ * is info.
9
+ *
10
+ * A person whose inbox has an asks file (`asks.json`) gets their "Needs you"
11
+ * from it alone: each open ask is one item, with the records of its thread
12
+ * folded in when there are any, and a record that said needs-you but whose
13
+ * ask is no longer open has been dealt with in its source, so it is handled.
9
14
  */
10
15
  import { createHash } from 'node:crypto'
11
16
  import { GROUPS } from './store.js'
@@ -29,10 +34,15 @@ export function liveNow(record, now) {
29
34
 
30
35
  /**
31
36
  * The group an item's newest record shows in at `now`, with `moved` saying why when it isn't the
32
- * writer's: 'done' (the person marked it done), 'snoozed', or 'ended' (a live item past its time).
37
+ * writer's: 'done' (the person marked it done), 'snoozed', 'ended' (a live item past its time) or
38
+ * 'closed' (its ask is no longer open). `asked` is the person's asks (`{ present, open: Set }`).
33
39
  */
34
- export function groupOf(record, now) {
35
- if (record.attention === 'needs-you') {
40
+ export function groupOf(record, now, asked = { present: false, open: new Set() }) {
41
+ if (record.attention === 'needs-you' && asked.present) {
42
+ if (asked.open.has(record.thread)) return { group: 'needs-you', moved: null }
43
+ return record.thread === '' ? { group: record.lane === 'interrupt' ? 'urgent' : 'info', moved: null } : { group: 'handled', moved: 'closed' }
44
+ }
45
+ if (record.attention === 'urgent' || record.attention === 'needs-you') {
36
46
  const last = record.outcomes.findLast(row => row.result === 'done' || row.result === 'snoozed')
37
47
  if (last?.result === 'done') return { group: 'handled', moved: 'done' }
38
48
  if (last?.result === 'snoozed' && (last.until === undefined || Date.parse(last.until) > now)) return { group: 'info', moved: 'snoozed' }
@@ -41,11 +51,32 @@ export function groupOf(record, now) {
41
51
  return { group: record.attention, moved: null }
42
52
  }
43
53
 
54
+ /** An open ask as an item: alone, or on top of its thread's newest record. */
55
+ function askItem(ask, record) {
56
+ const base = record ?? {
57
+ id: ask.id, person: ask.person, time: ask.time, lane: 'next-moment', domain: ask.domain, title: ask.title, spoken: '',
58
+ text: ask.text, links: [], files: [], source: '', key: '', actions: [], thread: ask.id, live: null, handled: null,
59
+ session: null, test: false, push: false, routed: [], read: ask.read, outcomes: ask.outcomes,
60
+ }
61
+ return {
62
+ ...base,
63
+ title: ask.title,
64
+ text: record === undefined || record.text === '' ? ask.text : record.text,
65
+ actions: [...base.actions.filter(action => action.kind !== 'done' && action.kind !== 'snooze'), ...ask.actions],
66
+ attention: 'needs-you',
67
+ session: ask.session ?? base.session,
68
+ ask: { id: ask.id, points: ask.points, next: ask.next, due: ask.due, text: ask.text },
69
+ read: record === undefined ? ask.read : base.read,
70
+ }
71
+ }
72
+
44
73
  /**
45
- * Fold records (newest first, each with `read` and `outcomes`) into items, ordered by group
46
- * (needs-you, live, handled, info) and newest first within a group.
74
+ * Fold records (newest first, each with `read` and `outcomes`) and the people's asks (person →
75
+ * `{ present, asks }`) into items, ordered by group (urgent, needs-you, live, handled, info) and
76
+ * newest first within a group.
47
77
  */
48
- export function buildItems(records, now) {
78
+ export function buildItems(records, now, asking = new Map()) {
79
+ const asked = new Map([...asking].map(([person, value]) => [person, { present: value.present, open: new Map(value.asks.map(ask => [ask.id, ask])) }]))
49
80
  const byKey = new Map()
50
81
  for (const record of records) {
51
82
  const key = itemKey(record)
@@ -58,7 +89,18 @@ export function buildItems(records, now) {
58
89
  item.read &&= record.read
59
90
  if (item.history.length < HISTORY_MAX) item.history.push({ id: record.id, time: record.time, title: record.title, spoken: record.spoken })
60
91
  }
61
- const items = [...byKey.values()].map(item => ({ ...item, ...groupOf(item, now), liveNow: liveNow(item, now) }))
92
+ for (const [person, { open }] of asked) {
93
+ for (const ask of open.values()) {
94
+ const key = itemKey({ person, thread: ask.id, id: ask.id })
95
+ const folded = byKey.get(key)
96
+ byKey.set(key, folded === undefined ? { ...askItem(ask), key, ids: [ask.id], history: [] } : { ...askItem(ask, folded), key, ids: folded.ids, history: folded.history })
97
+ }
98
+ }
99
+ const items = [...byKey.values()].map(item => {
100
+ const mine = asked.get(item.person)
101
+ const where = groupOf(item, now, mine === undefined ? undefined : { present: mine.present, open: mine.open })
102
+ return { ...item, ...where, liveNow: liveNow(item, now) }
103
+ })
62
104
  const rank = group => GROUPS.indexOf(group)
63
105
  return items.sort((a, b) => rank(a.group) - rank(b.group) || (a.time === b.time ? 0 : a.time < b.time ? 1 : -1))
64
106
  }