fix(wechat): preserve page tasks across input questions and explicit resumes

This commit is contained in:
john
2026-11-26 13:46:54 +08:00
parent 327864c2f9
commit 31481b5f2b
7 changed files with 315 additions and 32 deletions
+10 -1
View File
@@ -8,10 +8,12 @@
- `chat`:处理本轮问题;显式聊天频道、不要生成页面、文字/密码/日程修改不能被页面分类覆盖。
- `page.create`:新建页面。有现存对话时轮换 Agent 会话,不携带旧正文;本轮完整需求仍是唯一正文来源。
- `page.from_context`:将紧邻诗文等内容排版成页面,保留原有即时上下文守卫。
- `page.continue`:用户回答页面任务的资料追问,携带原始任务,继续同一会话;不是新建另一项任务。
- `page.edit`:从用户提供的页面链接/文件路径,或当前会话最近 assistant 文本中的唯一页面链接绑定目标。
- `clarify`:目标缺失或最近回复包含多个页面时直接询问链接,不启动 Agent,不扫描工作区猜文件。
编辑目标传入 Agent 提示和 `metadata.memindRun.wechatTaskTarget`;模式记入 `wechatTaskMode`。
新建/补资料任务将最多 2000 字原始需求记入 `wechatTaskRequest`,以便后续追问仍保留目标。
记忆编排必须保留本轮任务提示;普通执行、页面补写和异常重试均携带相同目标约束。
正式发送编辑结果前,必须有目标页面产物,且产物/回复不得混入其他页面路径。
@@ -19,7 +21,11 @@
这是现有执行链上的第一阶段约束,不是完整的多任务调度器,也未实现工具层文件写权限沙箱。
交付检查能阻止错页链接被当作成功结果发送,不能撤销 Agent 已做出的错误写入。
当前只使用紧邻 assistant 的页面链接;跨话题恢复旧页面须用户重发链接,不从长期记忆猜测。
普通修改只使用紧邻可见 assistant 的页面链接。只有用户明确说返回刚才页面并给出修改要求时,
才在同一会话最近 12 条消息内寻找最近一次页面交付;多个候选仍须澄清,不从长期记忆或目录猜测。
同一消息提供多个不同目标时也必须澄清;重复同一链接不视为多个目标。
生成过程缺少资料时,可以发送受限的资料追问并继续任务;该中间状态不算页面生成成功,
不能携带页面产物、完成声明、错误信息或链接,也不绕过 Page Data 交付验收。
上下文读取失败时不猜编辑目标;已有真实 route 时间戳的新建请求仍轮换旧会话。
没有数据库迁移,目标从已有会话恢复;不改变 H5、页面物化、Page Data 验收、图片隔离或定时任务确认机制。
@@ -27,8 +33,11 @@
```bash
node --test wechat/intent/task-route.test.mjs wechat-intent-router.test.mjs wechat-mp.test.mjs wechat-cursor-channel.test.mjs wechat/handlers/scheduled-task.test.mjs
node scripts/simulate-wechat-task-routing.mjs --out=/tmp/memind-wechat-task-routing-simulation.json
```
必须覆盖:视觉修改、显式链接优先、文字/账号/日程修改、缺失及多个目标澄清、
新页面不携带旧正文、Agent 实际提示及 metadata、交付混入错页时阻断。
模拟器使用人工编写的多轮会话和确定性分类;三轮服务号集成模拟使用本地 mock SSE/微信接口,
并实际写入临时工作区 HTML。两者均不调用真实微信或真实 LLM,不替代真实用户对话验收。
生产发布仍需实际对话回放和原有发布闸门;本地测试通过不等于真实用户任务偏离已全部解决。
+52
View File
@@ -0,0 +1,52 @@
import fs from 'node:fs/promises';
import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { wechatTaskRouteScenarios } from '../wechat/intent/task-route-scenarios.mjs';
import { classifyWechatIntent } from '../wechat/intent/classifier.mjs';
import { readWechatTaskContext, resolveWechatTaskRoute } from '../wechat/intent/task-route.mjs';
function simulate(resolveRoute, readContext) {
return wechatTaskRouteScenarios.map((scenario) => {
const decision = resolveRoute({
wechatIntent: classifyWechatIntent({ msgType: 'text', agentText: scenario.text }),
text: scenario.text,
context: readContext(scenario.conversation),
});
const passed = scenario.kind ? decision.kind === scenario.kind
: decision.taskRoute?.mode === scenario.mode
&& (!scenario.target || decision.taskRoute?.targetPath === scenario.target);
return {
name: scenario.name, input: scenario.text,
expected: { kind: scenario.kind, mode: scenario.mode, target: scenario.target },
actual: { kind: decision.kind, mode: decision.taskRoute?.mode, target: decision.taskRoute?.targetPath },
passed,
};
});
}
const results = simulate(resolveWechatTaskRoute, readWechatTaskContext);
const report = {
simulation: 'local deterministic routing with synthetic conversation history; no live WeChat or LLM calls',
total: results.length, passed: results.filter((result) => result.passed).length,
failed: results.filter((result) => !result.passed).length, results,
};
const baseline = process.argv.find((arg) => arg.startsWith('--baseline='))?.slice(11);
if (baseline) {
if (!/^[a-f\d]{7,40}$/iu.test(baseline)) throw new Error('baseline must be a Git commit hash');
const source = execFileSync('git', ['show', `${baseline}:wechat/intent/task-route.mjs`], {
cwd: fileURLToPath(new URL('..', import.meta.url)), encoding: 'utf8',
}).replace(/from '([^']+)'/gu, (_match, specifier) =>
`from '${new URL(specifier, new URL('../wechat/intent/task-route.mjs', import.meta.url)).href}'`);
const previous = await import(`data:text/javascript;base64,${Buffer.from(source).toString('base64')}`);
const previousResults = simulate(previous.resolveWechatTaskRoute, previous.readWechatTaskContext);
report.baseline = {
commit: baseline, scope: 'historical task-route module with the same synthetic cases', total: previousResults.length,
passed: previousResults.filter((result) => result.passed).length,
failed: previousResults.filter((result) => !result.passed).length, results: previousResults,
};
}
const out = process.argv.find((arg) => arg.startsWith('--out='))?.slice(6);
if (out) await fs.writeFile(out, JSON.stringify(report, null, 2) + '\n');
for (const result of results) console.log(`${result.passed ? 'PASS' : 'FAIL'} ${result.name}`);
console.log(`Simulation: ${report.passed}/${report.total} passed, ${report.failed} failed`);
if (report.baseline) console.log(`Baseline ${baseline}: ${report.baseline.passed}/${report.baseline.total} passed`);
if (report.failed) process.exitCode = 1;
+32 -11
View File
@@ -66,6 +66,7 @@ import { classifyWechatIntent } from './wechat/intent/classifier.mjs';
import {
assertWechatTaskDeliveryTarget,
buildWechatTaskRoutePrompt,
isWechatTaskInputQuestion,
needsWechatTaskContext,
readWechatTaskContext,
resolveWechatTaskRoute,
@@ -2693,6 +2694,7 @@ export function createWechatMpService({
...(intent.taskRoute ? {
wechatTaskMode: intent.taskRoute.mode,
...(intent.taskRoute.targetPath ? { wechatTaskTarget: intent.taskRoute.targetPath } : {}),
...(intent.taskRoute.requestText ? { wechatTaskRequest: intent.taskRoute.requestText } : {}),
} : {}),
...(pgRequired ? { pgRequired: true } : {}),
},
@@ -2885,7 +2887,9 @@ export function createWechatMpService({
const agentReplyTimeoutMs = config.agentReplyTimeoutMs;
const resetCandidate =
intent.msgType === 'text' || intent.msgType === 'voice' ? intent.agentText : '';
const isPageDataRequest = isWechatPageDataTask(resetCandidate);
const taskCandidate = wechatIntent.taskRoute?.mode === 'page.continue'
? `${wechatIntent.taskRoute.requestText}\n${resetCandidate}` : resetCandidate;
const isPageDataRequest = isWechatPageDataTask(taskCandidate);
const htmlArtifactDeliveryExpected = wechatIntent.taskRoute?.mode === 'chat'
? false : shouldDeliverWechatHtmlArtifacts(wechatIntent, intent);
const allowHtmlArtifactRecovery =
@@ -2896,13 +2900,14 @@ export function createWechatMpService({
);
const sessionPageContinuation =
wechatIntent.taskRoute
? ['page.edit', 'page.from_context'].includes(wechatIntent.taskRoute.mode)
? ['page.edit', 'page.from_context', 'page.continue'].includes(wechatIntent.taskRoute.mode)
: isWechatSessionPageContinuation(wechatIntent, resetCandidate);
const imagePolicy = resolveWechatImageGenerationPolicy({
text: resetCandidate,
text: taskCandidate,
isPageGenerate: wechatIntent.kind === 'page.generate',
requireFreshPageThumbnail:
config.requireFreshPageThumbnail && !sessionPageContinuation,
config.requireFreshPageThumbnail
&& (!sessionPageContinuation || wechatIntent.taskRoute?.mode === 'page.continue'),
});
// Page Data delivery owns persistent files, datasets and two publication
// policies. Reusing a conversational route here can make a new request
@@ -3015,8 +3020,8 @@ export function createWechatMpService({
? buildPageGenerateAgentPrompt(intent, {
wantsDocx: wechatIntent.wantsDocx,
imagePolicy,
preferImmediateContext: sessionPageContinuation,
carriedSessionContent,
preferImmediateContext: sessionPageContinuation && wechatIntent.taskRoute?.mode !== 'page.continue',
carriedSessionContent: wechatIntent.taskRoute?.mode === 'page.continue' ? '' : carriedSessionContent,
})
: buildWechatAgentPrompt(intent, {
imagePolicy,
@@ -3024,7 +3029,8 @@ export function createWechatMpService({
});
const agentPrompt = [taskRoutePrompt, baseAgentPrompt].filter(Boolean).join('\n\n');
const maxImmediateContextPageAttempts =
wechatIntent.kind === 'page.generate' && sessionPageContinuation ? 2 : 1;
wechatIntent.kind === 'page.generate' && sessionPageContinuation
&& wechatIntent.taskRoute?.mode !== 'page.continue' ? 2 : 1;
let reply;
let publishArtifacts = [];
let confirmedArtifacts = [];
@@ -3226,6 +3232,21 @@ export function createWechatMpService({
hasValidLinkInReply,
});
const bareCompletionReply = isSuspiciousBareCompletionReply(reply, intent);
if (!isPageDataRequest && isWechatTaskInputQuestion(
wechatIntent.taskRoute, reply?.text, [...confirmedArtifacts, ...verifiedArtifacts, ...publishedArtifacts],
)) {
if (reply.tokenState) {
const tokenState = await resolveWechatBillingTokenState(sessionId, reply.tokenState);
await userAuth.billSessionUsage(user.userId, sessionId, tokenState, requestId);
}
const delivery = await sendCustomerServiceText(inbound.fromUserName, reply.text, user, {
deliveryPriority: 'formal_reply', sourceMsgId: intent.msgId,
});
if (delivery?.deferred) {
throw markWechatUserNotified(markWechatDeliveryDeferred(new Error('任务资料追问已排队发送')));
}
return { sessionId };
}
publishArtifacts =
effectiveHtmlDelivery || publishedArtifacts.length > 0
? selectSendableHtmlArtifacts({ verifiedArtifacts, confirmedArtifacts })
@@ -3338,7 +3359,7 @@ export function createWechatMpService({
requestId,
sessionId,
sourceMessageId: intent.msgId,
originalUserText: resetCandidate,
originalUserText: taskCandidate,
requestStartedAt,
artifacts: [...confirmedArtifacts, ...publishArtifacts],
forcePageData: isPageDataRequest,
@@ -3554,8 +3575,8 @@ export function createWechatMpService({
? buildPageGenerateAgentPrompt(intent, {
wantsDocx: wechatIntent.wantsDocx,
imagePolicy,
preferImmediateContext: retryPageContinuation,
carriedSessionContent: retryPageContinuation ? carriedSessionContent : '',
preferImmediateContext: retryPageContinuation && wechatIntent.taskRoute?.mode !== 'page.continue',
carriedSessionContent: retryPageContinuation && wechatIntent.taskRoute?.mode !== 'page.continue' ? carriedSessionContent : '',
})
: buildWechatAgentPrompt(intent, {
imagePolicy,
@@ -3731,7 +3752,7 @@ export function createWechatMpService({
requestId: retryId,
sessionId,
sourceMessageId: intent.msgId,
originalUserText: resetCandidate,
originalUserText: taskCandidate,
requestStartedAt: retryStartedAt,
artifacts: [...confirmedArtifacts, ...publishArtifacts],
forcePageData: isPageDataRequest,
+74
View File
@@ -7443,3 +7443,77 @@ test('wechat task routing isolates a new page from an existing task without carr
assert.match(prompt, /周末旅行/);
assert.doesNotMatch(prompt, /旧任务正文|咖啡店介绍|待排版正文/);
});
test('wechat multi-turn simulation collects missing page inputs and resumes the same task to a real HTML delivery', async () => {
const workspace = fs.mkdtempSync('/tmp/memind-wechat-task-simulation-');
const conversation = [];
const requests = [];
const delivered = [];
const pageUrl = 'https://example.com/MindSpace/user-1/public/coffee.html';
let activeRequestId;
let eventController;
const service = createBoundWechatService({
userAuth: {
async resolveWorkingDir() { return workspace; },
async getUserPublishLayout() { return { publishDir: workspace, displayName: 'Test', constraints: null }; },
},
submitSessionReply: async (input) => {
activeRequestId = input.requestId;
requests.push(input);
conversation.push(structuredClone(input.userMessage));
if (requests.length === 3) {
fs.mkdirSync(path.join(workspace, 'public'), { recursive: true });
fs.writeFileSync(path.join(workspace, 'public/coffee.html'), previewReadyPageHtml({ title: '山间咖啡' }));
}
const text = requests.length === 1 ? '请提供店名和地址。'
: requests.length === 2 ? '还需要电话和营业时间。' : `页面已生成:${pageUrl}`;
const message = { id: `assistant-${requests.length}`, role: 'assistant', metadata: { userVisible: true }, content: [{ type: 'text', text }] };
conversation.push(message);
const events = [];
if (requests.length === 3) {
events.push({ type: 'Message', request_id: activeRequestId, message: {
id: 'write-page', role: 'assistant', content: [{ type: 'toolRequest', toolCall: { value: {
name: 'sandbox-fs__write_file', arguments: { path: 'public/coffee.html', content: previewReadyPageHtml({ title: '山间咖啡' }) },
} } }],
} });
}
events.push({ type: 'Message', request_id: activeRequestId, message }, { type: 'Finish', request_id: activeRequestId });
eventController.enqueue(new TextEncoder().encode(events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join('')));
eventController.close();
return { ok: true };
},
sessionApiFetch: async (_id, pathname) => {
if (pathname === '/sessions/session-1') return new Response(JSON.stringify({ conversation, working_dir: workspace }));
if (pathname.endsWith('/extensions')) return new Response(JSON.stringify({ extensions: [
{ type: 'platform', name: 'developer', available_tools: ['write'] },
] }));
if (pathname.endsWith('/events')) {
return new Response(new ReadableStream({ start(controller) { eventController = controller; } }), { headers: { 'Content-Type': 'text/event-stream' } });
}
return new Response('{}');
},
wechatFetch: async (url, init) => {
if (String(url).includes('/stable_token')) return new Response(JSON.stringify({ access_token: 'test-token', expires_in: 7200 }));
if (String(url).includes('/custom/send')) delivered.push(JSON.parse(init.body).text.content);
return new Response(JSON.stringify({ errcode: 0 }));
},
});
try {
for (const [index, text] of ['做一个咖啡店介绍页面', '店名叫山间咖啡,地址是苏州工业园区', '电话是12345678,营业时间是9点到18点'].entries()) {
const result = await service.handleInboundMessage(inboundXml({ content: text, extraFields: { MsgId: `task-input-${index}` } }), {
timestamp: '1710000000', nonce: 'nonce', signature: signatureFor('token', '1710000000', 'nonce'),
});
await result.task;
}
assert.equal(requests.length, 3);
assert.deepEqual(requests.map((request) => request.sessionId), ['session-1', 'session-1', 'session-1']);
assert.deepEqual(requests.map((request) => request.userMessage.metadata.memindRun.wechatTaskMode), ['page.create', 'page.continue', 'page.continue']);
assert.equal(requests.at(-1).userMessage.metadata.memindRun.wechatTaskRequest, '做一个咖啡店介绍页面');
assert.equal(delivered[0], '请提供店名和地址。');
assert.equal(delivered[1], '还需要电话和营业时间。');
assert.ok(delivered.at(-1).includes('coffee.html'), delivered.join('\n'));
assert.equal(fs.existsSync(path.join(workspace, 'public/coffee.html')), true);
} finally {
fs.rmSync(workspace, { recursive: true, force: true });
}
});
+39
View File
@@ -0,0 +1,39 @@
const coffee = 'https://m.tkmind.cn/MindSpace/user/public/coffee.html';
const trip = 'https://m.tkmind.cn/MindSpace/user/public/trip.html';
const user = (text, mode = 'chat') => ({ role: 'user', content: [{ type: 'text', text }], metadata: {
displayText: text, memindRun: { wechatTaskMode: mode },
} });
const assistant = (text) => ({ role: 'assistant', content: [{ type: 'text', text }] });
const created = [user('做一个咖啡店介绍页面', 'page.create'), assistant(`已生成:${coffee}`)];
const interrupted = [...created, user('苏州明天天气怎么样'), assistant('明天晴,适合户外活动。')];
export const wechatTaskRouteScenarios = [
{ name: '新页面隔离旧任务', conversation: created, text: '帮我做一个徒步活动页面,时间改为周六', mode: 'page.create' },
{ name: '原页改颜色', conversation: created, text: '颜色换成绿色', mode: 'page.edit', target: 'public/coffee.html' },
{ name: '生成后补店名地址', conversation: created, text: '店名叫山间咖啡,地址是苏州工业园区', mode: 'page.edit', target: 'public/coffee.html' },
{ name: '生成前回答资料追问', conversation: [user('做一个咖啡店介绍页面', 'page.create'), assistant('请提供店名和地址。')], text: '店名叫山间咖啡,地址是苏州工业园区', mode: 'page.continue' },
{ name: '插入天气问答', conversation: created, text: '苏州明天天气怎么样', mode: 'chat' },
{ name: '跨话题明确返回原页', conversation: interrupted, text: '继续改刚才那个页面,背景换成绿色', mode: 'page.edit', target: 'public/coffee.html' },
{ name: '跨话题含糊修改先澄清', conversation: interrupted, text: '颜色换成绿色', mode: 'clarify' },
{ name: '标题中的如何不是提问', conversation: created, text: '把页面标题改成“如何选择咖啡豆”', mode: 'page.edit', target: 'public/coffee.html' },
{ name: '真正操作教程保持问答', conversation: created, text: '如何修改页面标题?', mode: 'chat' },
{ name: '写文章提到页面不是建页', conversation: created, text: '帮我写一篇如何修改页面标题的文章,不需要网页', mode: 'chat' },
{ name: '同时提供两个编辑链接先澄清', conversation: created, text: `把这两个页面标题改一下:${coffee} ${trip}`, mode: 'clarify' },
{ name: '最近回复多个页面先澄清', conversation: [assistant(`两个作品:${coffee} ${trip}`)], text: '把页面背景换成绿色', mode: 'clarify' },
{ name: '用户明确链接优先', conversation: created, text: `${trip} 标题改成周末旅行`, mode: 'page.edit', target: 'public/trip.html' },
{ name: '同链接重复不算歧义', conversation: created, text: `${trip} 修改标题,这个链接 ${trip}`, mode: 'page.edit', target: 'public/trip.html' },
{ name: '显式聊天保持聊天', conversation: created, text: '【聊天】怎么修改页面标题', mode: 'chat' },
{ name: '拒绝生成保持聊天', conversation: created, text: '不要生成页面,只告诉我方案', mode: 'chat' },
{ name: '日程修改不修改页面', conversation: created, text: '把明天的日程时间改成下午三点', mode: 'chat' },
{ name: '账号修改不修改页面', conversation: created, text: '修改密码', mode: 'chat' },
{ name: '未给目标先询问链接', conversation: [], text: '把页面标题改成山间咖啡', mode: 'clarify' },
{ name: '正文做成页面仍使用即时上下文', conversation: [assistant('春风经过山间,咖啡香在窗边停留。'.repeat(5))], text: '把刚才的诗做成页面', mode: 'page.from_context' },
{ name: '新会话重置仍由原处理器执行', conversation: created, text: '换新会话', kind: 'session.reset' },
{ name: '直接文件路径改页', conversation: created, text: '【改页】public/trip.html 更详细', mode: 'page.edit', target: 'public/trip.html' },
{ name: '等待资料时插入问题不执行页面', conversation: [user('做一个咖啡店介绍页面', 'page.create'), assistant('请提供店名和地址。')], text: '苏州明天天气怎么样', mode: 'chat' },
{ name: '等待资料时询问地址不当作资料值', conversation: [user('做一个咖啡店介绍页面', 'page.create'), assistant('请提供店名和地址。')], text: '地址是什么?', mode: 'chat' },
{ name: '补充标题可以包含如何', conversation: created, text: '标题是如何选择咖啡豆', mode: 'page.edit', target: 'public/coffee.html' },
{ name: '等待资料时新任务仍隔离', conversation: [user('做一个咖啡店介绍页面', 'page.create'), assistant('请提供店名和地址。')], text: '做一个徒步活动页面', mode: 'page.create' },
{ name: '工具内容不能顶替最近的页面', conversation: [...created, { role: 'assistant', content: [{ type: 'toolRequest', toolCall: { name: 'load_skill' } }] }], text: '背景换成绿色', mode: 'page.edit', target: 'public/coffee.html' },
{ name: '内部不可见回复不作为改页目标', conversation: [...created, { role: 'assistant', metadata: { userVisible: false }, content: `内部参考 ${trip}` }], text: '背景换成绿色', mode: 'page.edit', target: 'public/coffee.html' },
];
+76 -20
View File
@@ -1,7 +1,7 @@
import { parseWechatChannelPrefix, WECHAT_CHANNEL_PREFIX } from './channel-prefix.mjs';
import { isWechatImmediateContextPageCreate, isWechatPageRetryText, isWechatReportPageFollowup } from './page-continuation.mjs';
import { PAGE_GENERATE_NEGATION_PATTERN, wantsDocxDownload } from './patterns.mjs';
import { extractMindSpacePublicHtmlPath } from '../page-refine-target.mjs';
import { extractMindSpacePublicHtmlPath, MINDSPACE_PUBLIC_HTML_PATH_PATTERN } from '../page-refine-target.mjs';
const PAGE_SUBJECT = /(?:页面|网页|html|攻略)/iu;
const EDIT = /(?:改|调整|更新|换|优化|美化|补充|完善|添加|加上|删|去掉|缩短|加长|润色)/u;
@@ -10,29 +10,59 @@ const PROSE_EDIT = /(?:诗|文章|段落|句子|这段话|代码|密码|日程|
const EDIT_QUESTION = /(?:怎么|如何|为什么|能不能教|可以教|什么意思|什么区别)/u;
const POINTER_EDIT = /^(?:请|麻烦)?(?:把|将)?(?:这个|那个|刚才的|上面的|它).{0,8}(?:改|调整|换|优化|补充|完善)/u;
const SHORT_EDIT = /^(?:请)?(?:改|换|调整)(?:成|为).{1,20}$/u;
const FIELD_ANSWER = /^(?:店名|名称|活动名称|主题|地址|电话|联系电话|营业时间|时间|地点|价格|费用|报名方式|联系人|姓名|职位|公司|风格|配色|背景|标题|文案|颜色)(?:叫|是|为|用|[::])/u;
const RETURN_TO_PAGE = /(?:继续|回到|返回|接着).{0,10}(?:刚才|之前|上次|前面|那个|上面).{0,6}(?:页面|网页)|(?:刚才|之前|上次|前面|那个|上面).{0,6}(?:页面|网页).{0,10}(?:继续|改|修改|换|补充)/u;
const ASKS_FOR_FIELDS = /(?:请|需要|还缺|告诉我).{0,24}(?:店名|名称|地址|电话|时间|地点|价格|费用|姓名|风格|资料)|(?:店名|名称|地址|时间|地点).{0,12}(?:是什么|多少|哪里)/u;
function explicitPageTarget(text) {
return extractMindSpacePublicHtmlPath(text)
?? String(text).match(/(?:^|[\s::((])(?:文件[::]\s*)?(public\/[\w.-]+\.html)(?=$|[\s,。!?))])/u)?.[1]
?? null;
function explicitPageTargets(text) {
const fullPaths = [...String(text).matchAll(new RegExp(MINDSPACE_PUBLIC_HTML_PATH_PATTERN.source, 'giu'))]
.map((match) => match[1]);
const relativePaths = [...String(text).matchAll(/(?:^|[\s::((])(?:文件[::]\s*)?(public\/[\w.-]+\.html)(?=$|[\s,。!?))])/giu)]
.map((match) => match[1]);
return [...new Set([...fullPaths, ...relativePaths])];
}
function visibleText(message) {
return typeof message?.content === 'string' ? message.content
: Array.isArray(message?.content)
? message.content.filter((part) => part?.type === 'text').map((part) => part.text ?? '').join('\n')
: String(message?.text ?? '');
}
function isEditQuestion(body) {
const command = body.replace(/https?:\/\/[^\s<>"'))]+/gu, '').trim();
return EDIT_QUESTION.test(command)
&& !/^(?:(?:请|麻烦|帮我)\s*)*(?:把|将|修改|调整|更新|更换|改|换)/u.test(command);
}
function isFieldAnswer(body) {
if (!FIELD_ANSWER.test(body) || /[??]\s*$/u.test(body)) return false;
const value = body.replace(FIELD_ANSWER, '').trim();
return value.length > 0 && !/^(?:什么|多少|哪里|哪儿)/u.test(value);
}
/** Only immediate assistant text can supply an implicit edit target; never scan the workspace. */
export function readWechatTaskContext(conversation = []) {
const messages = Array.isArray(conversation) ? conversation.slice(-12) : [];
const last = messages.reverse().find((message) => message?.role === 'assistant');
const text = typeof last?.content === 'string' ? last.content
: Array.isArray(last?.content)
? last.content.filter((part) => part?.type === 'text').map((part) => part.text ?? '').join('\n')
: String(last?.text ?? '');
const urls = text.match(/https?:\/\/[^\s<>"'))]+/gu) ?? [];
const targets = [...new Set(urls.map(extractMindSpacePublicHtmlPath).filter(Boolean))];
return { targetPaths: targets, hasPage: targets.length > 0, hasConversation: messages.length > 0 };
const recent = [...messages].reverse();
const last = recent.find((message) => message?.role === 'assistant' && message.metadata?.userVisible !== false && visibleText(message).trim());
const targets = explicitPageTargets(visibleText(last));
const lastUser = recent.find((message) => message?.role === 'user');
const run = lastUser?.metadata?.memindRun;
const pending = ['page.create', 'page.continue', 'page.from_context'].includes(run?.wechatTaskMode)
&& targets.length === 0 && ASKS_FOR_FIELDS.test(visibleText(last));
const previousPage = recent.find((message) => message?.role === 'assistant'
&& message.metadata?.userVisible !== false && explicitPageTargets(visibleText(message)).length);
return {
targetPaths: targets, resumeTargetPaths: explicitPageTargets(visibleText(previousPage)),
hasPage: targets.length > 0, hasConversation: messages.length > 0,
...(pending ? { pendingRequest: String(run.wechatTaskRequest ?? lastUser.metadata?.displayText ?? visibleText(lastUser)).slice(0, 2000) } : {}),
};
}
export function needsWechatTaskContext(wechatIntent, text) {
const body = parseWechatChannelPrefix(text).body;
return wechatIntent?.kind === 'page.generate' || (!explicitPageTarget(body) && (
return wechatIntent?.kind === 'page.generate' || FIELD_ANSWER.test(body) || RETURN_TO_PAGE.test(body) || (!explicitPageTargets(body).length && (
isWechatImmediateContextPageCreate(wechatIntent, body)
|| isWechatPageRetryText(body)
|| (EDIT.test(body) && (PAGE_SUBJECT.test(body) || VISUAL_EDIT.test(body) || POINTER_EDIT.test(body) || SHORT_EDIT.test(body)))
@@ -48,20 +78,30 @@ export function resolveWechatTaskRoute({ wechatIntent, text, context = {} }) {
|| PAGE_GENERATE_NEGATION_PATTERN.test(body)) {
return { ...result('chat'), kind: 'chat.general', text: body };
}
const explicitTarget = explicitPageTarget(body);
const userTargets = explicitPageTargets(body);
const explicitTarget = userTargets[0];
if (!explicitTarget && !PAGE_SUBJECT.test(body) && PROSE_EDIT.test(body) && EDIT.test(body)
&& channel !== WECHAT_CHANNEL_PREFIX.PAGE) {
return { ...result('chat'), kind: 'chat.general', text: body };
}
const freshPage = /^(?:生成页面[::]\s*)?(?:(?:请|麻烦)\s*)?(?:帮我|给我)?\s*(?:新建|另外做|再做|创建|生成|制作|做)(?:一个|一张|一份|个|张|份)?\s*[^,。!?\n]{1,80}(?:页面|网页|html)/iu.test(body)
&& !isWechatImmediateContextPageCreate(wechatIntent, body);
if (freshPage && wechatIntent.kind === 'page.generate') return result('page.create', { forceNew: context.hasConversation === true });
if (freshPage && wechatIntent.kind === 'page.generate') return result('page.create', { forceNew: context.hasConversation === true, requestText: body.slice(0, 2000) });
if (context.pendingRequest && isFieldAnswer(body)) {
return {
...result('page.continue', { requestText: context.pendingRequest }),
kind: 'page.generate', topic: body, wantsDocx: wantsDocxDownload(`${context.pendingRequest}\n${body}`),
};
}
const editRequest = (explicitTarget && channel === WECHAT_CHANNEL_PREFIX.PAGE)
|| (EDIT.test(body) && !EDIT_QUESTION.test(body)
|| (isFieldAnswer(body) && context.hasPage)
|| (EDIT.test(body) && !isEditQuestion(body)
&& (PAGE_SUBJECT.test(body) || explicitTarget || VISUAL_EDIT.test(body) || POINTER_EDIT.test(body) || SHORT_EDIT.test(body)));
const retry = isWechatPageRetryText(body);
if (editRequest || retry) {
const targets = explicitTarget ? [explicitTarget] : context.targetPaths ?? [];
const targets = userTargets.length ? userTargets
: RETURN_TO_PAGE.test(body) ? context.resumeTargetPaths ?? context.targetPaths ?? []
: context.targetPaths ?? [];
if (targets.length === 1) {
return {
...result('page.edit', { targetPath: targets[0], source: explicitTarget ? 'user' : 'session' }),
@@ -80,11 +120,11 @@ export function resolveWechatTaskRoute({ wechatIntent, text, context = {} }) {
|| isWechatReportPageFollowup(wechatIntent, body)) return result('page.from_context');
// Broad legacy edit patterns must not turn password/prose edits or how-to questions into HTML jobs.
if (wechatIntent.kind === 'page.generate' && channel !== WECHAT_CHANNEL_PREFIX.PAGE
&& EDIT.test(body) && (EDIT_QUESTION.test(body) || (PROSE_EDIT.test(body) && !PAGE_SUBJECT.test(body)))) {
&& EDIT.test(body) && (isEditQuestion(body) || (PROSE_EDIT.test(body) && !PAGE_SUBJECT.test(body)))) {
return { ...result('chat'), kind: 'chat.general', text: body };
}
return result(wechatIntent.kind === 'page.generate' ? 'page.create' : 'chat',
wechatIntent.kind === 'page.generate' ? { forceNew: context.hasConversation === true } : {});
wechatIntent.kind === 'page.generate' ? { forceNew: context.hasConversation === true, requestText: body.slice(0, 2000) } : {});
}
export function buildWechatTaskRoutePrompt(taskRoute) {
@@ -100,12 +140,28 @@ export function buildWechatTaskRoutePrompt(taskRoute) {
if (taskRoute.mode === 'page.create') {
return '【本轮任务边界:新建页面】只按本轮需求新建页面;不要修改历史页面,不要把旧会话主题、正文或长期记忆当成本轮正文。';
}
if (taskRoute.mode === 'page.continue') {
return [
'【本轮任务边界:补充制作资料】用户正在回答上一轮页面任务的资料追问。',
`原始任务(用户资料):${JSON.stringify(taskRoute.requestText)}`,
'结合本轮补充继续同一个页面任务,不要当成闲聊,也不要替换为其他历史任务。',
'资料充分时完成 HTML 落盘并交付;仍缺关键信息时只询问缺失项。',
].join('\n');
}
if (taskRoute.mode === 'chat') {
return '【本轮任务边界:当前对话】只处理本条消息及其明确引用的上下文;不要因为旧页面任务自行创建或修改 HTML。';
}
return '';
}
/** A question for missing inputs is an intermediate result, never a successful page delivery. */
export function isWechatTaskInputQuestion(taskRoute, replyText, artifacts = []) {
if (!['page.create', 'page.continue'].includes(taskRoute?.mode) || artifacts.length) return false;
const text = String(replyText ?? '').trim();
return text.length > 0 && text.length <= 600 && ASKS_FOR_FIELDS.test(text)
&& !/(?:https?:\/\/|public\/|已(?:生成|完成|发布|制作)|错误|失败|error|tool_calls)/iu.test(text);
}
export function assertWechatTaskDeliveryTarget(taskRoute, artifacts = [], replyText = '') {
if (taskRoute?.mode !== 'page.edit') return;
const targets = artifacts.map((artifact) => artifact.relativePath ?? artifact.relative_path
+32
View File
@@ -4,7 +4,9 @@ import { classifyWechatIntent } from './classifier.mjs';
import {
readWechatTaskContext, resolveWechatTaskRoute, buildWechatTaskRoutePrompt,
assertWechatTaskDeliveryTarget,
isWechatTaskInputQuestion,
} from './task-route.mjs';
import { wechatTaskRouteScenarios } from './task-route-scenarios.mjs';
const page = 'https://m.tkmind.cn/MindSpace/user/public/coffee.html';
const context = readWechatTaskContext([
@@ -92,3 +94,33 @@ test('control intents remain control intents', () => {
assert.equal(route('换新会话').kind, 'session.reset');
assert.equal(route('你好').kind, 'greeting');
});
for (const scenario of wechatTaskRouteScenarios) {
test(`conversation simulation: ${scenario.name}`, () => {
const decision = route(scenario.text, readWechatTaskContext(scenario.conversation));
if (scenario.kind) assert.equal(decision.kind, scenario.kind);
else {
assert.equal(decision.taskRoute?.mode, scenario.mode);
if (scenario.target) assert.equal(decision.taskRoute.targetPath, scenario.target);
}
});
}
test('missing-input questions remain intermediate results and cannot hide completed or failed delivery', () => {
assert.equal(isWechatTaskInputQuestion({ mode: 'page.create' }, '请提供店名和地址。'), true);
assert.equal(isWechatTaskInputQuestion({ mode: 'page.continue' }, '还需要电话和营业时间。'), true);
for (const text of ['已生成,请提供店名。', '生成失败,请提供店名。', `请提供店名,页面 ${page}`, '已完成。']) {
assert.equal(isWechatTaskInputQuestion({ mode: 'page.create' }, text), false, text);
}
assert.equal(isWechatTaskInputQuestion({ mode: 'page.edit' }, '请提供店名。'), false);
assert.equal(isWechatTaskInputQuestion({ mode: 'page.create' }, '请提供店名。', [{ url: page }]), false);
});
test('answering missing inputs retains the original task and Word download requirement', () => {
const decision = route('店名叫山间咖啡', {
pendingRequest: '做一个咖啡店介绍页面,提供 Word 文档下载', hasConversation: true,
});
assert.equal(decision.taskRoute.mode, 'page.continue');
assert.equal(decision.wantsDocx, true);
assert.match(buildWechatTaskRoutePrompt(decision.taskRoute), /Word 文档下载/);
});