import { closeSync, createReadStream, openSync, readSync, statSync, } from 'node:fs'; import { open as openAsync } from 'node:fs/promises'; import { StringDecoder } from 'node:string_decoder'; import { REPORT_ARTIFACT_SCRIPT_TYPE, assertReportArtifactPath, } from '@midscene/shared/report-artifact'; import { antiEscapeScriptTag, escapeScriptTag } from '@midscene/shared/utils'; import { TEST_RUN_REPORT_SCRIPT_TYPE, type TestRunReportDump, } from '../test-run-report'; import type { AIUsageInfo, IReportActionDump, ModelBrief } from '../types'; export const escapeContent = escapeScriptTag; export const unescapeContent = antiEscapeScriptTag; function cleanHtmlCommentValue(value: unknown): string { return String(value ?? 'N/A') .replace(/\0/g, '') .replace(/--/g, '- -'); } function formatModelBriefForAgent(brief: ModelBrief): string { const intent = brief.intent || 'default'; const model = brief.name || 'unknown'; const description = brief.modelDescription ? ` (${brief.modelDescription})` : ''; return `${intent}: ${model}${description}`; } function hasUsageModelInfo(usage?: AIUsageInfo): usage is AIUsageInfo { return Boolean( usage && (usage.model_name || usage.response_model_name || usage.model_description || usage.intent), ); } function formatUsageModelForAgent(source: string, usage: AIUsageInfo): string { const intent = usage.intent || source; const model = usage.model_name || usage.response_model_name || 'unknown'; const description = usage.model_description ? ` (${usage.model_description})` : ''; return `${intent}: ${model}${description}`; } function collectUsageModelsForAgent(report: IReportActionDump): string { const models = new Map(); const executions = Array.isArray(report.executions) ? report.executions : []; for (const execution of executions) { const tasks = Array.isArray(execution.tasks) ? execution.tasks : []; for (const task of tasks) { const taskWithUsage = task as { usage?: AIUsageInfo; searchAreaUsage?: AIUsageInfo; }; const usages: Array<[string, AIUsageInfo | undefined]> = [ ['main', taskWithUsage.usage], ['searchArea', taskWithUsage.searchAreaUsage], ]; for (const [source, usage] of usages) { if (!hasUsageModelInfo(usage)) { continue; } const formatted = formatUsageModelForAgent(source, usage); models.set(formatted, formatted); } } } return Array.from(models.values()).join('; '); } export function generateAgentReportComment(report: IReportActionDump): string { const executions = Array.isArray(report.executions) ? report.executions : []; const taskCount = executions.reduce( (sum, execution) => sum + (Array.isArray(execution.tasks) ? execution.tasks.length : 0), 0, ); const modelBriefs = report.modelBriefs?.length ? report.modelBriefs.map(formatModelBriefForAgent).join('; ') : collectUsageModelsForAgent(report) || 'No model metadata recorded'; const lines = [ 'For Agent Analysis:', `Report: ${cleanHtmlCommentValue(report.groupName)}`, `SDK: ${cleanHtmlCommentValue(report.sdkVersion)}`, `Device: ${cleanHtmlCommentValue(report.deviceType)}`, `Executions: ${executions.length}; Tasks: ${taskCount}`, `Models: ${cleanHtmlCommentValue(modelBriefs)}`, 'Structured report JSON is stored in script[type="midscene_web_dump"] tags near this comment.', 'Screenshots are stored as script[type="midscene-image"] tags or files referenced by screenshot refs.', 'For AI analysis, inspect each execution task for type, status, timing, param, output, usage, searchAreaUsage, recorder, and screenshot refs.', 'Use the Markdown export when available; it contains the same report context plus image links for agent review.', ]; return `\n\n`; } function htmlScriptCloseTag(): string { // biome-ignore lint/style/useTemplate: keep this token runtime-built for inline report bundles return String.fromCharCode(60) + '/script>'; } /** Directory reports declare their data entry separately from the Viewer. */ export function generateReportArtifactScriptTag(path: string): string { assertReportArtifactPath(path); return [ String.fromCharCode(60), 'script type="', REPORT_ARTIFACT_SCRIPT_TYPE, '">', JSON.stringify(path), htmlScriptCloseTag(), ].join(''); } function reportArtifactPathExtractor(filePath: string) { let result: string | undefined; return { get path() { return result; }, visit: (content: string) => { const tagEnd = content.indexOf('>'); const type = content .slice(0, tagEnd) .match(/(?:^|\s)type\s*=\s*["']([^"']+)["']/i)?.[1]; if (type !== REPORT_ARTIFACT_SCRIPT_TYPE) return false; if (result !== undefined) throw new Error( `Report contains multiple artifact entries: ${filePath}`, ); const path: unknown = JSON.parse( unescapeContent(content.slice(tagEnd + 1)), ); assertReportArtifactPath(path); result = path; return false; }, }; } export function extractReportArtifactPathSync( filePath: string, ): string | undefined { const extractor = reportArtifactPathExtractor(filePath); streamScanTags( filePath, `${String.fromCharCode(60)}script`, htmlScriptCloseTag(), extractor.visit, ); return extractor.path; } export async function extractReportArtifactPathAsync( filePath: string, ): Promise { const extractor = reportArtifactPathExtractor(filePath); await streamScanTagsAsync( filePath, `${String.fromCharCode(60)}script`, htmlScriptCloseTag(), extractor.visit, ); return extractor.path; } /** Consume complete elements so dump-tag strings in the Viewer are never payloads. */ export async function streamDumpScriptsAsync( filePath: string, visitor: (dump: { openTag: string; content: string }) => boolean, ): Promise { await streamScanTagsAsync( filePath, `${String.fromCharCode(60)}script`, htmlScriptCloseTag(), (content) => { const tagEnd = content.indexOf('>'); const type = content .slice(0, tagEnd) .match(/(?:^|\s)type\s*=\s*["']([^"']+)["']/i)?.[1]; return type === 'midscene_web_dump' ? visitor({ openTag: `${String.fromCharCode(60)}script${content.slice(0, tagEnd + 1)}`, content: content.slice(tagEnd + 1), }) : false; }, ); } /** Avoid raw close tokens: this writer itself is bundled into report HTML. */ export function generateTestRunReportScriptTag( dump: TestRunReportDump, ): string { return [ String.fromCharCode(60), 'script type="', TEST_RUN_REPORT_SCRIPT_TYPE, '">\n', escapeScriptTag(JSON.stringify(dump)), '\n', htmlScriptCloseTag(), '\n', ].join(''); } export function extractTestRunReportDumpSync( filePath: string, ): TestRunReportDump | undefined { let result: TestRunReportDump | undefined; // Consume executable scripts as whole elements: the embedded viewer itself // contains report-writer source with data-tag strings that are not payloads. const openTag = `${String.fromCharCode(60)}script`; streamScanTags(filePath, openTag, htmlScriptCloseTag(), (content) => { const tagEnd = content.indexOf('>'); const attributes = content.slice(0, tagEnd); const type = attributes.match(/(?:^|\s)type\s*=\s*["']([^"']+)["']/i)?.[1]; if (type !== TEST_RUN_REPORT_SCRIPT_TYPE) return false; if (result) throw new Error( `Report contains multiple Midscene Test dumps: ${filePath}`, ); const parsed = JSON.parse(unescapeContent(content.slice(tagEnd + 1))); if ( parsed?.schemaVersion !== 1 || parsed?.kind !== 'test-runner' || !Array.isArray(parsed.projects) ) throw new Error(`Invalid Midscene Test report dump: ${filePath}`); result = parsed; return false; }); return result; } /** Chunk size for streaming file operations (64KB) */ export const STREAMING_CHUNK_SIZE = 64 * 1024; /** * Callback for processing matched tags during streaming. * @param content - The content between open and close tags * @returns true to stop scanning, false to continue */ type TagMatchCallback = (content: string) => boolean; class StreamingTagMatcher { private leftover = ''; private capturing = false; private currentContent = ''; constructor( private readonly openTag: string, private readonly closeTag: string, private readonly onMatch: TagMatchCallback, ) {} push(nextChunk: string): boolean { const chunk = this.leftover + nextChunk; this.leftover = ''; let searchStart = 0; while (searchStart < chunk.length) { if (!this.capturing) { const startIndex = chunk.indexOf(this.openTag, searchStart); if (startIndex === -1) { const retainedSuffixLength = Math.max(0, this.openTag.length - 1); this.leftover = retainedSuffixLength ? chunk.slice(-retainedSuffixLength) : ''; return false; } this.capturing = true; searchStart = startIndex + this.openTag.length; } const endIndex = chunk.indexOf(this.closeTag, searchStart); if (endIndex !== -1) { this.currentContent += chunk.slice(searchStart, endIndex); if (this.onMatch(this.currentContent)) return true; this.capturing = false; this.currentContent = ''; searchStart = endIndex + this.closeTag.length; continue; } const retainedSuffixLength = Math.max(0, this.closeTag.length - 1); const contentEnd = Math.max( searchStart, chunk.length - retainedSuffixLength, ); this.currentContent += chunk.slice(searchStart, contentEnd); this.leftover = chunk.slice(contentEnd); return false; } return false; } } /** * Stream through a file and find tags matching the pattern. * Memory usage: O(chunk_size + tag_size), not O(file_size). * * @param filePath - Absolute path to the file * @param openTag - Opening tag to search for * @param closeTag - Closing tag * @param onMatch - Callback for each matched tag content */ export function streamScanTags( filePath: string, openTag: string, closeTag: string, onMatch: TagMatchCallback, ): void { const fd = openSync(filePath, 'r'); const fileSize = statSync(filePath).size; const buffer = Buffer.alloc(STREAMING_CHUNK_SIZE); const decoder = new StringDecoder('utf8'); const matcher = new StreamingTagMatcher(openTag, closeTag, onMatch); let position = 0; try { while (position < fileSize) { const bytesRead = readSync(fd, buffer, 0, STREAMING_CHUNK_SIZE, position); position += bytesRead; if (matcher.push(decoder.write(buffer.subarray(0, bytesRead)))) return; } matcher.push(decoder.end()); } finally { closeSync(fd); } } /** Asynchronously stream tags without blocking the Node.js event loop. */ export async function streamScanTagsAsync( filePath: string, openTag: string, closeTag: string, onMatch: TagMatchCallback, ): Promise { const handle = await openAsync(filePath, 'r'); const buffer = Buffer.alloc(STREAMING_CHUNK_SIZE); const decoder = new StringDecoder('utf8'); let position = 0; const matcher = new StreamingTagMatcher(openTag, closeTag, onMatch); try { while (true) { const { bytesRead } = await handle.read( buffer, 0, STREAMING_CHUNK_SIZE, position, ); if (bytesRead === 0) { matcher.push(decoder.end()); return; } position += bytesRead; if (matcher.push(decoder.write(buffer.subarray(0, bytesRead)))) return; } } finally { await handle.close(); } } /** * Synchronously extract a specific image's base64 data from an HTML file by its id. * Uses streaming to avoid loading the entire file into memory. * * @param htmlPath - Absolute path to the HTML file * @param imageId - The id of the image to extract * @returns The base64 data string, or null if not found */ export function extractImageByIdSync( htmlPath: string, imageId: string, ): string | null { const targetTag = `