pipeline.mjs 23.6 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 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
// ============================================================================
// Pipeline Module - 管线执行策略
// Strategy Pattern: 批量模式 / 流水线模式 / 单 URL 模式
// ============================================================================

import { spawn } from "node:child_process";
import fs from "node:fs";
import path from "node:path";

import { DEFAULT_CONFIG, PREVIEW_DIR } from "./config.mjs";
import { findTargetProject, listGeneratedFiles, listPreviewProjects } from "./preview-project.mjs";
import {
	getIsRunning,
	setCurrentProcess,
	setIsRunning,
	spawnAsync,
	stopCurrentProcess,
} from "./process-manager.mjs";
import { broadcast, emitConsole, emitStep, setPreviewUrl, startHeartbeat, stopHeartbeat } from "./sse.mjs";

/**
 * 创建带时间戳的日志函数
 */
function createLog() {
	return (msg) => {
		const timePrefix = new Date().toISOString().slice(11, 23);
		console.log(`[${timePrefix}][ai-direct-server] ${msg}`);
		broadcast("log", { message: msg, timestamp: Date.now() });
	};
}

/**
 * 运行管线(主入口)
 * @param {object} config - 配置对象
 * @param {string} repoRoot - 仓库根目录
 */
export async function runPipeline(config, repoRoot) {
	const log = createLog();

	if (getIsRunning()) {
		log("停止旧任务...");
		await stopCurrentProcess();
		setIsRunning(false);
		stopHeartbeat();
	}

	setIsRunning(true);
	startHeartbeat(getIsRunning);

	const env = buildEnv(config);
	const figmaUrls = parseFigmaUrls(config);
	const generateStrategy = config.generateStrategy || "batch";

	if (figmaUrls.length === 0) {
		broadcast("error", { message: "必须提供至少一个 Figma URL" });
		broadcast("status", { running: false, step: "error" });
		setIsRunning(false);
		stopHeartbeat();
		return;
	}

	if (figmaUrls.length > 1) {
		if (generateStrategy === "sequential") {
			await runPipelineSequential(config, figmaUrls, env, repoRoot, log);
		} else {
			await runPipelineBatch(config, figmaUrls, env, repoRoot, log);
		}
		return;
	}

	await runSingleUrl(config, figmaUrls[0], env, repoRoot, log);
}

/**
 * 构建环境变量
 */
function buildEnv(config) {
	return {
		...process.env,
		FIGMA_API_KEY: config.figmaApiKey || DEFAULT_CONFIG.figmaApiKey,
		AI_DIRECT_OPENAI_BASE_URL: config.aiBaseUrl || DEFAULT_CONFIG.aiBaseUrl,
		AI_DIRECT_OPENAI_API_KEY: config.aiApiKey || DEFAULT_CONFIG.aiApiKey,
		AI_DIRECT_OPENAI_MODEL: config.aiModel || DEFAULT_CONFIG.aiModel,
		AI_DIRECT_VISION_MODEL: config.visionModel || DEFAULT_CONFIG.visionModel,
	};
}

/**
 * 解析 Figma URL 列表
 */
function parseFigmaUrls(config) {
	if (Array.isArray(config.figmaUrls) && config.figmaUrls.length > 0) {
		return config.figmaUrls.map((u) => u.trim()).filter(Boolean);
	}
	if (config.figmaUrl?.trim()) {
		return [config.figmaUrl.trim()];
	}
	return [];
}

/**
 * 批量模式:合并所有 URL 一次生成
 */
async function runPipelineBatch(config, figmaUrls, env, repoRoot, log) {
	log(`批量模式: ${figmaUrls.length} 个 URL 合并一次生成`);

	const args = buildBatchArgs(config, figmaUrls, repoRoot);

	emitConsole(`\n═══════════════════════════════════════\n`, "system");
	emitConsole(`  Venus AI Direct Pipeline (批量模式)\n`, "system");
	emitConsole(`  ${figmaUrls.length} 个模块合并生成\n`, "system");
	emitConsole(`  ${new Date().toLocaleString()}\n`, "system");
	emitConsole(`═══════════════════════════════════════\n\n`, "system");

	log(`启动命令: node ${args.join(" ")}`);
	launchPipelineChild(args, env, config, repoRoot, log);
}

/**
 * 构建批量模式参数
 */
function buildBatchArgs(config, figmaUrls, repoRoot) {
	const args = ["scripts/ai-direct-execute.mjs"];
	const existingProject = config.existingProject?.trim() || null;

	if (existingProject) {
		const existingRoot = path.join(repoRoot, PREVIEW_DIR, existingProject);
		args.push("--project-dir", existingRoot, "--existing-preview-project-root", existingRoot);
	} else {
		let projectDir = config.projectDir?.trim() || null;
		if (!projectDir) {
			const previews = listPreviewProjects(repoRoot);
			projectDir = previews.length > 0 ? previews[0].path : ".";
		}
		args.push("--project-dir", projectDir);
	}

	args.push("--multi-figma-urls", figmaUrls.join(","));
	if (config.pageName?.trim()) args.push("--page-name", config.pageName.trim());
	if (config.refreshContext) args.push("--refresh-context");
	args.push(
		"--provider", "openai-compatible",
		"--model", config.aiModel || DEFAULT_CONFIG.aiModel,
		"--auto-repair",
		"--without-variables",
		"--preview-dir", PREVIEW_DIR
	);
	if (config.force !== false) args.push("--force");
	if (config.skipPreview) args.push("--skip-preview");
	if (config.skipValidate) args.push("--skip-validate");
	if (config.targetPlatform?.trim()) args.push("--target-platform", config.targetPlatform.trim());
	if (config.fallbackUi?.trim()) args.push("--fallback-ui", config.fallbackUi.trim());

	return args;
}

/**
 * 流水线模式:逐个 URL 独立生成
 */
async function runPipelineSequential(config, figmaUrls, env, repoRoot, log) {
	log(`流水线模式: ${figmaUrls.length} 个 URL,每 URL 一批`);

	emitConsole(`\n═══════════════════════════════════════\n`, "system");
	emitConsole(`  Venus AI Direct Pipeline (流水线)\n`, "system");
	emitConsole(`  ${figmaUrls.length} 个 URL,每 URL 一批\n`, "system");
	emitConsole(`  ${new Date().toLocaleString()}\n`, "system");
	emitConsole(`═══════════════════════════════════════\n\n`, "system");

	const tempBaseDir = path.join(repoRoot, PREVIEW_DIR, "_temp-sequential");
	fs.mkdirSync(tempBaseDir, { recursive: true });

	let projectRoot = null;
	let firstBatchDir = null;
	let batchIndex = 0;
	let anyContextFetched = false;
	const successfulBatches = [];

	for (let i = 0; i < figmaUrls.length; i++) {
		const url = figmaUrls[i];
		const label = `[${i + 1}/${figmaUrls.length}]`;
		const tempDir = path.join(tempBaseDir, `ctx-${i}`);
		fs.mkdirSync(tempDir, { recursive: true });

		emitConsole(`\n${label} 拉取 context: ${url}\n`, "system");
		log(`${label} 拉取 context: ${url}`);
		await new Promise((resolve) => setImmediate(resolve));

		let fetchedCtx = null;
		try {
			let pDir = config.projectDir?.trim() || null;
			if (!pDir) {
				const previews = listPreviewProjects(repoRoot);
				pDir = previews.length > 0 ? previews[0].path : ".";
			}

			const ctxArgs = [
				"--project-dir", path.resolve(pDir),
				"--figma-url", url,
				"--output-dir", tempDir,
			];
			if (config.withoutVariables) ctxArgs.push("--without-variables");
			if (config.targetPlatform?.trim()) ctxArgs.push("--target-platform", config.targetPlatform.trim());
			if (config.fallbackUi?.trim()) ctxArgs.push("--fallback-ui", config.fallbackUi.trim());

			const result = await spawnAsync(process.execPath, ["scripts/ai-direct-context.mjs", ...ctxArgs], {
				cwd: repoRoot,
				env,
				timeout: 60_000,
			}, (line, stream) => {
				broadcast("output", { stream, text: `[${label}] ${line}\n`, timestamp: Date.now() });
			});

			const tempFiles = fs.readdirSync(tempDir);
			const bundleFile = tempFiles.find((f) => f.endsWith(".ai-direct-context-bundle.json"));
			if (bundleFile) {
				const bundle = JSON.parse(fs.readFileSync(path.join(tempDir, bundleFile), "utf8"));
				const artifacts = bundle.artifacts || {};
				let contextLength = 0;
				let designContextText = "";

				if (artifacts.designContextFile && fs.existsSync(artifacts.designContextFile)) {
					designContextText = fs.readFileSync(artifacts.designContextFile, "utf8");
					contextLength = designContextText.length;
				}

				fetchedCtx = {
					url,
					tempDir,
					bundlePath: path.join(tempDir, bundleFile),
					designContextFile: artifacts.designContextFile,
					screenshotFile: artifacts.screenshotFile,
					designContextText,
					contextLength,
				};

				anyContextFetched = true;
				emitConsole(`${label} ✓ context: ${contextLength} 字符\n`, "system");
				log(`${label} ✓ context: ${contextLength} 字符`);
			} else {
				emitConsole(`${label} ✗ 未找到 bundle 文件\n`, "stderr");
				log(`${label} ✗ 未找到 bundle`);
			}
		} catch (error) {
			emitConsole(`${label} ✗ context 拉取失败: ${error.message}\n`, "stderr");
			log(`${label} ✗ 失败: ${error.message}`);
		}

		if (fetchedCtx) {
			const isLastUrl = i === figmaUrls.length - 1;
			const batch = { contexts: [fetchedCtx], totalSize: fetchedCtx.contextLength };
			emitConsole(`\n--- 批次 ${batchIndex + 1}: ${fetchedCtx.url} (${fetchedCtx.contextLength} 字符) ---\n`, "system");
			log(`批次 ${batchIndex + 1}: ${fetchedCtx.url} (${fetchedCtx.contextLength} 字符)`);

			const exitCode = await runBatchGeneration(batch, batchIndex, isLastUrl, config, repoRoot, env, log, {
				getProjectRoot: () => projectRoot,
				setProjectRoot: (v) => { projectRoot = v; },
				getFirstBatchDir: () => firstBatchDir,
				setFirstBatchDir: (v) => { firstBatchDir = v; },
			});

			if (exitCode === 0) {
				successfulBatches.push({
					url: fetchedCtx.url,
					batchIndex,
					urlIndex: i,
				});
			}
			batchIndex++;
		}
	}

	if (!anyContextFetched) {
		emitConsole(`\n✗ 没有成功拉取任何 context,流程终止\n`, "stderr");
		broadcast("error", { message: "没有成功拉取任何 Figma context" });
		broadcast("status", { running: false, step: "error" });
		setIsRunning(false);
		stopHeartbeat();
		return;
	}

	if (projectRoot && config.pageName && successfulBatches.length > 0) {
		const manifestPath = path.join(projectRoot, "src", "views", config.pageName, ".component-manifest.json");
		const manifest = {
			pageName: config.pageName,
			componentNames: config.componentNames || {},
			batches: successfulBatches.map((b) => ({
				url: b.url,
				urlIndex: b.urlIndex,
				batchIndex: b.batchIndex,
			})),
		};
		fs.mkdirSync(path.dirname(manifestPath), { recursive: true });
		fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2), "utf8");
		log(`✓ 组件 manifest 已创建: ${manifestPath}`);
		emitConsole(`\n✓ 成功批次: ${successfulBatches.length}/${figmaUrls.length}\n`, "system");
	}

	if (projectRoot) {
		const routerRegistered = await registerRoutesAndStartPreview(projectRoot, env, repoRoot, log);
		log(`路由注册和预览启动: ${routerRegistered}`);
	}

	emitConsole(`\n--- 流程完成 ---\n`, "system");
	log("流程完成");

	try {
		fs.rmSync(tempBaseDir, { recursive: true, force: true });
	} catch {
		// ignore
	}

	broadcast("status", { running: false, exitCode: 0, step: "complete" });
	const target = findTargetProject(repoRoot, config);
	if (target) {
		broadcast("files", { project: target.name, files: listGeneratedFiles(target.path) });
	}

	setIsRunning(false);
	stopHeartbeat();
}

/**
 * 运行单批次生成
 */
async function runBatchGeneration(batch, bIndex, isLastBatch, config, repoRoot, env, log, state) {
	const batchLabel = `[批次 ${bIndex + 1}]`;

	emitConsole(`\n${batchLabel} 开始生成 (${batch.contexts.length} 个模块, ${batch.totalSize} 字符)...\n`, "system");
	log(`${batchLabel} 开始生成`);

	const mergedContextParts = batch.contexts.map((c) =>
		`\n\n### === Module: ${c.url} ===\n\n${c.designContextText}`
	);
	const mergedContext = mergedContextParts.join("");

	const tempBaseDir = path.join(repoRoot, PREVIEW_DIR, "_temp-sequential");
	const batchTempDir = path.join(tempBaseDir, `batch-${bIndex}`);
	fs.mkdirSync(batchTempDir, { recursive: true });
	const mergedContextPath = path.join(batchTempDir, "merged-design-context.html");
	fs.writeFileSync(mergedContextPath, mergedContext, "utf8");

	const screenshotPaths = batch.contexts
		.map((c) => c.screenshotFile)
		.filter((f) => f && fs.existsSync(f));

	const baseCtx = batch.contexts[0];
	const baseBundle = JSON.parse(fs.readFileSync(baseCtx.bundlePath, "utf8"));
	baseBundle.artifacts.designContextFile = mergedContextPath;
	if (screenshotPaths.length > 0) {
		baseBundle.artifacts.allScreenshotFiles = screenshotPaths;
	}
	baseBundle.figma = baseBundle.figma || {};
	baseBundle.figma._batchMode = true;
	baseBundle.figma._batchUrls = batch.contexts.map((c) => c.url);

	const batchBundlePath = path.join(batchTempDir, "batch-bundle.json");
	fs.writeFileSync(batchBundlePath, JSON.stringify(baseBundle, null, 2), "utf8");

	if (bIndex > 0 && state.getFirstBatchDir()) {
		const copyFiles = ["batch-bundle.json.preview-project.json"];
		for (const fileName of copyFiles) {
			const src = path.join(state.getFirstBatchDir(), fileName);
			const dst = path.join(batchTempDir, fileName);
			if (fs.existsSync(src)) {
				fs.copyFileSync(src, dst);
			}
		}
		log(`${batchLabel} 已从首批复制 preview-project.json`);
	}
	if (bIndex === 0) {
		state.setFirstBatchDir(batchTempDir);
	}

	const args = ["scripts/ai-direct-execute.mjs", "--bundle-file", batchBundlePath];

	if (bIndex > 0) {
		args.push("--skip-preamble");
		if (state.getProjectRoot()) {
			args.push("--existing-preview-project-root", state.getProjectRoot());
		}
	} else if (state.getProjectRoot()) {
		args.push("--existing-preview-project-root", state.getProjectRoot());
	} else {
		const existingProject = config.existingProject?.trim() || null;
		if (existingProject) {
			const existingRoot = path.join(repoRoot, PREVIEW_DIR, existingProject);
			if (!fs.existsSync(existingRoot)) {
				emitConsole(`\n${batchLabel} 错误: 已有项目不存在 ${existingRoot}\n`, "stderr");
				return 1;
			}
			args.push("--project-dir", existingRoot, "--existing-preview-project-root", existingRoot);
			state.setProjectRoot(existingRoot);
		} else {
			let pDir = config.projectDir?.trim() || null;
			if (!pDir) {
				const previews = listPreviewProjects(repoRoot);
				pDir = previews.length > 0 ? previews[0].path : ".";
			}
			args.push("--project-dir", pDir);
		}
	}

	if (config.pageName?.trim()) args.push("--page-name", config.pageName.trim());
	args.push(
		"--provider", "openai-compatible",
		"--model", config.aiModel || DEFAULT_CONFIG.aiModel,
		"--auto-repair",
		"--without-variables",
		"--preview-dir", PREVIEW_DIR
	);
	if (bIndex === 0 && config.force !== false) args.push("--force");
	args.push("--skip-preview", "--skip-validate", "--skip-fitness");
	args.push("--batch-index", String(bIndex));
	if (config.componentNames && Object.keys(config.componentNames).length > 0) {
		args.push("--component-names", JSON.stringify(config.componentNames));
	}
	if (config.targetPlatform?.trim()) args.push("--target-platform", config.targetPlatform.trim());
	if (config.fallbackUi?.trim()) args.push("--fallback-ui", config.fallbackUi.trim());
	if (config.skipScreenshotSummary) args.push("--skip-screenshot-summary");
	if (config.skipValidate) args.push("--skip-validate");
	if (config.skipGovernance) args.push("--skip-governance");

	log(`${batchLabel} 命令: node ${args.join(" ")}`);

	const exitCode = await new Promise((resolve) => {
		const child = spawn(process.execPath, args, {
			cwd: repoRoot,
			env,
			stdio: ["ignore", "pipe", "pipe"],
		});
		setCurrentProcess(child);

		let stdoutBuffer = "";
		child.stdout.on("data", (data) => {
			stdoutBuffer += data.toString();
			const lines = stdoutBuffer.split("\n");
			stdoutBuffer = lines.pop() || "";
			for (const line of lines) {
				if (!line) continue;
				broadcast("output", { stream: "stdout", text: `[${batchLabel}] ${line}\n`, timestamp: Date.now() });
				const viteMatch = line.match(/Local:\s+(https?:\/\/(?:localhost|127\.0\.0\.1):\d+\/?)/);
				if (viteMatch) setPreviewUrl(viteMatch[1], log);
				const progressMatch = line.match(/\[(\d+)\/(\d+)\]\s*(\S+)/);
				if (progressMatch) {
					const stepNum = Number(progressMatch[1]);
					const stepName = progressMatch[3];
					if (stepNum >= 0 && stepNum <= 8) {
						emitStep(`step-${stepNum}`, stepName);
					}
				}
			}
		});
		child.stderr.on("data", (data) => {
			broadcast("output", { stream: "stderr", text: data.toString(), timestamp: Date.now() });
		});
		child.on("exit", (code) => {
			setCurrentProcess(null);
			emitConsole(`\n${batchLabel} 完成 (exit=${code})\n`, "system");
			log(`${batchLabel} 完成 (exit=${code})`);

			if (!state.getProjectRoot()) {
				const projects = listPreviewProjects(repoRoot);
				if (projects.length > 0) {
					const target = projects.find((p) => config.pageName && p.name.includes(config.pageName.toLowerCase()))
						|| projects.sort((a, b) => fs.statSync(b.path).mtimeMs - fs.statSync(a.path).mtimeMs)[0];
					if (target) {
						state.setProjectRoot(target.path);
						log(`检测到项目根: ${target.path}`);
					}
				}
			}

			resolve(code);
		});
		child.on("error", (err) => {
			setCurrentProcess(null);
			emitConsole(`\n${batchLabel} 启动失败: ${err.message}\n`, "stderr");
			resolve(1);
		});
	});

	if (exitCode !== 0) {
		emitConsole(`\n${batchLabel} ⚠ 生成失败 (exit=${exitCode}),继续下一批次\n`, "stderr");
		log(`${batchLabel} ⚠ 失败,继续下一批次`);
	}

	return exitCode;
}

/**
 * 单 URL 模式
 */
async function runSingleUrl(config, figmaUrl, env, repoRoot, log) {
	const args = ["scripts/ai-direct-execute.mjs"];
	const existingProject = config.existingProject?.trim() || null;

	if (existingProject) {
		const existingRoot = path.join(repoRoot, PREVIEW_DIR, existingProject);
		if (!fs.existsSync(existingRoot)) {
			broadcast("error", { message: `已有项目不存在: ${existingProject}` });
			broadcast("status", { running: false, step: "error" });
			setIsRunning(false);
			stopHeartbeat();
			return;
		}
		args.push("--project-dir", existingRoot, "--figma-url", figmaUrl, "--existing-preview-project-root", existingRoot);
		if (config.pageName?.trim()) args.push("--page-name", config.pageName.trim());
		if (config.refreshContext) args.push("--refresh-context");
		log(`追加到已有项目: ${existingProject}`);
	} else {
		let projectDir = config.projectDir?.trim() || null;
		if (!projectDir) {
			const previews = listPreviewProjects(repoRoot);
			if (previews.length > 0) {
				projectDir = previews[0].path;
				log(`使用已有预览项目作为参考: ${previews[0].name}`);
			} else {
				projectDir = ".";
				log("使用仓库根目录作为项目参考");
			}
		}
		args.push("--project-dir", projectDir, "--figma-url", figmaUrl);
		if (config.pageName?.trim()) args.push("--page-name", config.pageName.trim());
		if (config.refreshContext) args.push("--refresh-context");
	}

	args.push(
		"--provider", "openai-compatible",
		"--model", config.aiModel || DEFAULT_CONFIG.aiModel,
		"--auto-repair",
		"--without-variables",
		"--preview-dir", PREVIEW_DIR
	);
	if (config.force !== false) args.push("--force");
	if (config.skipPreview) args.push("--skip-preview");
	if (config.targetPlatform?.trim()) {
		args.push("--target-platform", config.targetPlatform.trim());
		log(`目标平台: ${config.targetPlatform.trim()}`);
	}
	if (config.fallbackUi?.trim()) {
		args.push("--fallback-ui", config.fallbackUi.trim());
		log(`降级组件库: ${config.fallbackUi.trim()}`);
	}
	if (config.skipScreenshotSummary) {
		args.push("--skip-screenshot-summary");
		log("跳过截图视觉摘要");
	}
	if (config.skipValidate) {
		args.push("--skip-validate");
		log("跳过代码验证和自动修复");
	}
	if (config.skipGovernance) {
		args.push("--skip-governance");
		log("跳过 Venus 治理检查");
	}

	emitConsole(`\n═══════════════════════════════════════\n`, "system");
	emitConsole(`  Venus AI Direct Pipeline\n`, "system");
	emitConsole(`  ${new Date().toLocaleString()}\n`, "system");
	emitConsole(`═══════════════════════════════════════\n\n`, "system");

	emitStep("init", "初始化流程...");
	log(`启动命令: node ${args.join(" ")}`);
	log(`参数数量: ${args.length}`);

	launchPipelineChild(args, env, config, repoRoot, log);
}

/**
 * 启动管线子进程
 */
function launchPipelineChild(args, env, config, repoRoot, log) {
	emitStep("init", "初始化流程...");

	const child = spawn(process.execPath, args, {
		cwd: repoRoot,
		env,
		stdio: ["ignore", "pipe", "pipe"],
	});
	setCurrentProcess(child);

	let lastStep = "init";
	let stdoutBuffer = "";

	child.stdout.on("data", (data) => {
		stdoutBuffer += data.toString();
		const lines = stdoutBuffer.split("\n");
		stdoutBuffer = lines.pop() || "";
		for (const line of lines) {
			if (!line) continue;
			broadcast("output", { stream: "stdout", text: `${line}\n`, timestamp: Date.now() });
			const viteMatch = line.match(/Local:\s+(https?:\/\/(?:localhost|127\.0\.0\.1):\d+\/?)/);
			if (viteMatch) setPreviewUrl(viteMatch[1], log);
			const progressMatch = line.match(/\[(\d+)\/(\d+)\]\s*(\S+)/);
			if (progressMatch) {
				const stepNum = Number(progressMatch[1]);
				const stepName = progressMatch[3];
				if (stepNum >= 0 && stepNum <= 8) {
					emitStep(`step-${stepNum}`, stepName);
					lastStep = `step-${stepNum}`;
				}
			}
		}
	});

	child.stderr.on("data", (data) => {
		broadcast("output", { stream: "stderr", text: data.toString(), timestamp: Date.now() });
	});

	child.on("exit", (code) => {
		setCurrentProcess(null);
		broadcast("status", { running: false, exitCode: code, step: code === 0 ? "complete" : "failed" });
		log(`流程结束 (exit=${code})`);

		const target = findTargetProject(repoRoot, config);
		if (target) {
			broadcast("files", { project: target.name, files: listGeneratedFiles(target.path) });
		}

		setIsRunning(false);
		stopHeartbeat();
	});

	child.on("error", (err) => {
		setCurrentProcess(null);
		broadcast("error", { message: `启动失败: ${err.message}` });
		broadcast("status", { running: false, step: "error" });
		log(`启动失败: ${err.message}`);
		setIsRunning(false);
		stopHeartbeat();
	});
}

/**
 * 注册路由并启动预览项目
 */
async function registerRoutesAndStartPreview(projectRoot, env, repoRoot, log) {
	try {
		const result = await spawnAsync(process.execPath, [
			"scripts/ai-direct-apply-output.mjs",
			"--register-routes-only",
			"--project-root", projectRoot,
		], {
			cwd: repoRoot,
			env,
			timeout: 30_000,
		}, (line, stream) => {
			broadcast("output", { stream, text: `${line}\n`, timestamp: Date.now() });
		});

		if (result.status !== 0) {
			emitConsole(`\n⚠ 路由注册失败: exit=${result.status}\n`, "stderr");
			return `路由注册失败: exit=${result.status}`;
		}

		emitConsole(`\n✓ 路由注册完成\n`, "system");
		emitConsole(`\n--- 启动预览项目 ---\n`, "system");
		log("启动预览项目");

		const child = spawn("pnpm", ["dev"], {
			cwd: projectRoot,
			env,
			stdio: ["ignore", "pipe", "pipe"],
			detached: true,
		});

		let previewUrlDetected = false;
		const detectPreviewUrl = (text) => {
			if (previewUrlDetected) return;
			// 匹配多种格式的 Vite 输出
			const patterns = [
				/Local:\s+(https?:\/\/(?:localhost|127\.0\.0\.1):\d+\/?)/i,
				/(https?:\/\/localhost:\d+\/?)/i,
				/> Local:\s+(https?:\/\/\S+)/i,
			];
			for (const pattern of patterns) {
				const match = text.match(pattern);
				if (match) {
					previewUrlDetected = true;
					const url = match[1];
					setPreviewUrl(url, log);
					emitConsole(`\n✓ 预览地址: ${url}\n`, "system");
					log(`检测到预览地址: ${url}`);
					return;
				}
			}
		};

		child.stdout.on("data", (data) => {
			const text = data.toString();
			broadcast("output", { stream: "stdout", text, timestamp: Date.now() });
			detectPreviewUrl(text);
		});

		child.stderr.on("data", (data) => {
			const text = data.toString();
			broadcast("output", { stream: "stderr", text, timestamp: Date.now() });
			detectPreviewUrl(text);
		});

		child.unref();
		return "路由注册完成,预览项目已启动";
	} catch (error) {
		emitConsole(`\n⚠ 启动预览项目失败: ${error.message}\n`, "stderr");
		return `启动失败: ${error.message}`;
	}
}