graph.ts
5.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
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!');
}