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>
)
}
+157
View File
@@ -0,0 +1,157 @@
'use client'
import type { SceneGraph } from '@pascal-app/editor'
import { useRouter } from 'next/navigation'
import { useCallback, useState } from 'react'
const EMPTY_GRAPH: SceneGraph = {
nodes: {},
rootNodeIds: [],
}
interface SaveButtonProps {
sceneId: string
name: string
version: number
getGraph: () => SceneGraph | null
}
/**
* Creates a new empty scene and navigates the user to it.
*/
export function CreateSceneButton({ label = 'Create new scene' }: { label?: string } = {}) {
const router = useRouter()
const [isCreating, setIsCreating] = useState(false)
const [error, setError] = useState<string | null>(null)
const handleCreate = useCallback(async () => {
setIsCreating(true)
setError(null)
try {
const response = await fetch('/api/scenes', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Untitled scene', graph: EMPTY_GRAPH }),
})
if (!response.ok) {
setError(`Failed to create scene (${response.status})`)
return
}
const meta = (await response.json()) as { id: string }
router.push(`/scene/${meta.id}`)
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to create scene')
} finally {
setIsCreating(false)
}
}, [router])
return (
<div className="flex items-center gap-3">
{error && <span className="text-destructive text-xs">{error}</span>}
<button
className="rounded-md border border-border bg-accent px-3 py-1.5 font-medium text-sm hover:bg-accent/80 disabled:opacity-50"
disabled={isCreating}
onClick={handleCreate}
type="button"
>
{isCreating ? 'Creating…' : label}
</button>
</div>
)
}
/**
* Save + Save-as buttons that call the scenes API directly.
* Used for UIs that want explicit save controls outside of the Editor's
* built-in autosave plumbing.
*/
export function SaveButton({ sceneId, name, version, getGraph }: SaveButtonProps) {
const router = useRouter()
const [isSaving, setIsSaving] = useState(false)
const [status, setStatus] = useState<string | null>(null)
const handleSave = useCallback(async () => {
const graph = getGraph()
if (!graph) {
setStatus('No scene to save')
return
}
setIsSaving(true)
setStatus(null)
try {
const response = await fetch(`/api/scenes/${sceneId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'If-Match': String(version),
},
body: JSON.stringify({ name, graph }),
})
if (response.status === 409) {
setStatus('Conflict — reload to continue')
return
}
if (!response.ok) {
setStatus(`Save failed (${response.status})`)
return
}
setStatus('Saved')
} catch (error) {
setStatus(error instanceof Error ? error.message : 'Save failed')
} finally {
setIsSaving(false)
}
}, [getGraph, name, sceneId, version])
const handleSaveAs = useCallback(async () => {
const graph = getGraph()
if (!graph) {
setStatus('No scene to save')
return
}
const newName = typeof window !== 'undefined' ? window.prompt('New scene name', name) : null
if (!newName) return
setIsSaving(true)
setStatus(null)
try {
const response = await fetch('/api/scenes', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: newName, graph }),
})
if (!response.ok) {
setStatus(`Save-as failed (${response.status})`)
return
}
const meta = (await response.json()) as { id: string }
router.push(`/scene/${meta.id}`)
} catch (error) {
setStatus(error instanceof Error ? error.message : 'Save-as failed')
} finally {
setIsSaving(false)
}
}, [getGraph, name, router])
return (
<div className="flex items-center gap-2">
<button
className="rounded-md border border-border bg-accent px-3 py-1.5 font-medium text-xs hover:bg-accent/80 disabled:opacity-50"
disabled={isSaving}
onClick={handleSave}
type="button"
>
{isSaving ? 'Saving…' : 'Save'}
</button>
<button
className="rounded-md border border-border bg-background px-3 py-1.5 font-medium text-xs hover:bg-accent/40 disabled:opacity-50"
disabled={isSaving}
onClick={handleSaveAs}
type="button"
>
Save as
</button>
{status && <span className="text-muted-foreground text-xs">{status}</span>}
</div>
)
}
+145
View File
@@ -0,0 +1,145 @@
'use client'
import {
Editor,
type SceneGraph,
type SidebarTab,
ViewerToolbarLeft,
ViewerToolbarRight,
} from '@pascal-app/editor'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { useCallback, useRef, useState } from 'react'
export interface SceneMeta {
id: string
name: string
projectId: string | null
thumbnailUrl: string | null
version: number
createdAt: string
updatedAt: string
ownerId: string | null
sizeBytes: number
nodeCount: number
}
const SIDEBAR_TABS: (SidebarTab & { component: React.ComponentType })[] = [
{
id: 'site',
label: 'Scene',
component: () => null, // Built-in SitePanel handles this
},
]
interface SceneLoaderProps {
initialScene: SceneGraph
meta: SceneMeta
}
export function SceneLoader({ initialScene, meta }: SceneLoaderProps) {
const router = useRouter()
const versionRef = useRef(meta.version)
const [conflict, setConflict] = useState(false)
const [saveError, setSaveError] = useState<string | null>(null)
const handleLoad = useCallback(async () => initialScene, [initialScene])
const handleSave = useCallback(
async (graph: SceneGraph) => {
try {
const response = await fetch(`/api/scenes/${meta.id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'If-Match': String(versionRef.current),
},
body: JSON.stringify({ name: meta.name, graph }),
})
if (response.status === 409) {
setConflict(true)
return
}
if (!response.ok) {
setSaveError(`Save failed (${response.status})`)
return
}
const next = (await response.json()) as SceneMeta
versionRef.current = next.version
setSaveError(null)
} catch (error) {
setSaveError(error instanceof Error ? error.message : 'Save failed')
}
},
[meta.id, meta.name],
)
const handleThumb = useCallback(
async (_blob: Blob) => {
// TODO(phase7): upload thumbnail via POST /api/scenes/[id]/thumbnail.
// Stub endpoint is not yet implemented in v0.1 — skip upload for now.
await fetch(`/api/scenes/${meta.id}/thumbnail`, {
method: 'POST',
// Intentionally no body — endpoint is a stub.
}).catch(() => {
// Swallow errors silently; thumbnail upload is best-effort.
})
},
[meta.id],
)
return (
<div className="relative h-screen w-screen">
{conflict && (
<div className="pointer-events-auto absolute top-4 left-1/2 z-50 w-full max-w-md -translate-x-1/2 rounded-lg border border-border bg-background p-4 shadow-xl">
<h2 className="font-semibold text-sm">Another session saved first refresh?</h2>
<p className="mt-1 text-muted-foreground text-xs">
Your changes haven&apos;t been saved. Reload to pick up the latest version.
</p>
<div className="mt-3 flex items-center gap-2">
<button
className="rounded-md border border-border bg-accent px-3 py-1.5 font-medium text-xs hover:bg-accent/80"
onClick={() => router.refresh()}
type="button"
>
Reload
</button>
<button
className="rounded-md border border-border bg-background px-3 py-1.5 font-medium text-xs hover:bg-accent/40"
onClick={() => setConflict(false)}
type="button"
>
Dismiss
</button>
</div>
</div>
)}
{saveError && !conflict && (
<div className="pointer-events-auto absolute top-4 left-1/2 z-50 w-full max-w-md -translate-x-1/2 rounded-lg border border-destructive/50 bg-background p-3 shadow-xl">
<p className="font-medium text-destructive text-xs">{saveError}</p>
</div>
)}
<div className="pointer-events-none absolute top-4 right-4 z-40 flex items-center gap-2">
<Link
className="pointer-events-auto rounded-md border border-border bg-background/90 px-3 py-1.5 font-medium text-xs shadow-sm backdrop-blur hover:bg-accent/40"
href="/scenes"
>
All scenes
</Link>
</div>
<Editor
layoutVersion="v2"
onLoad={handleLoad}
onSave={handleSave}
onThumbnailCapture={handleThumb}
projectId={meta.projectId ?? 'default'}
sidebarTabs={SIDEBAR_TABS}
viewerToolbarLeft={<ViewerToolbarLeft />}
viewerToolbarRight={<ViewerToolbarRight />}
/>
</div>
)
}
@@ -0,0 +1,58 @@
import { beforeEach, describe, expect, mock, test } from 'bun:test'
describe('getSceneStore', () => {
beforeEach(() => {
mock.module('@pascal-app/mcp/storage', () => {
let callCount = 0
return {
createSceneStore: async (_env?: NodeJS.ProcessEnv) => {
callCount++
return {
backend: 'filesystem' as const,
__instanceNumber: callCount,
save: async () => ({}) as never,
load: async () => null,
list: async () => [],
delete: async () => false,
rename: async () => ({}) as never,
}
},
}
})
})
test('returns the same promise on repeated calls', async () => {
const mod = await import('./scene-store-server')
mod.__resetSceneStoreForTests()
const a = mod.getSceneStore()
const b = mod.getSceneStore()
expect(a).toBe(b)
})
test('resolves to the same store instance across calls', async () => {
const mod = await import('./scene-store-server')
mod.__resetSceneStoreForTests()
const storeA = await mod.getSceneStore()
const storeB = await mod.getSceneStore()
expect(storeA).toBe(storeB)
// Factory should have been invoked exactly once — asserted indirectly via
// our mock's instance counter.
expect((storeA as unknown as { __instanceNumber: number }).__instanceNumber).toBe(1)
expect((storeB as unknown as { __instanceNumber: number }).__instanceNumber).toBe(1)
})
test('reset helper clears the cached singleton', async () => {
const mod = await import('./scene-store-server')
mod.__resetSceneStoreForTests()
const first = await mod.getSceneStore()
mod.__resetSceneStoreForTests()
const second = await mod.getSceneStore()
expect(first).not.toBe(second)
})
})
+91
View File
@@ -0,0 +1,91 @@
// TODO: auth — every call in this module currently runs unauthenticated.
// v0.1 skips auth; the factory should eventually receive a user context from
// middleware / a request-scoped session and propagate it into SceneStore.
// Only import this module from server code (route handlers, server components,
// server actions). Importing from client code will leak the Supabase service
// role key into the browser bundle.
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
/**
* Inlined copies of the shared storage contract. The canonical source lives in
* `packages/mcp/src/storage/types.ts`; re-declared here so the editor only
* needs the runtime factory from `@pascal-app/mcp/storage` and type-checks
* without a hard compile-time dependency on the MCP package's source tree.
*
* Keep this file in sync whenever the MCP storage types change.
*/
export type SceneId = string
export interface SceneMeta {
id: SceneId
name: string
projectId: string | null
thumbnailUrl: string | null
version: number
createdAt: string
updatedAt: string
ownerId: string | null
sizeBytes: number
nodeCount: number
}
export interface SceneWithGraph extends SceneMeta {
graph: SceneGraph
}
export interface SceneSaveOptions {
id?: SceneId
name: string
projectId?: string | null
ownerId?: string | null
graph: SceneGraph
thumbnailUrl?: string | null
expectedVersion?: number
}
export interface SceneListOptions {
projectId?: string
ownerId?: string
limit?: number
}
export interface SceneMutateOptions {
expectedVersion?: number
}
export interface SceneStore {
readonly backend: 'filesystem' | 'supabase'
save(opts: SceneSaveOptions): Promise<SceneMeta>
load(id: SceneId): Promise<SceneWithGraph | null>
list(opts?: SceneListOptions): Promise<SceneMeta[]>
delete(id: SceneId, opts?: SceneMutateOptions): Promise<boolean>
rename(id: SceneId, newName: string, opts?: SceneMutateOptions): Promise<SceneMeta>
}
/**
* Per-process singleton. The factory is async because backend modules are
* dynamically imported — we cache the in-flight promise so concurrent calls
* during a cold start share a single instantiation.
*/
let cached: Promise<SceneStore> | null = null
export function getSceneStore(): Promise<SceneStore> {
if (!cached) {
cached = (async () => {
const mod = (await import('@pascal-app/mcp/storage')) as {
createSceneStore: (env?: NodeJS.ProcessEnv) => Promise<SceneStore>
}
return mod.createSceneStore(process.env)
})()
}
return cached
}
/**
* Test-only helper to reset the cached singleton. Not exported for production
* callers.
*/
export function __resetSceneStoreForTests(): void {
cached = null
}
+3 -1
View File
@@ -14,6 +14,7 @@
"@number-flow/react": "^0.5.14",
"@pascal-app/core": "*",
"@pascal-app/editor": "*",
"@pascal-app/mcp": "*",
"@pascal-app/viewer": "*",
"@react-three/drei": "^10.7.7",
"@react-three/fiber": "^9.5.0",
@@ -26,7 +27,8 @@
"react-dom": "^19.2.4",
"tailwind-merge": "^3.5.0",
"tailwindcss": "^4.2.1",
"three": "^0.184.0"
"three": "^0.184.0",
"zod": "^4.3.5"
},
"devDependencies": {
"@pascal/typescript-config": "*",