Files

151 lines
7.8 KiB
JavaScript
Raw Permalink Normal View History

// history 读回窗口的**上限定性**(纯只读,零副作用)。
//
// 起因:上一轮 get_friend_msg_history 传 count=60 实测只回 10 条。这个数字直接决定
// QLinker 的补拉策略:上限是 10 就要多次分页往返,是 100 则完全不同,不得凭猜测写进设计。
//
// 必须区分三种解释(对补拉策略含义不同):
// A) 接口有硬上限,超出部分被截断
// B) 该会话消息本就不足,返回的是全部
// C) count 参数被忽略(参数名/类型不对),返回的是默认值
// 区分方法:递增 count 多次请求看返回条数何时不再增长;再用 start_id/end_id 翻页,
// 验证翻页能否突破单次上限。
//
// 群与私聊分别测:不同接口,上限不保证一致,不得互相外推。
const WS_URL = process.env.NAPCAT_WS_URL || 'ws://192.168.5.32:16099';
const TOKEN = process.env.NAPCAT_WS_TOKEN;
const GROUP = Number(process.env.PROBE_GROUP || 933280401);
const FRIEND = Number(process.env.PROBE_FRIEND || 2161656029);
if (!TOKEN) { console.error('缺少环境变量 NAPCAT_WS_TOKEN。凭据不得硬编码。'); process.exit(1); }
const fs = await import('node:fs');
const path = await import('node:path');
const OUT_DIR = process.env.PROBE_OUT || 'local';
fs.mkdirSync(OUT_DIR, { recursive: true });
const OUT = path.join(OUT_DIR, `history-window-${new Date().toISOString().replace(/[:.]/g, '-')}.jsonl`);
const say = (...a) => console.log(...a);
const ws = new WebSocket(`${WS_URL.replace(/\/$/, '')}/?access_token=${encodeURIComponent(TOKEN)}`);
const pending = new Map();
let opened = false, authed = false;
ws.onopen = () => { opened = true; };
ws.onmessage = (ev) => {
let o; try { o = JSON.parse(String(ev.data)); } catch { return; }
if (o.echo && pending.has(o.echo)) { pending.get(o.echo).resolve(o); pending.delete(o.echo); return; }
if (o.post_type === 'meta_event' && o.meta_event_type === 'lifecycle') authed = true;
};
for (let i = 0; i < 100 && !opened; i++) await new Promise((r) => setTimeout(r, 100));
if (!opened) { console.error('连接超时'); process.exit(1); }
for (let i = 0; i < 100 && !authed; i++) await new Promise((r) => setTimeout(r, 100));
say('认证=' + authed);
if (!authed) { console.error('未收到 lifecycle,中止(GC-008:onopen 不代表认证成功)。'); process.exit(2); }
const api = (action, params, ms = 30000) => new Promise((resolve) => {
const echo = `hw-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
const to = setTimeout(() => { pending.delete(echo); resolve({ __timeout: true }); }, ms);
pending.set(echo, { resolve: (o) => { clearTimeout(to); resolve(o); }, to });
ws.send(JSON.stringify({ action, params, echo }));
});
const rec = (o) => { fs.appendFileSync(OUT, JSON.stringify(o) + '\n'); return o; };
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const COUNTS = [1, 5, 10, 20, 30, 50, 60, 80, 100, 200];
async function probe(action, base, label) {
say(`\n===== ${label} (${action}) =====`);
const rows = [];
for (const count of COUNTS) {
const r = await api(action, { ...base, count });
const msgs = r?.data?.messages ?? [];
const row = {
kind: 'result', id: `${label}:count=${count}`, action,
retcode: r.__timeout ? 'TIMEOUT' : r.retcode,
message: String(r.message ?? r.wording ?? ''),
count_param: count,
returned: msgs.length,
first_seq: msgs.length ? String(msgs[0].real_seq) : null,
last_seq: msgs.length ? String(msgs[msgs.length - 1].real_seq) : null,
has_more: r?.data?.has_more ?? null,
};
rows.push(rec(row));
say(` count=${String(count).padStart(3)} -> 返回 ${String(row.returned).padStart(3)} 条 seq ${row.first_seq ?? '-'}..${row.last_seq ?? '-'} ${row.message.slice(0, 40)}`);
await sleep(400);
}
const maxReturned = Math.max(...rows.map((r) => r.returned || 0));
const plateau = rows.filter((r) => r.returned === maxReturned).map((r) => r.count_param);
say(` 最大返回 ${maxReturned} 条,首次达到该值的 count=${plateau[0] ?? '-'}`);
return { rows, maxReturned };
}
const gBase = { group_id: GROUP };
const pBase = { user_id: FRIEND };
const g = await probe('get_group_msg_history', gBase, 'group');
const p = await probe('get_friend_msg_history', pBase, 'private');
say('\n===== 默认值(不传 count)=====');
for (const [action, base, label] of [
['get_group_msg_history', gBase, 'group'],
['get_friend_msg_history', pBase, 'private'],
]) {
const r = await api(action, base);
const n = (r?.data?.messages ?? []).length;
rec({ kind: 'result', id: `${label}:count=default`, action, retcode: r.retcode, returned: n, message: String(r.message ?? '') });
say(` ${label.padEnd(8)} 不传 count -> 返回 ${n} 条`);
}
// 翻页:history 的 real_seq 是 string(GC-010),同时验数字与字符串形式的边界参数
say('\n===== 翻页能力(决定补拉能否覆盖长历史)=====');
// ⚠️ 实测 messages 数组按 real_seq **升序**排列(count=10 → seq 1231..1240),
// 即 m[0] 是窗口内**最旧**、m[last] 是**最新**。取错端会把「最新消息 id」当边界传给
// 翻页参数,返回相同结果属正常,从而误判成「参数未生效」。边界必须取 m[0]。
async function pageProbe(action, base, label) {
const first = await api(action, { ...base, count: 40 });
const m1 = first?.data?.messages ?? [];
if (!m1.length) { say(` ${label}: 无数据,跳过`); return; }
const asc = Number(m1[0].real_seq) < Number(m1[m1.length - 1].real_seq);
say(` ${label}: 第 1 页 ${m1.length} 条,排列=${asc ? '升序(m[0]最旧)' : '降序(m[0]最新)'}`);
const oldest = asc ? m1[0] : m1[m1.length - 1];
const minMid = oldest.message_id;
const minSeq = oldest.real_seq;
say(` ${label}: 窗口内最旧 real_seq=${minSeq} message_id=${minMid}`);
for (const pk of ['start_id', 'end_id']) {
for (const [vform, v] of [['number', minMid], ['string', String(minMid)]]) {
const r = await api(action, { ...base, count: 40, [pk]: v });
const m = r?.data?.messages ?? [];
const gotOldest = m.length ? (asc ? m[0] : m[m.length - 1]) : null;
// 翻页生效的判据:返回窗口里出现了**比 minSeq 更旧**的消息
const pushedBack = m.length > 0 && gotOldest
&& Number(gotOldest.real_seq) < Number(minSeq);
const identical = m.length > 0 && String(m[0].real_seq) === String(m1[0].real_seq)
&& String(m[m.length - 1].real_seq) === String(m1[m1.length - 1].real_seq);
rec({
kind: 'result',
id: `${label}:page:${pk}:${vform}`,
action, retcode: r.retcode, returned: m.length,
first_seq: m.length ? String(m[0].real_seq) : null,
last_seq: m.length ? String(m[m.length - 1].real_seq) : null,
pushed_back: !!pushedBack, identical_to_page1: !!identical,
message: String(r.message ?? ''),
});
say(` ${pk}(${vform})=${v} -> ${m.length} 条 seq ${m.length ? m[0].real_seq + '..' + m[m.length - 1].real_seq : '-'}${pushedBack ? ' [OK] 翻到更旧' : (identical ? ' [!] 与第 1 页完全相同,参数未生效' : '')} ${String(r.message ?? '').slice(0, 40)}`);
}
}
}
await pageProbe('get_group_msg_history', gBase, 'group');
await pageProbe('get_friend_msg_history', pBase, 'private');
say('\n===== 定性 =====');
for (const [label, r] of [['group', g], ['private', p]]) {
const max = r.maxReturned;
const rets = r.rows.map((x) => x.returned);
const allSame = rets.every((n) => n === rets[0]);
say(` ${label}: 各 count 返回条数 = [${rets.join(',')}]`);
if (allSame)
say(` -> 返回条数不随 count 变化(恒为 ${max}):count 未生效,或该会话总数恰为 ${max}。需结合翻页结果区分。`);
else
say(` -> 返回条数随 count 增长,观测到单次上限约 ${max}。`);
}
say('\n结果 -> ' + OUT);
try { ws.close(); } catch {}
process.exit(0);