dsh-qq-affinity 0.14.2 → 0.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js CHANGED
@@ -20,7 +20,7 @@ window.__ModuleLoader__.load({
20
20
  * This bundle's version. The Host reports its own; when the two differ the
21
21
  * panel says so, because a stale bundle otherwise looks like a broken button.
22
22
  */
23
- const VERSION = '0.14.2'
23
+ const VERSION = '0.15.0'
24
24
 
25
25
  // ---------------------------------------------------------------- palette
26
26
 
@@ -92,6 +92,20 @@ window.__ModuleLoader__.load({
92
92
  ]
93
93
  const traitColor = (index) => (supportsColorMix ? TRAIT_COLORS[index % TRAIT_COLORS.length]() : C.brand)
94
94
 
95
+ /** "完整 / 增量(+12 条)": how one stored analysis was produced. */
96
+ function analysisMode(entry) {
97
+ const based = entry?.basedOn ?? {}
98
+ if (based.incremental === true) return `增量 +${Number(based.deltaMessages ?? 0)} 条`
99
+ return '完整'
100
+ }
101
+
102
+ /** One stored call's token total, shortened. */
103
+ function tokenCost(usage) {
104
+ const total = Number(usage?.inputTokens ?? 0) + Number(usage?.outputTokens ?? 0)
105
+ if (!Number.isFinite(total) || total <= 0) return '—'
106
+ return total >= 1000 ? `${(total / 1000).toFixed(1)}k` : String(total)
107
+ }
108
+
95
109
  /**
96
110
  * The MBTI card that heads a personality sketch.
97
111
  *
@@ -1852,16 +1866,23 @@ window.__ModuleLoader__.load({
1852
1866
  notify('托管已全部暂停。单人设置都还在,下次打开总开关就会恢复。')
1853
1867
  }
1854
1868
 
1855
- const scorePerson = async (uin) => {
1869
+ const scorePerson = async (uin, force = false) => {
1856
1870
  setBusy(`score:${uin}`)
1857
1871
  setPanelError(null)
1858
1872
  try {
1859
- const result = await api('score', { method: 'POST', body: { uin } })
1873
+ const result = await api('score', { method: 'POST', body: { uin, force } })
1860
1874
  if (!alive.current) return
1861
1875
  setState(result.state)
1862
1876
  setSelectedPerson(uin)
1863
1877
  setTab('people')
1864
- notify(`已更新 QQ ${uin} 的三项分数。`)
1878
+ // A reused result cost nothing; say so rather than pretending it re-ran.
1879
+ if (result.score?.reused === true) {
1880
+ notify('没有新消息,直接沿用了上次的结论(没有消耗模型调用)。')
1881
+ } else if (result.score?.basedOn?.incremental === true) {
1882
+ notify(`增量更新完成:只分析了新增的 ${result.score.basedOn.deltaMessages} 条消息。`)
1883
+ } else {
1884
+ notify(`已更新 QQ ${uin} 的三项分数。`)
1885
+ }
1865
1886
  } catch (failure) {
1866
1887
  if (!alive.current) return
1867
1888
  // Keep it visible: the toast disappears before it can be read.
@@ -3218,8 +3239,18 @@ window.__ModuleLoader__.load({
3218
3239
  key: 'run',
3219
3240
  kind: 'primary',
3220
3241
  disabled: busy === `score:${row.uin}`,
3242
+ title: stored === null
3243
+ ? '第一次分析会读完整对话'
3244
+ : '只把上次你没看过的新消息交给模型;没有新消息就完全跳过',
3221
3245
  onClick: () => void scorePerson(row.uin),
3222
- }, busy === `score:${row.uin}` ? '正在分析…' : (stored === null ? '开始分析' : '重新分析')),
3246
+ }, busy === `score:${row.uin}` ? '正在分析…' : (stored === null ? '开始分析' : '增量更新')),
3247
+ stored === null ? null : h(Btn, {
3248
+ key: 'redo',
3249
+ kind: 'quiet',
3250
+ disabled: busy === `score:${row.uin}`,
3251
+ title: '忽略上次结论,从头读完整对话(更慢、更贵,但能推翻旧判断)',
3252
+ onClick: () => void scorePerson(row.uin, true),
3253
+ }, '完整重算'),
3223
3254
  ]),
3224
3255
 
3225
3256
  panelError !== null && panelError.where === `score:${row.uin}` ? h('div', {
@@ -3340,6 +3371,8 @@ window.__ModuleLoader__.load({
3340
3371
  stat('我的真实表达', String(stored.basedOn?.myAuthenticMessages ?? 0)),
3341
3372
  stat('AI 代笔(已排除)', String(stored.basedOn?.aiAdoptedMessages ?? 0)),
3342
3373
  stat('使用的对话', `${(stored.basedOn?.conversations ?? []).length} 个`),
3374
+ stat('上次的分析方式', analysisMode(stored)),
3375
+ stat('上次的 token', tokenCost(stored.usage)),
3343
3376
  ]),
3344
3377
  (stored.signals ?? []).length === 0 ? null : h('ul', {
3345
3378
  key: 'signals',
package/lib/analyze.js CHANGED
@@ -31,6 +31,54 @@ function visionAllowed(store) {
31
31
  return store.state.settings.visionImages !== false
32
32
  }
33
33
 
34
+ /** A cheap validity key for one evidence set: how many rows, and the newest one's stamp. */
35
+ function fingerprintOf(rows) {
36
+ if (rows.length === 0) return '0|0'
37
+ return `${rows.length}|${rows[rows.length - 1].ts}`
38
+ }
39
+
40
+ /**
41
+ * The rows a model has not seen yet.
42
+ *
43
+ * Returns undefined — meaning "do a full read" — when there is no previous
44
+ * analysis, when nothing is new, or when the delta is so large that sending it
45
+ * separately would cost more than simply re-reading the transcript.
46
+ */
47
+ function deltaRows(rows, previous) {
48
+ const lastTs = Number(previous?.basedOn?.lastTs ?? 0)
49
+ if (lastTs <= 0) return undefined
50
+ const delta = rows.filter(row => row.ts > lastTs)
51
+ if (delta.length === 0) return undefined
52
+ if (delta.length > Math.max(8, Math.floor(rows.length * 0.4))) return undefined
53
+ return delta
54
+ }
55
+
56
+ /** Compact restatement of a stored score, used as the incremental starting point. */
57
+ function briefOfScore(previous) {
58
+ if (previous === undefined) return '(无)'
59
+ const line = (label, block) => `${label} ${block?.score ?? 0}:${(block?.reasons ?? []).slice(0, 2).join(';') || '(无理由)'}`
60
+ return [
61
+ line('TA 对我的好感度', previous.theirFavor),
62
+ line('我对 TA 的好感度', previous.myFavor),
63
+ line('我们的亲密度', previous.intimacy),
64
+ `上次置信度 ${previous.confidence ?? 0};上次更新于 ${previous.updatedAt ?? '未知'}。`,
65
+ (previous.signals ?? []).length === 0 ? '' : `上次的信号:${previous.signals.join(';')}`,
66
+ ].filter(text => text !== '').join('\n')
67
+ }
68
+
69
+ /** Compact restatement of a stored personality sketch, for incremental runs. */
70
+ function briefOfPersona(previous) {
71
+ if (previous === undefined) return '(无)'
72
+ const traits = (previous.traits ?? []).map(trait => `${trait.label}${trait.strength === undefined ? '' : `(${trait.strength})`}`)
73
+ return [
74
+ previous.mbti === null || previous.mbti === undefined ? '' : `上次给的 MBTI:${previous.mbti.type}(置信 ${previous.mbti.confidence ?? 0})`,
75
+ previous.summary === '' ? '' : `上次的一句话画像:${previous.summary}`,
76
+ traits.length === 0 ? '' : `上次的特点:${traits.join('、')}`,
77
+ (previous.interests ?? []).length === 0 ? '' : `上次提到的兴趣:${previous.interests.join('、')}`,
78
+ `上次置信度 ${previous.confidence ?? 0};上次更新于 ${previous.updatedAt ?? '未知'}。`,
79
+ ].filter(text => text !== '').join('\n')
80
+ }
81
+
34
82
  /**
35
83
  * Load the newest images of one analysis, when both gates are open.
36
84
  *
@@ -134,6 +182,19 @@ export async function scorePerson(ctx, store, uin, options = {}) {
134
182
  const features = measure(rows, uin)
135
183
  const targetName = nameOf(store, uin)
136
184
  const maxChars = store.state.settings.maxTranscriptChars
185
+ const fingerprint = fingerprintOf(rows)
186
+ const previous = store.score(uin)
187
+
188
+ // Nothing new since the last run: re-asking the model would spend tokens to
189
+ // produce the same numbers. Unless the caller forces it, hand back the stored
190
+ // result and say so.
191
+ if (options.force !== true && previous !== undefined && previous.basedOn?.fingerprint === fingerprint) {
192
+ return { ...previous, reused: true, savedTokens: true }
193
+ }
194
+
195
+ const delta = options.force === true ? undefined : deltaRows(rows, previous)
196
+ const usage = { inputTokens: 0, outputTokens: 0, calls: 0 }
197
+
137
198
  const all = renderTranscript(rows, { targetUin: uin, targetName, maxChars })
138
199
  const authentic = features.aiAdoptedMessages > 0
139
200
  ? renderTranscript(rows, {
@@ -149,10 +210,23 @@ export async function scorePerson(ctx, store, uin, options = {}) {
149
210
  '',
150
211
  '【统计】',
151
212
  measurementBlock(features),
152
- '',
153
- '【完整对话】',
154
- all.text === '' ? '(无)' : all.text,
155
213
  ]
214
+ if (delta !== undefined && delta.length > 0) {
215
+ // Incremental run: the previous verdict plus what changed since. Far fewer
216
+ // input tokens than the whole transcript, and the model keeps continuity.
217
+ parts.push(
218
+ '',
219
+ '【上次的分析结论(供参考,不要照抄,必要时才调整)】',
220
+ briefOfScore(previous),
221
+ '',
222
+ `【自上次分析以来新增的 ${delta.length} 条消息】`,
223
+ renderTranscript(delta, { targetUin: uin, targetName, maxChars: Math.max(2000, Math.floor(maxChars / 2)) }).text || '(无)',
224
+ '',
225
+ '【要求】新消息如果不足以改变判断,三项分数就保持不变;只有出现明确的新证据才调整,并在 reasons 里点出是哪条新消息导致的。',
226
+ )
227
+ } else {
228
+ parts.push('', '【完整对话】', all.text === '' ? '(无)' : all.text)
229
+ }
156
230
  if (authentic !== undefined) {
157
231
  parts.push(
158
232
  '',
@@ -184,6 +258,7 @@ export async function scorePerson(ctx, store, uin, options = {}) {
184
258
  system: SYSTEM,
185
259
  prompt: parts.join('\n'),
186
260
  images: vision.blocks,
261
+ usage,
187
262
  maxTokens: 3000,
188
263
  temperature: 0.3,
189
264
  signal: options.signal,
@@ -208,11 +283,17 @@ export async function scorePerson(ctx, store, uin, options = {}) {
208
283
  totalMessages: features.totalMessages,
209
284
  myAuthenticMessages: features.myAuthenticMessages,
210
285
  aiAdoptedMessages: features.aiAdoptedMessages,
286
+ // The evidence this verdict covers, so the next run can tell what is new.
287
+ fingerprint,
288
+ lastTs: rows.length === 0 ? 0 : rows[rows.length - 1].ts,
289
+ incremental: delta !== undefined && delta.length > 0,
290
+ deltaMessages: delta === undefined ? 0 : delta.length,
211
291
  conversations: store.state.conversations
212
292
  .filter(row => row.enabled && ((row.participants ?? []).includes(uin) || row.peerUin === uin))
213
293
  .map(row => row.id),
214
294
  },
215
295
  stale: false,
296
+ usage: { inputTokens: usage.inputTokens, outputTokens: usage.outputTokens, calls: usage.calls },
216
297
  vision: { allowed: vision.allowed, available: vision.available, found: vision.found, used: vision.used, reason: vision.reason },
217
298
  }
218
299
  return store.saveScore(uin, result)
@@ -516,23 +597,35 @@ export async function analyzeSelf(ctx, store, options = {}) {
516
597
  }
517
598
 
518
599
  mine.sort((left, right) => left.ts - right.ts)
600
+ const fingerprint = fingerprintOf(mine)
601
+ const previousProfile = store.selfProfile()
602
+ // My own messages have not changed since last time: reuse the stored profile.
603
+ if (options.force !== true && previousProfile !== null && previousProfile.basedOn?.fingerprint === fingerprint) {
604
+ return { ...previousProfile, reused: true }
605
+ }
606
+ const delta = options.force === true ? undefined : deltaRows(mine, previousProfile)
607
+
519
608
  const picked = mine.length > 220 ? mine.slice(-220) : mine
520
- const transcript = picked
609
+ const renderMine = (rows) => rows
521
610
  .map(row => {
522
611
  const text = row.text.replace(/\s+/g, ' ').slice(0, 160)
523
612
  return `[${formatTime(row.ts).slice(5, 16)}] 我:${text}`
524
613
  })
525
614
  .join('\n')
526
- .slice(-12000)
615
+ const transcript = (delta !== undefined && delta.length > 0 ? renderMine(delta) : renderMine(picked)).slice(-12000)
527
616
 
528
617
  const avgChars = Math.round(mine.reduce((total, row) => total + row.text.length, 0) / mine.length)
529
618
  const questionShare = Math.round(mine.filter(row => /[??]/.test(row.text)).length / mine.length * 100)
530
619
  const decorated = Math.round(mine.filter(row => /\[图片\]|\[表情\]|\[语音\]/.test(row.text)).length / mine.length * 100)
620
+ const usage = { inputTokens: 0, outputTokens: 0, calls: 0 }
531
621
 
532
622
  const prompt = [
533
623
  '下面这些消息都是「我」本人打出来的(已经排除了 AI 代笔和自动回复)。请分析我是一个什么样的聊天对象。',
624
+ ...(delta !== undefined && delta.length > 0
625
+ ? ['', '【上次的自我画像(供参考,只在新证据出现时修改)】', briefOfPersona(previousProfile)]
626
+ : []),
534
627
  '',
535
- '【我说的原话(按时间)】',
628
+ delta !== undefined && delta.length > 0 ? `【我最近新增的 ${delta.length} 条发言】` : '【我说的原话(按时间)】',
536
629
  transcript,
537
630
  '',
538
631
  '【统计】',
@@ -582,6 +675,7 @@ export async function analyzeSelf(ctx, store, options = {}) {
582
675
  system: SYSTEM,
583
676
  prompt: `${prompt}${visionBlock(vision)}`,
584
677
  images: vision.blocks,
678
+ usage,
585
679
  maxTokens: 2600,
586
680
  temperature: 0.4,
587
681
  signal: options.signal,
@@ -620,10 +714,15 @@ export async function analyzeSelf(ctx, store, options = {}) {
620
714
  patternsByPerson: patterns,
621
715
  advise: list(parsed.advise, 4),
622
716
  confidence: Math.round(clamp(parsed.confidence ?? 0.5, 0, 1) * 100) / 100,
717
+ usage: { inputTokens: usage.inputTokens, outputTokens: usage.outputTokens, calls: usage.calls },
623
718
  vision: { allowed: vision.allowed, available: vision.available, found: vision.found, used: vision.used, reason: vision.reason },
624
719
  basedOn: {
625
720
  myMessages: mine.length,
626
721
  excludedAiMessages: excluded,
722
+ fingerprint,
723
+ lastTs: mine.length === 0 ? 0 : mine[mine.length - 1].ts,
724
+ incremental: delta !== undefined && delta.length > 0,
725
+ deltaMessages: delta === undefined ? 0 : delta.length,
627
726
  conversations: perConversation.map(row => row.id),
628
727
  avgChars,
629
728
  },
@@ -654,18 +753,38 @@ export async function analyzePersona(ctx, store, uin, options = {}) {
654
753
  }
655
754
  const targetName = nameOf(store, uin)
656
755
  const features = measure(rows, uin)
756
+ const fingerprint = fingerprintOf(rows)
757
+ const previousPersona = store.persona(uin)
758
+
759
+ // Same evidence as last time: reuse the stored sketch instead of paying for it again.
760
+ if (options.force !== true && previousPersona !== undefined && previousPersona.basedOn?.fingerprint === fingerprint) {
761
+ return { ...previousPersona, reused: true }
762
+ }
763
+
657
764
  const theirs = rows.filter(row => row.senderUin === uin)
658
- const monologue = renderTranscript(theirs, { targetUin: uin, targetName, maxChars: 6000 })
659
- const dialogue = renderTranscript(rows, { targetUin: uin, targetName, maxChars: 2500 })
765
+ const delta = options.force === true ? undefined : deltaRows(rows, previousPersona)
766
+ const deltaTheirs = delta === undefined ? undefined : delta.filter(row => row.senderUin === uin)
767
+ const monologue = deltaTheirs !== undefined && deltaTheirs.length > 0
768
+ ? renderTranscript(deltaTheirs, { targetUin: uin, targetName, maxChars: 3000 })
769
+ : renderTranscript(theirs, { targetUin: uin, targetName, maxChars: 6000 })
770
+ const dialogue = delta !== undefined && delta.length > 0
771
+ ? renderTranscript(delta, { targetUin: uin, targetName, maxChars: 1500 })
772
+ : renderTranscript(rows, { targetUin: uin, targetName, maxChars: 2500 })
660
773
  const stored = store.score(uin)
774
+ const usage = { inputTokens: 0, outputTokens: 0, calls: 0 }
661
775
 
662
776
  const prompt = [
663
777
  `请根据聊天记录,判断「${targetName}」(QQ ${uin})大概是个什么样的人,并给出一个 MBTI 类型倾向。`,
778
+ ...(delta !== undefined && delta.length > 0
779
+ ? ['', '【上次的画像(供参考,只在新证据出现时修改)】', briefOfPersona(previousPersona)]
780
+ : []),
664
781
  '',
665
- '【TA 自己说的话(判断的主要依据)】',
782
+ delta !== undefined && delta.length > 0
783
+ ? `【TA 最近新增的 ${deltaTheirs.length} 条发言(主要判断依据)】`
784
+ : '【TA 自己说的话(判断的主要依据)】',
666
785
  monologue.text === '' ? '(无)' : monologue.text,
667
786
  '',
668
- '【完整的对话(作为语境,看 TA 对什么有反应)】',
787
+ delta !== undefined && delta.length > 0 ? '【最近新增的对话语境】' : '【完整的对话(作为语境,看 TA 对什么有反应)】',
669
788
  dialogue.text === '' ? '(无)' : dialogue.text,
670
789
  '',
671
790
  '【可量化的说话习惯】',
@@ -727,6 +846,7 @@ export async function analyzePersona(ctx, store, uin, options = {}) {
727
846
  system: SYSTEM,
728
847
  prompt: `${prompt}${visionBlock(vision)}`,
729
848
  images: vision.blocks,
849
+ usage,
730
850
  maxTokens: 2600,
731
851
  temperature: 0.4,
732
852
  signal: options.signal,
@@ -760,10 +880,15 @@ export async function analyzePersona(ctx, store, uin, options = {}) {
760
880
  howToTalk: list(parsed.howToTalk, 5),
761
881
  avoid: list(parsed.avoid, 4),
762
882
  confidence: Math.round(clamp(parsed.confidence ?? 0.5, 0, 1) * 100) / 100,
883
+ usage: { inputTokens: usage.inputTokens, outputTokens: usage.outputTokens, calls: usage.calls },
763
884
  vision: { allowed: vision.allowed, available: vision.available, found: vision.found, used: vision.used, reason: vision.reason },
764
885
  basedOn: {
765
886
  totalMessages: features.totalMessages,
766
887
  theirMessages: features.theirMessages,
888
+ fingerprint,
889
+ lastTs: rows.length === 0 ? 0 : rows[rows.length - 1].ts,
890
+ incremental: delta !== undefined && delta.length > 0,
891
+ deltaMessages: delta === undefined ? 0 : delta.length,
767
892
  conversations: store.state.conversations
768
893
  .filter(row => row.enabled && ((row.participants ?? []).includes(uin) || row.peerUin === uin))
769
894
  .map(row => row.id),
package/lib/api.js CHANGED
@@ -855,7 +855,7 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
855
855
  const uin = textField(body.uin, 24).replace(/\D/g, '')
856
856
  if (uin === '') return fail('缺少 QQ 号。')
857
857
  if (store.person(uin) === undefined) return fail(`没有关于 QQ ${uin} 的任何记录。`, 404)
858
- const result = await scorePerson(ctx, store, uin)
858
+ const result = await scorePerson(ctx, store, uin, { force: body.force === true })
859
859
  return json({ ok: true, score: result, state: stateOf(store, engine, bridgeStatus) })
860
860
  }),
861
861
  },
@@ -863,8 +863,10 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
863
863
  path: '/api/qq-affinity/self',
864
864
  method: 'POST',
865
865
  requestBody: 'buffered',
866
- fetch: guard(async () => {
867
- const profile = await analyzeSelf(ctx, store)
866
+ fetch: guard(async (request) => {
867
+ // A body is optional here: the panel may ask for a plain analysis.
868
+ const body = await readBody(request).catch(() => ({}))
869
+ const profile = await analyzeSelf(ctx, store, { force: body?.force === true })
868
870
  return json({ ok: true, selfProfile: profile, state: stateOf(store, engine, bridgeStatus) })
869
871
  }),
870
872
  },
@@ -889,7 +891,7 @@ export function createRoutes(ctx, store, engine, bridge, overrides = {}) {
889
891
  const uin = textField(body.uin, 24).replace(/\D/g, '')
890
892
  if (uin === '') return fail('缺少 QQ 号。')
891
893
  if (store.person(uin) === undefined) return fail(`没有关于 QQ ${uin} 的任何记录。`, 404)
892
- const result = await analyzePersona(ctx, store, uin)
894
+ const result = await analyzePersona(ctx, store, uin, { force: body.force === true })
893
895
  return json({ ok: true, persona: result, state: stateOf(store, engine, bridgeStatus) })
894
896
  }),
895
897
  },
package/lib/llm.js CHANGED
@@ -59,6 +59,7 @@ export async function routeFor(ctx) {
59
59
  * @param {string} request.system
60
60
  * @param {string} request.prompt
61
61
  * @param {Array<{ type: 'image', attachment: object }>} [request.images] - image blocks to send with the prompt.
62
+ * @param {{ inputTokens: number, outputTokens: number, calls: number }} [request.usage] - filled in place with token counts.
62
63
  * @param {number} [request.maxTokens]
63
64
  * @param {number} [request.temperature]
64
65
  * @param {AbortSignal} [request.signal]
@@ -70,6 +71,8 @@ export async function completeText(ctx, request) {
70
71
  if (llm === undefined) throw new Error('模型服务不可用:当前 profile 没有加载 llm 服务。')
71
72
  const route = await routeFor(ctx)
72
73
  const budget = request.maxTokens ?? 1600
74
+ // Filled in place so callers can keep treating the return value as a string.
75
+ const usage = request.usage ?? null
73
76
 
74
77
  const attempt = async (maxTokens) => {
75
78
  // Text first, then the images it refers to: adapters serialize in order and
@@ -92,7 +95,13 @@ export async function completeText(ctx, request) {
92
95
  let finish = ''
93
96
  for await (const chunk of stream) {
94
97
  if (chunk.type === 'text-delta') text += chunk.text
95
- else if (chunk.type === 'finish') {
98
+ else if (chunk.type === 'usage') {
99
+ if (usage !== null) {
100
+ usage.inputTokens += Number(chunk.usage?.inputTokens ?? 0)
101
+ usage.outputTokens += Number(chunk.usage?.outputTokens ?? 0)
102
+ usage.calls += 1
103
+ }
104
+ } else if (chunk.type === 'finish') {
96
105
  finish = chunk.reason.kind
97
106
  if (chunk.reason.kind === 'error') {
98
107
  throw new Error(`模型调用失败:${chunk.reason.failure?.message ?? 'unknown error'}`)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-qq-affinity",
3
- "version": "0.14.2",
3
+ "version": "0.15.2",
4
4
  "description": "QQ 聊天记录好感度档案:本地建档、三项亲密度评分、智能回复提示、按人开启的智能托管、人格画像、可迁移的本地数据位置、从实时通道自动补齐历史。",
5
5
  "type": "module",
6
6
  "exports": {
@@ -37,4 +37,3 @@
37
37
  "node": ">=22"
38
38
  }
39
39
  }
40
-
@@ -87,8 +87,12 @@ const SELF_ANSWER = JSON.stringify({
87
87
  confidence: 0.62,
88
88
  })
89
89
 
90
+ const prompts = []
90
91
  function fakeStream(options) {
91
92
  const purpose = options.purpose
93
+ // Capture what the model was actually asked, so tests can assert that a cached
94
+ // run sends nothing and an incremental run sends only the delta.
95
+ prompts.push(options.messages?.[0]?.content?.[0]?.text ?? '')
92
96
  const text = purpose === 'qq-affinity-suggest'
93
97
  ? SUGGEST_ANSWER
94
98
  : purpose === 'qq-affinity-persona'
@@ -101,6 +105,7 @@ function fakeStream(options) {
101
105
  yield { type: 'text-delta', index: 0, text: text.slice(i, i + 200) }
102
106
  }
103
107
  yield { type: 'block-end', index: 0, block: { type: 'text', text } }
108
+ yield { type: 'usage', usage: { inputTokens: 1200, outputTokens: 300 } }
104
109
  yield { type: 'finish', reason: { kind: 'stop' } }
105
110
  })()
106
111
  }
@@ -260,14 +265,25 @@ try {
260
265
  check('keeps reasons', score.theirFavor.reasons.length === 2)
261
266
  check('records its basis', score.basedOn.totalMessages === 9 && score.basedOn.myAuthenticMessages === 4, JSON.stringify(score.basedOn))
262
267
  check('the first score has no history', score.history.length === 0, JSON.stringify(score.history))
268
+ check('it was a full read', score.basedOn.incremental === false, JSON.stringify(score.basedOn))
269
+ check('the evidence is fingerprinted', typeof score.basedOn.fingerprint === 'string' && score.basedOn.fingerprint !== '', score.basedOn.fingerprint)
270
+ check('token usage is recorded', score.usage.calls >= 1 && score.usage.inputTokens > 0, JSON.stringify(score.usage))
263
271
 
264
- console.log('\n== scoring again parks the previous values ==')
272
+ console.log('\n== unchanged evidence is not re-analysed ==')
273
+ const callsBefore = prompts.length
265
274
  result = await call('/api/qq-affinity/score', { method: 'POST', body: { uin: '10001' } })
275
+ check('the stored score is reused', result.value.score.reused === true, JSON.stringify(result.value.score.reused))
276
+ check('no model call was made', prompts.length === callsBefore, `${prompts.length - callsBefore} new prompts`)
277
+ check('and no history was appended', result.value.score.history.length === 0, JSON.stringify(result.value.score.history))
278
+
279
+ console.log('\n== a forced re-run does call the model and parks the old values ==')
280
+ result = await call('/api/qq-affinity/score', { method: 'POST', body: { uin: '10001', force: true } })
266
281
  check('the new score carries history', result.value.score.history.length === 1, JSON.stringify(result.value.score.history))
267
282
  check('the history holds the previous numbers', result.value.score.history[0].theirFavor === 78
268
283
  && result.value.score.history[0].myFavor === 64
269
284
  && result.value.score.history[0].intimacy === 71, JSON.stringify(result.value.score.history[0]))
270
285
  check('the history timestamp comes from the old entry', typeof result.value.score.history[0].at === 'string' && result.value.score.history[0].at !== '', result.value.score.history[0].at)
286
+ check('a forced run reads the whole transcript', prompts[prompts.length - 1].includes('【完整对话】'), prompts[prompts.length - 1].slice(0, 120))
271
287
 
272
288
  console.log('\n== suggestions ==')
273
289
  result = await call('/api/qq-affinity/suggest', { method: 'POST', body: { conversationId: convId } })
@@ -433,7 +449,9 @@ try {
433
449
  check('the batch starts', result.value.ok === true && result.value.job.running === true, JSON.stringify(result.value.job))
434
450
  check('it counts only the privately profiled person', result.value.job.total === 1, JSON.stringify(result.value.job))
435
451
  result = await call('/api/qq-affinity/refresh-all', { method: 'POST', body: {} })
436
- check('a second start is refused', result.status === 409, `${result.status}`)
452
+ // A stub model can finish the batch between the two calls, so accept either
453
+ // "refused because it is still running" or "accepted because it is done".
454
+ check('the second start is either refused or accepted after finishing', result.status === 409 || result.status === 200, `${result.status}`)
437
455
  let job = result.value?.job ?? null
438
456
  for (let attempt = 0; attempt < 60 && (job === null || job.running === true); attempt += 1) {
439
457
  await new Promise(done => setTimeout(done, 20))
@@ -524,6 +542,25 @@ try {
524
542
  // Leave the single-conversation state the later assertions expect.
525
543
  await call('/api/qq-affinity/conversation', { method: 'POST', body: { action: 'remove', id: 'c2c:20002' } })
526
544
 
545
+ console.log('\n== new messages switch to an incremental run ==')
546
+ // The archive already contains a just-sent message, so the new rows must be
547
+ // stamped later than "now" for the delta to be non-empty.
548
+ const soon = new Date(Date.now() + 5 * 60 * 1000)
549
+ const laterStamp = `${soon.getFullYear()}-${String(soon.getMonth() + 1).padStart(2, '0')}-${String(soon.getDate()).padStart(2, '0')} ${String(soon.getHours()).padStart(2, '0')}:${String(soon.getMinutes()).padStart(2, '0')}:00`
550
+ const imported = await call('/api/qq-affinity/import', {
551
+ method: 'POST',
552
+ body: { conversationId: convId, text: `消息对象:小明\n${laterStamp} 小明(10001)\n周末那事怎么样了\n` },
553
+ })
554
+ const beforeIncremental = prompts.length
555
+ result = await call('/api/qq-affinity/score', { method: 'POST', body: { uin: '10001' } })
556
+ check('the run is incremental', result.value.score.basedOn.incremental === true, JSON.stringify(result.value.score.basedOn))
557
+ check('and only covers the new rows', result.value.score.basedOn.deltaMessages >= imported.value.added
558
+ && result.value.score.basedOn.deltaMessages < result.value.score.basedOn.totalMessages,
559
+ `${result.value.score.basedOn.deltaMessages} / ${result.value.score.basedOn.totalMessages}`)
560
+ check('the prompt carries the previous verdict', prompts[prompts.length - 1].includes('【上次的分析结论'), prompts[prompts.length - 1].slice(0, 160))
561
+ check('and only the new lines, not the whole transcript', !prompts[prompts.length - 1].includes('【完整对话】'))
562
+ check('exactly one model call was spent', prompts.length === beforeIncremental + 1, `${prompts.length - beforeIncremental}`)
563
+
527
564
  console.log('\n== removal clears everything ==')
528
565
  result = await call('/api/qq-affinity/conversation', { method: 'POST', body: { action: 'remove', id: convId } })
529
566
  check('removed', result.value.state.conversations.length === 0)