Merge pull request '画布问题反馈接入统一钉钉通知中心' (#106) from codex/canvas-issue-feedback-20261118 into main

This commit is contained in:
WuYongJie 2026-11-18 17:29:23 +08:00
commit ee1c5bf971
20 changed files with 1837 additions and 0 deletions

View File

@ -40,6 +40,11 @@ EMAIL_VERIFICATION_SECRET=
# Optional scheduled job protection. # Optional scheduled job protection.
CRON_SECRET= 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 # Database
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------

View File

@ -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);
}
}

View File

@ -11406,6 +11406,7 @@ export default function CanvasEditorLegacyPage({
setPanelMode("fileList"); setPanelMode("fileList");
}} }}
projectTitle={projectTitle} projectTitle={projectTitle}
projectId={id}
rightInset={panelOcclusionRight} rightInset={panelOcclusionRight}
/> />
)} )}

107
app/feedback/[id]/page.tsx Normal file
View File

@ -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 (
<main className="mx-auto max-w-3xl space-y-6 px-6 py-8 text-foreground">
<h1 className="text-2xl font-semibold">画布问题反馈</h1>
<p className="text-sm text-muted-foreground">{feedbackReceipt(feedback).message}</p>
<dl className="space-y-3">
{fields.map(([label, value]) => (
<div key={label} className="grid gap-1 text-sm sm:grid-cols-[8rem_1fr]">
<dt className="text-muted-foreground">{label}</dt>
<dd className="whitespace-pre-wrap break-words">{value}</dd>
</div>
))}
</dl>
{[
["用户说明", feedback.description || "未补充说明"],
["请求内容", request?.prompt || "未关联具体请求"],
["错误信息", request?.error || client.errors.join("\n") || "未记录明确错误"],
].map(([label, value]) => (
<section key={label} className="space-y-2">
<h2 className="text-base font-medium">{label}</h2>
<p className="whitespace-pre-wrap break-words rounded-lg bg-muted p-4 text-sm">{value}</p>
</section>
))}
{request?.parameters && Object.keys(request.parameters).length > 0 && (
<section className="space-y-2">
<h2 className="text-base font-medium">请求参数</h2>
<pre className="overflow-auto whitespace-pre-wrap break-all rounded-lg bg-muted p-4 text-sm">
{JSON.stringify(request.parameters, null, 2)}
</pre>
</section>
)}
{client.nodes.length > 0 && (
<details className="text-sm">
<summary className="cursor-pointer">相关画布节点</summary>
<pre className="mt-3 overflow-auto whitespace-pre-wrap break-all">
{JSON.stringify(client.nodes, null, 2)}
</pre>
</details>
)}
<details className="text-sm">
<summary className="cursor-pointer">当前对话上下文</summary>
<div className="mt-4 space-y-4">
{client.messages.map((item) => (
<div key={item.id} className="space-y-1">
<p className="text-muted-foreground">
{item.role === "user" ? "用户" : "助手"} · {item.id}
</p>
<p className="whitespace-pre-wrap break-words">{item.text}</p>
</div>
))}
</div>
</details>
<a
className="inline-block text-sm underline underline-offset-4"
href={`/canvas/${project.id}`}
>
打开相关画布
</a>
</main>
);
}

View File

@ -1,4 +1,6 @@
"use client"; "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 { advancePastAtomicRanges, scanMarkdownImageStreaming } from "@/lib/canvas/markdown-image-streaming";
import { useChat } from "@ai-sdk/react"; import { useChat } from "@ai-sdk/react";
@ -4429,6 +4431,15 @@ export function CanvasChatPanel({
// 获取纯 UUID(去掉 canvas- 前缀)用于 API 调用 // 获取纯 UUID(去掉 canvas- 前缀)用于 API 调用
const rawChatId = toRawCanvasChatId(activeChatId); 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( const buildHistoryMessagesUrl = useCallback(
(targetRawChatId: string, options?: { cacheBust?: boolean }) => { (targetRawChatId: string, options?: { cacheBust?: boolean }) => {
const params = new URLSearchParams({ const params = new URLSearchParams({
@ -15887,6 +15898,9 @@ export function CanvasChatPanel({
</div> </div>
<div className="flex shrink-0 items-center"> <div className="flex shrink-0 items-center">
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
<div className={isVideoWorkspace ? "" : "sm:hidden"}>
<CanvasFeedbackDialog projectId={canvasId} />
</div>
<Button <Button
variant="ghost" variant="ghost"
size="icon" size="icon"

View File

@ -0,0 +1,363 @@
"use client";
import { Bug } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { captureFeedbackChat } from "@/lib/canvas/feedback-client";
import { useCanvasStore } from "@/store/canvas";
import {
feedbackCommandSchema,
formatFeedbackTime,
type FeedbackClient,
type FeedbackContext,
type FeedbackReceipt,
} from "@/lib/canvas/feedback-contract";
type Submission = Extract<ReturnType<typeof feedbackCommandSchema.parse>, { action: "submit" }>;
const terminal = (value: string) => ["sent", "unread", "read", "failed"].includes(value);
const fieldClass =
"w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring";
export function CanvasFeedbackDialog({ projectId }: { projectId: string }) {
const [open, setOpen] = useState(false);
const [context, setContext] = useState<FeedbackContext | null>(null);
const [selection, setSelection] = useState<string | null>(null);
const [description, setDescription] = useState("");
const [loading, setLoading] = useState(false);
const [sending, setSending] = useState(false);
const [sealed, setSealed] = useState(false);
const [error, setError] = useState("");
const [receipt, setReceipt] = useState<FeedbackReceipt | null>(null);
const captured = useRef<FeedbackClient | null>(null);
const submission = useRef<Submission | null>(null);
const errors = useRef<string[]>([]);
const submitLock = useRef(false);
const endpoint = `/api/canvas/${projectId}/feedback`;
const storageKey = `canvas-feedback:${projectId}`;
useEffect(() => {
const rememberError = (event: ErrorEvent) => {
errors.current = [
...errors.current,
String(event.message || "页面脚本错误").slice(0, 2000),
].slice(-5);
};
window.addEventListener("error", rememberError);
return () => window.removeEventListener("error", rememberError);
}, []);
useEffect(() => {
if (!open || receipt) return;
const controller = new AbortController();
try {
const raw = sessionStorage.getItem(storageKey);
if (raw && !submission.current) {
const command = feedbackCommandSchema.parse(JSON.parse(raw));
if (command.action === "submit") {
submission.current = command;
captured.current = command.client;
setSealed(true);
setDescription(command.description);
setSelection(command.selection);
}
}
} catch {
/* An unavailable local draft does not prevent a new feedback report. */
}
if (submission.current) {
void fetch(`${endpoint}?feedbackId=${submission.current.id}`, {
cache: "no-store",
signal: controller.signal,
})
.then(async (response) => {
const data = await response.json();
if (response.ok) setReceipt(data.feedback);
else if (response.status !== 404)
setError(data.error || "暂时无法确认反馈状态,请重试提交同一条反馈。");
})
.catch(() => {
if (!controller.signal.aborted) setError("暂时无法确认反馈状态,可重试提交同一条反馈。");
});
return () => controller.abort();
}
const canvas = useCanvasStore.getState();
const selectedIds = new Set(canvas.selectedNodeIds);
const nodes = [...canvas.nodes]
.sort((a, b) => Number(selectedIds.has(b.id)) - Number(selectedIds.has(a.id)))
.slice(0, 20);
const client: FeedbackClient = {
...captureFeedbackChat(projectId),
capturedAt: new Date().toISOString(),
pageVersion: process.env.NEXT_PUBLIC_APP_RELEASE || "development",
viewport: { width: window.innerWidth, height: window.innerHeight },
online: navigator.onLine,
errors: [...errors.current],
nodes: nodes.map((node) => {
const data = node.data as unknown as Record<string, unknown>;
const metadata = data.metadata as Record<string, unknown> | undefined;
return {
id: node.id.slice(0, 180),
type: node.type.slice(0, 64),
title: String(data.title || "").slice(0, 256),
status: String(data.status || "").slice(0, 64),
taskId: String(metadata?.taskId || "").slice(0, 180),
width: node.size?.width,
height: node.size?.height,
};
}),
};
captured.current = client;
setLoading(true);
setError("");
void fetch(endpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action: "context", client }),
signal: controller.signal,
})
.then(async (response) => {
const data = await response.json();
if (!response.ok) throw new Error(data.error || "排查资料暂时加载失败,请重新打开反馈。");
setContext(data.context);
setSelection(data.context.requests[0]?.key || null);
})
.catch((failure) => {
if (!controller.signal.aborted)
setError(failure.message || "排查资料暂时加载失败,请重新打开反馈。");
})
.finally(() => {
if (!controller.signal.aborted) setLoading(false);
});
return () => controller.abort();
}, [open, endpoint, projectId, receipt, storageKey]);
useEffect(() => {
if (!open || !receipt || terminal(receipt.status)) return;
const controller = new AbortController();
let timer: ReturnType<typeof setTimeout>;
const poll = async () => {
try {
const response = await fetch(`${endpoint}?feedbackId=${receipt.id}`, {
cache: "no-store",
signal: controller.signal,
});
const data = await response.json();
if (response.ok && !controller.signal.aborted) {
setReceipt(data.feedback);
setError("");
} else if (!controller.signal.aborted)
setError(data.error || "暂时无法刷新通知状态,已保存的反馈会继续处理。");
} catch {
if (!controller.signal.aborted)
setError("网络暂时不可用,已保存的反馈会继续处理,请勿重复提交。");
}
if (!controller.signal.aborted) timer = setTimeout(poll, 4000);
};
timer = setTimeout(poll, 1500);
return () => {
controller.abort();
clearTimeout(timer);
};
}, [open, receipt?.id, receipt?.status, endpoint]);
const send = async () => {
if (submitLock.current || receipt) return;
if (!submission.current) {
if (!captured.current || !context) return;
submission.current = {
action: "submit",
id: crypto.randomUUID(),
description,
selection,
client: captured.current,
};
try {
sessionStorage.setItem(storageKey, JSON.stringify(submission.current));
} catch {
/* In-memory retries still retain this report's id. */
}
}
submitLock.current = true;
setSending(true);
setSealed(true);
setError("");
try {
const response = await fetch(endpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(submission.current),
signal: AbortSignal.timeout(20000),
});
const data = await response.json();
if (!response.ok) {
if (response.status === 400 || response.status === 409 || response.status === 413) {
submission.current = null;
sessionStorage.removeItem(storageKey);
setSealed(false);
}
throw new Error(data.error || "暂时无法确认反馈是否保存,请重试提交同一条反馈。");
}
setReceipt(data.feedback);
} catch (failure) {
setError(
failure instanceof Error && failure.name !== "TimeoutError"
? failure.message
: "提交连接超时。请重试提交同一条反馈,系统会核对原编号,避免重复通知。",
);
} finally {
submitLock.current = false;
setSending(false);
}
};
const startAnother = () => {
submission.current = null;
captured.current = null;
sessionStorage.removeItem(storageKey);
setContext(null);
setDescription("");
setSelection(null);
setError("");
setSealed(false);
setReceipt(null);
};
const selected = context?.requests.find((item) => item.key === selection);
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<button
type="button"
className="ml-2 inline-flex shrink-0 items-center gap-2 rounded-lg px-3 py-2 text-sm text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
aria-label="问题反馈"
>
<Bug className="size-4" aria-hidden="true" />
<span className="hidden sm:inline">问题反馈</span>
</button>
</DialogTrigger>
<DialogContent
className="max-h-[85dvh] overflow-y-auto sm:max-w-xl"
aria-busy={loading || sending}
>
<DialogHeader>
<DialogTitle>问题反馈</DialogTitle>
<DialogDescription className="text-pretty">
自动附上当前画布、用户和相关请求资料。你可以补充问题现象,发送给魔礼红。
</DialogDescription>
</DialogHeader>
{receipt ? (
<div className="space-y-3 py-2" role="status" aria-live="polite">
<p className="text-sm">{receipt.message}</p>
<p className="break-all text-sm text-muted-foreground">反馈编号:{receipt.id}</p>
<a
href={`/feedback/${receipt.id}`}
target="_blank"
rel="noreferrer"
className="inline-block text-sm underline underline-offset-4"
>
查看已保存的完整反馈
</a>
</div>
) : (
<div className="space-y-4">
{loading ? (
<p role="status" className="py-4 text-sm text-muted-foreground">
正在整理排查资料…
</p>
) : context ? (
<p className="text-sm text-muted-foreground">
{context.reporter.name} · {context.project.title}
</p>
) : null}
<div className="space-y-2">
<label htmlFor="canvas-feedback-request" className="text-sm font-medium">
关联请求
</label>
<select
id="canvas-feedback-request"
className={fieldClass}
value={selection || ""}
disabled={sealed || loading}
onChange={(event) => setSelection(event.target.value || null)}
>
<option value="">页面或画布问题,不关联具体请求</option>
{context?.requests.map((item) => (
<option key={item.key} value={item.key}>
{item.createdAt ? formatFeedbackTime(item.createdAt) : "时间未记录"} ·{" "}
{item.prompt.slice(0, 45)}
</option>
))}
</select>
{selected && (
<div className="space-y-2 rounded-lg bg-muted p-3 text-sm">
<p>
请求号:
<span className="break-all">
{selected.requestId || "尚未获取,将附上消息编号"}
</span>
</p>
<p className="max-h-28 overflow-y-auto whitespace-pre-wrap break-words text-muted-foreground">
{selected.prompt}
</p>
{selected.error && (
<p className="whitespace-pre-wrap break-words">{selected.error}</p>
)}
</div>
)}
</div>
<div className="space-y-2">
<label htmlFor="canvas-feedback-description" className="text-sm font-medium">
补充说明 <span className="font-normal text-muted-foreground">(选填)</span>
</label>
<textarea
id="canvas-feedback-description"
rows={4}
maxLength={2000}
className={`${fieldClass} resize-y`}
value={description}
disabled={sealed}
onChange={(event) => setDescription(event.target.value)}
placeholder="例如:点击预览后一直加载,等待约 30 秒仍无法查看。"
/>
</div>
<p className="text-xs text-muted-foreground">
将附上相关请求内容、任务状态、页面版本及已记录的错误;本次反馈不会重新执行任务。
</p>
</div>
)}
{error && (
<p role="alert" className="whitespace-pre-wrap text-sm text-destructive">
{error}
</p>
)}
<DialogFooter className="gap-2 sm:space-x-0">
<Button type="button" variant="outline" onClick={() => setOpen(false)}>
{receipt ? "返回画布" : "取消"}
</Button>
{receipt ? (
<Button type="button" variant="outline" onClick={startAnother}>
反馈另一个问题
</Button>
) : (
<Button
type="button"
onClick={() => void send()}
disabled={sending || loading || (!context && !submission.current)}
>
{sending ? "正在发送…" : sealed ? "重试提交同一反馈" : "发送给魔礼红"}
</Button>
)}
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@ -1,12 +1,14 @@
"use client"; "use client";
import { ReferenceIcon } from "@/components/lovart/reference-icon"; import { ReferenceIcon } from "@/components/lovart/reference-icon";
import { CanvasFeedbackDialog } from "./CanvasFeedbackDialog";
type CanvasSurfaceHeaderProps = { type CanvasSurfaceHeaderProps = {
onAddImage: () => void; onAddImage: () => void;
onHome: () => void; onHome: () => void;
onOpenFiles: () => void; onOpenFiles: () => void;
projectTitle: string; projectTitle: string;
projectId: string;
rightInset: number; rightInset: number;
}; };
@ -18,6 +20,7 @@ export function CanvasSurfaceHeader({
onHome, onHome,
onOpenFiles, onOpenFiles,
projectTitle, projectTitle,
projectId,
rightInset, rightInset,
}: CanvasSurfaceHeaderProps) { }: CanvasSurfaceHeaderProps) {
return ( return (
@ -71,6 +74,7 @@ export function CanvasSurfaceHeader({
<ReferenceIcon name="plus" size={16} /> <ReferenceIcon name="plus" size={16} />
</button> </button>
</div> </div>
<CanvasFeedbackDialog projectId={projectId} />
</div> </div>
); );
} }

38
docs/canvas-feedback.md Normal file
View File

@ -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 不变;查询通知中心最终状态,并核对完整反馈页面权限。

View File

@ -12,6 +12,11 @@ export function register() {
void import("@/lib/canvas/image-task-queue") void import("@/lib/canvas/image-task-queue")
.then(({ resumeDetailReplacementBatchTasks }) => resumeDetailReplacementBatchTasks()) .then(({ resumeDetailReplacementBatchTasks }) => resumeDetailReplacementBatchTasks())
.catch((error) => console.error("[Detail Replacement Batch] Recovery failed", error)); .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?.(); setTimeout(recover, 5000).unref?.();
setInterval(recover, 60_000).unref?.(); setInterval(recover, 60_000).unref?.();

View File

@ -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();
}

View File

@ -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<Record<string, unknown>>`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<string, any>) {
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<string>,
) {
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<FeedbackContext> {
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<string>`${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<string, any>;
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<string, any>;
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 };
}

View File

@ -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<typeof feedbackClientSchema>;
export type FeedbackMessage = z.infer<typeof feedbackMessageSchema>;
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<string, unknown>;
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<FeedbackContext, "requests"> & {
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));
}

View File

@ -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);
}

View File

@ -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");

View File

@ -638,6 +638,13 @@
"when": 1792454400000, "when": 1792454400000,
"tag": "0104_add_canvas_agent_runs", "tag": "0104_add_canvas_agent_runs",
"breakpoints": true "breakpoints": true
},
{
"idx": 89,
"version": "7",
"when": 1794960000000,
"tag": "0105_add_canvas_feedback",
"breakpoints": true
} }
] ]
} }

View File

@ -704,6 +704,21 @@ export type ClientPerformanceEvent = InferSelectModel<
typeof clientPerformanceEvent 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<import("@/lib/canvas/feedback-contract").FeedbackSnapshot>().notNull(),
notification: jsonb("notification").$type<import("@/lib/notifications/notification-center").NotificationPayload>().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", { export const accessIpEvent = pgTable("AccessIpEvent", {
id: uuid("id").primaryKey().notNull().defaultRandom(), id: uuid("id").primaryKey().notNull().defaultRandom(),
eventType: varchar("eventType", { length: 32 }).notNull().default("request"), eventType: varchar("eventType", { length: 32 }).notNull().default("request"),

View File

@ -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<NotificationDelivery> {
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;
}

View File

@ -3,6 +3,7 @@ import { defineConfig } from "@playwright/test";
export default defineConfig({ export default defineConfig({
testDir: "./tests", testDir: "./tests",
testMatch: [ testMatch: [
/routes\/canvas-feedback\.test\.ts/,
/routes\/aos-image-transfer\.test\.ts/, /routes\/aos-image-transfer\.test\.ts/,
/routes\/rmbg-delivery\.test\.ts/, /routes\/rmbg-delivery\.test\.ts/,
/routes\/legacy-oss-recovery\.test\.ts/, /routes\/legacy-oss-recovery\.test\.ts/,

View File

@ -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);
});

View File

@ -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<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([]);
});