agent-console-smoke-test.js 39 KB

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