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.
package/lib/store.js CHANGED
@@ -64,6 +64,12 @@ function emptyMeta() {
64
64
  personas: {},
65
65
  /** Per-QQ-number automatic reply settings. */
66
66
  care: {},
67
+ /** Per-conversation group analysis, keyed by conversation id. */
68
+ groupProfiles: {},
69
+ /** User-added reply personas; the built-in presets live in code. */
70
+ replyPersonas: [],
71
+ /** uin -> ISO time the hourly reply quota was last reset by hand. */
72
+ careReset: {},
67
73
  /** User-arranged display order for the two left-hand lists. */
68
74
  order: { conversations: [], people: [] },
69
75
  /** Pinned conversation ids, first is topmost. Multiple pins allowed. */
@@ -83,6 +89,13 @@ export function defaultCare() {
83
89
  quietTo: '08:00',
84
90
  groupOnlyWhenMentioned: true,
85
91
  maxReplyChars: 60,
92
+ /** Reply voice: 'default' (imitate me), a preset id, or a custom persona id. */
93
+ persona: 'default',
94
+ /**
95
+ * Seconds to wait before answering, so a burst of messages gets one reply
96
+ * instead of several. Every new message restarts the wait. 0 = answer at once.
97
+ */
98
+ replyDelaySeconds: 5,
86
99
  updatedAt: new Date().toISOString(),
87
100
  }
88
101
  }
@@ -94,6 +107,15 @@ function normalizeMeta(raw) {
94
107
  const settings = raw.settings !== null && typeof raw.settings === 'object' ? raw.settings : {}
95
108
  const onebot = settings.onebot !== null && typeof settings.onebot === 'object' ? settings.onebot : {}
96
109
  const care = {}
110
+ // Personas are parsed first: a care entry may point at a custom one, and a
111
+ // persona that no longer exists must fall back to the default voice instead of
112
+ // leaving a dangling id in the settings.
113
+ const customPersonas = Array.isArray(raw.replyPersonas) ? raw.replyPersonas : []
114
+ const knownPersona = (id) => {
115
+ const value = typeof id === 'string' ? id : ''
116
+ if (value === 'default') return 'default'
117
+ return customPersonas.some(entry => entry !== null && typeof entry === 'object' && entry.id === value) ? value : 'default'
118
+ }
97
119
  if (raw.care !== null && typeof raw.care === 'object') {
98
120
  for (const [uin, value] of Object.entries(raw.care)) {
99
121
  if (value === null || typeof value !== 'object') continue
@@ -108,6 +130,10 @@ function normalizeMeta(raw) {
108
130
  quietTo: typeof value.quietTo === 'string' ? value.quietTo : fallback.quietTo,
109
131
  groupOnlyWhenMentioned: value.groupOnlyWhenMentioned !== false,
110
132
  maxReplyChars: Number.isFinite(Number(value.maxReplyChars)) ? Math.min(300, Math.max(10, Number(value.maxReplyChars))) : fallback.maxReplyChars,
133
+ persona: knownPersona(value.persona),
134
+ replyDelaySeconds: Number.isFinite(Number(value.replyDelaySeconds))
135
+ ? Math.min(300, Math.max(0, Math.round(Number(value.replyDelaySeconds))))
136
+ : fallback.replyDelaySeconds,
111
137
  updatedAt: typeof value.updatedAt === 'string' ? value.updatedAt : fallback.updatedAt,
112
138
  }
113
139
  }
@@ -151,6 +177,9 @@ function normalizeMeta(raw) {
151
177
  adoptions: Array.isArray(raw.adoptions) ? raw.adoptions.filter(row => row !== null && typeof row === 'object') : [],
152
178
  personas: raw.personas !== null && typeof raw.personas === 'object' ? raw.personas : {},
153
179
  care,
180
+ groupProfiles: raw.groupProfiles !== null && typeof raw.groupProfiles === 'object' ? raw.groupProfiles : {},
181
+ replyPersonas: customPersonas,
182
+ careReset: raw.careReset !== null && typeof raw.careReset === 'object' ? raw.careReset : {},
154
183
  order: {
155
184
  conversations: Array.isArray(raw.order?.conversations) ? raw.order.conversations.filter(v => typeof v === 'string') : [],
156
185
  people: Array.isArray(raw.order?.people) ? raw.order.people.filter(v => typeof v === 'string') : [],
@@ -387,6 +416,8 @@ export class Store {
387
416
  this.state.conversations.splice(index, 1)
388
417
  fs.rmSync(this.messagesFile(id), { force: true })
389
418
  fs.rmSync(this.suggestionsFile(id), { force: true })
419
+ delete this.state.groupProfiles[id]
420
+ this.state.pinned = this.state.pinned.filter(value => value !== id)
390
421
  this.save()
391
422
  this.rebuildPeople()
392
423
  return true
@@ -486,6 +517,68 @@ export class Store {
486
517
  return this.state.selfProfile ?? null
487
518
  }
488
519
 
520
+ /** Record one group analysis for a conversation. */
521
+ saveGroupProfile(conversationId, result) {
522
+ this.state.groupProfiles[conversationId] = { ...result, conversationId, updatedAt: new Date().toISOString() }
523
+ this.save()
524
+ return this.state.groupProfiles[conversationId]
525
+ }
526
+
527
+ /** The stored group analysis for a conversation, or undefined. */
528
+ groupProfile(conversationId) {
529
+ return this.state.groupProfiles[conversationId]
530
+ }
531
+
532
+ /** Every user-added reply persona. */
533
+ customPersonas() {
534
+ return this.state.replyPersonas
535
+ }
536
+
537
+ /**
538
+ * Add one custom reply persona. The id is derived from a counter so it never
539
+ * collides with a built-in preset id.
540
+ * @param {{ name: string, prompt: string }} draft
541
+ */
542
+ addReplyPersona(draft) {
543
+ const name = String(draft?.name ?? '').trim().slice(0, 40)
544
+ const prompt = String(draft?.prompt ?? '').trim().slice(0, 2000)
545
+ if (name === '' || prompt === '') return undefined
546
+ let index = this.state.replyPersonas.length + 1
547
+ const taken = new Set(this.state.replyPersonas.map(entry => entry.id))
548
+ while (taken.has(`custom-${index}`)) index += 1
549
+ const entry = { id: `custom-${index}`, name, prompt, createdAt: new Date().toISOString() }
550
+ this.state.replyPersonas.push(entry)
551
+ this.save()
552
+ return entry
553
+ }
554
+
555
+ /** Remove one custom persona; returns whether it existed. */
556
+ removeReplyPersona(id) { const before = this.state.replyPersonas.length
557
+ this.state.replyPersonas = this.state.replyPersonas.filter(entry => entry.id !== id)
558
+ if (this.state.replyPersonas.length === before) return false
559
+ this.save()
560
+ return true
561
+ }
562
+
563
+ /**
564
+ * Forget the hourly reply count for one person.
565
+ *
566
+ * Stored as a timestamp rather than by deleting outbox rows: the record of what
567
+ * was said stays intact, the quota simply starts counting from now.
568
+ */
569
+ resetCareCount(uin) {
570
+ const key = String(uin)
571
+ this.state.careReset[key] = new Date().toISOString()
572
+ this.save()
573
+ return this.state.careReset[key]
574
+ }
575
+
576
+ /** When this person's quota was last reset by hand, in ms; 0 when never. */
577
+ careResetAt(uin) {
578
+ const at = Date.parse(this.state.careReset[String(uin)] ?? '')
579
+ return Number.isFinite(at) ? at : 0
580
+ }
581
+
489
582
  /** Pin one conversation to the top; returns the pinned list, first is topmost. */
490
583
  pin(id) {
491
584
  if (!this.state.pinned.includes(id)) {
@@ -636,7 +729,7 @@ export class Store {
636
729
  const next = { ...current }
637
730
  if (typeof patch.enabled === 'boolean') next.enabled = patch.enabled
638
731
  if (patch.mode === 'auto' || patch.mode === 'draft') next.mode = patch.mode
639
- for (const [field, min, max] of [['hourlyCap', 1, 60], ['maxReplyChars', 10, 300]]) {
732
+ for (const [field, min, max] of [['hourlyCap', 1, 60], ['maxReplyChars', 10, 300], ['replyDelaySeconds', 0, 300]]) {
640
733
  if (patch[field] === undefined) continue
641
734
  const value = Number(patch[field])
642
735
  if (Number.isFinite(value)) next[field] = Math.round(Math.min(max, Math.max(min, value)))
@@ -648,6 +741,10 @@ export class Store {
648
741
  if (value === '' || minutesOfClock(value) !== undefined) next[field] = value
649
742
  }
650
743
  if (typeof patch.groupOnlyWhenMentioned === 'boolean') next.groupOnlyWhenMentioned = patch.groupOnlyWhenMentioned
744
+ // 'default', a preset id, or a custom persona id. An unknown id still saves —
745
+ // resolution falls back to the default voice, and a deleted custom persona
746
+ // should not silently rewrite the user's choice back to 'default'.
747
+ if (typeof patch.persona === 'string' && patch.persona.trim() !== '') next.persona = patch.persona.trim().slice(0, 60)
651
748
  next.updatedAt = new Date().toISOString()
652
749
  this.state.care[key] = next
653
750
  this.save()
@@ -678,6 +775,17 @@ export class Store {
678
775
  inboundTs: row.inboundTs ?? 0,
679
776
  text: row.text ?? '',
680
777
  status: row.status ?? 'draft',
778
+ // 'reply' for a normal answer, 'excuse' for the one polite brush-off sent
779
+ // when the hourly cap is reached.
780
+ kind: row.kind === 'excuse' ? 'excuse' : 'reply',
781
+ // How many inbound messages this one row answers (the debounce coalesces).
782
+ inboundCount: Number.isFinite(Number(row.inboundCount)) ? Number(row.inboundCount) : 1,
783
+ // Which reply persona produced this text, so the record stays readable after
784
+ // the persona is renamed or deleted.
785
+ personaId: typeof row.personaId === 'string' ? row.personaId : '',
786
+ personaName: typeof row.personaName === 'string' ? row.personaName : '',
787
+ // Size of the request this row was generated from, in characters.
788
+ promptChars: Number.isFinite(Number(row.promptChars)) ? Number(row.promptChars) : 0,
681
789
  reason: row.reason ?? '',
682
790
  createdAt: row.createdAt ?? new Date().toISOString(),
683
791
  decidedAt: row.decidedAt ?? null,
package/lib/tasks.js ADDED
@@ -0,0 +1,126 @@
1
+ /**
2
+ * A tiny in-memory registry of long-running work, so the panel can show what
3
+ * the plugin is actually doing right now.
4
+ *
5
+ * Nothing here is durable: a task lives for the duration of one operation plus a
6
+ * short grace period, so a finished task can flash "done" in the UI before it
7
+ * disappears. A plugin reload clears everything, which is correct — the work it
8
+ * described is gone too.
9
+ */
10
+
11
+ const DEFAULTS = {
12
+ /** How long a finished task stays visible. */
13
+ keepFinishedMs: 6000,
14
+ /** The plugin never runs more than a handful of things at once. */
15
+ maxTasks: 40,
16
+ }
17
+
18
+ /**
19
+ * @param {{ now?: () => number, keepFinishedMs?: number, maxTasks?: number }} [options]
20
+ */
21
+ export function createTaskRegistry(options = {}) {
22
+ const config = { ...DEFAULTS, ...options }
23
+ // `Date.now` when the caller passes nothing: the plugin always uses the real
24
+ // clock, and calling an undefined `now` was a hard crash in production.
25
+ const now = typeof options.now === 'function' ? options.now : Date.now
26
+ const tasks = new Map()
27
+ let sequence = 0
28
+
29
+ /** Drop finished tasks once their grace period is over. */
30
+ const prune = () => {
31
+ const stamp = now()
32
+ for (const [id, task] of tasks) {
33
+ if (task.finishedAt !== undefined && stamp - task.finishedAt > config.keepFinishedMs) tasks.delete(id)
34
+ }
35
+ }
36
+
37
+ /** Oldest first, which is also the order they were started. */
38
+ const list = () => {
39
+ prune()
40
+ return [...tasks.values()]
41
+ .sort((left, right) => left.startedAt - right.startedAt)
42
+ .map(task => ({
43
+ id: task.id,
44
+ kind: task.kind,
45
+ label: task.label,
46
+ detail: task.detail,
47
+ state: task.state,
48
+ startedAt: task.startedAt,
49
+ done: task.done,
50
+ total: task.total,
51
+ queued: task.queued.slice(0, 8),
52
+ queuedCount: task.queued.length,
53
+ error: task.error,
54
+ }))
55
+ }
56
+
57
+ return {
58
+ /**
59
+ * Register a task that is starting now.
60
+ * @param {{ kind: string, label: string, detail?: string, total?: number }} info
61
+ * @returns {string} the task id, to pass back to update/finish.
62
+ */
63
+ begin(info) {
64
+ prune()
65
+ // A runaway caller must not grow this map without bound.
66
+ if (tasks.size >= config.maxTasks) {
67
+ const finished = [...tasks.values()].find(task => task.finishedAt !== undefined)
68
+ if (finished !== undefined) tasks.delete(finished.id)
69
+ }
70
+ sequence += 1
71
+ const id = `t${sequence}`
72
+ tasks.set(id, {
73
+ id,
74
+ kind: String(info.kind ?? 'work'),
75
+ label: String(info.label ?? '处理中'),
76
+ detail: String(info.detail ?? ''),
77
+ state: 'running',
78
+ startedAt: now(),
79
+ done: 0,
80
+ total: Number.isFinite(Number(info.total)) ? Number(info.total) : 0,
81
+ queued: [],
82
+ error: '',
83
+ })
84
+ return id
85
+ },
86
+
87
+ /** Update progress and/or the human-readable detail of one task. */
88
+ update(id, patch = {}) {
89
+ const task = tasks.get(id)
90
+ if (task === undefined) return
91
+ if (Number.isFinite(Number(patch.done))) task.done = Number(patch.done)
92
+ if (Number.isFinite(Number(patch.total)) && Number(patch.total) > 0) task.total = Number(patch.total)
93
+ if (typeof patch.detail === 'string') task.detail = patch.detail
94
+ if (typeof patch.label === 'string') task.label = patch.label
95
+ },
96
+
97
+ /** Replace the "still to come" names of one task. */
98
+ setQueue(id, names) {
99
+ const task = tasks.get(id)
100
+ if (task === undefined) return
101
+ task.queued = (Array.isArray(names) ? names : []).map(name => String(name))
102
+ },
103
+
104
+ /** Mark a task finished (or failed) and start its grace period. */
105
+ finish(id, error = '') {
106
+ const task = tasks.get(id)
107
+ if (task === undefined) return
108
+ task.state = error === '' ? 'done' : 'failed'
109
+ task.error = typeof error === 'string' ? error : String(error)
110
+ task.finishedAt = now()
111
+ task.detail = ''
112
+ task.queued = []
113
+ if (task.total > 0) task.done = task.total
114
+ },
115
+
116
+ /** Every known task, oldest first. */
117
+ list() {
118
+ return list()
119
+ },
120
+
121
+ /** How many tasks are visible, for a badge. */
122
+ count() {
123
+ return list().length
124
+ },
125
+ }
126
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-qq-affinity",
3
- "version": "1.0.0",
3
+ "version": "1.5.6",
4
4
  "description": "QQ 聊天记录好感度档案:本地建档、三项亲密度评分、智能回复提示、按人开启的智能托管、人格画像、可迁移的本地数据位置、从实时通道自动补齐历史。",
5
5
  "type": "module",
6
6
  "exports": {
@@ -188,7 +188,7 @@ const SAMPLE = `消息对象:小明
188
188
 
189
189
  try {
190
190
  console.log('\n== routes ==')
191
- check('all routes registered', routes.length === 21, `${routes.length}`)
191
+ check('all routes registered', routes.length === 23, `${routes.length}`)
192
192
  check('every route is GET or POST', routes.every(r => r.method === 'GET' || r.method === 'POST'))
193
193
  check('every route sits below /api', routes.every(r => r.path.startsWith('/api/qq-affinity/')))
194
194
  check('the bridge callback is not an /api route', !routes.some(r => r.path === '/qq-affinity/onebot'))
@@ -561,6 +561,22 @@ try {
561
561
  check('and only the new lines, not the whole transcript', !prompts[prompts.length - 1].includes('【完整对话】'))
562
562
  check('exactly one model call was spent', prompts.length === beforeIncremental + 1, `${prompts.length - beforeIncremental}`)
563
563
 
564
+ console.log('\n== the group route only accepts group chats ==')
565
+ result = await call('/api/qq-affinity/group', { method: 'POST', body: { conversationId: convId } })
566
+ check('a private chat is refused', result.status === 400 && String(result.value.error).includes('只有群聊'), JSON.stringify(result.value))
567
+ result = await call('/api/qq-affinity/group', { method: 'POST', body: {} })
568
+ check('a missing id is refused', result.status === 400, `${result.status}`)
569
+ result = await call('/api/qq-affinity/group', { method: 'POST', body: { conversationId: 'group:99999' } })
570
+ check('an unknown conversation is 404', result.status === 404, `${result.status}`)
571
+
572
+ console.log('\n== resetting the hourly reply count ==')
573
+ await call('/api/qq-affinity/care', { method: 'POST', body: { uin: '10001', patch: { hourlyCap: 1 } } })
574
+ result = await call('/api/qq-affinity/care', { method: 'POST', body: { uin: '10001', action: 'reset-count' } })
575
+ check('the reset succeeds', result.value.ok === true && typeof result.value.resetAt === 'string', JSON.stringify(result.value.resetAt))
576
+ check('the care settings come back unchanged', result.value.care.hourlyCap === 1, JSON.stringify(result.value.care))
577
+ result = await call('/api/qq-affinity/care', { method: 'POST', body: { uin: '99999999', action: 'reset-count' } })
578
+ check('an unknown person is refused', result.status === 404, `${result.status}`)
579
+
564
580
  console.log('\n== removal clears everything ==')
565
581
  result = await call('/api/qq-affinity/conversation', { method: 'POST', body: { action: 'remove', id: convId } })
566
582
  check('removed', result.value.state.conversations.length === 0)
@@ -21,6 +21,7 @@ const check = (label, condition, detail = '') => {
21
21
  }
22
22
 
23
23
  const REPLY = '好呀,周六下午两点老地方见'
24
+ const EXCUSE = '我这边有点事 晚点再聊'
24
25
  // Replies are rewritten into chat shape before they are stored or sent.
25
26
  const STYLED_REPLY = styleReply(REPLY)
26
27
 
@@ -29,8 +30,11 @@ const ctx = {
29
30
  get(name) {
30
31
  if (name === 'llm') {
31
32
  return {
32
- stream: () => (async function* () {
33
- yield { type: 'text-delta', index: 0, text: REPLY }
33
+ stream: options => (async function* () {
34
+ // A brush-off is a different ask: answer it in kind so the assertions
35
+ // can tell an excuse apart from a normal reply.
36
+ const text = options?.purpose === 'qq-affinity-excuse' ? EXCUSE : REPLY
37
+ yield { type: 'text-delta', index: 0, text }
34
38
  yield { type: 'finish', reason: { kind: 'stop' } }
35
39
  })(),
36
40
  }
@@ -107,7 +111,7 @@ try {
107
111
  check('nothing was sent', sent.length === 0)
108
112
 
109
113
  console.log('\n== draft mode ==')
110
- store.setCare('10001', { enabled: true, mode: 'draft', hourlyCap: 5 })
114
+ store.setCare('10001', { enabled: true, mode: 'draft', hourlyCap: 5, replyDelaySeconds: 0 })
111
115
  result = await engine.enqueue(eventOf())
112
116
  check('drafts instead of sending', result.action === 'drafted', JSON.stringify(result))
113
117
  check('still nothing sent', sent.length === 0)
@@ -169,10 +173,142 @@ try {
169
173
  check('auto mode sends without asking', result.action === 'sent', JSON.stringify(result))
170
174
  check('exactly one send was added', sent.length === beforeAuto + 1, `${beforeAuto} -> ${sent.length}`)
171
175
 
172
- console.log('\n== hourly cap ==')
176
+ console.log('\n== the cap ends the chat with one polite excuse ==')
173
177
  store.setCare('10001', { hourlyCap: 2 })
178
+ const excuseRowsBefore = store.outbox().filter(row => row.kind === 'excuse').length
179
+ const sendsBefore = sent.length
174
180
  result = await engine.enqueue(eventOf({ raw_message: '再问一句' }))
175
- check('capped after two replies', result.action === 'skipped' && /小时/.test(result.reason), JSON.stringify(result))
181
+ check('the cap produces a brush-off, not silence', result.action === 'declined', JSON.stringify(result))
182
+ check('something was actually sent', sent.length === sendsBefore + 1, `${sendsBefore} -> ${sent.length}`)
183
+ const excuseRows = store.outbox().filter(row => row.kind === 'excuse')
184
+ check('the row is marked as an excuse', excuseRows.length === excuseRowsBefore + 1, `${excuseRows.length}`)
185
+ const lastExcuse = excuseRows[excuseRows.length - 1]
186
+ check('the excuse was delivered as-is', lastExcuse.text === styleReply(EXCUSE), lastExcuse.text)
187
+ check('it was sent, not left as a draft', lastExcuse.status === 'sent', lastExcuse.status)
188
+
189
+ // Same hour, another message: silent, and no second excuse.
190
+ result = await engine.enqueue(eventOf({ raw_message: '人呢' }))
191
+ check('a second message after the excuse is skipped', result.action === 'skipped', JSON.stringify(result))
192
+ check('no second excuse is written', store.outbox().filter(row => row.kind === 'excuse').length === excuseRowsBefore + 1)
193
+ check('and nothing extra was sent', sent.length === sendsBefore + 1, `${sent.length}`)
194
+
195
+ console.log('\n== a burst after the excuse stays silent ==')
196
+ // However many messages arrive, the excuse happened once and only once.
197
+ for (let index = 0; index < 4; index += 1) {
198
+ result = await engine.enqueue(eventOf({ raw_message: `第 ${index} 条追问` }))
199
+ check(`message ${index + 1} is skipped`, result.action === 'skipped', JSON.stringify(result))
200
+ }
201
+ check('still exactly one excuse', store.outbox().filter(row => row.kind === 'excuse').length === excuseRowsBefore + 1)
202
+ check('still nothing extra sent', sent.length === sendsBefore + 1, `${sent.length}`)
203
+
204
+ console.log('\n== the quota survives a reload ==')
205
+ // A fresh engine has empty in-memory maps; the outbox must still say "capped
206
+ // and already excused", otherwise a restart would produce a second brush-off.
207
+ const reloaded = createCareEngine({
208
+ ctx,
209
+ store,
210
+ deliver: async (settings, target, text) => {
211
+ sent.push({ target, text })
212
+ return { messageId: `mid-${sent.length}` }
213
+ },
214
+ })
215
+ result = await reloaded.enqueue(eventOf({ raw_message: '重启之后还在吗' }))
216
+ check('after a reload the message is still skipped', result.action === 'skipped', JSON.stringify(result))
217
+ check('no new excuse after a reload', store.outbox().filter(row => row.kind === 'excuse').length === excuseRowsBefore + 1)
218
+ check('and nothing was sent', sent.length === sendsBefore + 1, `${sent.length}`)
219
+
220
+ console.log('\n== resetting the hourly count restores replies ==')
221
+ const sentBeforeReset = sent.length
222
+ store.resetCareCount('10001')
223
+ result = await engine.enqueue(eventOf({ raw_message: '刚才那个还没说完' }))
224
+ check('after a reset it answers again', result.action === 'sent', JSON.stringify(result))
225
+ check('a real reply went out', sent.length === sentBeforeReset + 1, `${sentBeforeReset} -> ${sent.length}`)
226
+ check('the reset is remembered on disk', store.careResetAt('10001') > 0, `${store.careResetAt('10001')}`)
227
+ // And the old excuse no longer suppresses anything: hitting the cap again may
228
+ // produce a fresh brush-off.
229
+ const excusesAfterReset = store.outbox().filter(row => row.kind === 'excuse').length
230
+ store.setCare('10001', { hourlyCap: 1 })
231
+ result = await engine.enqueue(eventOf({ raw_message: '再问一句' }))
232
+ check('a fresh cap can end with a new excuse', result.action === 'declined', JSON.stringify(result))
233
+ check('the excuse count grew', store.outbox().filter(row => row.kind === 'excuse').length === excusesAfterReset + 1)
234
+ store.setCare('10001', { hourlyCap: 10 })
235
+ console.log('\n== a burst waits, then gets one reply ==')
236
+ // The debounce window: each new message restarts it, and only when the other
237
+ // side goes quiet does one reply cover everything buffered.
238
+ store.setCare('10001', { replyDelaySeconds: 1 })
239
+ const burstBefore = sent.length
240
+ const burstOutboxBefore = store.outbox().length
241
+ result = await engine.enqueue(eventOf({ raw_message: '在吗' }))
242
+ check('the first message is queued, not answered', result.action === 'queued', JSON.stringify(result))
243
+ check('the wait is stated', /等 1 秒/.test(result.reason), result.reason)
244
+ check('nothing was sent yet', sent.length === burstBefore, `${sent.length}`)
245
+ result = await engine.enqueue(eventOf({ raw_message: '那个参数你看了吗' }))
246
+ check('a second message joins the same window', result.action === 'queued', JSON.stringify(result))
247
+ check('still nothing sent', sent.length === burstBefore)
248
+ check('both messages are archived right away', store.messages(conversation.id).filter(row => row.text === '那个参数你看了吗').length === 1)
249
+ check('one pending turn is buffered', engine.pendingCount() === 1, `${engine.pendingCount()}`)
250
+
251
+ // Let the real timer fire this time, so the schedule is exercised end to end.
252
+ await new Promise(done => setTimeout(done, 1300))
253
+ check('the timer flushed the burst', engine.pendingCount() === 0, `${engine.pendingCount()}`)
254
+ check('exactly one reply was sent', sent.length === burstBefore + 1, `${burstBefore} -> ${sent.length}`)
255
+ const burstRows = store.outbox().slice(burstOutboxBefore)
256
+ check('one outbox row covers the whole burst', burstRows.length === 1, JSON.stringify(burstRows.map(row => row.status)))
257
+ check('it records how many messages it answered', burstRows[0].inboundCount === 2, `${burstRows[0].inboundCount}`)
258
+ check('it answers the newest message', burstRows[0].inboundText === '那个参数你看了吗', burstRows[0].inboundText)
259
+
260
+ console.log('\n== the wait can be switched off ==')
261
+ store.setCare('10001', { replyDelaySeconds: 0 })
262
+ const immediateBefore = sent.length
263
+ result = await engine.enqueue(eventOf({ raw_message: '立刻回我' }))
264
+ check('zero delay answers at once', result.action === 'sent', JSON.stringify(result))
265
+ check('and it really sent', sent.length === immediateBefore + 1)
266
+
267
+ console.log('\n== a burst with nothing to answer is skipped once ==')
268
+ store.setCare('10001', { replyDelaySeconds: 0 })
269
+ const silentBefore = store.outbox().length
270
+ result = await engine.enqueue(eventOf({ raw_message: '[CQ:face,id=178]' }))
271
+ check('a bare face is skipped', result.action === 'skipped', JSON.stringify(result))
272
+ check('with one recorded reason', store.outbox().slice(silentBefore).length === 1, `${store.outbox().slice(silentBefore).length}`)
273
+
274
+ console.log('\n== one reply event counts as one 次, whatever it covers ==')
275
+ // The debounce folds a burst into a single reply; that reply is 一次, not 三条.
276
+ store.setCare('10001', { replyDelaySeconds: 0, hourlyCap: 20 })
277
+ const usageBefore = engine.usage()['10001']?.lastHour ?? 0
278
+ await engine.enqueue(eventOf({ raw_message: '第一句' }))
279
+ await engine.enqueue(eventOf({ raw_message: '第二句' }))
280
+ const usageAfter = engine.usage()['10001']
281
+ check('two answers took two 次', usageAfter.lastHour === usageBefore + 2, `${usageBefore} -> ${usageAfter.lastHour}`)
282
+ check('each 次 covered one message', usageAfter.coveredMessages >= 2, JSON.stringify(usageAfter))
283
+ check('the cap is reported alongside', usageAfter.cap === 20, JSON.stringify(usageAfter))
284
+
285
+ console.log('\n== every reply record names the persona that wrote it ==')
286
+ store.setCare('10001', { replyDelaySeconds: 0, hourlyCap: 20, persona: 'default' })
287
+ await engine.enqueue(eventOf({ raw_message: '用默认人设回我' }))
288
+ const defaultRow = store.outbox().slice(-1)[0]
289
+ check('the default voice is recorded', defaultRow.personaId === 'default', JSON.stringify(defaultRow.personaId))
290
+ check('and its display name too', defaultRow.personaName === '默认(像我本人)', defaultRow.personaName)
291
+
292
+ const voice = store.addReplyPersona({ name: '测试人设', prompt: '只用短句,语气平淡。' })
293
+ store.setCare('10001', { persona: voice.id })
294
+ await engine.enqueue(eventOf({ raw_message: '换个人设回我' }))
295
+ const customRow = store.outbox().slice(-1)[0]
296
+ check('a custom persona is recorded by id', customRow.personaId === voice.id, customRow.personaId)
297
+ check('and by the name shown in the picker', customRow.personaName === '测试人设', customRow.personaName)
298
+ // The record must survive the persona being deleted.
299
+ store.removeReplyPersona(voice.id)
300
+ const keptName = store.outbox().slice(-1)[0].personaName
301
+ check('the recorded name survives a delete', keptName === '测试人设', keptName)
302
+ store.setCare('10001', { persona: 'default' })
303
+
304
+ console.log('\n== one huge message cannot inflate the request ==')
305
+ store.setCare('10001', { replyDelaySeconds: 0, hourlyCap: 20, persona: 'default' })
306
+ const huge = '这是一段很长的消息'.repeat(2000) // 18000 chars
307
+ await engine.enqueue(eventOf({ raw_message: huge }))
308
+ const hugeRow = store.outbox().slice(-1)[0]
309
+ check('the request stayed bounded', hugeRow.promptChars > 0 && hugeRow.promptChars <= 6000, `${hugeRow.promptChars}`)
310
+ check('the inbound size was noted', hugeRow.inboundCount === 1, `${hugeRow.inboundCount}`)
311
+ check('the stored transcript keeps the full text', store.messages(conversation.id).some(row => row.text.length >= 18000), `${Math.max(...store.messages(conversation.id).map(row => row.text.length))}`)
176
312
 
177
313
  console.log('\n== a group only wakes on a mention ==')
178
314
  const { conversation: group } = store.ensureConversation({ kind: 'group', title: '老同学群', groupUin: '555666' })
@@ -180,13 +316,13 @@ try {
180
316
  store.appendMessages(group.id, [{ ts: Date.now() - 60000, senderName: '小明', senderUin: '10001', text: '大家好' }])
181
317
  store.setCare('10001', { hourlyCap: 10 })
182
318
  const before = store.messages(group.id).length
183
- const outboxBefore = store.outbox().length
319
+ const groupOutboxBefore = store.outbox().length
184
320
  result = await engine.enqueue(eventOf({ message_type: 'group', group_id: 555666, raw_message: '大家好' }))
185
321
  check('an unmentioned group line is ignored', result.action === 'ignored' && result.reason === 'not-mentioned', JSON.stringify(result))
186
322
  // The conversation is on, so the line belongs in its transcript; only the
187
323
  // answering is skipped.
188
324
  check('the line is still recorded', store.messages(group.id).length === before + 1, `${store.messages(group.id).length}`)
189
- check('but no outbox row is written for it', store.outbox().length === outboxBefore, `${store.outbox().length}`)
325
+ check('but no outbox row is written for it', store.outbox().length === groupOutboxBefore, `${store.outbox().length}`)
190
326
  result = await engine.enqueue(eventOf({ message_type: 'group', group_id: 555666, raw_message: `[CQ:at,qq=20002] 你说呢` }))
191
327
  check('a mention is answered into the group', result.action === 'sent' || result.action === 'drafted', JSON.stringify(result))
192
328