ai-chatbot/apps/editor/components/save-button.tsx
Adrian Perez e8d0b13ff5 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>
2026-04-18 19:29:28 +02:00

158 lines
4.6 KiB
TypeScript

'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>
)
}