@soffits/dsh-notify-inbox 0.6.0 → 0.8.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,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.8.0
4
+
5
+ - A reply never dead-ends: when the ask names no session, or the one it names is gone, archived, can't be loaded or was a finished helper, it opens a new top-level session with the whole ask quoted in and the session that asked named, so someone can act on it. New options `replyCwd` and `replyPreset` say where that session starts. Every ask has a reply box now, not only those that name a session.
6
+ - The ask's `session` is the one that counts, also when it has none: a notification filed earlier no longer sends a reply to a session the ask has dropped.
7
+
8
+ ## 0.7.0
9
+
10
+ - 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.
11
+ - 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.
12
+
13
+ ## 0.6.1
14
+
15
+ - The reply box has a visible border (it used a colour token DSH doesn't define).
16
+
3
17
  ## 0.6.0
4
18
 
5
19
  - 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
@@ -41,6 +41,8 @@ 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
+ | `replyCwd` | host default | The folder of the new session a reply opens when the ask names no session, or the one it names is gone (below). |
45
+ | `replyPreset` | host default | The agent preset of that new session. |
44
46
 
45
47
  **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.
46
48
 
@@ -67,7 +69,7 @@ Append one JSON object per line to `<dataDir>/<person>/inbox.jsonl` (person ids
67
69
  - `routed`: where else the notification went and whether that worked; shown under the text.
68
70
  - `actions`: buttons, see below.
69
71
  - `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).
72
+ - `session`: the session that asked, for a notification that waits on the person's answer; a reply goes there (below).
71
73
  - `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
74
  - `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
75
  - `handled`: `{ "text", "at"? }`, what was done for the person, shown as one quiet line with a check.
@@ -88,7 +90,9 @@ What waits on the person's answer (a decision, a pick, a small step for someone
88
90
 
89
91
  - 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
92
  - `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.
93
+ - Every opened ask 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 its `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.
94
+ - When the ask names no session, or the one it names is gone, archived, can't be loaded or was a helper (subagent) that has finished, the reply opens a new top-level session instead (in `replyCwd`, with `replyPreset`), whose first message is the words with the whole ask quoted in and the session that asked named, so whoever reads it can act. The ask's `session` is the one that counts: a notification filed about it earlier may name one the ask has since dropped. The reply answers `{ session, fresh }` so the page can say where it went.
95
+ - 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
96
  - 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
97
  - Without `asks.json` nothing changes: notifications keep the group they were filed with.
94
98
 
package/client.js CHANGED
@@ -14,9 +14,9 @@
14
14
  * stream (the inbox files' own changes), never a timer.
15
15
  *
16
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 reply goes into that session as the person, through
19
- * the UI actions' `start`, with the ask quoted in.
17
+ * from their list) shows its points and a reply box: the server puts the
18
+ * reply into the session that asked as the person, with the ask quoted in,
19
+ * or into a new session when that one is gone or the ask names none.
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, fresh: sent.fresh === true })
187
187
  onSent()
188
188
  } catch (reason) {
189
189
  setState({ phase: 'failed', message: reason.message })
@@ -201,7 +201,7 @@ window.__ModuleLoader__.load({
201
201
  h('div', { className: 'nib-replyBar' },
202
202
  h(Button, { variant: 'outline', size: 'sm', disabled: text.trim() === '' || state.phase === 'sending', onClick: send },
203
203
  h(IconSendOutlineRegular, null), ' ', t(state.phase === 'sending' ? 'reply.sending' : 'reply.send')),
204
- state.phase === 'sent' && h('span', { className: 'nib-meta' }, t('reply.sent'), ' ',
204
+ state.phase === 'sent' && h('span', { className: 'nib-meta' }, t(state.fresh ? 'reply.sentNew' : 'reply.sent'), ' ',
205
205
  h(Button, { variant: 'outline', size: 'sm', onClick: () => shared.openSession(state.session) }, t('reply.open'))),
206
206
  state.phase === 'failed' && h('span', { className: 'nib-meta nib-bad', role: 'alert' }, t('reply.failed', { message: state.message }))))
207
207
  }
@@ -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 || item.ask) && 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']
@@ -47,11 +48,15 @@ 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.'),
51
+ replyCwd: z.string().default('')
52
+ .description('The folder of the new session a reply opens when the item names no conversation, or the one it names is gone or archived. Empty means the host default. A leading ~/ means the home folder.'),
53
+ replyPreset: z.string().default('')
54
+ .description('The agent preset of that new session. Empty means the host default.'),
50
55
  })
51
56
 
52
57
  /**
53
58
  * @param {import('@deepseek-ai/cordis').Context} ctx
54
- * @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
59
+ * @param {{ dataDir: string, people: Record<string, string>, peopleFile: string, peopleKey: string, vapidFile: string, vapidSubject: string, domains: Record<string, { icon: string, tone?: string }>, summaryHours: number, replyCwd: string, replyPreset: string }} config
55
60
  */
56
61
  export function apply(ctx, config) {
57
62
  const logger = ctx.logger('notify-inbox')
@@ -76,7 +81,73 @@ export function apply(ctx, config) {
76
81
  warn,
77
82
  })
78
83
  const actions = createActions({ dataDir, events: () => ctx.get('cronJobs'), warn })
79
- const strings = readLocales(fileURLToPath(new URL('./locale/', import.meta.url))).then(tables)
84
+ const localeDir = fileURLToPath(new URL('./locale/', import.meta.url))
85
+ const strings = () => readLocales(localeDir).then(tables)
86
+ // Replies reach sessions through DSH's own services, looked up when one is sent.
87
+ const replyCwd = config.replyCwd ? absolute(config.replyCwd) : ''
88
+ const replyDeps = () => {
89
+ const agents = ctx.get('agents')
90
+ const controller = ctx.get('sessionController')
91
+ const query = ctx.get('sessionQuery')
92
+ if (agents === undefined || controller === undefined || query === undefined) return undefined
93
+ const flush = session => ctx.get('sessions')?.flush?.(session) ?? Promise.resolve(true)
94
+ return {
95
+ liveAgent: id => agents.get(id),
96
+ resolveAgent: async id => {
97
+ const found = await controller.resolveAgent(id)
98
+ if ('error' in found) throw found.error instanceof Error ? found.error : new Error(String(found.error))
99
+ return found.agent
100
+ },
101
+ readHeader: async id => {
102
+ try {
103
+ return (await query.readSession(id))?.session
104
+ } catch (error) {
105
+ if (error?.code === 'SESSION_QUERY_SESSION_NOT_FOUND') return undefined
106
+ throw error
107
+ }
108
+ },
109
+ ended: id => {
110
+ try {
111
+ return ctx.get('workspaceRegistry')?.archivedSessionIds?.includes(id) === true
112
+ } catch {
113
+ return false
114
+ }
115
+ },
116
+ // A new top-level session, the way a scheduled run with a new target opens one.
117
+ openSession: async ({ message, title }) => {
118
+ const { sessionId } = await controller.create({
119
+ ...(replyCwd ? { cwd: replyCwd } : {}),
120
+ ...(config.replyPreset ? { agentPreset: config.replyPreset } : {}),
121
+ })
122
+ const found = await controller.resolveAgent(sessionId)
123
+ if ('error' in found) throw found.error instanceof Error ? found.error : new Error(String(found.error))
124
+ const { agent } = found
125
+ if (replyCwd) {
126
+ try {
127
+ await (await ctx.get('workspaceRegistry')?.resolveByPath(replyCwd))?.attachSession(sessionId)
128
+ } catch (error) {
129
+ warn(`session ${sessionId} did not join the workspace at ${replyCwd}: ${error.message}`)
130
+ }
131
+ }
132
+ try {
133
+ ctx.get('sessionTitle')?.rename(agent.session, title)
134
+ } catch (error) {
135
+ warn(`session ${sessionId} was not named: ${error.message}`)
136
+ }
137
+ agent.followup(message)
138
+ if (!(await flush(agent.session))) throw new Error('the new conversation did not take the reply')
139
+ return sessionId
140
+ },
141
+ flush,
142
+ detached: fn => (agents.withoutInitiator ? agents.withoutInitiator(fn) : fn()),
143
+ warn,
144
+ }
145
+ }
146
+ const reply = async request => {
147
+ const deps = replyDeps()
148
+ if (deps === undefined) throw Object.assign(new Error('Replies need a DSH that lets plugins reach its sessions.'), { status: 503 })
149
+ return sendReply(deps, request)
150
+ }
80
151
  // New records are pushed when the inbox file changes; one scan at a time, and one more if a change came meanwhile.
81
152
  let scanning = null
82
153
  let again = false
@@ -100,7 +171,8 @@ export function apply(ctx, config) {
100
171
  store, people, push, actions, changes,
101
172
  identity: () => ctx.get('requestIdentity'),
102
173
  serviceWorker,
103
- strings: () => strings,
174
+ strings,
175
+ reply,
104
176
  domains: domainMap(config.domains ?? {}),
105
177
  summaryHours: config.summaryHours ?? 12,
106
178
  })
package/locale/en.json CHANGED
@@ -53,6 +53,7 @@
53
53
  "reply.send": "Send",
54
54
  "reply.sending": "Sending…",
55
55
  "reply.sent": "Sent to the conversation.",
56
+ "reply.sentNew": "Sent to a new conversation: the one that asked is no longer open.",
56
57
  "reply.open": "Open it",
57
58
  "reply.failed": "Couldn’t send: {message}",
58
59
  "moved.closed": "Settled."
package/locale/fr.json CHANGED
@@ -53,6 +53,7 @@
53
53
  "reply.send": "Envoyer",
54
54
  "reply.sending": "Envoi…",
55
55
  "reply.sent": "Envoyé dans la conversation.",
56
+ "reply.sentNew": "Envoyé dans une nouvelle conversation : celle qui demandait n’est plus ouverte.",
56
57
  "reply.open": "L’ouvrir",
57
58
  "reply.failed": "Envoi impossible : {message}",
58
59
  "moved.closed": "Réglé."
package/locale/zh.json CHANGED
@@ -53,6 +53,7 @@
53
53
  "reply.send": "发送",
54
54
  "reply.sending": "正在发送…",
55
55
  "reply.sent": "已经发到那个对话里了。",
56
+ "reply.sentNew": "提问的那个对话已经不在了,所以发到了一个新对话里。",
56
57
  "reply.open": "打开对话",
57
58
  "reply.failed": "没发出去:{message}",
58
59
  "moved.closed": "已经处理好了。"
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.8.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,114 @@
1
+ /**
2
+ * A reply to an ask, put into the session that asked, or into a new one.
3
+ *
4
+ * The page posts the person's words; the route has already checked the item is
5
+ * theirs. The words, with the item quoted in the format the UI actions package
6
+ * reads back as a card, go into the session that asked through DSH's own
7
+ * steering: a running session sees them at its next step, an idle or stored
8
+ * one is loaded and starts a turn with them. When the item names no session,
9
+ * or the one it names is gone, archived or a helper that has finished, the
10
+ * reply opens a new top-level session instead, with the whole item quoted, so
11
+ * whoever reads it there can act on it. The sender is the person the server
12
+ * verified (their sign-in's principal, the way the sign-in plugin stamps a
13
+ * message typed in the Web UI), or the owner when the inbox has no people
14
+ * mapping. Every DSH service comes in through `deps`, so the logic is tested
15
+ * without a host.
16
+ */
17
+ import { randomUUID } from 'node:crypto'
18
+
19
+ export const SOURCE_KIND = 'notify-inbox-reply'
20
+ export const MAX_REPLY = 8000
21
+ const QUOTED_LINES = 12
22
+ const FRESH_LINES = 60
23
+ const LINE_MAX = 300
24
+
25
+ /**
26
+ * @typedef {object} Deps
27
+ * @property {(id: string) => any} liveAgent - the loaded Agent of a session, or undefined
28
+ * @property {(id: string) => Promise<any>} resolveAgent - load (resume) a stored session's Agent
29
+ * @property {(id: string) => Promise<{ origin?: string, parentSession?: string } | undefined>} readHeader - a stored session's header
30
+ * @property {(id: string) => boolean} [ended] - whether the session was archived
31
+ * @property {(request: { message: object, title: string }) => Promise<string>} [openSession] - open a new top-level session with this first message; its id
32
+ * @property {(session: any) => Promise<boolean>} [flush] - wait until the session log has the message
33
+ * @property {<T>(fn: () => T) => T} [detached] - run outside whichever turn happens to be current
34
+ * @property {(message: string) => void} [warn]
35
+ */
36
+
37
+ const oneLine = (value, max) => String(value ?? '').replace(/\s+/gu, ' ').trim().slice(0, max)
38
+
39
+ /**
40
+ * The item as quoted text: title, the source line, its text, its context. A
41
+ * reply into the session that asked quotes a few lines; one that opens a new
42
+ * session quotes the whole item and the session that asked, since the new one
43
+ * knows nothing else.
44
+ */
45
+ export function quote(item, { fresh = false } = {}) {
46
+ const max = fresh ? FRESH_LINES : QUOTED_LINES
47
+ const lines = [oneLine(item.title, 200) || '…', '[Item from Inbox (@soffits/dsh-notify-inbox)]']
48
+ for (const line of String(item.text ?? '').split('\n')) {
49
+ if (lines.length >= max) break
50
+ const text = oneLine(line, LINE_MAX)
51
+ if (text !== '') lines.push(text)
52
+ }
53
+ const context = { notification: item.id, ask: item.ask, thread: item.thread || undefined }
54
+ if (fresh && item.asked) context.asked = item.asked
55
+ lines.push(`context: ${JSON.stringify(context)}`)
56
+ return lines.map(line => `> ${line}`).join('\n')
57
+ }
58
+
59
+ /** The sender of a reply: the verified person as their sign-in names them, or none (the owner). */
60
+ export function principalOf(identity) {
61
+ if (identity === null || identity === undefined || typeof identity.id !== 'string') return undefined
62
+ const principal = { kind: `${identity.provider || 'web'}-user`, channel: 'web', id: identity.id }
63
+ if (identity.name) principal.name = String(identity.name)
64
+ if (identity.issuer) principal.issuer = String(identity.issuer)
65
+ return principal
66
+ }
67
+
68
+ /**
69
+ * The loaded Agent of `session` if a reply can still go there: it exists, is
70
+ * not archived and is not a helper. Undefined otherwise.
71
+ * @param {Deps} deps
72
+ */
73
+ async function existing(deps, session) {
74
+ if (typeof session !== 'string' || session === '') return undefined
75
+ if (deps.ended?.(session)) return undefined
76
+ const live = deps.liveAgent(session)
77
+ const header = live?.session?.header ?? await deps.readHeader(session)
78
+ if (header === undefined || header.origin === 'subagent') return undefined
79
+ if (live !== undefined) return live
80
+ try {
81
+ return await deps.resolveAgent(session)
82
+ } catch (error) {
83
+ deps.warn?.(`session ${session} could not be opened for a reply, a new one takes it: ${error.message}`)
84
+ return undefined
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Put one reply into `session`, or into a new session when that one cannot
90
+ * take it. Returns `{ session, woke, fresh }`; throws with a message the page can show.
91
+ * @param {Deps} deps
92
+ */
93
+ export async function send(deps, { session, words, item, identity }) {
94
+ const text = String(words ?? '').trim()
95
+ if (text === '') throw Object.assign(new Error('Write a reply first.'), { status: 400 })
96
+ if (text.length > MAX_REPLY) throw Object.assign(new Error(`A reply is at most ${MAX_REPLY} characters.`), { status: 413 })
97
+ const principal = principalOf(identity)
98
+ const source = principal === undefined ? { kind: SOURCE_KIND } : { kind: SOURCE_KIND, principal }
99
+ const run = async () => {
100
+ const agent = await existing(deps, session)
101
+ if (agent !== undefined) {
102
+ const woke = agent.status !== 'running'
103
+ agent.steer({ id: randomUUID(), role: 'user', content: [{ type: 'text', text: `${text}\n\n${quote(item)}` }], source })
104
+ if (deps.flush && !(await deps.flush(agent.session))) throw new Error('the conversation did not take the reply')
105
+ return { session, woke, fresh: false }
106
+ }
107
+ if (deps.openSession === undefined) throw Object.assign(new Error('The conversation that asked is gone, and this DSH cannot open a new one.'), { status: 503 })
108
+ const quoted = quote({ ...item, asked: typeof session === 'string' && session !== '' ? session : undefined }, { fresh: true })
109
+ const message = { id: randomUUID(), role: 'user', content: [{ type: 'text', text: `${text}\n\n${quoted}` }], source }
110
+ const opened = await deps.openSession({ message, title: oneLine(`Reply: ${oneLine(item.title, 200) || '…'}`, 80) })
111
+ return { session: opened, woke: true, fresh: true }
112
+ }
113
+ return deps.detached ? deps.detached(run) : run()
114
+ }
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 (or a new one)
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 | undefined, 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, 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,28 @@ 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
+ /**
215
+ * A reply to an ask the caller sees, into the session the ask names (its own, else its notification's),
216
+ * or into a new session when it names none or that one is gone (src/reply.js decides).
217
+ */
218
+ const answer = handle(async (request, who) => {
219
+ const value = await body(request)
220
+ const record = await recordOf(who, value.record)
221
+ if (record === undefined) return json(404, { error: 'No such notification.' })
222
+ const ask = (await store.asks(record.person)).asks.find(row => row.id === record.thread || row.id === record.id)
223
+ const session = typeof record.session === 'string' && record.session !== '' ? record.session : undefined
224
+ if (session === undefined && ask === undefined) return json(400, { error: 'This notification is not an ask and names no conversation to reply to.' })
225
+ if (reply === undefined) return json(503, { error: 'Replies need a DSH that lets plugins reach its sessions.' })
226
+ const text = ask !== undefined && ask.text && ask.text !== record.text ? [record.text, ask.text].filter(Boolean).join('\n\n') : record.text
227
+ try {
228
+ const sent = await reply({ session, words: value.text, item: { id: record.id, title: ask?.title ?? record.title, text, thread: record.thread, ask: ask?.id }, identity: identity()?.current?.() ?? undefined })
229
+ await store.setRead(record.person, [record.id], true)
230
+ return json(200, { ok: true, session: sent.session, woke: sent.woke, fresh: sent.fresh === true })
231
+ } catch (error) {
232
+ return json(error.status ?? 502, { error: error.message })
233
+ }
234
+ })
235
+
212
236
  const file = handle(async (request, who) => {
213
237
  const params = new URL(request.url).searchParams
214
238
  const found = await store.file(who.folders, params.get('id') ?? '', params.get('name') ?? '')
@@ -250,7 +274,8 @@ export function createRoutes({ store, people, push, actions, identity, serviceWo
250
274
  })
251
275
  const pushTest = handle(async (request, who) => json(200, await push.test(who.person, await body(request))))
252
276
 
253
- const words = async () => json(200, { tables: await strings() }, { 'cache-control': 'private, max-age=300' })
277
+ // Read for each request and never cached: an update in place brings new words with no stale copy anywhere.
278
+ const words = async () => json(200, { tables: await strings() }, { 'cache-control': 'no-store' })
254
279
 
255
280
  const worker = async () => new Response(serviceWorker, {
256
281
  status: 200,
@@ -265,6 +290,7 @@ export function createRoutes({ store, people, push, actions, identity, serviceWo
265
290
  get('/events', events),
266
291
  post('/read', read),
267
292
  post('/action', action),
293
+ post('/reply', answer),
268
294
  get('/file', file),
269
295
  get('/push/config', pushConfig),
270
296
  post('/push/state', pushState),
package/src/view.js CHANGED
@@ -64,7 +64,8 @@ function askItem(ask, record) {
64
64
  text: record === undefined || record.text === '' ? ask.text : record.text,
65
65
  actions: [...base.actions.filter(action => action.kind !== 'done' && action.kind !== 'snooze'), ...ask.actions],
66
66
  attention: 'needs-you',
67
- session: ask.session ?? base.session,
67
+ // The ask says who asked; a notification about it may name a session the ask has since dropped.
68
+ session: ask.session,
68
69
  ask: { id: ask.id, points: ask.points, next: ask.next, due: ask.due, text: ask.text },
69
70
  read: record === undefined ? ask.read : base.read,
70
71
  }