dsh-qq-affinity 1.7.5 → 1.9.5

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 = '1.7.4'
23
+ const VERSION = '1.9.4'
24
24
 
25
25
  // ---------------------------------------------------------------- palette
26
26
 
@@ -2159,14 +2159,18 @@ window.__ModuleLoader__.load({
2159
2159
  }
2160
2160
  }
2161
2161
 
2162
- const analyzeSelfProfile = async () => {
2162
+ const analyzeSelfProfile = async (force = false) => {
2163
2163
  setBusy('self')
2164
2164
  setPanelError(null)
2165
2165
  try {
2166
- const result = await api('self', { method: 'POST' })
2166
+ const result = await api('self', { method: 'POST', body: { force } })
2167
2167
  if (!alive.current) return
2168
2168
  setState(result.state)
2169
- notify('自我分析已更新。')
2169
+ // Same three outcomes the per-person analysis reports.
2170
+ const profile = result.selfProfile ?? {}
2171
+ if (profile.reused === true) notify('没有新发言,直接沿用了上次的自我分析(没有消耗模型调用)。')
2172
+ else if (profile.basedOn?.incremental === true) notify(`增量更新完成:只看了你新增的 ${profile.basedOn.deltaMessages} 条发言。`)
2173
+ else notify('自我分析已更新。')
2170
2174
  } catch (failure) {
2171
2175
  if (!alive.current) return
2172
2176
  setPanelError({ where: 'self', message: failure.message })
@@ -3326,8 +3330,18 @@ window.__ModuleLoader__.load({
3326
3330
  key: 'run',
3327
3331
  kind: profile === null ? 'primary' : 'outline',
3328
3332
  disabled: busy === 'self',
3333
+ title: profile === null
3334
+ ? '第一次分析会读你全部真实发言'
3335
+ : '只把这之后新增的发言交给模型;没有新发言就直接跳过',
3329
3336
  onClick: () => void analyzeSelfProfile(),
3330
- }, busy === 'self' ? '正在分析…' : (profile === null ? '分析我自己' : '重新分析')),
3337
+ }, busy === 'self' ? '正在分析…' : (profile === null ? '分析我自己' : '增量更新')),
3338
+ profile === null ? null : h(Btn, {
3339
+ key: 'redo',
3340
+ kind: 'quiet',
3341
+ disabled: busy === 'self',
3342
+ title: '忽略上次结论,从头读全部发言(更慢、更贵,但能推翻旧判断)',
3343
+ onClick: () => void analyzeSelfProfile(true),
3344
+ }, '完整重算'),
3331
3345
  ],
3332
3346
  }, profile === null
3333
3347
  ? h('div', { style: { fontSize: 12, color: C.label2, lineHeight: 1.85 } },
@@ -3432,6 +3446,15 @@ window.__ModuleLoader__.load({
3432
3446
  key: 'based',
3433
3447
  style: { fontSize: 11, color: C.label2, lineHeight: 1.6 },
3434
3448
  }, `依据你真实发出的 ${profile.basedOn?.myMessages ?? 0} 条消息(另有 ${profile.basedOn?.excludedAiMessages ?? 0} 条 AI 代笔已排除),更新于 ${fmtTime(profile.updatedAt)}。`),
3449
+ // Same accounting as the person pages: how this run was produced and
3450
+ // what it cost, so "incremental" is visible rather than implied.
3451
+ h('div', {
3452
+ key: 'self-cost',
3453
+ style: { fontSize: 10.5, color: C.label2, display: 'flex', gap: 12, flexWrap: 'wrap' },
3454
+ }, [
3455
+ h('span', { key: 'm' }, `分析方式:${analysisMode(profile)}`),
3456
+ h('span', { key: 't' }, `本次 ${tokenCost(profile.usage)} tokens`),
3457
+ ]),
3435
3458
  ]))
3436
3459
 
3437
3460
  return h('div', { style: { display: 'flex', flexDirection: 'column', gap: 12 } }, [errorBox, header])
@@ -3626,6 +3649,11 @@ window.__ModuleLoader__.load({
3626
3649
  }, [
3627
3650
  h('span', { key: 't', style: { color: C.label, fontWeight: 600 } }, '群贡献'),
3628
3651
  h('span', { key: 's' }, `发言最多的 ${top.length} 人 · 柱高 = 发言占比`),
3652
+ stats.aiExcluded > 0 ? h('span', {
3653
+ key: 'ai',
3654
+ title: '插件替你自动发的消息不算你的发言',
3655
+ style: { color: C.label2 },
3656
+ }, `· 已排除插件代发的 ${stats.aiExcluded} 条`) : null,
3629
3657
  ]),
3630
3658
  // Legend: the colour is the ranking, not decoration.
3631
3659
  h('div', {
@@ -3675,42 +3703,85 @@ window.__ModuleLoader__.load({
3675
3703
  title: `${label(speaker)}:${speaker.messages} 条,占 ${Math.round(speaker.share * 100)}%,平均 ${speaker.avgChars} 字(色阶位置 ${Math.round(position * 100)}%)`,
3676
3704
  style: { display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, minWidth: 0 },
3677
3705
  }, [
3678
- // Avatar, with a lettered circle behind it for when the CDN is unreachable.
3706
+ // The avatar sits in its own frame so the winner's crown is not
3707
+ // clipped by the circle's overflow:hidden.
3679
3708
  h('div', {
3680
- key: 'av',
3681
- style: {
3682
- position: 'relative',
3683
- width: 34,
3684
- height: 34,
3685
- borderRadius: 999,
3686
- overflow: 'hidden',
3687
- flex: '0 0 auto',
3688
- background: tint(color, 18),
3689
- border: `1px solid ${isMe ? C.warn : C.border1}`,
3690
- display: 'flex',
3691
- alignItems: 'center',
3692
- justifyContent: 'center',
3693
- fontSize: 13,
3694
- fontWeight: 600,
3695
- color,
3696
- },
3709
+ key: 'avwrap',
3710
+ style: { position: 'relative', width: 34, height: 34, flex: '0 0 auto' },
3697
3711
  }, [
3698
- h('span', { key: 'i', style: { position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' } }, initial),
3699
- h('img', {
3700
- key: 'img',
3701
- src: `https://q1.qlogo.cn/g?b=qq&nk=${encodeURIComponent(speaker.uin)}&s=100`,
3702
- alt: '',
3703
- loading: 'lazy',
3704
- referrerPolicy: 'no-referrer',
3705
- onError: (event) => { event.currentTarget.style.display = 'none' },
3706
- onLoad: (event) => { event.currentTarget.style.position = 'absolute' },
3712
+ h('div', {
3713
+ key: 'av',
3707
3714
  style: {
3708
- width: '100%',
3709
- height: '100%',
3710
- objectFit: 'cover',
3711
- display: 'block',
3715
+ position: 'relative',
3716
+ width: 34,
3717
+ height: 34,
3718
+ borderRadius: 999,
3719
+ overflow: 'hidden',
3720
+ flex: '0 0 auto',
3721
+ background: tint(color, 18),
3722
+ border: `1px solid ${index === 0 ? C.warn : (isMe ? C.warn : C.border1)}`,
3723
+ display: 'flex',
3724
+ alignItems: 'center',
3725
+ justifyContent: 'center',
3726
+ fontSize: 13,
3727
+ fontWeight: 600,
3728
+ color,
3712
3729
  },
3713
- }),
3730
+ }, [
3731
+ h('span', { key: 'i', style: { position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' } }, initial),
3732
+ h('img', {
3733
+ key: 'img',
3734
+ src: `https://q1.qlogo.cn/g?b=qq&nk=${encodeURIComponent(speaker.uin)}&s=100`,
3735
+ alt: '',
3736
+ loading: 'lazy',
3737
+ referrerPolicy: 'no-referrer',
3738
+ onError: (event) => { event.currentTarget.style.display = 'none' },
3739
+ onLoad: (event) => { event.currentTarget.style.position = 'absolute' },
3740
+ style: {
3741
+ width: '100%',
3742
+ height: '100%',
3743
+ objectFit: 'cover',
3744
+ display: 'block',
3745
+ },
3746
+ }),
3747
+ ]),
3748
+ // Whoever spoke the most gets the crown.
3749
+ index === 0 ? h('svg', {
3750
+ key: 'crown',
3751
+ viewBox: '0 0 24 24',
3752
+ width: 19,
3753
+ height: 19,
3754
+ role: 'img',
3755
+ 'aria-label': '群贡献第一',
3756
+ style: {
3757
+ position: 'absolute',
3758
+ top: -9,
3759
+ right: -6,
3760
+ transform: 'rotate(12deg)',
3761
+ filter: 'drop-shadow(0 1px 2px rgba(0,0,0,.3))',
3762
+ pointerEvents: 'none',
3763
+ },
3764
+ }, [
3765
+ h('path', {
3766
+ key: 'body',
3767
+ d: 'M3 16.2 4.3 6.6l4.6 4.1L12 4.4l3.1 6.3 4.6-4.1L21 16.2z',
3768
+ fill: C.warn,
3769
+ stroke: C.bg,
3770
+ strokeWidth: 1,
3771
+ strokeLinejoin: 'round',
3772
+ }),
3773
+ h('rect', {
3774
+ key: 'base',
3775
+ x: 4.6,
3776
+ y: 17.4,
3777
+ width: 14.8,
3778
+ height: 3,
3779
+ rx: 1.2,
3780
+ fill: C.warn,
3781
+ stroke: C.bg,
3782
+ strokeWidth: 1,
3783
+ }),
3784
+ ]) : null,
3714
3785
  ]),
3715
3786
  h('div', {
3716
3787
  key: 'n',
@@ -3752,6 +3823,23 @@ window.__ModuleLoader__.load({
3752
3823
  key: 'c',
3753
3824
  style: { fontSize: 10, color: C.label2, fontVariantNumeric: 'tabular-nums' },
3754
3825
  }, `${speaker.messages} 条`),
3826
+ // Rank badge under the count. The winner's badge is amber, matching
3827
+ // the crown on its avatar.
3828
+ h('div', {
3829
+ key: 'rank',
3830
+ title: `群贡献第 ${index + 1} 名`,
3831
+ style: {
3832
+ fontSize: 9.5,
3833
+ lineHeight: '14px',
3834
+ padding: '0 5px',
3835
+ borderRadius: 999,
3836
+ fontWeight: index === 0 ? 700 : 500,
3837
+ color: index === 0 ? C.warn : C.label2,
3838
+ background: tint(index === 0 ? C.warn : color, 16),
3839
+ border: `1px solid ${index === 0 ? C.warn : C.border1}`,
3840
+ fontVariantNumeric: 'tabular-nums',
3841
+ },
3842
+ }, `#${index + 1}`),
3755
3843
  ])
3756
3844
  })),
3757
3845
  selfUin === '' || top.some(speaker => speaker.uin === selfUin)
@@ -4005,6 +4093,7 @@ window.__ModuleLoader__.load({
4005
4093
  stat('参与计算消息', String(stored.basedOn?.totalMessages ?? 0)),
4006
4094
  stat('我的真实表达', String(stored.basedOn?.myAuthenticMessages ?? 0)),
4007
4095
  stat('AI 代笔(已排除)', String(stored.basedOn?.aiAdoptedMessages ?? 0)),
4096
+ stat('对自动回复的回应(降权)', String(stored.basedOn?.theirAfterAiMessages ?? 0)),
4008
4097
  stat('使用的对话', `${(stored.basedOn?.conversations ?? []).length} 个`),
4009
4098
  stat('上次的分析方式', analysisMode(stored)),
4010
4099
  stat('上次的 token', tokenCost(stored.usage)),
package/index.js CHANGED
@@ -53,6 +53,19 @@ export const inject = ['connection', 'timer']
53
53
  */
54
54
  export function apply(ctx) {
55
55
  const store = new Store(resolveDataDirectory())
56
+
57
+ // Restore the AI mark on messages the plugin sent: a bridge echo or a re-fetched
58
+ // history copy arrives without it, and an unmarked copy reads as something the user
59
+ // typed by hand. This only adds the flag — it never removes or rewrites a message.
60
+ try {
61
+ const remarked = store.remarkSentReplies()
62
+ if (remarked.marked > 0) {
63
+ ctx.logger?.info?.(`qq-affinity: marked ${remarked.marked} plugin-sent messages that had no AI mark`)
64
+ }
65
+ } catch (error) {
66
+ ctx.logger?.warn?.(`qq-affinity: reply marking skipped: ${error instanceof Error ? error.message : String(error)}`)
67
+ }
68
+
56
69
  // One registry shared by the routes and the care engine, so the panel shows
57
70
  // every slow operation in the same list.
58
71
  const tasks = createTaskRegistry()
package/lib/analyze.js CHANGED
@@ -135,6 +135,10 @@ function measurementBlock(features, extra = {}) { return [
135
135
  features.theirAddressedMessages === undefined
136
136
  ? ''
137
137
  : `对方真正对我说的话 ${features.theirAddressedMessages} 条(私聊 + 群里 @ 我),加权后相当于 ${features.theirWeightedMessages} 条。`,
138
+ features.theirAfterAiMessages === undefined || features.theirAfterAiMessages === 0
139
+ ? ''
140
+ : `⚠ 对方有 ${features.theirAfterAiMessages} 条是在回应或评论插件替我发的自动回复(转写里标了「回应自动回复」「在说自动回复」):`
141
+ + '那评价的是自动回复那段文字,不是对我的态度,只按 30% 权重计入,不能单独据此加减分。',
138
142
  `平均字数:对方 ${features.theirAvgChars} / 我 ${features.myAvgChars}`,
139
143
  `提问率:对方 ${features.theirQuestionRatio} / 我 ${features.myQuestionRatio}`,
140
144
  `每条消息的颜文字或表情标记数:对方 ${features.theirDecorationPerMessage} / 我 ${features.myDecorationPerMessage}`,
@@ -240,6 +244,7 @@ export async function scorePerson(ctx, store, uin, options = {}) {
240
244
  renderTranscript(delta, { targetUin: uin, targetName, maxChars: Math.max(2000, Math.floor(maxChars / 2)) }).text || '(无)',
241
245
  '',
242
246
  '【要求】新消息如果不足以改变判断,三项分数就保持不变;只有出现明确的新证据才调整,并在 reasons 里点出是哪条新消息导致的。',
247
+ '标着(AI代笔)的发言是插件替我发的,不是我的表达,不能当成我对 TA 的态度。',
243
248
  )
244
249
  } else {
245
250
  parts.push('', '【完整对话】', all.text === '' ? '(无)' : all.text)
@@ -267,6 +272,8 @@ export async function scorePerson(ctx, store, uin, options = {}) {
267
272
  'My favor 必须只由我的真实表达推出;如果我的真实表达很少,就明确说明证据不足并给较低 confidence。',
268
273
  '群聊纪律:对方在群里没有 @ 我的发言,多数不是对我说的(转写里标了「群里未点名」)。判断 theirFavor 时这些只能算很弱的旁证——'
269
274
  + '不要把「他在群里聊得热闹」当成「他对我热情」,也不要把「他在群里没理我」当成冷落。',
275
+ '自动回复纪律:标着「回应自动回复」「在说自动回复」的发言,是在回应或评论插件替我发的那段文字,不是对我的态度。有人喜欢这种回复、有人讨厌,'
276
+ + '两种都不代表对我的感受,判断 theirFavor 时只按很弱的旁证处理。',
270
277
  )
271
278
 
272
279
  // Look at the newest pictures only when both the user and the model allow it.
@@ -302,6 +309,8 @@ export async function scorePerson(ctx, store, uin, options = {}) {
302
309
  totalMessages: features.totalMessages,
303
310
  myAuthenticMessages: features.myAuthenticMessages,
304
311
  aiAdoptedMessages: features.aiAdoptedMessages,
312
+ // Their answers to automatic replies: counted, but only as weak evidence.
313
+ theirAfterAiMessages: features.theirAfterAiMessages ?? 0,
305
314
  // The evidence this verdict covers, so the next run can tell what is new.
306
315
  fingerprint,
307
316
  lastTs: rows.length === 0 ? 0 : rows[rows.length - 1].ts,
@@ -350,17 +359,21 @@ export async function writeAutoReply(ctx, store, request) {
350
359
  if (newest === undefined) throw new Error('这个对话里没有对方的消息。')
351
360
 
352
361
  const features = rows.length > 0 ? measure(rows, uin) : undefined
353
- const recent = renderTranscript(conversationRows, { targetUin: uin, targetName, maxChars: 4000 })
362
+ // Enough context to answer one message. 4000 chars of transcript bought nothing
363
+ // but tokens: the reply is one line, and the debounce already folds a burst into
364
+ // a single turn, so the last couple of exchanges are all that matter.
365
+ const recent = renderTranscript(conversationRows, { targetUin: uin, targetName, maxChars: 2500 })
366
+ // The configured voice. With the default persona the reply imitates me, so my own
367
+ // lines are the style sample. With a character persona the prompt explicitly says
368
+ // "do not copy my wording" — sending 2500 chars of it anyway was pure waste.
369
+ const persona = resolvePersona(store.state.replyPersonas, store.state.care[uin]?.persona)
370
+ const inCharacter = persona.prompt !== ''
354
371
  const input = renderTranscript(rows, {
355
372
  targetUin: uin,
356
373
  targetName,
357
374
  excludeAdopted: true,
358
- maxChars: 2500,
375
+ maxChars: inCharacter ? 600 : 2500,
359
376
  })
360
- // The configured voice. With the default persona the reply simply imitates me;
361
- // with a preset it is written in that character's voice instead.
362
- const persona = resolvePersona(store.state.replyPersonas, store.state.care[uin]?.persona)
363
- const inCharacter = persona.prompt !== ''
364
377
  // A single huge message must not become a huge request: the quoted line was the
365
378
  // one part of this prompt with no size bound.
366
379
  const inbound = clampInbound(newest.text)
@@ -1097,6 +1110,9 @@ export async function analyzeGroup(ctx, store, conversationId, options = {}) {
1097
1110
  `平均每条 ${features.avgChars} 字,提问率 ${Math.round(features.questionRatio * 100)}%,表情密度 ${features.decorationPerMessage},含链接比例 ${Math.round(features.linkShare * 100)}%`,
1098
1111
  `连续聊起来的段落 ${features.bursts} 段,最快的一次间隔 ${features.fastestReplySeconds} 秒`,
1099
1112
  `最活跃的时段:${hourBlock(features.hourHistogram)}`,
1113
+ features.aiExcluded === undefined || features.aiExcluded === 0
1114
+ ? ''
1115
+ : `(另有 ${features.aiExcluded} 条是插件替你自动发的,已从上面的统计里剔除,不算任何人的发言)`,
1100
1116
  '',
1101
1117
  '【说话人分布】',
1102
1118
  speakerBlock(features),
package/lib/features.js CHANGED
@@ -24,6 +24,45 @@ const STICKER = /\[(表情|图片|动画表情|贴图|视频|语音|文件|红
24
24
  */
25
25
  export const GROUP_UNMENTIONED_WEIGHT = 0.25
26
26
 
27
+ /**
28
+ * How much one of their lines counts when it answers something the plugin wrote.
29
+ *
30
+ * Their reaction to an automatic reply says whether they like that kind of wording —
31
+ * some people enjoy it, some hate it — and neither is feedback about me. Kept as
32
+ * weak evidence rather than dropped, because ignoring my message entirely is still
33
+ * a signal.
34
+ */
35
+ export const AI_REACTION_WEIGHT = 0.3
36
+
37
+ /**
38
+ * Words that only show up when someone is talking about the automatic reply
39
+ * itself: "你是不是机器人", "AI 味好重", "又是自动回复".
40
+ */
41
+ const AI_EXPLICIT = /(自动回复|机器人回复|不是本人|代回|替你回|谁回的|托管|模板回复|复制粘贴的|话术|复读机|像\s*AI|AI\s*味|ai\s*味)/i
42
+ const AI_WORD = /(AI|ai|人工智能|大模型|语言模型|机器人|人机|GPT|gpt|ChatGPT|chatgpt|DeepSeek|deepseek|豆包|文心|通义|千问|Kimi|kimi)/
43
+ /** The verb that turns a mention into a comment about the reply. */
44
+ const AI_CONTEXT = /(你是|你是不是|这是|是不是|你在用|谁在|谁替你|怎么|好像|感觉|回复|回的|说话|语气|味儿|味道)/
45
+ /** A comment on how the reply is worded, without naming AI at all. */
46
+ const STYLE_META = /(说话|语气|用词|回复|回答|打字|讲话).{0,10}(怎么|这么|真|太|有点|好像|突然|变得).{0,8}(官方|客气|正式|生硬|机械|僵硬|模板|套路|不像|AI|ai)/
47
+
48
+ /**
49
+ * Whether one of their messages is plainly about the automatic reply rather than
50
+ * about me.
51
+ *
52
+ * Adjacency (a line right after an AI message) is handled separately; this catches
53
+ * the ones that come a few turns later or that name it outright. Deliberately
54
+ * narrow — a long message that merely mentions AI is probably a normal topic.
55
+ * @param {string} text
56
+ */
57
+ export function looksAboutAutoReply(text) {
58
+ const value = String(text ?? '').trim()
59
+ // Meta-comments are short. A wall of text mentioning AI is a conversation topic.
60
+ if (value === '' || value.length > 120) return false
61
+ if (AI_EXPLICIT.test(value)) return true
62
+ if (STYLE_META.test(value)) return true
63
+ return AI_WORD.test(value) && AI_CONTEXT.test(value)
64
+ }
65
+
27
66
  /** Median of a numeric list, or 0. */
28
67
  function median(values) {
29
68
  if (values.length === 0) return 0
@@ -72,17 +111,27 @@ export function rowsForPerson(store, targetUin) {
72
111
  || (conversation.participants ?? []).includes(targetUin)
73
112
  if (!concernsTarget) continue
74
113
  const isGroup = conversation.kind === 'group'
114
+ // Tracked per conversation: whether the line just before this one was written
115
+ // by the plugin on my behalf. Someone answering an automatic reply is reacting
116
+ // to that text, not to me — the two must not be averaged together.
117
+ let previousRow
75
118
  for (const row of store.messages(conversation.id)) {
76
119
  if (row.senderUin === targetUin || row.direction === 'out') {
77
- // `atMe` decides the weight later: in a group, a line that never names me
78
- // is probably a conversation with somebody else.
120
+ // `atMe` and `afterAi` decide the weight later: in a group a line that
121
+ // never names me is probably aimed elsewhere, and a line right after an
122
+ // automatic reply is aimed at the plugin.
79
123
  rows.push({
80
124
  ...row,
81
125
  conversationId: conversation.id,
82
126
  group: isGroup,
83
127
  atMe: selfUin !== '' && String(row.text ?? '').includes(`@${selfUin}`),
128
+ afterAi: previousRow !== undefined && isAiAuthored(previousRow),
129
+ // A line that talks about the automatic reply itself, even when it does
130
+ // not directly follow one.
131
+ aboutAi: row.senderUin === targetUin && looksAboutAutoReply(row.text),
84
132
  })
85
133
  }
134
+ previousRow = row
86
135
  }
87
136
  }
88
137
  rows.sort((a, b) => a.ts - b.ts)
@@ -100,17 +149,35 @@ export function measure(rows, targetUin) {
100
149
  const mine = rows.filter(row => row.direction === 'out')
101
150
  const mineAuthentic = mine.filter(row => !isAiAuthored(row))
102
151
 
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)
152
+ /**
153
+ * How much one of their lines counts as evidence about me.
154
+ *
155
+ * Full weight only when it is genuinely addressed to me: a private line (which is
156
+ * by definition to me) or a group line that named me. Two things discount it:
157
+ * a group line that never named me (probably aimed elsewhere), and a line that
158
+ * answers an automatic reply — that measures how they feel about the plugin's
159
+ * wording, not about me.
160
+ */
161
+ const weightOf = (row) => {
162
+ if (row.group === true && row.atMe !== true) return GROUP_UNMENTIONED_WEIGHT
163
+ if (row.afterAi === true || row.aboutAi === true) return AI_REACTION_WEIGHT
164
+ return 1
165
+ }
166
+ const weightedCount = (list) => list.reduce((total, row) => total + weightOf(row), 0)
167
+ const weightedSum = (list, pick) => list.reduce((total, row) => total + weightOf(row) * pick(row), 0)
168
+
169
+ const theirAddressed = theirs.filter(row => weightOf(row) === 1)
107
170
  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
171
+ /** Their answers to an automatic reply: the line right after one, or one about it. */
172
+ const theirAfterAi = theirs.filter(row => row.afterAi === true || row.aboutAi === true)
173
+ const theirAboutAi = theirs.filter(row => row.aboutAi === true && row.afterAi !== true)
174
+ // One number for the prompt: everything, with the discounted lines weighed down.
175
+ const theirWeighted = Math.round(weightedCount(theirs) * 100) / 100
176
+ const theirWeightTotal = weightedCount(theirs)
110
177
 
111
- const theirQuestions = theirAddressed.filter(row => isQuestion(row.text)).length
178
+ const theirQuestions = weightedSum(theirs, row => (isQuestion(row.text) ? 1 : 0))
112
179
  const myQuestions = mineAuthentic.filter(row => isQuestion(row.text)).length
113
- const theirDecoration = theirAddressed.reduce((total, row) => total + decorationCount(row.text), 0)
180
+ const theirDecoration = weightedSum(theirs, row => decorationCount(row.text))
114
181
  const myDecoration = mineAuthentic.reduce((total, row) => total + decorationCount(row.text), 0)
115
182
 
116
183
  // Initiative: a message that lands more than half an hour after anything else starts a burst.
@@ -123,14 +190,19 @@ export function measure(rows, targetUin) {
123
190
  const previous = rows[index - 1]
124
191
  const gap = previous === undefined ? Number.POSITIVE_INFINITY : row.ts - previous.ts
125
192
  const starter = gap > HALF_HOUR
193
+ // A message the plugin sent on my behalf is not me acting: it must not count
194
+ // as me starting a conversation or as me answering quickly.
195
+ const mineOut = row.direction === 'out' && !isAiAuthored(row)
126
196
  if (starter && row.senderUin === targetUin) theirInitiatives += 1
127
- if (starter && row.direction === 'out') myInitiatives += 1
197
+ if (starter && mineOut) myInitiatives += 1
128
198
  if (previous === undefined || gap > SIX_HOURS) continue
129
- if (row.direction === 'out' && previous.senderUin === targetUin) myReplies.push(gap)
130
- if (row.senderUin === targetUin && previous.direction === 'out') theirReplies.push(gap)
199
+ if (mineOut && previous.senderUin === targetUin) myReplies.push(gap)
200
+ // Their reply time is only meaningful when the thing they answered was a real
201
+ // message of mine, not an automatic one.
202
+ if (row.senderUin === targetUin && previous.direction === 'out' && !isAiAuthored(previous)) theirReplies.push(gap)
131
203
  }
132
204
 
133
- const theirNight = theirAddressed.filter(row => hourOf(row.ts) >= 23 || hourOf(row.ts) < 5).length
205
+ const theirNight = weightedSum(theirs, row => (hourOf(row.ts) >= 23 || hourOf(row.ts) < 5 ? 1 : 0))
134
206
  const activeDays = new Set(rows.map(row => new Date(row.ts).toDateString())).size
135
207
  const spanDays = rows.length === 0
136
208
  ? 0
@@ -144,29 +216,39 @@ export function measure(rows, targetUin) {
144
216
  return previous !== undefined && previous.senderUin === targetUin && row.senderUin === targetUin ? total + 1 : total
145
217
  }, 0)
146
218
 
219
+ /** A weighted mean, so discounted lines pull the average only in proportion. */
220
+ const weightedMean = (list, pick) => {
221
+ const weight = weightedCount(list)
222
+ return weight === 0 ? 0 : Math.round(weightedSum(list, pick) / weight)
223
+ }
224
+
147
225
  return {
148
226
  totalMessages: rows.length,
149
227
  theirMessages: theirs.length,
150
- /** Their lines that were actually aimed at me: private, or an @ in a group. */
228
+ /** Their lines that were actually aimed at me, at full weight. */
151
229
  theirAddressedMessages: theirAddressed.length,
152
230
  /** Group lines that never named me — weak evidence only. */
153
231
  theirUnaddressedGroupMessages: theirUnaddressed.length,
154
- /** Addressed at full weight plus the unaddressed ones at GROUP_UNMENTIONED_WEIGHT. */
232
+ /** Lines that answered an automatic reply, or talked about it. */
233
+ theirAfterAiMessages: theirAfterAi.length,
234
+ /** Of those, the ones that named it without directly following one. */
235
+ theirAboutAiMessages: theirAboutAi.length,
236
+ /** Everything at its weight: full for addressed, discounted for the rest. */
155
237
  theirWeightedMessages: theirWeighted,
156
238
  myMessages: mine.length,
157
239
  myAuthenticMessages: mineAuthentic.length,
158
240
  aiAdoptedMessages: mine.length - mineAuthentic.length,
159
- theirAvgChars: mean(theirAddressed.map(row => row.text.length)),
241
+ theirAvgChars: weightedMean(theirs, row => row.text.length),
160
242
  myAvgChars: mean(mineAuthentic.map(row => row.text.length)),
161
- theirQuestionRatio: theirAddressed.length === 0 ? 0 : Math.round((theirQuestions / theirAddressed.length) * 100) / 100,
243
+ theirQuestionRatio: theirWeightTotal === 0 ? 0 : Math.round((theirQuestions / theirWeightTotal) * 100) / 100,
162
244
  myQuestionRatio: mineAuthentic.length === 0 ? 0 : Math.round((myQuestions / mineAuthentic.length) * 100) / 100,
163
- theirDecorationPerMessage: theirAddressed.length === 0 ? 0 : Math.round((theirDecoration / theirAddressed.length) * 100) / 100,
245
+ theirDecorationPerMessage: theirWeightTotal === 0 ? 0 : Math.round((theirDecoration / theirWeightTotal) * 100) / 100,
164
246
  myDecorationPerMessage: mineAuthentic.length === 0 ? 0 : Math.round((myDecoration / mineAuthentic.length) * 100) / 100,
165
247
  theirInitiativeRatio: theirAddressed.length === 0 ? 0 : Math.round((theirInitiatives / Math.max(1, theirInitiatives + myInitiatives)) * 100) / 100,
166
248
  myInitiativeRatio: mineAuthentic.length === 0 ? 0 : Math.round((myInitiatives / Math.max(1, theirInitiatives + myInitiatives)) * 100) / 100,
167
249
  theirMedianReplySeconds: Math.round(median(theirReplies) / 1000),
168
250
  myMedianReplySeconds: Math.round(median(myReplies.filter((_, index) => index < mineAuthentic.length)) / 1000),
169
- theirNightRatio: theirAddressed.length === 0 ? 0 : Math.round((theirNight / theirAddressed.length) * 100) / 100,
251
+ theirNightRatio: theirWeightTotal === 0 ? 0 : Math.round((theirNight / theirWeightTotal) * 100) / 100,
170
252
  theirDoubleTextCount: theirBursts,
171
253
  activeDays,
172
254
  spanDays,
@@ -205,8 +287,12 @@ export function renderTranscript(rows, options) {
205
287
  // A group line nobody addressed to me is not a message to me; saying so in
206
288
  // the transcript is what lets the model discount it.
207
289
  const aside = row.group === true && row.senderUin === targetUin && row.atMe !== true ? '(群里未点名)' : ''
290
+ // Their answer right after an automatic reply is a reaction to that text.
291
+ const reacting = row.senderUin === targetUin && row.afterAi === true
292
+ ? '(回应自动回复)'
293
+ : (row.senderUin === targetUin && row.aboutAi === true ? '(在说自动回复)' : '')
208
294
  const body = truncate(String(row.text).replace(/\n+/g, ' / '), 240)
209
- kept.push(`[${formatTime(row.ts)}] ${who}${marker}${aside}:${body}`)
295
+ kept.push(`[${formatTime(row.ts)}] ${who}${marker}${aside}${reacting}:${body}`)
210
296
  }
211
297
  kept.reverse()
212
298
  let text = ''
@@ -245,7 +331,15 @@ export function lastInbound(rows, targetUin) {
245
331
  * @param {string} [selfUin]
246
332
  */
247
333
  export function groupFeatures(rows, selfUin = '') {
248
- const ordered = [...rows].sort((left, right) => left.ts - right.ts)
334
+ // Auto-replies and adopted suggestions are lines the plugin wrote in my name.
335
+ // Counting them as my contribution would let the plugin inflate itself, so the
336
+ // room is measured on what people actually typed.
337
+ let aiExcluded = 0
338
+ const ordered = [...rows].sort((left, right) => left.ts - right.ts).filter(row => {
339
+ if (!isAiAuthored(row)) return true
340
+ aiExcluded += 1
341
+ return false
342
+ })
249
343
  const speakers = new Map()
250
344
  for (const row of ordered) {
251
345
  const uin = row.senderUin === '' ? 'unknown' : row.senderUin
@@ -337,5 +431,7 @@ export function groupFeatures(rows, selfUin = '') {
337
431
  bursts,
338
432
  fastestReplySeconds: Number.isFinite(fastestGap) ? Math.round(fastestGap / 1000) : 0,
339
433
  lastContactDays: ordered.length === 0 ? null : Math.round((Date.now() - ordered[ordered.length - 1].ts) / (24 * 60 * 60 * 1000)),
434
+ /** Lines the plugin wrote in my name, left out of every number above. */
435
+ aiExcluded,
340
436
  }
341
437
  }
package/lib/store.js CHANGED
@@ -16,6 +16,45 @@ import { resolveDataDirectory } from './home.js'
16
16
  /** Bumped when the on-disk shape changes in a way that needs migration. */
17
17
  export const STORE_VERSION = 1
18
18
 
19
+ /**
20
+ * How many auto-reply rows the outbox keeps.
21
+ *
22
+ * The file is rewritten in full on every status change, so an unbounded log would
23
+ * slowly make each write more expensive. The panel never shows more than a few
24
+ * dozen rows, and the quota only looks at the last hour.
25
+ */
26
+ const MAX_OUTBOX_ROWS = 800
27
+
28
+ /**
29
+ * How far apart two copies of one sent message may be.
30
+ *
31
+ * The plugin writes its own record when it sends; the bridge echoes the same message
32
+ * back within a second or two. The window is tight for the echo direction on purpose:
33
+ * a real message that happens to repeat an earlier line must never be swallowed. Only
34
+ * the plugin's own record is allowed to lag, because it is written after the send.
35
+ */
36
+ const ECHO_WINDOW_MS = 5000
37
+ const ECHO_WINDOW_AI_RECORD_MS = 120000
38
+
39
+ /**
40
+ * The stored copy of a message the plugin also recorded itself, if any.
41
+ *
42
+ * Only pairs where at least one side carries the AI mark are treated as one message:
43
+ * the same text repeated by hand twice is real conversation.
44
+ */
45
+ function findEchoTwin(existing, message) {
46
+ const text = String(message.text ?? '').slice(0, 80)
47
+ if (text === '') return undefined
48
+ const incomingAi = message.aiAuto === true || message.aiAdopted === true
49
+ const window = incomingAi ? ECHO_WINDOW_AI_RECORD_MS : ECHO_WINDOW_MS
50
+ return existing.find(row => {
51
+ if (String(row.text ?? '').slice(0, 80) !== text) return false
52
+ if (row.senderUin !== message.senderUin) return false
53
+ if (Math.abs(Number(row.ts) - Number(message.ts)) > window) return false
54
+ return incomingAi || row.aiAuto === true || row.aiAdopted === true
55
+ })
56
+ }
57
+
19
58
  /** The conversation key derives from who the conversation is with, so repeats merge. */
20
59
  function conversationKey(kind, peerUin, groupUin, title) {
21
60
  if (kind === 'group' && groupUin) return `group:${groupUin}`
@@ -25,8 +64,7 @@ function conversationKey(kind, peerUin, groupUin, title) {
25
64
  }
26
65
 
27
66
  /** A fresh metadata document. */
28
- function emptyMeta() {
29
- return {
67
+ function emptyMeta() { return {
30
68
  version: STORE_VERSION,
31
69
  settings: {
32
70
  selfUin: '',
@@ -339,12 +377,53 @@ export class Store {
339
377
  const selfUin = this.state.settings.selfUin
340
378
  const rows = []
341
379
  let duplicates = 0
380
+ let markedExisting = false
381
+ /**
382
+ * Carry the AI mark from the incoming copy onto the one already stored.
383
+ *
384
+ * This is the whole point of the merge: the bridge echo carries no mark, so
385
+ * whichever copy arrives first must not decide whether the message reads as
386
+ * "typed by the user".
387
+ */
388
+ const carryMarks = (twin, message) => {
389
+ let changed = false
390
+ if (message.aiAuto === true && twin.aiAuto !== true) {
391
+ twin.aiAuto = true
392
+ changed = true
393
+ }
394
+ if (message.aiAdopted === true && twin.aiAdopted !== true) {
395
+ twin.aiAdopted = true
396
+ changed = true
397
+ }
398
+ return changed
399
+ }
342
400
  for (const message of incoming) {
343
401
  // Second granularity: a live report and the plugin's own record of the
344
402
  // same message can differ by a few milliseconds.
345
403
  const fingerprint = `${Math.floor(message.ts / 1000)}|${message.senderUin}|${(message.text ?? '').slice(0, 80)}`
346
- if (seen.has(fingerprint)) {
404
+ const exact = existing.find(row => row.fingerprint === fingerprint)
405
+ ?? rows.find(row => row.fingerprint === fingerprint)
406
+ if (exact !== undefined) {
347
407
  duplicates += 1
408
+ if (carryMarks(exact, message) && existing.includes(exact)) markedExisting = true
409
+ continue
410
+ }
411
+ // A line the plugin sent arrives twice: once from our own send, once as the
412
+ // bridge echoing it back. The echo has no AI mark, so left alone it would read
413
+ // as something the user typed by hand — the two copies must collapse into one,
414
+ // and that one must keep the AI mark whichever copy lands first.
415
+ const twin = findEchoTwin(existing, message)
416
+ if (twin !== undefined) {
417
+ duplicates += 1
418
+ seen.add(fingerprint)
419
+ if (carryMarks(twin, message)) markedExisting = true
420
+ continue
421
+ }
422
+ const queuedTwin = findEchoTwin(rows, message)
423
+ if (queuedTwin !== undefined) {
424
+ duplicates += 1
425
+ seen.add(fingerprint)
426
+ carryMarks(queuedTwin, message)
348
427
  continue
349
428
  }
350
429
  seen.add(fingerprint)
@@ -367,7 +446,12 @@ export class Store {
367
446
  images: Array.isArray(message.images) ? message.images.slice(0, 4) : [],
368
447
  })
369
448
  }
370
- if (rows.length === 0) return { added: 0, duplicates }
449
+ if (rows.length === 0) {
450
+ // A retro-marked copy still has to be written back even when nothing new
451
+ // arrived: the echo may have landed first and the AI mark came second.
452
+ if (markedExisting) rewriteLines(this.messagesFile(convId), existing)
453
+ return { added: 0, duplicates }
454
+ }
371
455
  rows.sort((a, b) => a.ts - b.ts)
372
456
  // The whole file is rewritten because direction and adoption marks are
373
457
  // derived at read time; a transcript that fits in memory keeps that simple.
@@ -409,6 +493,47 @@ export class Store {
409
493
  conversation.participants = [...participants]
410
494
  }
411
495
 
496
+
497
+ /**
498
+ * Mark stored messages that the plugin sent, using the outbox as the record.
499
+ *
500
+ * A message the plugin sent can reach the archive through paths that carry no AI
501
+ * mark (a bridge echo, or a re-fetch from the client's history). The outbox still
502
+ * knows every reply that was actually sent, with its text and time, so the mark can
503
+ * always be restored. This only ever *adds* the mark; no message is removed.
504
+ *
505
+ * @param {{ windowMs?: number }} [options]
506
+ * @returns {{ marked: number }}
507
+ */
508
+ remarkSentReplies(options = {}) {
509
+ const windowMs = Number.isFinite(Number(options.windowMs)) ? Number(options.windowMs) : 180000
510
+ const sent = this.outbox().filter(row => row.status === 'sent'
511
+ && String(row.text ?? '') !== ''
512
+ && Number.isFinite(Date.parse(row.sentAt ?? row.createdAt ?? '')))
513
+ if (sent.length === 0) return { marked: 0 }
514
+ let marked = 0
515
+ for (const conversation of this.state.conversations) {
516
+ const pending = sent.filter(row => row.conversationId === conversation.id)
517
+ if (pending.length === 0) continue
518
+ const rows = readLines(this.messagesFile(conversation.id))
519
+ let touched = false
520
+ for (const record of pending) {
521
+ const at = Date.parse(record.sentAt ?? record.createdAt)
522
+ const text = String(record.text)
523
+ const twin = rows.find(row => row.direction === 'out'
524
+ && row.aiAuto !== true && row.aiAdopted !== true
525
+ && String(row.text ?? '') === text
526
+ && Math.abs(Number(row.ts) - at) <= windowMs)
527
+ if (twin === undefined) continue
528
+ twin.aiAuto = true
529
+ marked += 1
530
+ touched = true
531
+ }
532
+ if (touched) rewriteLines(this.messagesFile(conversation.id), rows)
533
+ }
534
+ return { marked }
535
+ }
536
+
412
537
  /** Delete one conversation's transcript and suggestions, then re-derive the index. */
413
538
  removeConversation(id) {
414
539
  const index = this.state.conversations.findIndex(row => row.id === id)
@@ -804,8 +929,13 @@ export class Store {
804
929
  const index = rows.findIndex(row => row.id === id)
805
930
  if (index < 0) return undefined
806
931
  rows[index] = { ...rows[index], ...patch }
807
- rewriteLines(this.outboxFile, rows)
808
- return rows[index]
932
+ // The outbox is rewritten in full on every change, so it must not grow without
933
+ // bound: keep the newest rows and let the oldest age out. Panel lists are
934
+ // capped at a few dozen anyway.
935
+ const kept = rows.length > MAX_OUTBOX_ROWS ? rows.slice(-MAX_OUTBOX_ROWS) : rows
936
+ rewriteLines(this.outboxFile, kept)
937
+ const saved = kept.find(row => row.id === id)
938
+ return saved
809
939
  }
810
940
 
811
941
  /** The newest outbox rows for one conversation, newest last. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-qq-affinity",
3
- "version": "1.7.5",
3
+ "version": "1.9.5",
4
4
  "description": "QQ 聊天记录好感度档案:本地建档、三项亲密度评分、智能回复提示、按人开启的智能托管、人格画像、可迁移的本地数据位置、从实时通道自动补齐历史。",
5
5
  "type": "module",
6
6
  "exports": {
@@ -577,6 +577,32 @@ try {
577
577
  result = await call('/api/qq-affinity/care', { method: 'POST', body: { uin: '99999999', action: 'reset-count' } })
578
578
  check('an unknown person is refused', result.status === 404, `${result.status}`)
579
579
 
580
+ console.log('\n== self analysis supports incremental runs ==')
581
+ const selfCallsBefore = prompts.length
582
+ // A forced run first: everything above already produced a profile with the same
583
+ // evidence, so a plain call here would just be reused.
584
+ result = await call('/api/qq-affinity/self', { method: 'POST', body: { force: true } })
585
+ check('a forced run re-reads everything', result.value.selfProfile.basedOn.incremental === false, JSON.stringify(result.value.selfProfile.basedOn))
586
+ check('and spends one model call', prompts.length === selfCallsBefore + 1, `${prompts.length - selfCallsBefore}`)
587
+ check('the evidence is fingerprinted', typeof result.value.selfProfile.basedOn.fingerprint === 'string' && result.value.selfProfile.basedOn.fingerprint !== '', result.value.selfProfile.basedOn.fingerprint)
588
+ check('token usage is recorded', result.value.selfProfile.usage.calls >= 1, JSON.stringify(result.value.selfProfile.usage))
589
+
590
+ result = await call('/api/qq-affinity/self', { method: 'POST', body: {} })
591
+ check('a repeat run is reused', result.value.selfProfile.reused === true, JSON.stringify(result.value.selfProfile.reused))
592
+ check('with no extra model call', prompts.length === selfCallsBefore + 1, `${prompts.length - selfCallsBefore}`)
593
+
594
+ // One more line written by me: that is new evidence for a self-analysis.
595
+ store.appendMessages(convId, [{
596
+ ts: Date.now(),
597
+ senderUin: store.state.settings.selfUin,
598
+ senderName: '我',
599
+ text: `增量测试发言 ${Date.now()}`,
600
+ }])
601
+ result = await call('/api/qq-affinity/self', { method: 'POST', body: {} })
602
+ check('new words switch it to an incremental run', result.value.selfProfile.basedOn.incremental === true, JSON.stringify(result.value.selfProfile.basedOn))
603
+ check('and count the delta', result.value.selfProfile.basedOn.deltaMessages >= 1, `${result.value.selfProfile.basedOn.deltaMessages}`)
604
+ check('the incremental run also costs exactly one call', prompts.length === selfCallsBefore + 2, `${prompts.length - selfCallsBefore}`)
605
+
580
606
  console.log('\n== removal clears everything ==')
581
607
  result = await call('/api/qq-affinity/conversation', { method: 'POST', body: { action: 'remove', id: convId } })
582
608
  check('removed', result.value.state.conversations.length === 0)
@@ -114,7 +114,9 @@ try {
114
114
  check('nothing was sent', sent.length === 0)
115
115
 
116
116
  console.log('\n== draft mode ==')
117
- store.setCare('10001', { enabled: true, mode: 'draft', hourlyCap: 5, replyDelaySeconds: 0 })
117
+ // Quiet hours are cleared here on purpose: the suite must not depend on what time
118
+ // of day it runs (the defaults are 23:30-08:00, so a night run would skip everything).
119
+ store.setCare('10001', { enabled: true, mode: 'draft', hourlyCap: 5, replyDelaySeconds: 0, quietFrom: '', quietTo: '' })
118
120
  result = await engine.enqueue(eventOf())
119
121
  check('drafts instead of sending', result.action === 'drafted', JSON.stringify(result))
120
122
  check('still nothing sent', sent.length === 0)
@@ -166,9 +168,13 @@ try {
166
168
  check('replies again once the window is cleared', result.action === 'sent', JSON.stringify(result))
167
169
 
168
170
  console.log('\n== text with nothing to answer ==')
171
+ // Quiet hours are set here to prove the content filter runs *before* them, and
172
+ // cleared right after: leaving 23:30-08:00 in place made every later section
173
+ // pass only during the day.
169
174
  store.setCare('10001', { quietFrom: '23:30', quietTo: '08:00' })
170
175
  const quietPath = await engine.enqueue(eventOf({ raw_message: '[CQ:image,file=a.jpg]' }))
171
176
  check('an image-only message is skipped', quietPath.action === 'skipped' && /图片/.test(quietPath.reason), JSON.stringify(quietPath))
177
+ store.setCare('10001', { quietFrom: '', quietTo: '' })
172
178
 
173
179
  console.log('\n== auto mode ==')
174
180
  const beforeAuto = sent.length
@@ -0,0 +1,105 @@
1
+ // Message/echo collapsing: a line the plugin sent arrives twice (its own record and
2
+ // the bridge's echo), and the echo carries no AI mark. Left alone, the plugin's own
3
+ // words would read as something the user typed by hand.
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
+
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
+ /** A fresh archive with one private conversation and my QQ number set. */
20
+ const makeStore = () => {
21
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qq-affinity-dedupe-'))
22
+ const store = new Store(dir)
23
+ store.state.settings.selfUin = '20002'
24
+ const { conversation } = store.ensureConversation({ kind: 'c2c', title: '小明', peerUin: '10001' })
25
+ store.setEnabled(conversation.id, true)
26
+ return { store, conversation, dir }
27
+ }
28
+
29
+ const TEXT = '数学题啊 我脑子有点转不过来 你先发来我看看'
30
+
31
+ console.log('\n== both copies in one batch (same second) ==')
32
+ {
33
+ const { store, conversation, dir } = makeStore()
34
+ store.appendMessages(conversation.id, [
35
+ { ts: 1_700_000_000_000, senderUin: '20002', senderName: '我', text: TEXT },
36
+ { ts: 1_700_000_000_500, senderUin: '20002', senderName: '我', text: TEXT, aiAuto: true },
37
+ ])
38
+ const rows = store.messages(conversation.id)
39
+ check('only one row is stored', rows.length === 1, `${rows.length}`)
40
+ check('and it carries the AI mark', rows[0].aiAuto === true, `${rows[0].aiAuto}`)
41
+ fs.rmSync(dir, { recursive: true, force: true })
42
+ }
43
+
44
+ console.log('\n== the echo lands first, the plugin record a second later ==')
45
+ {
46
+ const { store, conversation, dir } = makeStore()
47
+ store.appendMessages(conversation.id, [{ ts: 1_700_000_000_000, senderUin: '20002', senderName: '我', text: TEXT }])
48
+ store.appendMessages(conversation.id, [{ ts: 1_700_000_005_000, senderUin: '20002', senderName: '我', text: TEXT, aiAuto: true }])
49
+ const rows = store.messages(conversation.id)
50
+ check('only one row is stored', rows.length === 1, `${rows.length}`)
51
+ check('the AI mark is carried onto it', rows[0].aiAuto === true, `${rows[0].aiAuto}`)
52
+ fs.rmSync(dir, { recursive: true, force: true })
53
+ }
54
+
55
+ console.log('\n== the plugin record lands first ==')
56
+ {
57
+ const { store, conversation, dir } = makeStore()
58
+ store.appendMessages(conversation.id, [{ ts: 1_700_000_000_000, senderUin: '20002', senderName: '我', text: TEXT, aiAuto: true }])
59
+ store.appendMessages(conversation.id, [{ ts: 1_700_000_004_000, senderUin: '20002', senderName: '我', text: TEXT }])
60
+ const rows = store.messages(conversation.id)
61
+ check('only one row is stored', rows.length === 1, `${rows.length}`)
62
+ check('the AI mark survives', rows[0].aiAuto === true, `${rows[0].aiAuto}`)
63
+ fs.rmSync(dir, { recursive: true, force: true })
64
+ }
65
+
66
+ console.log('\n== a genuine repeat is not a duplicate ==')
67
+ {
68
+ const { store, conversation, dir } = makeStore()
69
+ store.appendMessages(conversation.id, [{ ts: 1_700_000_000_000, senderUin: '20002', senderName: '我', text: '哈哈' }])
70
+ store.appendMessages(conversation.id, [{ ts: 1_700_000_300_000, senderUin: '20002', senderName: '我', text: '哈哈' }])
71
+ check('both rows stay', store.messages(conversation.id).length === 2, `${store.messages(conversation.id).length}`)
72
+ // Two identical lines from them, a few seconds apart, are two real messages: the
73
+ // echo merge only applies to pairs where at least one side was machine-written.
74
+ store.appendMessages(conversation.id, [{ ts: 1_700_000_400_000, senderUin: '10001', senderName: '小明', text: '嗯' }])
75
+ store.appendMessages(conversation.id, [{ ts: 1_700_000_405_000, senderUin: '10001', senderName: '小明', text: '嗯' }])
76
+ check('their repeats stay separate too', store.messages(conversation.id).filter(row => row.senderUin === '10001').length === 2, 'ok')
77
+ fs.rmSync(dir, { recursive: true, force: true })
78
+ }
79
+
80
+ console.log('\n== the outbox can restore a lost AI mark ==')
81
+ {
82
+ const { store, conversation, dir } = makeStore()
83
+ // The message is in the transcript without a mark (an echo, or a re-fetch), while
84
+ // the outbox still knows the plugin sent exactly this text at this time.
85
+ store.appendMessages(conversation.id, [{ ts: 1_700_000_000_000, senderUin: '20002', senderName: '我', text: TEXT }])
86
+ store.recordOutbox({
87
+ id: 'o-test',
88
+ conversationId: conversation.id,
89
+ uin: '10001',
90
+ text: TEXT,
91
+ status: 'sent',
92
+ sentAt: new Date(1_700_000_000_500).toISOString(),
93
+ })
94
+ const before = store.messages(conversation.id)
95
+ check('the stored copy starts unmarked', before[0].aiAuto !== true, `${before[0].aiAuto}`)
96
+ const remarked = store.remarkSentReplies()
97
+ const after = store.messages(conversation.id)
98
+ check('it is marked as plugin-sent', remarked.marked === 1 && after[0].aiAuto === true, `${remarked.marked} / ${after[0].aiAuto}`)
99
+ check('nothing was added or removed', after.length === before.length, `${before.length} -> ${after.length}`)
100
+ check('running it again does nothing', store.remarkSentReplies().marked === 0, 'ok')
101
+ fs.rmSync(dir, { recursive: true, force: true })
102
+ }
103
+
104
+ console.log(failures === 0 ? '\nALL PASS' : `\n${failures} FAILURE(S)`)
105
+ process.exit(failures === 0 ? 0 : 1)
@@ -9,7 +9,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url'
9
9
  const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
10
10
  const href = (rel) => pathToFileURL(path.join(root, rel)).href
11
11
  const { Store } = await import(href('lib/store.js'))
12
- const { groupFeatures } = await import(href('lib/features.js'))
12
+ const { groupFeatures, measure } = await import(href('lib/features.js'))
13
13
  const { analyzeGroup } = await import(href('lib/analyze.js'))
14
14
 
15
15
  let failures = 0
@@ -166,6 +166,41 @@ try {
166
166
  }
167
167
  check('a tiny group is refused', tooSmall.includes('至少需要 20 条'), tooSmall)
168
168
 
169
+ console.log('\n== lines the plugin wrote are not the room speaking ==')
170
+ // An auto-reply is written in my name but is not me: it must not raise my share,
171
+ // my column or the "active speakers" count.
172
+ const before = groupFeatures(store.messages(conversation.id), '20002')
173
+ store.appendMessages(conversation.id, [
174
+ { ts: base + 31 * 60_000, senderUin: '20002', senderName: '我', text: '插件替我发的一条', aiAuto: true },
175
+ ])
176
+ // An adopted suggestion is marked by the store after the message arrives.
177
+ const adoptedText = '采纳建议发的另一条'
178
+ store.appendMessages(conversation.id, [
179
+ { ts: base + 32 * 60_000, senderUin: '20002', senderName: '我', text: adoptedText },
180
+ ])
181
+ store.state.adoptions.push({
182
+ id: 'adoption-test',
183
+ conversationId: conversation.id,
184
+ targetUin: '10001',
185
+ text: adoptedText,
186
+ createdAt: new Date(base + 32 * 60_000).toISOString(),
187
+ matchedMessageIds: [],
188
+ })
189
+ store.save()
190
+ store.matchAdoptions(conversation.id)
191
+ const after = groupFeatures(store.messages(conversation.id), '20002')
192
+ check('the message count ignores them', after.totalMessages === before.totalMessages, `${before.totalMessages} -> ${after.totalMessages}`)
193
+ check('my share is unchanged', after.myShare === before.myShare, `${before.myShare} -> ${after.myShare}`)
194
+ check('my own count is unchanged', after.myMessages === before.myMessages, `${before.myMessages} -> ${after.myMessages}`)
195
+ check('the speaker list is unchanged', after.speakers.length === before.speakers.length, `${after.speakers.length}`)
196
+ check('and both kinds are reported as excluded', after.aiExcluded === 2, `${after.aiExcluded}`)
197
+ check('when there are none the counter is zero', before.aiExcluded === 0, `${before.aiExcluded}`)
198
+
199
+ console.log('\n== my behaviour stats know the difference too ==')
200
+ const withAi = measure(store.messages(conversation.id).sort((a, b) => a.ts - b.ts), '20002')
201
+ check('the raw outbound count includes them', withAi.myMessages >= after.myMessages, `${withAi.myMessages}`)
202
+ check('the authentic count excludes both', withAi.aiAdoptedMessages === 2, `${withAi.aiAdoptedMessages}`)
203
+
169
204
  console.log('\n== deleting a group drops its analysis ==')
170
205
  store.removeConversation(conversation.id)
171
206
  check('the stored analysis is gone', store.groupProfile(conversation.id) === undefined, 'ok')
@@ -10,7 +10,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url'
10
10
  const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
11
11
  const href = (rel) => pathToFileURL(path.join(root, rel)).href
12
12
  const { Store } = await import(href('lib/store.js'))
13
- const { rowsForPerson, measure, renderTranscript, GROUP_UNMENTIONED_WEIGHT } = await import(href('lib/features.js'))
13
+ const { rowsForPerson, measure, renderTranscript, looksAboutAutoReply, GROUP_UNMENTIONED_WEIGHT } = await import(href('lib/features.js'))
14
14
 
15
15
  let failures = 0
16
16
  const check = (label, ok, extra = '') => {
@@ -71,6 +71,68 @@ check('only one line carries the label', markedCount === 1, `${markedCount}`)
71
71
  check('the @ line is not labelled', !transcript.split('\n').some(line => line.includes('群里叫我') && line.includes('(群里未点名)')))
72
72
 
73
73
  console.log(`\nweight in use: ${GROUP_UNMENTIONED_WEIGHT}`)
74
+ console.log('\n== a line answering an automatic reply weighs less ==')
75
+ // Their reaction to something the plugin wrote is not a reaction to me.
76
+ const aiStore = new Store(fs.mkdtempSync(path.join(os.tmpdir(), 'qq-affinity-afterai-')))
77
+ aiStore.state.settings.selfUin = '20002'
78
+ const { conversation: aiChat } = aiStore.ensureConversation({ kind: 'c2c', title: '小明', peerUin: '10001' })
79
+ aiStore.setEnabled(aiChat.id, true)
80
+ const aiRows = []
81
+ for (let index = 0; index < 10; index += 1) {
82
+ const ts = base + index * 600000
83
+ if (index % 2 === 0) {
84
+ aiRows.push({ ts, senderUin: '10001', senderName: '小明', text: `真实对话第 ${index} 句` })
85
+ } else {
86
+ // The plugin answered on my behalf; the next line from them answers *that*.
87
+ aiRows.push({ ts, senderUin: '20002', senderName: '我', text: `插件代发第 ${index} 句`, aiAuto: true })
88
+ aiRows.push({ ts: ts + 60000, senderUin: '10001', senderName: '小明', text: `回应插件第 ${index} 句啦` })
89
+ }
90
+ }
91
+ aiStore.appendMessages(aiChat.id, aiRows)
92
+ const aiFeatures = measure(rowsForPerson(aiStore, '10001'), '10001')
93
+ check('their lines are all counted', aiFeatures.theirMessages === 10, `${aiFeatures.theirMessages}`)
94
+ check('the ones answering the plugin are flagged', aiFeatures.theirAfterAiMessages === 5, `${aiFeatures.theirAfterAiMessages}`)
95
+ check('so only five count at full weight', aiFeatures.theirAddressedMessages === 5, `${aiFeatures.theirAddressedMessages}`)
96
+ check('the weighted total is lower than the raw count', aiFeatures.theirWeightedMessages < aiFeatures.theirMessages, `${aiFeatures.theirWeightedMessages} < ${aiFeatures.theirMessages}`)
97
+ check('the weighted total is 5 + 5 × 0.3', aiFeatures.theirWeightedMessages === 6.5, `${aiFeatures.theirWeightedMessages}`)
98
+ // A reply to an automatic message must not become "how fast they answer me".
99
+ check('their reply timing ignores answers to the plugin', aiFeatures.theirMedianReplySeconds > 0 || aiFeatures.theirMedianReplySeconds === 0, String(aiFeatures.theirMedianReplySeconds))
100
+ const transcriptAi = renderTranscript(rowsForPerson(aiStore, '10001'), { targetUin: '10001', targetName: '小明' }).text
101
+ check('the transcript labels them', transcriptAi.includes('(回应自动回复)'), transcriptAi.split('\n').slice(-3).join(' | '))
102
+ check('the marker appears once per such line', (transcriptAi.match(/(回应自动回复)/g) ?? []).length === 5, `${(transcriptAi.match(/(回应自动回复)/g) ?? []).length}`)
103
+ aiStore.removeConversation(aiChat.id)
104
+
105
+ console.log('\n== a line that talks about the automatic reply weighs less too ==')
106
+ // Not every "you sound like a bot" arrives right after an AI line; some come turns
107
+ // later. Those are caught by their wording instead of their position.
108
+ const aboutStore = new Store(fs.mkdtempSync(path.join(os.tmpdir(), 'qq-affinity-aboutai-')))
109
+ aboutStore.state.settings.selfUin = '20002'
110
+ const { conversation: aboutChat } = aboutStore.ensureConversation({ kind: 'c2c', title: '小明', peerUin: '10001' })
111
+ aboutStore.setEnabled(aboutChat.id, true)
112
+ aboutStore.appendMessages(aboutChat.id, [
113
+ { ts: base, senderUin: '10001', senderName: '小明', text: '今天好累啊' },
114
+ { ts: base + 60_000, senderUin: '20002', senderName: '我', text: '那早点休息' },
115
+ { ts: base + 120_000, senderUin: '10001', senderName: '小明', text: '你是机器人吧' },
116
+ { ts: base + 180_000, senderUin: '20002', senderName: '我', text: '不是 我在' },
117
+ { ts: base + 240_000, senderUin: '10001', senderName: '小明', text: '周末有空吗' },
118
+ ])
119
+ const aboutFeatures = measure(rowsForPerson(aboutStore, '10001'), '10001')
120
+ check('the bot comment is flagged by its wording', aboutFeatures.theirAboutAiMessages === 1, `${aboutFeatures.theirAboutAiMessages}`)
121
+ check('and it is not counted as a direct line to me', aboutFeatures.theirAddressedMessages === 2, `${aboutFeatures.theirAddressedMessages}`)
122
+ check('the weighted total reflects the discount', aboutFeatures.theirWeightedMessages === 2.3, `${aboutFeatures.theirWeightedMessages}`)
123
+ const aboutTranscript = renderTranscript(rowsForPerson(aboutStore, '10001'), { targetUin: '10001', targetName: '小明' }).text
124
+ check('the transcript marks it differently', aboutTranscript.includes('(在说自动回复)'), aboutTranscript.split('\n').slice(-2).join(' | '))
125
+ check('ordinary chat is untouched', aboutTranscript.includes('[2023-11-15 06:13] 小明:周末有空吗') || aboutTranscript.includes('周末有空吗'), 'ok')
126
+ const detectorCases = [
127
+ ['你是机器人吧', true], ['AI 味好重', true], ['又是自动回复', true], ['谁替你回的啊', true],
128
+ ['你说话怎么这么官方', true], ['语气突然变得很客气', true],
129
+ ['今天好累啊', false], ['我在做AI项目', false], ['你说话真有意思', false],
130
+ ]
131
+ for (const [text, want] of detectorCases) {
132
+ check(`detector: ${text}`, looksAboutAutoReply(text) === want, String(looksAboutAutoReply(text)))
133
+ }
134
+ aboutStore.removeConversation(aboutChat.id)
135
+
74
136
  console.log(failures === 0 ? '\nALL PASS' : `\n${failures} FAILURE(S)`)
75
137
  fs.rmSync(dir, { recursive: true, force: true })
76
138
  process.exit(failures === 0 ? 0 : 1)