CanvasForge

Turn prompts into editable, shippable page layouts.

CanvasForge is an enterprise workspace for generating structured page layouts from natural language, previewing them in a secure sandbox, editing the result in real time, and exporting production-ready Next.js projects. It is built for product teams, designers, and internal platform teams that want AI-assisted layout generation without sacrificing type safety, security, or control.

Business Goals

  • Reach 300 active teams within 6 months of launch.
  • Convert at least 25% of trial users to paid plans within 90 days of signup.
  • Keep monthly AI generation costs under 18% of revenue through token budgeting and call limits.
  • Achieve 40% week-4 retention for workspace users by shipping fast edit-and-preview loops.
  • Reduce median time from prompt to first usable layout to under 3 minutes.

User Goals

  • Generate a structured page layout from a plain-language prompt without writing code.
  • Inspect and edit text, spacing, and colors immediately after generation.
  • Trust that previewed layouts are isolated from the host app and cannot run arbitrary code.
  • Export a clean Next.js App Router project that engineering can continue from.
  • Understand generation progress, token usage, and quota limits before running expensive requests.

Non-Goals

  • Not a general-purpose code editor or full CMS.
  • Not a visual website builder with freeform drag-and-drop composition.
  • Not a multi-framework exporter for Vue, Svelte, or plain HTML.
  • Not a public marketplace for sharing or remixing templates in v1.

Product Designer Priya, 34 - Priya designs internal marketing and product pages for a B2B SaaS team. She needs a fast way to turn rough content ideas into a validated layout she can review with stakeholders.

Product Designer Priya, 34

  • As a product designer, I want to generate a landing page layout from a short prompt, so that I can explore directions before handoff.
  • As a product designer, I want to edit headings and button labels in the inspector, so that I can refine copy without regenerating the whole page.
  • As a product designer, I want to export a working Next.js project, so that engineering can implement the approved layout quickly.

Frontend Engineer Marcus, 41 - Marcus owns a small internal design system and wants AI assistance without giving up code quality or security. He cares about predictable outputs, typed components, and project portability.

Frontend Engineer Marcus, 41

  • As a frontend engineer, I want the generated AST to be strictly validated, so that I can trust the layout structure before export.
  • As a frontend engineer, I want a sandboxed preview that cannot execute arbitrary code, so that I can review output safely.
  • As a frontend engineer, I want deterministic code generation, so that repeated exports produce stable diffs.

Ops Lead Elena, 39 - Elena manages enterprise software usage and budget controls. She needs visibility into quotas, connection status, and token spend across the team.

Ops Lead Elena, 39

  • As an ops lead, I want to see token consumption and remaining quota, so that I can manage costs proactively.
  • As an ops lead, I want a dedicated integration screen for model connection status, so that I can verify the account is configured correctly.
  • As an ops lead, I want generation requests to stop when quota is exhausted, so that the system never overspends unexpectedly.

AI Prompt-to-Layout Generation · High priority

  • Users can submit a natural-language prompt and receive a structured page layout AST that is validated before preview or save.
  • Support streaming generation events from the backend with visible progress and model call count.
  • Reject invalid or truncated outputs until they are repaired or explicitly failed.
  • Enforce a strict model call budget of three calls per generation request.
  • Store only validated ASTs in the database and never persist partial JSON as a successful version.
  • Use a controlled component allowlist only.

Sandboxed Preview Renderer · High priority

  • Render validated layouts inside an isolated iframe using a deterministic component renderer and a strict host-preview message protocol.
  • Use an iframe sandbox with scripts enabled but no same-origin, forms, popups, or top navigation.
  • Validate all host-preview messages with Zod and session nonces.
  • Prevent arbitrary HTML, JavaScript, or React source execution.
  • Support live updates for text, color, and component property changes without model calls.
  • Handle iframe readiness, resize requests, and preview errors deterministically.

Inspector and Real-Time Editing · High priority

  • Users can select supported components and edit allowed properties instantly with undo/redo and autosave.
  • Allow editing of heading text, paragraph content, button labels, badge labels, and input placeholders.
  • Allow editing of page background, component background, text color, border color, and button color through validated tokens.
  • Update local AST state immediately and push validated changes to preview via postMessage.
  • Provide undo/redo for property changes and a dirty state indicator.
  • Debounce autosave and surface save failures without losing local changes.

Export to Next.js Project · High priority

  • Users can export the current validated layout as a standalone ZIP containing a clean Next.js App Router project.
  • Generate deterministic React components from the validated AST.
  • Include package.json, app router files, Tailwind v4 setup, typed props, README, and environment example files where needed.
  • Exclude secrets, auth tokens, database credentials, and internal service endpoints from the export.
  • Package the project using ZIP generation with stable file ordering.
  • Ensure the exported project builds independently after dependency installation.

Authentication, Quotas, and Project Management · Medium priority

  • Users can log in with Google, manage projects, and see token usage and generation limits in the dashboard.
  • Use secure session-based login and server-side authorization for all generation requests.
  • Track token quota, reserved tokens, and consumed tokens per user in PostgreSQL.
  • Support project creation, deletion, search, and recent project listing.
  • Show account connection status for the model provider and guidance when supported authentication is unavailable.
  • Prevent concurrent generations from overspending quota.

First-Time Workspace Onboarding

  • Sign in with Google and land on the dashboard with quota and connection status visible.
  • Create a new project from a starter prompt or empty workspace.
  • Connect or verify the model provider account using the supported authentication method.
  • Submit a prompt and watch generation stream into the AST panel within 30 to 60 seconds for typical requests.
  • Review the validated preview in the sandboxed iframe and make the first text edit immediately.
  • Export the finished layout as a ZIP or save it as a versioned project.

1. Prompt and Budget Check

  • The user enters a page prompt and the system checks quota, call budget, and provider connection before generation begins.
  • Reject requests early if available tokens are zero or negative.
  • Display estimated token cost and the maximum model call count before submission.
  • Prevent duplicate submissions while one generation is in flight.

2. Streaming Generation

  • The backend streams structured progress events and incremental AST text back to the browser.
  • Show model call started, AST delta, validation, and completion events in a logs panel.
  • Handle provider exhaustion or timeouts with normalized error codes.
  • Do not render incomplete JSON as executable output.

3. Validated Preview

  • Once the AST passes validation, the sandbox iframe renders the page using the allowlisted component registry.
  • Use a deterministic renderer that maps only approved component types.
  • Refresh the preview only after full validation succeeds.
  • Show clear preview errors if the sandbox contract fails.

4. Inspector Editing

  • The user selects a component and edits supported properties in the inspector with instant feedback.
  • Apply local changes immediately and sync them to the preview via postMessage.
  • Support undo/redo and unsaved-change indicators.
  • Validate color values and component-specific props before saving.

5. Save and Export

  • The user saves a versioned project state or exports the layout as a ZIP for engineering handoff.
  • Persist validated AST snapshots in JSONB.
  • Generate deterministic Next.js App Router source files on export.
  • Show export progress and a clear success state with download access.

Power User Features and Edge Cases

  • Token-aware generation budgeting that blocks overspend before provider calls.
  • Generation cancellation with abort propagation from browser to Next.js to FastAPI.
  • Support for model continuation or repair when output is truncated or invalid.
  • Version history for saved layouts with timestamps and prompt context.
  • Dedicated model connection screen with supported authentication guidance and connection testing.
  • Safe handling for opaque-origin iframe messaging with session nonce validation.

Interface Quality Principles

  • Keep the workspace responsive with a three-panel layout and collapsible event log.
  • Use accessible color tokens and keyboard navigable component selection.
  • Surface quota, call count, and validation state prominently to reduce uncertainty.
  • Prefer fast local updates over AI regeneration for ordinary text and color edits.
  • Optimize for low-latency streaming feedback and minimal visual jank.

Priya starts with a vague request for a pricing page and a deadline in two days. In CanvasForge, she signs in, opens a new workspace, and submits a prompt that produces a structured layout within minutes instead of waiting for a full design pass.

She reviews the validated preview in the sandbox, changes a headline and button label in the inspector, and adjusts the hero background color using approved tokens. The page updates instantly, and she exports a clean Next.js project that her engineering team can drop into the codebase with minimal cleanup.

What used to take multiple design reviews and handoff cycles now happens in one workspace with clear quota controls, safe previews, and deterministic code output. For the business, that means faster internal delivery, fewer rework loops, and more predictable AI usage costs.

User-Centric Metrics

  • At least 70% of new users generate a valid first layout within 5 minutes.
  • At least 85% of successful generations render a validated preview on the first attempt.
  • At least 60% of projects receive at least one inspector edit after generation.
  • Average time from prompt submission to usable preview under 90 seconds for standard requests.
  • Undo/redo used in at least 30% of editing sessions, indicating active refinement.

Business Metrics

  • 25% trial-to-paid conversion within 90 days.
  • 40% week-4 retention for active workspace users.
  • Monthly active teams growing by 15% quarter over quarter.
  • Average revenue per account increases through quota-based usage expansion.
  • Generation cost remains below 18% of revenue on a monthly basis.

Technical Metrics

  • 99.9% API uptime for core workspace endpoints.
  • P95 prompt-to-first-stream event latency under 3 seconds.
  • P95 complete generation time under 90 seconds for standard layouts.
  • Zero tolerance for secret leakage into exports or preview messages.

Tracking Plan

  • Track project_created with source and user segment.
  • Track generation_requested with prompt length, requested budget, and project id.
  • Track model_call_started with call number and provider metadata.
  • Track ast_validated with component count, depth, and validation duration.
  • Track inspector_edit_applied with field name and component type.
  • Track export_started and export_completed with file size and build target.
  • Track generation_error with normalized error code and recovery outcome.

Technical Needs

  • Next.js App Router frontend with route handlers, server actions, and secure server-side sessions.
  • FastAPI generation service with native async streaming and SSE responses.
  • PostgreSQL with Drizzle ORM and JSONB storage for validated PageLayoutAST snapshots.
  • Pydantic v2 as the canonical schema source, with generated JSON Schema shared to TypeScript.
  • Ajv validation in the browser and sandbox renderer for the generated schema.
  • fflate for deterministic ZIP packaging of exported projects.
  • Strict TypeScript and Tailwind CSS v4 for the host application and exported project templates.

Integration Points

  • Google OAuth 2.0 / OIDC via Auth.js for application login.
  • Google Antigravity SDK for model generation, using only officially supported authentication methods.
  • PostgreSQL or Neon serverless PostgreSQL as the primary data store.
  • Browser postMessage channel between host app and sandboxed iframe.
  • Server-to-server authenticated SSE proxy between Next.js and FastAPI.

Data Storage & Privacy

  • Store only the minimum account and project metadata required for product operation.
  • Encrypt any provider credential references at rest and never show stored secrets after save.
  • Keep validated layout ASTs in JSONB and avoid storing raw unfiltered model transcripts as primary project state.
  • Support deletion of projects and account connection data in line with GDPR and CCPA expectations.
  • Separate application login identity from model provider connection records to reduce credential coupling.

Scalability & Performance

  • Use streaming responses and incremental events to reduce perceived latency.
  • Keep the rendering contract bounded with component count and nesting depth limits.
  • Reserve and reconcile tokens atomically to prevent overspend under concurrency.
  • Avoid heavyweight background workers or extra infrastructure for the MVP.
  • Optimize export generation for deterministic file writes and stable archive creation.

Potential Challenges

  • Model output may be invalid or truncated, mitigated by strict validation, repair attempts, and continuation limits.
  • Quota overspend under concurrent requests, mitigated by atomic reservation and server-side accounting.
  • Sandbox escape or message spoofing, mitigated by iframe sandboxing, source checks, session nonces, and Zod validation.
  • Provider authentication ambiguity for Antigravity, mitigated by supporting only documented authentication methods and surfacing unsupported modes clearly.
  • Export drift between preview and generated code, mitigated by a single canonical AST and deterministic renderer/codegen pipeline.

Team & resourcing - Small team - 2 full-stack engineers, 1 product designer, part-time PM, and shared DevOps/security support

Phase 1: Core Workspace MVP · Weeks 1–4

  • Google login and secure sessions
  • Project dashboard with create, list, search, and delete
  • Validated prompt-to-AST generation pipeline with SSE streaming
  • Sandboxed preview iframe with allowlisted renderer
  • PostgreSQL schema, Drizzle setup, and basic quota tracking

Phase 2: Editing and Reliability · Weeks 5–7

  • Inspector for text and color edits
  • Undo/redo, autosave, and versioned project state
  • Generation cancellation and normalized error handling
  • Token reservation and reconciliation logic
  • Provider connection screen with supported authentication guidance

Phase 3: Export and Hand-off · Weeks 8–9

  • Deterministic Next.js App Router export to ZIP
  • Reusable component generation from validated AST
  • README and environment example generation
  • Preview and export parity checks
  • Download, error, and success states for export flow

Phase 4: Harden and Launch · Weeks 10–12

  • Security review for sandbox and message protocol
  • Performance tuning for streaming and validation paths
  • Analytics instrumentation and usage dashboards
  • Accessibility pass for all primary screens
  • Beta launch with quota controls and support playbooks

Paste this into Cursor, Bolt, Lovable, or v0 to start building.

Build a production-ready web app called CanvasForge, an enterprise AI-assisted page layout workspace.

Tech stack:
Next.js App Router, React 19, TypeScript strict mode, Tailwind CSS v4, shadcn/ui, Lucide icons, Zod on the frontend, PostgreSQL with Drizzle ORM, Auth.js with Google OAuth login, and a separate FastAPI service for AI generation streaming.

Core product requirements:
1. Users sign in with Google and land on a dashboard showing projects, remaining token quota, tokens consumed, generation limits, and model account connection status.
2. Users create a project, enter a natural-language prompt, and start a generation request.
3. The backend streams generation progress over SSE through Next.js from FastAPI, with event types for generation_started, generation_progress, model_call_started, ast_delta, ast_validated, generation_completed, generation_error, and generation_cancelled.
4. The AI output must be a strictly validated PageLayoutAST built from Pydantic models in Python, then shared as JSON Schema for TypeScript validation. The app must never accept executable code, arbitrary HTML, or arbitrary React source.
5. Supported components only: Container, Section, Grid, Flex, Heading, Paragraph, Button, Badge, Card, Image placeholder, Input, Textarea, Divider, Spacer.
6. Render the validated AST inside a sandboxed iframe with no allow-same-origin, no forms, no popups, no top navigation. Use postMessage with Zod validation, session nonce checks, and source checks for host-preview communication.
7. Build an inspector panel for editing text and colors only for supported properties, with instant updates, undo/redo, autosave, and dirty state indication.
8. Add export to ZIP that generates a clean Next.js App Router project with typed components, app/layout.tsx, app/page.tsx, package.json, tsconfig.json, Tailwind v4 setup, README, and no secrets.
9. Implement quota enforcement in PostgreSQL with atomic token reservation, concurrent request protection, call limits of 3 per generation, and normalized error handling for quota exceeded, truncated output, validation failure, unavailable model, timeout, and cancellation.
10. Include project CRUD, version tracking, connection screen for the model provider, and clear empty/loading/error states.

Data model:
users with id, email, name, avatar_url, token_quota, tokens_consumed, tokens_reserved, created_at, updated_at.
projects with id, user_id, name, description, prompt, layout_ast JSONB, status, created_at, updated_at.
user_antigravity_accounts with id, user_id, provider, authentication_method, account_metadata, encrypted_credential_reference, connection_status, last_verified.

Implementation guidance:
Use a minimal two-service architecture: Next.js handles authentication, user management, projects, quota accounting, SSE proxying, preview orchestration, and export. FastAPI handles prompt construction, AI generation, streaming, Pydantic validation, and error normalization. Use secure server-to-server authentication between them. Keep dependencies lean. Prioritize type safety, deterministic rendering, security boundaries, and low-latency streaming.

Deliver the full app with working screens, routes, components, database schema, streaming flow, sandboxed preview, inspector, export pipeline, and clear placeholder implementations only where an external service is required.

Business Idea

# CANVFORGE — Enterprise AI-Assisted Page Layout Workspace ## 1. ROLE & OBJECTIVE Act as a Principal Software Architect, Senior Full-Stack Engineer, AI Integration Engineer, and Application Security Engineer. Build **CanvasForge**, an AI-assisted visual page layout workspace that enables users to: 1. Generate structured UI layouts from natural-language prompts. 2. Stream generation progress and validated UI AST. 3. Preview generated layouts inside an isolated sandboxed iframe. 4. Edit text, colors, and supported component properties instantly. 5. Export production-ready Next.js App Router projects as ZIP files. Build a functional application, not merely a UI mockup or architectural demonstration. Prioritize: - Technical correctness. - Minimal infrastructure. - Low memory and CPU consumption. - Fast development and build times. - Strict type safety. - Maintainable architecture. - Secure execution boundaries. - Predictable AI generation costs. --- # 2. TECHNOLOGY STACK Use the following stack unless an incompatibility is demonstrated through official documentation. ## Frontend - Next.js 16 (latest stable compatible release). - React 19. - TypeScript with strict mode. - Next.js App Router. - Tailwind CSS v4. - shadcn/ui. - Lucide React. - React built-in hooks for local state management. - Zod for runtime validation. - Ajv for validating generated JSON Schema. Avoid unnecessary state management libraries. ## Backend **Next.js application backend:** - Route Handlers. - Server Components. - Server Actions where appropriate. - Node.js runtime. - Streaming API proxy. **AI Generation Service:** - Python 3.11+. - FastAPI. - Pydantic v2. - Google Antigravity Python SDK. - Native asynchronous streaming. - SSE through FastAPI StreamingResponse. Keep the Python service dedicated to AI generation and AST validation. Do not duplicate authentication, database operations, or business logic unnecessarily between the two services. ## Database - PostgreSQL. - Drizzle ORM. - Neon serverless PostgreSQL as the default managed database option. - Use a compatible PostgreSQL connection driver. - JSONB for storing validated PageLayoutAST. For deployments using persistent PostgreSQL infrastructure, allow a standard PostgreSQL connection through configuration. ## Authentication - Auth.js. - Google OAuth 2.0 / OIDC for CanvasForge application login. - Use the authentication library's supported PKCE and state validation. - Secure server-side sessions. Important distinction: Application login and Antigravity model authentication are separate concerns. Do not assume that CanvasForge can obtain an Antigravity personal account token through a generic Google OAuth PKCE flow. Before implementing Antigravity authentication: 1. Inspect the official Google Antigravity SDK documentation. 2. Identify currently supported programmatic authentication methods. 3. Implement only officially supported authentication paths. 4. Support Gemini API Key and Google Cloud/Vertex AI authentication where supported. 5. Do not extract credentials from local CLI files, browser sessions, or operating-system keychains. 6. Do not fabricate OAuth endpoints or token exchange behavior. If per-user personal Google account authentication is not officially supported for the hosted SDK integration, provide a clear limitation and an appropriate supported connection alternative. ## Export - fflate for ZIP packaging. - Deterministic AST-to-React code generation. - No external build service required. ## Dependency Policy Use the smallest practical dependency set. Do not introduce: - Redis. - Celery. - Kafka. - Kubernetes. - Multiple database systems. - Separate caching infrastructure. - Additional microservices. - Heavy state management libraries. Do not install dependencies that duplicate existing framework capabilities. Verify package compatibility before adding dependencies. Use stable releases and generate reproducible lockfiles. --- # 3. SYSTEM ARCHITECTURE Build a minimal two-service architecture. ### Service A: Next.js Application Responsibilities: - Application authentication. - User management. - Project management. - Database access. - Quota enforcement. - Token consumption accounting. - SSE proxy. - UI state management. - Preview orchestration. - Inspector editing. - ZIP export. ### Service B: Python FastAPI Generation Service Responsibilities: - Antigravity SDK integration. - Prompt construction. - AI generation. - Structured output handling. - Streaming generation events. - Pydantic validation. - Error normalization. The Python service must not independently manage user sessions or user quotas. Next.js is responsible for authorizing every generation request and calculating the allowed token budget. ### Communication Use the following flow: Browser → Next.js API → FastAPI → Antigravity SDK. Generation events travel back through the same path using SSE. All sensitive credentials remain server-side. Do not expose the FastAPI service directly to browsers. Use service-to-service authentication between Next.js and FastAPI. --- # 4. STRICT UI GENERATION CONTRACT This is one of the most important requirements. Pydantic models are the ONLY permitted schemas for AI-generated UI layouts. Implement: - `UIComponentNode` - `PageLayoutAST` Use Pydantic v2 with: - Strict field validation. - `extra="forbid"`. - Discriminated unions. - Explicit property types. - Required fields. - Bounded recursive structures. - Maximum component count. - Maximum nesting depth. - Validated color values. - Explicit component allowlists. Example conceptual AST: ```json { "version": 1, "page": { "title": "Dashboard", "background": "#FFFFFF", "children": [ { "type": "heading", "props": { "text": "Welcome", "level": 1 } }, { "type": "button", "props": { "text": "Get Started", "variant": "primary" } } ] } } ``` This is an illustrative format. Define the actual production schema and its constraints explicitly. ## Schema Management Pydantic is the canonical source of truth. Generate a JSON Schema artifact from the Python Pydantic models. Place the generated contract in a shared location accessible to both services. Use Ajv in TypeScript and the sandbox renderer to validate the generated JSON Schema. Use Zod for the independent host-preview communication protocol. Do not manually maintain competing definitions of the UI AST. The frontend must never accept arbitrary generated JSX, JavaScript, HTML, or executable source code. AI output must contain structured data only. ## Supported Components Initially support a controlled component registry: - Container. - Section. - Grid. - Flex. - Heading. - Paragraph. - Button. - Badge. - Card. - Image placeholder. - Input. - Textarea. - Divider. - Spacer. Every component must have explicitly typed properties and allowed variants. Do not permit arbitrary component imports. Do not permit arbitrary CSS or script injection. --- # 5. GENERATION ENGINE & RESOURCE CONTROL Enforce strict generation limits. ## Model Call Budget Maximum model calls per generation request: **3**. Count every generation, repair, continuation, and retry attempt. Do not allow subagents or hidden model calls to bypass this limit. Recommended execution: - Call 1: Generate initial PageLayoutAST. - Call 2: Repair invalid output OR continue truncated output. - Call 3: Final repair or continuation when necessary. Do not call all three automatically. Stop immediately when a valid AST is obtained. ## Token Budget Calculate the generation budget on the server. Use: `available_output_tokens = min(provider_limit, remaining_user_quota - estimated_input_tokens - safety_reserve)` Requirements: - Read current user quota from PostgreSQL. - Do not trust quota values supplied by browsers. - Reject generation when available output tokens are zero or negative. - Apply an atomic quota reservation before calling the model. - Reconcile reserved tokens with actual usage after generation. - Release unused reservations. - Prevent concurrent requests from overspending the quota. - Use provider-reported token usage whenever available. - Record estimated usage separately when exact usage is unavailable. Do not silently allow unlimited generation. ## Deterministic Error Handling Implement normalized error codes: - `QUOTA_EXCEEDED` - `GENERATION_CALL_LIMIT` - `MODEL_RESOURCE_EXHAUSTED` - `OUTPUT_TRUNCATED` - `AST_VALIDATION_FAILED` - `MODEL_UNAVAILABLE` - `GENERATION_CANCELLED` - `GENERATION_TIMEOUT` ### Resource Exhaustion When the provider returns a documented resource exhaustion error: 1. Stop generation. 2. Do not launch an uncontrolled retry loop. 3. Preserve the previously validated project state. 4. Release unused quota reservations. 5. Record the failed attempt. 6. Return a structured SSE error event. ### Maximum Token Stop Reason When generation stops because of output token limits: 1. Never treat incomplete JSON as a valid AST. 2. Attempt continuation only if sufficient quota and model calls remain. 3. Validate the complete resulting AST. 4. If the continuation fails, return `OUTPUT_TRUNCATED`. 5. Do not save incomplete AST as a valid project version. ### Validation Failure If the generated AST is invalid: 1. Record validation errors. 2. Attempt a constrained repair within the remaining call budget. 3. Validate the repaired response again. 4. Stop after the maximum allowed calls. All generation operations must be cancellable. --- # 6. SSE STREAMING Implement streaming in FastAPI using native asynchronous streaming. Next.js must proxy the SSE stream to the browser. Use structured events: - `generation_started` - `generation_progress` - `model_call_started` - `ast_delta` - `ast_validated` - `generation_completed` - `generation_error` - `generation_cancelled` Important behavior: - Stream incremental AST text for live inspection. - Do not render incomplete or unvalidated JSON as executable content. - Render the preview only from a complete, validated AST. - Support browser cancellation. - Propagate AbortSignal to the Python service. - Handle disconnected clients. - Prevent duplicate generation submissions. - Ensure correct SSE headers and disable intermediary buffering where possible. Do not simulate streaming with artificial delays. --- # 7. SANDBOXED PREVIEW ARCHITECTURE This is a mandatory security boundary. All generated layouts must render inside an isolated iframe. Use: ```html <iframe sandbox="allow-scripts"></iframe> ``` Never add: - `allow-same-origin` - `allow-top-navigation` - `allow-popups` - `allow-forms` ## Rendering Rules Build a deterministic renderer using the allowlisted component registry. Never execute AI-generated JavaScript. Do not use: - eval(). - new Function(). - Dynamic script imports. - Arbitrary HTML execution. - Arbitrary React source evaluation. - Unsanitized innerHTML. Generate trusted preview HTML from validated AST data. Apply an iframe Content Security Policy that blocks unnecessary network access, external scripts, forms, plugins, and nested frames. Permit only the resources strictly required for the preview. ## postMessage Protocol All host-preview communication must use `postMessage`. Implement a strict message contract. Use Zod validation for every incoming and outgoing message. Validate: - Message type. - Protocol version. - Session nonce. - Payload shape. - Payload size. - Allowed operations. Check: `event.source === iframe.contentWindow` Also validate the expected session nonce. Because the sandbox has an opaque origin without `allow-same-origin`, account for opaque-origin messaging safely. Do not rely on origin checks alone. For messages sent to an opaque-origin iframe, use the required target-origin behavior and compensate with strict source, session, and schema validation. Support: - `PREVIEW_READY` - `UPDATE_AST` - `UPDATE_TEXT` - `UPDATE_COLOR` - `REQUEST_RESIZE` - `PREVIEW_ERROR` Reject all unknown message types. Do not permit the iframe to access host cookies, local storage, authentication tokens, database APIs, or privileged application functions. --- # 8. INSPECTOR & REAL-TIME EDITING Build an inspector that allows users to select supported components and edit their properties. Required capabilities: ### Text Editing - Heading text. - Paragraph content. - Button labels. - Badge labels. - Input placeholders. ### Color Editing - Page background. - Component background. - Text color. - Border color. - Button color. Use predefined design tokens and validated color values. Update the client-side AST immediately. Send validated AST updates to the preview through postMessage. Implement: - Instant preview updates. - Undo/redo for property changes. - Dirty state indicator. - Debounced autosave. - Save error feedback. - Project version tracking. Do not invoke the AI model for ordinary inspector edits. --- # 9. APPLICATION SCREENS ## A. Login Create a clean authentication experience. Features: - Google sign-in. - Session management. - Authentication errors. - Loading states. - Secure logout. ## B. Account Connection Create a dedicated Antigravity integration screen. Show: - Connection status. - Supported authentication method. - Account/project metadata. - Model configuration. - Connection test. - Disconnect action. - Clear instructions for unsupported authentication modes. Never display stored API secrets after they have been saved. ## C. Project Dashboard Display: - Total projects. - Recent projects. - Remaining token quota. - Tokens consumed. - Generation limits. - Account connection status. Include: - Search. - Create project. - Delete project with confirmation. - Empty state. - Loading state. - Error state. ## D. Generation Workspace Main editor layout: - Left: Prompt and generation controls. - Center: Sandboxed live preview. - Right: Component inspector. - Bottom or collapsible panel: AST stream and generation logs. Support: - Prompt submission. - Streaming progress. - Model call counter. - Token budget indicator. - Cancel generation. - Validation feedback. - Preview refresh. - Responsive layout. ## E. Export Allow downloading generated projects as ZIP. Export must contain a clean Next.js App Router project. Include: - `package.json` - `tsconfig.json` - Tailwind CSS v4 configuration. - `app/layout.tsx` - `app/page.tsx` - Reusable components. - Typed props. - Design tokens. - README. - `.env.example` where applicable. Generate React components deterministically from validated AST. Never export: - Model credentials. - User authentication tokens. - Server secrets. - Internal service credentials. - Application database connection strings. The ZIP must be independently usable after installing its dependencies. --- # 10. DATABASE DESIGN Use PostgreSQL with Drizzle ORM. Required application tables: ### users Fields: - id - email - name - avatar_url - token_quota - tokens_consumed - tokens_reserved - created_at - updated_at ### projects Fields: - id - user_id - name - description - prompt - layout_ast (JSONB) - status - created_at - updated_at ### user_antigravity_accounts Fields: - id - user_id - provider - authentication_method - account_metadata - encrypted_credential_reference - connection_status - last_verified

Make My PRD

Design by The Resonance | Powered by GPC – The AI Transformation Company