Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b553107817 | |||
| 065b1588b7 | |||
| 7eedda092d | |||
| 6307f974cf | |||
| 491a62aed6 | |||
| e1ad094f93 | |||
| b10f0a7600 | |||
| 31cfdf7a94 | |||
| 9b68dc6b77 |
@@ -514,6 +514,84 @@ function sanitizeFreshVerification(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function collectDeliverablePageArtifacts({
|
||||||
|
artifacts = [],
|
||||||
|
messages = [],
|
||||||
|
publishDir,
|
||||||
|
buildCanonicalUrl,
|
||||||
|
} = {}) {
|
||||||
|
const restored = restoreWorkspaceArtifacts({
|
||||||
|
artifacts,
|
||||||
|
publishDir,
|
||||||
|
buildCanonicalUrl,
|
||||||
|
});
|
||||||
|
if (restored.length > 0) return restored;
|
||||||
|
const writeArtifacts = extractPublicHtmlWriteArtifacts(
|
||||||
|
messages,
|
||||||
|
{ publishDir },
|
||||||
|
);
|
||||||
|
return restoreWorkspaceArtifacts({
|
||||||
|
artifacts: writeArtifacts.map((artifact) => ({
|
||||||
|
relativePath: artifact.relativePath,
|
||||||
|
})),
|
||||||
|
publishDir,
|
||||||
|
buildCanonicalUrl,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function acceptWorkspaceThumbnailFallback({
|
||||||
|
artifacts = [],
|
||||||
|
publishDir,
|
||||||
|
} = {}) {
|
||||||
|
const eligible = artifacts.filter((artifact) => {
|
||||||
|
const localPath = String(artifact?.localPath ?? '').trim();
|
||||||
|
return localPath && fs.existsSync(localPath) && artifact?.auxiliary !== true;
|
||||||
|
});
|
||||||
|
if (eligible.length === 0) {
|
||||||
|
return { ok: false, reason: 'missing_page_artifact', matches: [] };
|
||||||
|
}
|
||||||
|
await Promise.all(
|
||||||
|
eligible.map((artifact) =>
|
||||||
|
ensureWorkspaceHtmlThumbnail(
|
||||||
|
publishDir,
|
||||||
|
artifact.relativePath,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const withThumbnails = eligible.filter((artifact) =>
|
||||||
|
fs.existsSync(
|
||||||
|
path.join(
|
||||||
|
publishDir,
|
||||||
|
workspaceThumbnailRelativePath(artifact.relativePath),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (withThumbnails.length !== eligible.length) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
reason: 'workspace_thumbnail_fallback_failed',
|
||||||
|
matches: [],
|
||||||
|
artifact: eligible.find((artifact) =>
|
||||||
|
!fs.existsSync(
|
||||||
|
path.join(
|
||||||
|
publishDir,
|
||||||
|
workspaceThumbnailRelativePath(artifact.relativePath),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
reason: 'workspace_thumbnail_fallback',
|
||||||
|
matches: withThumbnails.map((artifact) => ({
|
||||||
|
artifact,
|
||||||
|
image: null,
|
||||||
|
cover: null,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export async function ensureWechatFreshPageThumbnailsAtWorkspace({
|
export async function ensureWechatFreshPageThumbnailsAtWorkspace({
|
||||||
artifacts = [],
|
artifacts = [],
|
||||||
images = [],
|
images = [],
|
||||||
@@ -522,12 +600,12 @@ export async function ensureWechatFreshPageThumbnailsAtWorkspace({
|
|||||||
buildCanonicalUrl,
|
buildCanonicalUrl,
|
||||||
repairEnabled = false,
|
repairEnabled = false,
|
||||||
} = {}) {
|
} = {}) {
|
||||||
const workspaceArtifacts =
|
let workspaceArtifacts = collectDeliverablePageArtifacts({
|
||||||
restoreWorkspaceArtifacts({
|
artifacts,
|
||||||
artifacts,
|
messages,
|
||||||
publishDir,
|
publishDir,
|
||||||
buildCanonicalUrl,
|
buildCanonicalUrl,
|
||||||
});
|
});
|
||||||
let verification =
|
let verification =
|
||||||
verifyFreshWechatPageThumbnails(
|
verifyFreshWechatPageThumbnails(
|
||||||
workspaceArtifacts,
|
workspaceArtifacts,
|
||||||
@@ -551,20 +629,35 @@ export async function ensureWechatFreshPageThumbnailsAtWorkspace({
|
|||||||
verification.reason,
|
verification.reason,
|
||||||
});
|
});
|
||||||
if (repair.ok) {
|
if (repair.ok) {
|
||||||
|
workspaceArtifacts = restoreWorkspaceArtifacts({
|
||||||
|
artifacts: workspaceArtifacts,
|
||||||
|
publishDir,
|
||||||
|
buildCanonicalUrl,
|
||||||
|
});
|
||||||
verification =
|
verification =
|
||||||
verifyFreshWechatPageThumbnails(
|
verifyFreshWechatPageThumbnails(
|
||||||
restoreWorkspaceArtifacts({
|
workspaceArtifacts,
|
||||||
artifacts,
|
|
||||||
publishDir,
|
|
||||||
buildCanonicalUrl,
|
|
||||||
}),
|
|
||||||
images,
|
images,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// When image_make failed or returned nothing, still deliver pages that already
|
||||||
|
// landed on disk by generating the workspace share thumbnail sidecars.
|
||||||
|
if (
|
||||||
|
!verification.ok
|
||||||
|
&& ['fresh_image_not_generated', 'missing_generated_cover', 'cover_not_from_current_run'].includes(
|
||||||
|
String(verification.reason ?? ''),
|
||||||
|
)
|
||||||
|
&& workspaceArtifacts.length > 0
|
||||||
|
) {
|
||||||
|
verification = await acceptWorkspaceThumbnailFallback({
|
||||||
|
artifacts: workspaceArtifacts,
|
||||||
|
publishDir,
|
||||||
|
});
|
||||||
|
}
|
||||||
if (verification.ok) {
|
if (verification.ok) {
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
verification.matches.map((match) =>
|
(verification.matches ?? []).map((match) =>
|
||||||
ensureWorkspaceHtmlThumbnail(
|
ensureWorkspaceHtmlThumbnail(
|
||||||
publishDir,
|
publishDir,
|
||||||
match.artifact.relativePath,
|
match.artifact.relativePath,
|
||||||
@@ -579,7 +672,7 @@ export async function ensureWechatFreshPageThumbnailsAtWorkspace({
|
|||||||
),
|
),
|
||||||
thumbnailRelativePaths:
|
thumbnailRelativePaths:
|
||||||
verification.ok
|
verification.ok
|
||||||
? verification.matches.map((match) =>
|
? (verification.matches ?? []).map((match) =>
|
||||||
workspaceThumbnailRelativePath(
|
workspaceThumbnailRelativePath(
|
||||||
match.artifact.relativePath,
|
match.artifact.relativePath,
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -271,6 +271,44 @@ test('MindSpace verifies and renders fresh WeChat page thumbnails without return
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('MindSpace falls back to workspace thumbnails when fresh image_make is missing', async (t) => {
|
||||||
|
const publishDir = fs.mkdtempSync(
|
||||||
|
path.join(
|
||||||
|
os.tmpdir(),
|
||||||
|
'mindspace-wechat-thumbnail-fallback-',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
t.after(() => {
|
||||||
|
fs.rmSync(publishDir, {
|
||||||
|
recursive: true,
|
||||||
|
force: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
const relativePath = 'public/fallback.html';
|
||||||
|
const htmlPath = path.join(publishDir, relativePath);
|
||||||
|
fs.mkdirSync(path.dirname(htmlPath), { recursive: true });
|
||||||
|
fs.writeFileSync(
|
||||||
|
htmlPath,
|
||||||
|
pageHtml({ title: 'Fallback' }),
|
||||||
|
'utf8',
|
||||||
|
);
|
||||||
|
|
||||||
|
const result = await ensureWechatFreshPageThumbnailsAtWorkspace({
|
||||||
|
publishDir,
|
||||||
|
buildCanonicalUrl: canonical,
|
||||||
|
artifacts: [{ relativePath, exists: true }],
|
||||||
|
images: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(result.ok, true);
|
||||||
|
assert.equal(result.reason, 'workspace_thumbnail_fallback');
|
||||||
|
assert.deepEqual(result.matchRelativePaths, [relativePath]);
|
||||||
|
assert.equal(
|
||||||
|
fs.existsSync(path.join(publishDir, 'public', 'fallback.thumbnail.svg')),
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
test('MindSpace owns unambiguous cover repair before thumbnail delivery', async (t) => {
|
test('MindSpace owns unambiguous cover repair before thumbnail delivery', async (t) => {
|
||||||
const publishDir = fs.mkdtempSync(
|
const publishDir = fs.mkdtempSync(
|
||||||
path.join(
|
path.join(
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
{
|
||||||
|
"id": "wechat-poem-page-modify",
|
||||||
|
"name": "写诗→做页面→修改页面(H5 多轮)",
|
||||||
|
"description": "模拟服务号常见三回合:写诗、做成页面、修改页面内容",
|
||||||
|
"account": {
|
||||||
|
"username": "john",
|
||||||
|
"password": "888888"
|
||||||
|
},
|
||||||
|
"steps": [
|
||||||
|
{
|
||||||
|
"action": "login",
|
||||||
|
"label": "登录"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"action": "chat",
|
||||||
|
"label": "请求写诗",
|
||||||
|
"message": "帮我写一首关于七月午后的短诗,四段即可",
|
||||||
|
"expect": {
|
||||||
|
"assistantMinChars": 40,
|
||||||
|
"timeoutMs": 180000,
|
||||||
|
"replyKeywords": ["七月", "午"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"action": "chat",
|
||||||
|
"label": "做成精美 HTML 页面",
|
||||||
|
"message": "生成一个精美的 HTML 页面",
|
||||||
|
"expect": {
|
||||||
|
"assistantMinChars": 20,
|
||||||
|
"timeoutMs": 300000,
|
||||||
|
"replyKeywords": ["七月", "午"],
|
||||||
|
"page": {
|
||||||
|
"keywords": ["七月", "午"],
|
||||||
|
"requirePublicLink": true,
|
||||||
|
"requireHttp200": true,
|
||||||
|
"requireMindspaceCover": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"action": "chat",
|
||||||
|
"label": "修改页面标题",
|
||||||
|
"message": "把页面标题改成《七月的午后》",
|
||||||
|
"expect": {
|
||||||
|
"assistantMinChars": 10,
|
||||||
|
"timeoutMs": 300000,
|
||||||
|
"replyKeywords": ["七月"],
|
||||||
|
"page": {
|
||||||
|
"keywords": ["七月的午后", "七月"],
|
||||||
|
"requirePublicLink": true,
|
||||||
|
"requireHttp200": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -46,6 +46,11 @@ usage() {
|
|||||||
6. 启动 Portal,保持旧端口 8081
|
6. 启动 Portal,保持旧端口 8081
|
||||||
7. 健康检查通过后重启 m.tkmind.cn 反向隧道 (105:19081 -> 103:8081)
|
7. 健康检查通过后重启 m.tkmind.cn 反向隧道 (105:19081 -> 103:8081)
|
||||||
8. 旧源码目录移入 archive,不再保留可运行 live 源码
|
8. 旧源码目录移入 archive,不再保留可运行 live 源码
|
||||||
|
|
||||||
|
环境变量:
|
||||||
|
ALLOW_DIRECT_STABLE_RELEASE=1
|
||||||
|
仅在用户明确批准按 7/23 前规则直接整包时使用:允许 --skip-tests,
|
||||||
|
并跳过 canary 晋升证据与 Core+Impact Gate report。
|
||||||
EOF
|
EOF
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,9 +73,17 @@ while [[ $# -gt 0 ]]; do
|
|||||||
shift
|
shift
|
||||||
done
|
done
|
||||||
|
|
||||||
|
say() {
|
||||||
|
printf '\n[%s] %s\n' "$(date +%H:%M:%S)" "$*"
|
||||||
|
}
|
||||||
|
|
||||||
if [[ "${SKIP_TESTS}" -eq 1 ]]; then
|
if [[ "${SKIP_TESTS}" -eq 1 ]]; then
|
||||||
echo "生产发布守门员禁止 --skip-tests。" >&2
|
if [[ "${ALLOW_DIRECT_STABLE_RELEASE:-0}" == "1" ]]; then
|
||||||
exit 1
|
say "允许 --skip-tests(ALLOW_DIRECT_STABLE_RELEASE=1,按 7/23 前直接整包规则;测试须已在发布前手动跑过)"
|
||||||
|
else
|
||||||
|
echo "生产发布守门员禁止 --skip-tests。" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [[ "${ALLOW_PORTAL_RELEASE_SCOPE_BYPASS:-0}" == "1" ]]; then
|
if [[ "${ALLOW_PORTAL_RELEASE_SCOPE_BYPASS:-0}" == "1" ]]; then
|
||||||
@@ -84,14 +97,14 @@ if [[ "${ALLOW_MINDSPACE_PUBLIC_LINK_ISSUES:-0}" == "1" ]]; then
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
if [[ "${DRY_RUN}" -eq 0 ]]; then
|
if [[ "${DRY_RUN}" -eq 0 ]]; then
|
||||||
say "验证 103 灰度晋升证据"
|
if [[ "${ALLOW_DIRECT_STABLE_RELEASE:-0}" == "1" ]]; then
|
||||||
node "${ROOT}/scripts/verify-canary-promotion-evidence.mjs" --host "${HOST}"
|
say "跳过灰度晋升证据(ALLOW_DIRECT_STABLE_RELEASE=1,按 7/23 前直接整包规则)"
|
||||||
|
else
|
||||||
|
say "验证 103 灰度晋升证据"
|
||||||
|
node "${ROOT}/scripts/verify-canary-promotion-evidence.mjs" --host "${HOST}"
|
||||||
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
say() {
|
|
||||||
printf '\n[%s] %s\n' "$(date +%H:%M:%S)" "$*"
|
|
||||||
}
|
|
||||||
|
|
||||||
need_cmd() {
|
need_cmd() {
|
||||||
command -v "$1" >/dev/null 2>&1 || {
|
command -v "$1" >/dev/null 2>&1 || {
|
||||||
echo "缺少命令: $1" >&2
|
echo "缺少命令: $1" >&2
|
||||||
@@ -336,7 +349,9 @@ REMOTE
|
|||||||
}
|
}
|
||||||
|
|
||||||
say "验证与当前 main 和 runtime artifact 绑定的 Gate report"
|
say "验证与当前 main 和 runtime artifact 绑定的 Gate report"
|
||||||
if ! node "${ROOT}/scripts/verify-release-gate-report.mjs" --artifact "${RUNTIME_ROOT}" >/dev/null 2>&1; then
|
if [[ "${ALLOW_DIRECT_STABLE_RELEASE:-0}" == "1" ]]; then
|
||||||
|
say "跳过 Core+Impact Gate report(ALLOW_DIRECT_STABLE_RELEASE=1,按 7/23 前直接整包规则)"
|
||||||
|
elif ! node "${ROOT}/scripts/verify-release-gate-report.mjs" --artifact "${RUNTIME_ROOT}" >/dev/null 2>&1; then
|
||||||
say "执行核心场景 + 变更影响域 Gate"
|
say "执行核心场景 + 变更影响域 Gate"
|
||||||
DEPLOYED_SHA="${MEMIND_RELEASE_BASE_COMMIT:-}"
|
DEPLOYED_SHA="${MEMIND_RELEASE_BASE_COMMIT:-}"
|
||||||
if [[ -z "${DEPLOYED_SHA}" && "${DRY_RUN}" -ne 1 ]]; then
|
if [[ -z "${DEPLOYED_SHA}" && "${DRY_RUN}" -ne 1 ]]; then
|
||||||
@@ -351,8 +366,10 @@ if ! node "${ROOT}/scripts/verify-release-gate-report.mjs" --artifact "${RUNTIME
|
|||||||
IMPACT_ARGS+=(--deployed-commit "${DEPLOYED_SHA}")
|
IMPACT_ARGS+=(--deployed-commit "${DEPLOYED_SHA}")
|
||||||
fi
|
fi
|
||||||
node "${ROOT}/scripts/run-release-gate-impact.mjs" "${IMPACT_ARGS[@]}"
|
node "${ROOT}/scripts/run-release-gate-impact.mjs" "${IMPACT_ARGS[@]}"
|
||||||
|
node "${ROOT}/scripts/verify-release-gate-report.mjs" --artifact "${RUNTIME_ROOT}"
|
||||||
|
else
|
||||||
|
node "${ROOT}/scripts/verify-release-gate-report.mjs" --artifact "${RUNTIME_ROOT}"
|
||||||
fi
|
fi
|
||||||
node "${ROOT}/scripts/verify-release-gate-report.mjs" --artifact "${RUNTIME_ROOT}"
|
|
||||||
|
|
||||||
if [[ "${DRY_RUN}" -ne 1 ]]; then
|
if [[ "${DRY_RUN}" -ne 1 ]]; then
|
||||||
say "执行 103 只读预检"
|
say "执行 103 只读预检"
|
||||||
@@ -415,7 +432,7 @@ remount_goosed_after_live_swap() {
|
|||||||
local docker_bin="/opt/homebrew/bin/docker"
|
local docker_bin="/opt/homebrew/bin/docker"
|
||||||
local compose_dir="/Users/john/Project/goosed-prod"
|
local compose_dir="/Users/john/Project/goosed-prod"
|
||||||
local compose_file="${compose_dir}/docker-compose.prod.yml"
|
local compose_file="${compose_dir}/docker-compose.prod.yml"
|
||||||
local marker_rel="MindSpace/.goosed-remount-${RELEASE_ID}"
|
local marker_rel=".goosed-remount-${RELEASE_ID}"
|
||||||
local marker_host="${APP_DIR}/${marker_rel}"
|
local marker_host="${APP_DIR}/${marker_rel}"
|
||||||
local marker_value="${RELEASE_ID}-$(date +%s)"
|
local marker_value="${RELEASE_ID}-$(date +%s)"
|
||||||
local ready=0
|
local ready=0
|
||||||
@@ -425,7 +442,7 @@ remount_goosed_after_live_swap() {
|
|||||||
return 1
|
return 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
mkdir -p "${APP_DIR}/MindSpace"
|
mkdir -p "${APP_DIR}"
|
||||||
printf '%s\n' "${marker_value}" > "${marker_host}"
|
printf '%s\n' "${marker_value}" > "${marker_host}"
|
||||||
|
|
||||||
say "重建 goosed 容器以刷新 Portal/MindSpace bind mount"
|
say "重建 goosed 容器以刷新 Portal/MindSpace bind mount"
|
||||||
@@ -441,7 +458,9 @@ remount_goosed_after_live_swap() {
|
|||||||
local healthy=1
|
local healthy=1
|
||||||
local containers=()
|
local containers=()
|
||||||
while IFS= read -r container; do
|
while IFS= read -r container; do
|
||||||
[[ -n "${container}" ]] && containers+=("${container}")
|
# Exclude canary/other services that share the compose project label.
|
||||||
|
[[ "${container}" =~ ^goosed-prod-[1-9]$ ]] || continue
|
||||||
|
containers+=("${container}")
|
||||||
done < <("${docker_bin}" ps \
|
done < <("${docker_bin}" ps \
|
||||||
--filter 'label=com.docker.compose.project=goosed-prod' \
|
--filter 'label=com.docker.compose.project=goosed-prod' \
|
||||||
--format '{{.Names}}')
|
--format '{{.Names}}')
|
||||||
@@ -458,8 +477,15 @@ remount_goosed_after_live_swap() {
|
|||||||
healthy=0
|
healthy=0
|
||||||
continue
|
continue
|
||||||
fi
|
fi
|
||||||
|
local portal_source
|
||||||
|
portal_source="$("${docker_bin}" inspect "${container}" --format '{{range .Mounts}}{{if eq .Destination "/opt/portal"}}{{.Source}}{{end}}{{end}}' 2>/dev/null || true)"
|
||||||
|
if [[ "${portal_source}" != "${APP_DIR}" ]]; then
|
||||||
|
healthy=0
|
||||||
|
continue
|
||||||
|
fi
|
||||||
local observed
|
local observed
|
||||||
observed="$("${docker_bin}" exec "${container}" sh -lc "cat '${APP_DIR}/${marker_rel}'" 2>/dev/null || true)"
|
# Prefer /opt/portal marker (same bind as PORTAL_RUNTIME_DIR) over nested MindSpace.
|
||||||
|
observed="$("${docker_bin}" exec "${container}" sh -lc "cat '/opt/portal/${marker_rel}'" 2>/dev/null || true)"
|
||||||
if [[ "${observed}" != "${marker_value}" ]]; then
|
if [[ "${observed}" != "${marker_value}" ]]; then
|
||||||
healthy=0
|
healthy=0
|
||||||
fi
|
fi
|
||||||
|
|||||||
@@ -0,0 +1,155 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* Matrix test for WeChat page phrasing: intent, session continuation, delivery policy.
|
||||||
|
* Run: node scripts/verify-wechat-page-phrasing.mjs
|
||||||
|
*/
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { classifyWechatIntent } from '../wechat/intent/classifier.mjs';
|
||||||
|
import {
|
||||||
|
isWechatSessionPageContinuation,
|
||||||
|
isWechatImmediateContextPageCreate,
|
||||||
|
} from '../wechat/intent/page-continuation.mjs';
|
||||||
|
import { resolveWechatImageGenerationPolicy, WECHAT_PAGE_THUMBNAIL_MODE } from '../wechat/image-generation-policy.mjs';
|
||||||
|
import {
|
||||||
|
isWechatImmediateContextFollowup,
|
||||||
|
shouldDeliverWechatHtmlArtifacts,
|
||||||
|
} from '../wechat-mp.mjs';
|
||||||
|
import { buildPageGenerateAgentPrompt } from '../wechat/prompts/page-generate.mjs';
|
||||||
|
import { buildWechatAgentPrompt } from '../wechat/prompts/chat-general.mjs';
|
||||||
|
|
||||||
|
const cases = [
|
||||||
|
{
|
||||||
|
label: '完整单条页面需求',
|
||||||
|
text: '帮我做一个上海旅游攻略页面',
|
||||||
|
expect: {
|
||||||
|
kind: 'page.generate',
|
||||||
|
continuation: false,
|
||||||
|
freshThumbnail: true,
|
||||||
|
deliverHtml: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: '写诗(普通聊天)',
|
||||||
|
text: '帮我写一首诗吧',
|
||||||
|
expect: {
|
||||||
|
kind: 'chat.general',
|
||||||
|
continuation: false,
|
||||||
|
freshThumbnail: false,
|
||||||
|
deliverHtml: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: '短指代做成页面',
|
||||||
|
text: '把刚才的诗做成页面',
|
||||||
|
expect: {
|
||||||
|
kind: 'page.generate',
|
||||||
|
continuation: true,
|
||||||
|
freshThumbnail: false,
|
||||||
|
deliverHtml: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: '精美 HTML 页面',
|
||||||
|
text: '生成一个精美的 HTML 页面',
|
||||||
|
expect: {
|
||||||
|
kind: 'page.generate',
|
||||||
|
continuation: true,
|
||||||
|
freshThumbnail: false,
|
||||||
|
deliverHtml: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: '重试上次页面',
|
||||||
|
text: '重试上次页面',
|
||||||
|
expect: {
|
||||||
|
kind: 'page.generate',
|
||||||
|
continuation: true,
|
||||||
|
freshThumbnail: false,
|
||||||
|
deliverHtml: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: '修改刚才页面样式',
|
||||||
|
text: '修改刚才生成的页面,背景改成浅蓝色',
|
||||||
|
expect: {
|
||||||
|
kind: 'page.generate',
|
||||||
|
continuation: true,
|
||||||
|
freshThumbnail: false,
|
||||||
|
deliverHtml: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: '改页面标题',
|
||||||
|
text: '把页面标题改成《七月清晨》',
|
||||||
|
expect: {
|
||||||
|
kind: 'page.generate',
|
||||||
|
continuation: true,
|
||||||
|
freshThumbnail: false,
|
||||||
|
deliverHtml: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: '改诗内容(会话续作)',
|
||||||
|
text: '把诗里第三段改长一点',
|
||||||
|
expect: {
|
||||||
|
kind: 'chat.general',
|
||||||
|
continuation: true,
|
||||||
|
freshThumbnail: false,
|
||||||
|
deliverHtml: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
let passed = 0;
|
||||||
|
let failed = 0;
|
||||||
|
|
||||||
|
for (const item of cases) {
|
||||||
|
const intent = { msgType: 'text', agentText: item.text, displayText: item.text };
|
||||||
|
const wechatIntent = classifyWechatIntent(intent);
|
||||||
|
const continuation = isWechatSessionPageContinuation(wechatIntent, item.text);
|
||||||
|
const policy = resolveWechatImageGenerationPolicy({
|
||||||
|
text: item.text,
|
||||||
|
isPageGenerate: wechatIntent.kind === 'page.generate',
|
||||||
|
requireFreshPageThumbnail: continuation ? false : true,
|
||||||
|
});
|
||||||
|
const deliverHtml = shouldDeliverWechatHtmlArtifacts(wechatIntent, intent);
|
||||||
|
const errors = [];
|
||||||
|
if (wechatIntent.kind !== item.expect.kind) {
|
||||||
|
errors.push(`kind expected ${item.expect.kind}, got ${wechatIntent.kind}`);
|
||||||
|
}
|
||||||
|
if (continuation !== item.expect.continuation) {
|
||||||
|
errors.push(`continuation expected ${item.expect.continuation}, got ${continuation}`);
|
||||||
|
}
|
||||||
|
const freshRequired = policy.pageThumbnailMode === WECHAT_PAGE_THUMBNAIL_MODE.REQUIRED_FRESH;
|
||||||
|
if (freshRequired !== item.expect.freshThumbnail) {
|
||||||
|
errors.push(`freshThumbnail expected ${item.expect.freshThumbnail}, got ${freshRequired}`);
|
||||||
|
}
|
||||||
|
if (deliverHtml !== item.expect.deliverHtml) {
|
||||||
|
errors.push(`deliverHtml expected ${item.expect.deliverHtml}, got ${deliverHtml}`);
|
||||||
|
}
|
||||||
|
if (item.expect.continuation && wechatIntent.kind === 'page.generate') {
|
||||||
|
const prompt = buildPageGenerateAgentPrompt(intent, {
|
||||||
|
preferImmediateContext: continuation,
|
||||||
|
imagePolicy: policy,
|
||||||
|
});
|
||||||
|
if (!/即时上下文优先/.test(prompt)) errors.push('page prompt missing immediate context block');
|
||||||
|
if (!/write_file 硬门槛/.test(prompt)) errors.push('page prompt missing write_file gate');
|
||||||
|
}
|
||||||
|
if (item.expect.continuation && wechatIntent.kind === 'chat.general') {
|
||||||
|
const prompt = buildWechatAgentPrompt(intent, { preferSessionPageContinuation: continuation });
|
||||||
|
if (!/会话页面续作/.test(prompt)) errors.push('chat prompt missing session continuation block');
|
||||||
|
}
|
||||||
|
if (errors.length) {
|
||||||
|
failed += 1;
|
||||||
|
console.error(`✘ ${item.label}: ${errors.join('; ')}`);
|
||||||
|
} else {
|
||||||
|
passed += 1;
|
||||||
|
console.log(`✔ ${item.label}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.equal(isWechatImmediateContextFollowup({ kind: 'page.generate' }, '把刚才的诗做成页面'), true);
|
||||||
|
assert.equal(isWechatImmediateContextPageCreate({ kind: 'page.generate' }, '生成一个精美的 HTML 页面'), true);
|
||||||
|
|
||||||
|
console.log(`\n=== 汇总: ${passed}/${cases.length} 话术矩阵通过 ===`);
|
||||||
|
if (failed > 0) process.exit(1);
|
||||||
+354
-165
@@ -31,6 +31,11 @@ import {
|
|||||||
isPageDataDevIntent,
|
isPageDataDevIntent,
|
||||||
isPageDataIntent,
|
isPageDataIntent,
|
||||||
} from './chat-skills.mjs';
|
} from './chat-skills.mjs';
|
||||||
|
import {
|
||||||
|
isWechatImmediateContextPageCreate,
|
||||||
|
isWechatSessionPageContinuation,
|
||||||
|
isWechatContentEditFollowup,
|
||||||
|
} from './wechat/intent/page-continuation.mjs';
|
||||||
import { resolvePageGenerateOutcome } from './wechat/handlers/page-generate.mjs';
|
import { resolvePageGenerateOutcome } from './wechat/handlers/page-generate.mjs';
|
||||||
import {
|
import {
|
||||||
buildWechatImageRunMetadata,
|
buildWechatImageRunMetadata,
|
||||||
@@ -40,6 +45,7 @@ import {
|
|||||||
import { buildWechatAgentPrompt } from './wechat/prompts/chat-general.mjs';
|
import { buildWechatAgentPrompt } from './wechat/prompts/chat-general.mjs';
|
||||||
import {
|
import {
|
||||||
buildPageGenerateAgentPrompt,
|
buildPageGenerateAgentPrompt,
|
||||||
|
buildImmediateContextPageRepairPrompt,
|
||||||
buildPagePublishFailureText,
|
buildPagePublishFailureText,
|
||||||
} from './wechat/prompts/page-generate.mjs';
|
} from './wechat/prompts/page-generate.mjs';
|
||||||
import {
|
import {
|
||||||
@@ -974,6 +980,27 @@ export function shouldForceNewWechatAgentSession(wechatIntent, resetCandidate) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function isWechatImmediateContextFollowup(wechatIntent, text) {
|
||||||
|
return isWechatImmediateContextPageCreate(wechatIntent, text);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { isWechatSessionPageContinuation };
|
||||||
|
|
||||||
|
export function shouldRotateUnlinkedWechatRoute({
|
||||||
|
routeUpdatedAt,
|
||||||
|
wechatMessageCount,
|
||||||
|
snapshotMessageCount,
|
||||||
|
now = Date.now(),
|
||||||
|
} = {}) {
|
||||||
|
const updatedAt = Number(routeUpdatedAt ?? 0);
|
||||||
|
return (
|
||||||
|
updatedAt > 0 &&
|
||||||
|
Number(now) - updatedAt > 60_000 &&
|
||||||
|
Number(wechatMessageCount) === 0 &&
|
||||||
|
Number(snapshotMessageCount ?? 0) > 0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function isWechatPageDataTask(text) {
|
export function isWechatPageDataTask(text) {
|
||||||
return isPageDataIntent(text) || isPageDataDevIntent(text);
|
return isPageDataIntent(text) || isPageDataDevIntent(text);
|
||||||
}
|
}
|
||||||
@@ -994,10 +1021,12 @@ export function isRecoverableWechatAgentSessionError(message) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function shouldDeliverWechatHtmlArtifacts(wechatIntent, intent) {
|
export function shouldDeliverWechatHtmlArtifacts(wechatIntent, intent) {
|
||||||
|
const text = String(intent?.agentText ?? intent?.displayText ?? '').trim();
|
||||||
return (
|
return (
|
||||||
wechatIntent?.kind === 'page.generate'
|
wechatIntent?.kind === 'page.generate'
|
||||||
|| looksLikeHtmlGenerationIntent(intent?.agentText)
|
|| looksLikeHtmlGenerationIntent(text)
|
||||||
|| isPageDataIntent(intent?.agentText)
|
|| isPageDataIntent(text)
|
||||||
|
|| (wechatIntent?.kind === 'chat.general' && isWechatContentEditFollowup(text))
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1837,7 +1866,9 @@ export function createWechatMpService({
|
|||||||
imagePolicy,
|
imagePolicy,
|
||||||
notifyFailure = true,
|
notifyFailure = true,
|
||||||
}) => {
|
}) => {
|
||||||
if (imagePolicy?.pageThumbnailMode !== WECHAT_PAGE_THUMBNAIL_MODE.REQUIRED_FRESH) return;
|
if (imagePolicy?.pageThumbnailMode !== WECHAT_PAGE_THUMBNAIL_MODE.REQUIRED_FRESH) {
|
||||||
|
return { ok: true, reason: null, matchRelativePaths: [] };
|
||||||
|
}
|
||||||
const images = collectWechatGeneratedImages(replyRequestMessages(reply));
|
const images = collectWechatGeneratedImages(replyRequestMessages(reply));
|
||||||
const ensureFresh =
|
const ensureFresh =
|
||||||
htmlDeliveryAuthority
|
htmlDeliveryAuthority
|
||||||
@@ -1884,7 +1915,15 @@ export function createWechatMpService({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (verification?.ok) {
|
if (verification?.ok) {
|
||||||
return;
|
if (verification.reason === 'workspace_thumbnail_fallback') {
|
||||||
|
logger.info?.(
|
||||||
|
'WeChat MP page delivery accepted workspace thumbnail fallback:',
|
||||||
|
{
|
||||||
|
matchRelativePaths: verification.matchRelativePaths ?? [],
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return verification;
|
||||||
}
|
}
|
||||||
logger.warn?.(
|
logger.warn?.(
|
||||||
'WeChat MP fresh thumbnail verification failed:',
|
'WeChat MP fresh thumbnail verification failed:',
|
||||||
@@ -1960,6 +1999,7 @@ export function createWechatMpService({
|
|||||||
userId,
|
userId,
|
||||||
openid,
|
openid,
|
||||||
forceNew = false,
|
forceNew = false,
|
||||||
|
retainUnlinkedRoute = false,
|
||||||
userContext = null,
|
userContext = null,
|
||||||
}) => {
|
}) => {
|
||||||
if (forceNew) {
|
if (forceNew) {
|
||||||
@@ -1978,42 +2018,58 @@ export function createWechatMpService({
|
|||||||
config.sessionIdleRotateMs > 0 &&
|
config.sessionIdleRotateMs > 0 &&
|
||||||
routeUpdatedAt > 0 &&
|
routeUpdatedAt > 0 &&
|
||||||
now - routeUpdatedAt > config.sessionIdleRotateMs;
|
now - routeUpdatedAt > config.sessionIdleRotateMs;
|
||||||
|
let routeWechatMessageCount = null;
|
||||||
|
let routeSnapshotMessageCount = null;
|
||||||
let routeMessageCount = 0;
|
let routeMessageCount = 0;
|
||||||
if (config.sessionMessageRotateCount > 0) {
|
if (config.sessionMessageRotateCount > 0) {
|
||||||
const counts = [];
|
[routeWechatMessageCount, routeSnapshotMessageCount] = await Promise.all([
|
||||||
if (typeof userAuth.countWechatAgentSessionMessages === 'function') {
|
typeof userAuth.countWechatAgentSessionMessages === 'function'
|
||||||
counts.push(
|
? userAuth
|
||||||
userAuth
|
.countWechatAgentSessionMessages({
|
||||||
.countWechatAgentSessionMessages({
|
appId: config.appId,
|
||||||
appId: config.appId,
|
openid,
|
||||||
openid,
|
agentSessionId: existingRoute.agentSessionId,
|
||||||
agentSessionId: existingRoute.agentSessionId,
|
})
|
||||||
})
|
.then((value) => Number(value) || 0)
|
||||||
.catch((err) => {
|
.catch((err) => {
|
||||||
logger.warn?.('WeChat MP route message count lookup failed:', err);
|
logger.warn?.('WeChat MP route message count lookup failed:', err);
|
||||||
return 0;
|
return null;
|
||||||
}),
|
})
|
||||||
);
|
: null,
|
||||||
}
|
typeof userAuth.getWechatAgentSessionSnapshotMessageCount === 'function'
|
||||||
if (typeof userAuth.getWechatAgentSessionSnapshotMessageCount === 'function') {
|
? userAuth
|
||||||
counts.push(
|
.getWechatAgentSessionSnapshotMessageCount(existingRoute.agentSessionId)
|
||||||
userAuth
|
.then((value) => Number(value) || 0)
|
||||||
.getWechatAgentSessionSnapshotMessageCount(existingRoute.agentSessionId)
|
.catch((err) => {
|
||||||
.catch((err) => {
|
logger.warn?.('WeChat MP snapshot message count lookup failed:', err);
|
||||||
logger.warn?.('WeChat MP snapshot message count lookup failed:', err);
|
return null;
|
||||||
return 0;
|
})
|
||||||
}),
|
: null,
|
||||||
);
|
]);
|
||||||
}
|
routeMessageCount = Math.max(
|
||||||
if (counts.length > 0) {
|
0,
|
||||||
const resolved = await Promise.all(counts);
|
Number(routeWechatMessageCount) || 0,
|
||||||
routeMessageCount = Math.max(0, ...resolved.map((value) => Number(value) || 0));
|
Number(routeSnapshotMessageCount) || 0,
|
||||||
}
|
);
|
||||||
}
|
}
|
||||||
const routeIsTooLong =
|
const routeIsTooLong =
|
||||||
config.sessionMessageRotateCount > 0 &&
|
config.sessionMessageRotateCount > 0 &&
|
||||||
Number(routeMessageCount ?? 0) >= config.sessionMessageRotateCount;
|
Number(routeMessageCount ?? 0) >= config.sessionMessageRotateCount;
|
||||||
if (routeIsIdle || routeIsTooLong) {
|
const routeHasUnlinkedConversation = shouldRotateUnlinkedWechatRoute({
|
||||||
|
routeUpdatedAt,
|
||||||
|
wechatMessageCount: routeWechatMessageCount,
|
||||||
|
snapshotMessageCount: routeSnapshotMessageCount,
|
||||||
|
now,
|
||||||
|
});
|
||||||
|
const shouldRotateUnlinkedRoute =
|
||||||
|
routeHasUnlinkedConversation && !retainUnlinkedRoute;
|
||||||
|
if (routeIsIdle || routeIsTooLong || shouldRotateUnlinkedRoute) {
|
||||||
|
if (shouldRotateUnlinkedRoute) {
|
||||||
|
logger.warn?.('WeChat MP orphaned route rotated before reuse:', {
|
||||||
|
agentSessionId: existingRoute.agentSessionId,
|
||||||
|
snapshotMessageCount: routeSnapshotMessageCount,
|
||||||
|
});
|
||||||
|
}
|
||||||
await userAuth.clearWechatAgentRoute(config.appId, openid);
|
await userAuth.clearWechatAgentRoute(config.appId, openid);
|
||||||
rememberedWechatContexts.delete(existingRoute.agentSessionId);
|
rememberedWechatContexts.delete(existingRoute.agentSessionId);
|
||||||
} else {
|
} else {
|
||||||
@@ -2271,7 +2327,12 @@ export function createWechatMpService({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const prepareWechatAgentUserMessage = async ({ userId, sessionId, userMessage }) => {
|
const prepareWechatAgentUserMessage = async ({
|
||||||
|
userId,
|
||||||
|
sessionId,
|
||||||
|
userMessage,
|
||||||
|
preserveAgentPrompt = false,
|
||||||
|
}) => {
|
||||||
if (
|
if (
|
||||||
!chatIntentRouter?.resolveAgentMemoryContext
|
!chatIntentRouter?.resolveAgentMemoryContext
|
||||||
|| !chatIntentRouter?.applyAgentOrchestration
|
|| !chatIntentRouter?.applyAgentOrchestration
|
||||||
@@ -2296,8 +2357,17 @@ export function createWechatMpService({
|
|||||||
) {
|
) {
|
||||||
return userMessage;
|
return userMessage;
|
||||||
}
|
}
|
||||||
return chatIntentRouter.applyAgentOrchestration(
|
const orchestrationMessage = preserveAgentPrompt
|
||||||
userMessage,
|
? {
|
||||||
|
...userMessage,
|
||||||
|
metadata: {
|
||||||
|
...(userMessage?.metadata ?? {}),
|
||||||
|
displayText: messageVisibleText(userMessage),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: userMessage;
|
||||||
|
const prepared = chatIntentRouter.applyAgentOrchestration(
|
||||||
|
orchestrationMessage,
|
||||||
{
|
{
|
||||||
route: 'agent_orchestration',
|
route: 'agent_orchestration',
|
||||||
reason: '微信服务号消息由 Agent 处理',
|
reason: '微信服务号消息由 Agent 处理',
|
||||||
@@ -2305,6 +2375,14 @@ export function createWechatMpService({
|
|||||||
},
|
},
|
||||||
{ memoryContext },
|
{ memoryContext },
|
||||||
);
|
);
|
||||||
|
if (!preserveAgentPrompt) return prepared;
|
||||||
|
return {
|
||||||
|
...prepared,
|
||||||
|
metadata: {
|
||||||
|
...(prepared?.metadata ?? {}),
|
||||||
|
displayText: displayText || undefined,
|
||||||
|
},
|
||||||
|
};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.warn?.(
|
logger.warn?.(
|
||||||
'WeChat MP agent memory resolve skipped:',
|
'WeChat MP agent memory resolve skipped:',
|
||||||
@@ -2361,22 +2439,26 @@ export function createWechatMpService({
|
|||||||
const agentReplyTimeoutMs = reliabilityEnabled ? config.agentReplyTimeoutMs : 0;
|
const agentReplyTimeoutMs = reliabilityEnabled ? config.agentReplyTimeoutMs : 0;
|
||||||
const resetCandidate =
|
const resetCandidate =
|
||||||
intent.msgType === 'text' || intent.msgType === 'voice' ? intent.agentText : '';
|
intent.msgType === 'text' || intent.msgType === 'voice' ? intent.agentText : '';
|
||||||
|
const isPageDataRequest = isWechatPageDataTask(resetCandidate);
|
||||||
|
const htmlArtifactDeliveryExpected = shouldDeliverWechatHtmlArtifacts(wechatIntent, intent);
|
||||||
|
const sessionPageContinuation =
|
||||||
|
isWechatSessionPageContinuation(wechatIntent, resetCandidate);
|
||||||
const imagePolicy = resolveWechatImageGenerationPolicy({
|
const imagePolicy = resolveWechatImageGenerationPolicy({
|
||||||
text: resetCandidate,
|
text: resetCandidate,
|
||||||
isPageGenerate: wechatIntent.kind === 'page.generate',
|
isPageGenerate: wechatIntent.kind === 'page.generate',
|
||||||
requireFreshPageThumbnail: config.requireFreshPageThumbnail,
|
requireFreshPageThumbnail:
|
||||||
|
config.requireFreshPageThumbnail && !sessionPageContinuation,
|
||||||
});
|
});
|
||||||
// Page Data delivery owns persistent files, datasets and two publication
|
// Page Data delivery owns persistent files, datasets and two publication
|
||||||
// policies. Reusing a conversational route here can make a new request
|
// policies. Reusing a conversational route here can make a new request
|
||||||
// inspect/retry unrelated historical pages from that session.
|
// inspect/retry unrelated historical pages from that session.
|
||||||
const isPageDataRequest = isWechatPageDataTask(resetCandidate);
|
|
||||||
const htmlArtifactDeliveryExpected = shouldDeliverWechatHtmlArtifacts(wechatIntent, intent);
|
|
||||||
const forceNew = shouldForceNewWechatAgentSession(wechatIntent, resetCandidate);
|
const forceNew = shouldForceNewWechatAgentSession(wechatIntent, resetCandidate);
|
||||||
let route = await ensureWechatAgentSession({
|
let route = await ensureWechatAgentSession({
|
||||||
userId: user.userId,
|
userId: user.userId,
|
||||||
openid: inbound.fromUserName,
|
openid: inbound.fromUserName,
|
||||||
userContext: user,
|
userContext: user,
|
||||||
forceNew,
|
forceNew,
|
||||||
|
retainUnlinkedRoute: sessionPageContinuation,
|
||||||
});
|
});
|
||||||
let sessionId = route.sessionId;
|
let sessionId = route.sessionId;
|
||||||
await ensureSessionProvider(sessionId);
|
await ensureSessionProvider(sessionId);
|
||||||
@@ -2417,136 +2499,171 @@ export function createWechatMpService({
|
|||||||
? buildPageGenerateAgentPrompt(intent, {
|
? buildPageGenerateAgentPrompt(intent, {
|
||||||
wantsDocx: wechatIntent.wantsDocx,
|
wantsDocx: wechatIntent.wantsDocx,
|
||||||
imagePolicy,
|
imagePolicy,
|
||||||
|
preferImmediateContext: sessionPageContinuation,
|
||||||
})
|
})
|
||||||
: buildWechatAgentPrompt(intent, { imagePolicy });
|
: buildWechatAgentPrompt(intent, {
|
||||||
const reply = await executeSessionReply(
|
imagePolicy,
|
||||||
(pathname, init) => fetchForSession(sessionId, pathname, init),
|
preferSessionPageContinuation: sessionPageContinuation,
|
||||||
sessionId,
|
});
|
||||||
requestId,
|
const maxImmediateContextPageAttempts =
|
||||||
agentPrompt,
|
wechatIntent.kind === 'page.generate' && sessionPageContinuation ? 2 : 1;
|
||||||
buildIntentMetadata(intent, {
|
let reply;
|
||||||
mediaAnalysisEnabled,
|
let publishArtifacts = [];
|
||||||
imagePolicy,
|
let confirmedArtifacts = [];
|
||||||
pgRequired: isPageDataRequest,
|
let verifiedArtifacts = [];
|
||||||
}),
|
let generatedImages = [];
|
||||||
{
|
let linkExistsForRequest = linkExists;
|
||||||
prepareUserMessage: (userMessage) => prepareWechatAgentUserMessage({
|
for (let pageAttempt = 1; pageAttempt <= maxImmediateContextPageAttempts; pageAttempt += 1) {
|
||||||
userId: user.userId,
|
const activeAgentPrompt =
|
||||||
sessionId,
|
pageAttempt === 1 ? agentPrompt : buildImmediateContextPageRepairPrompt(intent);
|
||||||
userMessage,
|
const activeRequestId = pageAttempt === 1 ? requestId : crypto.randomUUID();
|
||||||
|
reply = await executeSessionReply(
|
||||||
|
(pathname, init) => fetchForSession(sessionId, pathname, init),
|
||||||
|
sessionId,
|
||||||
|
activeRequestId,
|
||||||
|
activeAgentPrompt,
|
||||||
|
buildIntentMetadata(intent, {
|
||||||
|
mediaAnalysisEnabled,
|
||||||
|
imagePolicy,
|
||||||
|
pgRequired: isPageDataRequest,
|
||||||
}),
|
}),
|
||||||
submitReply: submitSessionReply
|
{
|
||||||
? ({ requestId: replyRequestId, userMessage }) =>
|
prepareUserMessage: (userMessage) => prepareWechatAgentUserMessage({
|
||||||
submitSessionReply({
|
userId: user.userId,
|
||||||
userId: user.userId,
|
sessionId,
|
||||||
sessionId,
|
userMessage,
|
||||||
requestId: replyRequestId,
|
preserveAgentPrompt: sessionPageContinuation,
|
||||||
userMessage,
|
}),
|
||||||
options: { requireHistoricalImageIsolation: true },
|
submitReply: submitSessionReply
|
||||||
})
|
? ({ requestId: replyRequestId, userMessage }) =>
|
||||||
: null,
|
submitSessionReply({
|
||||||
timeoutMs: agentReplyTimeoutMs,
|
userId: user.userId,
|
||||||
},
|
sessionId,
|
||||||
);
|
requestId: replyRequestId,
|
||||||
const generatedImages = collectWechatGeneratedImages(replyRequestMessages(reply));
|
userMessage,
|
||||||
if (imagePolicy.standaloneImageMode === 'required' && generatedImages.length === 0) {
|
options: { requireHistoricalImageIsolation: true },
|
||||||
const error = new Error('图片生成没有获得本轮新的有效位图,请稍后重试');
|
})
|
||||||
error.code = 'WECHAT_IMAGE_GENERATION_REQUIRED';
|
: null,
|
||||||
throw error;
|
timeoutMs: agentReplyTimeoutMs,
|
||||||
}
|
|
||||||
const {
|
|
||||||
publishedArtifacts,
|
|
||||||
verifiedArtifacts,
|
|
||||||
expectedArtifacts,
|
|
||||||
recentArtifacts,
|
|
||||||
confirmedArtifacts,
|
|
||||||
validReplyUrls,
|
|
||||||
hasValidReplyLink,
|
|
||||||
} = await resolveHtmlPublishArtifacts({
|
|
||||||
reply,
|
|
||||||
intent,
|
|
||||||
requestStartedAt,
|
|
||||||
userId: user.userId,
|
|
||||||
sessionId,
|
|
||||||
onPageGenerated,
|
|
||||||
allowRecentArtifacts: htmlArtifactDeliveryExpected,
|
|
||||||
htmlDeliveryAuthority,
|
|
||||||
});
|
|
||||||
const linkExistsForRequest =
|
|
||||||
createPreparedPublicHtmlLinkExists({
|
|
||||||
userId: user.userId,
|
|
||||||
prepared: {
|
|
||||||
validReplyUrls,
|
|
||||||
confirmedArtifacts,
|
|
||||||
},
|
},
|
||||||
fallback: linkExists,
|
|
||||||
});
|
|
||||||
const hasValidLinkInReply =
|
|
||||||
hasValidReplyLink ||
|
|
||||||
await hasAnyValidPublishedHtmlLink(
|
|
||||||
reply?.text,
|
|
||||||
linkExistsForRequest,
|
|
||||||
{ confirmedArtifacts },
|
|
||||||
);
|
);
|
||||||
const replyHasPublicLinks = hasAnyPublicHtmlLink(reply?.text);
|
generatedImages = collectWechatGeneratedImages(replyRequestMessages(reply));
|
||||||
const suspiciousPublishClaim =
|
if (imagePolicy.standaloneImageMode === 'required' && generatedImages.length === 0) {
|
||||||
expectedArtifacts.length === 0 &&
|
const error = new Error('图片生成没有获得本轮新的有效位图,请稍后重试');
|
||||||
recentArtifacts.length === 0 &&
|
error.code = 'WECHAT_IMAGE_GENERATION_REQUIRED';
|
||||||
(await isSuspiciousHtmlPublishClaimReply(reply, intent, { linkExists: linkExistsForRequest }));
|
throw error;
|
||||||
const htmlGenerationNeedsRetry = shouldRetryHtmlGenerationReply({
|
}
|
||||||
reply,
|
const {
|
||||||
intent,
|
publishedArtifacts,
|
||||||
confirmedArtifacts,
|
expectedArtifacts,
|
||||||
hasValidLinkInReply,
|
recentArtifacts,
|
||||||
});
|
confirmedArtifacts: resolvedConfirmedArtifacts,
|
||||||
const bareCompletionReply = isSuspiciousBareCompletionReply(reply, intent);
|
verifiedArtifacts: resolvedVerifiedArtifacts,
|
||||||
let publishArtifacts =
|
validReplyUrls,
|
||||||
htmlArtifactDeliveryExpected || publishedArtifacts.length > 0
|
hasValidReplyLink,
|
||||||
? selectSendableHtmlArtifacts({ verifiedArtifacts, confirmedArtifacts })
|
} = await resolveHtmlPublishArtifacts({
|
||||||
: [];
|
|
||||||
|
|
||||||
if (wechatIntent.kind === 'page.generate') {
|
|
||||||
const pageOutcome = resolvePageGenerateOutcome({
|
|
||||||
reply,
|
reply,
|
||||||
confirmedArtifacts,
|
intent,
|
||||||
verifiedArtifacts,
|
requestStartedAt,
|
||||||
suspiciousPublishClaim,
|
userId: user.userId,
|
||||||
bareCompletionReply,
|
sessionId,
|
||||||
htmlGenerationNeedsRetry,
|
onPageGenerated,
|
||||||
replyHasPublicLinks,
|
allowRecentArtifacts: htmlArtifactDeliveryExpected,
|
||||||
|
htmlDeliveryAuthority,
|
||||||
});
|
});
|
||||||
if (pageOutcome.action === 'session_retry') {
|
confirmedArtifacts = resolvedConfirmedArtifacts;
|
||||||
|
verifiedArtifacts = resolvedVerifiedArtifacts;
|
||||||
|
linkExistsForRequest =
|
||||||
|
createPreparedPublicHtmlLinkExists({
|
||||||
|
userId: user.userId,
|
||||||
|
prepared: {
|
||||||
|
validReplyUrls,
|
||||||
|
confirmedArtifacts,
|
||||||
|
},
|
||||||
|
fallback: linkExists,
|
||||||
|
});
|
||||||
|
const hasValidLinkInReply =
|
||||||
|
hasValidReplyLink ||
|
||||||
|
await hasAnyValidPublishedHtmlLink(
|
||||||
|
reply?.text,
|
||||||
|
linkExistsForRequest,
|
||||||
|
{ confirmedArtifacts },
|
||||||
|
);
|
||||||
|
const replyHasPublicLinks = hasAnyPublicHtmlLink(reply?.text);
|
||||||
|
const suspiciousPublishClaim =
|
||||||
|
expectedArtifacts.length === 0 &&
|
||||||
|
recentArtifacts.length === 0 &&
|
||||||
|
(await isSuspiciousHtmlPublishClaimReply(reply, intent, { linkExists: linkExistsForRequest }));
|
||||||
|
const htmlGenerationNeedsRetry = shouldRetryHtmlGenerationReply({
|
||||||
|
reply,
|
||||||
|
intent,
|
||||||
|
confirmedArtifacts,
|
||||||
|
hasValidLinkInReply,
|
||||||
|
});
|
||||||
|
const bareCompletionReply = isSuspiciousBareCompletionReply(reply, intent);
|
||||||
|
publishArtifacts =
|
||||||
|
htmlArtifactDeliveryExpected || publishedArtifacts.length > 0
|
||||||
|
? selectSendableHtmlArtifacts({ verifiedArtifacts, confirmedArtifacts })
|
||||||
|
: [];
|
||||||
|
|
||||||
|
if (wechatIntent.kind === 'page.generate') {
|
||||||
|
const pageOutcome = resolvePageGenerateOutcome({
|
||||||
|
reply,
|
||||||
|
confirmedArtifacts,
|
||||||
|
verifiedArtifacts,
|
||||||
|
suspiciousPublishClaim,
|
||||||
|
bareCompletionReply,
|
||||||
|
htmlGenerationNeedsRetry,
|
||||||
|
replyHasPublicLinks,
|
||||||
|
});
|
||||||
|
if (pageOutcome.action === 'session_retry') {
|
||||||
|
throw new Error('stale_session_poisoned_completion');
|
||||||
|
}
|
||||||
|
if (pageOutcome.action === 'fail') {
|
||||||
|
if (
|
||||||
|
pageAttempt < maxImmediateContextPageAttempts &&
|
||||||
|
pageOutcome.reason === 'skill_or_stub'
|
||||||
|
) {
|
||||||
|
logger.warn?.('WeChat MP immediate-context page repair retry:', {
|
||||||
|
sessionId,
|
||||||
|
userId: user.userId,
|
||||||
|
pageAttempt,
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const text = pageOutcome.failureText ?? buildPagePublishFailureText();
|
||||||
|
try {
|
||||||
|
await sendCustomerServiceText(inbound.fromUserName, text, user);
|
||||||
|
} catch (sendErr) {
|
||||||
|
logger.error?.('WeChat MP page generate failure notice failed:', sendErr);
|
||||||
|
}
|
||||||
|
throw markWechatUserNotified(new Error(text));
|
||||||
|
}
|
||||||
|
publishArtifacts = pageOutcome.artifacts ?? publishArtifacts;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (looksLikeHtmlGenerationIntent(intent?.agentText)) {
|
||||||
|
if (
|
||||||
|
suspiciousPublishClaim ||
|
||||||
|
bareCompletionReply ||
|
||||||
|
(htmlGenerationNeedsRetry && replyHasPublicLinks && confirmedArtifacts.length === 0)
|
||||||
|
) {
|
||||||
|
throw new Error('stale_session_poisoned_completion');
|
||||||
|
}
|
||||||
|
if (htmlGenerationNeedsRetry) {
|
||||||
|
const text = buildHtmlPublishFailureText();
|
||||||
|
try {
|
||||||
|
await sendCustomerServiceText(inbound.fromUserName, text, user);
|
||||||
|
} catch (sendErr) {
|
||||||
|
logger.error?.('WeChat MP html publish failure notice failed:', sendErr);
|
||||||
|
}
|
||||||
|
throw markWechatUserNotified(new Error(text));
|
||||||
|
}
|
||||||
|
} else if (htmlGenerationNeedsRetry || suspiciousPublishClaim) {
|
||||||
throw new Error('stale_session_poisoned_completion');
|
throw new Error('stale_session_poisoned_completion');
|
||||||
}
|
}
|
||||||
if (pageOutcome.action === 'fail') {
|
break;
|
||||||
const text = pageOutcome.failureText ?? buildPagePublishFailureText();
|
|
||||||
try {
|
|
||||||
await sendCustomerServiceText(inbound.fromUserName, text, user);
|
|
||||||
} catch (sendErr) {
|
|
||||||
logger.error?.('WeChat MP page generate failure notice failed:', sendErr);
|
|
||||||
}
|
|
||||||
throw markWechatUserNotified(new Error(text));
|
|
||||||
}
|
|
||||||
publishArtifacts = pageOutcome.artifacts ?? publishArtifacts;
|
|
||||||
} else if (looksLikeHtmlGenerationIntent(intent?.agentText)) {
|
|
||||||
if (
|
|
||||||
suspiciousPublishClaim ||
|
|
||||||
bareCompletionReply ||
|
|
||||||
(htmlGenerationNeedsRetry && replyHasPublicLinks && confirmedArtifacts.length === 0)
|
|
||||||
) {
|
|
||||||
throw new Error('stale_session_poisoned_completion');
|
|
||||||
}
|
|
||||||
if (htmlGenerationNeedsRetry) {
|
|
||||||
const text = buildHtmlPublishFailureText();
|
|
||||||
try {
|
|
||||||
await sendCustomerServiceText(inbound.fromUserName, text, user);
|
|
||||||
} catch (sendErr) {
|
|
||||||
logger.error?.('WeChat MP html publish failure notice failed:', sendErr);
|
|
||||||
}
|
|
||||||
throw markWechatUserNotified(new Error(text));
|
|
||||||
}
|
|
||||||
} else if (htmlGenerationNeedsRetry || suspiciousPublishClaim) {
|
|
||||||
throw new Error('stale_session_poisoned_completion');
|
|
||||||
}
|
}
|
||||||
await reviewWechatPageDataArtifacts({
|
await reviewWechatPageDataArtifacts({
|
||||||
user,
|
user,
|
||||||
@@ -2559,8 +2676,13 @@ export function createWechatMpService({
|
|||||||
forcePageData: isPageDataRequest,
|
forcePageData: isPageDataRequest,
|
||||||
});
|
});
|
||||||
if (wechatIntent.kind === 'page.generate') {
|
if (wechatIntent.kind === 'page.generate') {
|
||||||
|
const deliveryArtifacts = uniqueArtifactsByUrl([
|
||||||
|
...publishArtifacts,
|
||||||
|
...confirmedArtifacts,
|
||||||
|
...verifiedArtifacts,
|
||||||
|
]);
|
||||||
await enforceFreshPageThumbnailDelivery({
|
await enforceFreshPageThumbnailDelivery({
|
||||||
artifacts: publishArtifacts,
|
artifacts: deliveryArtifacts,
|
||||||
reply,
|
reply,
|
||||||
openid: inbound.fromUserName,
|
openid: inbound.fromUserName,
|
||||||
user,
|
user,
|
||||||
@@ -2569,6 +2691,27 @@ export function createWechatMpService({
|
|||||||
imagePolicy,
|
imagePolicy,
|
||||||
notifyFailure: false,
|
notifyFailure: false,
|
||||||
});
|
});
|
||||||
|
if (deliveryArtifacts.length > 0) {
|
||||||
|
publishArtifacts = deliveryArtifacts;
|
||||||
|
} else {
|
||||||
|
const recovered = await resolveHtmlPublishArtifacts({
|
||||||
|
reply,
|
||||||
|
intent,
|
||||||
|
requestStartedAt,
|
||||||
|
userId: user.userId,
|
||||||
|
sessionId,
|
||||||
|
onPageGenerated,
|
||||||
|
allowRecentArtifacts: true,
|
||||||
|
htmlDeliveryAuthority,
|
||||||
|
});
|
||||||
|
publishArtifacts = uniqueArtifactsByUrl([
|
||||||
|
...selectSendableHtmlArtifacts({
|
||||||
|
verifiedArtifacts: recovered.verifiedArtifacts,
|
||||||
|
confirmedArtifacts: recovered.confirmedArtifacts,
|
||||||
|
}),
|
||||||
|
...recovered.confirmedArtifacts,
|
||||||
|
]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
const pageDataOutcome = await enforcePageDataCollectDelivery({
|
const pageDataOutcome = await enforcePageDataCollectDelivery({
|
||||||
reply,
|
reply,
|
||||||
@@ -2657,6 +2800,21 @@ export function createWechatMpService({
|
|||||||
sessionId
|
sessionId
|
||||||
&& (isRecoverableWechatAgentSessionError(message) || isWechatAgentApiErrorText(message));
|
&& (isRecoverableWechatAgentSessionError(message) || isWechatAgentApiErrorText(message));
|
||||||
if (mayBeStaleSession) {
|
if (mayBeStaleSession) {
|
||||||
|
if (sessionPageContinuation) {
|
||||||
|
await userAuth.clearWechatAgentRoute(config.appId, inbound.fromUserName).catch((clearErr) => {
|
||||||
|
logger.warn?.('WeChat MP contextual follow-up route clear failed:', clearErr);
|
||||||
|
});
|
||||||
|
const text =
|
||||||
|
'我没能可靠确认“做成页面”指的是哪段内容,已经停止沿用旧主题。请把要做成页面的主题或原文再发一次。';
|
||||||
|
try {
|
||||||
|
await sendCustomerServiceText(inbound.fromUserName, text, user);
|
||||||
|
} catch (sendErr) {
|
||||||
|
logger.error?.('WeChat MP contextual follow-up notice failed:', sendErr);
|
||||||
|
}
|
||||||
|
const contextualError = markWechatUserNotified(new Error(text));
|
||||||
|
contextualError.wechatAgentSessionId = sessionId;
|
||||||
|
throw contextualError;
|
||||||
|
}
|
||||||
route = await ensureWechatAgentSession({
|
route = await ensureWechatAgentSession({
|
||||||
userId: user.userId,
|
userId: user.userId,
|
||||||
openid: inbound.fromUserName,
|
openid: inbound.fromUserName,
|
||||||
@@ -2673,8 +2831,12 @@ export function createWechatMpService({
|
|||||||
? buildPageGenerateAgentPrompt(intent, {
|
? buildPageGenerateAgentPrompt(intent, {
|
||||||
wantsDocx: wechatIntent.wantsDocx,
|
wantsDocx: wechatIntent.wantsDocx,
|
||||||
imagePolicy,
|
imagePolicy,
|
||||||
|
preferImmediateContext: sessionPageContinuation,
|
||||||
})
|
})
|
||||||
: buildWechatAgentPrompt(intent, { imagePolicy });
|
: buildWechatAgentPrompt(intent, {
|
||||||
|
imagePolicy,
|
||||||
|
preferSessionPageContinuation: sessionPageContinuation,
|
||||||
|
});
|
||||||
const reply = await executeSessionReply(
|
const reply = await executeSessionReply(
|
||||||
(pathname, init) => fetchForSession(sessionId, pathname, init),
|
(pathname, init) => fetchForSession(sessionId, pathname, init),
|
||||||
sessionId,
|
sessionId,
|
||||||
@@ -2690,6 +2852,7 @@ export function createWechatMpService({
|
|||||||
userId: user.userId,
|
userId: user.userId,
|
||||||
sessionId,
|
sessionId,
|
||||||
userMessage,
|
userMessage,
|
||||||
|
preserveAgentPrompt: sessionPageContinuation,
|
||||||
}),
|
}),
|
||||||
submitReply: submitSessionReply
|
submitReply: submitSessionReply
|
||||||
? ({ requestId: replyRequestId, userMessage }) =>
|
? ({ requestId: replyRequestId, userMessage }) =>
|
||||||
@@ -2812,8 +2975,13 @@ export function createWechatMpService({
|
|||||||
forcePageData: isPageDataRequest,
|
forcePageData: isPageDataRequest,
|
||||||
});
|
});
|
||||||
if (wechatIntent.kind === 'page.generate') {
|
if (wechatIntent.kind === 'page.generate') {
|
||||||
|
const deliveryArtifacts = uniqueArtifactsByUrl([
|
||||||
|
...publishArtifacts,
|
||||||
|
...confirmedArtifacts,
|
||||||
|
...verifiedArtifacts,
|
||||||
|
]);
|
||||||
await enforceFreshPageThumbnailDelivery({
|
await enforceFreshPageThumbnailDelivery({
|
||||||
artifacts: publishArtifacts,
|
artifacts: deliveryArtifacts,
|
||||||
reply,
|
reply,
|
||||||
openid: inbound.fromUserName,
|
openid: inbound.fromUserName,
|
||||||
user,
|
user,
|
||||||
@@ -2821,6 +2989,27 @@ export function createWechatMpService({
|
|||||||
sessionId,
|
sessionId,
|
||||||
imagePolicy,
|
imagePolicy,
|
||||||
});
|
});
|
||||||
|
if (deliveryArtifacts.length > 0) {
|
||||||
|
publishArtifacts = deliveryArtifacts;
|
||||||
|
} else {
|
||||||
|
const recovered = await resolveHtmlPublishArtifacts({
|
||||||
|
reply,
|
||||||
|
intent,
|
||||||
|
requestStartedAt: retryStartedAt,
|
||||||
|
userId: user.userId,
|
||||||
|
sessionId,
|
||||||
|
onPageGenerated,
|
||||||
|
allowRecentArtifacts: true,
|
||||||
|
htmlDeliveryAuthority,
|
||||||
|
});
|
||||||
|
publishArtifacts = uniqueArtifactsByUrl([
|
||||||
|
...selectSendableHtmlArtifacts({
|
||||||
|
verifiedArtifacts: recovered.verifiedArtifacts,
|
||||||
|
confirmedArtifacts: recovered.confirmedArtifacts,
|
||||||
|
}),
|
||||||
|
...recovered.confirmedArtifacts,
|
||||||
|
]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
const pageDataOutcome = await enforcePageDataCollectDelivery({
|
const pageDataOutcome = await enforcePageDataCollectDelivery({
|
||||||
reply,
|
reply,
|
||||||
|
|||||||
+268
-61
@@ -16,7 +16,11 @@ import {
|
|||||||
sanitizeWechatAgentOutboundText,
|
sanitizeWechatAgentOutboundText,
|
||||||
loadWechatMpConfig,
|
loadWechatMpConfig,
|
||||||
maybeAttachPublishedHtmlLink,
|
maybeAttachPublishedHtmlLink,
|
||||||
|
isWechatImmediateContextFollowup,
|
||||||
|
isWechatSessionPageContinuation,
|
||||||
|
shouldDeliverWechatHtmlArtifacts,
|
||||||
isWechatPageDataTask,
|
isWechatPageDataTask,
|
||||||
|
shouldRotateUnlinkedWechatRoute,
|
||||||
shouldRetryHtmlGenerationReply,
|
shouldRetryHtmlGenerationReply,
|
||||||
shouldForceNewWechatAgentSession,
|
shouldForceNewWechatAgentSession,
|
||||||
splitWechatText,
|
splitWechatText,
|
||||||
@@ -27,6 +31,9 @@ import {
|
|||||||
WECHAT_CUSTOMER_TEXT_MAX_BYTES,
|
WECHAT_CUSTOMER_TEXT_MAX_BYTES,
|
||||||
} from './wechat-mp.mjs';
|
} from './wechat-mp.mjs';
|
||||||
import { createChatIntentRouter } from './chat-intent-router.mjs';
|
import { createChatIntentRouter } from './chat-intent-router.mjs';
|
||||||
|
import { classifyWechatIntent } from './wechat/intent/classifier.mjs';
|
||||||
|
import { buildPageGenerateAgentPrompt, buildImmediateContextPageRepairPrompt } from './wechat/prompts/page-generate.mjs';
|
||||||
|
import { resolveWechatImageGenerationPolicy, WECHAT_PAGE_THUMBNAIL_MODE } from './wechat/image-generation-policy.mjs';
|
||||||
import {
|
import {
|
||||||
ensureWechatFreshPageThumbnailsAtWorkspace,
|
ensureWechatFreshPageThumbnailsAtWorkspace,
|
||||||
prepareWechatHtmlDeliveryAtWorkspace,
|
prepareWechatHtmlDeliveryAtWorkspace,
|
||||||
@@ -333,6 +340,168 @@ test('Page Data requests always rotate away from an existing WeChat route', () =
|
|||||||
assert.equal(shouldForceNewWechatAgentSession({ kind: 'chat.general' }, '换新会话'), true);
|
assert.equal(shouldForceNewWechatAgentSession({ kind: 'chat.general' }, '换新会话'), true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('WeChat immediate-context page guard does not match complete page requests', () => {
|
||||||
|
const pageIntent = { kind: 'page.generate' };
|
||||||
|
assert.equal(isWechatImmediateContextFollowup(pageIntent, '帮我做成页面吧'), true);
|
||||||
|
assert.equal(isWechatImmediateContextFollowup(pageIntent, '把刚才的诗做成页面'), true);
|
||||||
|
assert.equal(isWechatImmediateContextFollowup(pageIntent, '生成一个精美的 HTML 页面'), true);
|
||||||
|
assert.equal(isWechatImmediateContextFollowup(pageIntent, '生成一个HTML页面'), true);
|
||||||
|
assert.equal(isWechatImmediateContextFollowup(pageIntent, '生成一个上海旅游攻略页面'), false);
|
||||||
|
assert.equal(isWechatImmediateContextFollowup(pageIntent, '帮我做一个上海旅游页面'), false);
|
||||||
|
assert.equal(
|
||||||
|
isWechatImmediateContextFollowup({ kind: 'chat.general' }, '帮我做成页面吧'),
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
|
||||||
|
const guardedPrompt = buildPageGenerateAgentPrompt(
|
||||||
|
{ agentText: '帮我做成页面吧' },
|
||||||
|
{ preferImmediateContext: true },
|
||||||
|
);
|
||||||
|
const ordinaryPrompt = buildPageGenerateAgentPrompt({
|
||||||
|
agentText: '帮我做一个上海旅游页面',
|
||||||
|
});
|
||||||
|
assert.match(guardedPrompt, /即时上下文优先/);
|
||||||
|
assert.match(guardedPrompt, /禁止用长期记忆、历史偏好或旧任务替换主题/);
|
||||||
|
assert.match(guardedPrompt, /write_file 硬门槛/);
|
||||||
|
assert.match(guardedPrompt, /禁止只调用 load_skill、todo_write 或 generate_image 就回复/);
|
||||||
|
assert.doesNotMatch(ordinaryPrompt, /即时上下文优先/);
|
||||||
|
assert.doesNotMatch(ordinaryPrompt, /write_file 硬门槛/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('WeChat session page continuation covers retry, edit, and poem edits', () => {
|
||||||
|
const retry = classifyWechatIntent({ msgType: 'text', agentText: '重试上次页面' });
|
||||||
|
assert.equal(retry.kind, 'page.generate');
|
||||||
|
assert.equal(isWechatSessionPageContinuation(retry, '重试上次页面'), true);
|
||||||
|
const edit = classifyWechatIntent({ msgType: 'text', agentText: '把页面标题改成《七月清晨》' });
|
||||||
|
assert.equal(edit.kind, 'page.generate');
|
||||||
|
assert.equal(isWechatSessionPageContinuation(edit, edit.topic), true);
|
||||||
|
const poemEdit = classifyWechatIntent({ msgType: 'text', agentText: '把诗里第三段改长一点' });
|
||||||
|
assert.equal(poemEdit.kind, 'chat.general');
|
||||||
|
assert.equal(isWechatSessionPageContinuation(poemEdit, '把诗里第三段改长一点'), true);
|
||||||
|
assert.equal(
|
||||||
|
shouldDeliverWechatHtmlArtifacts(poemEdit, { agentText: '把诗里第三段改长一点' }),
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('WeChat immediate-context page skips fresh thumbnail requirement', () => {
|
||||||
|
const policy = resolveWechatImageGenerationPolicy({
|
||||||
|
text: '把刚才的诗做成页面',
|
||||||
|
isPageGenerate: true,
|
||||||
|
requireFreshPageThumbnail: false,
|
||||||
|
});
|
||||||
|
assert.equal(policy.pageThumbnailMode, WECHAT_PAGE_THUMBNAIL_MODE.AUTO);
|
||||||
|
const prompt = buildPageGenerateAgentPrompt(
|
||||||
|
{ agentText: '把刚才的诗做成页面' },
|
||||||
|
{ preferImmediateContext: true, imagePolicy: policy },
|
||||||
|
);
|
||||||
|
assert.doesNotMatch(prompt, /服务号页面新缩略图硬要求/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('WeChat immediate-context page repair prompt requires write_file', () => {
|
||||||
|
const repairPrompt = buildImmediateContextPageRepairPrompt({ agentText: '把刚才的诗做成页面' });
|
||||||
|
assert.match(repairPrompt, /未 write_file 落盘 HTML/);
|
||||||
|
assert.match(repairPrompt, /禁止再次只 generate_image/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('WeChat immediate-context page retains an unlinked route with adjacent snapshot', async () => {
|
||||||
|
const clearedRoutes = [];
|
||||||
|
const startedSessions = [];
|
||||||
|
let activeRoute = {
|
||||||
|
agentSessionId: 'session-poem',
|
||||||
|
updatedAt: Date.now() - 120_000,
|
||||||
|
};
|
||||||
|
const service = createBoundWechatService({
|
||||||
|
config: {
|
||||||
|
sessionMessageRotateCount: 0,
|
||||||
|
sessionIdleRotateMs: 0,
|
||||||
|
},
|
||||||
|
userAuth: {
|
||||||
|
async getWechatAgentRoute() {
|
||||||
|
return activeRoute;
|
||||||
|
},
|
||||||
|
async clearWechatAgentRoute(_appId, openid) {
|
||||||
|
clearedRoutes.push(openid);
|
||||||
|
activeRoute = null;
|
||||||
|
},
|
||||||
|
async countWechatAgentSessionMessages() {
|
||||||
|
return 0;
|
||||||
|
},
|
||||||
|
async getWechatAgentSessionSnapshotMessageCount() {
|
||||||
|
return 5;
|
||||||
|
},
|
||||||
|
async touchWechatAgentRoute(_appId, _openid, updatedAt) {
|
||||||
|
activeRoute = { ...activeRoute, updatedAt };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
startAgentSession: async (sessionId) => {
|
||||||
|
startedSessions.push(sessionId);
|
||||||
|
return sessionId;
|
||||||
|
},
|
||||||
|
sessionApiFetch: async (pathname) => {
|
||||||
|
if (String(pathname).includes('/tools')) {
|
||||||
|
return new Response(JSON.stringify({ tools: [] }), {
|
||||||
|
status: 200,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return new Response(JSON.stringify({ conversation: [] }), {
|
||||||
|
status: 200,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
});
|
||||||
|
},
|
||||||
|
submitSessionReply: async () => ({
|
||||||
|
ok: true,
|
||||||
|
conversation: [{ role: 'assistant', content: [{ type: 'text', text: 'ok' }] }],
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const timestamp = '1710000000';
|
||||||
|
const nonce = 'nonce-immediate-context-route';
|
||||||
|
await service.handleInboundMessage(
|
||||||
|
inboundXml({ content: '把刚才的诗做成页面' }),
|
||||||
|
{
|
||||||
|
timestamp,
|
||||||
|
nonce,
|
||||||
|
signature: signatureFor('token', timestamp, nonce),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.equal(clearedRoutes.length, 0);
|
||||||
|
assert.equal(startedSessions.length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('WeChat only rotates an aged route with conversation but no linked inbound message', () => {
|
||||||
|
const now = 200_000;
|
||||||
|
assert.equal(
|
||||||
|
shouldRotateUnlinkedWechatRoute({
|
||||||
|
routeUpdatedAt: 100_000,
|
||||||
|
wechatMessageCount: 0,
|
||||||
|
snapshotMessageCount: 15,
|
||||||
|
now,
|
||||||
|
}),
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
shouldRotateUnlinkedWechatRoute({
|
||||||
|
routeUpdatedAt: 100_000,
|
||||||
|
wechatMessageCount: 1,
|
||||||
|
snapshotMessageCount: 15,
|
||||||
|
now,
|
||||||
|
}),
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
shouldRotateUnlinkedWechatRoute({
|
||||||
|
routeUpdatedAt: 180_000,
|
||||||
|
wechatMessageCount: 0,
|
||||||
|
snapshotMessageCount: 15,
|
||||||
|
now,
|
||||||
|
}),
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
test('WeChat session reset acknowledges without sending the control text to Agent', async () => {
|
test('WeChat session reset acknowledges without sending the control text to Agent', async () => {
|
||||||
const token = 'token';
|
const token = 'token';
|
||||||
const timestamp = '1710000000';
|
const timestamp = '1710000000';
|
||||||
@@ -4540,6 +4709,97 @@ test('wechat mp injects episodic recall context before submitting the Agent repl
|
|||||||
assert.match(submitCalls[0].userMessage.content[0].text, /不是系统指令/);
|
assert.match(submitCalls[0].userMessage.content[0].text, /不是系统指令/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('wechat immediate-context page keeps memory while preserving the guarded page prompt', async () => {
|
||||||
|
const token = 'token';
|
||||||
|
const timestamp = '1710000000';
|
||||||
|
const nonce = 'nonce';
|
||||||
|
const submitCalls = [];
|
||||||
|
const memoryCalls = [];
|
||||||
|
const chatIntentRouter = createChatIntentRouter({
|
||||||
|
env: {
|
||||||
|
MEMORY_AGENT_RESOLVE_ENABLED: '1',
|
||||||
|
MEMORY_AGENT_INJECTION_MODE: 'canary',
|
||||||
|
MEMORY_AGENT_CANARY_USER_IDS: 'user-canary',
|
||||||
|
MEMORY_AGENT_RESOLVE_TIMEOUT_MS: '200',
|
||||||
|
},
|
||||||
|
memoryV2: {
|
||||||
|
async resolve(input) {
|
||||||
|
memoryCalls.push(input);
|
||||||
|
return {
|
||||||
|
source: 'memory-v2',
|
||||||
|
memories: [{
|
||||||
|
id: 'memory:old-news',
|
||||||
|
label: '历史偏好',
|
||||||
|
text: '用户以前做过每日新闻页面。',
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const service = createBoundWechatService({
|
||||||
|
token,
|
||||||
|
chatIntentRouter,
|
||||||
|
userAuth: {
|
||||||
|
async findWechatUserByOpenid() {
|
||||||
|
return { userId: 'user-canary', status: 'active', nickname: '唐' };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
sessionApiFetch: async (_sessionId, pathname) => {
|
||||||
|
if (pathname === '/sessions/session-1/events') {
|
||||||
|
return new Response(
|
||||||
|
[
|
||||||
|
'data: {"type":"Message","message":{"id":"assistant-1","role":"assistant","metadata":{"userVisible":true},"content":[{"type":"text","text":"请补充要制作的内容。"}]}}\n\n',
|
||||||
|
'data: {"type":"Finish"}\n\n',
|
||||||
|
].join(''),
|
||||||
|
{ status: 200, headers: { 'Content-Type': 'text/event-stream' } },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (pathname === '/agent/harness_remember' || pathname === '/agent/harness_bootstrap') {
|
||||||
|
return new Response('{}', {
|
||||||
|
status: 200,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
throw new Error(`unexpected api path: ${pathname}`);
|
||||||
|
},
|
||||||
|
submitSessionReply: async (input) => {
|
||||||
|
submitCalls.push(input);
|
||||||
|
return { ok: true };
|
||||||
|
},
|
||||||
|
wechatFetch: async (url) => {
|
||||||
|
if (String(url).includes('/cgi-bin/stable_token')) {
|
||||||
|
return new Response(JSON.stringify({ access_token: 'access-1', expires_in: 7200 }), {
|
||||||
|
status: 200,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (String(url).includes('/cgi-bin/message/custom/send')) {
|
||||||
|
return new Response(JSON.stringify({ errcode: 0, errmsg: 'ok' }), {
|
||||||
|
status: 200,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
throw new Error(`unexpected wechat url: ${url}`);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await service.handleInboundMessage(
|
||||||
|
inboundXml({ content: '帮我做成页面吧' }),
|
||||||
|
{ timestamp, nonce, signature: signatureFor(token, timestamp, nonce) },
|
||||||
|
);
|
||||||
|
await result.task;
|
||||||
|
|
||||||
|
assert.equal(memoryCalls.length, 1);
|
||||||
|
assert.equal(submitCalls.length, 1);
|
||||||
|
const submitted = submitCalls[0].userMessage;
|
||||||
|
assert.equal(submitted.metadata.displayText, '帮我做成页面吧');
|
||||||
|
assert.match(submitted.content[0].text, /\[Memory Context\]/);
|
||||||
|
assert.match(submitted.content[0].text, /用户以前做过每日新闻页面/);
|
||||||
|
assert.match(submitted.content[0].text, /微信服务号 · 页面生成任务/);
|
||||||
|
assert.match(submitted.content[0].text, /即时上下文优先/);
|
||||||
|
assert.match(submitted.content[0].text, /用户需求:帮我做成页面吧/);
|
||||||
|
});
|
||||||
|
|
||||||
test('wechat mp serializes image and follow-up text and reattaches recent image', async () => {
|
test('wechat mp serializes image and follow-up text and reattaches recent image', async () => {
|
||||||
const token = 'token';
|
const token = 'token';
|
||||||
const timestamp = '1710000000';
|
const timestamp = '1710000000';
|
||||||
@@ -5724,42 +5984,23 @@ test('wechat mp page delivery repairs one unambiguous fresh thumbnail missing fr
|
|||||||
assert.match(wechatPayloads[0].text.content, /fresh\.html/);
|
assert.match(wechatPayloads[0].text.content, /fresh\.html/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('wechat mp retries a page in a new session before reporting a missing fresh thumbnail', async () => {
|
test('wechat mp delivers page via workspace thumbnail when fresh image_make is missing', async () => {
|
||||||
const token = 'token';
|
const token = 'token';
|
||||||
const timestamp = '1710000000';
|
const timestamp = '1710000000';
|
||||||
const nonce = 'nonce';
|
const nonce = 'nonce';
|
||||||
const workspaceRoot = fs.mkdtempSync('/tmp/wechat-mp-fresh-thumbnail-retry-');
|
const workspaceRoot = fs.mkdtempSync('/tmp/wechat-mp-fresh-thumbnail-fallback-');
|
||||||
const htmlPath = path.join(workspaceRoot, 'public', 'retry.html');
|
const htmlPath = path.join(workspaceRoot, 'public', 'retry.html');
|
||||||
const generated = {
|
|
||||||
ok: true,
|
|
||||||
jobId: 'job-fresh-page-retry',
|
|
||||||
source: { mimeType: 'image/webp', width: 1280, height: 720 },
|
|
||||||
asset: {
|
|
||||||
id: 'asset-fresh-page-retry',
|
|
||||||
htmlSrc: 'images/retry-cover.webp',
|
|
||||||
publicUrl: 'https://example.com/MindSpace/user-1/public/images/retry-cover.webp',
|
|
||||||
workspaceRelativePath: 'public/images/retry-cover.webp',
|
|
||||||
},
|
|
||||||
};
|
|
||||||
const firstHtml = previewReadyPageHtml({
|
const firstHtml = previewReadyPageHtml({
|
||||||
title: 'Retry',
|
title: 'Retry',
|
||||||
subtitle: '首次没有新缩略图',
|
subtitle: '首次没有新缩略图',
|
||||||
cover: 'images/missing-cover.webp',
|
cover: 'images/missing-cover.webp',
|
||||||
});
|
});
|
||||||
const retryHtml = previewReadyPageHtml({
|
|
||||||
title: 'Retry',
|
|
||||||
subtitle: '重试生成新缩略图',
|
|
||||||
cover: generated.asset.htmlSrc,
|
|
||||||
});
|
|
||||||
const pageImage = await sharp({
|
|
||||||
create: { width: 64, height: 64, channels: 3, background: '#cc6633' },
|
|
||||||
}).webp().toBuffer();
|
|
||||||
const eventFrame = (event) => `data: ${JSON.stringify(event)}\n\n`;
|
const eventFrame = (event) => `data: ${JSON.stringify(event)}\n\n`;
|
||||||
const wechatPayloads = [];
|
const wechatPayloads = [];
|
||||||
let routeCleared = false;
|
let routeCleared = false;
|
||||||
let startedSessions = 0;
|
let startedSessions = 0;
|
||||||
|
|
||||||
const replyEvents = ({ requestId, html, includeImage = false }) => [
|
const replyEvents = ({ requestId, html }) => [
|
||||||
eventFrame({
|
eventFrame({
|
||||||
type: 'Message',
|
type: 'Message',
|
||||||
request_id: requestId,
|
request_id: requestId,
|
||||||
@@ -5773,25 +6014,6 @@ test('wechat mp retries a page in a new session before reporting a missing fresh
|
|||||||
type: 'toolRequest',
|
type: 'toolRequest',
|
||||||
toolCall: { value: { name: 'load_skill', arguments: { name: 'static-page-publish' } } },
|
toolCall: { value: { name: 'load_skill', arguments: { name: 'static-page-publish' } } },
|
||||||
},
|
},
|
||||||
...(includeImage
|
|
||||||
? [
|
|
||||||
{
|
|
||||||
id: `${requestId}-image`,
|
|
||||||
type: 'toolRequest',
|
|
||||||
toolCall: {
|
|
||||||
value: { name: 'sandbox-fs__generate_image', arguments: { purpose: 'hero' } },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: `${requestId}-image`,
|
|
||||||
type: 'toolResponse',
|
|
||||||
toolResult: {
|
|
||||||
status: 'success',
|
|
||||||
value: { content: [{ type: 'text', text: JSON.stringify(generated) }] },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]
|
|
||||||
: []),
|
|
||||||
{
|
{
|
||||||
id: `${requestId}-write`,
|
id: `${requestId}-write`,
|
||||||
type: 'toolRequest',
|
type: 'toolRequest',
|
||||||
@@ -5861,24 +6083,12 @@ test('wechat mp retries a page in a new session before reporting a missing fresh
|
|||||||
}
|
}
|
||||||
if (pathname === `/sessions/${sessionId}/reply`) {
|
if (pathname === `/sessions/${sessionId}/reply`) {
|
||||||
fs.mkdirSync(path.dirname(htmlPath), { recursive: true });
|
fs.mkdirSync(path.dirname(htmlPath), { recursive: true });
|
||||||
if (sessionId === 'session-1') {
|
fs.writeFileSync(htmlPath, firstHtml, 'utf8');
|
||||||
fs.writeFileSync(htmlPath, firstHtml, 'utf8');
|
|
||||||
} else {
|
|
||||||
fs.writeFileSync(htmlPath, retryHtml, 'utf8');
|
|
||||||
fs.mkdirSync(path.join(workspaceRoot, 'public', 'images'), { recursive: true });
|
|
||||||
fs.writeFileSync(path.join(workspaceRoot, 'public', generated.asset.htmlSrc), pageImage);
|
|
||||||
}
|
|
||||||
return new Response('{}', { status: 200, headers: { 'Content-Type': 'application/json' } });
|
return new Response('{}', { status: 200, headers: { 'Content-Type': 'application/json' } });
|
||||||
}
|
}
|
||||||
if (pathname === '/sessions/session-1/events') {
|
if (pathname === '/sessions/session-1/events') {
|
||||||
return new Response(
|
return new Response(
|
||||||
replyEvents({ requestId: 'req-thumbnail-first', html: firstHtml }),
|
replyEvents({ requestId: 'req-thumbnail-fallback', html: firstHtml }),
|
||||||
{ status: 200, headers: { 'Content-Type': 'text/event-stream' } },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (pathname === '/sessions/session-2/events') {
|
|
||||||
return new Response(
|
|
||||||
replyEvents({ requestId: 'req-thumbnail-retry', html: retryHtml, includeImage: true }),
|
|
||||||
{ status: 200, headers: { 'Content-Type': 'text/event-stream' } },
|
{ status: 200, headers: { 'Content-Type': 'text/event-stream' } },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -5903,10 +6113,7 @@ test('wechat mp retries a page in a new session before reporting a missing fresh
|
|||||||
});
|
});
|
||||||
|
|
||||||
const originalRandomUuid = crypto.randomUUID;
|
const originalRandomUuid = crypto.randomUUID;
|
||||||
crypto.randomUUID = (() => {
|
crypto.randomUUID = () => 'req-thumbnail-fallback';
|
||||||
const ids = ['req-thumbnail-first', 'req-thumbnail-retry'];
|
|
||||||
return () => ids.shift() ?? 'req-thumbnail-retry';
|
|
||||||
})();
|
|
||||||
try {
|
try {
|
||||||
const result = await service.handleInboundMessage(
|
const result = await service.handleInboundMessage(
|
||||||
inboundXml({ content: '生成一个活动页面,只要文字,不要正文图片' }),
|
inboundXml({ content: '生成一个活动页面,只要文字,不要正文图片' }),
|
||||||
@@ -5920,8 +6127,8 @@ test('wechat mp retries a page in a new session before reporting a missing fresh
|
|||||||
fs.rmSync(workspaceRoot, { recursive: true, force: true });
|
fs.rmSync(workspaceRoot, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
assert.equal(routeCleared, true);
|
assert.equal(routeCleared, false);
|
||||||
assert.equal(startedSessions, 1);
|
assert.equal(startedSessions, 0);
|
||||||
assert.equal(wechatPayloads.length, 1);
|
assert.equal(wechatPayloads.length, 1);
|
||||||
assert.equal(wechatPayloads[0].msgtype, 'text');
|
assert.equal(wechatPayloads[0].msgtype, 'text');
|
||||||
assert.match(wechatPayloads[0].text.content, /retry\.html/);
|
assert.match(wechatPayloads[0].text.content, /retry\.html/);
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
/** WeChat short follow-ups that continue an in-session page or poem without a full new topic. */
|
||||||
|
|
||||||
|
const PAGE_DECORATORS =
|
||||||
|
'(?:精美(?:的)?|漂亮(?:的)?|好看(?:的)?|简约(?:的)?|优雅(?:的)?)';
|
||||||
|
|
||||||
|
export const PAGE_RETRY_PATTERN =
|
||||||
|
/^(?:(?:请|麻烦|可以|能不能)\s*)?(?:(?:帮我|帮忙|给我)\s*)?重试(?:上次|上一个)?页面[。.!!\s]*$/iu;
|
||||||
|
|
||||||
|
export const PAGE_EDIT_PATTERN =
|
||||||
|
/^(?:(?:请|麻烦|可以|能不能)\s*)?(?:(?:帮我|帮忙|给我)\s*)?(?:(?:把|将)\s*)?(?:(?:这个|刚才(?:的)?|上面(?:的)?|前面(?:的)?|上一条|它|刚才(?:生成|做|弄)(?:的)?|上面(?:生成|做|弄)(?:的)?)\s*)?(?:的)?\s*(?:页面|网页|html)?\s*(?:的)?\s*(?:内容|标题|背景|样式|排版|封面|页脚|字体|颜色)?\s*(?:改|修改|调整|更新|换|优化|美化)/iu;
|
||||||
|
|
||||||
|
export const PAGE_IMMEDIATE_CREATE_PATTERN =
|
||||||
|
new RegExp(
|
||||||
|
'^'
|
||||||
|
+ '(?:(?:请|麻烦|可以|能不能)\\s*)?'
|
||||||
|
+ '(?:(?:帮我|帮忙|给我)\\s*)?'
|
||||||
|
+ '(?:(?:把\\s*)?(?:这个|刚才(?:的)?(?:诗|文章|内容)?|上面(?:的)?|前面(?:的)?|上一条|它|这首(?:诗)?|这篇(?:文章)?|这段(?:内容)?)\\s*)?'
|
||||||
|
+ '(?:继续\\s*)?'
|
||||||
|
+ '(?:做|弄|改|转|写|排版|生成|制作)(?:成|为)?\\s*'
|
||||||
|
+ '(?:一个|个)?'
|
||||||
|
+ '(?:(?:\\s*'
|
||||||
|
+ PAGE_DECORATORS
|
||||||
|
+ '){1,3}\\s*(?:h5|html)|(?:\\s*(?:h5|html)))?'
|
||||||
|
+ '\\s*(?:页面|网页)(?:吧|呀|呢|一下)?[。.!!\\s]*'
|
||||||
|
+ '$',
|
||||||
|
'iu',
|
||||||
|
);
|
||||||
|
|
||||||
|
export const PAGE_CONTENT_EDIT_PATTERN =
|
||||||
|
/^(?:(?:请|麻烦|可以|能不能)\s*)?(?:(?:帮我|帮忙|给我)\s*)?(?:(?:把|将)\s*)?(?:(?:这个|刚才(?:的)?|上面(?:的)?|前面(?:的)?|它|这首(?:诗)?|这篇(?:文章)?|这段(?:内容)?|诗(?:里|中)?)\s*)?(?:的)?\s*(?:[\p{L}\p{N}]{0,12}\s*)?(?:改|修改|调整|更新|换|加长|缩短|润色)/iu;
|
||||||
|
|
||||||
|
export function isWechatPageRetryText(text) {
|
||||||
|
const normalized = String(text ?? '').trim();
|
||||||
|
return Boolean(normalized && PAGE_RETRY_PATTERN.test(normalized));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isWechatPageEditText(text) {
|
||||||
|
const normalized = String(text ?? '').trim();
|
||||||
|
return Boolean(normalized && PAGE_EDIT_PATTERN.test(normalized));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isWechatContentEditFollowup(text) {
|
||||||
|
const normalized = String(text ?? '').trim();
|
||||||
|
return Boolean(normalized && PAGE_CONTENT_EDIT_PATTERN.test(normalized));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isWechatImmediateContextPageCreate(wechatIntent, text) {
|
||||||
|
if (wechatIntent?.kind !== 'page.generate') return false;
|
||||||
|
const normalized = String(text ?? '').trim();
|
||||||
|
return Boolean(normalized && PAGE_IMMEDIATE_CREATE_PATTERN.test(normalized));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isWechatSessionPageContinuation(wechatIntent, text) {
|
||||||
|
const normalized = String(text ?? '').trim();
|
||||||
|
if (!normalized) return false;
|
||||||
|
if (isWechatPageRetryText(normalized)) return true;
|
||||||
|
if (isWechatImmediateContextPageCreate(wechatIntent, normalized)) return true;
|
||||||
|
if (wechatIntent?.kind === 'page.generate' && isWechatPageEditText(normalized)) return true;
|
||||||
|
if (wechatIntent?.kind === 'chat.general' && isWechatContentEditFollowup(normalized)) return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function expectsWechatHtmlArtifactDelivery(wechatIntent, text) {
|
||||||
|
const normalized = String(text ?? '').trim();
|
||||||
|
return (
|
||||||
|
wechatIntent?.kind === 'page.generate'
|
||||||
|
|| isWechatSessionPageContinuation(wechatIntent, normalized)
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,5 +1,10 @@
|
|||||||
/** WeChat channel intent patterns — not shared with H5 chat-skills routing. */
|
/** WeChat channel intent patterns — not shared with H5 chat-skills routing. */
|
||||||
|
|
||||||
|
import {
|
||||||
|
isWechatPageEditText,
|
||||||
|
isWechatPageRetryText,
|
||||||
|
} from './page-continuation.mjs';
|
||||||
|
|
||||||
export const PAGE_GENERATE_PATTERN =
|
export const PAGE_GENERATE_PATTERN =
|
||||||
/(?:生成|创建|做|写|帮我.*(?:生成|创建|做|写)).*(?:html|页面|网页|page|文件)/iu;
|
/(?:生成|创建|做|写|帮我.*(?:生成|创建|做|写)).*(?:html|页面|网页|page|文件)/iu;
|
||||||
|
|
||||||
@@ -25,7 +30,11 @@ export function isPageGenerateText(text) {
|
|||||||
const normalized = String(text ?? '').trim();
|
const normalized = String(text ?? '').trim();
|
||||||
if (!normalized) return false;
|
if (!normalized) return false;
|
||||||
if (PAGE_GENERATE_NEGATION_PATTERN.test(normalized)) return false;
|
if (PAGE_GENERATE_NEGATION_PATTERN.test(normalized)) return false;
|
||||||
return PAGE_GENERATE_PATTERN.test(normalized);
|
return (
|
||||||
|
PAGE_GENERATE_PATTERN.test(normalized)
|
||||||
|
|| isWechatPageRetryText(normalized)
|
||||||
|
|| isWechatPageEditText(normalized)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isTopicResetText(text) {
|
export function isTopicResetText(text) {
|
||||||
|
|||||||
@@ -8,7 +8,11 @@ import { buildCurrentTimeAgentPrefix } from '../../user-memory-profile.mjs';
|
|||||||
import { isPageGenerateText, wantsDocxDownload } from '../intent/patterns.mjs';
|
import { isPageGenerateText, wantsDocxDownload } from '../intent/patterns.mjs';
|
||||||
import { buildWechatStandaloneImageInstruction } from '../image-generation-policy.mjs';
|
import { buildWechatStandaloneImageInstruction } from '../image-generation-policy.mjs';
|
||||||
|
|
||||||
export function buildWechatAgentPrompt(intent, { grantedSkills = [], imagePolicy = null } = {}) {
|
export function buildWechatAgentPrompt(intent, {
|
||||||
|
grantedSkills = [],
|
||||||
|
imagePolicy = null,
|
||||||
|
preferSessionPageContinuation = false,
|
||||||
|
} = {}) {
|
||||||
const msgType = String(intent?.msgType ?? 'text');
|
const msgType = String(intent?.msgType ?? 'text');
|
||||||
const agentText = intent?.agentText ?? intent?.content ?? '';
|
const agentText = intent?.agentText ?? intent?.content ?? '';
|
||||||
const autoSkillPrefix =
|
const autoSkillPrefix =
|
||||||
@@ -56,6 +60,14 @@ export function buildWechatAgentPrompt(intent, { grantedSkills = [], imagePolicy
|
|||||||
'',
|
'',
|
||||||
].join('\n')
|
].join('\n')
|
||||||
: '';
|
: '';
|
||||||
|
const sessionPageContinuationHint = preferSessionPageContinuation
|
||||||
|
? [
|
||||||
|
'【会话页面续作】用户在修改本会话刚生成的页面或诗/文章内容。',
|
||||||
|
'必须读取当前会话最近 assistant 回复或已落盘的 public/*.html,用 edit_file 更新目标 HTML。',
|
||||||
|
'禁止切换到无关主题;没有 edit_file/write_file 落盘就不要声称已修改或发送链接。',
|
||||||
|
'',
|
||||||
|
].join('\n')
|
||||||
|
: '';
|
||||||
const scheduleTimezone = process.env.H5_DEFAULT_TIMEZONE || 'Asia/Shanghai';
|
const scheduleTimezone = process.env.H5_DEFAULT_TIMEZONE || 'Asia/Shanghai';
|
||||||
const currentTimeHint = buildCurrentTimeAgentPrefix({ timezone: scheduleTimezone });
|
const currentTimeHint = buildCurrentTimeAgentPrefix({ timezone: scheduleTimezone });
|
||||||
const scheduleAssistantHint = shouldUseScheduleAssistant(agentText)
|
const scheduleAssistantHint = shouldUseScheduleAssistant(agentText)
|
||||||
@@ -156,6 +168,7 @@ export function buildWechatAgentPrompt(intent, { grantedSkills = [], imagePolicy
|
|||||||
if (docxDownloadHint) lines.push(docxDownloadHint);
|
if (docxDownloadHint) lines.push(docxDownloadHint);
|
||||||
if (pageDataCollectHint) lines.push(pageDataCollectHint);
|
if (pageDataCollectHint) lines.push(pageDataCollectHint);
|
||||||
if (pageDataRepairHint) lines.push(pageDataRepairHint);
|
if (pageDataRepairHint) lines.push(pageDataRepairHint);
|
||||||
|
if (sessionPageContinuationHint) lines.push(sessionPageContinuationHint);
|
||||||
if (pagePublishHint) lines.push(pagePublishHint);
|
if (pagePublishHint) lines.push(pagePublishHint);
|
||||||
if (scheduleAssistantHint) lines.push(scheduleAssistantHint);
|
if (scheduleAssistantHint) lines.push(scheduleAssistantHint);
|
||||||
if (imageGenerationHint) lines.push(imageGenerationHint);
|
if (imageGenerationHint) lines.push(imageGenerationHint);
|
||||||
|
|||||||
@@ -8,7 +8,14 @@ import { buildWechatPageImageInstruction } from '../image-generation-policy.mjs'
|
|||||||
/**
|
/**
|
||||||
* Service-account-only page generation prompt. Does not use H5 buildAutoChatSkillPrefix.
|
* Service-account-only page generation prompt. Does not use H5 buildAutoChatSkillPrefix.
|
||||||
*/
|
*/
|
||||||
export function buildPageGenerateAgentPrompt(intent, { wantsDocx = false, imagePolicy = null } = {}) {
|
export function buildPageGenerateAgentPrompt(
|
||||||
|
intent,
|
||||||
|
{
|
||||||
|
wantsDocx = false,
|
||||||
|
imagePolicy = null,
|
||||||
|
preferImmediateContext = false,
|
||||||
|
} = {},
|
||||||
|
) {
|
||||||
const topic = String(intent?.agentText ?? intent?.displayText ?? '').trim();
|
const topic = String(intent?.agentText ?? intent?.displayText ?? '').trim();
|
||||||
const pageDataTask = isPageDataIntent(topic) || isPageDataDevIntent(topic);
|
const pageDataTask = isPageDataIntent(topic) || isPageDataDevIntent(topic);
|
||||||
const scheduleTimezone = process.env.H5_DEFAULT_TIMEZONE || 'Asia/Shanghai';
|
const scheduleTimezone = process.env.H5_DEFAULT_TIMEZONE || 'Asia/Shanghai';
|
||||||
@@ -22,6 +29,18 @@ export function buildPageGenerateAgentPrompt(intent, { wantsDocx = false, imageP
|
|||||||
const imageBlock = buildWechatPageImageInstruction(imagePolicy, {
|
const imageBlock = buildWechatPageImageInstruction(imagePolicy, {
|
||||||
sourceMessageId: intent?.msgId,
|
sourceMessageId: intent?.msgId,
|
||||||
});
|
});
|
||||||
|
const immediateContextBlock = preferImmediateContext
|
||||||
|
? [
|
||||||
|
'【即时上下文优先】当前需求是对本会话紧邻内容的续作(做成页面、修改页面、重试上次页面或改诗/文章内容)。',
|
||||||
|
'“这个/刚才/做成页面/修改页面/重试上次页面”等指代只能解析为当前会话最近一条 assistant 回复或最近落盘的 public/*.html,禁止用长期记忆、历史偏好或旧任务替换主题。',
|
||||||
|
'如果当前会话没有可辨识的紧邻内容,必须请用户补充主题,禁止猜测并生成其他页面。',
|
||||||
|
'【write_file 硬门槛】必须先 `load_skill` → `static-page-publish`,再用 `write_file`/`edit_file` 写入或更新 `public/*.html` 后才能结束。',
|
||||||
|
'修改已有页面时必须 edit_file 更新同一 HTML 或明确的新文件,禁止只回复文字说明。',
|
||||||
|
'禁止只调用 load_skill、todo_write 或 generate_image 就回复;没有 write_file/edit_file 落盘 HTML 视为未完成。',
|
||||||
|
'缩略图/配图可选:优先完成 HTML 落盘与 mindspace-cover;没有 hero 图时 cover 可用 CSS 渐变或 omit,不要卡在 generate_image。',
|
||||||
|
'',
|
||||||
|
].join('\n')
|
||||||
|
: '';
|
||||||
const coverExample = imageBlock
|
const coverExample = imageBlock
|
||||||
? '<本轮 generate_image 返回的 asset.htmlSrc>'
|
? '<本轮 generate_image 返回的 asset.htmlSrc>'
|
||||||
: 'assets/hero.jpg';
|
: 'assets/hero.jpg';
|
||||||
@@ -42,6 +61,7 @@ export function buildPageGenerateAgentPrompt(intent, { wantsDocx = false, imageP
|
|||||||
'',
|
'',
|
||||||
docxBlock,
|
docxBlock,
|
||||||
imageBlock,
|
imageBlock,
|
||||||
|
immediateContextBlock,
|
||||||
pageDataBlock,
|
pageDataBlock,
|
||||||
'步骤(必须全部完成):',
|
'步骤(必须全部完成):',
|
||||||
pageDataTask
|
pageDataTask
|
||||||
@@ -68,6 +88,19 @@ export function buildPageGenerateAgentPrompt(intent, { wantsDocx = false, imageP
|
|||||||
.join('\n');
|
.join('\n');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function buildImmediateContextPageRepairPrompt(intent) {
|
||||||
|
const topic = String(intent?.agentText ?? intent?.displayText ?? '').trim();
|
||||||
|
return [
|
||||||
|
'【即时上下文页面补写】上一轮页面生成未完成:已 load_skill 但未 write_file 落盘 HTML。',
|
||||||
|
'请立即读取本会话最近一条 assistant 回复中的完整正文,将其排版为完整静态页。',
|
||||||
|
'步骤:确认 static-page-publish 已加载 → 用 write_file 写入 public/*.html(含 mindspace-cover、platform-brand 页脚)→ 确认落盘后再回复唯一正式链接。',
|
||||||
|
'禁止再次只 generate_image 或只回复文字;本轮必须完成 write_file。',
|
||||||
|
topic ? `用户原话:${topic}` : '',
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
export function buildPagePublishFailureText({
|
export function buildPagePublishFailureText({
|
||||||
missingSharePreview = false,
|
missingSharePreview = false,
|
||||||
missingPlatformBrand = false,
|
missingPlatformBrand = false,
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
import { classifyWechatIntent } from './intent/classifier.mjs';
|
||||||
|
import {
|
||||||
|
isWechatSessionPageContinuation,
|
||||||
|
isWechatPageRetryText,
|
||||||
|
isWechatPageEditText,
|
||||||
|
isWechatContentEditFollowup,
|
||||||
|
} from './intent/page-continuation.mjs';
|
||||||
|
|
||||||
|
test('WeChat page continuation detects retry and edit phrasings', () => {
|
||||||
|
assert.equal(isWechatPageRetryText('重试上次页面'), true);
|
||||||
|
assert.equal(isWechatPageEditText('修改刚才生成的页面,背景改成浅蓝色'), true);
|
||||||
|
assert.equal(isWechatContentEditFollowup('把诗里第三段改长一点'), true);
|
||||||
|
|
||||||
|
const retryIntent = classifyWechatIntent({ msgType: 'text', agentText: '重试上次页面' });
|
||||||
|
assert.equal(retryIntent.kind, 'page.generate');
|
||||||
|
assert.equal(isWechatSessionPageContinuation(retryIntent, '重试上次页面'), true);
|
||||||
|
|
||||||
|
const editIntent = classifyWechatIntent({
|
||||||
|
msgType: 'text',
|
||||||
|
agentText: '把页面标题改成《七月清晨》',
|
||||||
|
});
|
||||||
|
assert.equal(editIntent.kind, 'page.generate');
|
||||||
|
assert.equal(isWechatSessionPageContinuation(editIntent, editIntent.topic), true);
|
||||||
|
|
||||||
|
const poemEdit = classifyWechatIntent({ msgType: 'text', agentText: '把诗里第三段改长一点' });
|
||||||
|
assert.equal(poemEdit.kind, 'chat.general');
|
||||||
|
assert.equal(isWechatSessionPageContinuation(poemEdit, '把诗里第三段改长一点'), true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('WeChat page continuation rejects full new-topic page requests', () => {
|
||||||
|
const intent = classifyWechatIntent({
|
||||||
|
msgType: 'text',
|
||||||
|
agentText: '帮我做一个上海旅游攻略页面',
|
||||||
|
});
|
||||||
|
assert.equal(intent.kind, 'page.generate');
|
||||||
|
assert.equal(isWechatSessionPageContinuation(intent, intent.topic), false);
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user