Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,56 @@ test('canonical selector projection preserves recursive tree relations', () => {
containsDescendants: [{ text: 'Save', childOf: { id: 'body' } }],
});
});

test('canonicalizes repeat conditions from agent and upstream command shapes', () => {
const program = parseMaestroProgram(
[
'---',
'- repeat:',
' while:',
' platform: Android',
' notVisible: Ready',
' commands: []',
'- repeat:',
' times: 4',
' while:',
' true: "${output.counter < 3}"',
' commands: []',
].join('\n'),
);

expect(canonicalizeAgentCommands(program)).toEqual([
{ kind: 'repeat', while: { platform: 'android', notVisible: { text: 'Ready' } } },
{ kind: 'repeat', times: 4, while: { true: '${output.counter < 3}' } },
]);
expect(
canonicalizeUpstreamFlow([
{
type: 'RepeatCommand',
fields: {
times: null,
condition: {
platform: 'Android',
visible: null,
notVisible: { textRegex: 'Ready' },
scriptCondition: null,
},
},
},
{
type: 'RepeatCommand',
fields: {
times: '4',
condition: {
visible: null,
notVisible: null,
scriptCondition: '${output.counter < 3}',
},
},
},
]),
).toEqual([
{ kind: 'repeat', while: { platform: 'android', notVisible: { text: 'Ready' } } },
{ kind: 'repeat', times: 4, while: { true: '${output.counter < 3}' } },
]);
});
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, test } from 'vitest';
import { isMaestroConditionTruthy } from '../engine-truthiness.ts';
import { isMaestroConditionTruthy, isMaestroScriptResultTruthy } from '../engine-truthiness.ts';

// assertTrue phase 1 (#1295): pin the string-value truthiness table explicitly
// rather than relying on native JS coercion (which would treat every non-empty
Expand Down Expand Up @@ -47,3 +47,19 @@ describe('isMaestroConditionTruthy', () => {
expect(isMaestroConditionTruthy(123)).toBe(true);
});
});

describe('isMaestroScriptResultTruthy', () => {
test.each([
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
['false', false],
['0', false],
[false, false],
[0, false],
[null, false],
[undefined, false],
['true', true],
[1, true],
[{}, true],
])('%j is %s', (value, expected) => {
expect(isMaestroScriptResultTruthy(value)).toBe(expected);
});
});
96 changes: 96 additions & 0 deletions packages/maestro/src/internal/__tests__/engine.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { describe, expect, test, vi } from 'vitest';
import { AppError } from '@agent-device/kernel/errors';
import { maestroTestFailure } from '../compatibility-errors.ts';
import { MAESTRO_COMPATIBILITY_PRESETS } from '../compatibility-policy.ts';
import { parseMaestroProgram } from '../program-ir-parser.ts';
import type {
MaestroObservation,
Expand Down Expand Up @@ -679,6 +680,101 @@ describe('executeMaestroProgram', () => {
).toHaveLength(3);
});

test('repeat while evaluates JavaScript expressions and retains output updates', async () => {
Comment thread
ahmedu007 marked this conversation as resolved.
Resolved
const texts: string[] = [];
const port = makePort({
execute: vi.fn(async (request) => {
if (request.command.kind === 'inputText') texts.push(request.command.text);
request.invalidateObservation();
return {};
}),
});
const program = parseMaestroProgram(
[
'---',
'- evalScript: ${output.counter = 0}',
'- repeat:',
' while:',
' true: "${output.counter < 3}"',
' commands:',
' - inputText: loop',
' - evalScript: ${output.counter++}',
].join('\n'),
);

await executeMaestroProgram(program, port);

expect(texts).toEqual(['loop', 'loop', 'loop']);
});

test('repeat while observes selectors once per iteration and stops when false', async () => {
let checks = 0;
const observe = vi.fn(async ({ generation }: Parameters<MaestroRuntimePort['observe']>[0]) => ({
generation,
matched: ++checks < 3,
}));
const port = makePort({ observe });
const program = parseMaestroProgram(
[
'---',
'- repeat:',
' times: 10',
' while:',
' platform: Android',
' notVisible: ValueX',
' commands:',
' - inputText: loop',
].join('\n'),
);

await executeMaestroProgram(program, port, { platform: 'android' });

expect(port.execute).toHaveBeenCalledTimes(2);
expect(observe).toHaveBeenCalledTimes(3);
expect(observe).toHaveBeenCalledWith(
expect.objectContaining({
condition: { kind: 'notVisible', selector: { text: 'ValueX' } },
timeoutMs: MAESTRO_COMPATIBILITY_PRESETS.command.optionalTargetLookupTimeoutMs,
}),
);
});

test('repeat while stops at the times limit even while its condition remains true', async () => {
const port = makePort();
const program = parseMaestroProgram(
[
'---',
'- repeat:',
' times: 2',
' while:',
' true: true',
' commands:',
' - inputText: loop',
].join('\n'),
);

await executeMaestroProgram(program, port);

expect(port.execute).toHaveBeenCalledTimes(2);
});

test('repeat while expressions are refused for remote untrusted flows', async () => {
const program = parseMaestroProgram(
[
'---',
'- repeat:',
' while:',
' true: "${output.counter < 3}"',
' commands:',
' - inputText: loop',
].join('\n'),
);

await expect(
executeMaestroProgram(program, makePort(), { trustedScripts: false }),
).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
});

test('evalScript replaces output namespace so shrunken arrays drop stale leaves', async () => {
const texts: string[] = [];
const port = makePort({
Expand Down
58 changes: 58 additions & 0 deletions packages/maestro/src/internal/__tests__/program-ir-parser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,64 @@ describe('parseMaestroProgram', () => {
assert.equal(retry.commands[0]?.source.line, 27);
});

test('parses repeat while conditions with an optional times limit', () => {
const program = parseMaestroProgram(
[
'---',
'- repeat:',
' while:',
' platform: Android',
' notVisible: ValueX',
' commands:',
' - tapOn: Button',
'- repeat:',
' times: 4',
' while:',
' true: "${output.counter < 3}"',
' commands:',
' - evalScript: ${output.counter++}',
].join('\n'),
);

assert.deepEqual(program.commands[0], {
kind: 'repeat',
source: { line: 2 },
while: { platform: 'android', notVisible: { text: 'ValueX' } },
commands: [
{
kind: 'tapOn',
source: { line: 7 },
target: { space: 'target', selector: { text: 'Button' } },
},
],
});
assert.deepEqual(program.commands[1], {
kind: 'repeat',
source: { line: 8 },
times: 4,
while: { true: '${output.counter < 3}' },
commands: [{ kind: 'evalScript', source: { line: 13 }, script: '${output.counter++}' }],
});
});

test('requires repeat times or a non-empty while condition', () => {
assert.throws(
() => parseMaestroProgram('---\n- repeat:\n commands: []\n'),
/repeat requires times or while.*line 2/i,
);
assert.throws(
() => parseMaestroProgram('---\n- repeat:\n while: {}\n commands: []\n'),
/repeat\.while cannot be empty.*line 3/i,
);
assert.throws(
() =>
parseMaestroProgram(
'---\n- repeat:\n while:\n unsupported: Android\n commands: []\n',
),
/repeat\.while field "unsupported" is not supported.*line 4/i,
);
});

test('parses flow tags as typed metadata and validates each tag', () => {
const program = parseMaestroProgram(
['name: Pager', 'tags: [smoke, pager]', '---', '- launchApp'].join('\n'),
Expand Down
57 changes: 53 additions & 4 deletions packages/maestro/src/internal/conformance-normalize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@
// differences (regex-vs-literal selector storage, runScript path-vs-content,
// nested runFlow expansion) that the two IR designs express differently.

import type { MaestroCommand, MaestroProgram, MaestroSwipeGesture } from './program-ir.ts';
import type {
MaestroCommand,
MaestroProgram,
MaestroRepeatCondition,
MaestroSwipeGesture,
} from './program-ir.ts';
import { MAESTRO_COMPATIBILITY_PRESETS } from './compatibility-policy.ts';
import { asRecord, bool, dropUndefined, numLike, str } from './conformance-value-coercion.ts';
import {
Expand Down Expand Up @@ -36,6 +41,13 @@ export type CanonicalGesture =
}
| { mode: 'element'; from: CanonicalSelector; direction?: string; duration?: number | string };

type CanonicalRepeatCondition = {
platform?: string;
visible?: CanonicalSelector;
notVisible?: CanonicalSelector;
true?: boolean | string;
};

export type CanonicalCommand =
| {
kind: 'launchApp';
Expand Down Expand Up @@ -85,7 +97,11 @@ export type CanonicalCommand =
| { kind: 'stopApp' }
| { kind: 'setPermissions'; appId?: string; permissions?: Record<string, string> }
| { kind: 'clearState'; appId?: string }
| { kind: 'repeat'; times: string | number }
| {
kind: 'repeat';
times?: string | number;
while?: CanonicalRepeatCondition;
}
| { kind: 'retry'; maxRetries?: string | number }
| { kind: 'runFlow'; label?: string; source: 'file' | 'commands' }
| { kind: 'runScript' }
Expand Down Expand Up @@ -232,7 +248,11 @@ function canonicalizeUpstreamCommand(command: UpstreamCommand): CanonicalCommand
permissions: permissionsRecord(f.permissions),
});
case 'RepeatCommand':
return { kind: 'repeat', times: numLike(f.times) ?? str(f.times) ?? '' };
return dropUndefined({
kind: 'repeat' as const,
times: numLike(f.times) ?? str(f.times),
while: canonicalizeUpstreamRepeatCondition(f.condition),
});
case 'RetryCommand':
return dropUndefined({
kind: 'retry',
Expand All @@ -251,6 +271,19 @@ function canonicalizeUpstreamCommand(command: UpstreamCommand): CanonicalCommand
}
}

function canonicalizeUpstreamRepeatCondition(value: unknown): CanonicalRepeatCondition | undefined {
const condition = asRecord(value);
if (!condition) return undefined;
return dropUndefined({
platform: lower(str(condition.platform)),
visible:
condition.visible == null ? undefined : canonicalizeUpstreamSelector(condition.visible),
notVisible:
condition.notVisible == null ? undefined : canonicalizeUpstreamSelector(condition.notVisible),
true: str(condition.scriptCondition),
});
}

/**
* Build a canonical tap from the effective repeat semantics. `delay` only means
* anything for a repeated tap, so it is dropped for a single tap to keep the two
Expand Down Expand Up @@ -526,7 +559,11 @@ function canonicalizeAgentCommand(
permissions: command.permissions,
});
case 'repeat':
return { kind: 'repeat', times: numLike(command.times) ?? str(command.times) ?? '' };
return dropUndefined({
kind: 'repeat' as const,
times: numLike(command.times) ?? str(command.times),
while: canonicalizeAgentRepeatCondition(command.while),
});
case 'retry':
return dropUndefined({
kind: 'retry',
Expand All @@ -547,6 +584,18 @@ function canonicalizeAgentCommand(
}
}

function canonicalizeAgentRepeatCondition(
condition: MaestroRepeatCondition | undefined,
): CanonicalRepeatCondition | undefined {
if (!condition) return undefined;
return dropUndefined({
platform: condition.platform,
visible: condition.visible && canonicalizeAgentSelector(condition.visible),
notVisible: condition.notVisible && canonicalizeAgentSelector(condition.notVisible),
true: condition.true,
Comment thread
Copilot marked this conversation as resolved.
Resolved
});
}

function agentGesture(gesture: MaestroSwipeGesture): CanonicalGesture {
const duration = numLike(gesture.duration) ?? AGENT_SWIPE_DEFAULT_DURATION;
switch (gesture.kind) {
Expand Down
Loading