agent-console-smoke-test.js 30 KB

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