@soffits/dsh-notify-inbox 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.8.1
4
+
5
+ - A link to an item from another page of the app (`/?notify-inbox=<id>`, pushed in place) opens it; before, only a page load or a push did.
6
+ - `@deepseek-ai/schemastery` is a peer dependency, so an update never moves a private copy out from under the plugin.
7
+
8
+ ## 0.8.0
9
+
10
+ - 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.
11
+ - 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.
12
+
3
13
  ## 0.7.0
4
14
 
5
15
  - 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.
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,10 +90,12 @@ 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. `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.
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.
92
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.
93
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.
94
97
  - Without `asks.json` nothing changes: notifications keep the group they were filed with.
98
+ - `/?notify-inbox=<id>` opens the inbox on one item, an ask (`todo:1a2b...`) or a notification: from a push, on a page load, or from a link on another page of the app that moves there in place (a card's row, for example).
95
99
 
96
100
  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.
97
101
 
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 server puts the reply into that session as the
19
- * person, 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',
@@ -183,7 +183,7 @@ window.__ModuleLoader__.load({
183
183
  try {
184
184
  const sent = await call('reply', { record: item.id, text: words })
185
185
  setText('')
186
- setState({ phase: 'sent', session: 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 && h(Reply, { item, 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')}: `,
@@ -601,14 +601,19 @@ window.__ModuleLoader__.load({
601
601
  }, 100)
602
602
  }
603
603
  ctx.effect(() => {
604
- const params = new URLSearchParams(location.search)
605
- if (params.has(LINK_PARAM)) {
604
+ // A link to an item opens it, at page load and when another page of the app links here in place
605
+ // (it pushes the URL and fires popstate, as DSH's own links do).
606
+ const followLink = () => {
607
+ const params = new URLSearchParams(location.search)
608
+ if (!params.has(LINK_PARAM)) return
606
609
  const id = params.get(LINK_PARAM)
607
610
  params.delete(LINK_PARAM)
608
611
  const query = params.toString()
609
612
  history.replaceState(history.state, '', `${location.pathname}${query ? `?${query}` : ''}${location.hash}`)
610
613
  openLinked(id)
611
614
  }
615
+ followLink()
616
+ window.addEventListener('popstate', followLink)
612
617
  const onMessage = event => {
613
618
  if (event.data?.type !== 'notify-inbox/open') return
614
619
  try {
@@ -619,7 +624,10 @@ window.__ModuleLoader__.load({
619
624
  }
620
625
  navigator.serviceWorker?.addEventListener('message', onMessage)
621
626
  navigator.serviceWorker?.startMessages?.()
622
- return () => navigator.serviceWorker?.removeEventListener('message', onMessage)
627
+ return () => {
628
+ window.removeEventListener('popstate', followLink)
629
+ navigator.serviceWorker?.removeEventListener('message', onMessage)
630
+ }
623
631
  }, 'notify-inbox: links')
624
632
  },
625
633
  }
package/index.js CHANGED
@@ -48,11 +48,15 @@ export const Config = z.object({
48
48
  .description('How each domain (the record\'s domain field) is drawn, on top of the built-in defaults (mail, money, health, travel, home...).'),
49
49
  summaryHours: z.natural().min(1).max(168).default(12)
50
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.'),
51
55
  })
52
56
 
53
57
  /**
54
58
  * @param {import('@deepseek-ai/cordis').Context} ctx
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
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
56
60
  */
57
61
  export function apply(ctx, config) {
58
62
  const logger = ctx.logger('notify-inbox')
@@ -80,21 +84,63 @@ export function apply(ctx, config) {
80
84
  const localeDir = fileURLToPath(new URL('./locale/', import.meta.url))
81
85
  const strings = () => readLocales(localeDir).then(tables)
82
86
  // Replies reach sessions through DSH's own services, looked up when one is sent.
87
+ const replyCwd = config.replyCwd ? absolute(config.replyCwd) : ''
83
88
  const replyDeps = () => {
84
89
  const agents = ctx.get('agents')
85
90
  const controller = ctx.get('sessionController')
86
91
  const query = ctx.get('sessionQuery')
87
92
  if (agents === undefined || controller === undefined || query === undefined) return undefined
93
+ const flush = session => ctx.get('sessions')?.flush?.(session) ?? Promise.resolve(true)
88
94
  return {
89
95
  liveAgent: id => agents.get(id),
90
96
  resolveAgent: async id => {
91
97
  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 })
98
+ if ('error' in found) throw found.error instanceof Error ? found.error : new Error(String(found.error))
93
99
  return found.agent
94
100
  },
95
- readHeader: async id => (await query.readSession(id))?.session,
96
- flush: session => ctx.get('sessions')?.flush?.(session) ?? Promise.resolve(true),
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,
97
142
  detached: fn => (agents.withoutInitiator ? agents.withoutInitiator(fn) : fn()),
143
+ warn,
98
144
  }
99
145
  }
100
146
  const reply = async request => {
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.7.0",
3
+ "version": "0.8.1",
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",
@@ -62,11 +62,14 @@
62
62
  "check": "for f in index.js client.js src/*.js test/*.js; do node --check \"$f\" || exit 1; done",
63
63
  "test": "node --test test/*.test.js"
64
64
  },
65
- "dependencies": {
66
- "@deepseek-ai/schemastery": "3.18.5"
67
- },
68
65
  "engines": {
69
66
  "node": ">=22",
70
67
  "dsh": ">=0.2.2-rc.1 <0.3.0-0"
68
+ },
69
+ "peerDependencies": {
70
+ "@deepseek-ai/schemastery": "^3.18.5"
71
+ },
72
+ "devDependencies": {
73
+ "@deepseek-ai/schemastery": "3.18.5"
71
74
  }
72
75
  }
package/src/reply.js CHANGED
@@ -1,21 +1,25 @@
1
1
  /**
2
- * A reply to an ask, put into the session that asked.
2
+ * A reply to an ask, put into the session that asked, or into a new one.
3
3
  *
4
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.
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.
13
16
  */
14
17
  import { randomUUID } from 'node:crypto'
15
18
 
16
19
  export const SOURCE_KIND = 'notify-inbox-reply'
17
20
  export const MAX_REPLY = 8000
18
21
  const QUOTED_LINES = 12
22
+ const FRESH_LINES = 60
19
23
  const LINE_MAX = 300
20
24
 
21
25
  /**
@@ -23,21 +27,32 @@ const LINE_MAX = 300
23
27
  * @property {(id: string) => any} liveAgent - the loaded Agent of a session, or undefined
24
28
  * @property {(id: string) => Promise<any>} resolveAgent - load (resume) a stored session's Agent
25
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
26
32
  * @property {(session: any) => Promise<boolean>} [flush] - wait until the session log has the message
27
33
  * @property {<T>(fn: () => T) => T} [detached] - run outside whichever turn happens to be current
34
+ * @property {(message: string) => void} [warn]
28
35
  */
29
36
 
30
37
  const oneLine = (value, max) => String(value ?? '').replace(/\s+/gu, ' ').trim().slice(0, max)
31
38
 
32
- /** The item as quoted text: title, the source line, a few lines of text, its context. */
33
- export function quote(item) {
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
34
47
  const lines = [oneLine(item.title, 200) || '…', '[Item from Inbox (@soffits/dsh-notify-inbox)]']
35
48
  for (const line of String(item.text ?? '').split('\n')) {
36
- if (lines.length >= QUOTED_LINES) break
49
+ if (lines.length >= max) break
37
50
  const text = oneLine(line, LINE_MAX)
38
51
  if (text !== '') lines.push(text)
39
52
  }
40
- lines.push(`context: ${JSON.stringify({ notification: item.id, ask: item.ask, thread: item.thread || undefined })}`)
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)}`)
41
56
  return lines.map(line => `> ${line}`).join('\n')
42
57
  }
43
58
 
@@ -51,25 +66,49 @@ export function principalOf(identity) {
51
66
  }
52
67
 
53
68
  /**
54
- * Put one reply into `session`. Returns `{ session, woke }`; throws with a message the page can show.
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.
55
91
  * @param {Deps} deps
56
92
  */
57
93
  export async function send(deps, { session, words, item, identity }) {
58
94
  const text = String(words ?? '').trim()
59
95
  if (text === '') throw Object.assign(new Error('Write a reply first.'), { status: 400 })
60
96
  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
97
  const principal = principalOf(identity)
66
98
  const source = principal === undefined ? { kind: SOURCE_KIND } : { kind: SOURCE_KIND, principal }
67
99
  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 }
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 }
73
112
  }
74
113
  return deps.detached ? deps.detached(run) : run()
75
114
  }
package/src/routes.js CHANGED
@@ -6,7 +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
+ * POST /api/notify-inbox/reply { record, text } a reply to an ask, put into the session that asked (or a new one)
10
10
  * POST /api/notify-inbox/read { ids: [...], read?: false } or { all: true }
11
11
  * POST /api/notify-inbox/action { record, action, until? } a done/snooze/event press (record: a
12
12
  * record id or an ask's id; an ask's own buttons win in its thread)
@@ -69,7 +69,7 @@ async function body(request) {
69
69
  * @param {() => object | undefined} options.identity - the requestIdentity service right now, if any
70
70
  * @param {string} options.serviceWorker - the service worker's source
71
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)
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)
73
73
  * @param {ReturnType<import('./changes.js').createChanges>} options.changes
74
74
  * @param {Record<string, { icon: string, tone?: string }>} options.domains - the domain map (src/domains.js)
75
75
  * @param {number} options.summaryHours - how long a summary line is shown
@@ -180,7 +180,7 @@ export function createRoutes({ store, people, push, actions, identity, serviceWo
180
180
  const { asks } = await store.asks(person)
181
181
  const record = (await store.records(person)).records.find(row => row.id === id)
182
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] }
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] }
184
184
  if (ask !== undefined) return { ...ask, key: '', thread: ask.id }
185
185
  }
186
186
  return undefined
@@ -211,19 +211,23 @@ export function createRoutes({ store, people, push, actions, identity, serviceWo
211
211
  return json(200, { press: result.event.press, published: result.published, matched: result.matched ?? 0 })
212
212
  })
213
213
 
214
- /** A reply to an ask the caller sees, into the session the ask names (its own, else its notification's). */
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
+ */
215
218
  const answer = handle(async (request, who) => {
216
219
  const value = await body(request)
217
220
  const record = await recordOf(who, value.record)
218
221
  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.' })
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.' })
221
225
  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
226
+ const text = ask !== undefined && ask.text && ask.text !== record.text ? [record.text, ask.text].filter(Boolean).join('\n\n') : record.text
223
227
  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 })
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 })
225
229
  await store.setRead(record.person, [record.id], true)
226
- return json(200, { ok: true, session: sent.session, woke: sent.woke })
230
+ return json(200, { ok: true, session: sent.session, woke: sent.woke, fresh: sent.fresh === true })
227
231
  } catch (error) {
228
232
  return json(error.status ?? 502, { error: error.message })
229
233
  }
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
  }