validation-loop.ts 23.3 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
/**
 * Main validation loop orchestration.
 *
 * Simplified actor-critic pattern with in-memory data passing.
 * Iteratively validates positions, diagnoses errors, applies fixes until
 * MAE threshold is met or max iterations reached.
 */

import * as fs from 'fs';
import * as path from 'path';

import { DEFAULT_VALIDATION_LOOP_CONFIG } from '../constants';
import { logger } from '../../../utils/logger';
import { commit } from '../commit/index';
import { createJudgerAgent } from '../../../agents/judger-agent';
import { formatJudgerInstruction } from '../../../agents/judger-agent/instruction';
import { createRefinerAgent, formatRefinerInstruction } from '../../../agents/refiner-agent';
import { launch } from '../launch/index';
import type { ComponentHistory, MisalignedComponent, Dict } from '../../../types/validation-types';
import type { JudgerDiagnosis } from '../../../agents/judger-agent/types';
import type { RefinerResult } from '../../../agents/refiner-agent/types';
import type {
    ComponentCorrectionLog,
    IterationLog,
    ProcessedOutput,
    RefinementContext,
    ValidationIterationResult,
    ValidationLoopConfig,
    ValidationLoopParams,
    ValidationLoopResult,
    SkippedElement,
} from '../types';
import { extractLayoutFromContext } from '../utils/extraction/extract-layout-metadata';
import { report } from '../report/index';
import { LaunchTool } from '../../../tools/launch-tool';
import { VisualizationTool } from '../../../tools/visualization-tool';
import { extractValidationContext, extractComponentPaths, toElementMetadataRegistry } from '../utils/extraction/extract-protocol-context';
import { validatePositions } from './validate-position';
import { downloadImage } from '../../../tools/figma-tool/images';
import { ensureValidationDependencies } from '../../../utils/dependency-installer';
import { ValidationMode } from '../../../types/graph-types';

function filterComponentsToFix(misaligned: MisalignedComponent[], positionThreshold: number): MisalignedComponent[] {
    return misaligned.filter(comp => {
        const [errorX, errorY] = comp.validationReport.absoluteError;
        return errorX > positionThreshold || errorY > positionThreshold;
    });
}

function recordComponentPosition(comp: MisalignedComponent, iteration: number, componentHistory: ComponentHistory): void {
    const history = componentHistory[comp.componentId] ?? [];
    history.push({
        iteration,
        position: comp.validationReport.currentPosition,
        error: comp.validationReport.absoluteError,
        fixApplied: null,
    });
    componentHistory[comp.componentId] = history;
}

async function refineComponent(comp: MisalignedComponent, context: RefinementContext): Promise<ComponentCorrectionLog> {
    const { workspace, structureTree, componentPaths, componentHistory, validationContext, previousScreenshotPath } = context;

    try {
        // Extract element IDs from context for this component
        const elementIds = Array.from(validationContext.elements.values())
            .filter((e): e is NonNullable<typeof e> => e.parentComponentId === comp.componentId)
            .map(e => e.id);

        const figmaMetadata = extractLayoutFromContext(validationContext, elementIds);

        logger.printLog(`  Analyzing ${comp.name}...`);
        const judger = createJudgerAgent({
            workspaceDir: workspace.app,
            structureTree,
            componentPaths,
            history: componentHistory,
        });
        const judgerInstruction = formatJudgerInstruction(comp, figmaMetadata as unknown as Record<string, unknown>, componentPaths);
        const judgerImages = previousScreenshotPath ? [previousScreenshotPath] : undefined;
        const diagnosis = (await judger.run(judgerInstruction, judgerImages)) as JudgerDiagnosis;

        logger.printLog(`     Error type: ${diagnosis.errorType}`);
        logger.printLog(`     Fix instructions: ${diagnosis.refineInstructions?.length || 0}`);

        // Skip refiner if no instructions (judger failed to analyze)
        if (!diagnosis.refineInstructions || diagnosis.refineInstructions.length === 0) {
            const history = componentHistory[comp.componentId];
            return {
                componentId: comp.componentId,
                componentPath: comp.path,
                elementIds: comp.elementIds,
                validationReport: comp.validationReport,
                diagnosis,
                refinerResult: {
                    success: false,
                    summary: ['Skipped - no instructions from judger'],
                    editsApplied: 0,
                },
                positionHistory: history ? [...history] : undefined,
            };
        }

        logger.printLog(`  Applying fixes to ${comp.name}...`);
        const refiner = createRefinerAgent(workspace.app);
        const refinerInstruction = formatRefinerInstruction(comp, diagnosis, componentPaths);
        const refinerResult = (await refiner.run(refinerInstruction)) as RefinerResult;

        if (refinerResult.success) {
            logger.printSuccessLog(`${comp.name}: ${refinerResult.editsApplied} edits applied`);
        } else {
            logger.printWarnLog(`${comp.name}: ${refinerResult.editsApplied} edits applied`);
        }

        const history = componentHistory[comp.componentId];
        const last = history?.at(-1);
        if (last) {
            last.fixApplied = refinerResult.summary;
        }

        return {
            componentId: comp.componentId,
            componentPath: comp.path,
            elementIds: comp.elementIds,
            validationReport: comp.validationReport,
            diagnosis,
            refinerResult,
            positionHistory: history ? [...history] : undefined,
        };
    } catch (error) {
        const errorMsg = error instanceof Error ? error.message : String(error);
        logger.printInfoLog(`${comp.name}: ${errorMsg}`);

        const history = componentHistory[comp.componentId];
        return {
            componentId: comp.componentId,
            componentPath: comp.path,
            elementIds: comp.elementIds,
            validationReport: comp.validationReport,
            diagnosis: undefined,
            refinerResult: undefined,
            positionHistory: history ? [...history] : undefined,
        };
    }
}

function saveProcessedJson(outputDir: string, processedOutput: ProcessedOutput): void {
    const processedJsonPath = path.join(outputDir, 'processed.json');
    fs.writeFileSync(processedJsonPath, JSON.stringify(processedOutput, null, 2));
    logger.printInfoLog('Saved processed.json');
}

// Helper functions for reducing code duplication
async function performCommit(appPath: string, iteration: number | undefined, stage: string): Promise<void> {
    const commitResult = await commit({ appPath, iteration });
    if (!commitResult.success) {
        logger.printWarnLog(`Git commit (${stage}) failed: ${commitResult.message}`);
    } else if (iteration === undefined) {
        logger.printSuccessLog(`Initial project committed successfully, starting validation loop...`);
    }
}

function saveIterationAndProcessedJson(
    iterations: IterationLog[],
    iteration: number,
    currentMae: number,
    currentSae: number,
    misalignedCount: number,
    components: ComponentCorrectionLog[],
    screenshotPath: string,
    skippedElements: SkippedElement[] | undefined,
    outputDir: string,
    targetMae: number
): void {
    // Add current iteration to log
    iterations.push({
        iteration,
        metrics: { mae: currentMae, sae: currentSae, misalignedCount },
        components,
        screenshotPath,
        skippedElements: skippedElements && skippedElements.length > 0 ? skippedElements : undefined,
    });

    // Save processed.json with updated iterations
    const processedOutput: ProcessedOutput = {
        iterations,
        finalResult: {
            success: currentMae <= targetMae,
            finalMae: currentMae,
            finalSae: currentSae,
            totalIterations: iterations.length,
            misalignedCount,
        },
    };
    saveProcessedJson(outputDir, processedOutput);
}

export async function validationLoop(params: ValidationLoopParams): Promise<ValidationLoopResult> {
    // Ensure dependencies are installed before starting validation loop
    ensureValidationDependencies();

    const { protocol, figmaThumbnailUrl, outputDir, workspace } = params;

    if (!protocol || !figmaThumbnailUrl || !outputDir || !workspace) {
        throw new Error('Something wrong in validation loop, missing required parameters...');
    }

    const config: ValidationLoopConfig = {
        ...DEFAULT_VALIDATION_LOOP_CONFIG,
        ...params.config,
    };
    const mode: ValidationMode.ReportOnly | ValidationMode.Full = config.mode ?? ValidationMode.Full;
    const maxIterations = mode === ValidationMode.ReportOnly ? 1 : config.maxIterations;
    const visualizationTool = new VisualizationTool();

    // Variables to track server state (will be initialized in iteration 1)
    let currentServerUrl: string | undefined;
    let serverKey: string | undefined;

    try {
        // Extract unified validation context from protocol (single traversal)
        const validationContext = extractValidationContext(protocol);
        const designOffset: [number, number] = [validationContext.offset.x, validationContext.offset.y];
        if (Math.abs(designOffset[0]) >= 1 || Math.abs(designOffset[1]) >= 1) {
            logger.printInfoLog(`Design offset: (${designOffset[0].toFixed(0)}, ${designOffset[1].toFixed(0)} px)`);
        }

        // Extract component paths from context (already resolved to absolute filesystem paths)
        const resolvedComponentPaths = extractComponentPaths(validationContext, workspace);

        // Build element registry for compatibility with existing APIs
        const elementRegistry = toElementMetadataRegistry(validationContext);

        // Download and cache Figma thumbnail once to avoid redundant downloads in each iteration
        logger.printInfoLog('Downloading Figma thumbnail (will be cached for all iterations)...');
        const cachedFigmaThumbnailBase64 = await downloadImage(figmaThumbnailUrl, undefined, undefined, true);
        logger.printSuccessLog('Figma thumbnail cached successfully');

        const iterations: IterationLog[] = [];
        const componentHistory: ComponentHistory = {};
        let previousScreenshotPath: string | undefined;
        let currentMae = -1; // Sentinel value: -1 indicates no measurement yet
        let currentSae = 0;
        let lastMisalignedCount = 0;
        let lastValidationResult: ValidationIterationResult | undefined;
        // Track paths to last iteration's individual screenshots for report reuse
        let lastRenderMarkedPath: string | undefined;
        let lastTargetMarkedPath: string | undefined;

        for (let iteration = 1; iteration <= maxIterations; iteration++) {
            // Use different logging for reportOnly mode
            if (mode === ValidationMode.ReportOnly) {
                logger.printLog(`\n${'='.repeat(60)}`);
                logger.printLog(`Running validation (report-only mode)`);
                logger.printLog(`${'='.repeat(60)}`);
            } else {
                logger.printLog(`\n${'='.repeat(60)}`);
                logger.printLog(`Iteration ${iteration}/${maxIterations}`);
                logger.printLog(`${'='.repeat(60)}`);
            }

            // If this is iteration 1, we need to launch first to have a server for validation
            if (iteration === 1) {
                logger.printInfoLog('Initial launch: installing dependencies, building, fixing errors...');
                const launchResult = await launch(workspace.app, {
                    skipDependencyInstall: false,
                });

                if (!launchResult.success) {
                    throw new Error(`Initial launch failed: ${launchResult.error}`);
                }

                currentServerUrl = launchResult.url!;
                serverKey = launchResult.serverKey!;
                logger.printSuccessLog(`Dev server ready at ${currentServerUrl}`);

                // In reportOnly mode, commit the initial state after successful launch
                if (mode === ValidationMode.ReportOnly) {
                    await performCommit(workspace.app, undefined, 'initial state');
                }
            }

            const validationResult = await validatePositions({
                serverUrl: currentServerUrl!,
                figmaThumbnailUrl,
                protocol,
                iteration,
                positionThreshold: config.positionThreshold,
                designOffset,
                outputDir,
                validationContext,
                elementRegistry,
                cachedFigmaThumbnailBase64,
                resolvedComponentPaths,
            });

            // Store for final report generation
            lastValidationResult = validationResult;

            currentMae = validationResult.mae;
            currentSae = validationResult.sae;
            const misaligned = validationResult.misalignedComponents;
            lastMisalignedCount = misaligned.length;

            logger.printLog(`MAE: ${currentMae.toFixed(2)}px (target: <=${config.targetMae}px)`);
            logger.printLog(`SAE: ${currentSae.toFixed(2)}px`);
            logger.printLog(`Misaligned: ${misaligned.length}`);

            // Generate validation screenshot using VisualizationTool
            const screenshotResult = await visualizationTool.generateIterationScreenshot(
                misaligned,
                currentServerUrl!,
                figmaThumbnailUrl,
                validationResult.viewport,
                { x: designOffset[0], y: designOffset[1] },
                path.join(outputDir, 'comparison_screenshots', `iteration_${iteration}.webp`),
                cachedFigmaThumbnailBase64
            );

            // Save individual annotated screenshots to disk for report reuse
            if (screenshotResult.renderMarked && screenshotResult.targetMarked) {
                const comparisonDir = path.join(outputDir, 'comparison_screenshots');
                lastRenderMarkedPath = path.join(comparisonDir, `iteration_${iteration}_render_marked.webp`);
                lastTargetMarkedPath = path.join(comparisonDir, `iteration_${iteration}_target_marked.webp`);

                const sharp = (await import('sharp')).default;
                await sharp(Buffer.from(screenshotResult.renderMarked.split(',')[1]!, 'base64')).toFile(lastRenderMarkedPath);
                await sharp(Buffer.from(screenshotResult.targetMarked.split(',')[1]!, 'base64')).toFile(lastTargetMarkedPath);
            }

            // Use combined screenshot for judger visual context in next iteration
            const comparisonScreenshotPath = screenshotResult.combinedPath;
            previousScreenshotPath = comparisonScreenshotPath; // Pass to judger in next iteration

            const misalignedToFix = filterComponentsToFix(misaligned, config.positionThreshold);
            if (mode === ValidationMode.ReportOnly) {
                // In reportOnly mode, we don't fix anything, so no need to log about skipping
            } else {
                logger.printInfoLog(
                    `Skipping ${misaligned.length - misalignedToFix.length} components with error <= ${config.positionThreshold}px`
                );
            }

            for (const comp of misalignedToFix) {
                recordComponentPosition(comp, iteration, componentHistory);
            }

            const componentLogs: ComponentCorrectionLog[] = [];

            if (mode === ValidationMode.ReportOnly) {
                logger.printInfoLog('Report-only mode: skipping component refinement, saving validation report...');

                saveIterationAndProcessedJson(
                    iterations,
                    iteration,
                    currentMae,
                    currentSae,
                    misaligned.length,
                    componentLogs,
                    comparisonScreenshotPath,
                    validationResult.skippedElements,
                    outputDir,
                    config.targetMae
                );
                break;
            }

            if (currentMae <= config.targetMae) {
                logger.printSuccessLog('Validation passed!');

                saveIterationAndProcessedJson(
                    iterations,
                    iteration,
                    currentMae,
                    currentSae,
                    misaligned.length,
                    componentLogs,
                    comparisonScreenshotPath,
                    validationResult.skippedElements,
                    outputDir,
                    config.targetMae
                );

                if (serverKey) {
                    await performCommit(workspace.app, iteration, `iteration ${iteration}`);
                }
                break;
            }

            // Full mode: proceed with component refinement
            logger.printInfoLog(`Refining ${misalignedToFix.length} components...`);

            const refinementContext: RefinementContext = {
                workspace,
                structureTree: protocol as unknown as Dict,
                componentPaths: resolvedComponentPaths,
                componentHistory,
                validationContext,
                previousScreenshotPath,
            };

            for (const comp of misalignedToFix) {
                const log = await refineComponent(comp, refinementContext);
                componentLogs.push(log);
            }

            // Launch after refiner to catch any errors and rebuild
            logger.printInfoLog('Re-launching dev server after refiner changes...');

            // Stop current server
            const launchTool = new LaunchTool();
            await launchTool.stopDevServer(serverKey!).catch(() => {
                logger.printWarnLog('Failed to stop previous server');
            });

            // Launch with skipDependencyInstall (deps don't change)
            const launchResult = await launch(workspace.app, {
                skipDependencyInstall: true,
            });

            if (!launchResult.success) {
                throw new Error(`Launch failed after refiner at iteration ${iteration}: ${launchResult.error}`);
            }

            currentServerUrl = launchResult.url!;
            serverKey = launchResult.serverKey!;

            logger.printSuccessLog(`Dev server restarted at ${currentServerUrl}`);

            // Commit AFTER launch (ensures working state)
            if (mode === ValidationMode.Full) {
                await performCommit(workspace.app, iteration, `iteration ${iteration}`);
            }

            saveIterationAndProcessedJson(
                iterations,
                iteration,
                currentMae,
                currentSae,
                misaligned.length,
                componentLogs,
                comparisonScreenshotPath,
                validationResult.skippedElements,
                outputDir,
                config.targetMae
            );

            // This path is only reached in full mode (reportOnly breaks out earlier)
            logger.printInfoLog(`Iteration ${iteration} complete\n`);
        }

        const validationPassed = currentMae <= config.targetMae;
        if (!validationPassed) {
            if (mode === ValidationMode.ReportOnly) {
                logger.printWarnLog(
                    `Validation did not satisfy MAE threshold (${config.targetMae}px) in report-only mode. Final MAE: ${currentMae.toFixed(2)}px`
                );
            } else {
                logger.printWarnLog(
                    `Max iterations (${maxIterations}) reached without satisfying MAE threshold (${config.targetMae}px). Final MAE: ${currentMae.toFixed(2)}px`
                );
            }
        }

        const finalOutput: ProcessedOutput = {
            iterations,
            finalResult: {
                success: validationPassed,
                finalMae: currentMae,
                finalSae: currentSae,
                totalIterations: iterations.length,
                misalignedCount: lastMisalignedCount,
            },
        };

        // Ensure server was launched (should always be true after iteration 1)
        if (!currentServerUrl || !serverKey) {
            throw new Error('Server was not launched properly during validation');
        }

        // Generate final validation report using report() subnode
        try {
            if (!lastValidationResult) {
                throw new Error('No validation results available for report generation');
            }

            // Validate that we have saved screenshots
            if (!lastRenderMarkedPath || !lastTargetMarkedPath) {
                throw new Error('No saved screenshots available for report generation');
            }

            const reportResult = await report({
                validationResult: lastValidationResult,
                figmaThumbnailUrl,
                cachedFigmaThumbnailBase64,
                designOffset: { x: designOffset[0], y: designOffset[1] },
                outputDir,
                serverUrl: currentServerUrl,
                savedRenderMarkedPath: lastRenderMarkedPath,
                savedTargetMarkedPath: lastTargetMarkedPath,
            });

            // Update misaligned count from final report (may differ from last iteration)
            finalOutput.finalResult.misalignedCount = lastValidationResult.misalignedComponents.length;
            saveProcessedJson(outputDir, finalOutput);

            return {
                reportGenerated: reportResult.success,
                validationPassed,
                finalMae: currentMae,
                finalSae: currentSae,
                totalIterations: iterations.length,
                processedOutput: finalOutput,
                userReport: reportResult.userReport,
            };
        } catch (screenshotError) {
            const errorMsg = screenshotError instanceof Error ? screenshotError.message : String(screenshotError);
            logger.printWarnLog(`Failed to generate final report: ${errorMsg}. Returning minimal report.`);
            saveProcessedJson(outputDir, finalOutput);

            // Fallback: create minimal report
            return {
                reportGenerated: false,
                validationPassed,
                finalMae: currentMae,
                finalSae: currentSae,
                totalIterations: iterations.length,
                processedOutput: finalOutput,
                userReport: {
                    design: { snap: figmaThumbnailUrl, markedSnap: '' },
                    page: { url: currentServerUrl, snap: '', markedSnap: '' },
                    report: {
                        heatmap: '',
                        detail: {
                            metrics: { mae: currentMae, sae: currentSae, misalignedCount: lastMisalignedCount },
                            components: [],
                        },
                    },
                },
            };
        }
    } finally {
        // Cleanup: Stop dev server if it was started by this validation loop
        if (serverKey) {
            logger.printInfoLog('Cleaning up dev server...');
            const launchTool = new LaunchTool();
            await launchTool.stopDevServer(serverKey).catch((err: unknown) => {
                logger.printWarnLog(`Failed to stop dev server: ${err instanceof Error ? err.message : String(err)}`);
            });
        }
    }
}