#!/usr/bin/env node /** * 诊断 agent-node-lj-test 的文件返回行为(只读 Matrix + 向容器提问) * * 目的:查清「一次返回 4~5 个文件,App 只显示 2 张卡 / 重复卡片 / 带出上一会话卡片」。 * * 设计要点(都是踩过的坑): * · 容器收到新消息会**中途改航向** —— 必须一轮一问、上一轮彻底安静(收到 ✅ 且 60s 无新事件)再发下一轮 * · 结束信号是容器对「本轮问题消息」打的 ✅ reaction(rel_event = 问题 event_id) * · 每轮用一个**新房间**,避免跨轮干扰;另附一轮「同房连续两次提问」用来查旧卡片串入 * * 用法: * node scripts/diag-ljtest-files.mjs --use-app-account # 用主账号(App 会漏一段同步) * node scripts/diag-ljtest-files.mjs # 用独立诊断账号(需 ~/.fmode/config/diag-mx.json) */ import { readFileSync, writeFileSync, mkdirSync } from 'node:fs'; import { homedir } from 'node:os'; import { join } from 'node:path'; const F = 'https://server.fmode.cn/api/functions'; const TARGET = 'agent-node-lj-test'; const OUT = 'docs/00-tracking/attachments'; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); const t = JSON.parse(readFileSync(join(homedir(), '.fmode/config', 'user.json'), 'utf8'))?.sessionToken; async function provision(id) { const r = await fetch(F, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: 'RP5Ht55NeX', token: t, params: { agentId: id } }), }); const j = await r.json(); const d = j.result ?? j; if (!d?.accessToken) throw new Error('provision 失败: ' + JSON.stringify(j).slice(0, 300)); return d; } const RUN_TAG = String(Date.now()).slice(-6); /** 容器以 hermes(uid 10000) 运行,/opt/data/tmp 属 root 不可写 —— 只能用 /opt/data 可写区 */ const D = `/opt/data/diag-${RUN_TAG}`; /** * 诊断专用 Matrix 账号(默认)。fmode.cn 已关自助注册,需人工写入 * ~/.fmode/config/diag-mx.json:{"homeserver","userId","accessToken"} */ async function diagAccount(hs) { try { const j = JSON.parse(readFileSync(join(homedir(), '.fmode', 'config', 'diag-mx.json'), 'utf8')); if (j.homeserver === hs && j.accessToken) return j; } catch { /* 没有 */ } return null; } const isProgress = (b) => /^[*·•\s]*(🐍|💻|🔎|📖|✍️|🧠|📝|⚙|🔧|✅|⏳)/.test(b.trim()) || /^[*·•\s]*(Writing|Reading|Running|terminal|write_file|read_file)/i.test(b.trim()); const isAckBody = (b) => b.includes('容器已标记完成'); function summarize(ev) { const c = ev.content ?? {}; const rel = c['m.relates_to'] ?? {}; const url = c.url ?? c.file?.url ?? ''; const out = { event_id: ev.event_id, type: ev.type, sender: ev.sender, msgtype: c.msgtype, fmodeKind: c['fmode.kind'] ?? null, body: String(c.body ?? '').slice(0, 200), url, info: c.info ?? null, rel_type: rel.rel_type ?? null, relates_to: rel.event_id ?? null, key: c.key ?? null, ts: ev.origin_server_ts, }; if (c.msgtype === 'm.text' || c.msgtype === 'm.file') { out.links = [...String(c.body ?? '').matchAll(/https?:\/\/[^\s)\]"'<>]+/g)].map((m) => m[0]).slice(0, 12); out.mediaLines = [...String(c.body ?? '').matchAll(/MEDIA:\s*(\S+)/g)].map((m) => m[1]); } return out; } const isAttachment = (e) => ['m.file', 'm.image', 'm.video', 'm.audio'].includes(e.msgtype); function reportRound(label, events) { const list = [...events.values()].sort((a, b) => a.ts - b.ts); const files = list.filter(isAttachment); const texts = list.filter((e) => e.msgtype === 'm.text' && !isProgress(e.body) && !isAckBody(e.body)); const replaces = list.filter((e) => e.rel_type === 'm.replace'); console.log(`\n===== ${label} =====`); console.log(` 事件 ${list.length} | 附件 ${files.length} | 正文 ${texts.length} | 编辑(${replaces.length})`); for (const f of files) console.log( ` 📎 ${f.msgtype} body="${f.body}" url=${String(f.url).replace(/^.*\//, '…/').slice(0, 70)} info=${JSON.stringify(f.info)} kind=${f.fmodeKind} rel=${f.rel_type ?? '-'}→${String(f.relates_to ?? '').slice(0, 25)}`, ); for (const x of texts) { const flag = /Couldn't deliver/i.test(x.body) ? ' ❌投递失败' : ''; console.log(` 💬${flag} ${x.body.slice(0, 90).replace(/\n/g, ' ')} | links=${x.links?.length ?? 0} | MEDIA行=${x.mediaLines?.length ?? 0}`); } const byUrl = new Map(); for (const f of files) byUrl.set(f.url, (byUrl.get(f.url) ?? 0) + 1); const dups = [...byUrl].filter(([, n]) => n > 1); if (dups.length) console.log(' ⚠️ 同一 URL 发了多次:', dups.map(([u, n]) => `${String(u).slice(-45)} ×${n}`).join(', ')); const byName = new Map(); for (const f of files) byName.set(f.body, (byName.get(f.body) ?? 0) + 1); const nameDups = [...byName].filter(([, n]) => n > 1); if (nameDups.length) console.log(' ⚠️ 同名附件多份:', nameDups.map(([n, c]) => `${n}×${c}`).join(', ')); const links = texts.flatMap((x) => x.links ?? []); const sameName = links.filter((u) => files.some((f) => u.includes(encodeURIComponent(f.body)) || u.includes(f.body))); if (sameName.length) console.log(` ⚠️ 正文链接与附件同名(可能构成双卡): ${sameName.length} 条`); if (links.length) console.log(` 🔗 正文里的百度盘链接 ${links.length} 条: ${links.slice(0, 6).map((u) => u.slice(-50)).join(' | ')}`); return { list, files, texts, summary: { total: list.length, files: files.length, texts: texts.length, urlDups: dups.length, nameDups: nameDups.length, sameNameLinks: sameName.length } }; } async function main() { const agent = await provision(TARGET); const mx = await import('matrix-js-sdk'); const hs = agent.homeserver.replace(/\/$/, ''); const useAppAccount = process.argv.includes('--use-app-account'); const diag = useAppAccount ? { userId: agent.userMxId, accessToken: agent.accessToken } : await diagAccount(hs); if (!diag) { throw new Error( `需要独立诊断账号(fmode.cn 已关注册)。写入 ${join(homedir(), '.fmode', 'config', 'diag-mx.json')}:` + `{"homeserver":"${hs}","userId":"@xxx:fmode.cn","accessToken":"syt_xxx"};或加 --use-app-account(App 会漏一段同步)。`, ); } console.log(`App 主账号 @${agent.userMxId} | 容器 @${agent.agentMxId} | 诊断账号 @${diag.userId}${useAppAccount ? ' ⚠️主账号' : ''}`); console.log(`容器目录前缀:${D}`); const c = mx.createClient({ baseUrl: hs, accessToken: diag.accessToken, userId: diag.userId }); const auth = { Authorization: `Bearer ${diag.accessToken}` }; let since = (await (await fetch(`${hs}/_matrix/client/v3/sync?timeout=0`, { headers: auth })).json()).next_batch; const report = { startedAt: new Date().toISOString(), user: agent.userMxId, agent: agent.agentMxId, dir: D, rounds: [] }; async function drain() { const r = await fetch(`${hs}/_matrix/client/v3/sync?timeout=0&since=${encodeURIComponent(since)}`, { headers: auth }); const j = await r.json(); since = j.next_batch ?? since; return j; } async function openRoom(tag) { const room = (await c.createRoom({ invite: [agent.agentMxId], name: `diag-${tag}-${Date.now()}`, preset: mx.Preset.TrustedPrivateChat })).room_id; console.log(`\n【房间 ${tag}】${room}`); await drain(); for (let i = 0; i < 30; i++) { await sleep(3000); const j = await (await fetch(`${hs}/_matrix/client/v3/rooms/${encodeURIComponent(room)}/joined_members`, { headers: auth })).json().catch(() => ({})); if ((j.joined ?? {})[agent.agentMxId]) { console.log(' 容器已进房'); await drain(); return room; } } console.log(' ⚠️ 容器 90s 未进房,仍然继续'); return room; } /** 在 room 里发一条问题,收集事件直到:对本问题的 ✅ + 60s 静默(或 8 分钟超时) */ async function ask(room, q, label) { const sent = await c.sendEvent(room, 'm.room.message', { msgtype: 'm.text', body: q, 'm.mentions': { user_ids: [agent.agentMxId] } }); console.log(`\n--- ${label}:已发问题 ${sent.event_id.slice(0, 30)}`); const events = new Map(); const deadline = Date.now() + 10 * 60_000; let acked = false; let lastSize = 0; let quietFrom = Date.now(); while (Date.now() < deadline) { await sleep(4000); const j = await drain(); const tl = j.rooms?.join?.[room]?.timeline?.events ?? []; for (const ev of tl) { const s = summarize(ev); if (s.event_id === sent.event_id) continue; if (!events.has(s.event_id)) events.set(s.event_id, s); /* * 🔴 结束信号判定(2026-11-17 实测): * 容器收到问题后会**立刻**打一个 reaction(不是 ✅ 的「收到」), * 真正的 ✅ 在收尾时才打。这里只认 key === '✅',且必须在 * **容器已经产出过内容之后**才算 —— 否则会被「收到」反应提前收尾。 */ const hasReply = [...events.values()].some((e) => e.type === 'm.room.message' && e.sender === agent.agentMxId); if (s.type === 'm.reaction' && s.relates_to === sent.event_id && String(s.key) === '✅' && hasReply) acked = true; } if (tl.length) console.log(` +${tl.length} 事件(累计 ${events.size})ack=${acked}`); if (events.size !== lastSize) { lastSize = events.size; quietFrom = Date.now(); } // ✅ 已到、且 60s 没有新事件 → 本轮结束 if (acked && Date.now() - quietFrom > 60_000) break; // 兜底:内容已出现且 3 分钟无新事件(容器没打 ✅)→ 收尾,避免空等 if (!acked && events.size > 0 && Date.now() - quietFrom > 180_000) { console.log(' · 3 分钟无新事件,按静默收尾'); break; } } if (!acked) console.log(' ⚠️ 10 分钟内未收到对本问题的 ✅(按静默收尾)'); const r = reportRound(label, events); report.rounds.push({ label, room, question: q, rootId: sent.event_id, acked, events: r.list, summary: r.summary }); return r; } // ① 4 个文件(新房间) const roomA = await openRoom('four'); const r1 = await ask( roomA, `在 ${D}/a/ 下生成 4 个文件并逐个发给我:1.csv(三行两列数字)、2.md(一段说明)、3.txt(一行文字)、4.json(一个小对象)。每生成一个就立即发给我,不要攒到最后。完成后简短总结。`, '第1轮 · 新房间 · 4 个文件', ); // ② 同房再问 1 个文件(查:是否把上一轮的文件重发 / 旧卡片串入) const r2 = await ask( roomA, `在 ${D}/b/ 下生成 1 个文件 5.log(三行日志),发给我。只发这个文件,不要重发上一轮的 1.csv/2.md/3.txt/4.json。完成后简短总结。`, '第2轮 · 同房间第二次提问 · 1 个文件', ); // ③ 全新房间再问 1 个文件(查:是否带出其它会话的历史卡片) const roomB = await openRoom('fresh'); const r3 = await ask( roomB, `在 ${D}/c/ 下生成 1 个文件 only.html(最小 HTML 页面),发给我。只发这一个文件,不要发任何历史文件。完成后简短总结。`, '第3轮 · 新房间 · 1 个文件', ); // ④ 一次 5 个含图片(查:多附件上限、图片与文件混发) const roomC = await openRoom('five'); const r4 = await ask( roomC, `在 ${D}/d/ 下生成 5 个文件并全部发给我:a.xlsx(一张两列表格)、b.pdf(一页文字)、c.png(一张 200x100 纯色图)、d.md(一段说明)、e.txt(一行文字)。每个都要单独作为附件发给我,不要只发链接、不要攒到最后。完成后简短总结。`, '第4轮 · 新房间 · 5 个文件(含图片/PDF/Excel)', ); mkdirSync(OUT, { recursive: true }); const file = join(OUT, `diag-ljtest-${Date.now()}.json`); writeFileSync(file, JSON.stringify(report, null, 2)); console.log(`\n===== 汇总 =====`); for (const r of report.rounds) console.log(`${r.label}: 统计=${JSON.stringify(r.summary)} ack=${r.acked}`); console.log(`\n完整事件已落盘: ${file}`); c.stopClient(); } main().catch((e) => { console.error('失败:', e.message ?? e); process.exit(1); });