agent-console-smoke-test.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. const assert = require('assert/strict');
  2. const fs = require('fs');
  3. const os = require('os');
  4. const path = require('path');
  5. const { DatabaseSync } = require('node:sqlite');
  6. const { AgentWorkbenchDb } = require('../mcp/src/core/agent-workbench-db');
  7. const { AgentWorkbenchService } = require('../mcp/src/core/agent-workbench-service');
  8. const { createCustomerTaskOfficialSync } = require('../mcp/src/core/customer-task-official-sync');
  9. const { evaluatePolledMessage, roomIdOf } = require('../mcp/src/core/agent-poller-policy');
  10. const {
  11. ClaudeCodeClient,
  12. ClaudeCodeSessionStore,
  13. buildClaudeSessionName,
  14. claudeSessionResetReason,
  15. enforceAuthoritativeGrounding,
  16. extractExplicitCustomerIntelligence,
  17. isNoReplyNeededMessage,
  18. parseClaudeProcessResult,
  19. selectAuthoritativeHistory,
  20. } = require('../mcp/src/core/agent-runtime');
  21. const { getCustomerSessionGuide } = require('../mcp/src/core/agent-session-guide');
  22. const { FmodeQiweiClient } = require('../mcp/src/providers/fmode-agent-transport');
  23. const { normalizeAllowlistIds, normalizeAllowlistContact } = require('../mcp/src/core/allowlist-config');
  24. const { GroupAgentService } = require('../mcp/src/dashboard/group-agent-service');
  25. const results = [];
  26. function setup({ paused = false, defaultMode = 'review', agentRun } = {}) {
  27. const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qiwei-agent-smoke-'));
  28. const db = new AgentWorkbenchDb(path.join(dir, 'test.db'), {
  29. globalPaused: paused,
  30. defaultMode,
  31. autoSendConfidence: 0.88,
  32. });
  33. const sent = [];
  34. const qiwei = {
  35. isConfigured: () => true,
  36. async sendText(toId, content) {
  37. sent.push({ toId, content });
  38. return { isSendSuccess: true };
  39. },
  40. };
  41. const agent = {
  42. async run(input) {
  43. if (agentRun) return agentRun(input);
  44. return {
  45. content: '这是 Agent 基于知识检索生成的草稿',
  46. confidence: 0.91,
  47. intent: '购房咨询',
  48. reason: '命中企业规则与 FAQ',
  49. requiresHuman: false,
  50. profileUpdates: { intent: '购房' },
  51. citations: [{ id: 'faq.md#1', source: 'faq.md', heading: 'Agent 能做什么' }],
  52. toolTrace: [{ tool: 'search_knowledge', args: { query: '购房咨询' }, result: [] }],
  53. };
  54. },
  55. };
  56. const config = {
  57. agent: { apiKey: 'smoke-only', model: 'stub-model', provider: 'stub' },
  58. qiwei: { allowedSenders: ['contact-1'] },
  59. };
  60. const service = new AgentWorkbenchService({ db, agent, qiwei, config });
  61. return {
  62. dir,
  63. db,
  64. sent,
  65. service,
  66. close() {
  67. db.close();
  68. fs.rmSync(dir, { recursive: true, force: true });
  69. },
  70. };
  71. }
  72. async function check(name, fn) {
  73. await fn();
  74. results.push({ name, status: 'passed' });
  75. }
  76. async function main() {
  77. await check('白名单选择会去重并拒绝不安全的联系人 ID', async () => {
  78. assert.deepEqual(normalizeAllowlistIds(['contact-1', ' contact-1 ', 'wm_test:2']), ['contact-1', 'wm_test:2']);
  79. assert.throws(() => normalizeAllowlistIds(['contact-1\nINJECTED=true']), /联系人 ID 格式无效/);
  80. assert.deepEqual(normalizeAllowlistContact({ userId: 'contact-1', remark: '刘总', corpName: '示例公司' }), {
  81. id: 'contact-1', displayName: '刘总', remark: '刘总', company: '示例公司'
  82. });
  83. });
  84. await check('Agent 企微传输统一走 Fmode 网关与登录专用端点', async () => {
  85. const calls = [];
  86. const originalFetch = global.fetch;
  87. global.fetch = async (url, options = {}) => {
  88. const parsedBody = options.body ? JSON.parse(options.body) : null;
  89. calls.push({ url: String(url), options, body: parsedBody });
  90. const loginStatus = String(url).includes('/login/status');
  91. let payload;
  92. if (loginStatus) {
  93. payload = { code: 0, data: { configured: true, online: true, statusCode: 2, detail: { nickname: '演示账号' } } };
  94. } else if (parsedBody?.method === '/contact/getWxContactList') {
  95. payload = { code: 0, data: { data: { currentSeq: 9, contactCount: 1, hasMore: false, contactList: [{ userId: 'contact-1' }] } } };
  96. } else if (parsedBody?.method === '/contact/batchGetUserinfo') {
  97. payload = { code: 0, data: { data: { contactList: [{ userId: 'contact-1', nickname: '测试客户' }] } } };
  98. } else {
  99. payload = { code: 0, data: { data: { isSendSuccess: true, syncMsgList: [], travelSyncKey: 9 } } };
  100. }
  101. return {
  102. ok: true,
  103. status: 200,
  104. async text() { return JSON.stringify(payload); },
  105. };
  106. };
  107. try {
  108. const client = new FmodeQiweiClient({
  109. authToken: 'test-fmode-token',
  110. uid: 'uid-smoke',
  111. guid: 'guid-smoke',
  112. apiBase: 'https://gateway.example/api/qiwei',
  113. });
  114. const account = await client.checkLogin();
  115. await client.syncMessages(8, 50);
  116. const contacts = await client.listExternalContacts();
  117. await client.sendText('external-contact-1', '测试回复');
  118. assert.equal(account.online, true);
  119. assert.equal(account.nickname, '演示账号');
  120. assert.match(calls[0].url, /\/login\/status\?uid=uid-smoke$/);
  121. assert.equal(calls[0].options.method, 'GET');
  122. assert.equal(calls[1].body.uid, 'uid-smoke');
  123. assert.equal(calls[1].body.method, '/msg/syncMsg');
  124. assert.equal(calls[1].body.params.guid, 'guid-smoke');
  125. assert.equal(contacts.contacts[0].nickname, '测试客户');
  126. assert.equal(calls[2].body.method, '/contact/getWxContactList');
  127. assert.equal(calls[3].body.method, '/contact/batchGetUserinfo');
  128. assert.equal(calls[4].body.method, '/msg/sendText');
  129. assert.equal(calls[4].options.headers.Authorization, 'Bearer test-fmode-token');
  130. } finally {
  131. global.fetch = originalFetch;
  132. }
  133. });
  134. await check('多企微账号使用独立工作台数据库和 Claude Session', async () => {
  135. const { __testing } = require('../mcp/src/dashboard/agent-service');
  136. const accountA = { uid: 'account-a', guid: 'guid-a', nickname: '账号 A' };
  137. const accountB = { uid: 'account-b', guid: 'guid-b', nickname: '账号 B' };
  138. const keyA = __testing.accountRuntimeKey(accountA);
  139. const keyB = __testing.accountRuntimeKey(accountB);
  140. const configA = __testing.accountWorkbenchOverrides(accountA);
  141. const configB = __testing.accountWorkbenchOverrides(accountB);
  142. assert.notEqual(keyA, keyB);
  143. assert.notEqual(configA.dbPath, configB.dbPath);
  144. assert.notEqual(configA.agent.claudeSessionFile, configB.agent.claudeSessionFile);
  145. assert.equal(configA.qiwei.uid, accountA.uid);
  146. assert.equal(configB.qiwei.guid, accountB.guid);
  147. });
  148. await check('不同消息 ID 的同内容在 60 秒内只入库一次', async () => {
  149. const ctx = setup();
  150. try {
  151. const first = await ctx.service.ingestInbound({ externalId: 'm1', contactId: 'contact-1', contactName: '王刚', content: '我想咨询房源' });
  152. const duplicate = await ctx.service.ingestInbound({ externalId: 'm1-copy', contactId: 'contact-1', contactName: '王刚', content: '我想咨询房源' });
  153. assert.equal(first.status, 'pending_review');
  154. assert.equal(duplicate.status, 'duplicate_content');
  155. assert.equal(ctx.db.listMessages(first.conversation.id).length, 1);
  156. } finally { ctx.close(); }
  157. });
  158. await check('审核模式生成草稿但不自动外发', async () => {
  159. const ctx = setup();
  160. try {
  161. const result = await ctx.service.ingestInbound({ externalId: 'm2', contactId: 'contact-1', contactName: '王刚', content: '预算 150 万,想买三室' });
  162. assert.equal(result.status, 'pending_review');
  163. assert.equal(ctx.sent.length, 0);
  164. assert.equal(ctx.db.getDraft(result.draft.id).status, 'pending');
  165. assert.equal(result.draft.citations[0].source, 'faq.md');
  166. assert.equal(result.draft.tool_trace[0].tool, 'search_knowledge');
  167. } finally { ctx.close(); }
  168. });
  169. await check('批准草稿只发送一次,重复批准被拒绝', async () => {
  170. const ctx = setup();
  171. try {
  172. const result = await ctx.service.ingestInbound({ externalId: 'm3', contactId: 'contact-1', contactName: '王刚', content: '请给我一个建议' });
  173. await ctx.service.approveDraft(result.draft.id, { content: '人工编辑后的回复', actor: 'human' });
  174. await assert.rejects(() => ctx.service.approveDraft(result.draft.id, { actor: 'human' }), /不能重复发送/);
  175. assert.deepEqual(ctx.sent, [{ toId: 'contact-1', content: '人工编辑后的回复' }]);
  176. assert.equal(ctx.db.getDraft(result.draft.id).status, 'sent');
  177. } finally { ctx.close(); }
  178. });
  179. await check('全局暂停与人工接管都抑制 Agent', async () => {
  180. const ctx = setup({ paused: true });
  181. try {
  182. const paused = await ctx.service.ingestInbound({ externalId: 'm4', contactId: 'contact-1', contactName: '王刚', content: '暂停时消息' });
  183. assert.equal(paused.status, 'paused');
  184. ctx.service.setGlobal({ paused: false });
  185. ctx.service.setConversationMode(paused.conversation.id, 'human');
  186. const human = await ctx.service.ingestInbound({ externalId: 'm5', contactId: 'contact-1', contactName: '王刚', content: '人工接管时消息' });
  187. assert.equal(human.status, 'human');
  188. assert.equal(ctx.db.listDrafts().length, 0);
  189. assert.equal(ctx.sent.length, 0);
  190. } finally { ctx.close(); }
  191. });
  192. await check('Agent 上游失败只留审计,不生成伪回复、不外发', async () => {
  193. const ctx = setup({ agentRun: async () => { throw new Error('Agent 上游暂时不可用(HTTP 522)'); } });
  194. try {
  195. const result = await ctx.service.ingestInbound({ externalId: 'm6', contactId: 'contact-1', contactName: '王刚', content: '请推荐房源' });
  196. assert.equal(result.status, 'agent_failed');
  197. assert.equal(ctx.db.listDrafts().length, 0);
  198. assert.equal(ctx.sent.length, 0);
  199. assert.equal(ctx.db.latestAgentState(result.conversation.id).action, 'agent_failed');
  200. } finally { ctx.close(); }
  201. });
  202. await check('确认消息无需调用模型、无需回复且会清除旧错误状态', async () => {
  203. let agentCalls = 0;
  204. const ctx = setup({ agentRun: async () => { agentCalls += 1; throw new Error('不应调用模型'); } });
  205. try {
  206. const conversation = ctx.db.ensureConversation('contact-1', '王刚');
  207. ctx.db.audit({ actor: 'agent', action: 'agent_failed', conversationId: conversation.id, detail: { message: '历史上游失败' } });
  208. const result = await ctx.service.ingestInbound({ externalId: 'm-ack', contactId: 'contact-1', contactName: '王刚', content: '收到' });
  209. assert.equal(result.status, 'no_reply_needed');
  210. assert.equal(agentCalls, 0);
  211. assert.equal(ctx.sent.length, 0);
  212. assert.equal(ctx.db.latestAgentState(conversation.id), null);
  213. assert.equal(ctx.db.latestAgentOutcome(conversation.id).action, 'agent_no_reply_needed');
  214. assert.equal(ctx.db.latestAgentOutcome(conversation.id).entityId, result.message.id);
  215. assert.equal(isNoReplyNeededMessage('好的。'), true);
  216. assert.equal(isNoReplyNeededMessage('地址确认好了吗'), false);
  217. } finally { ctx.close(); }
  218. });
  219. await check('Claude Code 预算超限时轮换客户 Session 并只重试一次', async () => {
  220. const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qiwei-budget-reset-'));
  221. try {
  222. const client = new ClaudeCodeClient({
  223. claudeWorkdir: dir,
  224. claudeSessionFile: path.join(dir, 'sessions.json'),
  225. claudeMaxBudgetUsd: 0.35,
  226. claudeRetryMaxBudgetUsd: 1,
  227. });
  228. const sessionIds = [];
  229. const invokeOptions = [];
  230. client.invoke = async (_messages, _context, session, options = {}) => {
  231. sessionIds.push(session.id);
  232. invokeOptions.push(options);
  233. if (sessionIds.length === 1) throw new Error('Claude Code 调用失败(退出码 1):error_max_budget_usd');
  234. return { content: '{}', claudeCode: { resumed: false } };
  235. };
  236. const result = await client.complete([{ role: 'user', content: '请推荐房源' }], [], { conversation: { id: 'conversation-budget', contact_name: '王刚' } });
  237. assert.equal(sessionIds.length, 2);
  238. assert.notEqual(sessionIds[0], sessionIds[1]);
  239. assert.equal(invokeOptions[1].maxBudgetUsd, 1);
  240. assert.equal(result.claudeCode.sessionResetReason, 'budget_exceeded');
  241. assert.equal(claudeSessionResetReason(new Error('error_max_budget_usd')), 'budget_exceeded');
  242. } finally { fs.rmSync(dir, { recursive: true, force: true }); }
  243. });
  244. await check('Claude Code 客服调用使用精简模式与低推理强度', async () => {
  245. const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qiwei-claude-bare-'));
  246. try {
  247. let capturedArgs = [];
  248. const client = new ClaudeCodeClient({
  249. claudeWorkdir: dir,
  250. claudeSessionFile: path.join(dir, 'sessions.json'),
  251. claudeBare: true,
  252. claudeEffort: 'low',
  253. claudeTools: 'Read,Glob,Grep',
  254. model: 'deepseek-v4-pro',
  255. });
  256. client.runProcess = async args => {
  257. capturedArgs = args;
  258. return { structured_output: { reply: '测试草稿' }, duration_ms: 1, total_cost_usd: 0.01 };
  259. };
  260. await client.invoke([{ role: 'system', content: '测试' }, { role: 'user', content: '推荐房源' }], {}, { id: '33333333-3333-4333-8333-333333333333', initialized: false });
  261. assert(capturedArgs.includes('--bare'));
  262. assert.equal(capturedArgs[capturedArgs.indexOf('--effort') + 1], 'low');
  263. assert.equal(capturedArgs[capturedArgs.indexOf('--tools') + 1], 'Read,Glob,Grep');
  264. } finally { fs.rmSync(dir, { recursive: true, force: true }); }
  265. });
  266. await check('Claude Code 已完成结构化输出时不因末尾预算退出码丢弃草稿', async () => {
  267. const recovered = parseClaudeProcessResult(JSON.stringify({
  268. is_error: true,
  269. subtype: 'error_max_budget_usd',
  270. structured_output: {
  271. reply: '已经生成的客服草稿',
  272. confidence: 0.75,
  273. intent: '继续推荐',
  274. },
  275. }), '', 1);
  276. assert.equal(recovered.error, undefined);
  277. assert.equal(recovered.payload.is_error, false);
  278. assert.equal(recovered.payload.structured_output.reply, '已经生成的客服草稿');
  279. assert.equal(recovered.payload.process_warning.detail, 'error_max_budget_usd');
  280. const failed = parseClaudeProcessResult(JSON.stringify({ is_error: true, subtype: 'error_max_budget_usd' }), '', 1);
  281. assert.match(failed.error, /error_max_budget_usd/);
  282. });
  283. await check('非白名单联系人被忽略且不能人工发送', async () => {
  284. const ctx = setup();
  285. try {
  286. const ignored = await ctx.service.ingestInbound({ externalId: 'm7', contactId: 'contact-2', contactName: '其他人', content: '你好' });
  287. assert.equal(ignored.status, 'ignored_not_allowlisted');
  288. assert.equal(ctx.db.listConversations().length, 0);
  289. const allowed = ctx.db.ensureConversation('contact-1', '王刚');
  290. ctx.db.db.prepare('UPDATE conversations SET contact_id=? WHERE id=?').run('contact-2', allowed.id);
  291. await assert.rejects(() => ctx.service.manualSend(allowed.id, '测试'), /不在测试白名单/);
  292. assert.equal(ctx.sent.length, 0);
  293. } finally { ctx.close(); }
  294. });
  295. await check('项目主控关联下每个客户绑定独立 Claude Code Session', async () => {
  296. const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qiwei-session-map-'));
  297. try {
  298. const filePath = path.join(dir, 'sessions.json');
  299. const store = new ClaudeCodeSessionStore(filePath, {
  300. projectId: 'project-smoke',
  301. projectRoot: dir,
  302. mainSessionId: '11111111-1111-4111-8111-111111111111',
  303. });
  304. const first = store.ensure('conversation-a', { customerName: '王刚', displayName: '企微客户-王刚-a001' });
  305. const second = store.ensure('conversation-b', { customerName: '李女士', displayName: '企微客户-李女士-b002' });
  306. assert.notEqual(first.id, second.id);
  307. assert.equal(first.parentControllerSessionId, second.parentControllerSessionId);
  308. assert.equal(first.projectId, 'project-smoke');
  309. assert.equal(first.customerName, '王刚');
  310. assert.equal(first.displayName, '企微客户-王刚-a001');
  311. const persisted = JSON.parse(fs.readFileSync(filePath, 'utf8'));
  312. assert.equal(persisted.project.boundMainSessionId, '11111111-1111-4111-8111-111111111111');
  313. assert.equal(Object.keys(persisted.sessions).length, 2);
  314. } finally { fs.rmSync(dir, { recursive: true, force: true }); }
  315. });
  316. await check('Claude Code 只采用本轮权威上下文并使用客户可识别会话名', async () => {
  317. const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qiwei-prompt-boundary-'));
  318. try {
  319. const messages = [
  320. { role: 'user', content: '我是两个两个买' },
  321. { role: 'user', content: '加进去这个api服务就不用管了' },
  322. { role: 'assistant', content: '新北区有4套三室房,请问预算是多少?' },
  323. { role: 'user', content: '200万吧' },
  324. ];
  325. const authoritative = selectAuthoritativeHistory(messages);
  326. assert.deepEqual(authoritative.map(item => item.content), [
  327. '新北区有4套三室房,请问预算是多少?',
  328. '200万吧',
  329. ]);
  330. const client = new ClaudeCodeClient({
  331. claudeSessionFile: path.join(dir, 'sessions.json'),
  332. claudeWorkdir: dir,
  333. });
  334. const prompt = client.buildPrompt(messages, { profile: { profile: {} } });
  335. assert.match(prompt, /本轮有效会话/);
  336. assert.match(prompt, /200万吧/);
  337. assert.doesNotMatch(prompt, /两个两个买/);
  338. assert.doesNotMatch(prompt, /api服务/);
  339. const sessionName = buildClaudeSessionName({ conversation: { contact_name: '王刚' } }, 'conversation-a');
  340. assert.match(sessionName, /^企微客户-王刚-[a-f0-9]{4}$/);
  341. assert.doesNotMatch(sessionName, /conversation-a/);
  342. } finally { fs.rmSync(dir, { recursive: true, force: true }); }
  343. });
  344. await check('Session 残留原话被证据闸门拦截并降级为人工确认', async () => {
  345. const history = [
  346. { role: 'assistant', content: '新北区有4套三室房,请问预算是多少?' },
  347. { role: 'user', content: '200万吧' },
  348. ];
  349. const guarded = enforceAuthoritativeGrounding({
  350. reply: '您之前提到“两个两个买”,是想一次买两套吗?',
  351. confidence: 0.9,
  352. intent: '预算确认',
  353. reason: '客户之前说“两个两个买”。',
  354. requiresHuman: false,
  355. }, history, { preferredRegion: '新北区', layout: '三室', budgetWan: 200, budgetType: '待确认' }, '200万吧');
  356. assert.equal(guarded.requiresHuman, true);
  357. assert(guarded.confidence <= 0.68);
  358. assert.doesNotMatch(guarded.reply, /两个两个买|两套/);
  359. assert.match(guarded.reply, /新北区/);
  360. const intelligence = extractExplicitCustomerIntelligence('200万吧', { preferredRegion: '新北区', layout: '三室' }, {
  361. profileUpdates: { purchaseQuantity: 2, budgetWan: 200 },
  362. tasks: [{ type: 'purchase', title: '准备两套方案', evidence: '两个两个买' }],
  363. alerts: [{ type: 'high_intent', severity: 'high', title: '两套购买', evidence: '两个两个买' }],
  364. });
  365. assert.equal(intelligence.profileUpdates.purchaseQuantity, undefined);
  366. assert.equal(intelligence.profileUpdates.budgetWan, 200);
  367. assert.doesNotMatch(JSON.stringify(intelligence), /两个两个买|两套购买|准备两套方案/);
  368. });
  369. await check('客户 Session 指引主动返回可识别名称和安全打开命令', async () => {
  370. const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qiwei-session-guide-'));
  371. try {
  372. const sessionFile = path.join(dir, 'sessions.json');
  373. fs.writeFileSync(sessionFile, JSON.stringify({
  374. version: 1,
  375. project: {},
  376. sessions: {
  377. 'conversation-a': {
  378. id: '22222222-2222-4222-8222-222222222222',
  379. role: 'customer-agent',
  380. initialized: true,
  381. displayName: '企微客户-王刚-a001',
  382. },
  383. },
  384. }), 'utf8');
  385. const guide = getCustomerSessionGuide({ id: 'conversation-a', contact_name: '王刚' }, { sessionFile });
  386. assert.equal(guide.ready, true);
  387. assert.equal(guide.displayName, '企微客户-王刚-a001');
  388. assert.match(guide.openCommand, /agent:session/);
  389. assert.match(guide.openCommand, /王刚/);
  390. assert.doesNotMatch(JSON.stringify(guide), /22222222/);
  391. assert.equal(guide.productionSessionProtected, true);
  392. } finally { fs.rmSync(dir, { recursive: true, force: true }); }
  393. });
  394. await check('监听消息持续沉淀客户画像、内部待办和预警', async () => {
  395. const housing = extractExplicitCustomerIntelligence('我想咨询一下新北区的三室房', {}, {});
  396. assert.equal(housing.profileUpdates.preferredRegion, '新北区');
  397. assert.equal(housing.profileUpdates.layout, '三室');
  398. const explicit = extractExplicitCustomerIntelligence('200万吧', { preferredRegion: '新北区', layout: '三室' }, {});
  399. assert.equal(explicit.profileUpdates.budgetWan, 200);
  400. assert(explicit.tasks.some(item => item.type === 'recommendation'));
  401. assert(explicit.alerts.some(item => item.type === 'high_intent'));
  402. const purpose = extractExplicitCustomerIntelligence('自己住吧', { budgetWan: 200 }, {});
  403. assert.equal(purpose.profileUpdates.purpose, '自住');
  404. const ctx = setup({ agentRun: async () => ({
  405. content: '好的,我再确认一下您的用途和时间计划。',
  406. confidence: 0.82,
  407. intent: '预算确认',
  408. reason: '客户给出明确预算,需要补齐用途和时间。',
  409. requiresHuman: false,
  410. profileUpdates: { budgetWan: 200, budgetType: '待确认' },
  411. tasks: [{ type: 'qualification', title: '确认用途与时间计划', owner: '待分配', dueAt: '', priority: 'high', reason: '关键信息待补齐', evidence: '200万吧' }],
  412. alerts: [{ type: 'high_intent', severity: 'high', title: '预算已明确', detail: '可以进入需求收敛阶段', evidence: '200万吧', recommendedAction: '确认用途与时间' }],
  413. citations: [],
  414. toolTrace: [],
  415. }) });
  416. try {
  417. const result = await ctx.service.ingestInbound({ externalId: 'm-intel', contactId: 'contact-1', contactName: '王刚', content: '200万吧' });
  418. assert.equal(result.status, 'pending_review');
  419. const detail = ctx.service.conversationDetail(result.conversation.id);
  420. assert.equal(detail.profile.profile.budgetWan, 200);
  421. assert.equal(detail.tasks.length, 1);
  422. assert.equal(detail.alerts.length, 1);
  423. assert.equal(ctx.sent.length, 0);
  424. } finally { ctx.close(); }
  425. });
  426. await check('监听重启后仍接收停机期间的白名单积压消息', async () => {
  427. const candidate = evaluatePolledMessage({
  428. msgType: 1,
  429. senderId: 'contact-1',
  430. timestamp: Math.floor(Date.now() / 1000) - 600,
  431. msgData: { content: '自己住吧' },
  432. }, { selfUserId: 'self', allowedSenders: ['contact-1'] });
  433. assert.equal(candidate.eligible, true);
  434. assert.equal(candidate.content, '自己住吧');
  435. });
  436. await check('群聊与本账号消息不会串入白名单客户私聊', async () => {
  437. const group = evaluatePolledMessage({
  438. msgType: 2,
  439. senderId: 'contact-1',
  440. receiverId: 'self',
  441. fromRoomId: 'room-123',
  442. timestamp: Math.floor(Date.now() / 1000),
  443. msgData: { content: '@同事 请发会议录屏' },
  444. }, { selfUserId: 'self', allowedSenders: ['contact-1'] });
  445. assert.equal(group.eligible, false);
  446. assert.equal(group.reason, 'group_message');
  447. assert.equal(group.roomId, 'room-123');
  448. assert.equal(roomIdOf({ fromRoomId: 0, roomId: '' }), '');
  449. const self = evaluatePolledMessage({
  450. msgType: 1,
  451. senderId: 'self',
  452. receiverId: 'contact-1',
  453. timestamp: Math.floor(Date.now() / 1000),
  454. msgData: { content: '我发出的私聊' },
  455. }, { selfUserId: 'self', allowedSenders: ['contact-1'] });
  456. assert.equal(self.eligible, false);
  457. assert.equal(self.reason, 'self_message');
  458. const ctx = setup();
  459. try {
  460. const ignored = await ctx.service.ingestInbound({
  461. externalId: 'group-direct-entry',
  462. contactId: 'contact-1',
  463. contactName: '王刚',
  464. content: '群里的消息',
  465. raw: { fromRoomId: 'room-123', senderId: 'contact-1' },
  466. });
  467. assert.equal(ignored.status, 'ignored_group_message');
  468. assert.equal(ctx.db.listConversations().length, 0);
  469. const legacyGroup = ctx.db.ensureConversation('contact-1', '历史群聊');
  470. ctx.db.insertMessage({
  471. conversationId: legacyGroup.id,
  472. externalId: 'legacy-group-message',
  473. direction: 'inbound',
  474. senderType: 'customer',
  475. content: '旧数据中的群消息',
  476. raw: { fromRoomId: 'room-legacy', senderId: 'contact-1' },
  477. });
  478. await assert.rejects(() => ctx.service.manualSend(legacyGroup.id, '不应发送'), /群聊仅用于监控/);
  479. assert.equal(ctx.sent.length, 0);
  480. } finally { ctx.close(); }
  481. });
  482. await check('客户群支持人工审核与无视风险全自动两种独立模式', async () => {
  483. const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qiwei-group-agent-smoke-'));
  484. const messages = [{
  485. msgId: 'group-message-1',
  486. senderId: 'customer-1',
  487. senderName: '张三',
  488. fromRoomId: 'r-1',
  489. content: '明天下午可以看房吗',
  490. timestamp: '2026-07-23T08:00:00.000Z',
  491. }];
  492. const sent = [];
  493. const sendAttempts = [];
  494. const agentInputs = [];
  495. let sendShouldFail = false;
  496. let agentResponse = {
  497. content: '可以的,请问您明天下午几点方便?',
  498. confidence: 0.88,
  499. intent: '预约看房',
  500. reason: '客户明确询问看房时间',
  501. requiresHuman: false,
  502. citations: [],
  503. toolTrace: [],
  504. };
  505. const runtime = {
  506. config: { qiwei: { selfUserId: 'self-1', nickname: '王顾问' } },
  507. agent: {
  508. async run(input) {
  509. agentInputs.push(input);
  510. return agentResponse;
  511. },
  512. },
  513. qiwei: {
  514. async sendText(toId, content) {
  515. sendAttempts.push({ toId, content });
  516. if (sendShouldFail) return { isSendSuccess: false };
  517. sent.push({ toId, content });
  518. return { isSendSuccess: true };
  519. },
  520. },
  521. };
  522. const service = new GroupAgentService({
  523. projectRoot: dir,
  524. statePath: path.join(dir, 'group-agent.json'),
  525. runtime,
  526. getAccount: () => ({ uid: 'account-1', userId: 'self-1', nickname: '王顾问' }),
  527. loadGroups: () => ({ 'r-1': { roomName: '张三买房服务群', customerName: '张三' } }),
  528. loadMessages: () => messages,
  529. appendMessage: (roomId, message) => { messages.push({ ...message, fromRoomId: roomId }); return 'memory'; },
  530. });
  531. try {
  532. assert.equal(service.publicState('r-1').mode, 'review');
  533. const generated = await service.generate('r-1');
  534. assert.equal(generated.status, 'pending_review');
  535. assert.equal(generated.draft.requiresHuman, true);
  536. assert.equal(sent.length, 0);
  537. assert.equal(agentInputs[0].channelType, 'group');
  538. assert.match(agentInputs[0].directPrompt, /企业微信群聊客服 Agent/);
  539. const approved = await service.approve('r-1', generated.draft.id, '可以的,张三,请问您明天下午几点方便?');
  540. assert.equal(approved.status, 'sent');
  541. assert.deepEqual(sent, [{ toId: 'r-1', content: '可以的,张三,请问您明天下午几点方便?' }]);
  542. assert.equal(service.publicState('r-1').pendingReply, null);
  543. assert.equal(service.publicState('r-1').messages.at(-1).role, 'human');
  544. await assert.rejects(() => service.approve('r-1', generated.draft.id, '重复发送'), /已经是 sent/);
  545. await assert.rejects(() => service.generate('unconfirmed-room'), /尚未确认为客户群/);
  546. assert.throws(() => service.setMode('r-1', 'auto'), /需要明确确认/);
  547. assert.equal(service.setMode('r-1', 'auto', 'AUTO_SEND_GROUP_MESSAGES').mode, 'auto');
  548. agentResponse = {
  549. content: '三点可以,我先为您登记。',
  550. confidence: 0.1,
  551. intent: '预约看房',
  552. reason: '低置信回复仍由全自动模式放行',
  553. requiresHuman: true,
  554. citations: [],
  555. toolTrace: [],
  556. };
  557. const ingested = await service.ingestPolledMessage({
  558. msgType: 1,
  559. msgServerId: 'group-message-2',
  560. seq: 2,
  561. senderId: 'customer-1',
  562. senderName: '张三',
  563. fromRoomId: 'r-1',
  564. msgData: { content: '三点可以吗' },
  565. timestamp: Math.floor(Date.now() / 1000),
  566. }, { selfUserId: 'self-1' });
  567. assert.equal(ingested.status, 'auto_sent');
  568. assert.equal(agentInputs.length, 2);
  569. assert.equal(sent.length, 2);
  570. assert.deepEqual(sent.at(-1), { toId: 'r-1', content: '三点可以,我先为您登记。' });
  571. assert.equal(service.publicState('r-1').pendingReply, null);
  572. assert.equal(service.publicState('r-1').lastOutcome.action, 'group_message_auto_sent');
  573. assert.equal(messages.at(-1).rawData.source, 'group_agent_auto');
  574. sendShouldFail = true;
  575. const failed = await service.ingestPolledMessage({
  576. msgType: 1,
  577. msgServerId: 'group-message-3',
  578. seq: 3,
  579. senderId: 'customer-1',
  580. senderName: '张三',
  581. fromRoomId: 'r-1',
  582. msgData: { content: '能发个定位吗' },
  583. timestamp: Math.floor(Date.now() / 1000) + 1,
  584. }, { selfUserId: 'self-1' });
  585. assert.equal(failed.status, 'pending_review');
  586. assert.equal(failed.autoSendFailed, true);
  587. assert.equal(sent.length, 2);
  588. assert.equal(sendAttempts.length, 3);
  589. assert(service.publicState('r-1').pendingReply);
  590. assert(service.publicState('r-1').sendError);
  591. sendShouldFail = false;
  592. assert.equal(service.setMode('r-1', 'review').mode, 'review');
  593. const reviewed = await service.ingestPolledMessage({
  594. msgType: 1,
  595. msgServerId: 'group-message-4',
  596. seq: 4,
  597. senderId: 'customer-1',
  598. senderName: '张三',
  599. fromRoomId: 'r-1',
  600. msgData: { content: '四点也可以' },
  601. timestamp: Math.floor(Date.now() / 1000) + 2,
  602. }, { selfUserId: 'self-1' });
  603. assert.equal(reviewed.status, 'pending_review');
  604. assert.equal(sent.length, 2);
  605. assert.equal(service.publicState('r-1').mode, 'review');
  606. } finally {
  607. fs.rmSync(dir, { recursive: true, force: true });
  608. }
  609. });
  610. await check('同一业务待办只保留一张卡并聚合多条依据', async () => {
  611. const ctx = setup();
  612. try {
  613. const conversation = ctx.db.ensureConversation('contact-1', '王刚');
  614. ctx.db.upsertCustomerTasks(conversation.id, [{ businessKey: 'qualification:purpose_and_timeline', managedBy: 'rule', type: 'qualification', title: '确认客户用途与购置时间', evidence: '预算200万' }], 'message-a');
  615. ctx.db.upsertCustomerTasks(conversation.id, [{ businessKey: 'qualification:purpose_and_timeline', managedBy: 'rule', type: 'qualification', title: '确认客户用途与购置时间', evidence: '区域新北区' }], 'message-b');
  616. const tasks = ctx.db.listCustomerTasks(conversation.id);
  617. assert.equal(tasks.length, 1);
  618. assert.deepEqual(JSON.parse(tasks[0].evidence_json).map(item => item.text), ['预算200万', '区域新北区']);
  619. } finally { ctx.close(); }
  620. });
  621. await check('用途和购置时间补齐后资格确认待办自动完成', async () => {
  622. let turn = 0;
  623. const ctx = setup({ agentRun: async () => {
  624. turn += 1;
  625. return {
  626. content: '信息已记录。', confidence: 0.8, intent: '需求确认', reason: '测试', requiresHuman: false,
  627. profileUpdates: turn === 1 ? { budgetWan: 200 } : { purpose: '自住', timeline: '三个月内' },
  628. tasks: turn === 1 ? [{ businessKey: 'qualification:purpose_and_timeline', managedBy: 'rule', type: 'qualification', title: '确认客户用途与购置时间', evidence: '预算200万' }] : [],
  629. alerts: [], citations: [], toolTrace: [],
  630. };
  631. } });
  632. try {
  633. const first = await ctx.service.ingestInbound({ externalId: 'profile-a', contactId: 'contact-1', contactName: '王刚', content: '预算200万' });
  634. assert.equal(ctx.db.listCustomerTasks(first.conversation.id)[0].status, 'open');
  635. await ctx.service.ingestInbound({ externalId: 'profile-b', contactId: 'contact-1', contactName: '王刚', content: '自住,计划三个月内购买' });
  636. const qualification = ctx.db.listCustomerTasks(first.conversation.id).find(item => item.business_key === 'qualification:purpose_and_timeline');
  637. assert.equal(qualification.status, 'done');
  638. assert.equal(qualification.resolution_reason, 'profile_condition_resolved');
  639. } finally { ctx.close(); }
  640. });
  641. await check('发送房源方案后重点方案待办自动完成', async () => {
  642. const ctx = setup();
  643. try {
  644. const conversation = ctx.db.ensureConversation('contact-1', '王刚');
  645. ctx.db.upsertCustomerTasks(conversation.id, [{ businessKey: 'recommendation:shortlist', managedBy: 'rule', type: 'recommendation', title: '按已确认条件筛选并发送重点方案', evidence: '预算、区域、户型已明确' }], 'message-c');
  646. await ctx.service.manualSend(conversation.id, '已经为您筛选了三套重点房源方案,请查收。');
  647. const task = ctx.db.listCustomerTasks(conversation.id).find(item => item.business_key === 'recommendation:shortlist');
  648. assert.equal(task.status, 'done');
  649. assert.equal(task.resolution_reason, 'manual_recommendation_sent');
  650. } finally { ctx.close(); }
  651. });
  652. await check('旧数据库导入时合并重复业务项且不丢依据', async () => {
  653. const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qiwei-agent-import-'));
  654. const sourcePath = path.join(dir, 'legacy.db');
  655. const targetPath = path.join(dir, 'target.db');
  656. let source = new AgentWorkbenchDb(sourcePath, { defaultMode: 'review' });
  657. const conversation = source.ensureConversation('legacy-contact', '历史客户');
  658. source.close();
  659. const raw = new DatabaseSync(sourcePath);
  660. raw.exec('DROP INDEX IF EXISTS idx_customer_tasks_business_key');
  661. const timestamp = new Date().toISOString();
  662. const insert = raw.prepare(`INSERT INTO customer_tasks(id,conversation_id,fingerprint,business_key,managed_by,type,title,status,evidence,evidence_json,created_at,updated_at)
  663. VALUES(?,?,?,?,?,?,?,?,?,?,?,?)`);
  664. insert.run('legacy-task-a', conversation.id, 'legacy-fp-a', '', 'agent', 'qualification', '确认客户用途与购置时间', 'open', '预算200万', '[]', timestamp, timestamp);
  665. insert.run('legacy-task-b', conversation.id, 'legacy-fp-b', '', 'agent', 'qualification', '确认客户用途与购置时间', 'open', '区域新北区', '[]', timestamp, timestamp);
  666. raw.close();
  667. const target = new AgentWorkbenchDb(targetPath, { defaultMode: 'review' });
  668. try {
  669. const result = target.importCompatibleDatabase(sourcePath);
  670. assert.equal(result.imported, true);
  671. const tasks = target.listCustomerTasks(conversation.id);
  672. assert.equal(tasks.length, 1);
  673. assert.equal(tasks[0].business_key, 'qualification:purpose_and_timeline');
  674. assert.equal(JSON.parse(tasks[0].evidence_json).length, 2);
  675. } finally {
  676. target.close();
  677. fs.rmSync(dir, { recursive: true, force: true });
  678. }
  679. });
  680. await check('Claude Code 提示词读取统一待办和预警主账', async () => {
  681. const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qiwei-agent-prompt-'));
  682. try {
  683. const client = new ClaudeCodeClient({ claudeWorkdir: dir, claudeSessionFile: path.join(dir, 'sessions.json') });
  684. const prompt = client.buildPrompt([{ role: 'user', content: '继续推荐' }], { customerIntelligence: {
  685. tasks: [{ businessKey: 'recommendation:shortlist', title: '发送重点方案', status: 'open' }],
  686. alerts: [{ businessKey: 'high_intent:core_demand_ready', title: '高意向', status: 'open' }],
  687. } });
  688. assert.match(prompt, /当前未完成待办/);
  689. assert.match(prompt, /recommendation:shortlist/);
  690. assert.match(prompt, /当前未解决预警/);
  691. assert.match(prompt, /high_intent:core_demand_ready/);
  692. } finally { fs.rmSync(dir, { recursive: true, force: true }); }
  693. });
  694. await check('企微官方待办同步使用可注入 stub 并保持幂等', async () => {
  695. const ctx = setup();
  696. try {
  697. const conversation = ctx.db.ensureConversation('contact-1', '王刚');
  698. const [task] = ctx.db.upsertCustomerTasks(conversation.id, [{ businessKey: 'recommendation:shortlist', type: 'recommendation', title: '发送重点方案' }]);
  699. let createCalls = 0;
  700. const sync = createCustomerTaskOfficialSync({
  701. db: ctx.db,
  702. searchTodoUsers: async ({ keyword }) => ({ status: 'ok', data: { users: [{ id: 'internal-user-1', name: keyword, alias: '' }] } }),
  703. createTodoKnowledge: async input => {
  704. createCalls += 1;
  705. assert.deepEqual(input.followerIds, ['internal-user-1']);
  706. return { status: 'ok', summary: { todoId: 'official-todo-stub' }, data: { todo: { id: 'official-todo-stub' } } };
  707. },
  708. });
  709. await sync(task.id, { owner: '内部同事', dueAt: '2026-07-20 18:00' });
  710. await sync(task.id, { owner: '内部同事', dueAt: '2026-07-20 18:00' });
  711. const updated = ctx.db.getCustomerTask(task.id);
  712. assert.equal(createCalls, 1);
  713. assert.equal(updated.official_todo_id, 'official-todo-stub');
  714. assert.equal(updated.official_sync_status, 'synced');
  715. assert.equal(updated.status, 'in_progress');
  716. } finally { ctx.close(); }
  717. });
  718. process.stdout.write(`${JSON.stringify({ status: 'ok', passed: results.length, results }, null, 2)}\n`);
  719. }
  720. main().catch(error => {
  721. process.stderr.write(`${error.stack || error.message}\n`);
  722. process.exitCode = 1;
  723. });