dsh-qq-affinity 1.6.1 → 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 +272 -7
- package/index.js +13 -0
- package/lib/analyze.js +23 -7
- package/lib/features.js +118 -22
- package/lib/guard.js +2 -5
- package/lib/store.js +136 -6
- package/package.json +1 -1
- package/scripts/api-e2e.mjs +26 -0
- package/scripts/care-e2e.mjs +7 -1
- package/scripts/dedupe-e2e.mjs +105 -0
- package/scripts/group-e2e.mjs +45 -1
- package/scripts/guard-e2e.mjs +3 -1
- package/scripts/mention-e2e.mjs +63 -1
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.
|
|
23
|
+
const VERSION = '1.9.4'
|
|
24
24
|
|
|
25
25
|
// ---------------------------------------------------------------- palette
|
|
26
26
|
|
|
@@ -82,8 +82,7 @@ window.__ModuleLoader__.load({
|
|
|
82
82
|
: C.layer1)
|
|
83
83
|
|
|
84
84
|
/** Distinct accent per list position, so neighbouring traits never match. */
|
|
85
|
-
const TRAIT_COLORS = [
|
|
86
|
-
() => C.brand,
|
|
85
|
+
const TRAIT_COLORS = [ () => C.brand,
|
|
87
86
|
() => mix(C.brand, C.success, 45),
|
|
88
87
|
() => C.success,
|
|
89
88
|
() => mix(C.success, C.warn, 50),
|
|
@@ -92,6 +91,13 @@ window.__ModuleLoader__.load({
|
|
|
92
91
|
]
|
|
93
92
|
const traitColor = (index) => (supportsColorMix ? TRAIT_COLORS[index % TRAIT_COLORS.length]() : C.brand)
|
|
94
93
|
|
|
94
|
+
/**
|
|
95
|
+
* The contribution chart reuses the score palette on purpose: green for the
|
|
96
|
+
* people who carry the room, warm colours for the quiet end. Same bands as
|
|
97
|
+
* the favour meters, so the two charts read as one visual language.
|
|
98
|
+
*/
|
|
99
|
+
const contributionColor = (position) => tone(Math.round(Math.min(1, Math.max(0, position)) * 100))
|
|
100
|
+
|
|
95
101
|
/** "正在分析" 已经跑了多久: 12 秒 / 3 分 5 秒 / 1 小时 2 分. */
|
|
96
102
|
function formatElapsed(ms) {
|
|
97
103
|
const total = Math.max(0, Math.round(Number(ms) / 1000))
|
|
@@ -2153,14 +2159,18 @@ window.__ModuleLoader__.load({
|
|
|
2153
2159
|
}
|
|
2154
2160
|
}
|
|
2155
2161
|
|
|
2156
|
-
const analyzeSelfProfile = async () => {
|
|
2162
|
+
const analyzeSelfProfile = async (force = false) => {
|
|
2157
2163
|
setBusy('self')
|
|
2158
2164
|
setPanelError(null)
|
|
2159
2165
|
try {
|
|
2160
|
-
const result = await api('self', { method: 'POST' })
|
|
2166
|
+
const result = await api('self', { method: 'POST', body: { force } })
|
|
2161
2167
|
if (!alive.current) return
|
|
2162
2168
|
setState(result.state)
|
|
2163
|
-
|
|
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('自我分析已更新。')
|
|
2164
2174
|
} catch (failure) {
|
|
2165
2175
|
if (!alive.current) return
|
|
2166
2176
|
setPanelError({ where: 'self', message: failure.message })
|
|
@@ -3320,8 +3330,18 @@ window.__ModuleLoader__.load({
|
|
|
3320
3330
|
key: 'run',
|
|
3321
3331
|
kind: profile === null ? 'primary' : 'outline',
|
|
3322
3332
|
disabled: busy === 'self',
|
|
3333
|
+
title: profile === null
|
|
3334
|
+
? '第一次分析会读你全部真实发言'
|
|
3335
|
+
: '只把这之后新增的发言交给模型;没有新发言就直接跳过',
|
|
3323
3336
|
onClick: () => void analyzeSelfProfile(),
|
|
3324
|
-
}, 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
|
+
}, '完整重算'),
|
|
3325
3345
|
],
|
|
3326
3346
|
}, profile === null
|
|
3327
3347
|
? h('div', { style: { fontSize: 12, color: C.label2, lineHeight: 1.85 } },
|
|
@@ -3426,6 +3446,15 @@ window.__ModuleLoader__.load({
|
|
|
3426
3446
|
key: 'based',
|
|
3427
3447
|
style: { fontSize: 11, color: C.label2, lineHeight: 1.6 },
|
|
3428
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
|
+
]),
|
|
3429
3458
|
]))
|
|
3430
3459
|
|
|
3431
3460
|
return h('div', { style: { display: 'flex', flexDirection: 'column', gap: 12 } }, [errorBox, header])
|
|
@@ -3533,6 +3562,8 @@ window.__ModuleLoader__.load({
|
|
|
3533
3562
|
style: { margin: 0, paddingLeft: 18, fontSize: 11.5, color: C.label2, lineHeight: 1.8 },
|
|
3534
3563
|
}, (atmosphere.evidence ?? []).map((line, index) => h('li', { key: index }, line))),
|
|
3535
3564
|
|
|
3565
|
+
contributionChart(group),
|
|
3566
|
+
|
|
3536
3567
|
(group.coreMembers ?? []).length === 0 ? null : h('div', { key: 'core', style: { display: 'flex', flexDirection: 'column', gap: 5 } }, [
|
|
3537
3568
|
h('div', { key: 'h', style: { fontSize: 12, color: C.label2 } }, '谁在撑这个群'),
|
|
3538
3569
|
...group.coreMembers.map((member, index) => {
|
|
@@ -3585,6 +3616,239 @@ window.__ModuleLoader__.load({
|
|
|
3585
3616
|
])
|
|
3586
3617
|
}
|
|
3587
3618
|
|
|
3619
|
+
/**
|
|
3620
|
+
* Group contribution: the people who carry the room, with their avatar, and
|
|
3621
|
+
* a column chart underneath.
|
|
3622
|
+
*
|
|
3623
|
+
* The numbers come from the measured speakers, not from the model, so the
|
|
3624
|
+
* chart is exact. Avatars are QQ's public CDN by QQ number; when that image
|
|
3625
|
+
* cannot load (offline, or blocked), the circle falls back to an initial so
|
|
3626
|
+
* the row never collapses.
|
|
3627
|
+
*/
|
|
3628
|
+
function contributionChart(group) {
|
|
3629
|
+
const stats = group.stats ?? {}
|
|
3630
|
+
const speakers = (stats.speakers ?? []).filter(speaker => speaker.uin !== 'unknown')
|
|
3631
|
+
if (speakers.length === 0) return null
|
|
3632
|
+
const top = speakers.slice(0, 6)
|
|
3633
|
+
// Bar height ranks against the leader; colour spreads across the visible
|
|
3634
|
+
// range, so six near-equal shares still read as six different shades.
|
|
3635
|
+
const maxShare = Math.max(...top.map(speaker => speaker.share), 0.01)
|
|
3636
|
+
const minShare = Math.min(...top.map(speaker => speaker.share))
|
|
3637
|
+
const shareSpan = maxShare - minShare
|
|
3638
|
+
const positionOf = (speaker) => (shareSpan > 0.0001
|
|
3639
|
+
? (speaker.share - minShare) / shareSpan
|
|
3640
|
+
// Everyone identical: show them all at the strong end rather than
|
|
3641
|
+
// inventing differences that the numbers do not support.
|
|
3642
|
+
: 1)
|
|
3643
|
+
const selfUin = state.settings?.selfUin ?? ''
|
|
3644
|
+
const label = (speaker) => (speaker.name === '' ? `QQ ${speaker.uin}` : speaker.name)
|
|
3645
|
+
return h('div', { key: 'contribution', style: { display: 'flex', flexDirection: 'column', gap: 6 } }, [
|
|
3646
|
+
h('div', {
|
|
3647
|
+
key: 'h',
|
|
3648
|
+
style: { display: 'flex', alignItems: 'baseline', gap: 8, fontSize: 12, color: C.label2 },
|
|
3649
|
+
}, [
|
|
3650
|
+
h('span', { key: 't', style: { color: C.label, fontWeight: 600 } }, '群贡献'),
|
|
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,
|
|
3657
|
+
]),
|
|
3658
|
+
// Legend: the colour is the ranking, not decoration.
|
|
3659
|
+
h('div', {
|
|
3660
|
+
key: 'legend',
|
|
3661
|
+
style: { display: 'flex', alignItems: 'center', gap: 6, fontSize: 10.5, color: C.label2 },
|
|
3662
|
+
}, [
|
|
3663
|
+
h('span', { key: 'l' }, '贡献低'),
|
|
3664
|
+
h('div', {
|
|
3665
|
+
key: 'g',
|
|
3666
|
+
'aria-hidden': true,
|
|
3667
|
+
style: {
|
|
3668
|
+
flex: '0 0 92px',
|
|
3669
|
+
height: 5,
|
|
3670
|
+
borderRadius: 999,
|
|
3671
|
+
overflow: 'hidden',
|
|
3672
|
+
display: 'flex',
|
|
3673
|
+
},
|
|
3674
|
+
// Same band gradient the score legend uses, low → high.
|
|
3675
|
+
}, [...BANDS].reverse().map(([, color], index) => h('div', {
|
|
3676
|
+
key: index,
|
|
3677
|
+
style: { flex: 1, background: color() },
|
|
3678
|
+
}))),
|
|
3679
|
+
h('span', { key: 'r' }, '贡献高'),
|
|
3680
|
+
]),
|
|
3681
|
+
h('div', {
|
|
3682
|
+
key: 'chart',
|
|
3683
|
+
style: {
|
|
3684
|
+
display: 'grid',
|
|
3685
|
+
gridTemplateColumns: `repeat(${top.length}, minmax(0, 1fr))`,
|
|
3686
|
+
gap: 8,
|
|
3687
|
+
alignItems: 'end',
|
|
3688
|
+
padding: '10px 4px 2px',
|
|
3689
|
+
background: C.bg,
|
|
3690
|
+
border: `1px solid ${C.border1}`,
|
|
3691
|
+
borderRadius: 10,
|
|
3692
|
+
},
|
|
3693
|
+
}, top.map((speaker, index) => {
|
|
3694
|
+
const isMe = selfUin !== '' && speaker.uin === selfUin
|
|
3695
|
+
const height = Math.max(6, Math.round((speaker.share / maxShare) * 100))
|
|
3696
|
+
// Colour follows the score palette: the loudest of the six lands in the
|
|
3697
|
+
// green band, the quietest in the warm end.
|
|
3698
|
+
const position = positionOf(speaker)
|
|
3699
|
+
const color = contributionColor(position)
|
|
3700
|
+
const initial = (label(speaker).trim()[0] ?? '?').toUpperCase()
|
|
3701
|
+
return h('div', {
|
|
3702
|
+
key: speaker.uin,
|
|
3703
|
+
title: `${label(speaker)}:${speaker.messages} 条,占 ${Math.round(speaker.share * 100)}%,平均 ${speaker.avgChars} 字(色阶位置 ${Math.round(position * 100)}%)`,
|
|
3704
|
+
style: { display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, minWidth: 0 },
|
|
3705
|
+
}, [
|
|
3706
|
+
// The avatar sits in its own frame so the winner's crown is not
|
|
3707
|
+
// clipped by the circle's overflow:hidden.
|
|
3708
|
+
h('div', {
|
|
3709
|
+
key: 'avwrap',
|
|
3710
|
+
style: { position: 'relative', width: 34, height: 34, flex: '0 0 auto' },
|
|
3711
|
+
}, [
|
|
3712
|
+
h('div', {
|
|
3713
|
+
key: 'av',
|
|
3714
|
+
style: {
|
|
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,
|
|
3729
|
+
},
|
|
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,
|
|
3785
|
+
]),
|
|
3786
|
+
h('div', {
|
|
3787
|
+
key: 'n',
|
|
3788
|
+
style: {
|
|
3789
|
+
fontSize: 10.5,
|
|
3790
|
+
color: isMe ? C.warn : C.label2,
|
|
3791
|
+
maxWidth: '100%',
|
|
3792
|
+
overflow: 'hidden',
|
|
3793
|
+
textOverflow: 'ellipsis',
|
|
3794
|
+
whiteSpace: 'nowrap',
|
|
3795
|
+
},
|
|
3796
|
+
}, isMe ? '我' : label(speaker)),
|
|
3797
|
+
// The column itself: height is proportional to the share of speech.
|
|
3798
|
+
h('div', {
|
|
3799
|
+
key: 'bar',
|
|
3800
|
+
'aria-hidden': true,
|
|
3801
|
+
style: {
|
|
3802
|
+
width: '100%',
|
|
3803
|
+
height: 78,
|
|
3804
|
+
display: 'flex',
|
|
3805
|
+
alignItems: 'flex-end',
|
|
3806
|
+
justifyContent: 'center',
|
|
3807
|
+
},
|
|
3808
|
+
}, h('div', {
|
|
3809
|
+
style: {
|
|
3810
|
+
width: '62%',
|
|
3811
|
+
height: `${height}%`,
|
|
3812
|
+
minHeight: 4,
|
|
3813
|
+
background: color,
|
|
3814
|
+
borderRadius: '3px 3px 0 0',
|
|
3815
|
+
transition: 'height 240ms cubic-bezier(.2,.8,.2,1)',
|
|
3816
|
+
},
|
|
3817
|
+
})),
|
|
3818
|
+
h('div', {
|
|
3819
|
+
key: 'v',
|
|
3820
|
+
style: { fontSize: 10.5, color: C.label, fontVariantNumeric: 'tabular-nums' },
|
|
3821
|
+
}, `${Math.round(speaker.share * 100)}%`),
|
|
3822
|
+
h('div', {
|
|
3823
|
+
key: 'c',
|
|
3824
|
+
style: { fontSize: 10, color: C.label2, fontVariantNumeric: 'tabular-nums' },
|
|
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}`),
|
|
3843
|
+
])
|
|
3844
|
+
})),
|
|
3845
|
+
selfUin === '' || top.some(speaker => speaker.uin === selfUin)
|
|
3846
|
+
? null
|
|
3847
|
+
: h('div', { key: 'me', style: { fontSize: 10.5, color: C.label2 } },
|
|
3848
|
+
`我不在前 ${top.length} 名里,我的发言占 ${Math.round((stats.myShare ?? 0) * 100)}%。`),
|
|
3849
|
+
])
|
|
3850
|
+
}
|
|
3851
|
+
|
|
3588
3852
|
function personDetail(row) {
|
|
3589
3853
|
const stored = row.score
|
|
3590
3854
|
const persona = row.persona ?? null
|
|
@@ -3829,6 +4093,7 @@ window.__ModuleLoader__.load({
|
|
|
3829
4093
|
stat('参与计算消息', String(stored.basedOn?.totalMessages ?? 0)),
|
|
3830
4094
|
stat('我的真实表达', String(stored.basedOn?.myAuthenticMessages ?? 0)),
|
|
3831
4095
|
stat('AI 代笔(已排除)', String(stored.basedOn?.aiAdoptedMessages ?? 0)),
|
|
4096
|
+
stat('对自动回复的回应(降权)', String(stored.basedOn?.theirAfterAiMessages ?? 0)),
|
|
3832
4097
|
stat('使用的对话', `${(stored.basedOn?.conversations ?? []).length} 个`),
|
|
3833
4098
|
stat('上次的分析方式', analysisMode(stored)),
|
|
3834
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
|
-
|
|
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)
|
|
@@ -396,7 +409,7 @@ export async function writeAutoReply(ctx, store, request) {
|
|
|
396
409
|
'5. 不要问超过一个问题,不要连着寒暄,不要用「哈哈」「亲」这类套话开头。',
|
|
397
410
|
'6. 如果对方说的是坏消息、求助或情绪问题,先接住情绪,不要急着给建议。',
|
|
398
411
|
'7. 不要承诺时间、地点、金额这类具体事项 —— 这些需要我自己确认。',
|
|
399
|
-
'8.
|
|
412
|
+
'8. 只聊日常。如果对方要你解题、写代码、写论文、做表格这类正经活儿,不要真的去做,也不要说「我看看」——用一句日常的话推掉,例如「这个我可算不明白 你找找会的」「我脑子不够用 换个人问吧」。翻译和总结照常帮忙,那属于日常聊天。',
|
|
400
413
|
inCharacter ? '9. 保持人设,但不要写动作描写、不要用括号、不要说「(微笑)」这类旁白。' : '',
|
|
401
414
|
].filter(line => line !== '').join('\n')
|
|
402
415
|
|
|
@@ -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`
|
|
78
|
-
// is probably a
|
|
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
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
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
|
-
|
|
109
|
-
const
|
|
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 =
|
|
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 =
|
|
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 &&
|
|
197
|
+
if (starter && mineOut) myInitiatives += 1
|
|
128
198
|
if (previous === undefined || gap > SIX_HOURS) continue
|
|
129
|
-
if (
|
|
130
|
-
|
|
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 =
|
|
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
|
|
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
|
-
/**
|
|
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:
|
|
241
|
+
theirAvgChars: weightedMean(theirs, row => row.text.length),
|
|
160
242
|
myAvgChars: mean(mineAuthentic.map(row => row.text.length)),
|
|
161
|
-
theirQuestionRatio:
|
|
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:
|
|
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:
|
|
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
|
-
|
|
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/guard.js
CHANGED
|
@@ -26,7 +26,6 @@ const CODE_FENCE = /```|~~~/
|
|
|
26
26
|
const CODE_REQUEST = /(帮我|给我|替我|麻烦|帮忙|能否|能不能|可不可以|你).{0,8}(写|改|修|调|优化|检查|看).{0,12}(代码|程序|脚本|函数|正则|报错|bug|BUG|sql|SQL|接口|爬虫|算法|leetcode|LeetCode)|^(写|改|修|实现|优化).{0,12}(代码|程序|脚本|函数|爬虫|算法)/
|
|
27
27
|
const HOMEWORK = /(作业|考卷|考试题|习题|卷子|复习题|练习题)/
|
|
28
28
|
const HOMEWORK_ASK = /(怎么做|怎么解|答案是|答案|帮我做|解一下|算一下|写一下)/
|
|
29
|
-
const LONG_TEXT_TASK = /(翻译|总结|概括|润色|改写|缩写).{0,14}(这|下面|以下|一下|整篇|全文|文章|内容|这段)/
|
|
30
29
|
|
|
31
30
|
/**
|
|
32
31
|
* Whether one inbound message is asking for non-conversational work.
|
|
@@ -48,9 +47,8 @@ export function isNonChatRequest(text) {
|
|
|
48
47
|
if (HOMEWORK.test(trimmed) && (mathy || HOMEWORK_ASK.test(trimmed))) {
|
|
49
48
|
return { blocked: true, why: 'homework' }
|
|
50
49
|
}
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
}
|
|
50
|
+
// Translation and summarising are deliberately NOT refused: the user asked for
|
|
51
|
+
// them to go through, and the prompt cap keeps the cost bounded.
|
|
54
52
|
return { blocked: false, why: '' }
|
|
55
53
|
}
|
|
56
54
|
|
|
@@ -60,7 +58,6 @@ export function nonChatReason(why) {
|
|
|
60
58
|
code: '写代码/改代码',
|
|
61
59
|
math: '数学题/计算',
|
|
62
60
|
homework: '作业题',
|
|
63
|
-
'long-text': '长文翻译或总结',
|
|
64
61
|
}[why] ?? '非日常任务'
|
|
65
62
|
return `对方在要我做${label},托管不接这类请求(不是闲聊)。`
|
|
66
63
|
}
|
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
|
-
|
|
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)
|
|
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
|
-
|
|
808
|
-
|
|
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
package/scripts/api-e2e.mjs
CHANGED
|
@@ -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)
|
package/scripts/care-e2e.mjs
CHANGED
|
@@ -114,7 +114,9 @@ try {
|
|
|
114
114
|
check('nothing was sent', sent.length === 0)
|
|
115
115
|
|
|
116
116
|
console.log('\n== draft mode ==')
|
|
117
|
-
|
|
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)
|
package/scripts/group-e2e.mjs
CHANGED
|
@@ -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
|
|
@@ -120,6 +120,15 @@ check('the prompt names the group', prompts[0].includes('折腾群'), prompts[0]
|
|
|
120
120
|
check('the prompt carries the speaker table', prompts[0].includes('说话人分布'), prompts[0].slice(0, 200))
|
|
121
121
|
check('token usage is recorded', first.usage.inputTokens === 2400, JSON.stringify(first.usage))
|
|
122
122
|
check('the measured stats ride along', first.stats.activeSpeakers === 4 && first.stats.atMeMessages === 5, JSON.stringify(first.stats).slice(0, 120))
|
|
123
|
+
// The contribution chart draws straight from these fields: it needs a QQ number
|
|
124
|
+
// for the avatar, a name to label it, and the share to size the column.
|
|
125
|
+
const chartRow = first.stats.speakers[0]
|
|
126
|
+
check('speakers carry a uin for the avatar', typeof chartRow.uin === 'string' && /^\d+$/.test(chartRow.uin), chartRow.uin)
|
|
127
|
+
check('speakers carry a name', chartRow.name === '小明', chartRow.name)
|
|
128
|
+
check('speakers carry a message count', chartRow.messages === 9, `${chartRow.messages}`)
|
|
129
|
+
check('speakers carry a share between 0 and 1', chartRow.share > 0 && chartRow.share <= 1, `${chartRow.share}`)
|
|
130
|
+
check('speakers carry an average length', chartRow.avgChars > 0, `${chartRow.avgChars}`)
|
|
131
|
+
check('the list is longest-speaker first', first.stats.speakers.every((speaker, index, list) => index === 0 || list[index - 1].messages >= speaker.messages))
|
|
123
132
|
check('the verdict is stored on the conversation', store.groupProfile(conversation.id)?.summary === first.summary, 'ok')
|
|
124
133
|
check('the evidence is fingerprinted', typeof first.basedOn.fingerprint === 'string' && first.basedOn.fingerprint !== '', first.basedOn.fingerprint)
|
|
125
134
|
|
|
@@ -157,6 +166,41 @@ try {
|
|
|
157
166
|
}
|
|
158
167
|
check('a tiny group is refused', tooSmall.includes('至少需要 20 条'), tooSmall)
|
|
159
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
|
+
|
|
160
204
|
console.log('\n== deleting a group drops its analysis ==')
|
|
161
205
|
store.removeConversation(conversation.id)
|
|
162
206
|
check('the stored analysis is gone', store.groupProfile(conversation.id) === undefined, 'ok')
|
package/scripts/guard-e2e.mjs
CHANGED
|
@@ -36,6 +36,9 @@ const allowed = [
|
|
|
36
36
|
'这道菜怎么做',
|
|
37
37
|
'周末去看展吗',
|
|
38
38
|
'帮我翻译一下这段',
|
|
39
|
+
// Translation and summarising are allowed on purpose now, however long they are.
|
|
40
|
+
`帮我翻译一下这段好吗:${'这是一段需要翻译的英文文本。'.repeat(40)}`,
|
|
41
|
+
`总结一下这文章:${'内容内容内容内容内容。'.repeat(40)}`,
|
|
39
42
|
'```js\nconsole.log(1)\n```',
|
|
40
43
|
'',
|
|
41
44
|
'在吗',
|
|
@@ -49,7 +52,6 @@ console.log('\n== the recorded reason reads like a sentence ==')
|
|
|
49
52
|
check('math', nonChatReason('math').includes('数学题'), nonChatReason('math'))
|
|
50
53
|
check('code', nonChatReason('code').includes('代码'), nonChatReason('code'))
|
|
51
54
|
check('homework', nonChatReason('homework').includes('作业'), nonChatReason('homework'))
|
|
52
|
-
check('long text', nonChatReason('long-text').includes('长文'), nonChatReason('long-text'))
|
|
53
55
|
check('an unknown kind still reads fine', nonChatReason('mystery').includes('非日常'), nonChatReason('mystery'))
|
|
54
56
|
|
|
55
57
|
console.log(failures === 0 ? '\nALL PASS' : `\n${failures} FAILURE(S)`)
|
package/scripts/mention-e2e.mjs
CHANGED
|
@@ -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)
|