'use client'; import { mousePointer } from '@/utils'; import { paramStr, typeStr } from '@midscene/core/agent'; import { getTaskSearchArea } from '@midscene/core/dump/task-service-dump'; import { getCenterHighlightBox } from './highlight-element'; import type { ExecutionDump, ExecutionTask, ExecutionTaskPlanning, IExecutionDump, IReportActionDump, LocateResultElement, ModelBrief, Rect, ReportActionDump, ScreenshotItem, UIContext, } from '@midscene/core'; // Local type definition for Planning Locate task interface ExecutionTaskPlanningLocate extends ExecutionTask { type: 'Planning'; subType: 'Locate'; output?: { element: LocateResultElement | null; }; uiContext?: UIContext; log?: any; } export interface CameraState { left: number; top: number; width: number; pointerLeft: number; pointerTop: number; } export type TargetCameraState = Omit< CameraState, 'pointerLeft' | 'pointerTop' > & Partial>; export interface AnimationScript { type: | 'img' | 'insight' | 'clear-insight' | 'pointer' | 'spinning-pointer' | 'sleep'; img?: string; camera?: TargetCameraState; context?: UIContext; highlightElement?: LocateResultElement; searchArea?: Rect; duration: number; insightCameraDuration?: number; title?: string; subTitle?: string; imageWidth?: number; imageHeight?: number; taskId?: string; // ID of the associated ExecutionTask for playback synchronization } const stillDuration = 900; const actionSpinningPointerDuration = 300; const stillAfterInsightDuration = 300; const locateDuration = 800; const actionDuration = 500; const clearInsightDuration = 200; const lastFrameDuration = 200; // fit rect to camera export const cameraStateForRect = ( rect: Rect, imageWidth: number, imageHeight: number, ): TargetCameraState => { const canvasRatio = imageWidth / imageHeight; const rectRatio = rect.width / rect.height; let rectWidthOnPage: number; if (rectRatio >= canvasRatio) { rectWidthOnPage = rect.width; } else { rectWidthOnPage = (rect.height / imageHeight) * imageWidth; } const cameraPaddingRatio = rectWidthOnPage > 400 ? 0.1 : rectWidthOnPage > 50 ? 0.2 : 0.3; const cameraWidth = Math.min( imageWidth, rectWidthOnPage + imageWidth * cameraPaddingRatio * 2, ); const cameraHeight = cameraWidth * (imageHeight / imageWidth); let left = Math.min( rect.left - imageWidth * cameraPaddingRatio, imageWidth - cameraWidth, ); left = Math.max(left, 0); let top = Math.min( rect.top - imageHeight * cameraPaddingRatio, imageHeight - cameraHeight, ); top = Math.max(top, 0); return { left: Math.round(left), top: Math.round(top), width: Math.round(cameraWidth), }; }; const createFullPageCameraState = ( imageWidth: number, imageHeight: number, ): TargetCameraState => cameraStateForRect( { left: 0, top: 0, width: imageWidth, height: imageHeight, }, imageWidth, imageHeight, ); const resolveTaskShotSize = ( task: Pick | undefined, fallbackWidth: number, fallbackHeight: number, ): { width: number; height: number } => { const size = task?.uiContext?.shotSize; return { width: size?.width || fallbackWidth, height: size?.height || fallbackHeight, }; }; export const mergeTwoCameraState = ( cameraState1: TargetCameraState, cameraState2: TargetCameraState, ): TargetCameraState => { const newLeft = Math.min(cameraState1.left, cameraState2.left); const newTop = Math.min(cameraState1.top, cameraState2.top); const newRight = Math.max( cameraState1.left + cameraState1.width, cameraState2.left + cameraState2.width, ); const newWidth = newRight - newLeft; return { left: newLeft, top: newTop, width: newWidth, }; }; export interface ReplayScriptsInfo { scripts: AnimationScript[]; width?: number; height?: number; sdkVersion?: string; modelBriefs: ModelBrief[]; deviceType?: string; } const isSameModelBrief = (a: ModelBrief, b: ModelBrief): boolean => { return ( a.intent === b.intent && a.name === b.name && a.modelDescription === b.modelDescription ); }; const pushModelBriefIfNotExists = ( list: ModelBrief[], candidate: ModelBrief, ) => { if (!list.some((brief) => isSameModelBrief(brief, candidate))) { list.push(candidate); } }; type DumpInput = | ReportActionDump | IReportActionDump | ExecutionDump | null | undefined; const normalizeDump = (dump: DumpInput): IReportActionDump | null => { if (!dump) return null; return Array.isArray((dump as ReportActionDump).executions) ? (dump as ReportActionDump) : { sdkVersion: '', groupName: 'Execution', modelBriefs: [], executions: [dump as ExecutionDump], }; }; const sortExecutionsByLogTime = ( executions: Array, ): Array => executions .map((execution, index) => ({ execution, index })) .sort((left, right) => { const leftTime = Number.isFinite(left.execution.logTime) ? left.execution.logTime : Number.POSITIVE_INFINITY; const rightTime = Number.isFinite(right.execution.logTime) ? right.execution.logTime : Number.POSITIVE_INFINITY; return leftTime - rightTime || left.index - right.index; }) .map(({ execution }) => execution); export interface DumpMetaInfo { width: number; height: number; sdkVersion?: string; modelBriefs: ModelBrief[]; deviceType?: string; } /** * Extract lightweight metadata from a normalized dump without reading any .base64 fields. */ const extractMetaFromNormalized = ( normalizedDump: IReportActionDump, ): DumpMetaInfo | null => { let firstWidth: number | undefined; let firstHeight: number | undefined; const sdkVersion = normalizedDump.sdkVersion; const modelBriefs: ModelBrief[] = []; sortExecutionsByLogTime( normalizedDump.executions?.filter(Boolean) || [], ).forEach((execution) => { execution.tasks.forEach((task) => { const shotSize = task.uiContext?.shotSize; if (shotSize) { const w = shotSize.width; const h = shotSize.height; if (!firstWidth) { firstWidth = w; firstHeight = h; } } if (task.usage) { const { model_name, model_description, intent } = task.usage; const brief: ModelBrief = { intent, name: model_name, modelDescription: model_description, }; pushModelBriefIfNotExists(modelBriefs, brief); } }); }); if (!firstWidth || !firstHeight) { console.warn('width or height is missing in dump file'); return null; } return { width: firstWidth, height: firstHeight, sdkVersion, modelBriefs, deviceType: (normalizedDump as IReportActionDump).deviceType, }; }; /** * Extract lightweight metadata from dump without reading any .base64 fields. * Used to set up the UI (dimensions, version, model info) before replay. */ export const extractDumpMetaInfo = (dump: DumpInput): DumpMetaInfo | null => { const normalizedDump = normalizeDump(dump); if (!normalizedDump) return null; return extractMetaFromNormalized(normalizedDump); }; export const allScriptsFromDump = ( dump: DumpInput, ): ReplayScriptsInfo | null => { const normalizedDump = normalizeDump(dump); if (!normalizedDump) { console.warn('[allScriptsFromDump] dump is empty'); return { scripts: [], modelBriefs: [], }; } const metaInfo = extractMetaFromNormalized(normalizedDump); if (!metaInfo) { return { scripts: [], sdkVersion: normalizedDump.sdkVersion, modelBriefs: [], }; } const { width: firstWidth, height: firstHeight } = metaInfo; const allScripts: AnimationScript[] = []; const executions = sortExecutionsByLogTime( normalizedDump.executions?.filter(Boolean) || [], ); for (let execIndex = 0; execIndex < executions.length; execIndex++) { const execution = executions[execIndex]; const scripts = generateAnimationScripts( execution, -1, firstWidth, firstHeight, execIndex, ); if (scripts) { allScripts.push(...scripts); } } const allScriptsWithoutIntermediateDoneFrame = allScripts.filter( (script, index) => { if (index !== allScripts.length - 1 && script.title === 'Done') { return false; } return true; }, ); return { scripts: allScriptsWithoutIntermediateDoneFrame, width: firstWidth, height: firstHeight, sdkVersion: metaInfo.sdkVersion, modelBriefs: metaInfo.modelBriefs, deviceType: metaInfo.deviceType, }; }; export const generateAnimationScripts = ( execution: ExecutionDump | IExecutionDump | null, task: ExecutionTask | number, imageWidth: number, imageHeight: number, executionIndex = 0, ): AnimationScript[] | null => { if (!execution || !execution.tasks.length) return null; if (imageWidth === 0 || imageHeight === 0) { return null; } let tasksIncluded: ExecutionTask[] = []; let taskStartIndex = 0; if (task === -1) { tasksIncluded = execution.tasks; taskStartIndex = 0; } else { // find all tasks before next planning task const startIndex = execution.tasks.findIndex((t) => t === task); if (startIndex === -1) { console.error('task not found, cannot generate animation scripts'); return null; } if (startIndex === execution.tasks.length - 1) { return null; } taskStartIndex = startIndex; for (let i = startIndex; i < execution.tasks.length; i++) { if ( i > startIndex && execution.tasks[i].type === 'Planning' && execution.tasks[i].subType === 'Plan' ) { break; } tasksIncluded.push(execution.tasks[i]); } } if (tasksIncluded.length === 0) { return null; } // Get taskId from the task object const getTaskId = (taskIndex: number): string | undefined => { return tasksIncluded[taskIndex]?.taskId; }; const setPointerScript = ( img: string, title: string, subTitle: string, taskId?: string, ): AnimationScript => { return { type: 'pointer', img, duration: 0, title, subTitle, taskId, }; }; // Restored screenshot refs expose the same base64/capturedAt shape used by ScreenshotItem. type ScreenshotData = Pick | undefined | null; const asScreenshot = (s: unknown): ScreenshotData => s as ScreenshotData; // Helper: create AnimationScript with lazy img getter that defers .base64 read const createScript = ( base: Omit, screenshot: ScreenshotData, ): AnimationScript => { if (!screenshot) return base as AnimationScript; const script = { ...base } as AnimationScript; let cachedImg: string | null = null; Object.defineProperty(script, 'img', { get() { if (cachedImg === null) { cachedImg = screenshot.base64; } return cachedImg; }, enumerable: true, }); return script; }; const scripts: AnimationScript[] = []; let insightCameraState: TargetCameraState | undefined = undefined; // let currentCameraState: TargetCameraState = fullPageCameraState; let insightOnTop = false; let initSubTitle = ''; let errorStateFlag = false; let lastTaskId: string | undefined; tasksIncluded.forEach((task, index) => { const currentTaskId = getTaskId(index); lastTaskId = currentTaskId; // if (errorStateFlag) return; if (index === 0) { initSubTitle = paramStr(task); } if (task.type === 'Planning') { let locateElements: LocateResultElement[] = []; if (task.subType === 'Plan') { const planTask = task as ExecutionTaskPlanning; const actions = planTask.output?.actions || []; if (actions.length > 0) { const action = actions[0]; const knownFields = ['locate', 'start', 'end']; if (action.param) { knownFields.forEach((field) => { if ( action.param[field] && typeof action.param[field] === 'object' && 'center' in (action.param[field] || {}) ) { locateElements.push(action.param[field] as LocateResultElement); } }); for (const key in action.param) { if (knownFields.includes(key)) { continue; } if ( typeof action.param[key] === 'object' && 'center' in (action.param[key] || {}) ) { locateElements.push(action.param[key] as LocateResultElement); } } } } } else if (task.subType === 'Locate' && task.output?.element) { const locateTask = task as ExecutionTaskPlanningLocate; locateElements = [locateTask.output!.element!]; } const title = typeStr(task); const subTitle = paramStr(task); const context = task.uiContext; const contextScreenshot = context?.screenshot; if (context && contextScreenshot) { // show the original screenshot first const { width, height } = resolveTaskShotSize( task, imageWidth, imageHeight, ); scripts.push( createScript( { type: 'img', duration: stillAfterInsightDuration, title, subTitle, imageWidth: width, imageHeight: height, taskId: currentTaskId, }, asScreenshot(contextScreenshot), ), ); locateElements.forEach((element) => { const highlightElement = element; const highlightBox = getCenterHighlightBox(highlightElement); insightCameraState = { ...cameraStateForRect(highlightBox, width, height), pointerLeft: highlightElement.center[0], pointerTop: highlightElement.center[1], }; const newCameraState: TargetCameraState = insightCameraState; scripts.push( createScript( { type: 'insight', context: context, camera: newCameraState, highlightElement, searchArea: getTaskSearchArea(task), duration: locateDuration * 0.5, insightCameraDuration: locateDuration, title, subTitle: highlightElement.description || subTitle, imageWidth: width, imageHeight: height, taskId: currentTaskId, }, asScreenshot(contextScreenshot), ), ); insightOnTop = true; }); } const planningTask = task as ExecutionTaskPlanning; if (planningTask.recorder && planningTask.recorder.length > 0) { const screenshot = planningTask.recorder[0]?.screenshot; const { width, height } = resolveTaskShotSize( task, imageWidth, imageHeight, ); scripts.push( createScript( { type: 'img', duration: stillDuration, title: typeStr(task), subTitle: paramStr(task), imageWidth: width, imageHeight: height, taskId: currentTaskId, }, asScreenshot(screenshot), ), ); } } else if (task.type === 'Action Space') { const title = typeStr(task); const subTitle = paramStr(task); scripts.push({ type: 'spinning-pointer', duration: actionSpinningPointerDuration, title, subTitle, taskId: currentTaskId, }); if (insightOnTop) { // TODO: fine tune the duration scripts.push({ type: 'clear-insight', duration: clearInsightDuration, title, subTitle, taskId: currentTaskId, }); insightOnTop = false; } scripts.push( setPointerScript(mousePointer, title, subTitle, currentTaskId), ); // currentCameraState = insightCameraState ?? fullPageCameraState; // const ifLastTask = index === taskCount - 1; const screenshot = task.recorder?.[0]?.screenshot; const { width, height } = resolveTaskShotSize( task, imageWidth, imageHeight, ); scripts.push( createScript( { type: 'img', duration: actionDuration, camera: task.subType === 'Sleep' ? createFullPageCameraState(width, height) : undefined, title, subTitle, imageWidth: width, imageHeight: height, taskId: currentTaskId, }, asScreenshot(screenshot), ), ); } else { // Handle normal tasks const title = typeStr(task); const subTitle = paramStr(task); const screenshot = task.recorder?.[task.recorder.length - 1]?.screenshot; if (screenshot) { const { width, height } = resolveTaskShotSize( task, imageWidth, imageHeight, ); scripts.push( createScript( { type: 'img', duration: stillDuration, camera: createFullPageCameraState(width, height), title, subTitle, imageWidth: width, imageHeight: height, taskId: currentTaskId, }, asScreenshot(screenshot), ), ); } } if (task.status !== 'finished') { errorStateFlag = true; const errorTitle = typeStr(task); const errorMsg = task.errorMessage || 'unknown error'; const errorSubTitle = errorMsg.indexOf('NOT_IMPLEMENTED_AS_DESIGNED') > 0 ? 'Further actions cannot be performed in the current environment' : errorMsg; const screenshot = task.recorder?.[task.recorder.length - 1]?.screenshot; const { width, height } = resolveTaskShotSize( task, imageWidth, imageHeight, ); scripts.push( createScript( { type: 'img', camera: createFullPageCameraState(width, height), duration: stillDuration, title: errorTitle, subTitle: errorSubTitle, imageWidth: width, imageHeight: height, taskId: currentTaskId, }, asScreenshot(screenshot), ), ); } }); if (insightOnTop) { scripts.push({ type: 'clear-insight', duration: clearInsightDuration, title: '', subTitle: '', taskId: lastTaskId, }); insightOnTop = false; } const lastTaskShotSize = tasksIncluded.length > 0 ? resolveTaskShotSize( tasksIncluded[tasksIncluded.length - 1], imageWidth, imageHeight, ) : { width: imageWidth, height: imageHeight }; scripts.push({ title: 'End', subTitle: initSubTitle, type: 'img', duration: lastFrameDuration, camera: createFullPageCameraState( lastTaskShotSize.width, lastTaskShotSize.height, ), taskId: undefined, // Explicitly set to undefined to clear the playing state }); return scripts; };