Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,24 @@ jobs:
- name: Setup Puppeteer browser
uses: ./.github/actions/setup-puppeteer-browser

- name: Restore Chromium for Replay tests
id: replay-chromium
uses: ./.github/actions/cache/restore
with:
path: ~/.cache/ms-playwright
key: midscene-replay-chromium-ubuntu22-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}

- name: Install Chromium for Replay tests
if: steps.replay-chromium.outputs.cache-hit != 'true'
run: pnpm --dir packages/replay exec playwright install --with-deps chromium

- name: Save Chromium for Replay tests
if: steps.replay-chromium.outputs.cache-hit != 'true'
uses: ./.github/actions/cache/save
with:
path: ~/.cache/ms-playwright
key: midscene-replay-chromium-ubuntu22-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}

- name: Check tsconfig references
run: pnpm run check:references

Expand Down
51 changes: 36 additions & 15 deletions packages/core/src/agent/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import type { WorkflowExecutionRecord } from '../test-runner/execution-record';
// index.ts -> agent/index.ts -> agent/agent.ts -> index.ts
import {
type AIUsageInfo,
type ActionExecutionOptions,
type ActionParam,
type ActionReturn,
type AgentAIContextKey,
Expand Down Expand Up @@ -51,7 +52,6 @@ import {
} from '../types';
import type { MidsceneYamlScript } from '../yaml';
import {
YamlExecutionOwnershipError,
currentYamlSignal,
enterYamlAction,
enterYamlExecution,
Expand Down Expand Up @@ -95,6 +95,7 @@ import { ActionReadiness, isActionReadinessError } from './action-readiness';
import { normalizeAgentOptions, withAgentDefaults } from './agent-options';
import { AgentReportManager } from './agent-report-manager';
import { normalizeAgentCacheConfig } from './cache-config';
import { isNativeExecutionTerminalError } from './execution-error';
import { FileChooserAccepter } from './file-chooser';
import { Insight } from './insight';
import { MetricsCollector, type MidsceneUsageMetrics } from './metrics';
Expand Down Expand Up @@ -149,6 +150,10 @@ class AgentScopedModelConfigManager extends ModelConfigManager {
createOpenAIClient: this.createOpenAIClient,
};
}

override getUploadTestServerUrl(): string | undefined {
return this.baseManager.getUploadTestServerUrl();
}
}

export type AiActOptions = {
Expand Down Expand Up @@ -849,16 +854,23 @@ export class Agent<InterfaceType extends AbstractInterface = AbstractInterface>
type: string,
opt?: T, // and all other action params
abortSignal?: AbortSignal,
executionOptions?: ActionExecutionOptions,
) {
return this.withReportOperation(() =>
this.executeActionInActionSpace<T>(type, opt, abortSignal),
this.executeActionInActionSpace<T>(
type,
opt,
abortSignal,
executionOptions,
),
);
}

private async executeActionInActionSpace<T>(
type: string,
opt?: T,
abortSignal?: AbortSignal,
executionOptions?: ActionExecutionOptions,
) {
debug('callActionInActionSpace', type, ',', opt);

Expand All @@ -885,16 +897,20 @@ export class Agent<InterfaceType extends AbstractInterface = AbstractInterface>
locateParamStr((opt as any)?.locate || {}),
);

// assume all operation in action space is related to locating
const locateModel = this.resolveModelRuntime('locate', 'locate');
const planningModel = this.resolveModelRuntime('planning', 'planning');

const locate = () => this.resolveModelRuntime('locate', 'locate');
const planning = () => this.resolveModelRuntime('planning', 'planning');
const deferModels = executionOptions?.deferModelResolution;
const locateModel = deferModels ? locate : locate();
const planningModel = deferModels ? planning : planning();
const { output } = await this.taskExecutor.runPlans(
title,
plans,
planningModel,
locateModel,
{ abortSignal: abortSignal ?? currentYamlSignal(this) },
{
abortSignal: abortSignal ?? currentYamlSignal(this),
skipDefaultWait: executionOptions?.skipDefaultWait,
},
);
return output;
}
Expand Down Expand Up @@ -1380,11 +1396,7 @@ export class Agent<InterfaceType extends AbstractInterface = AbstractInterface>
});
return;
} catch (error) {
if (
error instanceof YamlExecutionOwnershipError ||
isActionReadinessError(error)
)
throw error;
if (isNativeExecutionTerminalError(error)) throw error;
abortSignal?.throwIfAborted();
cachedYamlFailed = true;
warn(
Expand Down Expand Up @@ -1550,11 +1562,18 @@ export class Agent<InterfaceType extends AbstractInterface = AbstractInterface>
* when available; otherwise, generate an approximate 8x8 compatibility box.
* Do not rely on rect for strict element boundaries. Prefer center for the target.
*/
async aiLocate(prompt: TUserPrompt, opt?: LocateOption) {
async aiLocate(
prompt: TUserPrompt,
opt?: LocateOption & { abortSignal?: AbortSignal },
) {
return this.withReportOperation(() => this.executeLocate(prompt, opt));
}

private async executeLocate(prompt: TUserPrompt, opt?: LocateOption) {
private async executeLocate(
prompt: TUserPrompt,
opt?: LocateOption & { abortSignal?: AbortSignal },
) {
opt?.abortSignal?.throwIfAborted();
const locateParam = buildDetailedLocateParam(
prompt,
this.withContext('aiLocate', opt),
Expand All @@ -1570,7 +1589,9 @@ export class Agent<InterfaceType extends AbstractInterface = AbstractInterface>
plans,
planningModel,
locateModel,
opt?.uiContext ? { uiContext: opt.uiContext } : undefined,
opt?.uiContext || opt?.abortSignal
? { uiContext: opt.uiContext, abortSignal: opt.abortSignal }
: undefined,
);

const { element } = output;
Expand Down
10 changes: 10 additions & 0 deletions packages/core/src/agent/execution-error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { YamlExecutionOwnershipError } from '../yaml/execution-session';
import { isActionReadinessError } from './action-readiness';

/** Failures that cannot be recovered by trying another native implementation. */
export function isNativeExecutionTerminalError(error: unknown): boolean {
return (
error instanceof YamlExecutionOwnershipError ||
isActionReadinessError(error)
);
}
35 changes: 23 additions & 12 deletions packages/core/src/agent/task-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,17 +110,21 @@ interface BuildOptions {
multimodalPrompt?: TMultimodalPrompt;
deepLocate?: boolean;
abortSignal?: AbortSignal;
skipDefaultWait?: boolean;
}

export type ModelRuntimeSource = ModelRuntime | (() => ModelRuntime);

interface PlanBuildContext {
distanceUnit?: DistanceUnit;
tasks: ExecutionTaskApply[];
planningModel: ModelRuntime;
locateModel: ModelRuntime;
planningModel: ModelRuntimeSource;
locateModel: ModelRuntimeSource;
cacheable?: boolean;
multimodalPrompt?: TMultimodalPrompt;
deepLocate?: boolean;
abortSignal?: AbortSignal;
skipDefaultWait?: boolean;
}

export class TaskBuilder {
Expand Down Expand Up @@ -159,8 +163,8 @@ export class TaskBuilder {

public async build(
plans: PlanningAction[],
planningModel: ModelRuntime,
locateModel: ModelRuntime,
planningModel: ModelRuntimeSource,
locateModel: ModelRuntimeSource,
options?: BuildOptions,
): Promise<{ tasks: ExecutionTaskApply[] }> {
const tasks: ExecutionTaskApply[] = [];
Expand All @@ -175,6 +179,7 @@ export class TaskBuilder {
multimodalPrompt: options?.multimodalPrompt,
deepLocate: options?.deepLocate,
abortSignal: options?.abortSignal,
skipDefaultWait: options?.skipDefaultWait,
};

type PlanHandler = (plan: PlanningAction) => Promise<void> | void;
Expand Down Expand Up @@ -314,10 +319,13 @@ export class TaskBuilder {
}
})();

const useDefaultWait = !this.actionReadiness;
taskContext.task.actionReadiness = useDefaultWait
? 'default'
: 'custom';
const useDefaultWait =
!this.actionReadiness && !context.skipDefaultWait;
taskContext.task.actionReadiness = this.actionReadiness
? 'custom'
: useDefaultWait
? 'default'
: 'none';
abortSignal?.throwIfAborted();

setTimingFieldOnce(timing, 'beforeInvokeActionHookStart');
Expand Down Expand Up @@ -379,8 +387,8 @@ export class TaskBuilder {
parsedParam,
abortSignal,
);
} else {
await this.actionReadiness!.wait(
} else if (this.actionReadiness) {
await this.actionReadiness.wait(
{
id: taskContext.task.taskId,
name: action.name,
Expand Down Expand Up @@ -612,7 +620,7 @@ export class TaskBuilder {
uiContext,
planLocatedElement,
},
locateModel,
typeof locateModel === 'function' ? locateModel() : locateModel,
abortSignal,
);
applyDump(locateResult.dump);
Expand Down Expand Up @@ -681,7 +689,10 @@ export class TaskBuilder {
: locateParam.prompt?.prompt,
modelRuntime: {
...defaultModel,
executionId: locateModel.executionId,
executionId:
typeof locateModel === 'function'
? locateModel().executionId
: locateModel.executionId,
},
},
);
Expand Down
40 changes: 29 additions & 11 deletions packages/core/src/agent/tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ import {
errorMessageForAiAct,
} from './progress';
import { renderAIContext } from './prompt-context';
import { TaskBuilder } from './task-builder';
import { type ModelRuntimeSource, TaskBuilder } from './task-builder';
import type { TaskCache } from './task-cache';
export { locatePlanForLocate } from './task-builder';
import { setTimingFieldOnce } from '@/task-timing';
Expand Down Expand Up @@ -323,14 +323,15 @@ export class TaskExecutor {

public async convertPlanToExecutable(
plans: PlanningAction[],
planningModel: ModelRuntime,
locateModel: ModelRuntime,
planningModel: ModelRuntimeSource,
locateModel: ModelRuntimeSource,
options?: {
distanceUnit?: DistanceUnit;
cacheable?: boolean;
multimodalPrompt?: TMultimodalPrompt;
deepLocate?: boolean;
abortSignal?: AbortSignal;
skipDefaultWait?: boolean;
},
) {
return this.taskBuilder.build(plans, planningModel, locateModel, options);
Expand Down Expand Up @@ -416,23 +417,40 @@ export class TaskExecutor {
async runPlans(
title: string,
plans: PlanningAction[],
planningModel: ModelRuntime,
locateModel: ModelRuntime,
options?: { uiContext?: UIContext; abortSignal?: AbortSignal },
planningModel: ModelRuntimeSource,
locateModel: ModelRuntimeSource,
options?: {
uiContext?: UIContext;
abortSignal?: AbortSignal;
skipDefaultWait?: boolean;
},
): Promise<ExecutionResult> {
const abortSignal = options?.abortSignal ?? this.getAbortSignal?.();
const session = this.createExecutionSession(title, {
...options,
abortSignal,
});
const runner = session.getRunner();
const executionPlanningModel = { ...planningModel, executionId: runner.id };
const executionLocateModel = { ...locateModel, executionId: runner.id };
// Direct actions and resolved locators need no model. Resolve only when a
// task actually falls through to AI, keeping usage tied to this execution.
const forExecution = (source: ModelRuntimeSource): ModelRuntimeSource => {
if (typeof source !== 'function')
return { ...source, executionId: runner.id };
let resolved: ModelRuntime | undefined;
return () => {
resolved ??= { ...source(), executionId: runner.id };
return resolved;
};
};
const { tasks } = await this.convertPlanToExecutable(
plans,
executionPlanningModel,
executionLocateModel,
{ distanceUnit: 'device-logical', abortSignal },
forExecution(planningModel),
forExecution(locateModel),
{
distanceUnit: 'device-logical',
abortSignal,
skipDefaultWait: options?.skipDefaultWait,
},
);
const result = await session.appendAndRun(tasks);
const { output } = result ?? {};
Expand Down
Loading
Loading