-
Notifications
You must be signed in to change notification settings - Fork 945
Expand file tree
/
Copy pathai-fixture.ts
More file actions
693 lines (661 loc) · 18.9 KB
/
ai-fixture.ts
File metadata and controls
693 lines (661 loc) · 18.9 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
import { PlaywrightAgent, type PlaywrightWebPage } from '@/playwright/index';
import type { WebPageAgentOpt } from '@/web-element';
import type { Cache } from '@midscene/core';
import type { Agent as PageAgent } from '@midscene/core/agent';
import { processCacheConfig } from '@midscene/core/utils';
import {
DEFAULT_WAIT_FOR_NAVIGATION_TIMEOUT,
DEFAULT_WAIT_FOR_NETWORK_IDLE_TIMEOUT,
} from '@midscene/shared/constants';
import { getDebug } from '@midscene/shared/logger';
import { uuid } from '@midscene/shared/utils';
import { replaceIllegalPathCharsAndSpace } from '@midscene/shared/utils';
import { type TestInfo, type TestType, test } from '@playwright/test';
import type { Page as OriginPlaywrightPage } from 'playwright';
export type APITestType = Pick<TestType<any, any>, 'step'>;
const debugPage = getDebug('web:playwright:ai-fixture');
const groupAndCaseForTest = (testInfo: TestInfo) => {
let taskFile: string;
let taskTitle: string;
const titlePath = [...testInfo.titlePath];
if (titlePath.length > 1) {
taskFile = titlePath.shift() || 'unnamed';
taskTitle = titlePath.join('__');
} else if (titlePath.length === 1) {
taskTitle = titlePath[0];
taskFile = `${taskTitle}`;
} else {
taskTitle = 'unnamed';
taskFile = 'unnamed';
}
const taskTitleWithRetry = `${taskTitle}${testInfo.retry ? `(retry #${testInfo.retry})` : ''}`;
return {
file: taskFile,
id: replaceIllegalPathCharsAndSpace(`${taskFile}(${taskTitle})`),
title: replaceIllegalPathCharsAndSpace(taskTitleWithRetry),
};
};
const midsceneAgentKeyId = '_midsceneAgentId';
export const midsceneDumpAnnotationId = 'MIDSCENE_DUMP_ANNOTATION';
type AgentRecord = {
agent: PageAgent<PlaywrightWebPage>;
finalizePromise?: Promise<string | undefined>;
finalReportPath?: string;
};
type PlaywrightCacheConfig = {
strategy?: 'read-only' | 'read-write' | 'write-only';
id?: string;
};
type PlaywrightCache = false | true | PlaywrightCacheConfig;
export type PlaywrightAiFixtureOptions = Omit<
WebPageAgentOpt,
| 'testId'
| 'cacheId'
| 'groupName'
| 'groupDescription'
| 'reportFileName'
| 'cache'
> & {
cache?: PlaywrightCache;
};
export const PlaywrightAiFixture = (options?: PlaywrightAiFixtureOptions) => {
const {
forceSameTabNavigation = true,
waitForNetworkIdleTimeout = DEFAULT_WAIT_FOR_NETWORK_IDLE_TIMEOUT,
waitForNavigationTimeout = DEFAULT_WAIT_FOR_NAVIGATION_TIMEOUT,
cache,
...sharedAgentOptions
} = options ?? {};
// Helper function to process cache configuration and auto-generate ID from test info
const processTestCacheConfig = (testInfo: TestInfo): Cache | undefined => {
// Generate ID from test info
const { id } = groupAndCaseForTest(testInfo);
// Use shared processCacheConfig with generated ID as fallback
return processCacheConfig(cache as Cache, id);
};
const pageAgentMap: Record<string, PageAgent<PlaywrightWebPage>> = {};
const testAgentRecords = new Map<string, Map<string, AgentRecord>>();
const getAgentRecordsForTest = (testInfo: TestInfo) => {
let records = testAgentRecords.get(testInfo.testId);
if (!records) {
records = new Map<string, AgentRecord>();
testAgentRecords.set(testInfo.testId, records);
}
return records;
};
const setReportAnnotation = (testInfo: TestInfo, reportPaths: string[]) => {
testInfo.annotations = testInfo.annotations.filter((item) => {
return item.type !== midsceneDumpAnnotationId;
});
for (const reportPath of reportPaths) {
testInfo.annotations.push({
type: midsceneDumpAnnotationId,
description: reportPath,
});
}
};
const finalizeAgentRecord = async (
record: AgentRecord,
): Promise<string | undefined> => {
if (!record.finalizePromise) {
record.finalizePromise = (async () => {
await record.agent.destroy();
const reportPath = record.agent.reportFile || undefined;
record.finalReportPath = reportPath;
return reportPath;
})();
}
return await record.finalizePromise;
};
const createOrReuseAgentForPage = (
page: OriginPlaywrightPage,
testInfo: TestInfo, // { testId: string; taskFile: string; taskTitle: string },
opts?: WebPageAgentOpt,
) => {
let idForPage = (page as any)[midsceneAgentKeyId];
if (!idForPage) {
idForPage = uuid();
(page as any)[midsceneAgentKeyId] = idForPage;
const { testId } = testInfo;
const { file, title } = groupAndCaseForTest(testInfo);
const cacheConfig = processTestCacheConfig(testInfo);
const agent = new PlaywrightAgent(page, {
testId: `playwright-${testId}-${idForPage}`,
reportFileName: `playwright-${testId}-${idForPage}`,
forceSameTabNavigation,
cache: cacheConfig,
groupName: title,
groupDescription: file,
generateReport: true,
...sharedAgentOptions,
...opts,
});
pageAgentMap[idForPage] = agent;
const records = getAgentRecordsForTest(testInfo);
const record: AgentRecord = { agent };
records.set(idForPage, record);
page.on('close', async () => {
debugPage('page closed');
try {
await finalizeAgentRecord(record);
} finally {
delete pageAgentMap[idForPage];
}
});
}
return pageAgentMap[idForPage];
};
async function generateAiFunction(options: {
page: OriginPlaywrightPage;
testInfo: TestInfo;
use: any;
aiActionType:
| 'ai'
| 'aiAct'
| 'aiAction'
| 'aiHover'
| 'aiInput'
| 'aiKeyboardPress'
| 'aiScroll'
| 'aiTap'
| 'aiRightClick'
| 'aiDoubleClick'
| 'aiQuery'
| 'aiAssert'
| 'aiWaitFor'
| 'aiLocate'
| 'aiNumber'
| 'aiString'
| 'aiBoolean'
| 'aiAsk'
| 'runYaml'
| 'setAIActionContext'
| 'evaluateJavaScript'
| 'recordToReport'
| 'logScreenshot'
| 'freezePageContext'
| 'unfreezePageContext';
}) {
const { page, testInfo, use, aiActionType } = options;
const agent = createOrReuseAgentForPage(page, testInfo, {
waitForNavigationTimeout,
waitForNetworkIdleTimeout,
}) as PlaywrightAgent;
await use(async (taskPrompt: string, ...args: any[]) => {
return new Promise((resolve, reject) => {
test.step(`ai-${aiActionType} - ${JSON.stringify(taskPrompt)}`, async () => {
try {
debugPage(
`waitForNetworkIdle timeout: ${waitForNetworkIdleTimeout}`,
);
await agent.waitForNetworkIdle(waitForNetworkIdleTimeout);
} catch (error) {
console.warn(
'[midscene:warning] Waiting for network idle has timed out, but Midscene will continue execution. Please check https://midscenejs.com/faq.html#customize-the-network-timeout for more information on customizing the network timeout',
);
}
try {
type AgentMethod = (
prompt: string,
...restArgs: any[]
) => Promise<any>;
const result = await (agent[aiActionType] as AgentMethod).bind(
agent,
)(taskPrompt, ...args);
resolve(result);
} catch (error) {
reject(error);
}
});
});
});
}
return {
_midsceneFinalizeReports: [
// biome-ignore lint/correctness/noEmptyPattern: Playwright fixture callbacks must use object destructuring for the first parameter even when no fixtures are consumed.
async ({}: Record<string, unknown>, use: any, testInfo: TestInfo) => {
await use();
const records = testAgentRecords.get(testInfo.testId);
if (!records || records.size === 0) {
return;
}
const reportPaths = (
await Promise.all(
Array.from(records.values()).map((record) =>
finalizeAgentRecord(record),
),
)
).filter((reportPath): reportPath is string => Boolean(reportPath));
if (reportPaths.length > 0) {
setReportAnnotation(testInfo, reportPaths);
}
testAgentRecords.delete(testInfo.testId);
},
{ auto: true },
],
agentForPage: async (
{ page }: { page: OriginPlaywrightPage },
use: any,
testInfo: TestInfo,
) => {
await use(
async (
propsPage?: OriginPlaywrightPage | undefined,
opts?: WebPageAgentOpt,
) => {
const cacheConfig = processTestCacheConfig(testInfo);
// Handle cache configuration priority:
// 1. If user provides cache in opts, use it (but auto-generate ID if missing)
// 2. Otherwise use fixture's cache config
let finalCacheConfig = cacheConfig;
if (opts?.cache !== undefined) {
const userCache = opts.cache;
if (userCache === false) {
finalCacheConfig = false;
} else if (userCache === true) {
// Auto-generate ID for user's cache: true
const { id } = groupAndCaseForTest(testInfo);
finalCacheConfig = { id };
} else if (typeof userCache === 'object') {
if (!userCache.id) {
// Auto-generate ID for user's cache object without ID
const { id } = groupAndCaseForTest(testInfo);
finalCacheConfig = { ...userCache, id };
} else {
finalCacheConfig = userCache;
}
}
}
const agent = createOrReuseAgentForPage(propsPage || page, testInfo, {
waitForNavigationTimeout,
waitForNetworkIdleTimeout,
cache: finalCacheConfig,
...opts,
});
return agent;
},
);
},
ai: async (
{ page }: { page: OriginPlaywrightPage },
use: any,
testInfo: TestInfo,
) => {
await generateAiFunction({
page,
testInfo,
use,
aiActionType: 'ai',
});
},
aiAct: async (
{ page }: { page: OriginPlaywrightPage },
use: any,
testInfo: TestInfo,
) => {
await generateAiFunction({
page,
testInfo,
use,
aiActionType: 'aiAct',
});
},
/**
* @deprecated Use {@link PlaywrightAiFixture.aiAct} instead.
*/
aiAction: async (
{ page }: { page: OriginPlaywrightPage },
use: any,
testInfo: TestInfo,
) => {
await generateAiFunction({
page,
testInfo,
use,
aiActionType: 'aiAction',
});
},
aiTap: async (
{ page }: { page: OriginPlaywrightPage },
use: any,
testInfo: TestInfo,
) => {
await generateAiFunction({
page,
testInfo,
use,
aiActionType: 'aiTap',
});
},
aiRightClick: async (
{ page }: { page: OriginPlaywrightPage },
use: any,
testInfo: TestInfo,
) => {
await generateAiFunction({
page,
testInfo,
use,
aiActionType: 'aiRightClick',
});
},
aiDoubleClick: async (
{ page }: { page: OriginPlaywrightPage },
use: any,
testInfo: TestInfo,
) => {
await generateAiFunction({
page,
testInfo,
use,
aiActionType: 'aiDoubleClick',
});
},
aiHover: async (
{ page }: { page: OriginPlaywrightPage },
use: any,
testInfo: TestInfo,
) => {
await generateAiFunction({
page,
testInfo,
use,
aiActionType: 'aiHover',
});
},
aiInput: async (
{ page }: { page: OriginPlaywrightPage },
use: any,
testInfo: TestInfo,
) => {
await generateAiFunction({
page,
testInfo,
use,
aiActionType: 'aiInput',
});
},
aiKeyboardPress: async (
{ page }: { page: OriginPlaywrightPage },
use: any,
testInfo: TestInfo,
) => {
await generateAiFunction({
page,
testInfo,
use,
aiActionType: 'aiKeyboardPress',
});
},
aiScroll: async (
{ page }: { page: OriginPlaywrightPage },
use: any,
testInfo: TestInfo,
) => {
await generateAiFunction({
page,
testInfo,
use,
aiActionType: 'aiScroll',
});
},
aiQuery: async (
{ page }: { page: OriginPlaywrightPage },
use: any,
testInfo: TestInfo,
) => {
await generateAiFunction({
page,
testInfo,
use,
aiActionType: 'aiQuery',
});
},
aiAssert: async (
{ page }: { page: OriginPlaywrightPage },
use: any,
testInfo: TestInfo,
) => {
await generateAiFunction({
page,
testInfo,
use,
aiActionType: 'aiAssert',
});
},
aiWaitFor: async (
{ page }: { page: OriginPlaywrightPage },
use: any,
testInfo: TestInfo,
) => {
await generateAiFunction({
page,
testInfo,
use,
aiActionType: 'aiWaitFor',
});
},
aiLocate: async (
{ page }: { page: OriginPlaywrightPage },
use: any,
testInfo: TestInfo,
) => {
await generateAiFunction({
page,
testInfo,
use,
aiActionType: 'aiLocate',
});
},
aiNumber: async (
{ page }: { page: OriginPlaywrightPage },
use: any,
testInfo: TestInfo,
) => {
await generateAiFunction({
page,
testInfo,
use,
aiActionType: 'aiNumber',
});
},
aiString: async (
{ page }: { page: OriginPlaywrightPage },
use: any,
testInfo: TestInfo,
) => {
await generateAiFunction({
page,
testInfo,
use,
aiActionType: 'aiString',
});
},
aiBoolean: async (
{ page }: { page: OriginPlaywrightPage },
use: any,
testInfo: TestInfo,
) => {
await generateAiFunction({
page,
testInfo,
use,
aiActionType: 'aiBoolean',
});
},
aiAsk: async (
{ page }: { page: OriginPlaywrightPage },
use: any,
testInfo: TestInfo,
) => {
await generateAiFunction({
page,
testInfo,
use,
aiActionType: 'aiAsk',
});
},
runYaml: async (
{ page }: { page: OriginPlaywrightPage },
use: any,
testInfo: TestInfo,
) => {
await generateAiFunction({
page,
testInfo,
use,
aiActionType: 'runYaml',
});
},
setAIActionContext: async (
{ page }: { page: OriginPlaywrightPage },
use: any,
testInfo: TestInfo,
) => {
await generateAiFunction({
page,
testInfo,
use,
aiActionType: 'setAIActionContext',
});
},
evaluateJavaScript: async (
{ page }: { page: OriginPlaywrightPage },
use: any,
testInfo: TestInfo,
) => {
await generateAiFunction({
page,
testInfo,
use,
aiActionType: 'evaluateJavaScript',
});
},
recordToReport: async (
{ page }: { page: OriginPlaywrightPage },
use: any,
testInfo: TestInfo,
) => {
await generateAiFunction({
page,
testInfo,
use,
aiActionType: 'recordToReport',
});
},
logScreenshot: async (
{ page }: { page: OriginPlaywrightPage },
use: any,
testInfo: TestInfo,
) => {
await generateAiFunction({
page,
testInfo,
use,
aiActionType: 'logScreenshot',
});
},
freezePageContext: async (
{ page }: { page: OriginPlaywrightPage },
use: any,
testInfo: TestInfo,
) => {
await generateAiFunction({
page,
testInfo,
use,
aiActionType: 'freezePageContext',
});
},
unfreezePageContext: async (
{ page }: { page: OriginPlaywrightPage },
use: any,
testInfo: TestInfo,
) => {
await generateAiFunction({
page,
testInfo,
use,
aiActionType: 'unfreezePageContext',
});
},
};
};
export type PlayWrightAiFixtureType = {
agentForPage: (
page?: OriginPlaywrightPage,
opts?: WebPageAgentOpt,
) => Promise<PageAgent<PlaywrightWebPage>>;
ai: <T = any>(...args: Parameters<PageAgent['ai']>) => Promise<T>;
aiAct: (
...args: Parameters<PageAgent['aiAct']>
) => ReturnType<PageAgent['aiAct']>;
/**
* @deprecated Use {@link PlayWrightAiFixtureType.aiAct} instead.
*/
aiAction: (
...args: Parameters<PageAgent['aiAction']>
) => ReturnType<PageAgent['aiAction']>;
aiTap: (
...args: Parameters<PageAgent['aiTap']>
) => ReturnType<PageAgent['aiTap']>;
aiRightClick: (
...args: Parameters<PageAgent['aiRightClick']>
) => ReturnType<PageAgent['aiRightClick']>;
aiDoubleClick: (
...args: Parameters<PageAgent['aiDoubleClick']>
) => ReturnType<PageAgent['aiDoubleClick']>;
aiHover: (
...args: Parameters<PageAgent['aiHover']>
) => ReturnType<PageAgent['aiHover']>;
aiInput: (
...args: Parameters<PageAgent['aiInput']>
) => ReturnType<PageAgent['aiInput']>;
aiKeyboardPress: (
...args: Parameters<PageAgent['aiKeyboardPress']>
) => ReturnType<PageAgent['aiKeyboardPress']>;
aiScroll: (
...args: Parameters<PageAgent['aiScroll']>
) => ReturnType<PageAgent['aiScroll']>;
aiQuery: <T = any>(...args: Parameters<PageAgent['aiQuery']>) => Promise<T>;
aiAssert: (
...args: Parameters<PageAgent['aiAssert']>
) => ReturnType<PageAgent['aiAssert']>;
aiWaitFor: (...args: Parameters<PageAgent['aiWaitFor']>) => Promise<void>;
aiLocate: (
...args: Parameters<PageAgent['aiLocate']>
) => ReturnType<PageAgent['aiLocate']>;
aiNumber: (
...args: Parameters<PageAgent['aiNumber']>
) => ReturnType<PageAgent['aiNumber']>;
aiString: (
...args: Parameters<PageAgent['aiString']>
) => ReturnType<PageAgent['aiString']>;
aiBoolean: (
...args: Parameters<PageAgent['aiBoolean']>
) => ReturnType<PageAgent['aiBoolean']>;
aiAsk: (
...args: Parameters<PageAgent['aiAsk']>
) => ReturnType<PageAgent['aiAsk']>;
runYaml: (
...args: Parameters<PageAgent['runYaml']>
) => ReturnType<PageAgent['runYaml']>;
setAIActionContext: (
...args: Parameters<PageAgent['setAIActionContext']>
) => ReturnType<PageAgent['setAIActionContext']>;
evaluateJavaScript: (
...args: Parameters<PageAgent['evaluateJavaScript']>
) => ReturnType<PageAgent['evaluateJavaScript']>;
recordToReport: (
...args: Parameters<PageAgent['recordToReport']>
) => ReturnType<PageAgent['recordToReport']>;
logScreenshot: (
...args: Parameters<PageAgent['logScreenshot']>
) => ReturnType<PageAgent['logScreenshot']>;
freezePageContext: (
...args: Parameters<PageAgent['freezePageContext']>
) => ReturnType<PageAgent['freezePageContext']>;
unfreezePageContext: (
...args: Parameters<PageAgent['unfreezePageContext']>
) => ReturnType<PageAgent['unfreezePageContext']>;
};