Skip to content

About

Structured context workspace for creative

Topics

Resources

Contributing

Stars

5 stars

Watchers

0 watching

Forks

Latest commit

 

History

632 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Cinematic Framework

Cinematic Canvas is the generative AI workspace for storytelling. The AI-assisted workspace treats story elements as structured primitives, giving you total control over cinematic worlds with character and narrative continuity.

Actively under development. UI and workflows may change.

Current Development Version

Current Version

Previous Version

Preview

Overview

Cinematic Canvas leverages Google's Vertex AI Gemini models and LangGraph to orchestrate a multi-agent workflow:

  • Analyzes audio tracks to extract musical structure, and compose narrative timing.
  • Generates detailed storyboards with scenes, characters, locations, and cinematography.
  • Maintains visual continuity across scenes using reference images and persistent state checkpoints.
  • Generated Asset Versioning tracks all and best assets.
  • Produces cinematic videos with intentional shot composition, lighting, and camera movements.
  • Evaluation Guidelines improve the generation process by learning from quality-check feedback.
  • Persisted State using PostgreSQL and database-persisted graph checkpoints.
  • Decentralized Store Architecture: High-performance client-side state management using specialized Zustand stores (useProjectStore, useAssetStore, usePipelineStore, etc.).

What's New

  • Node-Based Canvas UI: Replaced the static dashboard with a fully interactive React Flow DAG canvas interface for world building.
  • Scene-as-Code (SAC) Ledger: Introduced a Git-backed versioning system for world and project states, enabling true collaborative branching and pull requests.
  • Generative Job Batching: 3x throughput increase, 50% cost reduction
  • Human-in-the-Loop Approval Gates: Quality control before expensive rendering
  • Production Metrics Dashboard: Real-time quality and performance tracking
  • Robust Auth & Team Management: Multi-tenant team support with secure workspace isolation

Core Features

Feature Description
Multi-Tenant Teams Built-in support for team-based workspaces, allowing users to join or create teams and isolate their projects and worlds.
Secure Authentication Integrated authentication flow ensuring that only authorized team members can access and modify projects and worlds.
Node-Based Interface An interactive, DAG-style canvas using React Flow to visually manage world lore, assets, and pipeline execution flow.
Scene-as-Code (SAC) Ledger A Git-backed version control system for project lore and assets. Allows branching, forks, and structured PR-based collaboration.
Audio-Driven and/or Prompt-Based Generate videos or music videos from audio files (with automatic scene timing) and/or from creative prompts.
Multi-Agent Architecture Specialized agents for audio analysis, storyboard composition, character/location management, scene generation, and quality control.
Visual Continuity Maintains character appearance and location consistency using reference images and pre-generated start/end frames for each scene.
Role-Based Prompt Architecture Film production crew roles (Director, Cinematographer, Gaffer, Script Supervisor, etc.) compose prompts for specialized, high-quality output.
Cinematic Quality Professional shot types, camera movements, lighting, and transitions
Scene Regeneration & Intervention Allows users to selectively regenerate specific scenes or individual frames (GENERATE_SCENE_FRAMES) without restarting the entire pipeline. It also supports interactive correction of LLM failures via RESOLVE_INTERVENTION.
Self-Improving Generation A QualityCheckAgent evaluates generated scenes and provides feedback. This feedback is used to refine a set of "Generation Rules" that guide subsequent scene generations, improving quality and consistency over time.
Learning Metrics The framework tracks the number of attempts and quality scores for each scene, calculating trend lines to provide real-time feedback on whether the system is "learning" (i.e., requiring fewer attempts to generate high-quality scenes).
Distributed Architecture & Resilience Supports safe horizontal scaling across multiple worker replicas. Workflow state is persisted in PostgreSQL via LangGraph checkpointers, allowing for robust resumption and enabling command-driven operations like START/STOP/REGENERATE via Pub/Sub commands. Graceful cancellation is supported via AbortSignal propagation, allowing pipelines to safely interrupt long-running LLM and API calls.
Comprehensive Schemas Type-safe data structures using Zod for all workflow stages, defined in src/shared/db/schema.ts. The system implements a strict Project schema and runtime validation, ensuring application logic always operates on fully validated data.
Asset Versioning Tracks all generated assets and identifies the best versions based on quality metrics.
Human-in-the-Loop Retry Logic Supports human-in-the-loop retry logic for failed steps.
Enhanced Observability Enhanced observability with detailed logging and metrics tracking.

Architecture

The framework uses a LangGraph state machine running across one or more horizontally scalable pipeline-worker services (using Node 22). Execution is controlled via commands published to a Pub/Sub topic (video-commands). The worker service handles project concurrency via mechanisms like checkpointers and distributed locking. State changes are broadcast via another Pub/Sub topic (video-events), which the API server relays to connected clients via SSE.

graph TD
    A[Client/API] -->|Publish Command START_STOP_RETRY| B[Pub/Sub video-commands]
    B --> C[Pipeline Worker pipeline-worker]
    C -->|Check Save State| D[PostgreSQL Checkpoint]
    C -->|Execute Graph| E[LangGraph Workflow]
    C -->|Publish State Update| F[Pub/Sub video-events]
    F --> G[API Server]
    G -->|SSE Stream| A

    subgraph Workflow_Execution
        E
        D
    end
Loading

Key Components & Agents

  1. MediaProcessingAgent: Analyzes audio files to extract musical structure, timing, and mood, setting initial scene parameters.
  2. CompositionalAgent: Expands creative prompts and generates comprehensive storyboards.
  3. ContinuityManagerAgent: Manages character/location reference images and orchestrates Meta-Prompting. It uses a high-reasoning LLM to synthesize detailed department specifications into cohesive, high-quality video generation prompts, ensuring visual coherence. It also supports idempotent workflow by checking GCS for pre-generated assets.
  4. SceneGeneratorAgent: Generates individual video clips, now relying on pre-generated start/end frames from the persistent state for continuity.
  5. QualityCheckAgent: Evaluates generated scenes for quality and consistency, feeding back into the prompt/rule refinement loop.
  6. Prompt CorrectionInstruction: Guides the process for refining prompts based on quality feedback.
  7. Generation Rules Presets: Proactive domain-specific rules that can be automatically added to guide generation quality.
  8. Pipeline Worker (src/pipeline/): A dedicated, horizontally scalable service running the LangGraph instance using Node.js v20+. It handles command execution (START_PIPELINE, STOP_PIPELINE, GENERATE_SCENE_VIDEO, GENERATE_SCENE_FRAMES, RESOLVE_INTERVENTION), and uses the PostgresCheckpointer for reliable state management. (Distributed locking has been temporarily disabled). It intercepts console logs and publishes relevant info to the client as real-time LOG events via Pub/Sub.
  9. API Server (src/server/): The stateless API server acts as a proxy, publishing client requests as Pub/Sub commands and streaming Pub/Sub events back to connected clients via a single, shared, persistent SSE subscription to reduce Pub/Sub resource usage. It features error handling and acknowledgement for Pub/Sub messages to ensure reliable event delivery.

Prerequisites

  • Node.js (v22 or higher recommended)
  • Docker and Docker Compose (for local development environment)
  • Google Cloud Project with:
    • Vertex AI API enabled
    • Google Cloud Storage bucket created
    • Service account with appropriate permissions

Installation (Local Development with Docker)

The local setup now requires running Docker Compose to manage the background services:

# 1. Install dependencies for API/Worker/Client
npm install

# 2. Start necessary infrastructure components (Pub/Sub Emulator, API Server, Client)
docker-compose up --build -d

# Note: The postgres-db service is started automatically by docker-compose if needed by the worker, but is not externally exposed or required by the API server anymore.

Local Development (Without Docker)

For faster iteration and debugging, you can run the services directly using tsx outside of Docker. You will need to start the dependency containers first.

# 1. Start the dependent infrastructure (Postgres and Pub/Sub Emulator)
# Ensure you use the appropriate docker-compose file if needed, or run the services separately.
# Example: docker-compose up -d pubsub-emulator postgres-db

# 2. Start the Client (e.g., in VS Code integrated terminal)
npm run dev

# 3. Start the Server (The API layer)
npm run start:server

# 4. Start the Worker (The LangGraph execution environment)
npm run start:worker

# Alternatively, use the new VS Code Debug Configurations:
# - Launch Worker
# - Launch Server
# - Debug Client
# - Debug Server (Hot Reload)
# - Debug Worker (Hot Reload)
# - Debug Full-Stack (launches all 3)
# - Debug Full-Stack (Hot Reload) (launches Server, Worker, Client with hot reload)

Configuration

Environment Variables

Update .env (or environment variables in deployment). The API Server now explicitly loads environment variables using dotenv upon startup. Note that GOOGLE_CLOUD_PROJECT, GOOGLE_CLOUD_BUCKET, and POSTGRES_URL are required for full operation.

# Google Cloud Platform Configuration
GOOGLE_CLOUD_PROJECT="your-gcp-project-id"
GOOGLE_CLOUD_BUCKET="your-gcp-bucket-name"
PUBSUB_EMULATOR_PROJECT_ID="test-project" # Required for Pub/Sub operations
PUBSUB_EMULATOR_HOST="" # Set this to 'pubsub-emulator:8085' when running in Docker, or 'localhost:8085' when running locally outside Docker. Leave blank if using actual Pub/Sub service.
# GOOGLE_APPLICATION_CREDENTIALS is often omitted when using ADC or Workload Identity
# POSTGRES_URL must point to the database accessible by the pipeline worker
POSTGRES_URL="postgres://postgres:example@postgres-db:5432/cinematiccanvas"

# LLM Configuration
LLM_TEXT_PROVIDER="google" # Only supports google
TEXT_MODEL_NAME="gemini-2.5-pro" # Updated default model
IMAGE_MODEL_NAME="gemini-2.5-flash-image"
VIDEO_MODEL_NAME="veo-2.0-generate-exp"

.envrc file enables environment loading using direnv when entering the project directory.

  • GCS and PubSub Management: Idempotent resource management; the system verifies and ensures required topics, subscriptions, and buckets exist before takeoff.
  • Robust Initialization: The API and Worker services feature granular, step-by-step initialization blocks with detailed logging and immediate process exit on critical failure.

Prerequisites

Pipeline execution is initiated via API calls that publish commands to Pub/Sub, allowing the decoupled worker service to pick them up. The API server also provides endpoints for querying current state and available projects, leveraging direct GCS access for the latter.

Starting a Pipeline

Use POST to /api/video/start. This publishes a START_PIPELINE command.

curl -X POST http://localhost:8000/api/video/start \
-H "Content-Type: application/json" \
-d '{
  "projectId": "new-video-id-12345",
  "audioUrl": "gs://my-bucket/audio/song.mp3",
  "enhancedPrompt": "A 1980s VHS-style music video..."
}'

Stopping a Pipeline

Use POST to /api/video/stop. This publishes a STOP_PIPELINE command, causing the worker to save its current state and terminate processing for that run ID.

In local CLI executions (e.g., running src/pipeline/execute-workflow.ts directly), the workflow now supports graceful interruption via SIGINT (Ctrl+C). This triggers an AbortController signal, allowing LLM calls to be cancelled mid-flight, ensuring a cleaner shutdown and checkpointing if possible.

curl -X POST http://localhost:8000/api/video/stop \
-H "Content-Type: application/json" \
-d '{
  "projectId": "new-video-id-12345"
}'

Listing Available Projects

Use GET to /api/projects. This queries the configured GCS bucket directly to list existing project directories (prefixes). The API now returns a JSON object { "projects": [...] } instead of an array. The listing now excludes any project directory named 'audio' to prevent accessing raw audio assets.

Viewing Live State Updates (SSE)

Client applications connect to /api/events/:projectId to receive real-time state updates via SSE, which relies on the worker publishing to the video-events topic.

Project Structure

cinematic-canvas/
├── .keeper/                          # Agent task tracking
├── audio/                            # Local audio files for testing
├── src/client/                           # Frontend application (React/Vite)
│   ├── src/store/                        # Decentralized Zustand stores
│   │   ├── useProjectStore.ts            # Project, Scenes, Characters, Locations
│   │   ├── useAssetStore.ts              # Centralized asset registry & versioning
│   │   ├── usePipelineStore.ts           # Execution state & command queue
│   │   ├── useCanvasUIStore.ts           # Viewport, selection, and UI state
│   │   ├── useNodeStore.ts               # Canvas graph/DAG layout
│   │   └── useWorldStore.ts              # Global lore & world-building state
│   ├── src/services/
│   │   └── hybridNodeStorage.ts          # Dual-tier layout persistence (IndexedDB + Supabase)
│   ├── src/store/middleware/
│   │   └── canvasIndexedDBStorage.ts     # Debounced layout persistence with flush support
├── docs/                             # Documentation files
├── src/pipeline/                 # Dedicated service for running LangGraph/Checkpointer (Uses Node 20, runs via 'node index.ts')
│   ├── Dockerfile
│   └── index.ts                      # Main worker logic subscribing to Pub/Sub commands
├── src/pipeline/                         # Core workflow agents and logic
│   ├── agents/                       # Agent implementations
│   ├── lm/                          # LLM provider abstractions
│   ├── checkpointer-manager.ts       # Abstraction for Postgres checkpointer (LangGraph state serialization change)
│   ├── lib/                          # Utility libraries
│   ├── prompts/                      # System prompts for agents
│   ├── index.ts                      # Core graph definition (Uses import.meta.main)
│   └── types.ts
├── src/server/                           # Stateless API server
│   ├── index.ts                      # Server entry point and SSE implementation
│   └── routes.ts                     # API routing and Pub/Sub command publishing
├── src/shared/                           # Shared types/schemas used across client, server, and worker
│   ├── types/pipeline.types.ts             # Project and domain types
│   ├── pubsub-types.ts               # Command/Event structures (e.g., START_PIPELINE)
│   └── schema.ts
├── .env.example
├── package.json                      # Dependencies and scripts
├── docker-compose.yml                # Local development orchestration (Postgres service removed)
├── Dockerfile.api                    # Dockerfile for API/Server (Uses Node 20)
└── ...

Dependencies

Core Dependencies (Updated)

  • @google-cloud/pubsub (^5.2.0): For command/event communication between services.
  • @langchain/langgraph-checkpoint-postgres (^1.0.0): For persistent state management, handling LangGraph Checkpoint objects directly.
  • pg (^8.12.0): PostgreSQL client library used by the checkpointer.
  • uuid (^13.0.0): Used by the API server for unique SSE subscription IDs.

Development Dependencies

(No major changes observed in dev dependencies relevant to this file, retaining existing list below for completeness)

  • typescript (^5.9.3): TypeScript compiler
  • vitest (^4.0.14): Testing framework
  • @vitest/coverage-v8 (^4.0.14): Code coverage

Environment Variables (Docker Compose Context)

When running locally via docker-compose.yml, the following variables are implicitly set or need external definition for services connecting to external GCP resources (if not using the emulator):

  • PUBSUB_EMULATOR_HOST: Points to the local Pub/Sub emulator container.
  • POSTGRES_URL: Connection string for the service database.
  • GOOGLE_CLOUD_PROJECT, GOOGLE_CLOUD_BUCKET: GCP resource identifiers.
  • GOOGLE_CLOUD_PROJECT: Project ID for Pub/Sub operations (used by worker/server if not using emulator host).

Testing

# Run all tests
npm test

# Run tests in watch mode
npm run test:watch

## Deployment

### Automated Deploys to Netlify

The website and documentation are automatically deployed to Netlify.

- **Trigger**: Deploys are triggered only when changes are detected in the `website/` or `docs/` directories.
- **Config**: Managed via [website/netlify.toml](file:///Users/andresb/Projects/cinematic-canvas/website/netlify.toml).
- **Process**: The build command runs `npm run build` in the `website/` directory, which also ensures updated documentation is symlinked via `scripts/link-docs.js`.

To manually check if a build will be ignored locally:
```bash
# In the website directory
git diff --quiet $CACHED_COMMIT_REF $COMMIT_REF . ../docs

Security: Google Cloud Credentials & Data Access

State Persistence: All workflow progress, scenes, characters, and metrics are now persisted in a PostgreSQL database via LangGraph checkpoints (thread_id corresponds to projectId). The API server no longer directly interacts with the DB for state retrieval, relying on worker-published events or dedicated state API calls.

(Rest of Security section regarding GCP keys remains largely unchanged, referencing correct environment variables.)

Troubleshooting

Common Issues (Updated)

  • Issue: "Failed to connect to database"
    • Solution: Ensure the pipeline-worker service can access PostgreSQL. If running locally, check the POSTGRES_URL in .env or passed to the worker environment. The postgres-db service might need manual verification if not running via compose.
  • Issue: "Pipeline did not resume / Ran from beginning"
    • Solution: Verify that the projectId used matches the thread_id saved in the database, and that the pipeline-worker service is correctly deserializing checkpoint state (channel_values).
  • Issue: "Video generation timed out"
    • Solution: Increase timeout settings configured within the pipeline agents or pipeline worker environment.
  • Issue: "Safety filter triggered"
    • Solution: The framework automatically sanitizes prompts. Review safety error codes in pipeline agents.
  • Issue: "FFmpeg errors"
    • Solution: Verify FFmpeg is installed and accessible in the pipeline-worker container's PATH.

Canvas Layout Persistence

Node positions and layout metadata are stored in a dual-tier hybrid storage system:

  • IndexedDB (local, instant): Debounced writes on every layout change. Flushed on beforeunload and component unmount to prevent data loss.
  • Supabase (cloud, optional): Serialized queue ensures in-order writes. Enable with VITE_ENABLE_CLOUD_NODE_SYNC=true.

Layout Recall on Load

When a project or world canvas loads, stored layouts are fetched from hybrid storage and applied:

  1. loadPersistedLayouts() builds a Map<entityId, layoutData> from IndexedDB (merged with Supabase if cloud sync is enabled)
  2. Entity nodes are spawned using stored positions when available, falling back to grid-computed positions for new entities
  3. Stored metadata (collapsed state, pipeline selection, version) is applied after spawning
  4. Failed cloud syncs are retried via forceSyncUnsynced() on canvas mount

Key Files

File Purpose
hybridNodeStorage.ts Dual-tier IndexedDB + Supabase adapter with OCC conflict handling
canvasIndexedDBStorage.ts Debounced persist with flushPendingPersist() for unmount safety
useCanvasPipelineSync.ts Project canvas layout recall and entity spawning
WorldBuilderCanvas.tsx World canvas layout recall with stale-fetch guards

Performance Considerations

  • Scene generation: ~2-5 minutes per scene (API dependent)
  • Total workflow time: Highly dependent on retry counts, as failures are now managed via command/checkpointing, not just internal retries. A stalled pipeline can be explicitly stopped via API command.

Limitations

  • Video durations must be exactly 4, 6, or 8 seconds (Vertex AI constraint).
  • Maximum 15-minute timeout per scene generation.
  • Requires significant GCP quota for video generation API.

Contributing

Contributions are welcome! Please ensure:

  • All tests pass (npm test)
  • Code coverage remains above 90% (npm run coverage)
  • TypeScript strict mode compliance
  • New services (e.g., pipeline-worker) are properly containerized (Node 20+) and configured in docker-compose.yml.

License

ISC

Support

For issues and questions:

  • Review Docker Compose logs (docker-compose logs).
  • Check PostgreSQL database for state inconsistencies.
  • Review Pub/Sub topic messages if commands are not reaching the worker.

About

Structured context workspace for creative

Topics

Resources

Contributing

Stars

5 stars

Watchers

0 watching

Forks

Packages

Contributors

Languages