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.
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.
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.
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.
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.
Team & resourcing - Small team - 2 full-stack engineers, 1 product designer, part-time PM, and shared DevOps/security support
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.
# 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
Design by The Resonance | Powered by GPC – The AI Transformation Company