-
Notifications
You must be signed in to change notification settings - Fork 923
Expand file tree
/
Copy pathplayer.ts
More file actions
815 lines (746 loc) · 27.2 KB
/
player.ts
File metadata and controls
815 lines (746 loc) · 27.2 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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
import { basename, dirname, join, resolve } from 'node:path';
import { assert, ifInBrowser, ifInWorker } from '@midscene/shared/utils';
import { type ZodTypeAny, z } from 'zod';
// previous defined yaml flow, as a helper
interface MidsceneYamlFlowItemAIInput extends LocateOption {
// previous version
// aiInput: string; // value to input
// locate: TUserPrompt; // where to input
aiInput: TUserPrompt | undefined; // where to input
value: string | number; // value to input
}
interface MidsceneYamlFlowItemAIKeyboardPress extends LocateOption {
// previous version
// aiKeyboardPress: string;
// locate?: TUserPrompt; // where to press, optional
aiKeyboardPress: TUserPrompt | undefined; // where to press
keyName: string; // key to press
}
interface MidsceneYamlFlowItemAIScroll extends LocateOption, ScrollParam {
// previous version
// aiScroll: null;
// locate?: TUserPrompt; // which area to scroll, optional
aiScroll: TUserPrompt | undefined; // which area to scroll
}
import type { Agent } from '@/agent/agent';
import type { TUserPrompt } from '@/common';
import type {
DeviceAction,
FreeFn,
LocateOption,
MidsceneYamlFlowItemAIAction,
MidsceneYamlFlowItemAIAssert,
MidsceneYamlFlowItemAIWaitFor,
MidsceneYamlFlowItemEvaluateJavaScript,
MidsceneYamlFlowItemLogScreenshot,
MidsceneYamlFlowItemSleep,
MidsceneYamlScript,
MidsceneYamlScriptEnv,
ScriptPlayerStatusValue,
ScriptPlayerTaskStatus,
ScrollParam,
} from '@/types';
import { getMidsceneRunSubDir } from '@midscene/shared/common';
import { getDebug } from '@midscene/shared/logger';
import {
buildDetailedLocateParam,
buildDetailedLocateParamAndRestParams,
} from './utils';
const debug = getDebug('yaml-player');
const aiTaskHandlerMap = {
aiQuery: 'aiQuery',
aiNumber: 'aiNumber',
aiString: 'aiString',
aiBoolean: 'aiBoolean',
aiAsk: 'aiAsk',
aiLocate: 'aiLocate',
} as const;
type AISimpleTaskKey = keyof typeof aiTaskHandlerMap;
const isStringParamSchema = (schema?: ZodTypeAny): boolean => {
if (!schema) {
return false;
}
const schemaDef = (schema as any)?._def;
if (!schemaDef?.typeName) {
return false;
}
switch (schemaDef.typeName) {
case z.ZodFirstPartyTypeKind.ZodString:
case z.ZodFirstPartyTypeKind.ZodEnum:
case z.ZodFirstPartyTypeKind.ZodNativeEnum:
return true;
case z.ZodFirstPartyTypeKind.ZodLiteral:
return typeof schemaDef.value === 'string';
case z.ZodFirstPartyTypeKind.ZodOptional:
case z.ZodFirstPartyTypeKind.ZodNullable:
case z.ZodFirstPartyTypeKind.ZodDefault:
return isStringParamSchema(schemaDef.innerType);
case z.ZodFirstPartyTypeKind.ZodEffects:
return isStringParamSchema(schemaDef.schema);
case z.ZodFirstPartyTypeKind.ZodPipeline:
return isStringParamSchema(schemaDef.out);
case z.ZodFirstPartyTypeKind.ZodUnion: {
const options = schemaDef.options as ZodTypeAny[] | undefined;
return Array.isArray(options)
? options.every((option) => isStringParamSchema(option))
: false;
}
default:
return false;
}
};
export class ScriptPlayer<T extends MidsceneYamlScriptEnv> {
public currentTaskIndex?: number;
public taskStatusList: ScriptPlayerTaskStatus[] = [];
public status: ScriptPlayerStatusValue = 'init';
public reportFile?: string | null;
public result: Record<string, any>;
private unnamedResultIndex = 0;
public output?: string | null;
public unstableLogContent?: string | null;
public errorInSetup?: Error;
private interfaceAgent: Agent | null = null;
public agentStatusTip?: string;
public target?: MidsceneYamlScriptEnv;
private actionSpace: DeviceAction[] = [];
private scriptPath?: string;
constructor(
private script: MidsceneYamlScript,
private setupAgent: (platform: T) => Promise<{
agent: Agent;
freeFn: FreeFn[];
}>,
public onTaskStatusChange?: (taskStatus: ScriptPlayerTaskStatus) => void,
scriptPath?: string,
) {
this.scriptPath = scriptPath;
this.result = {};
const resolvedAiActContext =
script.agent?.aiActContext ?? script.agent?.aiActionContext;
if (resolvedAiActContext !== undefined && script.agent) {
if (
script.agent.aiActContext === undefined &&
script.agent.aiActionContext !== undefined
) {
console.warn(
'agent.aiActionContext is deprecated, please use agent.aiActContext instead. The legacy name is still accepted for backward compatibility.',
);
}
script.agent.aiActContext = resolvedAiActContext;
}
this.target =
script.target ||
script.web ||
script.android ||
script.ios ||
script.config;
if (ifInBrowser || ifInWorker) {
this.output = undefined;
debug('output is undefined in browser or worker');
} else if (this.target?.output) {
this.output = resolve(process.cwd(), this.target.output);
debug('setting output by config.output', this.output);
} else {
const scriptName = this.scriptPath
? basename(this.scriptPath, '.yaml').replace(/\.(ya?ml)$/i, '')
: 'script';
this.output = join(
getMidsceneRunSubDir('output'),
`${scriptName}-${Date.now()}.json`,
);
debug('setting output by script path', this.output);
}
if (ifInBrowser || ifInWorker) {
this.unstableLogContent = undefined;
} else if (typeof this.target?.unstableLogContent === 'string') {
this.unstableLogContent = resolve(
process.cwd(),
this.target.unstableLogContent,
);
} else if (this.target?.unstableLogContent === true) {
this.unstableLogContent = join(
getMidsceneRunSubDir('output'),
'unstableLogContent.json',
);
}
this.taskStatusList = (script.tasks || []).map((task, taskIndex) => ({
...task,
index: taskIndex,
status: 'init',
totalSteps: task.flow?.length || 0,
}));
}
private setResult(key: string | undefined, value: any) {
const keyToUse = key || this.unnamedResultIndex++;
if (this.result[keyToUse]) {
console.warn(`result key ${keyToUse} already exists, will overwrite`);
}
this.result[keyToUse] = value;
return this.flushResult();
}
private setPlayerStatus(status: ScriptPlayerStatusValue, error?: Error) {
this.status = status;
this.errorInSetup = error;
}
/**
* Build detailed failure context for AI fallback when cached workflow execution fails.
*
* This method constructs a human-readable failure summary with step-by-step breakdown,
* including completed tasks, failed tasks with error details, and pending tasks.
* The generated context is used to inform the AI during fallback execution so it can
* continue from the point of failure without repeating successful steps.
*
* @returns Object containing:
* - `fallbackContext`: Formatted string with detailed failure information for AI context
* - `completedTasks`: Array of successfully completed tasks with their indices and names
* - `failedTasks`: Array of failed tasks with indices, names, errors, and step information
* - `pendingTasks`: Array of tasks that were not executed due to earlier failure
*
* @example
* ```typescript
* // When a workflow fails at step 3:
* const context = player.buildFailureContext();
* // context.fallbackContext will contain:
* // "Previous cached workflow execution failed at step 3/5:
* //
* // Completed successfully:
* // ✓ Step 1/5: "Login to system"
* // ✓ Step 2/5: "Navigate to dashboard"
* //
* // Failed:
* // ✗ Step 3/5: "Click submit button"
* // Error: Element not found
* //
* // Remaining steps (not executed):
* // - Step 4/5: "Verify success message"
* // - Step 5/5: "Logout"
* //
* // Please continue from Step 3 and avoid repeating the successful steps."
* ```
*/
buildFailureContext(): {
fallbackContext: string;
completedTasks: { index: number; name: string }[];
failedTasks: {
index: number;
name: string;
error?: Error;
currentStep?: number;
totalSteps: number;
}[];
pendingTasks: { index: number; name: string }[];
} {
const totalTasks = this.taskStatusList.length;
const completedTasks = this.taskStatusList
.filter((t) => t.status === 'done')
.map((t) => ({ index: t.index, name: t.name }));
const failedTasks = this.taskStatusList
.filter((t) => t.status === 'error')
.map((t) => ({
index: t.index,
name: t.name,
error: t.error,
currentStep: t.currentStep,
totalSteps: t.totalSteps,
}));
const pendingTasks = this.taskStatusList
.filter((t) => t.status === 'init')
.map((t) => ({ index: t.index, name: t.name }));
const parts: string[] = [];
// Title
if (failedTasks.length > 0) {
parts.push(
`Previous cached workflow execution failed at step ${failedTasks[0].index + 1}/${totalTasks}:\n`,
);
} else {
// No specific task failed, but execution was interrupted
parts.push(
`Previous cached workflow execution was interrupted (${completedTasks.length}/${totalTasks} tasks completed).\n`,
);
}
// Completed
if (completedTasks.length > 0) {
parts.push(
'Completed successfully:',
...completedTasks.map(
(t) => ` ✓ Step ${t.index + 1}/${totalTasks}: "${t.name}"`,
),
'',
);
}
// Failed
if (failedTasks.length > 0) {
parts.push(
'Failed:',
...failedTasks.flatMap((t) => {
const stepInfo =
t.currentStep !== undefined
? ` (at substep ${t.currentStep + 1}/${t.totalSteps})`
: '';
return [
` ✗ Step ${t.index + 1}/${totalTasks}: "${t.name}"${stepInfo}`,
` Error: ${t.error?.message || 'Unknown error'}`,
];
}),
'',
);
}
// Pending
if (pendingTasks.length > 0) {
parts.push(
'Remaining steps (not executed):',
...pendingTasks.map(
(t) => ` - Step ${t.index + 1}/${totalTasks}: "${t.name}"`,
),
'',
);
}
// Guidance
if (failedTasks.length > 0) {
parts.push(
`Please continue from Step ${failedTasks[0].index + 1} and avoid repeating the successful steps.`,
);
} else if (pendingTasks.length > 0) {
// No failed tasks but there are pending tasks
parts.push(
`Please continue from Step ${pendingTasks[0].index + 1} and complete the remaining tasks.`,
);
} else {
// All tasks completed but execution still failed (unlikely edge case)
parts.push('Please retry the entire workflow with a different approach.');
}
return {
fallbackContext: parts.join('\n'),
completedTasks,
failedTasks,
pendingTasks,
};
}
private notifyCurrentTaskStatusChange(taskIndex?: number) {
const taskIndexToNotify =
typeof taskIndex === 'number' ? taskIndex : this.currentTaskIndex;
if (typeof taskIndexToNotify !== 'number') {
return;
}
const taskStatus = this.taskStatusList[taskIndexToNotify];
if (this.onTaskStatusChange) {
this.onTaskStatusChange(taskStatus);
}
}
private async setTaskStatus(
index: number,
statusValue: ScriptPlayerStatusValue,
error?: Error,
) {
this.taskStatusList[index].status = statusValue;
if (error) {
this.taskStatusList[index].error = error;
}
this.notifyCurrentTaskStatusChange(index);
}
private setTaskIndex(taskIndex: number) {
this.currentTaskIndex = taskIndex;
}
private flushResult() {
if (this.output) {
const output = resolve(process.cwd(), this.output);
const outputDir = dirname(output);
if (!existsSync(outputDir)) {
mkdirSync(outputDir, { recursive: true });
}
writeFileSync(output, JSON.stringify(this.result || {}, undefined, 2));
}
}
private flushUnstableLogContent() {
if (this.unstableLogContent) {
const content = this.interfaceAgent?._unstableLogContent();
const filePath = resolve(process.cwd(), this.unstableLogContent);
const outputDir = dirname(filePath);
if (!existsSync(outputDir)) {
mkdirSync(outputDir, { recursive: true });
}
writeFileSync(filePath, JSON.stringify(content, null, 2));
}
}
async playTask(taskStatus: ScriptPlayerTaskStatus, agent: Agent) {
const { flow } = taskStatus;
assert(flow, 'missing flow in task');
for (const flowItemIndex in flow) {
const currentStep = Number.parseInt(flowItemIndex, 10);
taskStatus.currentStep = currentStep;
const flowItem = flow[flowItemIndex];
debug(
`playing step ${flowItemIndex}, flowItem=${JSON.stringify(flowItem)}`,
);
const simpleAIKey = (
Object.keys(aiTaskHandlerMap) as AISimpleTaskKey[]
).find((key) => Object.prototype.hasOwnProperty.call(flowItem, key));
if (
'aiAct' in (flowItem as MidsceneYamlFlowItemAIAction) ||
'aiAction' in (flowItem as MidsceneYamlFlowItemAIAction) ||
'ai' in (flowItem as MidsceneYamlFlowItemAIAction)
) {
const actionTask = flowItem as MidsceneYamlFlowItemAIAction;
const { aiAct, aiAction, ai, ...actionOptions } = actionTask;
const prompt = aiAct || aiAction || ai;
assert(prompt, 'missing prompt for ai (aiAct)');
await agent.aiAct(prompt, actionOptions);
} else if ('aiAssert' in (flowItem as MidsceneYamlFlowItemAIAssert)) {
const assertTask = flowItem as MidsceneYamlFlowItemAIAssert;
const prompt = assertTask.aiAssert;
const msg = assertTask.errorMessage;
assert(prompt, 'missing prompt for aiAssert');
const { pass, thought, message } =
(await agent.aiAssert(prompt, msg, {
keepRawResponse: true,
})) || {};
this.setResult(assertTask.name, {
pass,
thought,
message,
});
if (!pass) {
throw new Error(message);
}
} else if (simpleAIKey) {
const {
[simpleAIKey]: prompt,
name,
...options
} = flowItem as Record<string, any>;
assert(prompt, `missing prompt for ${simpleAIKey}`);
const agentMethod = (agent as any)[aiTaskHandlerMap[simpleAIKey]];
assert(
typeof agentMethod === 'function',
`missing agent method for ${simpleAIKey}`,
);
const aiResult = await agentMethod.call(agent, prompt, options);
this.setResult(name, aiResult);
} else if ('aiWaitFor' in (flowItem as MidsceneYamlFlowItemAIWaitFor)) {
const waitForTask = flowItem as MidsceneYamlFlowItemAIWaitFor;
const { aiWaitFor, timeout, ...restWaitForOpts } = waitForTask;
const prompt = aiWaitFor;
assert(prompt, 'missing prompt for aiWaitFor');
const waitForOptions = {
...restWaitForOpts,
...(timeout !== undefined ? { timeout, timeoutMs: timeout } : {}),
};
await agent.aiWaitFor(prompt, waitForOptions);
} else if ('sleep' in (flowItem as MidsceneYamlFlowItemSleep)) {
const sleepTask = flowItem as MidsceneYamlFlowItemSleep;
const ms = sleepTask.sleep;
let msNumber = ms;
if (typeof ms === 'string') {
msNumber = Number.parseInt(ms, 10);
}
assert(
msNumber && msNumber > 0,
`ms for sleep must be greater than 0, but got ${ms}`,
);
await new Promise((resolve) => setTimeout(resolve, msNumber));
} else if (
'javascript' in (flowItem as MidsceneYamlFlowItemEvaluateJavaScript)
) {
const evaluateJavaScriptTask =
flowItem as MidsceneYamlFlowItemEvaluateJavaScript;
const result = await agent.evaluateJavaScript(
evaluateJavaScriptTask.javascript,
);
this.setResult(evaluateJavaScriptTask.name, result);
} else if (
'logScreenshot' in (flowItem as MidsceneYamlFlowItemLogScreenshot) ||
'recordToReport' in (flowItem as MidsceneYamlFlowItemLogScreenshot)
) {
const recordTask = flowItem as MidsceneYamlFlowItemLogScreenshot;
const title =
recordTask.recordToReport ?? recordTask.logScreenshot ?? 'untitled';
const content = recordTask.content || '';
await agent.recordToReport(title, { content });
} else if ('aiInput' in (flowItem as MidsceneYamlFlowItemAIInput)) {
// may be input empty string ''
const {
aiInput,
value: rawValue,
...inputTask
} = flowItem as MidsceneYamlFlowItemAIInput;
// Compatibility with previous version:
// Old format: { aiInput: string (value), locate: TUserPrompt }
// New format - 1: { aiInput: TUserPrompt, value: string | number }
// New format - 2: { aiInput: undefined, locate: TUserPrompt, value: string | number }
let locatePrompt: TUserPrompt | undefined;
let value: string | number | undefined;
if ((inputTask as any).locate) {
// Old format - aiInput is the value, locate is the prompt
// Keep backward compatibility: empty string is treated as no value
value = (aiInput as string | number) || rawValue;
locatePrompt = (inputTask as any).locate;
} else {
// New format - aiInput is the prompt, value is the value
locatePrompt = aiInput || '';
value = rawValue;
}
// Convert value to string for Input action
await agent.callActionInActionSpace('Input', {
...inputTask,
...(value !== undefined ? { value: String(value) } : {}),
...(locatePrompt
? { locate: buildDetailedLocateParam(locatePrompt, inputTask) }
: {}),
});
} else if (
'aiKeyboardPress' in (flowItem as MidsceneYamlFlowItemAIKeyboardPress)
) {
const { aiKeyboardPress, ...keyboardPressTask } =
flowItem as MidsceneYamlFlowItemAIKeyboardPress;
// Compatibility with previous version:
// Old format: { aiKeyboardPress: string (key), locate?: TUserPrompt }
// New format - 1: { aiKeyboardPress: TUserPrompt, keyName: string }
// New format - 2: { aiKeyboardPress: , locate?: TUserPrompt, keyName: string }
let locatePrompt: TUserPrompt | undefined;
let keyName: string | undefined;
if ((keyboardPressTask as any).locate) {
// Old format - aiKeyboardPress is the key, locate is the prompt
keyName = aiKeyboardPress as string;
locatePrompt = (keyboardPressTask as any).locate;
} else if (keyboardPressTask.keyName) {
// New format - aiKeyboardPress is the prompt, key is the key
keyName = keyboardPressTask.keyName;
locatePrompt = aiKeyboardPress;
} else {
keyName = aiKeyboardPress as string;
}
await agent.callActionInActionSpace('KeyboardPress', {
...keyboardPressTask,
...(keyName ? { keyName } : {}),
...(locatePrompt
? {
locate: buildDetailedLocateParam(
locatePrompt,
keyboardPressTask,
),
}
: {}),
});
} else if ('aiScroll' in (flowItem as MidsceneYamlFlowItemAIScroll)) {
const { aiScroll, ...scrollTask } =
flowItem as MidsceneYamlFlowItemAIScroll;
// Compatibility with previous version:
// Old format: { aiScroll: null, locate?: TUserPrompt, direction, scrollType, distance? }
// New format - 1: { aiScroll: TUserPrompt, direction, scrollType, distance? }
// New format - 2: { aiScroll: undefined, locate: TUserPrompt, direction, scrollType, distance? }
const { locate, ...scrollOptions } = scrollTask as any;
const locatePrompt: TUserPrompt | undefined = locate ?? aiScroll;
await agent.aiScroll(locatePrompt, scrollOptions);
} else {
// generic action, find the action in actionSpace
/* for aiTap, aiRightClick, the parameters are a flattened data for the 'locate', these are all valid data
- aiTap: 'search input box'
- aiTap: 'search input box'
deepThink: true
cacheable: false
- aiTap:
prompt: 'search input box'
- aiTap:
prompt: 'search input box'
deepThink: true
cacheable: false
*/
const actionSpace = this.actionSpace;
let locatePromptShortcut: string | undefined;
let actionParamForMatchedAction: unknown;
const matchedAction = actionSpace.find((action) => {
const actionInterfaceAlias = action.interfaceAlias;
if (
actionInterfaceAlias &&
Object.prototype.hasOwnProperty.call(flowItem, actionInterfaceAlias)
) {
actionParamForMatchedAction =
flowItem[actionInterfaceAlias as keyof typeof flowItem];
if (typeof actionParamForMatchedAction === 'string') {
locatePromptShortcut = actionParamForMatchedAction;
}
return true;
}
const keyOfActionInActionSpace = action.name;
if (
Object.prototype.hasOwnProperty.call(
flowItem,
keyOfActionInActionSpace,
)
) {
actionParamForMatchedAction =
flowItem[keyOfActionInActionSpace as keyof typeof flowItem];
if (typeof actionParamForMatchedAction === 'string') {
locatePromptShortcut = actionParamForMatchedAction;
}
return true;
}
return false;
});
assert(
matchedAction,
`unknown flowItem in yaml: ${JSON.stringify(flowItem)}`,
);
const schemaIsStringParam = isStringParamSchema(
matchedAction.paramSchema,
);
let stringParamToCall: string | undefined;
if (
typeof actionParamForMatchedAction === 'string' &&
schemaIsStringParam
) {
if (matchedAction.paramSchema) {
const parseResult = matchedAction.paramSchema.safeParse(
actionParamForMatchedAction,
);
if (parseResult.success && typeof parseResult.data === 'string') {
stringParamToCall = parseResult.data;
} else if (!parseResult.success) {
debug(
`parse failed for action ${matchedAction.name} with string param`,
parseResult.error,
);
stringParamToCall = actionParamForMatchedAction;
}
} else {
stringParamToCall = actionParamForMatchedAction;
}
}
if (stringParamToCall !== undefined) {
debug(
`matchedAction: ${matchedAction.name}`,
`flowParams: ${JSON.stringify(stringParamToCall)}`,
);
const result = await agent.callActionInActionSpace(
matchedAction.name,
stringParamToCall,
);
// Store result if there's a name property in flowItem
const resultName = (flowItem as any).name;
if (result !== undefined) {
this.setResult(resultName, result);
}
} else {
// Determine the source for parameter extraction:
// - If we have a locatePromptShortcut, use the flowItem (for actions like aiTap with prompt)
// - Otherwise, use actionParamForMatchedAction (for actions like runWdaRequest with structured params)
const sourceForParams =
locatePromptShortcut &&
typeof actionParamForMatchedAction === 'string'
? { ...flowItem, prompt: locatePromptShortcut }
: typeof actionParamForMatchedAction === 'object' &&
actionParamForMatchedAction !== null
? actionParamForMatchedAction
: flowItem;
const { locateParam, restParams } =
buildDetailedLocateParamAndRestParams(
locatePromptShortcut || '',
sourceForParams as LocateOption,
[
matchedAction.name,
matchedAction.interfaceAlias || '_never_mind_',
],
);
const flowParams = {
...restParams,
locate: locateParam,
};
debug(
`matchedAction: ${matchedAction.name}`,
`flowParams: ${JSON.stringify(flowParams, null, 2)}`,
);
const result = await agent.callActionInActionSpace(
matchedAction.name,
flowParams,
);
// Store result if there's a name property in flowItem
const resultName = (flowItem as any).name;
if (result !== undefined) {
this.setResult(resultName, result);
}
}
}
}
this.reportFile = agent.reportFile;
await this.flushUnstableLogContent();
}
async run() {
const { target, web, android, ios, tasks } = this.script;
const webEnv = web || target;
const androidEnv = android;
const iosEnv = ios;
const platform = webEnv || androidEnv || iosEnv;
this.setPlayerStatus('running');
let agent: Agent | null = null;
let freeFn: FreeFn[] = [];
try {
const { agent: newAgent, freeFn: newFreeFn } = await this.setupAgent(
platform as T,
);
this.actionSpace = await newAgent.getActionSpace();
agent = newAgent;
const originalOnTaskStartTip = agent.onTaskStartTip;
agent.onTaskStartTip = (tip) => {
if (this.status === 'running') {
this.agentStatusTip = tip;
}
originalOnTaskStartTip?.(tip);
};
freeFn = [
...(newFreeFn || []),
{
name: 'restore-agent-onTaskStartTip',
fn: () => {
if (agent) {
agent.onTaskStartTip = originalOnTaskStartTip;
}
},
},
];
} catch (e) {
this.setPlayerStatus('error', e as Error);
return;
}
this.interfaceAgent = agent;
let taskIndex = 0;
this.setPlayerStatus('running');
let errorFlag = false;
while (taskIndex < tasks.length) {
const taskStatus = this.taskStatusList[taskIndex];
this.setTaskStatus(taskIndex, 'running' as any);
this.setTaskIndex(taskIndex);
try {
await this.playTask(taskStatus, this.interfaceAgent);
this.setTaskStatus(taskIndex, 'done' as any);
} catch (e) {
this.setTaskStatus(taskIndex, 'error' as any, e as Error);
if (taskStatus.continueOnError) {
// nothing more to do
} else {
this.reportFile = agent.reportFile;
errorFlag = true;
break;
}
}
this.reportFile = agent?.reportFile;
taskIndex++;
}
if (errorFlag) {
this.setPlayerStatus('error');
} else {
this.setPlayerStatus('done');
}
this.agentStatusTip = '';
// free the resources
for (const fn of freeFn) {
try {
// console.log('freeing', fn.name);
await fn.fn();
// console.log('freed', fn.name);
} catch (e) {
// console.error('error freeing', fn.name, e);
}
}
}
}