@soffits/dsh-notify-inbox 0.3.0 → 0.5.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/docs/ui.md ADDED
@@ -0,0 +1,36 @@
1
+ # What the page is made of
2
+
3
+ The inbox page should look like it always was part of DSH, so it is built from DSH's own pieces first, then the shared kit, and only a little of its own.
4
+
5
+ ## DSH's own
6
+
7
+ From `@deepseek-ai/dsh-client-ui-primitives`, which DSH puts in every plugin's module table (`require` at runtime, no copy):
8
+
9
+ | Piece | Where |
10
+ |---|---|
11
+ | `Button` (outline, small) | Mark all read, Mark unread, Show older, the ⋯ trigger |
12
+ | `Pill` | The Needs you / All filters, as on the Automation page |
13
+ | `Menu`, `Tooltip` | The ⋯ menu: notifications on this device, a test push |
14
+ | `StateDot` | The green dot on a live item |
15
+ | `IconCheckCircleOutlineRegular`, `IconEllipsisOutlineRegular` | The handled check, the ⋯ trigger |
16
+ | Theme tokens (`--dsw-alias-*`) | Every colour, so light and dark follow the Web UI |
17
+
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.
19
+
20
+ `test/client-names.test.js` checks every primitive the page takes against the export list of the oldest DSH it supports (`test/fixtures/`), so a wrong name fails a test instead of the page.
21
+
22
+ ## The shared kit
23
+
24
+ From [@soffits/dsh-ui-kit](https://github.com/soffits/dsh-ui-kit) (`ctx.uiKit`), for what DSH has no piece for and other plugin pages need too: `Tile` and `Icon` (a domain's Lucide icon on a tinted tile), `TimeAgo` and `TimeUntil` (times that tick, full date on hover), `LiveStatus` and `useEventStream` (the live line and the events stream), `useWash` and `NewDot` (the two-second cue on an item that just changed, the unread dot), `History` (a thread's earlier entries), `Progress` (a live item's bar through time) and `Suggested` (the suggested steps). The buttons themselves come from [@soffits/dsh-ui-actions](https://github.com/soffits/dsh-ui-actions).
25
+
26
+ ## Ours
27
+
28
+ About forty lines of CSS in `client.js`, only for layout DSH doesn't expose:
29
+
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
+ - **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.
33
+ - **The unread badge on the sidebar bell**: DSH's sidebar has no count badge for an entry.
34
+ - **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
+
36
+ Nothing else: no colours, fonts or shadows of its own.
package/index.js CHANGED
@@ -15,6 +15,8 @@ import { fileURLToPath } from 'node:url'
15
15
  import z from '@deepseek-ai/schemastery'
16
16
  import { createPeople, expandHome } from './src/access.js'
17
17
  import { createActions } from './src/actions.js'
18
+ import { createChanges } from './src/changes.js'
19
+ import { TONES, domainMap } from './src/domains.js'
18
20
  import { createPush } from './src/push.js'
19
21
  import { createRoutes } from './src/routes.js'
20
22
  import { createStore } from './src/store.js'
@@ -38,13 +40,20 @@ export const Config = z.object({
38
40
  .description('Where the Web Push (VAPID) key pair is kept; made on first start, mode 600. Default: .push/vapid.json in dataDir.'),
39
41
  vapidSubject: z.string().default('mailto:admin@example.invalid')
40
42
  .description('A mailto: or https: contact that push services can reach about this server.'),
43
+ domains: z.dict(z.object({
44
+ icon: z.string().description('A Lucide icon name, such as plane or heart-pulse.'),
45
+ tone: z.union([...TONES]).description('A colour this domain keeps wherever it shows. Usually left out: the group gives the colour.'),
46
+ })).default({})
47
+ .description('How each domain (the record\'s domain field) is drawn, on top of the built-in defaults (mail, money, health, travel, home...).'),
48
+ summaryHours: z.natural().min(1).max(168).default(12)
49
+ .description('How long the summary line (<dataDir>/<person>/summary.json) is shown after it was written.'),
41
50
  pollSeconds: z.natural().min(2).max(3600).default(5)
42
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).'),
43
52
  })
44
53
 
45
54
  /**
46
55
  * @param {import('@deepseek-ai/cordis').Context} ctx
47
- * @param {{ dataDir: string, people: Record<string, string>, peopleFile: string, peopleKey: string, vapidFile: string, vapidSubject: string, pollSeconds: number }} config
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
48
57
  */
49
58
  export function apply(ctx, config) {
50
59
  const logger = ctx.logger('notify-inbox')
@@ -71,7 +80,16 @@ export function apply(ctx, config) {
71
80
  const actions = createActions({ dataDir, events: () => ctx.get('cronJobs'), warn })
72
81
  const pollSeconds = config.pollSeconds ?? 5
73
82
  const strings = readLocales(fileURLToPath(new URL('./locale/', import.meta.url))).then(tables)
74
- const routes = createRoutes({ store, people, push, actions, identity: () => ctx.get('requestIdentity'), serviceWorker, strings: () => strings, pollSeconds: Math.max(pollSeconds, 15) })
83
+ const changes = createChanges({ dataDir, persons: () => store.persons() })
84
+ const routes = createRoutes({
85
+ store, people, push, actions, changes,
86
+ identity: () => ctx.get('requestIdentity'),
87
+ serviceWorker,
88
+ strings: () => strings,
89
+ domains: domainMap(config.domains ?? {}),
90
+ summaryHours: config.summaryHours ?? 12,
91
+ pollSeconds: Math.max(pollSeconds, 15),
92
+ })
75
93
  for (const route of routes) ctx.connection.fetch.register(route)
76
94
 
77
95
  let stopped = false
@@ -88,6 +106,7 @@ export function apply(ctx, config) {
88
106
  ctx.on('dispose', () => {
89
107
  stopped = true
90
108
  clearTimeout(timer)
109
+ changes.stop()
91
110
  })
92
111
  logger.info(`inbox at ${dataDir} (${people.enabled ? 'per person' : 'single owner'})`)
93
112
  }
package/locale/en.json CHANGED
@@ -6,14 +6,11 @@
6
6
  "ui": {
7
7
  "panel": "Inbox",
8
8
  "title": "Inbox",
9
- "filter.unread": "Unread",
10
9
  "filter.all": "All",
11
10
  "markAll": "Mark all read",
12
11
  "markUnread": "Mark unread",
13
- "empty.unread": "Nothing unread.",
14
12
  "empty.all": "No notifications yet.",
15
13
  "loadMore": "Show older",
16
- "urgent": "Urgent",
17
14
  "test": "Test",
18
15
  "alsoSent": "Also sent to",
19
16
  "notSent": "Not sent anywhere else",
@@ -23,9 +20,9 @@
23
20
  "press.unhandled": "Nobody picked this up yet",
24
21
  "press.done": "Marked done",
25
22
  "press.snoozed": "Will remind you {time}",
23
+ "press.started": "Started",
26
24
  "push.title": "Notifications on this device",
27
- "push.on": "On",
28
- "push.off": "Off",
25
+ "push.on": "on",
29
26
  "push.enable": "Turn on",
30
27
  "push.disable": "Turn off",
31
28
  "push.test": "Send a test",
@@ -36,6 +33,18 @@
36
33
  "error": "Couldn’t load: {message}",
37
34
  "time.locale": "en-US",
38
35
  "push.testTitle": "Inbox",
39
- "push.testBody": "Notifications reach this device."
36
+ "push.testBody": "Notifications reach this device.",
37
+ "filter.label": "Show",
38
+ "group.needs-you": "Needs you",
39
+ "group.live": "Live",
40
+ "group.handled": "Handled",
41
+ "group.info": "To know",
42
+ "empty.needs-you": "Nothing needs you right now.",
43
+ "moved.done": "You marked it done.",
44
+ "moved.ended": "Ended",
45
+ "more": "More",
46
+ "push.off": "off",
47
+ "push.unavailable": "not available here",
48
+ "kitMissing": "This page needs the @soffits/dsh-ui-kit plugin."
40
49
  }
41
50
  }
package/locale/fr.json CHANGED
@@ -6,14 +6,11 @@
6
6
  "ui": {
7
7
  "panel": "Notifications",
8
8
  "title": "Notifications",
9
- "filter.unread": "Non lues",
10
9
  "filter.all": "Toutes",
11
10
  "markAll": "Tout marquer comme lu",
12
11
  "markUnread": "Marquer comme non lu",
13
- "empty.unread": "Rien de non lu.",
14
- "empty.all": "Pas encore de notifications.",
12
+ "empty.all": "Aucune notification pour l’instant.",
15
13
  "loadMore": "Plus anciennes",
16
- "urgent": "Urgent",
17
14
  "test": "Test",
18
15
  "alsoSent": "Aussi envoyé à",
19
16
  "notSent": "Envoyé nulle part ailleurs",
@@ -23,9 +20,9 @@
23
20
  "press.unhandled": "Personne ne l’a encore pris en charge",
24
21
  "press.done": "Marqué comme fait",
25
22
  "press.snoozed": "Rappel {time}",
23
+ "press.started": "Lancé",
26
24
  "push.title": "Notifications sur cet appareil",
27
- "push.on": "Activées",
28
- "push.off": "Désactivées",
25
+ "push.on": "activées",
29
26
  "push.enable": "Activer",
30
27
  "push.disable": "Désactiver",
31
28
  "push.test": "Envoyer un test",
@@ -36,6 +33,18 @@
36
33
  "error": "Chargement impossible : {message}",
37
34
  "time.locale": "fr-FR",
38
35
  "push.testTitle": "Notifications",
39
- "push.testBody": "Les notifications arrivent sur cet appareil."
36
+ "push.testBody": "Les notifications arrivent sur cet appareil.",
37
+ "filter.label": "Afficher",
38
+ "group.needs-you": "Pour vous",
39
+ "group.live": "En cours",
40
+ "group.handled": "Réglé",
41
+ "group.info": "À savoir",
42
+ "empty.needs-you": "Rien ne vous attend pour l’instant.",
43
+ "moved.done": "Vous l’avez marqué comme fait.",
44
+ "moved.ended": "Terminé",
45
+ "more": "Plus",
46
+ "push.off": "désactivées",
47
+ "push.unavailable": "indisponibles ici",
48
+ "kitMissing": "Cette page a besoin du plugin @soffits/dsh-ui-kit."
40
49
  }
41
50
  }
package/locale/zh.json CHANGED
@@ -6,14 +6,11 @@
6
6
  "ui": {
7
7
  "panel": "收件箱",
8
8
  "title": "收件箱",
9
- "filter.unread": "未读",
10
9
  "filter.all": "全部",
11
10
  "markAll": "全部已读",
12
11
  "markUnread": "标为未读",
13
- "empty.unread": "没有未读通知。",
14
12
  "empty.all": "还没有通知。",
15
13
  "loadMore": "更早的",
16
- "urgent": "紧急",
17
14
  "test": "测试",
18
15
  "alsoSent": "同时发到",
19
16
  "notSent": "没有发到别处",
@@ -23,9 +20,9 @@
23
20
  "press.unhandled": "暂时没有人处理",
24
21
  "press.done": "已标为完成",
25
22
  "press.snoozed": "会在{time}再提醒",
23
+ "press.started": "已开始",
26
24
  "push.title": "本设备的通知",
27
25
  "push.on": "已开启",
28
- "push.off": "未开启",
29
26
  "push.enable": "开启",
30
27
  "push.disable": "关闭",
31
28
  "push.test": "发一条测试",
@@ -36,6 +33,18 @@
36
33
  "error": "加载失败:{message}",
37
34
  "time.locale": "zh-CN",
38
35
  "push.testTitle": "收件箱",
39
- "push.testBody": "这台设备能收到通知了。"
36
+ "push.testBody": "这台设备能收到通知了。",
37
+ "filter.label": "显示",
38
+ "group.needs-you": "待你处理",
39
+ "group.live": "进行中",
40
+ "group.handled": "已处理",
41
+ "group.info": "知道就好",
42
+ "empty.needs-you": "现在没有要你处理的事。",
43
+ "moved.done": "你已标记为完成。",
44
+ "moved.ended": "已结束",
45
+ "more": "更多",
46
+ "push.off": "已关闭",
47
+ "push.unavailable": "这里不可用",
48
+ "kitMissing": "这个页面需要 @soffits/dsh-ui-kit 插件。"
40
49
  }
41
50
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soffits/dsh-notify-inbox",
3
- "version": "0.3.0",
3
+ "version": "0.5.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",
@@ -13,7 +13,15 @@
13
13
  "bugs": {
14
14
  "url": "https://github.com/soffits/dsh-notify-inbox/issues"
15
15
  },
16
- "keywords": ["dsh", "dsh-plugin", "deepseek-harness", "notifications", "inbox", "web-push", "pwa"],
16
+ "keywords": [
17
+ "dsh",
18
+ "dsh-plugin",
19
+ "deepseek-harness",
20
+ "notifications",
21
+ "inbox",
22
+ "web-push",
23
+ "pwa"
24
+ ],
17
25
  "main": "./index.js",
18
26
  "exports": {
19
27
  ".": "./index.js",
@@ -22,7 +30,18 @@
22
30
  "./icon": "./icon.svg",
23
31
  "./package.json": "./package.json"
24
32
  },
25
- "files": ["src", "client.js", "index.js", "cordis.patch.yml", "locale/*.json", "icon.svg", "README.md", "CHANGELOG.md", "LICENSE"],
33
+ "files": [
34
+ "src",
35
+ "client.js",
36
+ "index.js",
37
+ "cordis.patch.yml",
38
+ "locale/*.json",
39
+ "icon.svg",
40
+ "README.md",
41
+ "CHANGELOG.md",
42
+ "LICENSE",
43
+ "docs/*.md"
44
+ ],
26
45
  "dsh": {
27
46
  "bundle": {
28
47
  "patch": "./cordis.patch.yml"
@@ -32,6 +51,7 @@
32
51
  "immediately": true,
33
52
  "inject": [
34
53
  "@deepseek-ai/dsh-client-locale",
54
+ "@soffits/dsh-ui-kit",
35
55
  "@soffits/dsh-ui-actions",
36
56
  "@deepseek-ai/dsh-client-ui-layout",
37
57
  "@deepseek-ai/dsh-client-ui-sidebar"
@@ -47,6 +67,6 @@
47
67
  },
48
68
  "engines": {
49
69
  "node": ">=22",
50
- "dsh": ">=0.2.1-rc.2 <0.3.0"
70
+ "dsh": ">=0.2.2-rc.1 <0.3.0-0"
51
71
  }
52
72
  }
package/src/actions.js CHANGED
@@ -12,7 +12,8 @@ import { appendFile, mkdir, readFile } from 'node:fs/promises'
12
12
  import { randomBytes } from 'node:crypto'
13
13
  import { join } from 'node:path'
14
14
 
15
- export const EMITTING = ['done', 'snooze', 'event']
15
+ /** Kinds whose press is recorded here: a step's press is the person's go-ahead for what its label says. */
16
+ export const EMITTING = ['step', 'done', 'snooze', 'event']
16
17
  const ACTIONS_LOG = 'actions.jsonl'
17
18
 
18
19
  /** The event a press becomes (same shape as the practice's actions spec). */
@@ -77,7 +78,7 @@ export function createActions({ dataDir, events, warn }) {
77
78
  const event = JSON.parse(line)
78
79
  const id = event?.source?.record
79
80
  if (typeof id !== 'string') continue
80
- out.set(id, [...(out.get(id) ?? []), { press: event.press, action: event.action, at: event.at, until: event.payload?.until }])
81
+ out.set(id, [...(out.get(id) ?? []), { press: event.press, action: event.action, id: event.id, at: event.at, until: event.payload?.until }])
81
82
  } catch {
82
83
  // A torn line is skipped.
83
84
  }
package/src/changes.js ADDED
@@ -0,0 +1,75 @@
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.
8
+ */
9
+ import { stat } from 'node:fs/promises'
10
+ import { join } from 'node:path'
11
+
12
+ const FILES = ['inbox.jsonl', 'read.json', 'actions.jsonl', 'summary.json']
13
+
14
+ /**
15
+ * @param {object} options
16
+ * @param {string} options.dataDir
17
+ * @param {() => Promise<string[]>} options.persons - every inbox folder there is
18
+ * @param {number} [options.intervalMs]
19
+ */
20
+ export function createChanges({ dataDir, persons, intervalMs = 2000 }) {
21
+ const listeners = new Set()
22
+ const seen = new Map() // person -> signature
23
+ let running = false
24
+ let timer
25
+
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('|')
31
+ }
32
+
33
+ /** One look at every folder; the loop goes on while anyone listens and ends by itself after. */
34
+ async function tick() {
35
+ 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()
49
+ }
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Hear about changes to these folders (null: every folder, for an owner who sees them all).
55
+ * @returns {() => void} stop listening
56
+ */
57
+ function listen(folders, send) {
58
+ const listener = { folders, send }
59
+ listeners.add(listener)
60
+ if (!running) {
61
+ running = true
62
+ timer = setTimeout(tick, 0)
63
+ }
64
+ return () => listeners.delete(listener)
65
+ }
66
+
67
+ /** Stop at once (the plugin is going away). */
68
+ function stop() {
69
+ listeners.clear()
70
+ clearTimeout(timer)
71
+ running = false
72
+ }
73
+
74
+ return { listen, stop, tick }
75
+ }
package/src/domains.js ADDED
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The icon (and optionally the colour) each domain is drawn with. Records
3
+ * already carry a `domain` (mail, money, home...); these defaults cover the
4
+ * common ones and the `domains` setting adds or replaces entries. Icons are
5
+ * Lucide names drawn by @soffits/dsh-ui-kit. A domain names no colour by
6
+ * default: an item's colour says what it needs (its group), so a page of
7
+ * notifications isn't a rainbow; set `tone` only for a domain that should
8
+ * stand out wherever it shows.
9
+ */
10
+ export const TONES = ['ok', 'warn', 'bad', 'accent', 'violet', 'muted']
11
+
12
+ export const DEFAULT_DOMAINS = {
13
+ general: { icon: 'bell' },
14
+ mail: { icon: 'mail' },
15
+ calendar: { icon: 'calendar' },
16
+ money: { icon: 'wallet' },
17
+ bills: { icon: 'receipt' },
18
+ orders: { icon: 'package' },
19
+ shopping: { icon: 'shopping-cart' },
20
+ health: { icon: 'heart-pulse' },
21
+ medication: { icon: 'pill' },
22
+ food: { icon: 'utensils' },
23
+ travel: { icon: 'plane' },
24
+ weather: { icon: 'cloud-sun' },
25
+ home: { icon: 'house' },
26
+ people: { icon: 'users' },
27
+ work: { icon: 'briefcase' },
28
+ legal: { icon: 'scale' },
29
+ learning: { icon: 'graduation-cap' },
30
+ media: { icon: 'clapperboard' },
31
+ games: { icon: 'gamepad-2' },
32
+ news: { icon: 'newspaper' },
33
+ safety: { icon: 'shield-alert' },
34
+ upkeep: { icon: 'wrench' },
35
+ system: { icon: 'server' },
36
+ jobs: { icon: 'timer' },
37
+ test: { icon: 'terminal' },
38
+ }
39
+
40
+ /** The defaults with the configured entries on top; entries with an unknown tone keep only their icon. */
41
+ export function domainMap(configured = {}) {
42
+ const out = { ...DEFAULT_DOMAINS }
43
+ for (const [name, entry] of Object.entries(configured)) {
44
+ const icon = typeof entry?.icon === 'string' && entry.icon !== '' ? entry.icon : out[name]?.icon
45
+ const tone = TONES.includes(entry?.tone) ? entry.tone : undefined
46
+ out[name] = tone === undefined ? { icon } : { icon, tone }
47
+ }
48
+ return out
49
+ }
package/src/routes.js CHANGED
@@ -3,8 +3,9 @@
3
3
  * browser first and a `requestIdentity` provider sees the request; every
4
4
  * answer is decided here, per request, from who is asking.
5
5
  *
6
- * GET /api/notify-inbox/summary unread count and newest time (badge)
7
- * GET /api/notify-inbox/items?unread=1&keep=&before=&limit=
6
+ * GET /api/notify-inbox/summary counts per group, unread, the summary line, the domain map
7
+ * GET /api/notify-inbox/items?view=needs-you&keep=&before=&limit=
8
+ * GET /api/notify-inbox/events text/event-stream: a notice whenever the caller's inbox changed
8
9
  * POST /api/notify-inbox/read { ids: [...], read?: false } or { all: true }
9
10
  * POST /api/notify-inbox/action { record, action, until? } a done/snooze/event press
10
11
  * GET /api/notify-inbox/file?id=&name= a stored attachment
@@ -19,13 +20,17 @@
19
20
  import { readFile } from 'node:fs/promises'
20
21
  import { extname } from 'node:path'
21
22
  import { viewerOf } from './access.js'
23
+ import { EMITTING } from './actions.js'
22
24
  import { PERSON_PATTERN, RECORD_ID_PATTERN } from './store.js'
25
+ import { buildItems, countItems } from './view.js'
23
26
 
24
27
  export const PREFIX = '/api/notify-inbox'
25
28
  const MAX_BODY = 16 * 1024
26
29
  const PAGE = 50
27
- /** Most rows the Unread view keeps on screen after they turn read (ids in `keep`). */
30
+ /** Most items a filtered view keeps on screen after they leave it (keys in `keep`). */
28
31
  const KEEP_MAX = 200
32
+ const ITEM_KEY = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,79}$/
33
+ const HEARTBEAT_MS = 25 * 1000
29
34
 
30
35
  const HEADERS = {
31
36
  'content-type': 'application/json; charset=utf-8',
@@ -62,9 +67,12 @@ async function body(request) {
62
67
  * @param {() => object | undefined} options.identity - the requestIdentity service right now, if any
63
68
  * @param {string} options.serviceWorker - the service worker's source
64
69
  * @param {() => Promise<Record<string, Record<string, string>>>} [options.strings] - the page's words, complete per tag
70
+ * @param {ReturnType<import('./changes.js').createChanges>} options.changes
71
+ * @param {Record<string, { icon: string, tone?: string }>} options.domains - the domain map (src/domains.js)
72
+ * @param {number} options.summaryHours - how long a summary line is shown
65
73
  * @param {number} options.pollSeconds
66
74
  */
67
- export function createRoutes({ store, people, push, actions, identity, serviceWorker, strings = async () => ({}), pollSeconds }) {
75
+ export function createRoutes({ store, people, push, actions, identity, serviceWorker, strings = async () => ({}), changes, domains, summaryHours, pollSeconds }) {
68
76
  /** Who is asking, as the inbox folders they may read; undefined with the response to send instead. */
69
77
  async function caller() {
70
78
  const viewer = await viewerOf(people, identity())
@@ -90,31 +98,76 @@ export function createRoutes({ store, people, push, actions, identity, serviceWo
90
98
  return items.map(item => ({ ...item, presses: byPerson.get(item.person)?.get(item.id) ?? [] }))
91
99
  }
92
100
 
101
+ /** The caller's items, folded and grouped as of now. */
102
+ async function itemsOf(who) {
103
+ const { items: records, bad } = await store.view(who.folders)
104
+ return { items: buildItems(records, Date.now()), bad }
105
+ }
106
+
93
107
  const summary = handle(async (_request, who) => {
94
- const { items, bad } = await store.view(who.folders)
95
- const unread = items.filter(item => !item.read).length
96
- const handled = items.reduce((sum, item) => sum + item.handled.length, 0)
97
- return json(200, { mode: who.mode, person: who.person, unread, total: items.length, handled, latest: items[0]?.time ?? null, problems: { badLines: bad }, pollSeconds })
108
+ const [{ items, bad }, line] = await Promise.all([itemsOf(who), store.summaryLine(who.folders, summaryHours)])
109
+ const { groups, unread } = countItems(items)
110
+ 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 })
98
112
  })
99
113
 
100
114
  const list = handle(async (request, who) => {
101
115
  const params = new URL(request.url).searchParams
102
116
  const limit = Math.min(Math.max(Number(params.get('limit')) || PAGE, 1), 200)
103
- let { items } = await store.view(who.folders)
104
- if (params.get('unread') === '1') {
105
- // `keep` holds what the page already shows under Unread, so those rows stay put as they turn read.
106
- const keep = new Set((params.get('keep') ?? '').split(',').filter(id => RECORD_ID_PATTERN.test(id)).slice(0, KEEP_MAX))
107
- items = items.filter(item => !item.read || keep.has(item.id))
117
+ let { items } = await itemsOf(who)
118
+ if (params.get('view') === 'needs-you') {
119
+ // `keep` holds what the page already shows in this view, so those items stay put as they leave it.
120
+ const keep = new Set((params.get('keep') ?? '').split(',').filter(key => ITEM_KEY.test(key)).slice(0, KEEP_MAX))
121
+ items = items.filter(item => item.group === 'needs-you' || keep.has(item.key))
108
122
  }
109
123
  const before = params.get('before')
110
124
  if (before) {
111
- const at = items.findIndex(item => item.id === before)
125
+ const at = items.findIndex(item => item.key === before)
112
126
  items = at < 0 ? [] : items.slice(at + 1)
113
127
  }
114
128
  const page = items.slice(0, limit)
115
129
  return json(200, { items: await withPresses(who, page), more: items.length > limit })
116
130
  })
117
131
 
132
+ /** A notice per change, a comment every 25 s so proxies keep the stream open; ends when the page goes. */
133
+ const events = handle(async (request, who) => {
134
+ const encoder = new TextEncoder()
135
+ let stop = () => {}
136
+ const stream = new ReadableStream({
137
+ start(controller) {
138
+ const write = chunk => {
139
+ try {
140
+ controller.enqueue(encoder.encode(chunk))
141
+ } catch {
142
+ stop()
143
+ }
144
+ }
145
+ write('retry: 5000\n: open\n\n')
146
+ const unlisten = changes.listen(who.mode === 'owner' ? null : who.folders, () => write(`data: ${JSON.stringify({ type: 'change', at: new Date().toISOString() })}\n\n`))
147
+ const beat = setInterval(() => write(': beat\n\n'), HEARTBEAT_MS)
148
+ stop = () => {
149
+ unlisten()
150
+ clearInterval(beat)
151
+ }
152
+ request.signal?.addEventListener('abort', () => {
153
+ stop()
154
+ try {
155
+ controller.close()
156
+ } catch {
157
+ // Already closed.
158
+ }
159
+ }, { once: true })
160
+ },
161
+ cancel() {
162
+ stop()
163
+ },
164
+ })
165
+ return new Response(stream, {
166
+ status: 200,
167
+ headers: { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'private, no-cache, no-transform', 'x-accel-buffering': 'no', 'x-content-type-options': 'nosniff' },
168
+ })
169
+ })
170
+
118
171
  /** The record with this id the caller may see, or undefined. */
119
172
  async function recordOf(who, id) {
120
173
  if (typeof id !== 'string' || !RECORD_ID_PATTERN.test(id)) return undefined
@@ -144,7 +197,7 @@ export function createRoutes({ store, people, push, actions, identity, serviceWo
144
197
  if (record === undefined) return json(404, { error: 'No such notification.' })
145
198
  const declared = record.actions.find(row => row.id === value.action)
146
199
  if (declared === undefined) return json(400, { error: 'This notification has no such button.' })
147
- if (!['done', 'snooze', 'event'].includes(declared.kind)) return json(400, { error: 'This button acts in the page.' })
200
+ if (!EMITTING.includes(declared.kind)) return json(400, { error: 'This button acts in the page.' })
148
201
  const result = await actions.press(record.person, record, declared, { until: value.until })
149
202
  await store.setRead(record.person, [record.id], true)
150
203
  return json(200, { press: result.event.press, published: result.published, matched: result.matched ?? 0 })
@@ -203,6 +256,7 @@ export function createRoutes({ store, people, push, actions, identity, serviceWo
203
256
  return [
204
257
  get('/summary', summary),
205
258
  get('/items', list),
259
+ get('/events', events),
206
260
  post('/read', read),
207
261
  post('/action', action),
208
262
  get('/file', file),