@soffits/dsh-card-board 0.0.0-stage → 0.2.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.
@@ -0,0 +1,7 @@
1
+ # Bundle layer for @soffits/dsh-card-board: one Host row that serves the
2
+ # boards to the Web UI page. Set dataDir (default: card-board in the DSH
3
+ # home) and, for a DSH several people sign in to, people / peopleFile in a
4
+ # profile override of this row.
5
+ - insert:
6
+ - id: card-board
7
+ name: '@soffits/dsh-card-board'
@@ -0,0 +1,9 @@
1
+ {
2
+ "title": "Home",
3
+ "viewers": ["alex", "sam"],
4
+ "order": ["weather", "savings", "energy", "next-weeks", "spending", "chores", "house"],
5
+ "layout": {
6
+ "savings": { "w": 1, "h": 1 },
7
+ "next-weeks": { "w": 2, "h": 1 }
8
+ }
9
+ }
@@ -0,0 +1,57 @@
1
+ {
2
+ "type": "list",
3
+ "title": "Today",
4
+ "updatedAt": "2026-03-02T09:00:00Z",
5
+ "staleAfter": 3600,
6
+ "data": {
7
+ "progress": {
8
+ "done": 1,
9
+ "total": 3,
10
+ "label": "done"
11
+ },
12
+ "rows": [
13
+ {
14
+ "title": "Water the plants",
15
+ "checked": true
16
+ },
17
+ {
18
+ "title": "Return the library books",
19
+ "checked": false,
20
+ "chip": {
21
+ "text": "due today",
22
+ "tone": "warn"
23
+ },
24
+ "actions": [
25
+ {
26
+ "kind": "done",
27
+ "id": "library-books:done"
28
+ },
29
+ {
30
+ "kind": "snooze",
31
+ "id": "library-books:snooze"
32
+ }
33
+ ]
34
+ },
35
+ {
36
+ "title": "Call the landlord about the heater",
37
+ "sub": "waiting since Friday",
38
+ "date": "2026-02-27",
39
+ "chip": {
40
+ "text": "chase",
41
+ "tone": "bad"
42
+ },
43
+ "actions": [
44
+ {
45
+ "kind": "chat",
46
+ "id": "landlord:ask",
47
+ "label": "Draft a message",
48
+ "payload": {
49
+ "prompt": "Help me write a short, polite follow-up to the landlord about the heater."
50
+ }
51
+ }
52
+ ]
53
+ }
54
+ ],
55
+ "empty": "Nothing left for today."
56
+ }
57
+ }
@@ -0,0 +1,19 @@
1
+ {
2
+ "type": "bar",
3
+ "title": "Electricity this week",
4
+ "updatedAt": "2026-03-02T08:00:00Z",
5
+ "staleAfter": 7200,
6
+ "data": {
7
+ "bars": [
8
+ { "x": "Mon", "values": { "Day": 5.2, "Night": 2.1 } },
9
+ { "x": "Tue", "values": { "Day": 4.8, "Night": 2.4 } },
10
+ { "x": "Wed", "values": { "Day": 6.1, "Night": 1.9 } },
11
+ { "x": "Thu", "values": { "Day": 5.5, "Night": 2.2 } },
12
+ { "x": "Fri", "values": { "Day": 4.2, "Night": 3.0 } },
13
+ { "x": "Sat", "values": { "Day": 7.4, "Night": 2.6 } },
14
+ { "x": "Sun", "values": { "Day": 6.8, "Night": 2.3 } }
15
+ ],
16
+ "stacked": true,
17
+ "unit": "kWh"
18
+ }
19
+ }
@@ -0,0 +1,58 @@
1
+ {
2
+ "type": "status",
3
+ "title": "House",
4
+ "updatedAt": "2026-03-02T09:29:00Z",
5
+ "staleAfter": 600,
6
+ "data": {
7
+ "rows": [
8
+ {
9
+ "label": "Leak sensor",
10
+ "value": "dry",
11
+ "tone": "ok"
12
+ },
13
+ {
14
+ "label": "Living room",
15
+ "value": "20.5 °C",
16
+ "tone": "ok",
17
+ "spark": [
18
+ 19.8,
19
+ 19.6,
20
+ 19.9,
21
+ 20.4,
22
+ 20.8,
23
+ 20.6,
24
+ 20.3,
25
+ 20.5
26
+ ]
27
+ },
28
+ {
29
+ "label": "Front door",
30
+ "value": "unlocked",
31
+ "tone": "warn",
32
+ "sub": "since 08:12",
33
+ "actions": [
34
+ {
35
+ "kind": "event",
36
+ "id": "front-door:lock",
37
+ "label": "Lock"
38
+ }
39
+ ]
40
+ },
41
+ {
42
+ "label": "Backup drive",
43
+ "value": "offline",
44
+ "tone": "bad"
45
+ }
46
+ ]
47
+ },
48
+ "actions": [
49
+ {
50
+ "kind": "link",
51
+ "id": "house:panel",
52
+ "label": "Home panel",
53
+ "payload": {
54
+ "url": "https://example.com/home-panel"
55
+ }
56
+ }
57
+ ]
58
+ }
@@ -0,0 +1,16 @@
1
+ {
2
+ "type": "timeline",
3
+ "title": "Next two weeks",
4
+ "updatedAt": "2026-03-02T06:00:00Z",
5
+ "data": {
6
+ "from": "2026-03-02",
7
+ "to": "2026-03-16",
8
+ "points": [
9
+ { "date": "2026-03-04", "label": "Train to Lyon", "kind": "travel" },
10
+ { "date": "2026-03-05", "label": "Phone bill", "kind": "due", "tone": "warn" },
11
+ { "date": "2026-03-12", "label": "Dentist", "kind": "health" },
12
+ { "date": "2026-03-14", "label": "Book club", "kind": "event" }
13
+ ],
14
+ "spans": [{ "from": "2026-03-04", "to": "2026-03-09", "label": "In Lyon" }]
15
+ }
16
+ }
@@ -0,0 +1,26 @@
1
+ {
2
+ "type": "line",
3
+ "title": "Savings",
4
+ "updatedAt": "2026-03-02T06:00:00Z",
5
+ "staleAfter": 86400,
6
+ "stat": { "items": [{ "label": "Total", "value": "18,240", "unit": "EUR", "sub": "up 2,140 since October" }] },
7
+ "data": {
8
+ "series": [
9
+ {
10
+ "name": "Savings",
11
+ "points": [
12
+ { "x": "2025-10-01", "y": 16100 },
13
+ { "x": "2025-11-01", "y": 16650 },
14
+ { "x": "2025-12-01", "y": 16300 },
15
+ { "x": "2026-01-01", "y": 17200 },
16
+ { "x": "2026-02-01", "y": 17750 },
17
+ { "x": "2026-03-01", "y": 18240 }
18
+ ]
19
+ }
20
+ ],
21
+ "unit": "EUR",
22
+ "area": true,
23
+ "goal": { "label": "Goal 20k", "y": 20000 },
24
+ "markers": [{ "x": "2025-12-01", "label": "New laptop" }]
25
+ }
26
+ }
@@ -0,0 +1,17 @@
1
+ {
2
+ "type": "donut",
3
+ "title": "Spending this month",
4
+ "updatedAt": "2026-03-02T06:00:00Z",
5
+ "staleAfter": 86400,
6
+ "data": {
7
+ "segments": [
8
+ { "label": "Rent", "value": 950 },
9
+ { "label": "Groceries", "value": 310 },
10
+ { "label": "Transport", "value": 85 },
11
+ { "label": "Subscriptions", "value": 42 },
12
+ { "label": "Other", "value": 64, "tone": "muted" }
13
+ ],
14
+ "centre": { "text": "1,451", "sub": "EUR" },
15
+ "unit": "EUR"
16
+ }
17
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "type": "stat",
3
+ "title": "Outside",
4
+ "updatedAt": "2026-03-02T09:30:00Z",
5
+ "staleAfter": 3600,
6
+ "data": {
7
+ "items": [
8
+ { "label": "Temperature", "value": 4.5, "unit": "°C", "delta": { "value": -2.1, "unit": "°C", "tone": "accent" }, "sub": "feels like 1 °C" },
9
+ { "label": "Humidity", "value": 71, "unit": "%" }
10
+ ]
11
+ }
12
+ }
package/icon.svg ADDED
@@ -0,0 +1,7 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">
2
+ <rect width="64" height="64" rx="14" fill="#eef3ff"/>
3
+ <rect x="11" y="11" width="18" height="18" rx="4.5" fill="#4d6bfe"/>
4
+ <rect x="35" y="11" width="18" height="18" rx="4.5" fill="none" stroke="#4d6bfe" stroke-width="2.4"/>
5
+ <rect x="11" y="35" width="18" height="18" rx="4.5" fill="none" stroke="#4d6bfe" stroke-width="2.4"/>
6
+ <path d="M36 50l5-6.5 4.5 3 6-8.5" fill="none" stroke="#22a06b" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"/>
7
+ </svg>
package/index.js ADDED
@@ -0,0 +1,79 @@
1
+ /**
2
+ * DeepSeek Harness Host plugin: a read-only card board.
3
+ *
4
+ * Scripts write small JSON card files into a data folder; this plugin checks
5
+ * who is asking and serves the boards they may see to the Web UI page in
6
+ * client.js. It makes no outbound requests, holds no credentials and never
7
+ * runs anything.
8
+ */
9
+ import { readFileSync } from 'node:fs'
10
+ import { homedir } from 'node:os'
11
+ import { isAbsolute, join, resolve } from 'node:path'
12
+ import z from '@deepseek-ai/schemastery'
13
+ import { createPeople, expandHome } from './src/access.js'
14
+ import { createPresses } from './src/presses.js'
15
+ import { createRoutes } from './src/routes.js'
16
+
17
+ export const name = 'dsh-card-board'
18
+ export const inject = ['connection']
19
+
20
+ /** card-board in DSH's home folder. */
21
+ export const DEFAULT_DATA_DIR = join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'card-board')
22
+
23
+ const { version } = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'))
24
+
25
+ export const Config = z.object({
26
+ dataDir: z.string().default(DEFAULT_DATA_DIR)
27
+ .description('The folder holding the boards: <dataDir>/<board>/board.json and <dataDir>/<board>/cards/<card>.json. A leading ~/ means the home folder. Default: card-board in the DSH home.'),
28
+ people: z.dict(z.string()).default({})
29
+ .description('Verified user id (from the sign-in plugin, such as an OIDC sub) → person id used in a board\'s viewers. With any mapping configured, each person sees only the boards that list them.'),
30
+ peopleFile: z.string().default('')
31
+ .description('A JSON file with more of the same mapping, re-read when it changes. Entries in people win.'),
32
+ peopleKey: z.string().default('')
33
+ .description('The top-level key in peopleFile that holds the mapping. Empty means the whole file is the mapping.'),
34
+ ownerPerson: z.string().default('')
35
+ .description('With a mapping: the person id for requests DSH lets in with its own login (launch link or API token) rather than through the sign-in plugin. Empty means such requests see no boards.'),
36
+ pollSeconds: z.natural().min(5).max(3600).default(30)
37
+ .description('How often an open, visible page checks for changes.'),
38
+ actionLog: z.string().default('')
39
+ .description('Where presses of done, snooze and event actions are appended (JSON lines). Empty means .actions.jsonl in dataDir.'),
40
+ actionTimeoutSeconds: z.natural().min(10).default(300)
41
+ .description('A press whose card nobody rewrites within this time shows as not handled.'),
42
+ })
43
+
44
+ /**
45
+ * @param {import('@deepseek-ai/cordis').Context} ctx
46
+ * @param {{ dataDir: string, people: Record<string, string>, peopleFile: string, peopleKey: string, ownerPerson: string, pollSeconds: number, actionLog: string, actionTimeoutSeconds: number }} config
47
+ */
48
+ export function apply(ctx, config) {
49
+ const logger = ctx.logger('card-board')
50
+ const home = homedir()
51
+ const absolute = path => {
52
+ const expanded = expandHome(path, home)
53
+ return isAbsolute(expanded) ? expanded : resolve(expanded)
54
+ }
55
+ const people = createPeople({
56
+ people: config.people ?? {},
57
+ peopleFile: config.peopleFile ? absolute(config.peopleFile) : '',
58
+ peopleKey: config.peopleKey ?? '',
59
+ }, { warn: message => logger.warn(message) })
60
+ const dataDir = absolute(config.dataDir)
61
+ const presses = createPresses({
62
+ logPath: config.actionLog ? absolute(config.actionLog) : join(dataDir, '.actions.jsonl'),
63
+ publisher: () => ctx.get('cronJobs')?.controller?.(),
64
+ notify: event => ctx.emit('card-board/action', event),
65
+ timeoutSeconds: config.actionTimeoutSeconds ?? 300,
66
+ warn: message => logger.warn(message),
67
+ })
68
+ const routes = createRoutes({
69
+ dataDir,
70
+ people,
71
+ identity: () => ctx.get('requestIdentity'),
72
+ pollSeconds: config.pollSeconds ?? 30,
73
+ presses,
74
+ ownerPerson: config.ownerPerson ?? '',
75
+ version,
76
+ })
77
+ for (const route of routes) ctx.connection.fetch.register(route)
78
+ logger.info(`serving boards from ${dataDir} (${people.enabled ? 'per person' : 'single owner'})`)
79
+ }
package/locale/en.json ADDED
@@ -0,0 +1 @@
1
+ { "meta": { "title": "Card Board", "description": "Boards of small cards and charts that your own scripts keep up to date. Each person sees only the boards they're allowed to." } }
package/locale/zh.json ADDED
@@ -0,0 +1 @@
1
+ { "meta": { "title": "卡片面板", "description": "由你自己的脚本更新的卡片和图表面板。每个人只能看到允许自己看的面板。" } }
package/package.json CHANGED
@@ -1,6 +1,82 @@
1
1
  {
2
2
  "name": "@soffits/dsh-card-board",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "A data-driven card board for DeepSeek Harness: scripts write small JSON cards, the Web UI shows each person the boards they may see.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Sakina",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/soffits/dsh-card-board.git"
11
+ },
12
+ "homepage": "https://github.com/soffits/dsh-card-board#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/soffits/dsh-card-board/issues"
15
+ },
16
+ "keywords": [
17
+ "dsh",
18
+ "dsh-plugin",
19
+ "deepseek-harness",
20
+ "dashboard",
21
+ "cards",
22
+ "charts"
23
+ ],
24
+ "main": "./index.js",
25
+ "bin": {
26
+ "dsh-card-board": "./bin/dsh-card-board.js"
27
+ },
28
+ "exports": {
29
+ ".": "./index.js",
30
+ "./schema": "./src/schema.js",
31
+ "./client": "./client.js",
32
+ "./locale/*.json": "./locale/*.json",
33
+ "./icon": "./icon.svg",
34
+ "./package.json": "./package.json"
35
+ },
36
+ "files": [
37
+ "bin",
38
+ "src",
39
+ "client.js",
40
+ "client.actions.js",
41
+ "index.js",
42
+ "cordis.patch.yml",
43
+ "locale/*.json",
44
+ "icon.svg",
45
+ "examples",
46
+ "README.md",
47
+ "CHANGELOG.md",
48
+ "LICENSE"
49
+ ],
50
+ "dsh": {
51
+ "bundle": {
52
+ "patch": "./cordis.patch.yml"
53
+ },
54
+ "client": {
55
+ "platform": "web",
56
+ "immediately": true,
57
+ "inject": [
58
+ "@deepseek-ai/dsh-client-locale",
59
+ "@deepseek-ai/dsh-client-ui-layout",
60
+ "@deepseek-ai/dsh-client-ui-sidebar"
61
+ ]
62
+ }
63
+ },
64
+ "icon": "./icon.svg",
65
+ "engines": {
66
+ "node": ">=22",
67
+ "dsh": ">=0.2.1-rc.2 <0.3.0"
68
+ },
69
+ "scripts": {
70
+ "check": "for f in index.js client.js bin/*.js src/*.js test/*.js; do node --check \"$f\" || exit 1; done && node bin/dsh-card-board.js check --dir examples/boards",
71
+ "test": "node --test test/*.test.js"
72
+ },
73
+ "dependencies": {
74
+ "@deepseek-ai/schemastery": "3.18.5"
75
+ },
76
+ "devDependencies": {
77
+ "@deepseek-ai/cordis": "^4.1.0",
78
+ "@deepseek-ai/dsh-client-connection": "0.2.2-rc.1",
79
+ "@deepseek-ai/dsh-credentials": "0.2.2-rc.1",
80
+ "@deepseek-ai/dsh-host-webserver": "0.2.2-rc.1"
81
+ }
82
+ }
package/src/access.js ADDED
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Who may see which board.
3
+ *
4
+ * The caller comes from a `requestIdentity` service, if one is installed: any
5
+ * plugin that verifies the person behind an `/api` request can provide it
6
+ * (`current()` returns `{ id, ... }` or null). The verified user id maps to a
7
+ * person id through the configured mapping, and a board lists the person ids
8
+ * that may see it in `viewers`.
9
+ *
10
+ * Two modes:
11
+ * - people: a mapping is configured. A request needs a verified identity that
12
+ * maps to a person, and sees only boards that list that person. Without an
13
+ * identity provider nothing is shown.
14
+ * - owner: no mapping. Everyone DSH lets in is its owner and sees every board,
15
+ * which is what a single-person DSH wants.
16
+ */
17
+ import { readFile, stat } from 'node:fs/promises'
18
+
19
+ /** Person ids compare without regard to case or surrounding space. */
20
+ export function personKey(value) {
21
+ return typeof value === 'string' ? value.trim().normalize('NFKC').toLowerCase() : ''
22
+ }
23
+
24
+ /** Expand a leading `~/` to the home folder. */
25
+ export function expandHome(path, home) {
26
+ return typeof path === 'string' && (path === '~' || path.startsWith('~/')) ? home + path.slice(1) : path
27
+ }
28
+
29
+ /**
30
+ * The configured user id → person id mapping, re-read from `peopleFile`
31
+ * whenever that file changes. A file that can't be read or parsed maps nobody
32
+ * (and is reported once per change), so a broken file never widens access.
33
+ */
34
+ export function createPeople({ people = {}, peopleFile = '', peopleKey = '' }, { warn = () => {} } = {}) {
35
+ const inline = Object.entries(people)
36
+ const enabled = inline.length > 0 || peopleFile !== ''
37
+ let cached = { tag: undefined, entries: [] }
38
+
39
+ async function fromFile() {
40
+ if (peopleFile === '') return []
41
+ let tag
42
+ try {
43
+ const info = await stat(peopleFile)
44
+ tag = `${info.size}:${info.mtimeMs}`
45
+ } catch (error) {
46
+ tag = `error:${error.code}`
47
+ }
48
+ if (tag === cached.tag) return cached.entries
49
+ let entries = []
50
+ try {
51
+ let value = JSON.parse(await readFile(peopleFile, 'utf8'))
52
+ if (peopleKey !== '') value = value?.[peopleKey]
53
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error(peopleKey ? `no object at key ${peopleKey}` : 'not a JSON object')
54
+ entries = Object.entries(value).filter(([, person]) => typeof person === 'string')
55
+ } catch (error) {
56
+ warn(`people file ${peopleFile}: ${error.message}; nobody is mapped from it`)
57
+ }
58
+ cached = { tag, entries }
59
+ return entries
60
+ }
61
+
62
+ return {
63
+ enabled,
64
+ /** The person id for a verified user id, or undefined. Inline entries win over the file. */
65
+ async personFor(userId) {
66
+ if (typeof userId !== 'string' || userId === '') return undefined
67
+ const map = new Map([...(await fromFile()), ...inline])
68
+ const person = map.get(userId)
69
+ return person === undefined ? undefined : personKey(person)
70
+ },
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Decide who the current request is. Returns `{ mode: 'owner' }`,
76
+ * `{ mode: 'people', person }` (person may be undefined: sees nothing) or
77
+ * `{ mode: 'people', unavailable: true }` when a mapping is configured but no
78
+ * identity provider is installed.
79
+ *
80
+ * `ownerPerson` names the person behind a request the provider can't name:
81
+ * one DSH let in with its own login (its launch link or API token) rather
82
+ * than through the sign-in plugin. Without a provider at all nobody can be
83
+ * told apart, so that stays unavailable.
84
+ */
85
+ export async function viewerOf(people, identityService, ownerPerson = '') {
86
+ if (!people.enabled) return { mode: 'owner' }
87
+ if (identityService === undefined || typeof identityService?.current !== 'function') return { mode: 'people', unavailable: true }
88
+ const identity = identityService.current()
89
+ if (identity === null || identity === undefined) return { mode: 'people', person: ownerPerson ? personKey(ownerPerson) : undefined }
90
+ return { mode: 'people', person: await people.personFor(identity.id) }
91
+ }
92
+
93
+ /** Whether a viewer may see a board (its board.json already validated). */
94
+ export function maySee(viewer, board) {
95
+ if (viewer.mode === 'owner') return true
96
+ if (viewer.person === undefined || board === undefined) return false
97
+ return (board.viewers ?? []).some(person => personKey(person) === viewer.person)
98
+ }
package/src/presses.js ADDED
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Presses: what happens when someone taps a done, snooze or event action.
3
+ *
4
+ * The plugin changes no data and runs nothing. A press becomes an event that
5
+ * is appended to an action log (JSON lines) and handed to whoever publishes
6
+ * events (dsh-cron-jobs' `cronJobs` service when it runs, as channel
7
+ * `ui.action.<kind>`), so the owner of the item reacts and rewrites the card.
8
+ *
9
+ * A press is pending until its card file is written again after it (done),
10
+ * or until the timeout passes with no write (unhandled). Recent presses are
11
+ * kept in memory and reloaded from the log's tail after a restart.
12
+ */
13
+ import { randomUUID } from 'node:crypto'
14
+ import { appendFile, mkdir, open, stat } from 'node:fs/promises'
15
+ import { dirname } from 'node:path'
16
+
17
+ const KEEP_MS = 24 * 3600 * 1000
18
+ const TAIL_BYTES = 1024 * 1024
19
+ const DOUBLE_TAP_MS = 3000
20
+
21
+ /** Read the presses of the last day from the end of the log. */
22
+ async function readTail(path) {
23
+ let handle
24
+ try {
25
+ handle = await open(path, 'r')
26
+ } catch {
27
+ return []
28
+ }
29
+ try {
30
+ const { size } = await handle.stat()
31
+ const length = Math.min(size, TAIL_BYTES)
32
+ const buffer = Buffer.alloc(length)
33
+ await handle.read(buffer, 0, length, size - length)
34
+ const lines = buffer.toString('utf8').split('\n')
35
+ if (size > length) lines.shift()
36
+ const since = Date.now() - KEEP_MS
37
+ return lines.flatMap(line => {
38
+ try {
39
+ const event = JSON.parse(line)
40
+ return Date.parse(event.at) >= since ? [event] : []
41
+ } catch {
42
+ return []
43
+ }
44
+ })
45
+ } finally {
46
+ await handle.close()
47
+ }
48
+ }
49
+
50
+ /**
51
+ * @param {object} options
52
+ * @param {string} options.logPath - the action log (JSON lines)
53
+ * @param {() => object | undefined} options.publisher - `{ emit(event) }` right now, if any
54
+ * @param {(event: object) => void} [options.notify] - in-process listeners (a Cordis event)
55
+ * @param {number} options.timeoutSeconds
56
+ * @param {(message: string) => void} [options.warn]
57
+ * @param {() => number} [options.now]
58
+ */
59
+ export function createPresses({ logPath, publisher, notify = () => {}, timeoutSeconds, warn = () => {}, now = Date.now }) {
60
+ let recent
61
+ const loaded = readTail(logPath).then(events => { recent = events })
62
+
63
+ async function list() {
64
+ await loaded
65
+ const since = now() - KEEP_MS
66
+ recent = recent.filter(event => Date.parse(event.at) >= since)
67
+ return recent
68
+ }
69
+
70
+ /** Record one press; a second identical tap within a few seconds returns the first. */
71
+ async function press({ action, person, user, board, card, row, payload }) {
72
+ const events = await list()
73
+ const at = now()
74
+ const twin = events.find(event => event.id === action.id && event.person === person && event.source.board === board && event.source.card === card && event.source.row === row && at - Date.parse(event.at) < DOUBLE_TAP_MS)
75
+ if (twin) return twin
76
+ const event = {
77
+ press: randomUUID(),
78
+ action: action.kind,
79
+ id: action.id,
80
+ ...(action.label ? { label: action.label } : {}),
81
+ payload,
82
+ person,
83
+ ...(user ? { user } : {}),
84
+ at: new Date(at).toISOString(),
85
+ source: { plugin: 'dsh-card-board', board, card, ...(row === undefined ? {} : { row }) },
86
+ }
87
+ await mkdir(dirname(logPath), { recursive: true })
88
+ await appendFile(logPath, `${JSON.stringify(event)}\n`, { mode: 0o600 })
89
+ recent.push(event)
90
+ notify(event)
91
+ try {
92
+ const result = publisher()?.emit({ channel: `ui.action.${event.action}`, data: event, key: event.press, source: 'dsh-card-board' })
93
+ if (result === undefined) warn(`press ${event.press} logged; no event publisher is running`)
94
+ } catch (error) {
95
+ warn(`press ${event.press} logged but not published: ${error.message}`)
96
+ }
97
+ return event
98
+ }
99
+
100
+ /**
101
+ * The presses on one card with their state: done once the card file was
102
+ * written after the press, unhandled after the timeout, else pending.
103
+ */
104
+ async function statesFor(board, card, cardPath) {
105
+ const events = (await list()).filter(event => event.source.board === board && event.source.card === card)
106
+ if (events.length === 0) return []
107
+ const written = await stat(cardPath).then(info => info.mtimeMs, () => 0)
108
+ const at = now()
109
+ return events.map(event => {
110
+ const time = Date.parse(event.at)
111
+ const state = written > time ? 'done' : at - time > timeoutSeconds * 1000 ? 'unhandled' : 'pending'
112
+ return { press: event.press, id: event.id, ...(event.source.row === undefined ? {} : { row: event.source.row }), at: event.at, state }
113
+ })
114
+ }
115
+
116
+ return { press, statesFor, list }
117
+ }