diff --git a/.env.example b/.env.example
index 948807853..e40b60974 100644
--- a/.env.example
+++ b/.env.example
@@ -40,6 +40,11 @@ EMAIL_VERIFICATION_SECRET=
# Optional scheduled job protection.
CRON_SECRET=
+# Canvas feedback: server-side project credentials for the shared notification center.
+YYD_NOTIFICATION_CENTER_URL=https://sc.jiansun.vip/notification-center
+YYD_NOTIFICATION_CENTER_PROJECT_CODE=
+YYD_NOTIFICATION_CENTER_PROJECT_SECRET=
+
# -----------------------------------------------------------------------------
# Database
# -----------------------------------------------------------------------------
diff --git a/app/api/canvas/[id]/feedback/route.ts b/app/api/canvas/[id]/feedback/route.ts
new file mode 100644
index 000000000..12246e710
--- /dev/null
+++ b/app/api/canvas/[id]/feedback/route.ts
@@ -0,0 +1,92 @@
+import { after, NextResponse } from "next/server";
+import { z, ZodError } from "zod";
+import { auth } from "@/app/(auth)/auth";
+import { CanvasFeedbackError, collectCanvasFeedbackContext } from "@/lib/canvas/feedback-context";
+import { feedbackCommandSchema } from "@/lib/canvas/feedback-contract";
+import {
+ deliverCanvasFeedback,
+ feedbackReceipt,
+ findCanvasFeedback,
+ refreshCanvasFeedback,
+ saveCanvasFeedback,
+} from "@/lib/canvas/feedback-store";
+
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+const response = (data: unknown, status = 200) =>
+ NextResponse.json(data, { status, headers: { "Cache-Control": "no-store" } });
+function failure(error: unknown) {
+ if (error instanceof CanvasFeedbackError) return response({ error: error.message }, error.status);
+ if (error instanceof ZodError || error instanceof SyntaxError)
+ return response({ error: "反馈资料格式不正确,请重新打开问题反馈后重试。" }, 400);
+ console.error("[Canvas feedback] request failed", {
+ errorType: error instanceof Error ? error.name : "unknown",
+ });
+ return response({ error: "反馈暂未保存成功,请保留问题说明,稍后重试。" }, 503);
+}
+
+export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {
+ try {
+ const session = await auth();
+ if (!session?.user?.id) return response({ error: "登录已过期,请登录后发送反馈。" }, 401);
+ const projectId = z
+ .string()
+ .uuid()
+ .parse((await params).id);
+ const raw = await request.text();
+ if (new TextEncoder().encode(raw).byteLength > 262144)
+ return response({ error: "反馈资料过大,请减少补充说明后重试。" }, 413);
+ const command = feedbackCommandSchema.parse(JSON.parse(raw));
+ if (command.action === "submit") {
+ const existing = await findCanvasFeedback(command.id);
+ if (existing) {
+ if (existing.userId !== session.user.id || existing.projectId !== projectId)
+ throw new CanvasFeedbackError("反馈编号不可用", 409);
+ return response({ feedback: feedbackReceipt(await refreshCanvasFeedback(existing)) });
+ }
+ }
+ const context = await collectCanvasFeedbackContext(
+ session.user.id,
+ projectId,
+ command.client,
+ command.action === "submit" ? command.selection : null,
+ );
+ if (command.action === "context") return response({ context });
+ const selected = context.requests.find((item) => item.key === command.selection) || null;
+ const row = await saveCanvasFeedback({
+ id: command.id,
+ userId: session.user.id,
+ description: command.description,
+ appUrl: process.env.NEXT_PUBLIC_APP_URL || new URL(request.url).origin,
+ snapshot: {
+ reporter: context.reporter,
+ project: context.project,
+ request: selected,
+ client: command.client,
+ userAgent: (request.headers.get("user-agent") || "").slice(0, 512),
+ },
+ });
+ after(() => deliverCanvasFeedback(row.id));
+ return response({ feedback: feedbackReceipt(row) }, 202);
+ } catch (error) {
+ return failure(error);
+ }
+}
+
+export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
+ try {
+ const session = await auth();
+ if (!session?.user?.id) return response({ error: "登录已过期,请登录后查看反馈状态。" }, 401);
+ const projectId = z
+ .string()
+ .uuid()
+ .parse((await params).id);
+ const id = z.string().uuid().parse(new URL(request.url).searchParams.get("feedbackId"));
+ const row = await findCanvasFeedback(id);
+ if (!row || row.userId !== session.user.id || row.projectId !== projectId)
+ throw new CanvasFeedbackError("反馈记录不存在", 404);
+ return response({ feedback: feedbackReceipt(await refreshCanvasFeedback(row)) });
+ } catch (error) {
+ return failure(error);
+ }
+}
diff --git a/app/canvas/[id]/CanvasEditorLegacyPageClient.tsx b/app/canvas/[id]/CanvasEditorLegacyPageClient.tsx
index 634c5c2fe..b984bbfb5 100644
--- a/app/canvas/[id]/CanvasEditorLegacyPageClient.tsx
+++ b/app/canvas/[id]/CanvasEditorLegacyPageClient.tsx
@@ -11406,6 +11406,7 @@ export default function CanvasEditorLegacyPage({
setPanelMode("fileList");
}}
projectTitle={projectTitle}
+ projectId={id}
rightInset={panelOcclusionRight}
/>
)}
diff --git a/app/feedback/[id]/page.tsx b/app/feedback/[id]/page.tsx
new file mode 100644
index 000000000..3839cb1fd
--- /dev/null
+++ b/app/feedback/[id]/page.tsx
@@ -0,0 +1,107 @@
+import { notFound, redirect } from "next/navigation";
+import { z } from "zod";
+import { auth } from "@/app/(auth)/auth";
+import { feedbackReceipt, findCanvasFeedback } from "@/lib/canvas/feedback-store";
+import { formatFeedbackTime } from "@/lib/canvas/feedback-contract";
+
+export const dynamic = "force-dynamic";
+
+export default async function CanvasFeedbackPage({ params }: { params: Promise<{ id: string }> }) {
+ const session = await auth();
+ if (!session?.user?.id) redirect("/login");
+ const id = (await params).id;
+ if (!z.string().uuid().safeParse(id).success) notFound();
+ const feedback = await findCanvasFeedback(id);
+ if (!feedback || (feedback.userId !== session.user.id && session.user.type !== "admin"))
+ notFound();
+ const { reporter, project, request, client, userAgent } = feedback.snapshot;
+ const fields = [
+ ["反馈编号", feedback.id],
+ ["反馈人", `${reporter.name} · ${reporter.email} · ${reporter.department || "未登记部门"}`],
+ ["用户编号", reporter.id],
+ ["反馈时间", formatFeedbackTime(feedback.createdAt.toISOString())],
+ ["画布", `${project.title}(${project.id})`],
+ ["对话编号", client.chatId || "未打开对话"],
+ ["请求号", request?.requestId || "尚未获取"],
+ ["任务或消息编号", request?.id || "未关联"],
+ ["请求时间", request?.createdAt ? formatFeedbackTime(request.createdAt) : "未记录"],
+ ["状态与模型", `${request?.status || "页面问题"} / ${request?.model || "未记录"}`],
+ [
+ "处理耗时",
+ request?.durationMs != null
+ ? `${(request.durationMs / 1000).toFixed(1)} 秒`
+ : "未记录或尚未结束",
+ ],
+ [
+ "资料来源",
+ request?.evidence === "browser"
+ ? "浏览器当前对话,服务端尚无对应消息记录"
+ : "服务端记录及浏览器当前页面",
+ ],
+ ["页面版本", client.pageVersion],
+ ["浏览器", userAgent],
+ [
+ "窗口与网络",
+ `${client.viewport.width} × ${client.viewport.height} · ${client.online ? "在线" : "离线"}`,
+ ],
+ ];
+ return (
+
+ 画布问题反馈
+ {feedbackReceipt(feedback).message}
+
+ {fields.map(([label, value]) => (
+
+
- {label}
+ - {value}
+
+ ))}
+
+ {[
+ ["用户说明", feedback.description || "未补充说明"],
+ ["请求内容", request?.prompt || "未关联具体请求"],
+ ["错误信息", request?.error || client.errors.join("\n") || "未记录明确错误"],
+ ].map(([label, value]) => (
+
+ ))}
+ {request?.parameters && Object.keys(request.parameters).length > 0 && (
+
+ 请求参数
+
+ {JSON.stringify(request.parameters, null, 2)}
+
+
+ )}
+ {client.nodes.length > 0 && (
+
+ 相关画布节点
+
+ {JSON.stringify(client.nodes, null, 2)}
+
+
+ )}
+
+ 当前对话上下文
+
+ {client.messages.map((item) => (
+
+
+ {item.role === "user" ? "用户" : "助手"} · {item.id}
+
+
{item.text}
+
+ ))}
+
+
+
+ 打开相关画布
+
+
+ );
+}
diff --git a/components/canvas/CanvasChatPanel.tsx b/components/canvas/CanvasChatPanel.tsx
index b88bc921b..9032015fa 100644
--- a/components/canvas/CanvasChatPanel.tsx
+++ b/components/canvas/CanvasChatPanel.tsx
@@ -1,4 +1,6 @@
"use client";
+import { CANVAS_FEEDBACK_CONTEXT_EVENT, feedbackMessages, type FeedbackCaptureEvent } from "@/lib/canvas/feedback-client";
+import { CanvasFeedbackDialog } from "./CanvasFeedbackDialog";
import { advancePastAtomicRanges, scanMarkdownImageStreaming } from "@/lib/canvas/markdown-image-streaming";
import { useChat } from "@ai-sdk/react";
@@ -4429,6 +4431,15 @@ export function CanvasChatPanel({
// 获取纯 UUID(去掉 canvas- 前缀)用于 API 调用
const rawChatId = toRawCanvasChatId(activeChatId);
+ useEffect(() => {
+ const collectFeedback = (event: Event) => {
+ const detail = (event as FeedbackCaptureEvent).detail;
+ if (detail.projectId !== canvasId) return;
+ detail.receive({ chatId: rawChatId, messages: feedbackMessages(activeMessagesRef.current) });
+ };
+ window.addEventListener(CANVAS_FEEDBACK_CONTEXT_EVENT, collectFeedback);
+ return () => window.removeEventListener(CANVAS_FEEDBACK_CONTEXT_EVENT, collectFeedback);
+ }, [canvasId, rawChatId]);
const buildHistoryMessagesUrl = useCallback(
(targetRawChatId: string, options?: { cacheBust?: boolean }) => {
const params = new URLSearchParams({
@@ -15887,6 +15898,9 @@ export function CanvasChatPanel({
+
+
+
+
);
}
diff --git a/docs/canvas-feedback.md b/docs/canvas-feedback.md
new file mode 100644
index 000000000..2f706e53d
--- /dev/null
+++ b/docs/canvas-feedback.md
@@ -0,0 +1,38 @@
+# 画布问题反馈
+
+画布顶部提供“问题反馈”;小窗口及视频画布在对话顶部提供入口。用户确认关联请求、补充说明后发送。反馈不调用画布保存或生成接口。
+
+## 资料与权限
+
+- 用户身份由登录会话及服务端用户表确定;收件人固定为准确花名“魔礼红”。
+- 请求按当前用户、画布及对话查询。图片任务通过当前对话请求号或画布节点任务号关联,不查询账号下任意最近任务。
+- 服务端只读取任务表,不调用带恢复、执行或状态变更副作用的任务查询接口。
+- 自动采集当前对话最近 12 条公开消息(文字总量最多 48,000 字符)、最多 20 个节点的编号、尺寸及任务号,以及页面版本、窗口、网络和最近脚本错误。截图、图片二进制、内部提示词、Cookie 和认证头不采集。
+- 用户可以切换关联请求或选择页面问题。尚未持久化的消息标记为浏览器来源;缺少请求号时保留消息或任务编号,不推测编号。
+- 完整反馈保存在 `CanvasFeedback`;通知正文为限长摘要,按钮打开 `/feedback/{id}`。详情仅反馈本人及平台管理员可读。画布删除后反馈仍可查看,账号删除会级联删除其反馈。
+
+## 提交和投递
+
+- 浏览器在首次提交时固定反馈 UUID 和请求内容,在当前标签页保留提交资料。重复点击、响应丢失后的重试和刷新恢复均沿用原 UUID。
+- 服务端按 UUID 插入一次,持久化的通知内容保持不变。通知中心幂等键为 `canvas-feedback:{id}:v1`;每次 HTTP 请求生成新 nonce。
+- 保存成功后异步提交通知。节点运行时每分钟继续处理尚未入队的反馈,最多尝试 5 次;连接异常、5xx 和 429 按 1、5、15、30 分钟间隔重试,其他明确拒绝停止重试。
+- 通知中心返回投递 ID 后只查询该单,不重新发送。中心负责实际投递及其重试;`DELIVERY_OUTCOME_UNKNOWN` 不自动补发。
+- `pending`(本地保存)、`accepted`(中心受理)、`sent/unread/read`(钉钉接受或阅读)、`failed` 分别显示,不把受理当作送达。
+
+## 服务端配置
+
+```dotenv
+YYD_NOTIFICATION_CENTER_URL=https://sc.jiansun.vip/notification-center
+YYD_NOTIFICATION_CENTER_PROJECT_CODE=
+YYD_NOTIFICATION_CENTER_PROJECT_SECRET=
+```
+
+项目代码及密钥使用通知中心分配值,仅配置到服务端。消息签名沿用通知中心 HMAC 契约,签名路径不含公网 `/notification-center` 前缀。
+
+上线前先备份生产环境配置,并单独执行加表迁移 `0105_add_canvas_feedback.sql`;本次迁移仅新增反馈表和索引,不修改任务、画布、计费或原通知表。应用发布仍使用既有构建机直传流程。回滚应用可保留新增表,尚未入队的反馈在恢复新版后继续处理。
+
+## 验证
+
+`tests/routes/canvas-feedback.test.ts` 覆盖错误与原消息关联、固定收件人及摘要长度、受理状态、签名和重试边界;`tests/e2e/canvas-issue-feedback.test.ts` 覆盖自动采集、重复点击、丢失响应后刷新恢复和窄屏操作。
+
+生产验收使用维护者自己的独立测试画布及已失败的测试记录,不提交模型任务。核对反馈与通知各只有一条、原任务 attempts 不变;查询通知中心最终状态,并核对完整反馈页面权限。
diff --git a/instrumentation.ts b/instrumentation.ts
index 49a55aea1..4845c2423 100644
--- a/instrumentation.ts
+++ b/instrumentation.ts
@@ -12,6 +12,11 @@ export function register() {
void import("@/lib/canvas/image-task-queue")
.then(({ resumeDetailReplacementBatchTasks }) => resumeDetailReplacementBatchTasks())
.catch((error) => console.error("[Detail Replacement Batch] Recovery failed", error));
+ if (process.env.YYD_NOTIFICATION_CENTER_PROJECT_SECRET) {
+ void import("@/lib/canvas/feedback-store")
+ .then(({ runCanvasFeedbackDelivery }) => runCanvasFeedbackDelivery())
+ .catch(() => console.error("[Canvas feedback] notification queue unavailable"));
+ }
};
setTimeout(recover, 5000).unref?.();
setInterval(recover, 60_000).unref?.();
diff --git a/lib/canvas/feedback-client.ts b/lib/canvas/feedback-client.ts
new file mode 100644
index 000000000..0394c527f
--- /dev/null
+++ b/lib/canvas/feedback-client.ts
@@ -0,0 +1,78 @@
+import type { FeedbackMessage } from "./feedback-contract";
+
+export const CANVAS_FEEDBACK_CONTEXT_EVENT = "canvas-feedback-context";
+export type FeedbackChatCapture = { chatId: string | null; messages: FeedbackMessage[] };
+export type FeedbackCaptureEvent = CustomEvent<{
+ projectId: string;
+ receive: (value: FeedbackChatCapture) => void;
+}>;
+
+export function captureFeedbackChat(projectId: string): FeedbackChatCapture {
+ let result: FeedbackChatCapture = { chatId: null, messages: [] };
+ window.dispatchEvent(
+ new CustomEvent(CANVAS_FEEDBACK_CONTEXT_EVENT, {
+ detail: {
+ projectId,
+ receive: (value: FeedbackChatCapture) => {
+ result = value;
+ },
+ },
+ }),
+ );
+ return result;
+}
+
+export function feedbackMessages(messages: readonly unknown[]): FeedbackMessage[] {
+ let remaining = 48000;
+ return messages
+ .slice(-12)
+ .reverse()
+ .flatMap((value: any) => {
+ if (!value || !["user", "assistant"].includes(value.role) || typeof value.id !== "string")
+ return [];
+ const parts = Array.isArray(value.parts) ? value.parts : [];
+ let state: any = null;
+ for (const part of parts) {
+ if (part.type !== "data-imageGenerationStatus") continue;
+ try {
+ state = typeof part.data === "string" ? JSON.parse(part.data) : part.data;
+ } catch {
+ /* Keep public message text when a stream part is incomplete. */
+ }
+ }
+ const fullText = parts
+ .filter((part: any) => part.type === "text")
+ .map((part: any) => String(part.text || ""))
+ .join("\n");
+ const text = fullText.slice(0, Math.min(16000, remaining));
+ remaining -= text.length;
+ return [
+ {
+ id: value.id.slice(0, 180),
+ role: value.role,
+ text,
+ ...(value.createdAt
+ ? {
+ createdAt: String(
+ value.createdAt instanceof Date ? value.createdAt.toISOString() : value.createdAt,
+ ).slice(0, 64),
+ }
+ : {}),
+ ...(state?.requestId ? { requestId: String(state.requestId).slice(0, 180) } : {}),
+ ...(state?.userMessageId
+ ? { userMessageId: String(state.userMessageId).slice(0, 180) }
+ : {}),
+ ...(state?.phase ? { status: String(state.phase).slice(0, 64) } : {}),
+ ...(state?.failure?.message
+ ? {
+ error: [state.failure.message, state.failure.recommendation]
+ .filter(Boolean)
+ .join("\n")
+ .slice(0, 2000),
+ }
+ : {}),
+ },
+ ];
+ })
+ .reverse();
+}
diff --git a/lib/canvas/feedback-context.ts b/lib/canvas/feedback-context.ts
new file mode 100644
index 000000000..abb3dd825
--- /dev/null
+++ b/lib/canvas/feedback-context.ts
@@ -0,0 +1,301 @@
+import "server-only";
+import { and, asc, desc, eq, gte, inArray, sql } from "drizzle-orm";
+import { db } from "@/lib/db";
+import {
+ canvasProject,
+ canvasAgentRun,
+ canvasCapabilityTask,
+ canvasImageTask,
+ chat,
+ message,
+ user,
+} from "@/lib/db/schema";
+import { feedbackMessages } from "./feedback-client";
+import type {
+ FeedbackClient,
+ FeedbackContext,
+ FeedbackMessage,
+ FeedbackRequest,
+} from "./feedback-contract";
+
+export class CanvasFeedbackError extends Error {
+ status: number;
+ constructor(message: string, status = 400) {
+ super(message);
+ this.status = status;
+ }
+}
+const text = (value: unknown) => (typeof value === "string" ? value : "");
+const duration = (started: Date | null, completed: Date | null) =>
+ started && completed ? Math.max(0, completed.getTime() - started.getTime()) : null;
+function requestSummary(
+ column: typeof canvasImageTask.request | typeof canvasCapabilityTask.request,
+) {
+ return sql>`jsonb_build_object(
+ 'prompt', coalesce(${column}->'params'->>'prompt', ${column}->'input'->>'prompt', ${column}->>'displayPrompt', ${column}->>'prompt'),
+ 'model', coalesce(${column}->'params'->>'model', ${column}->>'model'))`;
+}
+function requestParameters(request: Record) {
+ const values = request.params || request.input || request;
+ const keys = [
+ "aspectRatio",
+ "imageSize",
+ "imageCount",
+ "sourceNodeIds",
+ "targetNodeIds",
+ "imageUrl",
+ "sourceImageUrl",
+ "referenceImage",
+ "referenceImages",
+ "region",
+ "selectionRect",
+ "width",
+ "height",
+ "operation",
+ "capabilityId",
+ ];
+ const compact = (value: unknown): unknown => {
+ if (typeof value === "string")
+ return value.startsWith("data:") ? "内嵌图片,已省略二进制内容" : value.slice(0, 4000);
+ if (Array.isArray(value)) return value.slice(0, 20).map(compact);
+ return value;
+ };
+ return Object.fromEntries(
+ keys.filter((key) => values[key] !== undefined).map((key) => [key, compact(values[key])]),
+ );
+}
+
+export function feedbackConversationRequests(
+ messages: FeedbackMessage[],
+ verifiedIds: Set,
+) {
+ const requests: FeedbackRequest[] = [];
+ for (const item of messages) {
+ if (item.role === "user") {
+ requests.push({
+ key: `message:${item.id}`,
+ kind: "message",
+ id: item.id,
+ requestId: null,
+ createdAt: item.createdAt || "",
+ prompt: item.text,
+ status: "未获取任务状态",
+ model: null,
+ error: null,
+ evidence: verifiedIds.has(item.id) ? "server" : "browser",
+ });
+ } else {
+ const latest = item.userMessageId
+ ? requests.find((request) => request.id === item.userMessageId)
+ : requests.at(-1);
+ if (!latest) continue;
+ if (item.requestId) latest.requestId = item.requestId;
+ if (item.status) latest.status = item.status;
+ if (item.error) latest.error = item.error;
+ }
+ }
+ return requests.filter((item) => item.prompt).reverse();
+}
+
+export async function collectCanvasFeedbackContext(
+ userId: string,
+ projectId: string,
+ client: FeedbackClient,
+ selection?: string | null,
+): Promise {
+ const [project] = await db
+ .select({ id: canvasProject.id, title: canvasProject.title })
+ .from(canvasProject)
+ .where(and(eq(canvasProject.id, projectId), eq(canvasProject.userId, userId)))
+ .limit(1);
+ if (!project) throw new CanvasFeedbackError("画布不存在或无权反馈该画布", 404);
+ const [reporter] = await db
+ .select({ id: user.id, name: user.name, email: user.email, department: user.department })
+ .from(user)
+ .where(eq(user.id, userId))
+ .limit(1);
+ if (!reporter) throw new CanvasFeedbackError("登录状态已失效,请重新登录", 401);
+ const [kind, selectedId] = (selection || "").split(":", 2);
+ const validId = /^[0-9a-f-]{36}$/i.test(selectedId || "");
+ const selectedMessage =
+ kind === "message" && validId && client.chatId
+ ? (
+ await db
+ .select({ createdAt: message.createdAt })
+ .from(message)
+ .innerJoin(chat, and(eq(chat.id, message.chatId), eq(chat.userId, userId)))
+ .where(and(eq(message.chatId, client.chatId), eq(message.id, selectedId)))
+ .limit(1)
+ )[0]
+ : null;
+ const [runs, capabilities, storedMessages] = await Promise.all([
+ db
+ .select({
+ id: canvasAgentRun.id,
+ createdAt: canvasAgentRun.createdAt,
+ status: canvasAgentRun.status,
+ objective: sql`${canvasAgentRun.snapshot}->>'objective'`,
+ errors: sql<
+ string[]
+ >`jsonb_path_query_array(${canvasAgentRun.snapshot}, '$.calls[*].error')`,
+ })
+ .from(canvasAgentRun)
+ .where(
+ and(
+ eq(canvasAgentRun.userId, userId),
+ eq(canvasAgentRun.projectId, projectId),
+ ...(client.chatId ? [eq(canvasAgentRun.chatId, client.chatId)] : []),
+ ...(kind === "agent" && validId ? [eq(canvasAgentRun.id, selectedId)] : []),
+ ),
+ )
+ .orderBy(desc(canvasAgentRun.createdAt))
+ .limit(10),
+ db
+ .select({
+ id: canvasCapabilityTask.id,
+ requestId: canvasCapabilityTask.requestId,
+ capabilityId: canvasCapabilityTask.capabilityId,
+ createdAt: canvasCapabilityTask.createdAt,
+ startedAt: canvasCapabilityTask.startedAt,
+ completedAt: canvasCapabilityTask.completedAt,
+ status: canvasCapabilityTask.status,
+ error: canvasCapabilityTask.error,
+ request:
+ kind === "capability" && validId
+ ? canvasCapabilityTask.request
+ : requestSummary(canvasCapabilityTask.request),
+ })
+ .from(canvasCapabilityTask)
+ .where(
+ and(
+ eq(canvasCapabilityTask.userId, userId),
+ eq(canvasCapabilityTask.projectId, projectId),
+ ...(kind === "capability" && validId ? [eq(canvasCapabilityTask.id, selectedId)] : []),
+ ),
+ )
+ .orderBy(desc(canvasCapabilityTask.createdAt))
+ .limit(10),
+ client.chatId
+ ? db
+ .select({
+ id: message.id,
+ role: message.role,
+ parts: message.parts,
+ createdAt: message.createdAt,
+ })
+ .from(message)
+ .innerJoin(chat, and(eq(chat.id, message.chatId), eq(chat.userId, userId)))
+ .where(
+ and(
+ eq(message.chatId, client.chatId),
+ ...(selectedMessage ? [gte(message.createdAt, selectedMessage.createdAt)] : []),
+ ),
+ )
+ .orderBy(selectedMessage ? asc(message.createdAt) : desc(message.createdAt))
+ .limit(12)
+ : Promise.resolve([]),
+ ]);
+ const verifiedIds = new Set(storedMessages.map((item) => item.id));
+ const serverById = new Map(
+ feedbackMessages(selectedMessage ? storedMessages : [...storedMessages].reverse()).map(
+ (item) => [item.id, item],
+ ),
+ );
+ const browserIds = new Set(client.messages.map((item) => item.id));
+ const combined = [...serverById.values()].filter((item) => !browserIds.has(item.id));
+ combined.push(...client.messages.map((item) => ({ ...item, ...serverById.get(item.id) })));
+ // Browser stream metadata can arrive before the final assistant row is persisted.
+ const conversation = feedbackConversationRequests(combined, verifiedIds);
+ const imageIds = Array.from(
+ new Set(
+ [
+ ...conversation.map((item) => item.requestId),
+ ...client.nodes.map((node) => node.taskId),
+ ].filter((id): id is string => Boolean(id && /^[0-9a-f-]{36}$/i.test(id))),
+ ),
+ );
+ if (kind === "image" && validId) imageIds.push(selectedId);
+ const images = imageIds.length
+ ? await db
+ .select({
+ id: canvasImageTask.id,
+ createdAt: canvasImageTask.createdAt,
+ startedAt: canvasImageTask.startedAt,
+ completedAt: canvasImageTask.completedAt,
+ status: canvasImageTask.status,
+ error: canvasImageTask.error,
+ request:
+ kind === "image" && validId
+ ? canvasImageTask.request
+ : requestSummary(canvasImageTask.request),
+ })
+ .from(canvasImageTask)
+ .where(
+ and(
+ eq(canvasImageTask.userId, userId),
+ inArray(canvasImageTask.id, imageIds),
+ ...(kind === "image" && validId ? [eq(canvasImageTask.id, selectedId)] : []),
+ ),
+ )
+ .limit(12)
+ : [];
+ const requests: FeedbackRequest[] = [
+ ...conversation,
+ ...runs.map(
+ (run): FeedbackRequest => ({
+ key: `agent:${run.id}`,
+ kind: "agent",
+ id: run.id,
+ requestId: run.id,
+ createdAt: run.createdAt.toISOString(),
+ prompt: run.objective || "Agent 任务",
+ status: run.status,
+ model: null,
+ error: (run.errors || []).join("\n") || null,
+ evidence: "server",
+ }),
+ ),
+ ...capabilities.map((task): FeedbackRequest => {
+ const request = task.request as Record;
+ return {
+ key: `capability:${task.id}`,
+ kind: "capability",
+ id: task.id,
+ requestId: task.requestId,
+ createdAt: task.createdAt.toISOString(),
+ prompt:
+ text(request.params?.prompt) ||
+ text(request.input?.prompt) ||
+ text(request.prompt) ||
+ task.capabilityId,
+ status: task.status,
+ model: text(request.params?.model) || text(request.model) || null,
+ error: task.error,
+ durationMs: duration(task.startedAt, task.completedAt),
+ parameters: requestParameters(request),
+ evidence: "server",
+ };
+ }),
+ ...images.map((task): FeedbackRequest => {
+ const request = task.request as Record;
+ return {
+ key: `image:${task.id}`,
+ kind: "image",
+ id: task.id,
+ requestId: task.id,
+ createdAt: task.createdAt.toISOString(),
+ prompt: text(request.displayPrompt) || text(request.prompt),
+ status: task.status,
+ model: text(request.model) || null,
+ error: task.error,
+ durationMs: duration(task.startedAt, task.completedAt),
+ parameters: requestParameters(request),
+ evidence: "server",
+ };
+ }),
+ ];
+ requests.sort((a, b) => (Date.parse(b.createdAt) || 0) - (Date.parse(a.createdAt) || 0));
+ if (selection && !requests.some((item) => item.key === selection))
+ throw new CanvasFeedbackError("关联请求已变化,请重新选择要反馈的请求", 409);
+ return { project, reporter: { ...reporter, name: reporter.name || reporter.email }, requests };
+}
diff --git a/lib/canvas/feedback-contract.ts b/lib/canvas/feedback-contract.ts
new file mode 100644
index 000000000..7aa33ea5d
--- /dev/null
+++ b/lib/canvas/feedback-contract.ts
@@ -0,0 +1,100 @@
+import { z } from "zod";
+
+export const feedbackMessageSchema = z.object({
+ id: z.string().max(180),
+ role: z.enum(["user", "assistant"]),
+ text: z.string().max(16000),
+ createdAt: z.string().max(64).optional(),
+ requestId: z.string().max(180).optional(),
+ status: z.string().max(64).optional(),
+ error: z.string().max(2000).optional(),
+ userMessageId: z.string().max(180).optional(),
+});
+export const feedbackClientSchema = z.object({
+ chatId: z.string().uuid().nullable(),
+ messages: z.array(feedbackMessageSchema).max(12),
+ pageVersion: z.string().max(100),
+ capturedAt: z.string().datetime(),
+ viewport: z.object({
+ width: z.number().int().min(0).max(30000),
+ height: z.number().int().min(0).max(30000),
+ }),
+ online: z.boolean(),
+ errors: z.array(z.string().max(2000)).max(5),
+ nodes: z
+ .array(
+ z.object({
+ id: z.string().max(180),
+ type: z.string().max(64),
+ title: z.string().max(256),
+ status: z.string().max(64),
+ taskId: z.string().max(180),
+ width: z.number().optional(),
+ height: z.number().optional(),
+ }),
+ )
+ .max(20)
+ .default([]),
+});
+export const feedbackCommandSchema = z.discriminatedUnion("action", [
+ z.object({ action: z.literal("context"), client: feedbackClientSchema }),
+ z.object({
+ action: z.literal("submit"),
+ id: z.string().uuid(),
+ description: z.string().trim().max(2000),
+ selection: z.string().max(220).nullable(),
+ client: feedbackClientSchema,
+ }),
+]);
+export type FeedbackClient = z.infer;
+export type FeedbackMessage = z.infer;
+export type FeedbackRequest = {
+ key: string;
+ kind: "message" | "agent" | "capability" | "image";
+ id: string;
+ requestId: string | null;
+ createdAt: string;
+ prompt: string;
+ status: string;
+ model: string | null;
+ error: string | null;
+ durationMs?: number | null;
+ parameters?: Record;
+ evidence: "server" | "browser";
+};
+export type FeedbackContext = {
+ reporter: { id: string; name: string; email: string; department: string | null };
+ project: { id: string; title: string };
+ requests: FeedbackRequest[];
+};
+export type FeedbackSnapshot = Omit & {
+ request: FeedbackRequest | null;
+ client: FeedbackClient;
+ userAgent: string;
+};
+export type FeedbackReceipt = {
+ id: string;
+ status: string;
+ deliveryId: string | null;
+ message: string;
+};
+
+export function feedbackStatusMessage(status: string, errorCode?: string | null) {
+ if (["sent", "unread", "read"].includes(status)) return "反馈已投递给魔礼红。";
+ if (status === "failed")
+ return errorCode === "DELIVERY_OUTCOME_UNKNOWN"
+ ? "反馈已保存,但钉钉投递结果暂无法确认。请保留反馈编号,避免重复提交。"
+ : "反馈已保存,但钉钉通知投递失败。请保留反馈编号并联系管理员。";
+ if (status === "pending") return "反馈已保存,正在提交通知;短暂故障会自动重试,无需再次反馈。";
+ return "反馈已保存,通知中心已受理,等待投递给魔礼红。";
+}
+
+export function formatFeedbackTime(value: string) {
+ if (!Number.isFinite(Date.parse(value))) return "未记录";
+ return new Intl.DateTimeFormat("zh-CN", {
+ timeZone: "Asia/Shanghai",
+ dateStyle: "short",
+ timeStyle: "medium",
+ hour12: false,
+ }).format(new Date(value));
+}
diff --git a/lib/canvas/feedback-store.ts b/lib/canvas/feedback-store.ts
new file mode 100644
index 000000000..fdcf703d0
--- /dev/null
+++ b/lib/canvas/feedback-store.ts
@@ -0,0 +1,189 @@
+import "server-only";
+import { and, asc, eq, isNull, lt, lte, sql } from "drizzle-orm";
+import { db } from "@/lib/db";
+import { canvasFeedback } from "@/lib/db/schema";
+import {
+ notificationCenterConfigured,
+ notificationCenterRequest,
+ NotificationCenterError,
+ type NotificationPayload,
+} from "@/lib/notifications/notification-center";
+import { CanvasFeedbackError } from "./feedback-context";
+import {
+ feedbackStatusMessage,
+ formatFeedbackTime,
+ type FeedbackReceipt,
+ type FeedbackSnapshot,
+} from "./feedback-contract";
+
+type FeedbackRow = typeof canvasFeedback.$inferSelect;
+const backoffMs = [60_000, 300_000, 900_000, 1800_000, 1800_000];
+const clip = (value: string, length: number) =>
+ value.length > length ? `${value.slice(0, length)}…(完整内容见反馈详情)` : value;
+const quote = (value: string) =>
+ value
+ .replace(/\r\n?/g, "\n")
+ .split("\n")
+ .map((line) => `> ${line}`)
+ .join("\n");
+
+export function buildFeedbackNotification(input: {
+ id: string;
+ description: string;
+ snapshot: FeedbackSnapshot;
+ createdAt: string;
+ appUrl: string;
+}): NotificationPayload {
+ const { reporter, project, request } = input.snapshot;
+ const content = [
+ `**反馈人:** ${reporter.name} · ${reporter.department || "未登记部门"}`,
+ `**反馈时间:** ${formatFeedbackTime(input.createdAt)}`,
+ `**画布:** ${project.title}`,
+ `**请求时间:** ${request?.createdAt ? formatFeedbackTime(request.createdAt) : "未关联请求"}`,
+ `**请求号:** ${request?.requestId || "尚未获取;可通过消息或任务编号排查"}`,
+ `**状态 / 模型:** ${request?.status || "页面问题"} / ${request?.model || "未记录"}`,
+ `**处理耗时:** ${request?.durationMs != null ? `${(request.durationMs / 1000).toFixed(1)} 秒` : "未记录或尚未结束"}`,
+ `**用户说明**\n${quote(clip(input.description || "用户未补充说明", 900))}`,
+ `**请求内容**\n${quote(clip(request?.prompt || "未关联具体请求", 1600))}`,
+ `**错误信息**\n${quote(clip(request?.error || input.snapshot.client.errors.join("\n") || "未记录明确错误", 600))}`,
+ `**反馈编号:** ${input.id}`,
+ `**页面版本:** ${input.snapshot.client.pageVersion}`,
+ ].join("\n\n");
+ return {
+ idempotencyKey: `canvas-feedback:${input.id}:v1`,
+ recipientAlias: "魔礼红",
+ title: "画布问题反馈",
+ content: clip(content, 4400),
+ actionTitle: "查看完整反馈",
+ actionUrl: `${input.appUrl.replace(/\/$/, "")}/feedback/${input.id}`,
+ };
+}
+
+export const feedbackReceipt = (row: FeedbackRow): FeedbackReceipt => {
+ const status = row.deliveryId && row.status === "pending" ? "accepted" : row.status;
+ return {
+ id: row.id,
+ deliveryId: row.deliveryId,
+ status,
+ message: feedbackStatusMessage(status, row.lastErrorCode),
+ };
+};
+
+export async function findCanvasFeedback(id: string) {
+ return (
+ (await db.select().from(canvasFeedback).where(eq(canvasFeedback.id, id)).limit(1))[0] || null
+ );
+}
+
+export async function saveCanvasFeedback(input: {
+ id: string;
+ userId: string;
+ description: string;
+ snapshot: FeedbackSnapshot;
+ appUrl: string;
+}) {
+ const createdAt = new Date();
+ await db
+ .insert(canvasFeedback)
+ .values({
+ id: input.id,
+ userId: input.userId,
+ projectId: input.snapshot.project.id,
+ description: input.description,
+ snapshot: input.snapshot,
+ notification: buildFeedbackNotification({ ...input, createdAt: createdAt.toISOString() }),
+ createdAt,
+ })
+ .onConflictDoNothing({ target: canvasFeedback.id });
+ const row = await findCanvasFeedback(input.id);
+ if (!row || row.userId !== input.userId || row.projectId !== input.snapshot.project.id)
+ throw new CanvasFeedbackError("反馈编号不可用", 409);
+ // The persisted notification is immutable so a lost response can be retried safely.
+ return row;
+}
+
+export async function deliverCanvasFeedback(id: string) {
+ const [claimed] = await db
+ .update(canvasFeedback)
+ .set({
+ attempts: sql`${canvasFeedback.attempts} + 1`,
+ nextAttemptAt: new Date(Date.now() + 60_000),
+ })
+ .where(
+ and(
+ eq(canvasFeedback.id, id),
+ eq(canvasFeedback.status, "pending"),
+ isNull(canvasFeedback.deliveryId),
+ lte(canvasFeedback.nextAttemptAt, new Date()),
+ lt(canvasFeedback.attempts, 5),
+ ),
+ )
+ .returning();
+ if (!claimed) return;
+ try {
+ const delivery = await notificationCenterRequest(
+ "POST",
+ "/v1/notifications",
+ claimed.notification,
+ );
+ await db
+ .update(canvasFeedback)
+ .set({
+ deliveryId: delivery.id,
+ status: delivery.status,
+ lastErrorCode: delivery.lastErrorCode || null,
+ })
+ .where(eq(canvasFeedback.id, id));
+ } catch (error) {
+ const failure =
+ error instanceof NotificationCenterError
+ ? error
+ : new NotificationCenterError("NOTIFICATION_CONNECTION_FAILED", true);
+ await db
+ .update(canvasFeedback)
+ .set({
+ status: failure.retryable && claimed.attempts < 5 ? "pending" : "failed",
+ lastErrorCode: failure.code,
+ nextAttemptAt: new Date(Date.now() + backoffMs[Math.min(claimed.attempts - 1, 4)]),
+ })
+ .where(and(eq(canvasFeedback.id, id), isNull(canvasFeedback.deliveryId)));
+ }
+}
+
+export async function refreshCanvasFeedback(row: FeedbackRow) {
+ if (!row.deliveryId) {
+ await deliverCanvasFeedback(row.id);
+ } else if (!["read", "failed"].includes(row.status)) {
+ try {
+ const delivery = await notificationCenterRequest(
+ "GET",
+ `/v1/notifications/${encodeURIComponent(row.deliveryId)}`,
+ );
+ await db
+ .update(canvasFeedback)
+ .set({ status: delivery.status, lastErrorCode: delivery.lastErrorCode || null })
+ .where(eq(canvasFeedback.id, row.id));
+ } catch {
+ /* A status lookup failure does not invalidate the accepted notification. */
+ }
+ }
+ return (await findCanvasFeedback(row.id))!;
+}
+
+export async function runCanvasFeedbackDelivery() {
+ if (!notificationCenterConfigured()) return;
+ const rows = await db
+ .select({ id: canvasFeedback.id })
+ .from(canvasFeedback)
+ .where(
+ and(
+ eq(canvasFeedback.status, "pending"),
+ isNull(canvasFeedback.deliveryId),
+ lte(canvasFeedback.nextAttemptAt, new Date()),
+ lt(canvasFeedback.attempts, 5),
+ ),
+ )
+ .orderBy(asc(canvasFeedback.createdAt))
+ .limit(10);
+ for (const row of rows) await deliverCanvasFeedback(row.id);
+}
diff --git a/lib/db/migrations/0105_add_canvas_feedback.sql b/lib/db/migrations/0105_add_canvas_feedback.sql
new file mode 100644
index 000000000..d7c847270
--- /dev/null
+++ b/lib/db/migrations/0105_add_canvas_feedback.sql
@@ -0,0 +1,15 @@
+CREATE TABLE IF NOT EXISTS "CanvasFeedback" (
+ "id" uuid PRIMARY KEY NOT NULL,
+ "userId" uuid NOT NULL REFERENCES "User"("id") ON DELETE CASCADE,
+ "projectId" uuid NOT NULL,
+ "description" text NOT NULL,
+ "snapshot" jsonb NOT NULL,
+ "notification" jsonb NOT NULL,
+ "deliveryId" varchar(128),
+ "status" varchar(24) NOT NULL DEFAULT 'pending',
+ "attempts" integer NOT NULL DEFAULT 0,
+ "nextAttemptAt" timestamp NOT NULL DEFAULT now(),
+ "lastErrorCode" varchar(128),
+ "createdAt" timestamp NOT NULL DEFAULT now()
+);
+CREATE INDEX IF NOT EXISTS "CanvasFeedback_due_idx" ON "CanvasFeedback" ("status", "nextAttemptAt");
diff --git a/lib/db/migrations/meta/_journal.json b/lib/db/migrations/meta/_journal.json
index 1fe42adcd..9ea13e496 100644
--- a/lib/db/migrations/meta/_journal.json
+++ b/lib/db/migrations/meta/_journal.json
@@ -638,6 +638,13 @@
"when": 1792454400000,
"tag": "0104_add_canvas_agent_runs",
"breakpoints": true
+ },
+ {
+ "idx": 89,
+ "version": "7",
+ "when": 1794960000000,
+ "tag": "0105_add_canvas_feedback",
+ "breakpoints": true
}
]
}
diff --git a/lib/db/schema.ts b/lib/db/schema.ts
index 77bcdadad..fc22af642 100644
--- a/lib/db/schema.ts
+++ b/lib/db/schema.ts
@@ -704,6 +704,21 @@ export type ClientPerformanceEvent = InferSelectModel<
typeof clientPerformanceEvent
>;
+export const canvasFeedback = pgTable("CanvasFeedback", {
+ id: uuid("id").primaryKey().notNull(),
+ userId: uuid("userId").notNull().references(() => user.id, { onDelete: "cascade" }),
+ projectId: uuid("projectId").notNull(),
+ description: text("description").notNull(),
+ snapshot: jsonb("snapshot").$type().notNull(),
+ notification: jsonb("notification").$type().notNull(),
+ deliveryId: varchar("deliveryId", { length: 128 }),
+ status: varchar("status", { length: 24 }).notNull().default("pending"),
+ attempts: integer("attempts").notNull().default(0),
+ nextAttemptAt: timestamp("nextAttemptAt").notNull().defaultNow(),
+ lastErrorCode: varchar("lastErrorCode", { length: 128 }),
+ createdAt: timestamp("createdAt").notNull().defaultNow(),
+}, (table) => ({ dueIndex: index("CanvasFeedback_due_idx").on(table.status, table.nextAttemptAt) }));
+
export const accessIpEvent = pgTable("AccessIpEvent", {
id: uuid("id").primaryKey().notNull().defaultRandom(),
eventType: varchar("eventType", { length: 32 }).notNull().default("request"),
diff --git a/lib/notifications/notification-center.ts b/lib/notifications/notification-center.ts
new file mode 100644
index 000000000..0e9707940
--- /dev/null
+++ b/lib/notifications/notification-center.ts
@@ -0,0 +1,83 @@
+import "server-only";
+import { createHash, createHmac, randomBytes } from "node:crypto";
+
+export type NotificationPayload = {
+ idempotencyKey: string;
+ recipientAlias: string;
+ title: string;
+ content: string;
+ actionTitle: string;
+ actionUrl: string;
+};
+export type NotificationDelivery = { id: string; status: string; lastErrorCode?: string | null };
+export class NotificationCenterError extends Error {
+ code: string;
+ retryable: boolean;
+ constructor(code: string, retryable: boolean) {
+ super(code);
+ this.code = code;
+ this.retryable = retryable;
+ }
+}
+
+export function notificationCenterConfigured() {
+ return Boolean(
+ process.env.YYD_NOTIFICATION_CENTER_URL &&
+ process.env.YYD_NOTIFICATION_CENTER_PROJECT_CODE &&
+ process.env.YYD_NOTIFICATION_CENTER_PROJECT_SECRET,
+ );
+}
+
+export async function notificationCenterRequest(
+ method: "GET" | "POST",
+ path: string,
+ payload?: NotificationPayload,
+): Promise {
+ if (!notificationCenterConfigured())
+ throw new NotificationCenterError("NOTIFICATION_CONFIG_MISSING", true);
+ const body = payload ? JSON.stringify(payload) : "";
+ const timestamp = String(Math.floor(Date.now() / 1000));
+ const nonce = randomBytes(18).toString("base64url");
+ const canonical = [
+ timestamp,
+ nonce,
+ method,
+ path,
+ createHash("sha256").update(body).digest("hex"),
+ ].join("\n");
+ let response: Response;
+ try {
+ response = await fetch(
+ `${process.env.YYD_NOTIFICATION_CENTER_URL!.replace(/\/$/, "")}${path}`,
+ {
+ method,
+ headers: {
+ "Content-Type": "application/json",
+ "x-yyd-project-code": process.env.YYD_NOTIFICATION_CENTER_PROJECT_CODE!,
+ "x-yyd-timestamp": timestamp,
+ "x-yyd-nonce": nonce,
+ "x-yyd-signature": createHmac(
+ "sha256",
+ process.env.YYD_NOTIFICATION_CENTER_PROJECT_SECRET!,
+ )
+ .update(canonical)
+ .digest("hex"),
+ },
+ ...(body ? { body } : {}),
+ cache: "no-store",
+ signal: AbortSignal.timeout(8000),
+ },
+ );
+ } catch {
+ throw new NotificationCenterError("NOTIFICATION_CONNECTION_FAILED", true);
+ }
+ const data = await response.json().catch(() => null);
+ if (!response.ok)
+ throw new NotificationCenterError(
+ typeof data?.error === "string" ? data.error : "NOTIFICATION_RESPONSE_FAILED",
+ response.status >= 500 || response.status === 429,
+ );
+ if (!data || typeof data.id !== "string" || typeof data.status !== "string")
+ throw new NotificationCenterError("NOTIFICATION_RESPONSE_INVALID", true);
+ return data;
+}
diff --git a/playwright.helpers.config.ts b/playwright.helpers.config.ts
index 549ba6103..f5b10d008 100644
--- a/playwright.helpers.config.ts
+++ b/playwright.helpers.config.ts
@@ -3,6 +3,7 @@ import { defineConfig } from "@playwright/test";
export default defineConfig({
testDir: "./tests",
testMatch: [
+ /routes\/canvas-feedback\.test\.ts/,
/routes\/aos-image-transfer\.test\.ts/,
/routes\/rmbg-delivery\.test\.ts/,
/routes\/legacy-oss-recovery\.test\.ts/,
diff --git a/tests/e2e/canvas-issue-feedback.test.ts b/tests/e2e/canvas-issue-feedback.test.ts
new file mode 100644
index 000000000..e9379c069
--- /dev/null
+++ b/tests/e2e/canvas-issue-feedback.test.ts
@@ -0,0 +1,225 @@
+import { expect, test, type Page } from "@playwright/test";
+
+const projectId = "24cce650-7cfb-48bb-aa65-b04f490ac978";
+const userMessageId = "998c3990-3e3b-49a0-91d9-4e29488231c0";
+const prompt = "把背景换成游乐场,保持杯子外观不变";
+const requestId = "source-request-for-feedback";
+test.setTimeout(60000);
+
+async function setup(page: Page, loseFirstResponse = false) {
+ const submissions: any[] = [];
+ const contexts: any[] = [];
+ const businessRequests: string[] = [];
+ const errors: string[] = [];
+ let saved: any = null;
+ let polls = 0;
+ page.on("pageerror", (error) => errors.push(error.message));
+ await page.context().addInitScript(() => localStorage.setItem("theme", "light"));
+ await page.context().route("**/api/**", async (route) => {
+ const request = route.request();
+ const path = new URL(request.url()).pathname;
+ const method = request.method();
+ let data: any = {};
+ if (path.endsWith("/feedback")) {
+ if (method === "GET") {
+ data = {
+ feedback: {
+ id: saved.id,
+ deliveryId: "test-delivery",
+ status: ++polls > 1 ? "sent" : "accepted",
+ message:
+ polls > 1 ? "反馈已投递给魔礼红。" : "反馈已保存,通知中心已受理,等待投递给魔礼红。",
+ },
+ };
+ } else {
+ const input = request.postDataJSON();
+ if (input.action === "context") {
+ contexts.push(input);
+ data = {
+ context: {
+ reporter: {
+ id: "feedback-user",
+ name: "反馈验收用户",
+ email: "test@example.com",
+ department: "设计",
+ },
+ project: { id: projectId, title: "问题反馈验收" },
+ requests: [
+ {
+ key: `message:${userMessageId}`,
+ kind: "message",
+ id: userMessageId,
+ requestId,
+ createdAt: "2026-11-18T08:00:00Z",
+ prompt,
+ status: "failed",
+ model: "Qwen Image 3.0",
+ error: "参考图片无法读取,请重新上传原图。",
+ evidence: "server",
+ },
+ ],
+ },
+ };
+ } else {
+ submissions.push(input);
+ saved = input;
+ if (loseFirstResponse && submissions.length === 1) {
+ await route.abort("connectionreset");
+ return;
+ }
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ data = {
+ feedback: {
+ id: input.id,
+ status: "pending",
+ deliveryId: null,
+ message: "反馈已保存,正在提交通知;短暂故障会自动重试,无需再次反馈。",
+ },
+ };
+ }
+ }
+ } else if (path.includes("validate-session")) data = { valid: true, success: true };
+ else if (path === "/api/auth/session")
+ data = {
+ user: { id: "feedback-user", name: "反馈验收用户", type: "admin" },
+ expires: "2099-01-01",
+ };
+ else if (path === "/api/site-settings")
+ data = { canvasEnabled: true, agentEnabled: true, membershipEnabled: false };
+ else if (path === "/api/vote") data = [];
+ else if (path === "/api/models")
+ data = {
+ models: [
+ {
+ id: "image-test",
+ modelId: "gpt-image-2",
+ name: "GPT Image",
+ type: "image",
+ providerType: "openai",
+ enabled: true,
+ supportsImageGen: true,
+ },
+ ],
+ };
+ else if (path === `/api/canvas/${projectId}` && method === "GET")
+ data = {
+ success: true,
+ data: {
+ id: projectId,
+ title: "问题反馈验收",
+ workspaceType: "canvas",
+ canvasData: { nodes: [], edges: [], viewport: { x: 0, y: 0, zoom: 1 } },
+ },
+ };
+ else if (path.includes("messages"))
+ data = {
+ messages: [
+ {
+ id: userMessageId,
+ role: "user",
+ createdAt: "2026-11-18T08:00:00Z",
+ parts: [{ type: "text", text: prompt }],
+ },
+ {
+ id: "bd7ca4ea-8f4d-4437-8e9d-23897e27b144",
+ role: "assistant",
+ createdAt: "2026-11-18T08:00:30Z",
+ parts: [
+ { type: "text", text: "参考图片无法读取,请重新上传原图。" },
+ {
+ type: "data-imageGenerationStatus",
+ data: {
+ phase: "failed",
+ userMessageId,
+ requestId,
+ failure: { message: "参考图片无法读取。", recommendation: "请重新上传原图。" },
+ },
+ },
+ ],
+ },
+ ],
+ };
+ else if (path.includes("sessions")) data = { sessions: [] };
+ else if (path.startsWith("/api/canvas/")) data = { success: true, runs: [] };
+ if (method === "POST" && /\/(?:agent-chat|generate|capabilities|chat)(?:\/|$)/.test(path))
+ businessRequests.push(path);
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify(data),
+ });
+ });
+ await page.goto(`/canvas/${projectId}`, { waitUntil: "domcontentloaded" });
+ await expect(page.getByRole("button", { name: "问题反馈", exact: true })).toBeVisible();
+ await expect(
+ page.getByTestId("canvas-chat-messages").getByText(prompt, { exact: true }),
+ ).toBeVisible();
+ return { submissions, contexts, businessRequests, errors };
+}
+
+test("collect current conversation, send once and distinguish queued from delivered", async ({
+ page,
+}) => {
+ const state = await setup(page);
+ await page.getByRole("button", { name: "问题反馈", exact: true }).click();
+ const dialog = page.getByRole("dialog");
+ await expect(dialog.getByText(requestId, { exact: true })).toBeVisible();
+ await dialog
+ .getByLabel("补充说明", { exact: false })
+ .fill("点击预览等待约 30 秒,仍无法查看图片。");
+ expect(
+ state.contexts[0].client.messages.some(
+ (item: any) => item.id === userMessageId && item.text === prompt,
+ ),
+ ).toBe(true);
+ expect(state.contexts[0].client.chatId).toBe(projectId);
+ await page.screenshot({ path: "test-results/canvas-feedback-desktop.png", animations: "disabled" });
+ await page
+ .getByRole("button", { name: "发送给魔礼红", exact: true })
+ .evaluate((button: HTMLButtonElement) => {
+ button.click();
+ button.click();
+ });
+ await expect(dialog.getByText(/反馈已保存,正在提交通知/)).toBeVisible();
+ expect(state.submissions).toHaveLength(1);
+ expect(state.submissions[0]).toMatchObject({
+ selection: `message:${userMessageId}`,
+ description: "点击预览等待约 30 秒,仍无法查看图片。",
+ });
+ await expect(dialog.getByText("反馈已投递给魔礼红。", { exact: true })).toBeVisible({
+ timeout: 12000,
+ });
+ expect(state.businessRequests).toEqual([]);
+ expect(state.errors).toEqual([]);
+});
+
+test("lost response and refresh recover original report without creating another notification", async ({
+ page,
+}) => {
+ const state = await setup(page, true);
+ await page.getByRole("button", { name: "问题反馈", exact: true }).click();
+ await expect(page.getByRole("dialog").getByText(requestId, { exact: true })).toBeVisible();
+ await page.getByRole("button", { name: "发送给魔礼红", exact: true }).click();
+ await expect(page.getByRole("alert")).toBeVisible();
+ const originalId = state.submissions[0].id;
+ await page.reload({ waitUntil: "domcontentloaded" });
+ await page.getByRole("button", { name: "问题反馈", exact: true }).click();
+ await expect(
+ page.getByRole("dialog").getByText(`反馈编号:${originalId}`, { exact: true }),
+ ).toBeVisible();
+ expect(state.submissions).toHaveLength(1);
+ expect(state.businessRequests).toEqual([]);
+ expect(state.errors).toEqual([]);
+});
+
+test("narrow screen retains a usable feedback entry and complete form", async ({ page }) => {
+ await page.setViewportSize({ width: 390, height: 844 });
+ await setup(page);
+ await page.getByRole("button", { name: "问题反馈", exact: true }).click();
+ await expect(page.getByRole("dialog").getByText(requestId, { exact: true })).toBeVisible();
+ await expect(page.getByRole("button", { name: "发送给魔礼红", exact: true })).toBeVisible();
+ await page.screenshot({ path: "test-results/canvas-feedback-mobile.png", animations: "disabled" });
+ const box = await page.getByRole("dialog").boundingBox();
+ expect(box!.x).toBeGreaterThanOrEqual(0);
+ expect(box!.x + box!.width).toBeLessThanOrEqual(391);
+});
diff --git a/tests/routes/canvas-feedback.test.ts b/tests/routes/canvas-feedback.test.ts
new file mode 100644
index 000000000..616e5f12b
--- /dev/null
+++ b/tests/routes/canvas-feedback.test.ts
@@ -0,0 +1,194 @@
+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;
+ expect(headers["x-yyd-nonce"]).not.toBe(
+ (calls[1].headers as Record)["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([]);
+});