ai-chatbot/tests/routes/canvas-feedback.test.ts

195 lines
6.7 KiB
TypeScript

import { createHash, createHmac } from "node:crypto";
import { expect, test } from "@playwright/test";
import { feedbackMessages } from "@/lib/canvas/feedback-client";
import { feedbackConversationRequests } from "@/lib/canvas/feedback-context";
import { feedbackCommandSchema, type FeedbackSnapshot } from "@/lib/canvas/feedback-contract";
import { buildFeedbackNotification, feedbackReceipt } from "@/lib/canvas/feedback-store";
import {
notificationCenterRequest,
NotificationCenterError,
} from "@/lib/notifications/notification-center";
test("a late failure is associated with its original user message", () => {
const messages = feedbackMessages([
{
id: "first",
role: "user",
parts: [
{ type: "text", text: "第一笔需求" },
{ type: "data-hiddenPrompt", data: "内部信息" },
],
},
{ id: "second", role: "user", parts: [{ type: "text", text: "第二笔需求" }] },
{
id: "reply",
role: "assistant",
parts: [
{
type: "data-imageGenerationStatus",
data: JSON.stringify({
phase: "failed",
userMessageId: "first",
requestId: "original-request",
failure: { message: "参考图读取失败", recommendation: "重新上传原图" },
}),
},
],
},
]);
const requests = feedbackConversationRequests(messages, new Set(["first"]));
expect(requests.find((item) => item.id === "first")).toMatchObject({
prompt: "第一笔需求",
requestId: "original-request",
error: "参考图读取失败\n重新上传原图",
evidence: "server",
});
expect(requests.find((item) => item.id === "second")?.requestId).toBeNull();
expect(JSON.stringify(messages)).not.toContain("内部信息");
});
test("notification uses a fixed recipient, stable event key and full-detail link within the center limit", () => {
const snapshot: FeedbackSnapshot = {
reporter: { id: "reporter", name: "验收用户", email: "test@example.com", department: "设计" },
project: { id: "project", title: "验收画布" },
request: {
key: "image:task",
kind: "image",
id: "task",
requestId: "request",
createdAt: "2026-11-18T08:00:00Z",
prompt: "长提示词".repeat(10000),
status: "failed",
model: "Qwen",
error: "错误".repeat(10000),
evidence: "server",
},
client: {
chatId: null,
messages: [],
pageVersion: "test-release",
capturedAt: "2026-11-18T08:00:00Z",
viewport: { width: 1440, height: 900 },
online: true,
errors: [],
nodes: [],
},
userAgent: "Test browser",
};
const notification = buildFeedbackNotification({
id: "feedback",
description: "补充".repeat(1000),
snapshot,
createdAt: "2026-11-18T08:01:00Z",
appUrl: "https://ai.yydd.ai/",
});
expect(notification).toMatchObject({
recipientAlias: "魔礼红",
idempotencyKey: "canvas-feedback:feedback:v1",
actionUrl: "https://ai.yydd.ai/feedback/feedback",
});
expect(notification.content.length).toBeLessThanOrEqual(4400);
expect(notification.content).toContain("完整内容见反馈详情");
expect(snapshot.request?.prompt.length).toBe(40000);
});
test("accepted queue status does not claim DingTalk delivery", () => {
const accepted = feedbackReceipt({
id: "feedback",
deliveryId: "delivery",
status: "pending",
lastErrorCode: null,
} as any);
expect(accepted.status).toBe("accepted");
expect(accepted.message).toContain("已受理");
expect(accepted.message).not.toContain("已投递");
expect(
feedbackReceipt({
id: "feedback",
deliveryId: "delivery",
status: "failed",
lastErrorCode: "DELIVERY_OUTCOME_UNKNOWN",
} as any).message,
).toContain("避免重复提交");
});
test("signed retries use identical business payload and fresh nonces", async () => {
const originalFetch = globalThis.fetch;
const originalEnv = { ...process.env };
const calls: RequestInit[] = [];
process.env.YYD_NOTIFICATION_CENTER_URL = "https://notify.example.test/notification-center";
process.env.YYD_NOTIFICATION_CENTER_PROJECT_CODE = "feedback-test";
process.env.YYD_NOTIFICATION_CENTER_PROJECT_SECRET = "test-secret-for-signature-verification";
globalThis.fetch = async (_input, init) => {
calls.push(init!);
return new Response(JSON.stringify({ id: "same-delivery", status: "pending" }), {
status: 202,
});
};
try {
const payload = {
idempotencyKey: "feedback:stable",
recipientAlias: "魔礼红",
title: "反馈",
content: "测试",
actionTitle: "详情",
actionUrl: "https://ai.yydd.ai/feedback/test",
};
await notificationCenterRequest("POST", "/v1/notifications", payload);
await notificationCenterRequest("POST", "/v1/notifications", payload);
expect(calls[0].body).toBe(calls[1].body);
const headers = calls[0].headers as Record<string, string>;
expect(headers["x-yyd-nonce"]).not.toBe(
(calls[1].headers as Record<string, string>)["x-yyd-nonce"],
);
const canonical = [
headers["x-yyd-timestamp"],
headers["x-yyd-nonce"],
"POST",
"/v1/notifications",
createHash("sha256")
.update(calls[0].body as string)
.digest("hex"),
].join("\n");
expect(headers["x-yyd-signature"]).toBe(
createHmac("sha256", process.env.YYD_NOTIFICATION_CENTER_PROJECT_SECRET!)
.update(canonical)
.digest("hex"),
);
globalThis.fetch = async () =>
new Response(JSON.stringify({ error: "SIGNATURE_INVALID" }), { status: 401 });
await expect(notificationCenterRequest("GET", "/v1/notifications/test")).rejects.toMatchObject({
code: "SIGNATURE_INVALID",
retryable: false,
});
globalThis.fetch = async () => {
throw new Error("private transport detail");
};
await expect(notificationCenterRequest("GET", "/v1/notifications/test")).rejects.toEqual(
new NotificationCenterError("NOTIFICATION_CONNECTION_FAILED", true),
);
} finally {
globalThis.fetch = originalFetch;
process.env = originalEnv;
}
});
test("feedback input bounds and fixed contract exclude recipient and arbitrary browser objects", () => {
const result = feedbackCommandSchema.parse({
action: "context",
recipientAlias: "其他人",
client: {
chatId: null,
messages: [],
pageVersion: "test",
capturedAt: new Date().toISOString(),
viewport: { width: 1000, height: 700 },
online: true,
errors: [],
cookies: "private",
},
});
expect(result).not.toHaveProperty("recipientAlias");
expect(result.client).not.toHaveProperty("cookies");
expect(result.client.nodes).toEqual([]);
});