Skip to content
Merged
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
1 change: 1 addition & 0 deletions scripts/integration-progress-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@ function summarizeProviderScenarioFlagExclusions() {
'help',
'version',
'verbose',
'cost',
],
},
{
Expand Down
1 change: 1 addition & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@ export async function runCli(argv: string[], deps: CliDeps = DEFAULT_CLI_DEPS):
lockPlatform: binding.defaultPlatform,
cwd: process.cwd(),
debug: debugOutputEnabled,
cost: currentFlags.cost,
});
let parsedBatchSteps: BatchStep[] | undefined;
if (command === 'batch') {
Expand Down
1 change: 1 addition & 0 deletions src/client-normalizers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,7 @@ export function buildMeta(options: InternalRequestOptions): DaemonRequest['meta'
cwd: options.cwd,
sessionExplicit: options.session !== undefined,
debug: options.debug,
includeCost: options.cost,
lockPolicy: options.lockPolicy,
lockPlatform: options.lockPlatform,
...leaseScopeToRequestMeta(leaseScope),
Expand Down
2 changes: 2 additions & 0 deletions src/client-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ export type AgentDeviceClientConfig = RemoteConnectionProfileFields & {
runtime?: SessionRuntimeHints;
cwd?: string;
debug?: boolean;
cost?: boolean;
iosXctestrunFile?: string;
iosXctestDerivedDataPath?: string;
iosXctestEnvDir?: string;
Expand All @@ -95,6 +96,7 @@ export type AgentDeviceRequestOverrides = Pick<
| 'leaseTtlMs'
| 'cwd'
| 'debug'
| 'cost'
| 'iosXctestrunFile'
| 'iosXctestDerivedDataPath'
| 'iosXctestEnvDir'
Expand Down
5 changes: 5 additions & 0 deletions src/contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ export type NetworkIncludeMode = (typeof NETWORK_INCLUDE_MODES)[number];
export type DaemonRequestMeta = {
requestId?: string;
debug?: boolean;
includeCost?: boolean;
cwd?: string;
sessionExplicit?: boolean;
tenantId?: string;
Expand Down Expand Up @@ -101,8 +102,11 @@ export type DaemonArtifact = {
path?: string;
};

export type ResponseCost = { wallClockMs: number };

export type DaemonResponseData = Record<string, unknown> & {
artifacts?: DaemonArtifact[];
cost?: ResponseCost;
};

export type DaemonError = {
Expand Down Expand Up @@ -423,6 +427,7 @@ export const daemonCommandRequestSchema = schema<DaemonRequest>((input, path) =>
: {
requestId: optionalString(meta, 'requestId', `${path}.meta`),
debug: optionalBoolean(meta, 'debug', `${path}.meta`),
includeCost: optionalBoolean(meta, 'includeCost', `${path}.meta`),
cwd: optionalString(meta, 'cwd', `${path}.meta`),
sessionExplicit: optionalBoolean(meta, 'sessionExplicit', `${path}.meta`),
tenantId: optionalString(meta, 'tenantId', `${path}.meta`),
Expand Down
1 change: 1 addition & 0 deletions src/daemon-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ export async function sendToDaemon(req: Omit<DaemonRequest, 'token'>): Promise<D
...(req.meta ?? {}),
requestId,
debug,
includeCost: req.meta?.includeCost,
cwd: req.meta?.cwd,
sessionExplicit: req.meta?.sessionExplicit,
tenantId: req.meta?.tenantId ?? req.flags?.tenant,
Expand Down
157 changes: 157 additions & 0 deletions src/daemon/__tests__/request-router-cost.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import { test, expect, vi, beforeEach } from 'vitest';
import os from 'node:os';
import path from 'node:path';

vi.mock('../../core/dispatch.ts', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../core/dispatch.ts')>();
return { ...actual, dispatchCommand: vi.fn(async () => ({})) };
});

vi.mock('../../platforms/ios/runner-client.ts', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../platforms/ios/runner-client.ts')>();
return { ...actual, stopIosRunnerSession: vi.fn(async () => {}) };
});

vi.mock('../device-ready.ts', () => ({ ensureDeviceReady: vi.fn(async () => {}) }));

import { dispatchCommand } from '../../core/dispatch.ts';
import { createRequestHandler } from '../request-router.ts';
import type { DaemonRequest, SessionState } from '../types.ts';
import { LeaseRegistry } from '../lease-registry.ts';
import { makeSessionStore } from '../../__tests__/test-utils/store-factory.ts';
import { daemonCommandRequestSchema } from '../../contracts.ts';

const mockDispatch = vi.mocked(dispatchCommand);

// A representative, structurally rich daemon payload so the parity assertions
// exercise nested objects/arrays rather than a trivial flat record.
const REPRESENTATIVE_PAYLOAD = {
message: 'home-ok',
detail: { nested: true, count: 3 },
items: [1, 2, 3],
} as const;

function makeIosSession(name: string): SessionState {
return {
name,
createdAt: 1_700_000_000_000,
actions: [],
device: {
platform: 'ios',
target: 'mobile',
id: 'SIM-001',
name: 'iPhone 16',
kind: 'simulator',
booted: true,
simulatorSetPath: '/tmp/tenant-a/set',
},
};
}

function makeHandler(sessionStore = makeSessionStore('agent-device-router-cost-')) {
return {
sessionStore,
handler: createRequestHandler({
logPath: path.join(os.tmpdir(), 'daemon.log'),
token: 'test-token',
sessionStore,
leaseRegistry: new LeaseRegistry(),
trackDownloadableArtifact: () => 'artifact-id',
}),
};
}

function baseRequest(overrides: Partial<DaemonRequest> = {}): DaemonRequest {
return {
token: 'test-token',
session: 'cost-session',
command: 'home',
positionals: [],
flags: {},
...overrides,
};
}

beforeEach(() => {
mockDispatch.mockReset();
mockDispatch.mockImplementation(async () => ({ ...REPRESENTATIVE_PAYLOAD }));
});

test('(a) flag-off identity: meta.includeCost absent === no meta at all, byte-identical and no cost', async () => {
const { sessionStore, handler } = makeHandler();
sessionStore.set('cost-session', makeIosSession('cost-session'));

const respNoMeta = await handler(baseRequest());
const respMetaWithoutCost = await handler(baseRequest({ meta: {} }));

// The serialized wire shape must be identical whether `meta` is omitted or
// present-without-includeCost. This is the Maestro `.ad` recompare invariant.
expect(JSON.stringify(respNoMeta)).toBe(JSON.stringify(respMetaWithoutCost));

expect(respNoMeta.ok).toBe(true);
expect(respMetaWithoutCost.ok).toBe(true);
if (respMetaWithoutCost.ok) {
expect('cost' in (respMetaWithoutCost.data ?? {})).toBe(false);
}
if (respNoMeta.ok) {
expect(respNoMeta.data).toEqual(REPRESENTATIVE_PAYLOAD);
}
});

test('(b) flag-on additive-only: cost.wallClockMs is the ONLY delta vs flag-off', async () => {
const { sessionStore, handler } = makeHandler();
sessionStore.set('cost-session', makeIosSession('cost-session'));

const respFlagOff = await handler(baseRequest());
const respFlagOn = await handler(baseRequest({ meta: { includeCost: true } }));

expect(respFlagOff.ok).toBe(true);
expect(respFlagOn.ok).toBe(true);
if (!respFlagOff.ok || !respFlagOn.ok) return;

const cost = respFlagOn.data?.cost;
expect(typeof cost?.wallClockMs).toBe('number');
expect(cost?.wallClockMs).toBeGreaterThanOrEqual(0);

// Deleting the single added key must leave a payload deep-equal to flag-off.
delete respFlagOn.data?.cost;
expect(respFlagOn.data).toEqual(respFlagOff.data);
});

test('(c) error path: a failing request with includeCost:true produces NO cost', async () => {
const { sessionStore, handler } = makeHandler();
sessionStore.set('cost-session', makeIosSession('cost-session'));

// Conflicting explicit selector under a reject lock policy fails before dispatch.
const failingRequest = baseRequest({
flags: { udid: 'SIM-999' },
meta: { lockPolicy: 'reject', includeCost: true },
});

const errOn = await handler(failingRequest);
expect(errOn.ok).toBe(false);
// The graft is gated on `response.ok`, so an error response is returned
// untouched: it carries an `error` (no `data`) and never a `cost` key.
expect('cost' in errOn).toBe(false);
expect((errOn as { data?: unknown }).data).toBeUndefined();
if (!errOn.ok) {
expect(errOn.error.code).toBe('INVALID_ARGS');
expect('cost' in errOn.error).toBe(false);
}
});

test('(d) boundary survival: meta.includeCost survives daemonCommandRequestSchema parsing', () => {
const parsed = daemonCommandRequestSchema.parse({
command: 'home',
positionals: [],
meta: { includeCost: true },
});
expect(parsed.meta?.includeCost).toBe(true);

const parsedOff = daemonCommandRequestSchema.parse({
command: 'home',
positionals: [],
meta: {},
});
expect(parsedOff.meta?.includeCost).toBeUndefined();
});
11 changes: 10 additions & 1 deletion src/daemon/request-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
} from '../core/dispatch-resolve.ts';
import { AppError, normalizeError } from '../utils/errors.ts';
import { timingSafeStringEqual } from '../utils/timing-safe-equal.ts';
import type { ResponseCost } from '../contracts.ts';
import type { DaemonInvokeFn, DaemonRequest, DaemonResponse } from './types.ts';
import { SessionStore } from './session-store.ts';
import { noActiveSessionError } from './handlers/response.ts';
Expand Down Expand Up @@ -79,8 +80,9 @@ export function createRequestHandler(deps: RequestRouterDeps): DaemonInvokeFn {
const { sessionStore, leaseRegistry } = deps;

async function handleRequest(req: DaemonRequest): Promise<DaemonResponse> {
const start = Date.now();
const debug = Boolean(req.meta?.debug || req.flags?.verbose);
return await withDiagnosticsScope(
const response = await withDiagnosticsScope(
{
session: req.session,
requestId: req.meta?.requestId,
Expand All @@ -107,6 +109,13 @@ export function createRequestHandler(deps: RequestRouterDeps): DaemonInvokeFn {
}
},
);
// Phase 4 (agent-cost) graft: cost is purely additive and opt-in. With the
// flag off — or on an error response — the serialized DaemonResponse is
// byte-identical to today (Maestro `.ad` recompare diffs it). Mirrors the
// conditional `registerDownloadableArtifacts` spread in request-finalization.
if (!req.meta?.includeCost || !response.ok) return response;
const cost: ResponseCost = { wallClockMs: Date.now() - start };
return { ok: true, data: { ...(response.data ?? {}), cost } };
}

async function executeRequestScope(
Expand Down
17 changes: 16 additions & 1 deletion src/utils/cli-flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ export type CliFlags = RemoteConfigMetroOptions &
bundleUrl?: string;
launchUrl?: string;
verbose?: boolean;
cost?: boolean;
snapshotInteractiveOnly?: boolean;
snapshotDiff?: boolean;
snapshotDepth?: number;
Expand Down Expand Up @@ -775,6 +776,13 @@ const FLAG_DEFINITIONS: readonly FlagDefinition[] = [
usageDescription:
'Enable debug diagnostics; test --verbose prints per-test step timings without debug logs',
},
{
key: 'cost',
names: ['--cost'],
type: 'boolean',
usageLabel: '--cost',
usageDescription: 'Include per-command wall-clock latency (cost.wallClockMs) in the response',
},
{
key: 'json',
names: ['--json'],
Expand Down Expand Up @@ -1131,7 +1139,14 @@ export const COMMON_COMMAND_SUPPORTED_FLAG_KEYS = flagKeys(
'noRecord',
);

export const GLOBAL_FLAG_KEYS = new Set<FlagKey>(['json', 'config', 'help', 'version', 'verbose']);
export const GLOBAL_FLAG_KEYS = new Set<FlagKey>([
'json',
'config',
'help',
'version',
'verbose',
'cost',
]);

const flagDefinitionByName = new Map<string, FlagDefinition>();
for (const definition of FLAG_DEFINITIONS) {
Expand Down
Loading