Skip to content

Commit 2318126

Browse files
authored
feat(core): allow running in worker (#967)
1 parent d890bfd commit 2318126

File tree

14 files changed

+59
-34
lines changed

14 files changed

+59
-34
lines changed

packages/core/src/ai-model/action-executor.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,8 @@ export class Executor {
152152
taskIndex++;
153153
} catch (e: any) {
154154
successfullyCompleted = false;
155-
task.error =
155+
task.error = e;
156+
task.errorMessage =
156157
e?.message || (typeof e === 'string' ? e : 'error-without-message');
157158
task.errorStack = e.stack;
158159

packages/core/src/types.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -430,7 +430,8 @@ export type ExecutionTask<
430430
: unknown
431431
> & {
432432
status: 'pending' | 'running' | 'finished' | 'failed' | 'cancelled';
433-
error?: string;
433+
error?: Error;
434+
errorMessage?: string;
434435
errorStack?: string;
435436
timing?: {
436437
start: number;

packages/core/src/utils.ts

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,12 @@ import {
1616
} from '@midscene/shared/env';
1717
import { getRunningPkgInfo } from '@midscene/shared/fs';
1818
import { assert, logMsg } from '@midscene/shared/utils';
19-
import { escapeScriptTag, ifInBrowser, uuid } from '@midscene/shared/utils';
19+
import {
20+
escapeScriptTag,
21+
ifInBrowser,
22+
ifInWorker,
23+
uuid,
24+
} from '@midscene/shared/utils';
2025
import type { Rect, ReportDumpWithAttributes } from './types';
2126

2227
let logEnvReady = false;
@@ -132,7 +137,7 @@ export function writeDumpReport(
132137
dumpData: string | ReportDumpWithAttributes,
133138
appendReport?: boolean,
134139
): string | null {
135-
if (ifInBrowser) {
140+
if (ifInBrowser || ifInWorker) {
136141
console.log('will not write report in browser');
137142
return null;
138143
}
@@ -179,7 +184,7 @@ export function writeLogFile(opts: {
179184
generateReport?: boolean;
180185
appendReport?: boolean;
181186
}) {
182-
if (ifInBrowser) {
187+
if (ifInBrowser || ifInWorker) {
183188
return '/mock/report.html';
184189
}
185190
const { fileName, fileExt, fileContent, type = 'dump' } = opts;
@@ -242,7 +247,7 @@ export function getTmpDir(): string | null {
242247
}
243248

244249
export function getTmpFile(fileExtWithoutDot: string): string | null {
245-
if (ifInBrowser) {
250+
if (ifInBrowser || ifInWorker) {
246251
return null;
247252
}
248253
const tmpDir = getTmpDir();

packages/shared/src/img/get-jimp.ts

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
11
// @ts-ignore
2-
import type Jimp from 'jimp/browser/lib/jimp.js';
2+
import Jimp from 'jimp';
3+
import { ifInBrowser, ifInWorker } from '../utils';
34

4-
const ifInBrowser = typeof window !== 'undefined';
55
export default async function getJimp(): Promise<typeof Jimp> {
6-
if (ifInBrowser) {
6+
if (ifInBrowser || ifInWorker) {
77
// @ts-ignore
88
await import('jimp/browser/lib/jimp.js');
9-
return (window as any).Jimp;
9+
return (typeof window !== 'undefined' ? window : (self as any)).Jimp;
1010
}
11-
// return Jimp;
12-
// @ts-ignore
13-
return (await import('jimp')).default;
11+
return Jimp;
1412
}

packages/shared/src/node/fs.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { existsSync, readFileSync } from 'node:fs';
22
import { dirname, join } from 'node:path';
3-
import { ifInBrowser } from '../utils';
3+
import { ifInBrowser, ifInWorker } from '../utils';
44

55
declare const __HTML_ELEMENT_SCRIPT__: string;
66

@@ -13,7 +13,7 @@ interface PkgInfo {
1313
const pkgCacheMap: Record<string, PkgInfo> = {};
1414

1515
export function getRunningPkgInfo(dir?: string): PkgInfo | null {
16-
if (ifInBrowser) {
16+
if (ifInBrowser || ifInWorker) {
1717
return null;
1818
}
1919
const dirToCheck = dir || process.cwd();
@@ -71,7 +71,7 @@ export function getElementInfosScriptContent() {
7171
}
7272

7373
export async function getExtraReturnLogic(tree = false) {
74-
if (ifInBrowser) {
74+
if (ifInBrowser || ifInWorker) {
7575
return null;
7676
}
7777

packages/shared/src/utils.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
import { sha256 } from 'js-sha256';
22

3+
declare const WorkerGlobalScope: any;
4+
35
export const ifInBrowser = typeof window !== 'undefined';
6+
export const ifInWorker = typeof WorkerGlobalScope !== 'undefined';
47

58
export function uuid(): string {
69
return Math.random().toString(36).substring(2, 15);

packages/visualizer/src/component/replay-scripts.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -415,7 +415,7 @@ export const generateAnimationScripts = (
415415
if (task.status !== 'finished') {
416416
errorStateFlag = true;
417417
const errorTitle = typeStr(task);
418-
const errorMsg = task.error || 'unknown error';
418+
const errorMsg = task.errorMessage || 'unknown error';
419419
const errorSubTitle =
420420
errorMsg.indexOf('NOT_IMPLEMENTED_AS_DESIGNED') > 0
421421
? 'Further actions cannot be performed in the current environment'

packages/web-integration/src/chrome-extension/dynamic-scripts.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
import fs from 'node:fs';
2-
import { ifInBrowser } from '@midscene/shared/utils';
2+
import { ifInBrowser, ifInWorker } from '@midscene/shared/utils';
33

44
// remember to include this file into extension's package
55
// extract html element from page
66
let scriptFileContentCache: string | null = null;
77
export const getHtmlElementScript = async () => {
88
const scriptFileToRetrieve = chrome.runtime.getURL('scripts/htmlElement.js');
99
if (scriptFileContentCache) return scriptFileContentCache;
10-
if (ifInBrowser) {
10+
if (ifInBrowser || ifInWorker) {
1111
const script = await fetch(scriptFileToRetrieve);
1212
scriptFileContentCache = await script.text();
1313
return scriptFileContentCache;
@@ -22,7 +22,7 @@ export const injectWaterFlowAnimation = async () => {
2222
'scripts/water-flow.js',
2323
);
2424
if (waterFlowScriptFileContentCache) return waterFlowScriptFileContentCache;
25-
if (ifInBrowser) {
25+
if (ifInBrowser || ifInWorker) {
2626
const script = await fetch(waterFlowScriptFileToRetrieve);
2727
waterFlowScriptFileContentCache = await script.text();
2828
return waterFlowScriptFileContentCache;
@@ -38,7 +38,7 @@ export const injectStopWaterFlowAnimation = async () => {
3838
);
3939
if (stopWaterFlowScriptFileContentCache)
4040
return stopWaterFlowScriptFileContentCache;
41-
if (ifInBrowser) {
41+
if (ifInBrowser || ifInWorker) {
4242
const script = await fetch(stopWaterFlowScriptFileToRetrieve);
4343
stopWaterFlowScriptFileContentCache = await script.text();
4444
return stopWaterFlowScriptFileContentCache;

packages/web-integration/src/chrome-extension/page.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ export default class ChromeExtensionProxyPage implements AbstractPage {
4444

4545
private isMobileEmulation: boolean | null = null;
4646

47+
public _continueWhenFailedToAttachDebugger = false;
48+
4749
constructor(forceSameTabNavigation: boolean) {
4850
this.forceSameTabNavigation = forceSameTabNavigation;
4951
}
@@ -143,7 +145,19 @@ export default class ChromeExtensionProxyPage implements AbstractPage {
143145

144146
// detach any debugger attached to the tab
145147
console.log('attaching debugger', currentTabId);
146-
await chrome.debugger.attach({ tabId: currentTabId }, '1.3');
148+
try {
149+
await chrome.debugger.attach({ tabId: currentTabId }, '1.3');
150+
} catch (e) {
151+
if (this._continueWhenFailedToAttachDebugger) {
152+
console.warn(
153+
'Failed to attach debugger, but the script will continue as if the debugger is attached since the _continueWhenFailedToAttachDebugger is true',
154+
e,
155+
);
156+
} else {
157+
throw e;
158+
}
159+
}
160+
147161
// wait util the debugger banner in Chrome appears
148162
await sleep(500);
149163

packages/web-integration/src/common/agent.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,9 @@ export class PageAgent<PageType extends WebPage = WebPage> {
265265

266266
if (executor.isInErrorState() && !doNotThrowError) {
267267
const errorTask = executor.latestErrorTask();
268-
throw new Error(`${errorTask?.error}\n${errorTask?.errorStack}`);
268+
throw new Error(`${errorTask?.errorMessage}\n${errorTask?.errorStack}`, {
269+
cause: errorTask?.error,
270+
});
269271
}
270272
}
271273

0 commit comments

Comments
 (0)