feat(mcp,editor): Option A+B storage + 10 agent deliverables (Phase 7)

Ships the combined filesystem/Supabase storage adapter + MCP scene
lifecycle tools + Next.js API routes + editor /scene/[id] route, so
an MCP save is directly openable at /scene/<id> without any
injection hack. End-to-end verified: 10/10 e2e steps pass.

Storage (A1/A2/A3):
- SceneStore interface + error classes + slug helpers
- FilesystemSceneStore at $PASCAL_DATA_DIR (defaults XDG/~/.pascal)
  with atomic writes, .index sidecar, optimistic locking
- SupabaseSceneStore with scenes + scene_revisions tables, RLS
  migration SQL, mock-backed unit tests
- createSceneStore(env) auto-selects based on SUPABASE_URL +
  SUPABASE_SERVICE_ROLE_KEY

MCP tools (A4, A8, A9, A10):
- save_scene / load_scene / list_scenes / delete_scene / rename_scene
- list_templates / create_from_template (3 seed templates:
  empty-studio, two-bedroom, garden-house)
- generate_variants (7 mutation kinds, seeded RNG, save=true|false)
- photo_to_scene (vision sampling → scene graph → save)

Editor (A5, A6):
- /api/scenes + /api/scenes/[id] with RFC 7232 If-Match locking
- /scene/[id] and /scenes route pages with save button, SceneLoader
- Removed the window.__pascalScene dev injection hack

Security + UX edges (A7, A8):
- AssetUrl Zod validator: asset:// blob: data:image/ /path https:
  (http://localhost for dev) + PASCAL_ALLOWED_ASSET_ORIGINS env
  allowlist. Hardens scan.url, guide.url, item.asset.src,
  material.texture.url, MaterialMaps.*Map
- Auto-frame camera on empty→non-empty scene transition
  (camera-controls:fit-scene emitter event)

Shared utilities:
- rehydrateSiteChildren() extracted to packages/mcp/src/lib/ and
  used by both create-from-template and generate-variants to work
  around the SiteNode.children-as-objects vs. ids inconsistency
  (CROSS_CUTTING §2)
- Storage + MCP subpath exports added to packages/mcp/package.json
  (CROSS_CUTTING §4)

Tests: 293 pass / 0 fail across 40 files (was 142 pre-Phase-7).
Biome: clean.

Phase-7 e2e script at packages/mcp/test-reports/phase7-e2e.ts:
MCP HTTP + editor Next.js both point at $PASCAL_DATA_DIR =
/tmp/pascal-e2e, save_scene from MCP, GET /api/scenes/<id> from
editor server, /scenes list page renders all saved scenes, scene
page renders SceneLoader, delete_scene works.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Adrian Perez
2026-04-18 19:29:28 +02:00
co-authored by Claude Opus 4.7
parent 42bd05db9c
commit e8d0b13ff5
81 changed files with 8933 additions and 1213 deletions
+191
View File
@@ -0,0 +1,191 @@
import { type NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { getSceneStore } from '@/lib/scene-store-server'
export const dynamic = 'force-dynamic'
type RouteParams = { params: Promise<{ id: string }> }
const graphSchema = z.unknown().refine((v: unknown) => v !== null && typeof v === 'object', {
message: 'graph must be an object',
})
const putSceneSchema = z.object({
name: z.string().min(1).max(200).optional(),
graph: graphSchema,
thumbnailUrl: z.string().url().nullable().optional(),
expectedVersion: z.number().int().nonnegative().optional(),
})
const patchSceneSchema = z.object({
name: z.string().min(1).max(200),
expectedVersion: z.number().int().nonnegative().optional(),
})
export async function GET(_request: NextRequest, { params }: RouteParams) {
const { id } = await params
const store = await getSceneStore()
try {
const scene = await store.load(id)
if (!scene) {
return NextResponse.json({ error: 'not_found' }, { status: 404 })
}
return NextResponse.json(scene, {
headers: { ETag: `"${scene.version}"` },
})
} catch (error) {
return handleStoreError(error)
}
}
export async function PUT(request: NextRequest, { params }: RouteParams) {
const { id } = await params
let body: unknown
try {
body = await request.json()
} catch {
return NextResponse.json(
{ error: 'invalid_request', details: 'body must be valid JSON' },
{ status: 400 },
)
}
const parsed = putSceneSchema.safeParse(body)
if (!parsed.success) {
return NextResponse.json(
{ error: 'invalid_request', details: parsed.error.issues },
{ status: 400 },
)
}
const ifMatch = parseIfMatch(request.headers.get('If-Match'))
const expectedVersion = ifMatch ?? parsed.data.expectedVersion
const store = await getSceneStore()
try {
const existing = await store.load(id)
if (!existing) {
return NextResponse.json({ error: 'not_found' }, { status: 404 })
}
const meta = await store.save({
id,
name: parsed.data.name ?? existing.name,
projectId: existing.projectId,
ownerId: existing.ownerId,
graph: parsed.data.graph as never,
thumbnailUrl:
parsed.data.thumbnailUrl === undefined ? existing.thumbnailUrl : parsed.data.thumbnailUrl,
expectedVersion,
})
return NextResponse.json(meta, {
headers: { ETag: `"${meta.version}"` },
})
} catch (error) {
return handleStoreError(error, { includeCurrentVersionFor: id })
}
}
export async function DELETE(request: NextRequest, { params }: RouteParams) {
const { id } = await params
const ifMatch = parseIfMatch(request.headers.get('If-Match'))
const store = await getSceneStore()
try {
const removed = await store.delete(id, { expectedVersion: ifMatch })
if (!removed) {
return NextResponse.json({ error: 'not_found' }, { status: 404 })
}
return new NextResponse(null, { status: 204 })
} catch (error) {
return handleStoreError(error, { includeCurrentVersionFor: id })
}
}
export async function PATCH(request: NextRequest, { params }: RouteParams) {
const { id } = await params
let body: unknown
try {
body = await request.json()
} catch {
return NextResponse.json(
{ error: 'invalid_request', details: 'body must be valid JSON' },
{ status: 400 },
)
}
const parsed = patchSceneSchema.safeParse(body)
if (!parsed.success) {
return NextResponse.json(
{ error: 'invalid_request', details: parsed.error.issues },
{ status: 400 },
)
}
const ifMatch = parseIfMatch(request.headers.get('If-Match'))
const expectedVersion = ifMatch ?? parsed.data.expectedVersion
const store = await getSceneStore()
try {
const meta = await store.rename(id, parsed.data.name, { expectedVersion })
return NextResponse.json(meta, {
headers: { ETag: `"${meta.version}"` },
})
} catch (error) {
return handleStoreError(error, { includeCurrentVersionFor: id })
}
}
/**
* Parses an `If-Match` header value per RFC 7232. Accepts `"<version>"` or
* weak `W/"<version>"` forms. Returns `undefined` when the header is absent,
* the wildcard `*`, or unparseable as a non-negative integer.
*/
function parseIfMatch(raw: string | null): number | undefined {
if (!raw) return undefined
const trimmed = raw.trim()
if (trimmed === '*') return undefined
const match = trimmed.match(/^(?:W\/)?"([^"]+)"$/)
const inner = match ? match[1] : trimmed
if (!inner) return undefined
const n = Number(inner)
if (!Number.isFinite(n) || !Number.isInteger(n) || n < 0) return undefined
return n
}
async function handleStoreError(
error: unknown,
opts: { includeCurrentVersionFor?: string } = {},
): Promise<NextResponse> {
const code = (error as { code?: string })?.code
if (code === 'version_conflict') {
let currentVersion: number | undefined
if (opts.includeCurrentVersionFor) {
try {
const store = await getSceneStore()
const current = await store.load(opts.includeCurrentVersionFor)
currentVersion = current?.version
} catch {
// Best-effort; skip reporting currentVersion on secondary failure.
}
}
return NextResponse.json(
currentVersion === undefined
? { error: 'version_conflict' }
: { error: 'version_conflict', currentVersion },
{ status: 409 },
)
}
if (code === 'not_found') {
return NextResponse.json({ error: 'not_found' }, { status: 404 })
}
if (code === 'too_large') {
return NextResponse.json({ error: 'too_large' }, { status: 413 })
}
if (code === 'invalid') {
return NextResponse.json({ error: 'invalid' }, { status: 400 })
}
const message = error instanceof Error ? error.message : 'unexpected_error'
return NextResponse.json({ error: 'internal_error', message }, { status: 500 })
}
+105
View File
@@ -0,0 +1,105 @@
import { type NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { getSceneStore } from '@/lib/scene-store-server'
export const dynamic = 'force-dynamic'
/**
* The `graph` payload is an opaque `SceneGraph` — we don't re-validate the
* full Zod schema here to keep the route lean. The storage layer performs
* size checks, and consumers supply graphs they built with the editor/core
* schema already. Passing through as `unknown` keeps the API contract
* honest without duplicating the core schema surface.
*/
const graphSchema = z.unknown().refine((v: unknown) => v !== null && typeof v === 'object', {
message: 'graph must be an object',
})
const createSceneSchema = z.object({
id: z.string().min(1).max(64).optional(),
name: z.string().min(1).max(200),
projectId: z.string().min(1).max(200).nullable().optional(),
graph: graphSchema,
thumbnailUrl: z.string().url().nullable().optional(),
})
const listQuerySchema = z.object({
projectId: z.string().min(1).max(200).optional(),
limit: z.coerce.number().int().positive().max(500).optional(),
})
export async function GET(request: NextRequest) {
const url = new URL(request.url)
const parsed = listQuerySchema.safeParse({
projectId: url.searchParams.get('projectId') ?? undefined,
limit: url.searchParams.get('limit') ?? undefined,
})
if (!parsed.success) {
return NextResponse.json(
{ error: 'invalid_request', details: parsed.error.issues },
{ status: 400 },
)
}
const store = await getSceneStore()
const scenes = await store.list({
projectId: parsed.data.projectId,
limit: parsed.data.limit,
})
return NextResponse.json({ scenes })
}
export async function POST(request: NextRequest) {
let body: unknown
try {
body = await request.json()
} catch {
return NextResponse.json(
{ error: 'invalid_request', details: 'body must be valid JSON' },
{ status: 400 },
)
}
const parsed = createSceneSchema.safeParse(body)
if (!parsed.success) {
return NextResponse.json(
{ error: 'invalid_request', details: parsed.error.issues },
{ status: 400 },
)
}
const store = await getSceneStore()
try {
const meta = await store.save({
id: parsed.data.id,
name: parsed.data.name,
projectId: parsed.data.projectId ?? null,
graph: parsed.data.graph as never,
thumbnailUrl: parsed.data.thumbnailUrl ?? null,
})
return NextResponse.json(meta, {
status: 201,
headers: { Location: `/scene/${meta.id}` },
})
} catch (error) {
return handleStoreError(error)
}
}
function handleStoreError(error: unknown): NextResponse {
const code = (error as { code?: string })?.code
if (code === 'version_conflict') {
return NextResponse.json({ error: 'version_conflict' }, { status: 409 })
}
if (code === 'not_found') {
return NextResponse.json({ error: 'not_found' }, { status: 404 })
}
if (code === 'too_large') {
return NextResponse.json({ error: 'too_large' }, { status: 413 })
}
if (code === 'invalid') {
return NextResponse.json({ error: 'invalid' }, { status: 400 })
}
const message = error instanceof Error ? error.message : 'unexpected_error'
return NextResponse.json({ error: 'internal_error', message }, { status: 500 })
}
+22 -15
View File
@@ -1,18 +1,7 @@
'use client'
import {
Editor,
type SidebarTab,
ViewerToolbarLeft,
ViewerToolbarRight,
} from '@pascal-app/editor'
import { useScene } from '@pascal-app/core'
// Dev-only: expose the scene store on window so MCP can inject a built
// scene into the running editor for visual verification. No-op in prod.
if (typeof window !== 'undefined' && process.env.NODE_ENV !== 'production') {
;(window as unknown as { __pascalScene?: typeof useScene }).__pascalScene = useScene
}
import { Editor, type SidebarTab, ViewerToolbarLeft, ViewerToolbarRight } from '@pascal-app/editor'
import Link from 'next/link'
const SIDEBAR_TABS: (SidebarTab & { component: React.ComponentType })[] = [
{
@@ -22,12 +11,30 @@ const SIDEBAR_TABS: (SidebarTab & { component: React.ComponentType })[] = [
},
]
const PROJECT_ID = 'local-editor'
export default function Home() {
return (
<div className="h-screen w-screen">
<div className="relative h-screen w-screen">
{PROJECT_ID === 'local-editor' && (
<div className="pointer-events-none absolute top-3 left-1/2 z-40 -translate-x-1/2">
<div className="pointer-events-auto flex items-center gap-3 rounded-full border border-border/60 bg-background/90 px-4 py-1.5 text-xs shadow-sm backdrop-blur">
<span className="text-muted-foreground">Local editor scenes are not saved.</span>
<Link className="font-medium text-foreground hover:underline" href="/scenes">
Open recent scenes
</Link>
<span aria-hidden className="text-muted-foreground">
·
</span>
<Link className="font-medium text-foreground hover:underline" href="/scenes">
Create new
</Link>
</div>
</div>
)}
<Editor
layoutVersion="v2"
projectId="local-editor"
projectId={PROJECT_ID}
sidebarTabs={SIDEBAR_TABS}
viewerToolbarLeft={<ViewerToolbarLeft />}
viewerToolbarRight={<ViewerToolbarRight />}
+73
View File
@@ -0,0 +1,73 @@
import type { SceneGraph } from '@pascal-app/editor'
import { headers } from 'next/headers'
import Link from 'next/link'
import { SceneLoader, type SceneMeta } from '@/components/scene-loader'
export const dynamic = 'force-dynamic'
interface SceneWithGraph extends SceneMeta {
graph: SceneGraph
}
async function resolveBaseUrl(): Promise<string> {
if (process.env.NEXT_PUBLIC_APP_URL) {
return process.env.NEXT_PUBLIC_APP_URL
}
const h = await headers()
const host = h.get('x-forwarded-host') ?? h.get('host')
const proto = h.get('x-forwarded-proto') ?? 'http'
if (!host) {
return 'http://localhost:3000'
}
return `${proto}://${host}`
}
async function fetchScene(id: string): Promise<SceneWithGraph | null> {
const base = await resolveBaseUrl()
const response = await fetch(`${base}/api/scenes/${encodeURIComponent(id)}`, {
cache: 'no-store',
})
if (response.status === 404) {
return null
}
if (!response.ok) {
throw new Error(`Failed to load scene: ${response.status}`)
}
return (await response.json()) as SceneWithGraph
}
export default async function ScenePage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
const scene = await fetchScene(id)
if (!scene) {
return (
<div className="flex min-h-screen items-center justify-center bg-background p-6">
<div className="w-full max-w-md rounded-2xl border border-border/60 bg-background p-6 text-center shadow-xl">
<p className="font-mono text-muted-foreground text-xs uppercase tracking-wide">404</p>
<h1 className="mt-2 font-semibold text-lg">Scene not found</h1>
<p className="mt-2 text-muted-foreground text-sm">
We couldn&apos;t find a scene with id <code className="font-mono">{id}</code>.
</p>
<div className="mt-4 flex items-center justify-center gap-2">
<Link
className="rounded-md border border-border bg-accent px-3 py-2 font-medium text-sm hover:bg-accent/80"
href="/scenes"
>
Browse scenes
</Link>
<Link
className="rounded-md border border-border bg-background px-3 py-2 font-medium text-sm hover:bg-accent/40"
href="/"
>
Back to editor
</Link>
</div>
</div>
</div>
)
}
const { graph, ...meta } = scene
return <SceneLoader initialScene={graph} meta={meta} />
}
+117
View File
@@ -0,0 +1,117 @@
import { headers } from 'next/headers'
import Link from 'next/link'
import { CreateSceneButton } from '@/components/save-button'
import type { SceneMeta } from '@/components/scene-loader'
export const dynamic = 'force-dynamic'
async function resolveBaseUrl(): Promise<string> {
if (process.env.NEXT_PUBLIC_APP_URL) {
return process.env.NEXT_PUBLIC_APP_URL
}
const h = await headers()
const host = h.get('x-forwarded-host') ?? h.get('host')
const proto = h.get('x-forwarded-proto') ?? 'http'
if (!host) {
return 'http://localhost:3000'
}
return `${proto}://${host}`
}
async function fetchScenes(): Promise<SceneMeta[]> {
const base = await resolveBaseUrl()
const response = await fetch(`${base}/api/scenes?limit=50`, {
cache: 'no-store',
})
if (!response.ok) {
return []
}
const payload = (await response.json()) as { scenes?: SceneMeta[] } | SceneMeta[]
if (Array.isArray(payload)) {
return payload
}
return payload.scenes ?? []
}
function formatDate(iso: string): string {
try {
return new Date(iso).toLocaleString()
} catch {
return iso
}
}
export default async function ScenesPage() {
const scenes = await fetchScenes()
return (
<div className="min-h-screen bg-background">
<header className="sticky top-0 z-10 border-border border-b bg-background/95 backdrop-blur">
<div className="container mx-auto flex items-center justify-between gap-4 px-6 py-4">
<nav className="flex items-center gap-4 text-sm">
<Link
className="text-muted-foreground transition-colors hover:text-foreground"
href="/"
>
Home
</Link>
<span className="text-muted-foreground">/</span>
<span className="font-medium text-foreground">Scenes</span>
</nav>
<CreateSceneButton />
</div>
</header>
<main className="container mx-auto max-w-5xl px-6 py-12">
<h1 className="mb-2 font-bold text-3xl">Your scenes</h1>
<p className="mb-8 text-muted-foreground text-sm">
{scenes.length === 0
? 'No scenes yet. Create one to get started.'
: `${scenes.length} scene${scenes.length === 1 ? '' : 's'}.`}
</p>
{scenes.length === 0 ? (
<div className="rounded-xl border border-border/60 border-dashed bg-background p-12 text-center">
<p className="text-muted-foreground text-sm">You haven&apos;t saved any scenes yet.</p>
<div className="mt-4 flex justify-center">
<CreateSceneButton />
</div>
</div>
) : (
<ul className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
{scenes.map((scene) => (
<li key={scene.id}>
<Link
className="group block rounded-xl border border-border/60 bg-background p-4 transition-colors hover:border-border hover:bg-accent/30"
href={`/scene/${scene.id}`}
>
<div className="flex aspect-video items-center justify-center overflow-hidden rounded-lg bg-accent/30">
{scene.thumbnailUrl ? (
// eslint-disable-next-line @next/next/no-img-element
<img
alt={scene.name}
className="h-full w-full object-cover"
src={scene.thumbnailUrl}
/>
) : (
<span className="text-muted-foreground text-xs">No thumbnail</span>
)}
</div>
<div className="mt-3">
<h2 className="truncate font-semibold text-sm group-hover:text-foreground">
{scene.name}
</h2>
<div className="mt-1 flex items-center justify-between text-muted-foreground text-xs">
<span>{scene.nodeCount} nodes</span>
<time dateTime={scene.updatedAt}>{formatDate(scene.updatedAt)}</time>
</div>
</div>
</Link>
</li>
))}
</ul>
)}
</main>
</div>
)
}