graph.ts 7.72 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, resetCheckpointDb } from './utils/checkpoint';
import { logger } from './utils/logger';
import { setRuntimeConfig } from './utils/config';
import { setProjectProfile } from './utils/project-profile';
import type { ProjectProfile } from './types/project-profile';

/**
 * 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;
    };
    /**
     * Project profile (the "画像" of the target project A) injected by the
     * orchestration backend. When present, the CODE node constrains generation
     * to the target project's components / tokens / utils / conventions so the
     * output matches the team's existing code rather than a generic scaffold.
     */
    projectProfile?: ProjectProfile | null;
    /**
     * Generation target chosen by the user on the workbench: where the code
     * should land (standalone / new-page / modify-slot). Recorded for a future
     * phase that rewrites into the real project; currently generation still
     * writes to the default workspace and this value is informational.
     */
    target?: {
        mode?: string;
        page?: string;
        slot?: string;
    } | null;
    /**
     * Whether the generated root component should fill its host container.
     * Defaults to `true` (embed-into-app-shell scenario). When `false`, the
     * root renders at the Figma frame's intrinsic width, centered, without
     * stretching to a wide viewport (useful for fixed-width standalone previews).
     */
    fillContainer?: boolean;
}

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,
        });
    }

    // Apply the target-project profile (画像) so the CODE node generates code
    // that matches the team's existing components / tokens / conventions.
    if (opts.projectProfile !== undefined) {
        setProjectProfile(opts.projectProfile);
    }

    // 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);
    const dbPath = workspace.db;

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

    // Resolve resume decision. Service mode always passes an explicit boolean
    // (resume:false), so no interactive prompt is needed there.
    let checkpointer: ReturnType<typeof initializeSqliteSaver>;
    let resume: boolean | undefined;
    if (typeof opts.resume === 'boolean') {
        resume = opts.resume;
    } else {
        // CLI: open a probe saver just to check for an existing checkpoint,
        // then close it (we reopen below once the decision is made).
        const probe = initializeSqliteSaver(dbPath);
        resume = await promptCheckpointChoice(probe, threadId);
        try {
            (probe as unknown as { db?: { close(): void } }).db?.close();
        } catch {
            /* ignore */
        }
    }

    if (resume !== true) {
        // Fresh start: open the checkpoint db, then reset its state in place
        // (flush + truncate the WAL and clear the checkpoint tables) so a
        // previous crashed / force-killed run can never leave a read-only WAL
        // behind. We reset via SQL rather than deleting the files because file
        // deletion is intercepted by the environment's `safe-delete` hook.
        checkpointer = initializeSqliteSaver(dbPath);
        resetCheckpointDb(checkpointer, dbPath);

        // Clean the rest of the workspace but keep the checkpoint database
        // files (they are reset in place above, no need to delete them).
        workspaceManager.deleteWorkspace(workspace, [
            'checkpoint/coderio-cli.db',
            'checkpoint/coderio-cli.db-shm',
            'checkpoint/coderio-cli.db-wal',
        ]);
        logger.printInfoLog('Starting fresh...');
    } else {
        checkpointer = initializeSqliteSaver(dbPath);
        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,
                  },
                  fillContainer: opts.fillContainer ?? true,
              };
    await graph.invoke(state, config);

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