dsh-work-fish 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +82 -2
- package/THIRD-PARTY-NOTICES.md +61 -0
- package/board/client.js +1048 -0
- package/cordis.patch.yml +173 -0
- package/core/approve-paths.mjs +387 -0
- package/core/approve-paths.test.mjs +241 -0
- package/core/approve.mjs +182 -0
- package/core/bootstrap.mjs +186 -0
- package/core/events.mjs +80 -0
- package/core/guard.mjs +155 -0
- package/core/index.mjs +630 -0
- package/core/parse.mjs +310 -0
- package/core/persona.mjs +98 -0
- package/core/pet-bridge.mjs +439 -0
- package/core/report.mjs +370 -0
- package/core/skills.mjs +111 -0
- package/docs/DETAIL.md +1 -0
- package/docs/DETAIL.zh.md +1 -0
- package/docs/preview.webp +0 -0
- package/icon.png +0 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +69 -4
- package/rules/code-rules.md +92 -0
- package/rules/experience-pool.md +59 -0
- package/rules/file-rules.md +134 -0
- package/rules/memory-rules.md +91 -0
- package/rules/task-rules.md +71 -0
- package/skills/code-review/LICENSE +202 -0
- package/skills/code-review/NOTICE.md +75 -0
- package/skills/code-review/SKILL.md +155 -0
- package/skills/code-review/upstream/README.md +258 -0
- package/skills/code-review/upstream/code-review.command.md +110 -0
- package/skills/code-review/upstream/plugin.json +10 -0
- package/skills/code-simplifier/LICENSE +202 -0
- package/skills/code-simplifier/NOTICE.md +72 -0
- package/skills/code-simplifier/SKILL.md +126 -0
- package/skills/code-simplifier/agents/code-simplifier.md +52 -0
- package/skills/code-simplifier/upstream/plugin.json +9 -0
- package/skills/comfyui-h3/SKILL.md +455 -0
- package/skills/comfyui-h3/reference/failures.md +84 -0
- package/skills/comfyui-h3/reference/serial-production.md +173 -0
- package/skills/delete-gate/SKILL.md +48 -0
- package/skills/doc-writing/SKILL.md +152 -0
- package/skills/doc-writing/reference/skeletons.md +81 -0
- package/skills/feature-dev/LICENSE +202 -0
- package/skills/feature-dev/NOTICE.md +67 -0
- package/skills/feature-dev/SKILL.md +181 -0
- package/skills/feature-dev/agents/code-architect.md +34 -0
- package/skills/feature-dev/agents/code-explorer.md +51 -0
- package/skills/feature-dev/agents/code-reviewer.md +46 -0
- package/skills/feature-dev/upstream/README.md +412 -0
- package/skills/feature-dev/upstream/feature-dev.command.md +125 -0
- package/skills/feature-dev/upstream/plugin.json +9 -0
- package/skills/frontend-design/LICENSE.txt +177 -0
- package/skills/frontend-design/SKILL.md +71 -0
- package/skills/git-flow/SKILL.md +80 -0
- package/skills/plan-revision/SKILL.md +54 -0
- package/skills/task-setup/SKILL.md +124 -0
- package/template/AGENTS.template.md +28 -0
- package/template/memory/pool/experience.md +9 -0
- package/template/memory/preferences.md +17 -0
- package/template/memory/projects/README.md +6 -0
- package/template/memory/user-profile.md +33 -0
- package/template/persona-core.md +32 -0
- package/template/persona-user.md +0 -0
- package/template/rules/user-rules.md +20 -0
- package/template/rules-index.md +50 -0
- package/template/tasks/index.md +34 -0
- package/tools/lib/paths.mjs +31 -0
- package/tools/lib/persona.mjs +454 -0
- package/tools/lib/taskboard.mjs +713 -0
- package/tools/wf-audit.cmd +3 -0
- package/tools/wf-audit.ps1 +242 -0
- package/tools/wf-mem.mjs +336 -0
- package/tools/wf-metrics.mjs +601 -0
- package/tools/wf-persona.mjs +337 -0
- package/tools/wf-pool.mjs +250 -0
- package/tools/wf-preview.mjs +242 -0
- package/tools/wf-recent.mjs +168 -0
- package/tools/wf-review.mjs +650 -0
- package/tools/wf-rule.mjs +407 -0
- package/tools/wf-snapshot.mjs +100 -0
- package/tools/wf-spec.mjs +882 -0
- package/tools/wf-task.mjs +303 -0
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The bridge between the Work Fish ledger and the `dsh-pet` character.
|
|
3
|
+
*
|
|
4
|
+
* Work Fish used to draw its own pet. Since the character belongs to `dsh-pet`,
|
|
5
|
+
* this module is the whole of the relationship: a few HTTP calls over the Web
|
|
6
|
+
* server's own origin, never an import, so either plugin can be upgraded or
|
|
7
|
+
* removed without the other one failing to load.
|
|
8
|
+
*
|
|
9
|
+
* Three things travel over it:
|
|
10
|
+
*
|
|
11
|
+
* 1. **Menu items** — the pet's right-click menu gets a 「大肥鱼」 group
|
|
12
|
+
* (`/menu/item`). A click comes back through `/menu/events`, which this
|
|
13
|
+
* module long-polls; that is how the task panel is opened from the
|
|
14
|
+
* character and how 「开始下一件」「完成进行中」become ledger writes.
|
|
15
|
+
* 2. **Work status** — the top in-progress row is pushed as the pet's task
|
|
16
|
+
* line (`/work-status`), so the character says what is being worked on.
|
|
17
|
+
* 3. **Reminders** — a new overdue row earns one short bubble (`/broadcast`).
|
|
18
|
+
*
|
|
19
|
+
* Every call is best-effort: `dsh-pet` may be disabled, missing, asleep or
|
|
20
|
+
* holding its lock, and none of that is an error worth surfacing to the user.
|
|
21
|
+
* The bridge therefore never throws, never retries in a tight loop, and reports
|
|
22
|
+
* its own state through `status()` so `/wf/info` can show it.
|
|
23
|
+
*
|
|
24
|
+
* @module dsh-work-fish/core/pet-bridge
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import fs from 'node:fs'
|
|
28
|
+
import { pushEvent } from './events.mjs'
|
|
29
|
+
|
|
30
|
+
/** Registry key for our menu group; also the group label the pet shows. */
|
|
31
|
+
const OWNER = '大肥鱼'
|
|
32
|
+
|
|
33
|
+
/** The three menu items, in menu order. Labels double as click identifiers. */
|
|
34
|
+
const LABELS = {
|
|
35
|
+
board: '打开任务板',
|
|
36
|
+
start: '开始下一件',
|
|
37
|
+
finish: '完成进行中',
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Wait ceiling for the menu long-poll, matching `dsh-pet`'s own limit. */
|
|
41
|
+
const POLL_WAIT_MS = 10_000
|
|
42
|
+
|
|
43
|
+
/** Backoff after a failed call: long enough that a missing pet costs nothing. */
|
|
44
|
+
const RETRY_MS = 15_000
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Sleep without holding anything.
|
|
48
|
+
* @param {number} ms milliseconds.
|
|
49
|
+
* @returns {Promise<void>} resolves after `ms`.
|
|
50
|
+
*/
|
|
51
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Cut a string to `max` code points so a proxy pair never splits.
|
|
55
|
+
* @param {string} text source text.
|
|
56
|
+
* @param {number} max code points allowed.
|
|
57
|
+
* @returns {string} the (possibly shortened) text.
|
|
58
|
+
*/
|
|
59
|
+
function clip(text, max) {
|
|
60
|
+
const points = Array.from(String(text ?? ''))
|
|
61
|
+
return points.length > max ? `${points.slice(0, max - 1).join('')}…` : points.join('')
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Start the bridge. Safe to call once per mount; every failure stays inside.
|
|
66
|
+
*
|
|
67
|
+
* @param {object} deps dependencies, all supplied by the host entry.
|
|
68
|
+
* @param {{homeDir: string, timeZone: string, allowWrites: boolean}} deps.options resolved row options.
|
|
69
|
+
* @param {{info?: Function, warn?: Function, error?: Function}} [deps.logger] Cordis logger.
|
|
70
|
+
* @param {() => string} deps.getOrigin returns the Web server origin, or `''`.
|
|
71
|
+
* @param {(args: string[]) => Promise<object>} deps.runCli runs `wf-task` and returns its JSON.
|
|
72
|
+
* @param {(options: object) => Promise<object>} deps.buildReport reads the ledger into the panel payload.
|
|
73
|
+
* @returns {{status: () => object}} liveness facts for `/wf/info`.
|
|
74
|
+
*/
|
|
75
|
+
export function startPetBridge({ options, logger, getOrigin, runCli, buildReport }) {
|
|
76
|
+
/** @type {{connected: boolean, petId: string, display: string, reason: string, lastFeedAt: number, lastAction: string}} */
|
|
77
|
+
const state = { connected: false, petId: '', display: '', reason: 'starting', lastFeedAt: 0, lastAction: '' }
|
|
78
|
+
|
|
79
|
+
/** Set once `dsh-pet` accepted our menu registration; cleared on any failure. */
|
|
80
|
+
let registered = false
|
|
81
|
+
|
|
82
|
+
/** Overdue count last announced, so a reminder is news rather than a loop. */
|
|
83
|
+
let announcedOverdue = -1
|
|
84
|
+
|
|
85
|
+
/** Last time a reminder was shown, in ms; reminders are rate-limited. */
|
|
86
|
+
let remindedAt = 0
|
|
87
|
+
|
|
88
|
+
/** Set by `stop()`; every loop checks it before continuing. */
|
|
89
|
+
let stopped = false
|
|
90
|
+
|
|
91
|
+
/** Handle of the feed interval, cleared by `stop()`. */
|
|
92
|
+
let feedTimer = undefined
|
|
93
|
+
|
|
94
|
+
/** Ledger mtime last seen, used to nudge open panels. */
|
|
95
|
+
let ledgerStamp = ''
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* `dsh-pet` mounts every route under one constant segment; this is the only
|
|
99
|
+
* place that spells it, and the probe in `/wf/info` shows when it stops matching.
|
|
100
|
+
* @returns {string} `origin + segment`, or `''` before the server knows its origin.
|
|
101
|
+
*/
|
|
102
|
+
const base = () => {
|
|
103
|
+
const origin = String(getOrigin() ?? '')
|
|
104
|
+
return origin === '' ? '' : `${origin.replace(/\/+$/u, '')}/dsh-pet-7340`
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* One JSON call against `dsh-pet`.
|
|
109
|
+
*
|
|
110
|
+
* `signal` bounds the long poll: without it a half-open socket would keep the
|
|
111
|
+
* loop from ever retrying. Every non-2xx answer is a rejection here so the
|
|
112
|
+
* caller has one branch, not two.
|
|
113
|
+
*
|
|
114
|
+
* @param {string} url absolute URL.
|
|
115
|
+
* @param {{method?: string, body?: object, timeoutMs?: number}} [init] request shape.
|
|
116
|
+
* @returns {Promise<object>} the parsed body, or `{ ok: false }` on any failure.
|
|
117
|
+
*/
|
|
118
|
+
async function call(url, init = {}) {
|
|
119
|
+
const controller = new AbortController()
|
|
120
|
+
const timer = setTimeout(() => controller.abort(), init.timeoutMs ?? 5_000)
|
|
121
|
+
try {
|
|
122
|
+
const response = await fetch(url, {
|
|
123
|
+
method: init.method ?? 'GET',
|
|
124
|
+
headers: init.body === undefined ? { accept: 'application/json' } : { accept: 'application/json', 'content-type': 'application/json' },
|
|
125
|
+
body: init.body === undefined ? undefined : JSON.stringify(init.body),
|
|
126
|
+
signal: controller.signal,
|
|
127
|
+
cache: 'no-store',
|
|
128
|
+
})
|
|
129
|
+
const text = await response.text()
|
|
130
|
+
let body = {}
|
|
131
|
+
try {
|
|
132
|
+
body = text === '' ? {} : JSON.parse(text)
|
|
133
|
+
} catch {
|
|
134
|
+
body = { ok: false, code: 'bad-json', message: `HTTP ${response.status}` }
|
|
135
|
+
}
|
|
136
|
+
if (!response.ok) return { ...body, ok: false, code: body?.code ?? `http-${response.status}` }
|
|
137
|
+
return body
|
|
138
|
+
} catch (error) {
|
|
139
|
+
return { ok: false, code: 'unreachable', message: error instanceof Error ? error.message : String(error) }
|
|
140
|
+
} finally {
|
|
141
|
+
clearTimeout(timer)
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Learn which character to address.
|
|
147
|
+
*
|
|
148
|
+
* `dsh-pet` requires an explicit `?pet=` on every feed call and refuses to
|
|
149
|
+
* guess, so the id is read from its merged config instead of being assumed.
|
|
150
|
+
* That config is keyed by pet id (`{ main: {...} }`), one entry per layer —
|
|
151
|
+
* it is not the same shape as the `pets[]` array in the on-disk file.
|
|
152
|
+
*
|
|
153
|
+
* The merged config is keyed by animation-entry name and each entry carries
|
|
154
|
+
* the `pets[]` array; the first pet's id is what `?pet=` wants, and its
|
|
155
|
+
* `display` decides which `surface` a bubble is allowed to target (`dsh-pet`
|
|
156
|
+
* refuses a bubble for a surface the pet is not shown on).
|
|
157
|
+
*
|
|
158
|
+
* @param {string} root `origin + segment`.
|
|
159
|
+
* @returns {Promise<{id: string, display: string}>} the first pet, or blanks.
|
|
160
|
+
*/
|
|
161
|
+
async function discoverPet(root) {
|
|
162
|
+
const config = await call(`${root}/config`)
|
|
163
|
+
if (config === null || typeof config !== 'object') return { id: '', display: '' }
|
|
164
|
+
for (const key of Object.keys(config)) {
|
|
165
|
+
const layer = config[key]
|
|
166
|
+
const pets = Array.isArray(layer?.pets) ? layer.pets : []
|
|
167
|
+
const pet = pets.find((candidate) => typeof candidate?.id === 'string' && candidate.id.trim() !== '')
|
|
168
|
+
if (pet !== undefined) {
|
|
169
|
+
return { id: pet.id.trim(), display: typeof pet.display === 'string' ? pet.display : '' }
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
return { id: '', display: '' }
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* (Re)register the 「大肥鱼」 menu group.
|
|
177
|
+
*
|
|
178
|
+
* Registration replaces the whole owner, so this is idempotent; it is repeated
|
|
179
|
+
* whenever a poll reports the owner is gone, which is what a `dsh-pet` restart
|
|
180
|
+
* looks like from here.
|
|
181
|
+
*
|
|
182
|
+
* @param {string} root `origin + segment`.
|
|
183
|
+
* @returns {Promise<boolean>} whether the group is in place.
|
|
184
|
+
*/
|
|
185
|
+
async function registerMenu(root) {
|
|
186
|
+
const result = await call(`${root}/menu/item`, {
|
|
187
|
+
method: 'POST',
|
|
188
|
+
body: { owner: OWNER, labels: Object.values(LABELS), target: 'both' },
|
|
189
|
+
})
|
|
190
|
+
if (result?.ok === true) return true
|
|
191
|
+
logger?.warn?.(`wf: 桌宠菜单注册失败(${result?.reason ?? result?.code ?? 'unknown'})`)
|
|
192
|
+
return false
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Forget the pet address so the next poll discovers it again.
|
|
197
|
+
*
|
|
198
|
+
* `dsh-pet` answers `unknown-pet` after the character is renamed or removed;
|
|
199
|
+
* without this the bridge would keep feeding an id nobody owns while still
|
|
200
|
+
* reporting itself as connected.
|
|
201
|
+
*/
|
|
202
|
+
function forgetPet() {
|
|
203
|
+
state.petId = ''
|
|
204
|
+
state.display = ''
|
|
205
|
+
state.connected = false
|
|
206
|
+
state.reason = 'pet id no longer exists, rediscovering'
|
|
207
|
+
registered = false
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Show one short line on the character.
|
|
212
|
+
*
|
|
213
|
+
* The `surface` must match where the character is actually shown, so it is
|
|
214
|
+
* read from its own config rather than assumed; `both` is the tolerant default.
|
|
215
|
+
*
|
|
216
|
+
* @param {string} text what to say; `dsh-pet` cuts a long line itself.
|
|
217
|
+
* @returns {Promise<boolean>} whether the character accepted the line.
|
|
218
|
+
*/
|
|
219
|
+
async function say(text) {
|
|
220
|
+
const root = base()
|
|
221
|
+
if (root === '' || state.petId === '') return false
|
|
222
|
+
const surface = state.display === 'desktop' || state.display === 'web' ? state.display : 'both'
|
|
223
|
+
const result = await call(`${root}/broadcast?pet=${encodeURIComponent(state.petId)}&surface=${surface}`, {
|
|
224
|
+
method: 'POST',
|
|
225
|
+
body: { text: clip(text, 120), duration: 8_000, anim: false },
|
|
226
|
+
})
|
|
227
|
+
if (result?.ok === true) return true
|
|
228
|
+
if (result?.reason === 'unknown-pet' || result?.reason === 'pet-required') forgetPet()
|
|
229
|
+
return false
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Push (or clear) the pet's task line from the top in-progress row.
|
|
234
|
+
* @returns {Promise<void>} resolves when the call is done or has failed.
|
|
235
|
+
*/
|
|
236
|
+
async function feed() {
|
|
237
|
+
const root = base()
|
|
238
|
+
if (root === '' || state.petId === '') return
|
|
239
|
+
const query = `?pet=${encodeURIComponent(state.petId)}`
|
|
240
|
+
let report
|
|
241
|
+
try {
|
|
242
|
+
report = await buildReport(options)
|
|
243
|
+
} catch (error) {
|
|
244
|
+
logger?.warn?.(`wf: 台账读取失败(${error instanceof Error ? error.message : String(error)})`)
|
|
245
|
+
return
|
|
246
|
+
}
|
|
247
|
+
const current = Array.isArray(report?.inProgress) ? report.inProgress[0] : undefined
|
|
248
|
+
/** Nothing in progress hands the slot back rather than leaving a stale line. */
|
|
249
|
+
const status =
|
|
250
|
+
current === undefined
|
|
251
|
+
? await call(`${root}/work-status${query}`, { method: 'DELETE' })
|
|
252
|
+
: await call(`${root}/work-status${query}`, {
|
|
253
|
+
method: 'POST',
|
|
254
|
+
body: { state: 'working', task: clip(`${current.id} ${current.title ?? ''}`.trim(), 40) },
|
|
255
|
+
})
|
|
256
|
+
if (status?.reason === 'unknown-pet' || status?.reason === 'pet-required') {
|
|
257
|
+
forgetPet()
|
|
258
|
+
return
|
|
259
|
+
}
|
|
260
|
+
state.lastFeedAt = Date.now()
|
|
261
|
+
|
|
262
|
+
const overdue = Number(report?.counts?.overdue ?? 0)
|
|
263
|
+
if (overdue > 0 && overdue !== announcedOverdue && Date.now() - remindedAt > 30 * 60_000) {
|
|
264
|
+
const late = [...(report?.inProgress ?? []), ...(report?.todo ?? [])].find((row) => Number(row?.overdueDays) > 0)
|
|
265
|
+
const spoken = await say(late === undefined ? `今天逾期 ${overdue} 件` : `逾期 ${overdue} 件,先看 ${late.id}`)
|
|
266
|
+
// Only a delivered line counts as told: a mute pet must not swallow the reminder.
|
|
267
|
+
if (spoken) remindedAt = Date.now()
|
|
268
|
+
else return
|
|
269
|
+
}
|
|
270
|
+
announcedOverdue = overdue
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Move one ledger row through the shared CLI.
|
|
275
|
+
* @param {object} row panel row (`id`, `rev`).
|
|
276
|
+
* @param {string} to target section name.
|
|
277
|
+
* @param {string[]} [extra] additional CLI flags.
|
|
278
|
+
* @returns {Promise<object>} the CLI verdict.
|
|
279
|
+
*/
|
|
280
|
+
async function move(row, to, extra = []) {
|
|
281
|
+
const result = await runCli([
|
|
282
|
+
'move',
|
|
283
|
+
'--task', String(row.id),
|
|
284
|
+
'--expect-rev', String(row.rev),
|
|
285
|
+
'--to', to,
|
|
286
|
+
...extra,
|
|
287
|
+
'--source', '桌宠',
|
|
288
|
+
])
|
|
289
|
+
state.lastAction = `${to} ${row.id}`
|
|
290
|
+
pushEvent('changed')
|
|
291
|
+
if (result?.ok === true) return result
|
|
292
|
+
if (result?.verdict === 'STALE') await say('台账刚被改过,已刷新')
|
|
293
|
+
else await say(`没写成:${clip(result?.message ?? '未知原因', 40)}`)
|
|
294
|
+
return result
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* React to one click on a menu item, in order of what the user asked for.
|
|
299
|
+
* @param {string} label the clicked label.
|
|
300
|
+
* @returns {Promise<void>} resolves when the action is done.
|
|
301
|
+
*/
|
|
302
|
+
async function onMenuClick(label) {
|
|
303
|
+
if (label === LABELS.board) {
|
|
304
|
+
pushEvent('open')
|
|
305
|
+
return
|
|
306
|
+
}
|
|
307
|
+
if (options.allowWrites !== true) {
|
|
308
|
+
await say('台账写入已关闭')
|
|
309
|
+
return
|
|
310
|
+
}
|
|
311
|
+
let report
|
|
312
|
+
try {
|
|
313
|
+
report = await buildReport(options)
|
|
314
|
+
} catch {
|
|
315
|
+
await say('台账读不到')
|
|
316
|
+
return
|
|
317
|
+
}
|
|
318
|
+
if (label === LABELS.start) {
|
|
319
|
+
const next = Array.isArray(report?.todo) ? report.todo[0] : undefined
|
|
320
|
+
if (next === undefined) {
|
|
321
|
+
await say('待办里没有可开的任务')
|
|
322
|
+
return
|
|
323
|
+
}
|
|
324
|
+
const result = await move(next, '进行中')
|
|
325
|
+
if (result?.ok === true) await say(`开始 ${next.id}`)
|
|
326
|
+
return
|
|
327
|
+
}
|
|
328
|
+
if (label === LABELS.finish) {
|
|
329
|
+
const current = Array.isArray(report?.inProgress) ? report.inProgress[0] : undefined
|
|
330
|
+
if (current === undefined) {
|
|
331
|
+
await say('没有进行中的任务')
|
|
332
|
+
return
|
|
333
|
+
}
|
|
334
|
+
const result = await move(current, '已完成', ['--result', '已完成'])
|
|
335
|
+
if (result?.ok === true) await say(`完成 ${current.id}`)
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** One poll round: discover, register, then drain clicks until aborted. */
|
|
340
|
+
async function pollLoop() {
|
|
341
|
+
while (!stopped) {
|
|
342
|
+
const root = base()
|
|
343
|
+
if (root === '') {
|
|
344
|
+
state.reason = 'web server origin unknown'
|
|
345
|
+
await sleep(RETRY_MS)
|
|
346
|
+
continue
|
|
347
|
+
}
|
|
348
|
+
if (state.petId === '') {
|
|
349
|
+
const found = await discoverPet(root)
|
|
350
|
+
state.petId = found.id
|
|
351
|
+
state.display = found.display
|
|
352
|
+
if (state.petId === '') {
|
|
353
|
+
state.connected = false
|
|
354
|
+
state.reason = 'dsh-pet 未安装或未启用'
|
|
355
|
+
await sleep(RETRY_MS)
|
|
356
|
+
continue
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
if (!registered) {
|
|
360
|
+
registered = await registerMenu(root)
|
|
361
|
+
if (!registered) {
|
|
362
|
+
state.connected = false
|
|
363
|
+
state.reason = 'menu registration refused'
|
|
364
|
+
await sleep(RETRY_MS)
|
|
365
|
+
continue
|
|
366
|
+
}
|
|
367
|
+
state.connected = true
|
|
368
|
+
state.reason = ''
|
|
369
|
+
}
|
|
370
|
+
const batch = await call(
|
|
371
|
+
`${root}/menu/events?owner=${encodeURIComponent(OWNER)}&wait=${POLL_WAIT_MS}`,
|
|
372
|
+
{ timeoutMs: POLL_WAIT_MS + 5_000 },
|
|
373
|
+
)
|
|
374
|
+
if (batch?.ok !== true) {
|
|
375
|
+
// A leftover long poll and a `dsh-pet` restart look the same here: drop
|
|
376
|
+
// the registration and let the next round re-establish both.
|
|
377
|
+
registered = false
|
|
378
|
+
state.connected = false
|
|
379
|
+
state.reason = 'pet unreachable'
|
|
380
|
+
await sleep(RETRY_MS)
|
|
381
|
+
continue
|
|
382
|
+
}
|
|
383
|
+
// `dsh-pet` answers `{ ok, events: { label: petId | null } }`: a null slot
|
|
384
|
+
// means "registered but not clicked", which is the common case.
|
|
385
|
+
const clicks = batch?.events !== null && typeof batch?.events === 'object' ? batch.events : {}
|
|
386
|
+
for (const [label, pet] of Object.entries(clicks)) {
|
|
387
|
+
if (typeof pet !== 'string' || pet === '') continue // unused click slot
|
|
388
|
+
try {
|
|
389
|
+
await onMenuClick(label)
|
|
390
|
+
} catch (error) {
|
|
391
|
+
logger?.warn?.(`wf: 菜单动作失败(${error instanceof Error ? error.message : String(error)})`)
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/** Refresh the feed and nudge open panels when the ledger file moved. */
|
|
398
|
+
function watchLoop() {
|
|
399
|
+
feedTimer = setInterval(() => {
|
|
400
|
+
if (stopped) return
|
|
401
|
+
try {
|
|
402
|
+
const stamp = String(fs.statSync(`${options.homeDir}/tasks/index.md`).mtimeMs)
|
|
403
|
+
if (ledgerStamp !== '' && stamp !== ledgerStamp) pushEvent('changed')
|
|
404
|
+
ledgerStamp = stamp
|
|
405
|
+
} catch {
|
|
406
|
+
// An unreadable ledger is the panel's problem to show, not the loop's.
|
|
407
|
+
}
|
|
408
|
+
void feed()
|
|
409
|
+
}, 30_000)
|
|
410
|
+
feedTimer.unref?.()
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
void pollLoop()
|
|
414
|
+
watchLoop()
|
|
415
|
+
|
|
416
|
+
return {
|
|
417
|
+
/** Liveness facts for `/wf/info` and the settings page. */
|
|
418
|
+
status() {
|
|
419
|
+
return {
|
|
420
|
+
connected: state.connected,
|
|
421
|
+
owner: OWNER,
|
|
422
|
+
petId: state.petId,
|
|
423
|
+
display: state.display,
|
|
424
|
+
labels: Object.values(LABELS),
|
|
425
|
+
reason: state.reason,
|
|
426
|
+
lastFeedAt: state.lastFeedAt,
|
|
427
|
+
lastAction: state.lastAction,
|
|
428
|
+
}
|
|
429
|
+
},
|
|
430
|
+
/** Stop polling; used when the row is disposed. */
|
|
431
|
+
stop() {
|
|
432
|
+
stopped = true
|
|
433
|
+
if (feedTimer !== undefined) {
|
|
434
|
+
clearInterval(feedTimer)
|
|
435
|
+
feedTimer = undefined
|
|
436
|
+
}
|
|
437
|
+
},
|
|
438
|
+
}
|
|
439
|
+
}
|