@soffits/dsh-notify-inbox 0.6.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,14 @@
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
+
3
12
  ## 0.6.0
4
13
 
5
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'.
package/README.md CHANGED
@@ -88,7 +88,8 @@ What waits on the person's answer (a decision, a pick, a small step for someone
88
88
 
89
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
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. The reply goes into that session as the person (through `@soffits/dsh-ui-actions`' `start`, DSH's own session prompt), with the ask quoted in, so the conversation that asked carries on with the answer; the page offers to open it.
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.
92
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.
93
94
  - Without `asks.json` nothing changes: notifications keep the group they were filed with.
94
95
 
package/client.js CHANGED
@@ -15,8 +15,8 @@
15
15
  *
16
16
  * An ask (a notification that waits on the person's answer, or an open ask
17
17
  * from their list) shows its points and, when it names the session that
18
- * asked, a reply box: the reply goes into that session as the person, through
19
- * the UI actions' `start`, with the ask quoted in.
18
+ * asked, a reply box: the server puts the reply into that session as the
19
+ * person, with the ask quoted in.
20
20
  */
21
21
  window.__ModuleLoader__.load({
22
22
  id: '@soffits/dsh-notify-inbox',
@@ -73,7 +73,7 @@ window.__ModuleLoader__.load({
73
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
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
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-primary,var(--dsw-alias-label-quaternary));border-radius:10px;background:var(--dsw-alias-bg-base);color:inherit;font:inherit;resize:vertical}
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
77
  .nib-replyBar{display:flex;flex-wrap:wrap;align-items:center;gap:8px}
78
78
  .nib-open .nib-title{-webkit-line-clamp:unset}
79
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)}
@@ -173,7 +173,7 @@ window.__ModuleLoader__.load({
173
173
  })
174
174
 
175
175
  /** A reply to an ask, sent into the session that asked as the person, with the ask quoted in. */
176
- function Reply({ item, ui, t, onSent }) {
176
+ function Reply({ item, t, onSent }) {
177
177
  const [text, setText] = useState('')
178
178
  const [state, setState] = useState({ phase: 'idle' })
179
179
  const send = async () => {
@@ -181,9 +181,9 @@ window.__ModuleLoader__.load({
181
181
  if (words === '' || state.phase === 'sending') return
182
182
  setState({ phase: 'sending' })
183
183
  try {
184
- const session = await ui.start(aboutOf(item), { instruction: words, session: item.session })
184
+ const sent = await call('reply', { record: item.id, text: words })
185
185
  setText('')
186
- setState({ phase: 'sent', session })
186
+ setState({ phase: 'sent', session: sent.session })
187
187
  onSent()
188
188
  } catch (reason) {
189
189
  setState({ phase: 'failed', message: reason.message })
@@ -259,7 +259,7 @@ window.__ModuleLoader__.load({
259
259
  ui !== null && h(ui.ActionBar, { actions: item.actions, states, about, defaultChat: true, part: 'buttons', onPress }),
260
260
  item.read && h(Button, { variant: 'outline', size: 'sm', onClick: () => onMark(item, false) }, t('markUnread')),
261
261
  status && h('span', { className: 'nib-meta' }, status)),
262
- item.group === 'needs-you' && item.session && ui?.start && h(Reply, { item, ui, t, onSent: () => { if (!item.read) onMark(item, true) } }),
262
+ item.group === 'needs-you' && item.session && h(Reply, { item, t, onSent: () => { if (!item.read) onMark(item, true) } }),
263
263
  h(kit.Suggested, { actions: item.actions, about, states, onPress }),
264
264
  h('div', { className: 'nib-meta' },
265
265
  item.routed.length === 0 ? t('notSent') : h(React.Fragment, null, `${t('alsoSent')}: `,
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']
@@ -76,7 +77,31 @@ export function apply(ctx, config) {
76
77
  warn,
77
78
  })
78
79
  const actions = createActions({ dataDir, events: () => ctx.get('cronJobs'), warn })
79
- const strings = readLocales(fileURLToPath(new URL('./locale/', import.meta.url))).then(tables)
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
+ }
80
105
  // New records are pushed when the inbox file changes; one scan at a time, and one more if a change came meanwhile.
81
106
  let scanning = null
82
107
  let again = false
@@ -100,7 +125,8 @@ export function apply(ctx, config) {
100
125
  store, people, push, actions, changes,
101
126
  identity: () => ctx.get('requestIdentity'),
102
127
  serviceWorker,
103
- strings: () => strings,
128
+ strings,
129
+ reply,
104
130
  domains: domainMap(config.domains ?? {}),
105
131
  summaryHours: config.summaryHours ?? 12,
106
132
  })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soffits/dsh-notify-inbox",
3
- "version": "0.6.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/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,6 +6,7 @@
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
11
  * POST /api/notify-inbox/action { record, action, until? } a done/snooze/event press (record: a
11
12
  * record id or an ask's id; an ask's own buttons win in its thread)
@@ -67,12 +68,13 @@ async function body(request) {
67
68
  * @param {ReturnType<import('./actions.js').createActions>} options.actions
68
69
  * @param {() => object | undefined} options.identity - the requestIdentity service right now, if any
69
70
  * @param {string} options.serviceWorker - the service worker's source
70
- * @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)
71
73
  * @param {ReturnType<import('./changes.js').createChanges>} options.changes
72
74
  * @param {Record<string, { icon: string, tone?: string }>} options.domains - the domain map (src/domains.js)
73
75
  * @param {number} options.summaryHours - how long a summary line is shown
74
76
  */
75
- export function createRoutes({ store, people, push, actions, identity, serviceWorker, strings = async () => ({}), changes, domains, summaryHours }) {
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())
@@ -178,7 +180,7 @@ export function createRoutes({ store, people, push, actions, identity, serviceWo
178
180
  const { asks } = await store.asks(person)
179
181
  const record = (await store.records(person)).records.find(row => row.id === id)
180
182
  const ask = asks.find(row => row.id === id || row.id === record?.thread)
181
- if (record !== undefined) return ask === undefined ? record : { ...record, actions: [...record.actions.filter(a => a.kind !== 'done' && a.kind !== 'snooze'), ...ask.actions] }
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] }
182
184
  if (ask !== undefined) return { ...ask, key: '', thread: ask.id }
183
185
  }
184
186
  return undefined
@@ -209,6 +211,24 @@ export function createRoutes({ store, people, push, actions, identity, serviceWo
209
211
  return json(200, { press: result.event.press, published: result.published, matched: result.matched ?? 0 })
210
212
  })
211
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
+
212
232
  const file = handle(async (request, who) => {
213
233
  const params = new URL(request.url).searchParams
214
234
  const found = await store.file(who.folders, params.get('id') ?? '', params.get('name') ?? '')
@@ -250,7 +270,8 @@ export function createRoutes({ store, people, push, actions, identity, serviceWo
250
270
  })
251
271
  const pushTest = handle(async (request, who) => json(200, await push.test(who.person, await body(request))))
252
272
 
253
- 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' })
254
275
 
255
276
  const worker = async () => new Response(serviceWorker, {
256
277
  status: 200,
@@ -265,6 +286,7 @@ export function createRoutes({ store, people, push, actions, identity, serviceWo
265
286
  get('/events', events),
266
287
  post('/read', read),
267
288
  post('/action', action),
289
+ post('/reply', answer),
268
290
  get('/file', file),
269
291
  get('/push/config', pushConfig),
270
292
  post('/push/state', pushState),