dsh-qq-affinity 0.15.3 → 1.0.3

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/client.js CHANGED
@@ -20,7 +20,7 @@ window.__ModuleLoader__.load({
20
20
  * This bundle's version. The Host reports its own; when the two differ the
21
21
  * panel says so, because a stale bundle otherwise looks like a broken button.
22
22
  */
23
- const VERSION = '0.15.0'
23
+ const VERSION = '1.0.2'
24
24
 
25
25
  // ---------------------------------------------------------------- palette
26
26
 
@@ -92,6 +92,15 @@ window.__ModuleLoader__.load({
92
92
  ]
93
93
  const traitColor = (index) => (supportsColorMix ? TRAIT_COLORS[index % TRAIT_COLORS.length]() : C.brand)
94
94
 
95
+ /** "正在分析" 已经跑了多久: 12 秒 / 3 分 5 秒 / 1 小时 2 分. */
96
+ function formatElapsed(ms) {
97
+ const total = Math.max(0, Math.round(Number(ms) / 1000))
98
+ if (total < 60) return `${total} 秒`
99
+ const minutes = Math.floor(total / 60)
100
+ if (minutes < 60) return `${minutes} 分 ${total % 60} 秒`
101
+ return `${Math.floor(minutes / 60)} 小时 ${minutes % 60} 分`
102
+ }
103
+
95
104
  /** "完整 / 增量(+12 条)": how one stored analysis was produced. */
96
105
  function analysisMode(entry) {
97
106
  const based = entry?.basedOn ?? {}
@@ -1730,6 +1739,15 @@ window.__ModuleLoader__.load({
1730
1739
  return () => window.clearInterval(timer)
1731
1740
  }, [careActive, draftCount, load, loadConversation, loadPersonOutbox])
1732
1741
 
1742
+ // A running task changes faster than the slow poll above: while any task is
1743
+ // in flight, refresh the snapshot every couple of seconds so the list moves.
1744
+ const hasRunningTask = (state?.tasks ?? []).some(task => task.state === 'running')
1745
+ useEffect(() => {
1746
+ if (hasRunningTask !== true) return undefined
1747
+ const timer = window.setInterval(() => { void load() }, 2000)
1748
+ return () => window.clearInterval(timer)
1749
+ }, [hasRunningTask, load])
1750
+
1733
1751
  // Handlers ----------------------------------------------------------
1734
1752
 
1735
1753
  const toggleConversation = async (row, enabled) => {
@@ -2167,6 +2185,7 @@ window.__ModuleLoader__.load({
2167
2185
  tabButton('conversations', '对话', conversations.length),
2168
2186
  tabButton('people', '档案', people.length),
2169
2187
  tabButton('self', '我', 0),
2188
+ tabButton('tasks', '任务', (state?.tasks ?? []).length),
2170
2189
  ]),
2171
2190
  tab === 'people' ? sortBar() : null,
2172
2191
  panelError !== null && typeof panelError.where === 'string' && panelError.where.startsWith('order:') ? h('div', {
@@ -2188,7 +2207,9 @@ window.__ModuleLoader__.load({
2188
2207
  h('div', { key: 'list', style: { flex: 1, minHeight: 0, overflowY: 'auto', padding: '4px 8px 12px' } },
2189
2208
  tab === 'conversations'
2190
2209
  ? conversationList()
2191
- : tab === 'people' ? peopleList() : selfRail()),
2210
+ : tab === 'people'
2211
+ ? peopleList()
2212
+ : tab === 'self' ? selfRail() : taskList()),
2192
2213
  h('div', {
2193
2214
  key: 'foot',
2194
2215
  style: {
@@ -2218,7 +2239,7 @@ window.__ModuleLoader__.load({
2218
2239
  ? (conversation === undefined ? emptyState() : conversationDetail(conversation))
2219
2240
  : tab === 'people'
2220
2241
  ? (person === undefined ? emptyState() : personDetail(person))
2221
- : selfDetail()),
2242
+ : tab === 'self' ? selfDetail() : tasksDetail()),
2222
2243
  ]),
2223
2244
 
2224
2245
  settingsOpen ? h(SettingsForm, {
@@ -2578,6 +2599,96 @@ window.__ModuleLoader__.load({
2578
2599
  ])
2579
2600
  }
2580
2601
 
2602
+ /** One task line, shared by the rail list and the detail pane. */
2603
+ function taskRow(task, { wide = false } = {}) {
2604
+ const color = task.state === 'running' ? C.brand : task.state === 'failed' ? C.error : C.success
2605
+ const progress = task.total > 0 ? ` ${Math.min(task.done, task.total)}/${task.total}` : ''
2606
+ const queued = task.queuedCount > 0 ? `(还有 ${task.queuedCount} 个)` : ''
2607
+ const elapsed = task.state === 'running'
2608
+ ? ` · ${formatElapsed(Date.now() - task.startedAt)}`
2609
+ : ''
2610
+ const title = task.queuedCount > 0 ? `排队中:${task.queued.join('、')}` : (task.error === '' ? task.label : task.error)
2611
+ const line = `${task.label}${task.detail === '' ? '' : ` · ${task.detail}`}${progress}${queued}`
2612
+ const percent = task.total > 0 ? Math.round(Math.min(100, (task.done / task.total) * 100)) : 0
2613
+ return h('div', {
2614
+ key: task.id,
2615
+ title,
2616
+ style: {
2617
+ display: 'flex',
2618
+ flexDirection: 'column',
2619
+ gap: 2,
2620
+ padding: wide ? '7px 0' : '0',
2621
+ borderBottom: wide ? `1px solid ${C.border1}` : 'none',
2622
+ minWidth: 0,
2623
+ },
2624
+ }, [
2625
+ h('div', { key: 'top', style: { display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 } }, [
2626
+ h('span', { key: 'dot', style: { width: 6, height: 6, borderRadius: 999, background: color, flex: '0 0 auto' } }),
2627
+ h('span', {
2628
+ key: 't',
2629
+ style: {
2630
+ flex: 1,
2631
+ minWidth: 0,
2632
+ overflow: 'hidden',
2633
+ textOverflow: 'ellipsis',
2634
+ whiteSpace: 'nowrap',
2635
+ fontSize: wide ? 12 : 11,
2636
+ lineHeight: 1.5,
2637
+ color: task.state === 'failed' ? C.error : C.label,
2638
+ },
2639
+ }, line + elapsed),
2640
+ ]),
2641
+ wide && task.total > 0 ? h('div', {
2642
+ key: 'bar',
2643
+ style: { height: 3, borderRadius: 999, background: C.layer2, overflow: 'hidden', marginLeft: 12 },
2644
+ }, h('div', { style: { width: `${percent}%`, height: '100%', background: color } })) : null,
2645
+ wide && task.error !== '' ? h('div', {
2646
+ key: 'err',
2647
+ style: { fontSize: 10.5, color: C.error, marginLeft: 12, lineHeight: 1.5, whiteSpace: 'pre-wrap' },
2648
+ }, task.error) : null,
2649
+ ])
2650
+ }
2651
+
2652
+ /** Rail list for the 任务 tab. */
2653
+ function taskList() {
2654
+ const rows = state?.tasks ?? []
2655
+ if (rows.length === 0) {
2656
+ return h('div', { style: { padding: '18px 10px', color: C.label2, fontSize: 12, lineHeight: 1.85 } }, [
2657
+ h('div', { key: 'a', style: { color: C.label, fontWeight: 600, marginBottom: 4 } }, '现在没有任务'),
2658
+ h('div', { key: 'b' }, '分析、批量更新、同步历史、托管回复开始运行时,会在这里排队出现。'),
2659
+ ])
2660
+ }
2661
+ return [...rows].reverse().map(task => h('div', {
2662
+ key: task.id,
2663
+ style: { padding: '6px 8px', marginBottom: 2, borderRadius: 6 },
2664
+ }, taskRow(task)))
2665
+ }
2666
+
2667
+ /** Main pane for the 任务 tab: the same queue, with progress and reasons. */
2668
+ function tasksDetail() {
2669
+ const rows = state?.tasks ?? []
2670
+ const running = rows.filter(task => task.state === 'running')
2671
+ const finished = rows.filter(task => task.state !== 'running')
2672
+ return h('div', { style: { display: 'flex', flexDirection: 'column', gap: 12, maxWidth: 900 } }, [
2673
+ h(Section, {
2674
+ key: 'running',
2675
+ title: '正在进行',
2676
+ extra: h(Chip, { key: 'c', mono: true, color: running.length > 0 ? C.brand : C.idle }, `${running.length} 个`),
2677
+ }, running.length === 0
2678
+ ? h('div', { style: { fontSize: 12, color: C.label2, lineHeight: 1.8 } }, '空闲中。点「分析」「一键更新全部」「同步已载入的消息」或让别人发条消息(托管开着时),任务会出现在这里。')
2679
+ : h('div', { style: { display: 'flex', flexDirection: 'column' } }, running.map(task => taskRow(task, { wide: true })))),
2680
+ h(Section, {
2681
+ key: 'finished',
2682
+ title: '刚结束',
2683
+ extra: h(Chip, { key: 'c', mono: true }, `${finished.length} 个`),
2684
+ }, finished.length === 0
2685
+ ? h('div', { style: { fontSize: 12, color: C.label2, lineHeight: 1.8 } }, '还没有结束的任务。')
2686
+ : h('div', { style: { display: 'flex', flexDirection: 'column' } }, finished.map(task => taskRow(task, { wide: true })))),
2687
+ h('div', { key: 'hint', style: { fontSize: 11, color: C.label2, lineHeight: 1.75 } },
2688
+ '任务由插件后台登记,结束的任务会保留几秒再消失。批量更新会在这里显示进度和还在排队的名单,悬停可以看到具体是谁。'),
2689
+ ])
2690
+ }
2691
+
2581
2692
  /** The batch-refresh bar, above the add-conversation button. */
2582
2693
  function refreshBar() {
2583
2694
  const job = refreshJob
package/index.js CHANGED
@@ -23,6 +23,7 @@ import { createCareEngine } from './lib/care.js'
23
23
  import { createNodeHandler } from './lib/inbound.js'
24
24
  import { bridgePort, startBridgeServer } from './lib/bridge-server.js'
25
25
  import { recoverLoaded } from './lib/recover.js'
26
+ import { createTaskRegistry } from './lib/tasks.js'
26
27
 
27
28
  export const name = 'qq-affinity'
28
29
 
@@ -52,10 +53,13 @@ export const inject = ['connection', 'timer']
52
53
  */
53
54
  export function apply(ctx) {
54
55
  const store = new Store(resolveDataDirectory())
55
- const engine = createCareEngine({ ctx, store })
56
+ // One registry shared by the routes and the care engine, so the panel shows
57
+ // every slow operation in the same list.
58
+ const tasks = createTaskRegistry()
59
+ const engine = createCareEngine({ ctx, store, tasks })
56
60
  // Shared mutable status: the listener settles asynchronously, the panel reads it on demand.
57
61
  const bridge = { listening: false, port: bridgePort(), url: '', error: 'starting' }
58
- const routes = createRoutes(ctx, store, engine, bridge, { version: VERSION })
62
+ const routes = createRoutes(ctx, store, engine, bridge, { version: VERSION, tasks })
59
63
 
60
64
  ctx.effect(() => {
61
65
  const disposers = routes.map(route => ctx.connection.fetch.register({
package/lib/analyze.js CHANGED
@@ -11,7 +11,7 @@
11
11
  */
12
12
 
13
13
  import { score as clampScore, clamp, isAiAuthored, formatTime, styleReply } from './util.js'
14
- import { lastInbound, measure, renderTranscript, rowsForPerson } from './features.js'
14
+ import { lastInbound, measure, renderTranscript, rowsForPerson, GROUP_UNMENTIONED_WEIGHT } from './features.js'
15
15
  import { completeText, extractJson, routeFor } from './llm.js'
16
16
  import { collectImageBlocks, imagesOf, modelSeesImages } from './vision.js'
17
17
 
@@ -118,6 +118,12 @@ function visionBlock(vision) {
118
118
  /** Render the measurement block for the prompt. */
119
119
  function measurementBlock(features, extra = {}) { return [
120
120
  `总消息数 ${features.totalMessages}(对方 ${features.theirMessages} / 我 ${features.myMessages},其中我的真实表达 ${features.myAuthenticMessages} 条、AI代笔 ${features.aiAdoptedMessages} 条)`,
121
+ features.theirUnaddressedGroupMessages === undefined || features.theirUnaddressedGroupMessages === 0
122
+ ? ''
123
+ : `⚠ 对方有 ${features.theirUnaddressedGroupMessages} 条群聊消息没有 @ 我(占他全部发言的 ${Math.round(features.theirUnaddressedGroupMessages / Math.max(1, features.theirMessages) * 100)}%):这些很可能不是说给我听的,按 ${Math.round(GROUP_UNMENTIONED_WEIGHT * 100)}% 权重计入,下面的行为统计只按「真正对我说的话」重算过。`,
124
+ features.theirAddressedMessages === undefined
125
+ ? ''
126
+ : `对方真正对我说的话 ${features.theirAddressedMessages} 条(私聊 + 群里 @ 我),加权后相当于 ${features.theirWeightedMessages} 条。`,
121
127
  `平均字数:对方 ${features.theirAvgChars} / 我 ${features.myAvgChars}`,
122
128
  `提问率:对方 ${features.theirQuestionRatio} / 我 ${features.myQuestionRatio}`,
123
129
  `每条消息的颜文字或表情标记数:对方 ${features.theirDecorationPerMessage} / 我 ${features.myDecorationPerMessage}`,
@@ -126,7 +132,7 @@ function measurementBlock(features, extra = {}) { return [
126
132
  `对方深夜(23:00-05:00)消息占比 ${features.theirNightRatio},连续追问 ${features.theirDoubleTextCount} 次`,
127
133
  `覆盖天数 ${features.spanDays},活跃天数 ${features.activeDays},距最后一条消息 ${features.lastContactDays ?? '—'} 天`,
128
134
  ...(extra.lines ?? []),
129
- ].join('\n')
135
+ ].filter(line => line !== '').join('\n')
130
136
  }
131
137
 
132
138
  /** Find one person row, with a readable display name. */
@@ -248,6 +254,8 @@ export async function scorePerson(ctx, store, uin, options = {}) {
248
254
  '字段含义:',
249
255
  'theirFavor = 对方对我的好感度;myFavor = 我对对方的好感度;intimacy = 我们的亲密度(熟悉、放松、互相接得住的程度)。',
250
256
  'My favor 必须只由我的真实表达推出;如果我的真实表达很少,就明确说明证据不足并给较低 confidence。',
257
+ '群聊纪律:对方在群里没有 @ 我的发言,多数不是对我说的(转写里标了「群里未点名」)。判断 theirFavor 时这些只能算很弱的旁证——'
258
+ + '不要把「他在群里聊得热闹」当成「他对我热情」,也不要把「他在群里没理我」当成冷落。',
251
259
  )
252
260
 
253
261
  // Look at the newest pictures only when both the user and the model allow it.
package/lib/api.js CHANGED
@@ -134,7 +134,7 @@ function personView(store, uin, transcripts) {
134
134
  }
135
135
 
136
136
  /** Build the whole panel snapshot, reading each enabled transcript once. */
137
- function stateOf(store, engine, bridgeStatus = {}) {
137
+ function stateOf(store, engine, bridgeStatus = {}, tasks = undefined) {
138
138
  // Reading every transcript once keeps this snapshot linear instead of
139
139
  // re-scanning the store for each person it lists.
140
140
  const transcripts = store.state.conversations
@@ -181,6 +181,16 @@ function stateOf(store, engine, bridgeStatus = {}) {
181
181
  bridgeError: bridgeStatus.error ?? '',
182
182
  },
183
183
  careAutoActive: Object.values(store.state.care).filter(entry => entry.enabled === true && entry.mode === 'auto').length,
184
+ // What the plugin is busy with right now, oldest first. The registry is
185
+ // optional: a bare route set (tests, or a host without one) simply has none.
186
+ // A registry failure must never take the whole snapshot down with it.
187
+ tasks: (() => {
188
+ try {
189
+ return tasks === undefined || tasks === null ? [] : tasks.list()
190
+ } catch {
191
+ return []
192
+ }
193
+ })(),
184
194
  pinned: store.state.pinned.slice(),
185
195
  selfProfile: store.selfProfile(),
186
196
  // Comparing the two versions is how a stale client bundle exposes itself.
@@ -224,6 +234,23 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
224
234
  }
225
235
  const bridgeStatus = bridge ?? { listening: false, port: 0, url: '', error: 'not started' }
226
236
  if (overrides.version !== undefined) bridgeStatus.version = overrides.version
237
+ // One registry for the panel: every slow operation in this file reports into it.
238
+ const tasks = overrides.tasks ?? null
239
+ const taskOf = (info) => (tasks === null ? '' : tasks.begin(info))
240
+ const taskDone = (id, error = '') => { if (tasks !== null && id !== '') tasks.finish(id, error) }
241
+ const taskStep = (id, patch) => { if (tasks !== null && id !== '') tasks.update(id, patch) }
242
+ /** Run one slow operation as a tracked task, recording how it ended. */
243
+ const tracked = async (info, work) => {
244
+ const id = taskOf(info)
245
+ try {
246
+ const value = await work()
247
+ taskDone(id)
248
+ return value
249
+ } catch (error) {
250
+ taskDone(id, error instanceof Error ? error.message : String(error))
251
+ throw error
252
+ }
253
+ }
227
254
 
228
255
  /**
229
256
  * The batch refresh job. In-memory only: a plugin reload resets it, and the
@@ -271,6 +298,10 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
271
298
  .filter(uin => privateUins.has(uin))
272
299
  .sort((left, right) => (store.state.people[right]?.messageCount ?? 0) - (store.state.people[left]?.messageCount ?? 0))
273
300
  refreshJob.total = targets.length
301
+ const batchTask = taskOf({ kind: 'refresh', label: '批量更新', total: targets.length })
302
+ if (tasks !== null && batchTask !== '') {
303
+ tasks.setQueue(batchTask, targets.slice(0, 8).map(uin => store.state.people[uin]?.names?.slice(-1)[0] ?? uin))
304
+ }
274
305
  let cursor = 0
275
306
  const worker = async () => {
276
307
  while (cursor < targets.length) {
@@ -278,6 +309,11 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
278
309
  const uin = targets[cursor]
279
310
  cursor += 1
280
311
  refreshJob.current = uin
312
+ taskStep(batchTask, {
313
+ done: refreshJob.done,
314
+ total: targets.length,
315
+ detail: store.state.people[uin]?.names?.slice(-1)[0] ?? uin,
316
+ })
281
317
  const outcome = { uin, score: false, persona: false, error: '' }
282
318
  try {
283
319
  await scorePerson(ctx, store, uin, { signal: refreshJob.abort.signal })
@@ -302,6 +338,8 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
302
338
  }
303
339
  // Two at a time: faster than one, still polite to the model provider.
304
340
  await Promise.all([worker(), worker()])
341
+ const cancelled = refreshJob.running !== true && refreshJob.done < refreshJob.total
342
+ taskDone(batchTask, cancelled ? '已手动停止' : '')
305
343
  refreshJob.running = false
306
344
  refreshJob.current = ''
307
345
  }
@@ -359,7 +397,7 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
359
397
  bridgeStatus.lastSeenClient = version
360
398
  appendArchiveLog(store, 'client.log', `state v=${version === '' ? '(none)' : version.slice(0, 24)}`)
361
399
  }
362
- const snapshot = stateOf(store, engine, bridgeStatus)
400
+ const snapshot = stateOf(store, engine, bridgeStatus, tasks)
363
401
  // Resolving model capability is a round trip; one answer per few seconds
364
402
  // is plenty for a panel that polls.
365
403
  const now = Date.now()
@@ -449,7 +487,7 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
449
487
  if (bridge.apiBase !== before.apiBase || bridge.accessToken !== before.accessToken) bridge.enabled = false
450
488
  }
451
489
  store.save()
452
- return json(stateOf(store, engine, bridgeStatus))
490
+ return json(stateOf(store, engine, bridgeStatus, tasks))
453
491
  }),
454
492
  },
455
493
  {
@@ -483,7 +521,7 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
483
521
  note: outcome.mode === 'migrate' && outcome.cleanup !== true
484
522
  ? `原来的数据仍留在 ${outcome.previous},确认新位置没问题后可以手动删除。`
485
523
  : '',
486
- state: stateOf(store, engine, bridgeStatus),
524
+ state: stateOf(store, engine, bridgeStatus, tasks),
487
525
  })
488
526
  }),
489
527
  },
@@ -499,12 +537,12 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
499
537
  if (action === 'toggle') {
500
538
  const isPinned = store.state.pinned.includes(id)
501
539
  const pinned = isPinned ? store.unpin(id) : store.pin(id)
502
- return json({ ok: true, pinned, state: stateOf(store, engine, bridgeStatus) })
540
+ return json({ ok: true, pinned, state: stateOf(store, engine, bridgeStatus, tasks) })
503
541
  }
504
542
  if (action === 'move') {
505
543
  const delta = Math.round(Number(body.delta))
506
544
  const pinned = store.movePinned(id, Number.isFinite(delta) ? delta : 0)
507
- return json({ ok: true, pinned, state: stateOf(store, engine, bridgeStatus) })
545
+ return json({ ok: true, pinned, state: stateOf(store, engine, bridgeStatus, tasks) })
508
546
  }
509
547
  return fail(`未知操作:${action}`)
510
548
  }),
@@ -518,7 +556,7 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
518
556
  fetch: guard(async (request) => {
519
557
  const body = await readBody(request)
520
558
  const action = textField(body.action, 20)
521
- if (action === 'status') return json({ ok: true, job: jobView(), state: stateOf(store, engine, bridgeStatus) })
559
+ if (action === 'status') return json({ ok: true, job: jobView(), state: stateOf(store, engine, bridgeStatus, tasks) })
522
560
  if (action === 'cancel') {
523
561
  if (!refreshJob.running) return fail('当前没有正在进行的更新。', 409)
524
562
  refreshJob.running = false
@@ -559,7 +597,7 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
559
597
  return fail('保存顺序失败。', 500)
560
598
  }
561
599
  logOrder(store, `saved ${kind} count=${ordered.length}`)
562
- return json({ ok: true, kind, order: ordered, state: stateOf(store, engine, bridgeStatus) })
600
+ return json({ ok: true, kind, order: ordered, state: stateOf(store, engine, bridgeStatus, tasks) })
563
601
  }),
564
602
  },
565
603
  {
@@ -576,7 +614,7 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
576
614
  }
577
615
  const care = store.setCare(uin, body.patch !== null && typeof body.patch === 'object' ? body.patch : {})
578
616
  if (care === undefined) return fail('保存失败。', 500)
579
- return json({ ok: true, care, state: stateOf(store, engine, bridgeStatus) })
617
+ return json({ ok: true, care, state: stateOf(store, engine, bridgeStatus, tasks) })
580
618
  }),
581
619
  },
582
620
  {
@@ -627,7 +665,7 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
627
665
  return json({
628
666
  ok: true,
629
667
  login: info,
630
- state: stateOf(store, engine, bridgeStatus),
668
+ state: stateOf(store, engine, bridgeStatus, tasks),
631
669
  })
632
670
  } catch (error) {
633
671
  store.state.settings.onebot.enabled = false
@@ -656,9 +694,16 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
656
694
  if (conversationId !== '') {
657
695
  const conversation = store.conversation(conversationId)
658
696
  if (conversation === undefined) return fail('找不到这个对话。', 404)
659
- reports = [await backfillConversation({ store, bridge, conversation, count })]
697
+ reports = await tracked(
698
+ { kind: 'backfill', label: '同步已载入消息', detail: conversation.title === '' ? conversationId : conversation.title },
699
+ async () => [await deps.backfill({ store, bridge, conversation, count })],
700
+ )
660
701
  } else {
661
- reports = await backfillAll({ store, bridge, count })
702
+ const enabledCount = store.state.conversations.filter(row => row.enabled === true).length
703
+ reports = await tracked(
704
+ { kind: 'backfill', label: '同步全部已载入消息', total: enabledCount },
705
+ () => backfillAll({ store, bridge, count }),
706
+ )
662
707
  }
663
708
 
664
709
  if (reports.length > 0 && reports.some(report => report.fetched > 0)) {
@@ -676,7 +721,7 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
676
721
  note: failed.length === 0
677
722
  ? `补齐完成,新增 ${added} 条。`
678
723
  : `${reports.length - failed.length} 个对话补齐,另 ${failed.length} 个没成功:${failed[0].error}`,
679
- state: stateOf(store, engine, bridgeStatus),
724
+ state: stateOf(store, engine, bridgeStatus, tasks),
680
725
  })
681
726
  }),
682
727
  },
@@ -705,11 +750,11 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
705
750
  const action = textField(body.action, 20)
706
751
  if (action === 'approve') {
707
752
  const row = await engine.approve(id)
708
- return json({ ok: true, row, state: stateOf(store, engine, bridgeStatus) })
753
+ return json({ ok: true, row, state: stateOf(store, engine, bridgeStatus, tasks) })
709
754
  }
710
755
  if (action === 'cancel') {
711
756
  const row = engine.cancel(id)
712
- return json({ ok: true, row, state: stateOf(store, engine, bridgeStatus) })
757
+ return json({ ok: true, row, state: stateOf(store, engine, bridgeStatus, tasks) })
713
758
  }
714
759
  return fail(`未知操作:${action}`)
715
760
  }),
@@ -737,7 +782,7 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
737
782
  created,
738
783
  conversation: store.conversation(conversation.id),
739
784
  autoPull: pull,
740
- state: stateOf(store, engine, bridgeStatus),
785
+ state: stateOf(store, engine, bridgeStatus, tasks),
741
786
  })
742
787
  }
743
788
  const id = textField(body.id, 80)
@@ -751,7 +796,7 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
751
796
  ok: true,
752
797
  conversation: store.conversation(id),
753
798
  autoPull: pull,
754
- state: stateOf(store, engine, bridgeStatus),
799
+ state: stateOf(store, engine, bridgeStatus, tasks),
755
800
  })
756
801
  }
757
802
  if (action === 'update') {
@@ -760,11 +805,11 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
760
805
  peerUin: typeof body.peerUin === 'string' ? body.peerUin : undefined,
761
806
  groupUin: typeof body.groupUin === 'string' ? body.groupUin : undefined,
762
807
  })
763
- return json({ ok: true, conversation: store.conversation(id), state: stateOf(store, engine, bridgeStatus) })
808
+ return json({ ok: true, conversation: store.conversation(id), state: stateOf(store, engine, bridgeStatus, tasks) })
764
809
  }
765
810
  if (action === 'remove') {
766
811
  store.removeConversation(id)
767
- return json({ ok: true, state: stateOf(store, engine, bridgeStatus) })
812
+ return json({ ok: true, state: stateOf(store, engine, bridgeStatus, tasks) })
768
813
  }
769
814
  return fail(`未知操作:${action}`)
770
815
  }),
@@ -842,7 +887,7 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
842
887
  stats: parsed.stats,
843
888
  totalMessages: after,
844
889
  adoptedMatched: matched,
845
- state: stateOf(store, engine, bridgeStatus),
890
+ state: stateOf(store, engine, bridgeStatus, tasks),
846
891
  })
847
892
  }),
848
893
  },
@@ -855,9 +900,11 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
855
900
  const uin = textField(body.uin, 24).replace(/\D/g, '')
856
901
  if (uin === '') return fail('缺少 QQ 号。')
857
902
  if (store.person(uin) === undefined) return fail(`没有关于 QQ ${uin} 的任何记录。`, 404)
858
- const result = await scorePerson(ctx, store, uin, { force: body.force === true })
859
- return json({ ok: true, score: result, state: stateOf(store, engine, bridgeStatus) })
860
- }),
903
+ const result = await tracked(
904
+ { kind: 'score', label: '好感度分析', detail: store.person(uin)?.names?.slice(-1)[0] ?? uin },
905
+ () => scorePerson(ctx, store, uin, { force: body.force === true }),
906
+ )
907
+ return json({ ok: true, score: result, state: stateOf(store, engine, bridgeStatus, tasks) }) }),
861
908
  },
862
909
  {
863
910
  path: '/api/qq-affinity/self',
@@ -866,8 +913,8 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
866
913
  fetch: guard(async (request) => {
867
914
  // A body is optional here: the panel may ask for a plain analysis.
868
915
  const body = await readBody(request).catch(() => ({}))
869
- const profile = await analyzeSelf(ctx, store, { force: body?.force === true })
870
- return json({ ok: true, selfProfile: profile, state: stateOf(store, engine, bridgeStatus) })
916
+ const profile = await tracked({ kind: 'self', label: '自我分析' }, () => analyzeSelf(ctx, store, { force: body?.force === true }))
917
+ return json({ ok: true, selfProfile: profile, state: stateOf(store, engine, bridgeStatus, tasks) })
871
918
  }),
872
919
  },
873
920
  {
@@ -891,8 +938,11 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
891
938
  const uin = textField(body.uin, 24).replace(/\D/g, '')
892
939
  if (uin === '') return fail('缺少 QQ 号。')
893
940
  if (store.person(uin) === undefined) return fail(`没有关于 QQ ${uin} 的任何记录。`, 404)
894
- const result = await analyzePersona(ctx, store, uin, { force: body.force === true })
895
- return json({ ok: true, persona: result, state: stateOf(store, engine, bridgeStatus) })
941
+ const result = await tracked(
942
+ { kind: 'persona', label: '人格画像', detail: store.person(uin)?.names?.slice(-1)[0] ?? uin },
943
+ () => analyzePersona(ctx, store, uin, { force: body.force === true }),
944
+ )
945
+ return json({ ok: true, persona: result, state: stateOf(store, engine, bridgeStatus, tasks) })
896
946
  }),
897
947
  },
898
948
  {
@@ -902,7 +952,10 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
902
952
  fetch: guard(async (request) => {
903
953
  const body = await readBody(request)
904
954
  const conversationId = textField(body.conversationId, 80)
905
- const batch = await suggestReplies(ctx, store, conversationId)
955
+ const batch = await tracked(
956
+ { kind: 'suggest', label: '生成回复建议', detail: store.conversation(conversationId)?.title ?? conversationId },
957
+ () => suggestReplies(ctx, store, conversationId),
958
+ )
906
959
  return json({ ok: true, batch, batches: store.suggestions(conversationId) })
907
960
  }),
908
961
  },
package/lib/care.js CHANGED
@@ -35,7 +35,7 @@ function nowMinutes(date = new Date()) {
35
35
  * @param {import('./store.js').Store} options.store
36
36
  * @param {Function} [options.deliver] - send implementation, replaceable for tests.
37
37
  */
38
- export function createCareEngine({ ctx, store, deliver: deliverOverride }) {
38
+ export function createCareEngine({ ctx, store, deliver: deliverOverride, tasks = null }) {
39
39
  /** Per-person serialization: two fast messages produce one answer, not two. */
40
40
  const chains = new Map()
41
41
  /** uin -> timestamps of replies actually sent, for the hourly cap. */
@@ -168,13 +168,20 @@ export function createCareEngine({ ctx, store, deliver: deliverOverride }) {
168
168
  }
169
169
 
170
170
  let text
171
+ const replyTask = tasks === null ? '' : tasks.begin({
172
+ kind: 'care',
173
+ label: care.mode === 'auto' ? '自动回复' : '生成托管草稿',
174
+ detail: store.person(event.peerUin)?.names?.slice(-1)[0] ?? event.peerUin,
175
+ })
171
176
  try {
172
177
  text = await writeAutoReply(ctx, store, {
173
178
  conversationId: conversation.id,
174
179
  uin: event.peerUin,
175
180
  maxChars: care.maxReplyChars,
176
181
  })
182
+ if (replyTask !== '') tasks.finish(replyTask)
177
183
  } catch (error) {
184
+ if (replyTask !== '') tasks.finish(replyTask, error instanceof Error ? error.message : String(error))
178
185
  return skip(`生成回复失败:${error instanceof Error ? error.message : String(error)}`)
179
186
  }
180
187
 
package/lib/features.js CHANGED
@@ -14,6 +14,16 @@ const SIX_HOURS = 6 * 60 * 60 * 1000
14
14
  const EMOJI = /[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}\u{FE0F}\u{2764}]/gu
15
15
  const STICKER = /\[(表情|图片|动画表情|贴图|视频|语音|文件|红包|转账)\]/g
16
16
 
17
+ /**
18
+ * How much one group message that did not @ me counts towards "their favour".
19
+ *
20
+ * In a group, a line nobody addressed to me is usually aimed at someone else, so
21
+ * counting it like a private message inflates the number badly. It is kept as
22
+ * weak evidence rather than dropped: they still chose to speak that way in front
23
+ * of me.
24
+ */
25
+ export const GROUP_UNMENTIONED_WEIGHT = 0.25
26
+
17
27
  /** Median of a numeric list, or 0. */
18
28
  function median(values) {
19
29
  if (values.length === 0) return 0
@@ -54,15 +64,24 @@ function hourOf(ts) {
54
64
  */
55
65
  export function rowsForPerson(store, targetUin) {
56
66
  const enabled = new Set(store.enabledConversationIds())
67
+ const selfUin = String(store.state.settings.selfUin ?? '')
57
68
  const rows = []
58
69
  for (const conversation of store.state.conversations) {
59
70
  if (!enabled.has(conversation.id)) continue
60
71
  const concernsTarget = conversation.peerUin === targetUin
61
72
  || (conversation.participants ?? []).includes(targetUin)
62
73
  if (!concernsTarget) continue
74
+ const isGroup = conversation.kind === 'group'
63
75
  for (const row of store.messages(conversation.id)) {
64
76
  if (row.senderUin === targetUin || row.direction === 'out') {
65
- rows.push({ ...row, conversationId: conversation.id })
77
+ // `atMe` decides the weight later: in a group, a line that never names me
78
+ // is probably a conversation with somebody else.
79
+ rows.push({
80
+ ...row,
81
+ conversationId: conversation.id,
82
+ group: isGroup,
83
+ atMe: selfUin !== '' && String(row.text ?? '').includes(`@${selfUin}`),
84
+ })
66
85
  }
67
86
  }
68
87
  }
@@ -81,9 +100,17 @@ export function measure(rows, targetUin) {
81
100
  const mine = rows.filter(row => row.direction === 'out')
82
101
  const mineAuthentic = mine.filter(row => !isAiAuthored(row))
83
102
 
84
- const theirQuestions = theirs.filter(row => isQuestion(row.text)).length
103
+ // In a group, only the lines that named me count as addressed to me. The rest
104
+ // still appear in the transcript, but they cannot carry the same weight in a
105
+ // "how do they feel about me" verdict.
106
+ const theirAddressed = theirs.filter(row => row.group !== true || row.atMe === true)
107
+ const theirUnaddressed = theirs.filter(row => row.group === true && row.atMe !== true)
108
+ // One number for the prompt: addressed lines at full weight, the rest discounted.
109
+ const theirWeighted = Math.round((theirAddressed.length + theirUnaddressed.length * GROUP_UNMENTIONED_WEIGHT) * 100) / 100
110
+
111
+ const theirQuestions = theirAddressed.filter(row => isQuestion(row.text)).length
85
112
  const myQuestions = mineAuthentic.filter(row => isQuestion(row.text)).length
86
- const theirDecoration = theirs.reduce((total, row) => total + decorationCount(row.text), 0)
113
+ const theirDecoration = theirAddressed.reduce((total, row) => total + decorationCount(row.text), 0)
87
114
  const myDecoration = mineAuthentic.reduce((total, row) => total + decorationCount(row.text), 0)
88
115
 
89
116
  // Initiative: a message that lands more than half an hour after anything else starts a burst.
@@ -103,7 +130,7 @@ export function measure(rows, targetUin) {
103
130
  if (row.senderUin === targetUin && previous.direction === 'out') theirReplies.push(gap)
104
131
  }
105
132
 
106
- const theirNight = theirs.filter(row => hourOf(row.ts) >= 23 || hourOf(row.ts) < 5).length
133
+ const theirNight = theirAddressed.filter(row => hourOf(row.ts) >= 23 || hourOf(row.ts) < 5).length
107
134
  const activeDays = new Set(rows.map(row => new Date(row.ts).toDateString())).size
108
135
  const spanDays = rows.length === 0
109
136
  ? 0
@@ -120,20 +147,26 @@ export function measure(rows, targetUin) {
120
147
  return {
121
148
  totalMessages: rows.length,
122
149
  theirMessages: theirs.length,
150
+ /** Their lines that were actually aimed at me: private, or an @ in a group. */
151
+ theirAddressedMessages: theirAddressed.length,
152
+ /** Group lines that never named me — weak evidence only. */
153
+ theirUnaddressedGroupMessages: theirUnaddressed.length,
154
+ /** Addressed at full weight plus the unaddressed ones at GROUP_UNMENTIONED_WEIGHT. */
155
+ theirWeightedMessages: theirWeighted,
123
156
  myMessages: mine.length,
124
157
  myAuthenticMessages: mineAuthentic.length,
125
158
  aiAdoptedMessages: mine.length - mineAuthentic.length,
126
- theirAvgChars: mean(theirs.map(row => row.text.length)),
159
+ theirAvgChars: mean(theirAddressed.map(row => row.text.length)),
127
160
  myAvgChars: mean(mineAuthentic.map(row => row.text.length)),
128
- theirQuestionRatio: theirs.length === 0 ? 0 : Math.round((theirQuestions / theirs.length) * 100) / 100,
161
+ theirQuestionRatio: theirAddressed.length === 0 ? 0 : Math.round((theirQuestions / theirAddressed.length) * 100) / 100,
129
162
  myQuestionRatio: mineAuthentic.length === 0 ? 0 : Math.round((myQuestions / mineAuthentic.length) * 100) / 100,
130
- theirDecorationPerMessage: theirs.length === 0 ? 0 : Math.round((theirDecoration / theirs.length) * 100) / 100,
163
+ theirDecorationPerMessage: theirAddressed.length === 0 ? 0 : Math.round((theirDecoration / theirAddressed.length) * 100) / 100,
131
164
  myDecorationPerMessage: mineAuthentic.length === 0 ? 0 : Math.round((myDecoration / mineAuthentic.length) * 100) / 100,
132
- theirInitiativeRatio: theirs.length === 0 ? 0 : Math.round((theirInitiatives / Math.max(1, theirInitiatives + myInitiatives)) * 100) / 100,
165
+ theirInitiativeRatio: theirAddressed.length === 0 ? 0 : Math.round((theirInitiatives / Math.max(1, theirInitiatives + myInitiatives)) * 100) / 100,
133
166
  myInitiativeRatio: mineAuthentic.length === 0 ? 0 : Math.round((myInitiatives / Math.max(1, theirInitiatives + myInitiatives)) * 100) / 100,
134
167
  theirMedianReplySeconds: Math.round(median(theirReplies) / 1000),
135
168
  myMedianReplySeconds: Math.round(median(myReplies.filter((_, index) => index < mineAuthentic.length)) / 1000),
136
- theirNightRatio: theirs.length === 0 ? 0 : Math.round((theirNight / theirs.length) * 100) / 100,
169
+ theirNightRatio: theirAddressed.length === 0 ? 0 : Math.round((theirNight / theirAddressed.length) * 100) / 100,
137
170
  theirDoubleTextCount: theirBursts,
138
171
  activeDays,
139
172
  spanDays,
@@ -169,8 +202,11 @@ export function renderTranscript(rows, options) {
169
202
  if (excludeAdopted && isAiAuthored(row)) continue
170
203
  const who = row.senderUin === targetUin ? targetName : '我'
171
204
  const marker = isAiAuthored(row) && markAdopted ? '(AI代笔)' : ''
205
+ // A group line nobody addressed to me is not a message to me; saying so in
206
+ // the transcript is what lets the model discount it.
207
+ const aside = row.group === true && row.senderUin === targetUin && row.atMe !== true ? '(群里未点名)' : ''
172
208
  const body = truncate(String(row.text).replace(/\n+/g, ' / '), 240)
173
- kept.push(`[${formatTime(row.ts)}] ${who}${marker}:${body}`)
209
+ kept.push(`[${formatTime(row.ts)}] ${who}${marker}${aside}:${body}`)
174
210
  }
175
211
  kept.reverse()
176
212
  let text = ''
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": "0.15.3",
3
+ "version": "1.0.3",
4
4
  "description": "QQ 聊天记录好感度档案:本地建档、三项亲密度评分、智能回复提示、按人开启的智能托管、人格画像、可迁移的本地数据位置、从实时通道自动补齐历史。",
5
5
  "type": "module",
6
6
  "exports": {
@@ -0,0 +1,76 @@
1
+ // Group lines that never @ me must weigh less than lines aimed at me.
2
+ // - rowsForPerson tags every row with `group` and `atMe`
3
+ // - measure() counts behaviour over addressed lines only and discounts the rest
4
+ // - renderTranscript() labels the unaddressed ones so the model can discount them
5
+ import fs from 'node:fs'
6
+ import os from 'node:os'
7
+ import path from 'node:path'
8
+ import { fileURLToPath, pathToFileURL } from 'node:url'
9
+
10
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
11
+ const href = (rel) => pathToFileURL(path.join(root, rel)).href
12
+ const { Store } = await import(href('lib/store.js'))
13
+ const { rowsForPerson, measure, renderTranscript, GROUP_UNMENTIONED_WEIGHT } = await import(href('lib/features.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
+ // ---------------------------------------------------------------- real rows
22
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qq-affinity-mention-'))
23
+ process.env.DSH_QQ_AFFINITY_HOME = dir
24
+ const store = new Store(dir)
25
+ store.state.settings.selfUin = '20002'
26
+ store.state.settings.selfName = '我'
27
+
28
+ const privateChat = store.ensureConversation({ kind: 'c2c', title: '私聊', peerUin: '10001' }).conversation
29
+ store.setEnabled(privateChat.id, true)
30
+ const groupChat = store.ensureConversation({ kind: 'group', title: '一个群', groupUin: '90001' }).conversation
31
+ store.setEnabled(groupChat.id, true)
32
+ // The group conversation only contributes while this person is one of its members.
33
+ store.updateConversation(groupChat.id, {})
34
+ store.state.conversations.find(row => row.id === groupChat.id).participants = ['10001']
35
+
36
+ const base = 1700000000000
37
+ store.appendMessages(privateChat.id, [
38
+ { ts: base, senderUin: '10001', senderName: '小明', text: '私聊一句' },
39
+ { ts: base + 1000, senderUin: '20002', senderName: '我', text: '我回一句' },
40
+ ])
41
+ store.appendMessages(groupChat.id, [
42
+ { ts: base + 2000, senderUin: '10001', senderName: '小明', text: '@20002 群里叫我' },
43
+ { ts: base + 3000, senderUin: '10001', senderName: '小明', text: '这句是在跟别人聊' },
44
+ ])
45
+
46
+ const rows = rowsForPerson(store, '10001')
47
+ const inGroup = rows.filter(row => row.group === true)
48
+ const inPrivate = rows.filter(row => row.group !== true)
49
+
50
+ console.log('\n== rowsForPerson tags the origin ==')
51
+ check('private rows are not marked as group', inPrivate.every(row => row.group !== true), JSON.stringify(inPrivate.map(row => row.group)))
52
+ check('group rows are marked', inGroup.length === 2, `${inGroup.length}`)
53
+ check('the @ line is recognised', inGroup.find(row => row.text.includes('@20002'))?.atMe === true)
54
+ check('the other line is not', inGroup.find(row => row.text.includes('跟别人'))?.atMe === false)
55
+
56
+ console.log('\n== measure splits addressed from unaddressed ==')
57
+ const features = measure(rows, '10001')
58
+ check('two of their lines were addressed to me', features.theirAddressedMessages === 2, `${features.theirAddressedMessages}`)
59
+ check('one group line was not', features.theirUnaddressedGroupMessages === 1, `${features.theirUnaddressedGroupMessages}`)
60
+ check('the weighted count discounts it', features.theirWeightedMessages === Math.round((2 + GROUP_UNMENTIONED_WEIGHT) * 100) / 100, `${features.theirWeightedMessages}`)
61
+ const addressedRows = rows.filter(row => row.senderUin === '10001' && (row.group !== true || row.atMe === true))
62
+ const expectedAvg = Math.round(addressedRows.reduce((total, row) => total + row.text.length, 0) / addressedRows.length)
63
+ check('average length uses addressed lines only', features.theirAvgChars === expectedAvg,
64
+ `${features.theirAvgChars} vs ${expectedAvg} over ${addressedRows.length} rows`)
65
+
66
+ console.log('\n== the transcript labels what was not aimed at me ==')
67
+ const transcript = renderTranscript(rows, { targetUin: '10001', targetName: '小明' }).text
68
+ check('the unaddressed group line is marked', transcript.includes('这句是在跟别人聊'.slice(0, 5)) && transcript.includes('(群里未点名)'), transcript)
69
+ const markedCount = (transcript.match(/(群里未点名)/g) ?? []).length
70
+ check('only one line carries the label', markedCount === 1, `${markedCount}`)
71
+ check('the @ line is not labelled', !transcript.split('\n').some(line => line.includes('群里叫我') && line.includes('(群里未点名)')))
72
+
73
+ console.log(`\nweight in use: ${GROUP_UNMENTIONED_WEIGHT}`)
74
+ console.log(failures === 0 ? '\nALL PASS' : `\n${failures} FAILURE(S)`)
75
+ fs.rmSync(dir, { recursive: true, force: true })
76
+ 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)