dsh-qq-affinity 1.0.0 → 1.5.6

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,166 @@
1
+ // Group-room analysis: the statistics behind it, and the stored verdict.
2
+ // - groupFeatures(): who speaks, when, how fast the room moves
3
+ // - analyzeGroup(): cached, incremental, and stored per conversation
4
+ import fs from 'node:fs'
5
+ import os from 'node:os'
6
+ import path from 'node:path'
7
+ import { fileURLToPath, pathToFileURL } from 'node:url'
8
+
9
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
10
+ const href = (rel) => pathToFileURL(path.join(root, rel)).href
11
+ const { Store } = await import(href('lib/store.js'))
12
+ const { groupFeatures } = await import(href('lib/features.js'))
13
+ const { analyzeGroup } = await import(href('lib/analyze.js'))
14
+
15
+ let failures = 0
16
+ const check = (label, ok, extra = '') => {
17
+ console.log(` ${ok ? 'ok ' : 'FAIL'} ${label}${extra === '' ? '' : ` :: ${extra}`}`)
18
+ if (!ok) failures += 1
19
+ }
20
+
21
+ const GROUP_ANSWER = JSON.stringify({
22
+ summary: '一个熟人局,白天聊工作和工具,晚上互相打趣。',
23
+ topics: [
24
+ { label: '折腾配置', share: 0.4, evidence: '「这个参数我又调了一晚上」' },
25
+ { label: '日常吐槽', share: 0.25, evidence: '「今天又加班」' },
26
+ ],
27
+ atmosphere: {
28
+ label: '熟人局的日常碎碎念',
29
+ energy: 68,
30
+ warmth: 62,
31
+ order: 40,
32
+ seriousness: 35,
33
+ evidence: ['「笑死」连着刷了三条'],
34
+ },
35
+ coreMembers: [
36
+ { uin: '10001', name: '小明', role: '话题发起', evidence: '每天都先开口' },
37
+ { uin: '10002', name: '小红', role: '气氛担当', evidence: '「笑死」' },
38
+ ],
39
+ norms: ['深夜不聊工作'],
40
+ cautions: ['别在群里催进度'],
41
+ howToJoin: ['接着别人的话茬问一句具体细节'],
42
+ confidence: 0.55,
43
+ })
44
+
45
+ const prompts = []
46
+ function fakeStream(options) {
47
+ prompts.push(options.messages?.[0]?.content?.[0]?.text ?? '')
48
+ const text = GROUP_ANSWER
49
+ return (async function* () {
50
+ for (let i = 0; i < text.length; i += 200) {
51
+ yield { type: 'text-delta', index: 0, text: text.slice(i, i + 200) }
52
+ }
53
+ yield { type: 'usage', usage: { inputTokens: 2400, outputTokens: 420 } }
54
+ yield { type: 'finish', reason: { kind: 'stop' } }
55
+ })()
56
+ }
57
+
58
+ function makeCtx() {
59
+ return {
60
+ get(name) {
61
+ if (name === 'agentDefaultModel') return { currentSelection: () => ({ provider: 'stub', model: 'stub-flash' }) }
62
+ if (name === 'llm') {
63
+ return {
64
+ stream: options => fakeStream(options),
65
+ listProviders: () => [{ id: 'stub' }],
66
+ listModels: async () => [{ id: 'stub-flash' }],
67
+ // Text-only, so the vision gate short-circuits and no download happens.
68
+ resolveModelInfo: async () => ({ inputModalities: ['text'] }),
69
+ }
70
+ }
71
+ return undefined
72
+ },
73
+ }
74
+ }
75
+
76
+ // ------------------------------------------------------------------ fixture
77
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qq-affinity-group-'))
78
+ process.env.DSH_QQ_AFFINITY_HOME = dir
79
+ const store = new Store(dir)
80
+ store.state.settings.selfUin = '20002'
81
+ store.state.settings.selfName = '我'
82
+ const conversation = store.ensureConversation({ kind: 'group', title: '折腾群', groupUin: '900123' }).conversation
83
+ store.setEnabled(conversation.id, true)
84
+
85
+ const base = Date.UTC(2024, 0, 1, 12, 0, 0)
86
+ const speakers = ['10001', '10002', '10003']
87
+ const rows = []
88
+ for (let index = 0; index < 30; index += 1) {
89
+ const isMine = index % 10 === 7
90
+ const sender = isMine ? '20002' : speakers[index % speakers.length]
91
+ const text = index % 6 === 0
92
+ ? `@20002 这个参数我又调了一晚上 ${index}`
93
+ : index % 4 === 0 ? '笑死' : `第 ${index} 条,今天又加班`
94
+ rows.push({ ts: base + index * 60_000, senderUin: sender, senderName: sender === '10001' ? '小明' : sender === '10002' ? '小红' : sender === '10003' ? '小刚' : '我', text })
95
+ }
96
+ store.appendMessages(conversation.id, rows)
97
+
98
+ console.log('\n== groupFeatures reads the room ==')
99
+ const features = groupFeatures(store.messages(conversation.id), '20002')
100
+ check('counts every message', features.totalMessages === 30, `${features.totalMessages}`)
101
+ check('finds the speakers', features.activeSpeakers === 4, `${features.activeSpeakers}`)
102
+ check('ranks the busiest first', features.speakers[0].messages >= features.speakers[1].messages, JSON.stringify(features.speakers.map(s => s.messages)))
103
+ check('names come from the rows', features.speakers.some(speaker => speaker.name === '小明'), JSON.stringify(features.speakers.map(s => s.name)))
104
+ check('my share is counted', features.myMessages === 3 && features.myShare > 0, `${features.myMessages}/${features.myShare}`)
105
+ check('mentions of me are counted', features.atMeMessages === 5, `${features.atMeMessages}`)
106
+ check('hours come from the clock', features.hourHistogram.length === 24 && features.peakHours.length >= 1, JSON.stringify(features.peakHours))
107
+ check('shares add up to about one', Math.abs(features.speakers.reduce((sum, speaker) => sum + speaker.share, 0) - 1) < 0.02, String(features.speakers.reduce((sum, speaker) => sum + speaker.share, 0)))
108
+ check('bursts are detected', features.bursts >= 1, `${features.bursts}`)
109
+
110
+ console.log('\n== analyzeGroup asks the model once and stores the verdict ==')
111
+ const ctx = makeCtx()
112
+ const first = await analyzeGroup(ctx, store, conversation.id)
113
+ check('it returns a summary', typeof first.summary === 'string' && first.summary !== '', first.summary)
114
+ check('topics came through', first.topics.length === 2 && first.topics[0].share > 0, JSON.stringify(first.topics))
115
+ check('the atmosphere has four dimensions', typeof first.atmosphere.energy === 'number' && typeof first.atmosphere.warmth === 'number'
116
+ && typeof first.atmosphere.order === 'number' && typeof first.atmosphere.seriousness === 'number', JSON.stringify(first.atmosphere))
117
+ check('core members keep their uin', first.coreMembers[0].uin === '10001', JSON.stringify(first.coreMembers))
118
+ check('norms and cautions are stored', first.norms.length === 1 && first.cautions.length === 1, JSON.stringify([first.norms, first.cautions]))
119
+ check('the prompt names the group', prompts[0].includes('折腾群'), prompts[0].slice(0, 80))
120
+ check('the prompt carries the speaker table', prompts[0].includes('说话人分布'), prompts[0].slice(0, 200))
121
+ check('token usage is recorded', first.usage.inputTokens === 2400, JSON.stringify(first.usage))
122
+ check('the measured stats ride along', first.stats.activeSpeakers === 4 && first.stats.atMeMessages === 5, JSON.stringify(first.stats).slice(0, 120))
123
+ check('the verdict is stored on the conversation', store.groupProfile(conversation.id)?.summary === first.summary, 'ok')
124
+ check('the evidence is fingerprinted', typeof first.basedOn.fingerprint === 'string' && first.basedOn.fingerprint !== '', first.basedOn.fingerprint)
125
+
126
+ console.log('\n== unchanged evidence is reused ==')
127
+ const callsBefore = prompts.length
128
+ const second = await analyzeGroup(ctx, store, conversation.id)
129
+ check('the stored analysis is reused', second.reused === true, String(second.reused))
130
+ check('no model call was made', prompts.length === callsBefore, `${prompts.length - callsBefore}`)
131
+
132
+ console.log('\n== new messages switch to an incremental run ==')
133
+ store.appendMessages(conversation.id, [
134
+ { ts: base + 30 * 60_000 + 5 * 60_000, senderUin: '10002', senderName: '小红', text: '今晚谁还在' },
135
+ ])
136
+ const third = await analyzeGroup(ctx, store, conversation.id)
137
+ check('the run is incremental', third.basedOn.incremental === true, JSON.stringify(third.basedOn))
138
+ check('it only covers the new rows', third.basedOn.deltaMessages === 1, `${third.basedOn.deltaMessages}`)
139
+ check('the prompt carries the previous verdict', prompts[prompts.length - 1].includes('【上次的群聊分析'), prompts[prompts.length - 1].slice(0, 120))
140
+
141
+ console.log('\n== guards ==')
142
+ const privateChat = store.ensureConversation({ kind: 'c2c', title: '私聊', peerUin: '10001' }).conversation
143
+ let refused = ''
144
+ try {
145
+ await analyzeGroup(ctx, store, privateChat.id)
146
+ } catch (error) {
147
+ refused = error.message
148
+ }
149
+ check('a private chat is refused', refused.includes('只有群聊'), refused)
150
+ const tiny = store.ensureConversation({ kind: 'group', title: '空群', groupUin: '900999' }).conversation
151
+ store.setEnabled(tiny.id, true)
152
+ let tooSmall = ''
153
+ try {
154
+ await analyzeGroup(ctx, store, tiny.id)
155
+ } catch (error) {
156
+ tooSmall = error.message
157
+ }
158
+ check('a tiny group is refused', tooSmall.includes('至少需要 20 条'), tooSmall)
159
+
160
+ console.log('\n== deleting a group drops its analysis ==')
161
+ store.removeConversation(conversation.id)
162
+ check('the stored analysis is gone', store.groupProfile(conversation.id) === undefined, 'ok')
163
+
164
+ console.log(failures === 0 ? '\nALL PASS' : `\n${failures} FAILURE(S)`)
165
+ fs.rmSync(dir, { recursive: true, force: true })
166
+ process.exit(failures === 0 ? 0 : 1)
@@ -0,0 +1,161 @@
1
+ // Reply personas: the built-in presets, the open "add your own" interface, and
2
+ // the fact that a persona actually changes the prompt the model sees.
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+ import { fileURLToPath, pathToFileURL } from 'node:url'
7
+
8
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
9
+ const href = (rel) => pathToFileURL(path.join(root, rel)).href
10
+ const { Store } = await import(href('lib/store.js'))
11
+ const { REPLY_PERSONAS, listPersonas, resolvePersona, presetPersona } = await import(href('lib/personas.js'))
12
+ const { writeAutoReply } = await import(href('lib/analyze.js'))
13
+ const { createRoutes } = await import(href('lib/api.js'))
14
+
15
+ let failures = 0
16
+ const check = (label, ok, extra = '') => {
17
+ console.log(` ${ok ? 'ok ' : 'FAIL'} ${label}${extra === '' ? '' : ` :: ${extra}`}`)
18
+ if (!ok) failures += 1
19
+ }
20
+
21
+ const prompts = []
22
+ function makeCtx() {
23
+ return {
24
+ get(name) {
25
+ if (name === 'agentDefaultModel') return { currentSelection: () => ({ provider: 'stub', model: 'stub-flash' }) }
26
+ if (name === 'llm') {
27
+ return {
28
+ stream(options) {
29
+ prompts.push(options.messages?.[0]?.content?.[0]?.text ?? '')
30
+ const text = '好的前辈 我马上确认一下参数'
31
+ return (async function* () {
32
+ yield { type: 'text-delta', index: 0, text }
33
+ yield { type: 'usage', usage: { inputTokens: 900, outputTokens: 40 } }
34
+ yield { type: 'finish', reason: { kind: 'stop' } }
35
+ })()
36
+ },
37
+ listProviders: () => [{ id: 'stub' }],
38
+ listModels: async () => [{ id: 'stub-flash' }],
39
+ resolveModelInfo: async () => ({ inputModalities: ['text'] }),
40
+ }
41
+ }
42
+ return undefined
43
+ },
44
+ }
45
+ }
46
+
47
+ console.log('\n== the built-ins ==')
48
+ check('only the default ships', REPLY_PERSONAS.length === 1, `${REPLY_PERSONAS.length}`)
49
+ check('the default imitates me', presetPersona('default').prompt === '', `"${presetPersona('default').prompt}"`)
50
+ check('小莫宁 is not built in any more', presetPersona('moning') === undefined)
51
+ check('弗洛洛 is not built in any more', presetPersona('fuluoluo') === undefined)
52
+ check('presets are listed before custom ones', listPersonas([{ id: 'custom-1', name: '我的', prompt: '直白' }]).length === 2, 'ok')
53
+ check('a custom persona can use a character name', listPersonas([{ id: 'custom-2', name: '小莫宁', prompt: '一口一个前辈' }])[1].name === '小莫宁')
54
+
55
+ console.log('\n== resolving a persona ==')
56
+ check('the default resolves', resolvePersona([], 'default').id === 'default')
57
+ check('a removed preset falls back to default', resolvePersona([], 'moning').id === 'default', resolvePersona([], 'moning').id)
58
+ check('an unknown id falls back to default', resolvePersona([], 'nope').id === 'default', resolvePersona([], 'nope').id)
59
+ check('a custom persona resolves', resolvePersona([{ id: 'custom-7', name: '老王', prompt: '直白' }], 'custom-7').name === '老王')
60
+ check('an empty stored list is fine', resolvePersona(undefined, undefined).id === 'default')
61
+
62
+ // ------------------------------------------------------------------- archive
63
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qq-affinity-persona-'))
64
+ process.env.DSH_QQ_AFFINITY_HOME = dir
65
+ const store = new Store(dir)
66
+ store.state.settings.selfUin = '20002'
67
+ store.state.settings.selfName = '我'
68
+ const chat = store.ensureConversation({ kind: 'c2c', title: '小明', peerUin: '10001' }).conversation
69
+ store.setEnabled(chat.id, true)
70
+ store.appendMessages(chat.id, [
71
+ { ts: 1700000000000, senderUin: '10001', senderName: '小明', text: '在吗' },
72
+ { ts: 1700000060000, senderUin: '20002', senderName: '我', text: '在' },
73
+ { ts: 1700000120000, senderUin: '10001', senderName: '小明', text: '那个参数你看了吗' },
74
+ ])
75
+
76
+ console.log('\n== a persona changes the prompt ==')
77
+ const ctx = makeCtx()
78
+ // Only the default ships now, so a character voice has to be added first.
79
+ const voice = store.addReplyPersona({
80
+ name: '小莫宁',
81
+ prompt: '称呼对方为「前辈」,语气礼貌认真,先给结论再补依据,偶尔卡一下用省略号。',
82
+ })
83
+ store.setCare('10001', { persona: voice.id })
84
+ check('setCare keeps the persona', store.state.care['10001'].persona === voice.id, store.state.care['10001'].persona)
85
+ const inCharacter = await writeAutoReply(ctx, store, { conversationId: chat.id, uin: '10001', maxChars: 60 })
86
+ check('the reply still comes back as text', typeof inCharacter === 'string' && inCharacter !== '', inCharacter)
87
+ check('the prompt carries the persona block', prompts[prompts.length - 1].includes('【说话人设】'), prompts[prompts.length - 1].slice(0, 80))
88
+ check('the prompt names the character', prompts[prompts.length - 1].includes('小莫宁'), 'ok')
89
+ check('the transcript is marked as reference only', prompts[prompts.length - 1].includes('不要模仿我的语气'), 'ok')
90
+
91
+ store.setCare('10001', { persona: 'default' })
92
+ await writeAutoReply(ctx, store, { conversationId: chat.id, uin: '10001', maxChars: 60 })
93
+ check('the default persona has no persona block', !prompts[prompts.length - 1].includes('【说话人设】'), 'ok')
94
+ check('the default keeps my own voice', prompts[prompts.length - 1].includes('以我的身份'), 'ok')
95
+
96
+ console.log('\n== adding a custom persona through the store ==')
97
+ const beforeAdd = store.customPersonas().length
98
+ const added = store.addReplyPersona({ name: '隔壁老王', prompt: '说话直白,爱用短句,习惯反问。' })
99
+ check('it gets a custom id', added !== undefined && added.id.startsWith('custom-'), JSON.stringify(added?.id))
100
+ check('an empty draft is refused', store.addReplyPersona({ name: '', prompt: 'x' }) === undefined)
101
+ const second = store.addReplyPersona({ name: '二号', prompt: '温和一点' })
102
+ check('ids do not collide', second.id !== added.id, `${added.id} / ${second.id}`)
103
+ check('both are listed', store.customPersonas().length === beforeAdd + 2, `${store.customPersonas().length}`)
104
+ check('the picker lists one preset plus the customs', listPersonas(store.customPersonas()).length === beforeAdd + 3, `${listPersonas(store.customPersonas()).length}`)
105
+ check('removing one works', store.removeReplyPersona(added.id) === true && store.customPersonas().length === beforeAdd + 1)
106
+ check('removing an unknown id is refused', store.removeReplyPersona('custom-999') === false)
107
+
108
+ console.log('\n== the API interface ==')
109
+ const routes = createRoutes(ctx, store, undefined, undefined, {})
110
+ const byPath = new Map()
111
+ for (const route of routes) {
112
+ const entry = byPath.get(route.path) ?? {}
113
+ entry[route.method] = route
114
+ byPath.set(route.path, entry)
115
+ }
116
+ const call = async (routePath, { method = 'GET', body } = {}) => {
117
+ const route = byPath.get(routePath)?.[method]
118
+ if (route === undefined) throw new Error(`missing route ${routePath} [${method}]`)
119
+ const init = { method, headers: {} }
120
+ if (body !== undefined) {
121
+ init.headers['content-type'] = 'application/json'
122
+ init.body = JSON.stringify(body)
123
+ }
124
+ const response = await route.fetch(new Request(`http://localhost${routePath}`, init))
125
+ return { status: response.status, value: await response.json() }
126
+ }
127
+
128
+ let result = await call('/api/qq-affinity/state')
129
+ check('state lists the picker options', (result.value.replyPersonas ?? []).length === 3, `${(result.value.replyPersonas ?? []).length}`)
130
+ check('state marks which are custom', result.value.replyPersonas.some(entry => entry.custom === true))
131
+ check('no removed preset survives in the picker', !result.value.replyPersonas.some(entry => entry.id === 'moning' || entry.id === 'fuluoluo'))
132
+
133
+ result = await call('/api/qq-affinity/personas', { method: 'POST', body: { action: 'add', name: '测试人设', prompt: '只回短句' } })
134
+ check('add works', result.value.ok === true && result.value.persona.name === '测试人设', JSON.stringify(result.value.persona))
135
+ check('the response returns the whole list', result.value.personas.length === 4, `${result.value.personas.length}`)
136
+ const newId = result.value.persona.id
137
+
138
+ result = await call('/api/qq-affinity/personas', { method: 'POST', body: { action: 'add', name: '', prompt: 'x' } })
139
+ check('an empty name is refused', result.status === 400, `${result.status}`)
140
+
141
+ // Point someone at the new persona, then delete it: they must fall back.
142
+ await call('/api/qq-affinity/care', { method: 'POST', body: { uin: '10001', patch: { persona: newId } } })
143
+ check('care accepts the custom persona', store.state.care['10001'].persona === newId, store.state.care['10001'].persona)
144
+ result = await call('/api/qq-affinity/personas', { method: 'POST', body: { action: 'delete', id: newId } })
145
+ check('delete works', result.value.ok === true && result.value.personas.length === 3, JSON.stringify(result.value.resetTo))
146
+ check('whoever used it fell back to default', store.state.care['10001'].persona === 'default', store.state.care['10001'].persona)
147
+
148
+ result = await call('/api/qq-affinity/personas', { method: 'POST', body: { action: 'delete', id: 'default' } })
149
+ check('a built-in cannot be deleted', result.status === 409, `${result.status}`)
150
+
151
+ result = await call('/api/qq-affinity/personas', { method: 'POST', body: { action: 'delete', id: 'custom-404' } })
152
+ check('an unknown custom id is 404', result.status === 404, `${result.status}`)
153
+
154
+ console.log('\n== a persona survives a reload ==')
155
+ const reloaded = new Store(dir)
156
+ check('the stored persona is read back', reloaded.state.care['10001'].persona === 'default', reloaded.state.care['10001'].persona)
157
+ check('the custom persona list is read back', reloaded.customPersonas().length === 2, `${reloaded.customPersonas().length}`)
158
+
159
+ console.log(failures === 0 ? '\nALL PASS' : `\n${failures} FAILURE(S)`)
160
+ fs.rmSync(dir, { recursive: true, force: true })
161
+ process.exit(failures === 0 ? 0 : 1)
@@ -0,0 +1,86 @@
1
+ // The task registry behind the panel's task list: begin → update/queue → finish,
2
+ // with finished tasks lingering briefly so the UI can show how they ended.
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+ import { fileURLToPath, pathToFileURL } from 'node:url'
7
+
8
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
9
+ const href = (rel) => pathToFileURL(path.join(root, rel)).href
10
+ const { createTaskRegistry } = await import(href('lib/tasks.js'))
11
+ const { Store } = await import(href('lib/store.js'))
12
+
13
+ let failures = 0
14
+ const check = (label, ok, extra = '') => {
15
+ console.log(` ${ok ? 'ok ' : 'FAIL'} ${label}${extra === '' ? '' : ` :: ${extra}`}`)
16
+ if (!ok) failures += 1
17
+ }
18
+
19
+ let clock = 1_000_000
20
+ const now = () => clock
21
+ const registry = createTaskRegistry({ now, keepFinishedMs: 5000 })
22
+
23
+ console.log('\n== a running task ==')
24
+ const first = registry.begin({ kind: 'score', label: '好感度分析', detail: '小明' })
25
+ let listed = registry.list()
26
+ check('one task is listed', listed.length === 1, `${listed.length}`)
27
+ check('it carries its label and detail', listed[0].label === '好感度分析' && listed[0].detail === '小明', JSON.stringify(listed[0]))
28
+ check('it starts as running', listed[0].state === 'running', listed[0].state)
29
+
30
+ console.log('\n== progress and queue ==')
31
+ const batch = registry.begin({ kind: 'refresh', label: '批量更新', total: 5 })
32
+ registry.update(batch, { done: 2, detail: '小红' })
33
+ registry.setQueue(batch, ['A', 'B', 'C'])
34
+ listed = registry.list()
35
+ const batchRow = listed.find(row => row.id === batch)
36
+ check('progress is reported', batchRow.done === 2 && batchRow.total === 5, JSON.stringify(batchRow))
37
+ check('the queue is exposed', batchRow.queuedCount === 3 && batchRow.queued[0] === 'A', JSON.stringify(batchRow.queued))
38
+
39
+ console.log('\n== finishing ==')
40
+ registry.finish(first)
41
+ listed = registry.list()
42
+ const firstRow = listed.find(row => row.id === first)
43
+ check('the finished task says done', firstRow.state === 'done', firstRow.state)
44
+ check('and keeps no queue', firstRow.queued.length === 0)
45
+ clock += 6000
46
+ check('it disappears after the grace period', !registry.list().some(row => row.id === first), JSON.stringify(registry.list().map(row => row.id)))
47
+
48
+ console.log('\n== failure ==')
49
+ const failing = registry.begin({ kind: 'persona', label: '人格画像' })
50
+ registry.finish(failing, '模型调用失败')
51
+ const failedRow = registry.list().find(row => row.id === failing)
52
+ check('a failed task keeps its reason', failedRow.state === 'failed' && failedRow.error === '模型调用失败', JSON.stringify(failedRow))
53
+
54
+ console.log('\n== the snapshot exposes tasks ==')
55
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qq-affinity-tasks-'))
56
+ process.env.DSH_QQ_AFFINITY_HOME = dir
57
+ const { createRoutes } = await import(href('lib/api.js'))
58
+ const store = new Store(dir)
59
+ const routes = createRoutes({ get: () => undefined }, store, undefined, undefined, { tasks: registry })
60
+ const stateRoute = routes.find(route => route.path === '/api/qq-affinity/state')
61
+ const response = await stateRoute.fetch(new Request('http://localhost/api/qq-affinity/state'))
62
+ const snapshot = await response.json()
63
+ check('the state route reports tasks', Array.isArray(snapshot.tasks) && snapshot.tasks.length >= 2, JSON.stringify(snapshot.tasks?.map(row => row.label)))
64
+
65
+ console.log('\n== the registry is bounded ==')
66
+ const small = createTaskRegistry({ now, keepFinishedMs: 5000, maxTasks: 3 })
67
+ for (let index = 0; index < 6; index += 1) {
68
+ const id = small.begin({ kind: 'x', label: `任务${index}` })
69
+ if (index % 2 === 0) small.finish(id)
70
+ }
71
+ check('it never holds more than maxTasks running entries', small.list().length <= 4, `${small.list().length}`)
72
+
73
+ console.log('\n== the real clock is the default ==')
74
+ // The plugin constructs the registry with no options at all; an undefined `now`
75
+ // used to make every /state request throw.
76
+ const plain = createTaskRegistry()
77
+ const plainId = plain.begin({ kind: 'score', label: '默认时钟' })
78
+ const plainRow = plain.list()[0]
79
+ check('a registry without options works', plainRow !== undefined && plainRow.label === '默认时钟', JSON.stringify(plainRow))
80
+ check('it uses a real timestamp', typeof plainRow.startedAt === 'number' && plainRow.startedAt > 1_700_000_000_000, `${plainRow.startedAt}`)
81
+ plain.finish(plainId)
82
+ check('finishing works too', plain.list()[0].state === 'done', JSON.stringify(plain.list()[0]))
83
+
84
+ console.log(failures === 0 ? '\nALL PASS' : `\n${failures} FAILURE(S)`)
85
+ fs.rmSync(dir, { recursive: true, force: true })
86
+ process.exit(failures === 0 ? 0 : 1)