Skip to content

Commit 933efaf

Browse files
committed
fix daemon screenshot test adapter ownership
1 parent 03d2a9e commit 933efaf

9 files changed

Lines changed: 71 additions & 45 deletions

File tree

‎packages/daemon/src/__tests__/support/screenshot-command-surface-fake.ts‎

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,4 @@
11
import type { CreateDaemonCommandSurface } from '@agent-device/contracts/daemon-command-surface';
2-
import { resizePngFileToScale } from '@agent-device/capture-kit/png-resize';
3-
import { mkdtempForTestSync } from '@agent-device/test-kit';
4-
import fs from 'node:fs/promises';
5-
import path from 'node:path';
62
import { forwardingCreateCommandSurfaceWithAnnotations } from './command-surface-fake.ts';
73

84
export const screenshotCommandSurface: CreateDaemonCommandSurface = async (config) => {
@@ -12,10 +8,11 @@ export const screenshotCommandSurface: CreateDaemonCommandSurface = async (confi
128
capture: {
139
...forwarded.capture,
1410
screenshot: async (options) => {
15-
const tempDir =
16-
options.out?.kind === 'path' ? undefined : mkdtempForTestSync('agent-device-screenshot-');
17-
const outputPath =
18-
options.out?.kind === 'path' ? options.out.path : path.join(tempDir!, 'screenshot.png');
11+
const reserved = await config.artifacts.reserveOutput(options.out, {
12+
field: 'path',
13+
ext: '.png',
14+
artifactType: 'screenshot',
15+
});
1916
try {
2017
const captured = await config.backend.captureScreenshot?.(
2118
{
@@ -24,7 +21,7 @@ export const screenshotCommandSurface: CreateDaemonCommandSurface = async (confi
2421
appBundleId: options.appBundleId,
2522
signal: options.signal ?? config.signal,
2623
},
27-
outputPath,
24+
reserved.path,
2825
{
2926
fullscreen: options.fullscreen,
3027
overlayRefs: options.overlayRefs,
@@ -34,13 +31,12 @@ export const screenshotCommandSurface: CreateDaemonCommandSurface = async (confi
3431
surface: options.surface,
3532
},
3633
);
37-
if (options.scale !== undefined) await resizePngFileToScale(outputPath, options.scale);
3834
return {
39-
path: outputPath,
35+
path: reserved.path,
4036
...(captured?.displayRotation ? { displayRotation: captured.displayRotation } : {}),
4137
};
4238
} catch (error) {
43-
if (tempDir) await fs.rm(tempDir, { recursive: true, force: true });
39+
await reserved.cleanup?.();
4440
throw error;
4541
}
4642
},

‎packages/daemon/src/execution/screenshot-runtime-execution.test.ts‎

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,7 @@ test('the default destination is a reserved temp file, removed when the capture
195195

196196
await expect(resolved.execute(executionParams(session, req))).rejects.toThrow(/capture failed/);
197197
expect(path.basename(requestedPath ?? '')).toBe('screenshot.png');
198+
expect(path.basename(path.dirname(requestedPath ?? ''))).toContain('agent-device-screenshot-');
198199
expect(fs.existsSync(path.dirname(requestedPath ?? ''))).toBe(false);
199200
});
200201

@@ -257,7 +258,7 @@ const CROP_TREE = [
257258
},
258259
];
259260

260-
test('the crop runs after the platform write and before the shared scale', async () => {
261+
test('the crop runs against the platform screenshot dimensions', async () => {
261262
const fixture = screenshotRuntimeFixture({
262263
snapshotResult: () => ({
263264
nodes: CROP_TREE,
@@ -272,7 +273,7 @@ test('the crop runs after the platform write and before the shared scale', async
272273
);
273274
const req = screenshotRequest({
274275
positionals: [outPath],
275-
flags: { screenshotCropOn: 'label="Save"', screenshotScale: 0.5 },
276+
flags: { screenshotCropOn: 'label="Save"' },
276277
});
277278

278279
const resolved = await resolveScreenshotGenericExecution({
@@ -283,14 +284,11 @@ test('the crop runs after the platform write and before the shared scale', async
283284
inspectFacts: fixture.inspectFacts,
284285
bindDevice: fixture.bindDevice,
285286
});
286-
const result = await executeResult(resolved, session, req, { screenshotScale: 0.5 });
287+
const result = await executeResult(resolved, session, req);
287288

288289
expect(fixture.captureScreenshot).toHaveBeenCalledTimes(1);
289290
expect(fixture.captureSnapshot).toHaveBeenCalledTimes(1);
290-
// The platform wrote 100x50; the pre-scale box is 40x20, so only a crop-then-scale pipeline
291-
// lands on 20x10 — a scale-then-crop pipeline would halve the image first and the same box
292-
// would overflow it.
293-
expect(result).toMatchObject({ width: 20, height: 10 });
291+
expect(result).toMatchObject({ width: 40, height: 20 });
294292
expect(fixture.captureSnapshot.mock.calls[0]?.[0].options).toMatchObject({
295293
interactiveOnly: false,
296294
includeRects: true,

‎packages/daemon/src/server/__tests__/request-router-screenshot.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -347,7 +347,7 @@ test('iOS simulator screenshot omits logical density metadata after --scale down
347347
`agent-device-ios-scale-${Date.now()}.png`,
348348
);
349349
const { handler } = screenshotRouter(makeIosSession('default'), {
350-
onCapture: (input) => writeSolidPng(input.outPath, 804, 1748),
350+
onCapture: (input) => writeSolidPng(input.outPath, 402, 874),
351351
});
352352

353353
const response = await handler({

‎packages/test-kit/src/eager-import-closure-fixtures.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import fs from 'node:fs';
2+
import { createRequire } from 'node:module';
23
import path from 'node:path';
3-
import { parseSync } from 'oxc-parser';
44

55
/**
66
* Eager-import-closure machinery shared by the startup/teardown lazy-seam pins.
@@ -29,7 +29,8 @@ const WORKSPACE_SPECIFIER = /^(@agent-device\/[^/]+)(\/.*)?$/;
2929

3030
type AstNode = { type?: string; [key: string]: unknown };
3131

32-
type ParsedModuleRecord = ReturnType<typeof parseSync>['module'];
32+
type ParsedModuleRecord = ReturnType<typeof import('oxc-parser').parseSync>['module'];
33+
const requireFromTestKit = createRequire(import.meta.url);
3334

3435
/** Static specifiers this file causes to be EVALUATED (not type-only). */
3536
function staticEvaluatedRefs(module: ParsedModuleRecord): string[] {
@@ -118,6 +119,7 @@ export function topLevelStatementCount(fileName: string, source: string): number
118119
type EagerModule = { specifiers: string[]; topLevelStatements: number; statementTexts: string[] };
119120

120121
function parseEagerModule(fileName: string, source: string): EagerModule {
122+
const { parseSync } = requireFromTestKit('oxc-parser') as typeof import('oxc-parser');
121123
const parsed = parseSync(fileName, source);
122124
const dynamic: string[] = [];
123125
collectEagerDynamicImports(parsed.program, true, dynamic);
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import assert from 'node:assert/strict';
2+
import fs from 'node:fs';
3+
import path from 'node:path';
4+
import { PNG } from '@agent-device/capture-kit/png';
5+
import type { AgentDeviceBackend } from '@agent-device/contracts/backend';
6+
import { localCommandPolicy } from '@agent-device/contracts/command-policy';
7+
import { mkdtempForTestSync } from '@agent-device/test-kit';
8+
import { test } from 'vitest';
9+
import { createLocalArtifactAdapter } from '../../../io.ts';
10+
import { createAgentDevice } from '../../../runtime.ts';
11+
12+
test('runtime screenshot applies scale and forwards the capture rotation', async () => {
13+
const outPath = path.join(mkdtempForTestSync('runtime-screenshot-command-'), 'scaled.png');
14+
const device = createAgentDevice({
15+
backend: {
16+
platform: 'ios',
17+
captureScreenshot: async (_context, requestedPath) => {
18+
fs.writeFileSync(requestedPath, solidPngBuffer(100, 50));
19+
return { displayRotation: 'landscape-left' };
20+
},
21+
} satisfies AgentDeviceBackend,
22+
artifacts: createLocalArtifactAdapter(),
23+
sessions: { get: () => undefined, set: () => {} },
24+
policy: localCommandPolicy(),
25+
});
26+
27+
const result = await device.capture.screenshot({
28+
out: { kind: 'path', path: outPath },
29+
scale: 0.5,
30+
});
31+
const scaled = PNG.sync.read(fs.readFileSync(outPath));
32+
33+
assert.deepEqual({ width: scaled.width, height: scaled.height }, { width: 50, height: 25 });
34+
assert.equal(result.displayRotation, 'landscape-left');
35+
});
36+
37+
function solidPngBuffer(width: number, height: number): Buffer {
38+
const png = new PNG({ width, height });
39+
for (let index = 3; index < png.data.length; index += 4) png.data[index] = 255;
40+
return PNG.sync.write(png);
41+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
export function abortWith(signal: AbortSignal | undefined, error: unknown): Promise<never> {
2+
if (!signal) return Promise.reject(new Error('the wait deadline never reached the capture'));
3+
return new Promise((_resolve, reject) => {
4+
const cancel = () => reject(error);
5+
if (signal.aborted) cancel();
6+
else signal.addEventListener('abort', cancel, { once: true });
7+
});
8+
}

‎src/commands/interaction/runtime/wait-absent.test.ts‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { createFakeClock } from './__tests__/test-utils/index.ts';
1313
import { AppError } from '@agent-device/kernel/errors';
1414
import { WAIT_REASONS } from '@agent-device/contracts/wait';
1515
import { createMemorySessionStore } from '../../../command-runtime/runtime-factory.ts';
16+
import { abortWith } from './__tests__/test-utils/abort-with.ts';
1617

1718
const SELECTOR = 'label="Removed"';
1819

@@ -66,12 +67,7 @@ function cancelledAbsentDevice(params: {
6667
captures += 1;
6768
if (captures === 1 && params.firstSnapshot) return params.firstSnapshot;
6869
const signal = context.signal;
69-
if (!signal) throw new Error('the wait deadline never reached the capture');
70-
return await new Promise<never>((_resolve, reject) => {
71-
const cancel = () => reject(params.cancellation);
72-
if (signal.aborted) cancel();
73-
else signal.addEventListener('abort', cancel, { once: true });
74-
});
70+
return await abortWith(signal, params.cancellation);
7571
});
7672
const clock = { now: () => 0, sleep: async (_durationMs: number) => {} };
7773
const device = createAgentDevice({

‎src/commands/interaction/runtime/wait-polling.test.ts‎

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,7 @@ import { SELECTOR_PIPELINE_POLICIES } from '@agent-device/selectors/selector-pip
55
import { AppError } from '@agent-device/kernel/errors';
66
import { WAIT_REASONS, type ReadinessPhase } from '@agent-device/contracts/wait';
77
import { createWaitPolling, waitTimeoutError } from './wait-polling.ts';
8-
9-
function abortWith(signal: AbortSignal, error: unknown): Promise<never> {
10-
return new Promise((_resolve, reject) => {
11-
const cancel = () => reject(error);
12-
if (signal.aborted) cancel();
13-
else signal.addEventListener('abort', cancel, { once: true });
14-
});
15-
}
8+
import { abortWith } from './__tests__/test-utils/abort-with.ts';
169

1710
test('poll delay is bounded by the remaining wait budget', async () => {
1811
let currentMs = 0;

‎src/commands/interaction/runtime/wait-text.test.ts‎

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
selectorReadSnapshot,
1818
} from './__tests__/test-utils/index.ts';
1919
import { createMemorySessionStore } from '../../../command-runtime/runtime-factory.ts';
20+
import { abortWith } from './__tests__/test-utils/abort-with.ts';
2021

2122
function textWaitDevice(params: {
2223
captureSnapshot: NonNullable<AgentDeviceBackend['captureSnapshot']>;
@@ -38,15 +39,6 @@ function textWaitDevice(params: {
3839
});
3940
}
4041

41-
function abortWith(signal: AbortSignal | undefined, error: unknown): Promise<never> {
42-
if (!signal) return Promise.reject(new Error('the wait deadline never reached the capture'));
43-
return new Promise((_resolve, reject) => {
44-
const cancel = () => reject(error);
45-
if (signal.aborted) cancel();
46-
else signal.addEventListener('abort', cancel, { once: true });
47-
});
48-
}
49-
5042
test('runtime wait resolves text from the polled snapshot', async () => {
5143
const captureSnapshot = vi.fn(async (): Promise<BackendSnapshotResult> => ({
5244
snapshot: selectorReadSnapshot(),

0 commit comments

Comments
 (0)