vc-runtime 0.1.0

Runtime backend for Visual Compiler
Documentation
use crate::renderer::{ImageRenderer, RenderOutput, RenderParams, RendererKind, OUTPUT_FILENAME};
use crate::services::comfy::{
    download_and_hash, BindingKey, ComfyClient, ValidatedWorkflowTemplate,
};
use crate::services::runtime::RuntimeBindings;
use crate::services::{WorkflowError, WorkflowInjector};
use anyhow::Result;
use serde_json::json;
use std::path::Path;
use std::sync::Arc;
use std::time::Instant;

/// ComfyUI renderer using the M2.6 validated workflow pipeline.
///
/// # Invariants
/// - `template` is already validated and immutable.
/// - All workflow-specific knowledge (node IDs, input names) lives in metadata.
/// - Renderer is stateless per request.
pub struct ComfyUIRenderer {
    template: Arc<ValidatedWorkflowTemplate>,
    client: Arc<ComfyClient>,
    runtime_handle: tokio::runtime::Handle,
}

impl ComfyUIRenderer {
    /// Create a new renderer with a validated template.
    ///
    /// The template is loaded and validated once at construction time.
    pub fn new(
        client: ComfyClient,
        template: ValidatedWorkflowTemplate,
        runtime_handle: tokio::runtime::Handle,
    ) -> Self {
        Self { template: Arc::new(template), client: Arc::new(client), runtime_handle }
    }

    /// Get the image output binding from the validated metadata.
    fn image_output_binding(&self) -> Result<&str, WorkflowError> {
        self.template.metadata().outputs.get("image").map(|b| b.node.as_str()).ok_or_else(|| {
            WorkflowError::Validation {
                reason: "Missing 'image' output binding in workflow metadata".to_string(),
            }
        })
    }
}

impl ImageRenderer for ComfyUIRenderer {
    fn render(
        &self,
        prompt: &str,
        negative_prompt: &str,
        seed: u64,
        output_dir: &Path,
        params: &RenderParams,
    ) -> Result<RenderOutput> {
        let start = Instant::now();

        // Build runtime bindings from render parameters.
        // These are the only values the renderer knows about.
        let mut bindings = RuntimeBindings::new();
        bindings.insert(BindingKey::new("positive_prompt"), json!(prompt));
        bindings.insert(BindingKey::new("negative_prompt"), json!(negative_prompt));
        bindings.insert(BindingKey::new("seed"), json!(seed));
        bindings.insert(BindingKey::new("width"), json!(params.width));
        bindings.insert(BindingKey::new("height"), json!(params.height));
        bindings.insert(BindingKey::new("steps"), json!(params.steps));
        bindings.insert(BindingKey::new("cfg"), json!(params.cfg));

        // Delegate injection to the injector.
        // The injector clones the workflow body once; the template remains immutable.
        let payload = WorkflowInjector::inject(&self.template, &bindings)?;

        let (bytes, hash) = self.runtime_handle.block_on(async {
            // Submit the clean payload (no _vc metadata) to ComfyUI.
            let prompt_id = self.client.submit_prompt(&payload).await?;
            let history = self.client.wait_for_completion(&prompt_id).await?;

            // Look up the image output node via metadata, not hardcoded IDs.
            let output_node_id = self.image_output_binding().map_err(anyhow::Error::msg)?;

            let outputs =
                history.outputs.as_ref().ok_or_else(|| anyhow::anyhow!("No outputs in history"))?;

            let image_output = outputs
                .get(output_node_id)
                .ok_or_else(|| anyhow::anyhow!("No output from image node"))?
                .images
                .first()
                .ok_or_else(|| anyhow::anyhow!("No image in output"))?
                .clone();

            download_and_hash(&self.client, &image_output).await
        })?;

        let image_path = output_dir.join(OUTPUT_FILENAME);
        std::fs::write(&image_path, &bytes)?;

        let duration_ms = start.elapsed().as_millis() as u64;

        Ok(RenderOutput {
            image_path,
            image_hash: hash,
            duration_ms,
            backend: RendererKind::Comfy,
            seed,
        })
    }
}