graph.ts 5.38 KB
import { StateGraph, START, END } from '@langchain/langgraph';
import { GraphNode, ValidationMode } from './types/graph-types';
import { GraphStateAnnotation } from './state';
import { initialProject } from './nodes/initial';
import { generateProtocol } from './nodes/process';
import { runValidation } from './nodes/validation';
import { parseFigmaUrl } from './utils/url-parser';
import { workspaceManager } from './utils/workspace';
import { generateCode } from './nodes/code';
import { initializeSqliteSaver, promptCheckpointChoice, clearThreadCheckpoint } from './utils/checkpoint';
import { logger } from './utils/logger';
import { setRuntimeConfig } from './utils/config';

/**
 * Optional parameters for the design-to-code run, used by the service mode
 * (`coderio serve`) to drive generation non-interactively.
 */
export interface Design2CodeOptions {
    /**
     * Custom root directory for the generated project. Maps to the `rootPath`
     * argument of `workspaceManager.initWorkspace`. Defaults to the current
     * working directory when omitted (CLI behavior).
     */
    outputDir?: string;
    /**
     * Custom generated app folder name (defaults to `my-app`).
     */
    appName?: string;
    /**
     * Explicit resume decision. When provided (true/false) the interactive
     * checkpoint prompt is skipped — required for non-interactive service mode.
     * When omitted, the CLI falls back to `promptCheckpointChoice`.
     */
    resume?: boolean;
    /**
     * Runtime model + Figma configuration injected by the orchestration backend
     * (apps/server). When provided, it overrides `~/.coderio/config.yaml` for
     * this run, so the backend owns credentials instead of a global file.
     * `figmaToken` maps to the Figma personal access token.
     */
    modelConfig?: {
        provider?: string;
        model?: string;
        baseUrl?: string;
        apiKey?: string;
        figmaToken?: string;
    };
}

export async function design2code(url: string, mode?: ValidationMode, options?: Design2CodeOptions): Promise<void> {
    const opts = options ?? {};

    // Apply backend-injected runtime config (overrides ~/.coderio/config.yaml).
    if (opts.modelConfig) {
        const mc = opts.modelConfig;
        const modelOverride: Record<string, string> = {};
        if (mc.provider !== undefined) modelOverride.provider = mc.provider;
        if (mc.model !== undefined) modelOverride.model = mc.model;
        if (mc.baseUrl !== undefined) modelOverride.baseUrl = mc.baseUrl;
        if (mc.apiKey !== undefined) modelOverride.apiKey = mc.apiKey;
        setRuntimeConfig({
            model: modelOverride,
            figma: mc.figmaToken !== undefined ? { token: mc.figmaToken } : undefined,
        });
    }

    // Reset cached workspace so a fresh run (especially in service mode, where
    // multiple jobs may run in the same process) does not reuse a stale path.
    workspaceManager.reset();

    const urlInfo = parseFigmaUrl(url);
    const threadId = urlInfo.projectName!;
    const workspace = workspaceManager.initWorkspace(threadId, opts.outputDir, opts.appName);

    // Initialize SqliteSaver with the database path
    const checkpointer = initializeSqliteSaver(workspace.db);

    // Resolve resume decision: explicit override (service mode) or interactive prompt (CLI).
    const resume: boolean | undefined =
        typeof opts.resume === 'boolean' ? opts.resume : await promptCheckpointChoice(checkpointer, threadId);

    logger.printInfoLog(`Starting design-to-code process for: ${urlInfo.projectName}`);

    // If not resuming, delete workspace and reinitialize checkpointer
    if (resume !== true) {
        // Preserve only the database file to avoid EBUSY error on Windows (SQLite lock)
        workspaceManager.deleteWorkspace(workspace, [
            'checkpoint/coderio-cli.db',
            'checkpoint/coderio-cli.db-shm',
            'checkpoint/coderio-cli.db-wal',
        ]);
        logger.printInfoLog('Starting fresh...');

        // Clear existing checkpoints for this thread instead of deleting the file
        await clearThreadCheckpoint(checkpointer, threadId);
    } else {
        logger.printInfoLog('Resuming from cache...');
    }

    // Compile graph with checkpointer (after potential reinitialization)
    const graph = new StateGraph(GraphStateAnnotation)
        .addNode(GraphNode.INITIAL, initialProject)
        .addNode(GraphNode.PROCESS, generateProtocol)
        .addNode(GraphNode.CODE, generateCode)
        .addNode(GraphNode.VALIDATION, runValidation)
        .addEdge(START, GraphNode.INITIAL)
        .addEdge(GraphNode.INITIAL, GraphNode.PROCESS)
        .addEdge(GraphNode.PROCESS, GraphNode.CODE)
        .addEdge(GraphNode.CODE, GraphNode.VALIDATION)
        .addEdge(GraphNode.VALIDATION, END)
        .compile({ checkpointer });

    const config = { configurable: { thread_id: threadId } };

    // If resuming from checkpoint, pass null to let LangGraph resume from saved state
    // Otherwise, pass initial state to start fresh
    const validationMode: ValidationMode = mode ?? ValidationMode.Full;
    const state =
        resume === true
            ? null
            : {
                  messages: [],
                  urlInfo,
                  workspace,
                  config: {
                      validationMode,
                  },
              };
    await graph.invoke(state, config);

    logger.printSuccessLog('Design-to-code process completed!');
}