import { NextResponse } from "next/server"; import { z } from "zod"; import { auth } from "@/app/(auth)/auth"; import { getChatById, getMessagesByChatId } from "@/lib/db/queries"; import { readOwnedVideoCanvas, saveVideoAgentCanvas, } from "@/lib/ai/canvas-agent-runtime/video-store"; import { AgentRunError } from "@/lib/ai/canvas-agent-runtime/store"; import { publicAgentError } from "@/lib/ai/canvas-agent-runtime/protocol"; export const dynamic = "force-dynamic"; export async function GET(request: Request) { const session = await auth(); if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 }); try { const projectId = z.string().uuid().parse(new URL(request.url).searchParams.get("projectId")); await readOwnedVideoCanvas(session.user.id, projectId); // One stable conversation per video workspace survives browser reloads. const chat = await getChatById({ id: projectId }); if (chat && chat.userId !== session.user.id) throw new AgentRunError("对话不存在", 404); const messages = chat ? (await getMessagesByChatId({ id: projectId })).slice(-40) : []; return NextResponse.json( { messages: messages.map(({ id, role, parts }) => ({ id, role, parts })) }, { headers: { "Cache-Control": "private, no-store" } }, ); } catch (error) { return NextResponse.json( { error: publicAgentError(error) }, { status: error instanceof AgentRunError ? error.status : error instanceof z.ZodError ? 400 : 503, }, ); } } const saveSchema = z.object({ projectId: z.string().uuid(), baseRevision: z.string().datetime(), canvasData: z.object({ nodes: z.array(z.record(z.unknown())).max(2000), edges: z .array( z.object({ id: z.string(), source: z.string(), target: z.string(), type: z.string().optional(), }), ) .max(4000), selectedNodeIds: z.array(z.string()).max(20), viewport: z.object({ x: z.number().finite(), y: z.number().finite(), zoom: z.number().positive(), }), tool: z.literal("select"), }), }); export async function POST(request: Request) { const session = await auth(); if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 }); try { const body = saveSchema.parse(await request.json()); await saveVideoAgentCanvas(session.user.id, body.projectId, body.baseRevision, body.canvasData); return NextResponse.json({ success: true }); } catch (error) { return NextResponse.json( { error: publicAgentError(error) }, { status: error instanceof AgentRunError ? error.status : error instanceof z.ZodError ? 400 : 503, }, ); } }