Files
software-mansion__argent/packages/tool-server/test/screenshot-diff-tool.test.ts
Sebastian Flajszer 1e69c90981 feat(ios-device): add physical iOS support (#944)
# Physical iOS device support

Try it now (cabled iPhone, unlocked, Developer Mode on):

```bash
argent run list-devices                                            # copy the 25-char UDID
argent run launch-app --udid <UDID> --bundleId com.apple.Preferences
```

First launch builds and signs the on-device runner: 3 to 5 minutes, keep
the phone unlocked. Every later start: seconds, from cache. No signing
setup needed if an Apple ID is signed into Xcode; the team is detected
from the keychain.

## What this adds

- Physical iPhone support, on by default: a cabled iPhone simply appears
in `list-devices`. iPhone-only: physical iPads are skipped at discovery.
- 15 tools ported to hardware. Flows replay on device.
- Zero-config signing from the keychain; `ARGENT_IOS_TEAM_ID` is an
override, nothing is persisted.
- Self-contained npm install: the runner's Swift sources ship in the
package. New package `@argent/ios-device-runner` (an XCUITest bundle
hosting an HTTP command server on the device), new tool-server backend
under `src/utils/ios-device/`.
- The one always-on cost: `list-devices` on macOS now runs physical
discovery in parallel with the other platform probes, under the existing
8s devicectl timeout; off-macOS it early-returns.

## Suggested review order

Rough estimate: half a day for the full pass.

1. `packages/ios-device-runner/PROTOCOL.md`, then `README.md` (wire
contract and reliability model, ~15 min)
2. `packages/tool-server/src/utils/ios-device/` (devicectl, usbmux,
team-detect, runner-build, runner-commands: the core)
3. `packages/tool-server/src/blueprints/ios-device-runner.ts` (service
lifecycle, crash recovery)
4. Per-tool device arms and the capability gates
(`ios-physical-device-classification.test.ts` is the ratchet)
5. Docs page, the two new skills, the Swift runner sources

## Requirements

1. macOS host with full Xcode (iOS platform installed); uses `xcrun
devicectl` and `xcodebuild`.
2. An Apple ID signed into Xcode; automatic signing mints the runner's
provisioning profile.
3. USB cable only. Wi-Fi is deliberately unsupported: the transport is
usbmux, and a Wi-Fi-only device lists as `paired`, not `connected`.
4. iPhone paired with and trusting the Mac, Developer Mode on, A12/2018
or newer (modern 8+16-hex UDID, the CoreDevice floor). Legacy 40-hex
UDIDs are not classified as iOS.
5. Signing resolves as: `ARGENT_IOS_TEAM_ID` in the tool-server's
environment (explicit override, CI) -> keychain detection (newest
identity first, memoized per server run, never persisted). One
certificate: nothing to do. Several teams: newest wins; the first tool
result names the pick, the runner-ups, and the override. No certificate:
the error walks through Xcode > Settings > Accounts and Manage
Certificates > + > Apple Development, then retry; it never names the env
var, since a team id alone cannot sign. Bundle ids derive per team
(`com.argent.runner.t<teamid>`). `ARGENT_IOS_RUNNER_PROJECT` overrides
the project path for unusual layouts.

Build artifacts cache under `~/.argent/ios-device-runner`, keyed by
runner sources, Xcode/SDK version, and signing. A team with no
registered devices self-heals: the failed generic build retries against
the connected phone, which registers it.

## How it works

1. `xcrun devicectl` (CoreDevice) is the control plane: discovery,
readiness, app lifecycle. Readiness gates on the wired transport, so an
unplugged phone is refused before any build starts.
2. A signed XCUITest runner is built lazily with the resolved team,
started via `xcodebuild test-without-building`, and parks as an HTTP
command server for 24h. On an npm install the Xcode project is the copy
shipped inside the package.
3. The listener binds to the device's loopback interface; the host
reaches it over usbmuxd with a dependency-free `node:net` client.
4. Mutating commands are journaled by `commandId`; a lost reply is
resolved by asking `status` for the journaled fate, never by replay
(at-most-once delivery).
5. Routing hangs off `resolveDevice` UDID-shape classification plus a
per-tool capability allowlist. CLI and MCP layers are untouched; outside
tool-server, docs, and the runner package the diff is failure-code
constants (registry), two agent skills plus rule updates (skills), the
pack step (packages/argent), and the e2e smoke script.

## Supported tools

| Tool | Status | Notes |
| ----------------- | --------- |
------------------------------------------------------------------------------------------------------------------------------------------------------------
|
| launch-app | Supported | Plain `devicectl` launch. System UI
(SpringBoard/Spotlight) registers a session only; no launch attempt.
Carries a note when signing is not resolvable yet. |
| restart-app | Supported | System UI bundle ids rejected before any
device contact. |
| reinstall-app | Supported | Same system UI pre-flight. |
| screenshot | Supported | Served through the runner; device-wide, needs
no registered app. (No host-side devicectl screenshot exists on any
toolchain; that dead route was removed.) |
| describe | Supported | AX tree snapshot via the runner. Snapshots the
session app's process, so another process's dialogs are not in the tree.
A backgrounded session app fails with an actionable error instead of
being silently re-fronted. Focus polling is off for this source; typing
uses a fixed settle. |
| keyboard | Supported | Types into the focused element; typing with
nothing focused is refused with "tap the text field first". `enter` and
`backspace` are the named keys (both exist as software-keyboard
characters; there is no per-keycode HID surface on hardware).
Whitespace-only keys rejected, not silently "typed". |
| gesture-tap | Supported | `clickCount > 1` dispatches as one native
multi-tap gesture, not separate taps. |
| gesture-swipe | Supported | Single-finger drag between two points. |
| gesture-custom | Supported | Two shapes only: press-hold and straight
single-finger drag. Second finger or `Move` waypoints rejected with
authoring guidance, before any runner starts. |
| button | Supported | `home`, `volumeUp`, `volumeDown`, `actionButton`
(volume buttons are simulator-unavailable in the SDK, not
device-unavailable). `power`/`appSwitch` have no public XCUIDevice API
and reject before device contact; a button the model lacks gets a typed
refusal via `hasHardwareButton`. |
| await-ui-element | Supported | Polls the same runner snapshot describe
returns; waits and taps see identical frames. Degrades to `cause:
"unreadable"` with a note on a backgrounded app, never a raw throw. |
| await-screen-idle | Supported | Same describe path; resolves
not-settled instead of throwing, so a follow-up screenshot still runs. |
| run-sequence | Supported | Outer gate only; each step pre-flights its
own capability. |
| open-url | Supported | devicectl launches the receiving app with the
URL as its launch payload. http(s) defaults to Safari; any other scheme
needs the new optional `bundleId` param (hardware cannot resolve a
scheme's handler system-wide). |
| screenshot-diff | Supported | Live captures through the runner
(full-resolution, device-wide, no registered app needed); the diff
itself runs on the host. Baselines are per device model/resolution;
`rotation` is ignored on hardware. |

Flows run through these tools; the device flow tree gets the same
`subtreeText` hoisting as every other platform, so container-scoped
`text` asserts work.

## Not supported (400 at the capability gate)

1. gesture-pinch, gesture-rotate: no two-finger coordinate API on
hardware. Pinch/rotate flow directives also fail upfront with a clear
error.
2. screen-recording-start/stop (video): simulator-only capture pipeline.
3. rotate, paste, shake, settings-permissions: simulator-only backends,
not ported (paste also hits the iOS 16+ cross-app paste permission
prompt).
4. native-devtools, debugger, profiler families: simulator-side
instrumentation (DYLD injection does not exist on hardware).
5. Physical iPads: filtered at discovery for now.

A test ratchet (`ios-physical-device-classification.test.ts`) keeps
`apple.device` declarations in sync with the ported list.

## Core contracts

1. Observation never mutates the screen: a backgrounded session app
makes `describe`/`await-*` fail with an error naming the three ways out
(screenshot, launch-app, or launch-app com.apple.springboard). Mutating
commands do re-front, and their result carries `reactivated: true`.
2. The runner listener is unauthenticated; mitigation is the
loopback-only bind.
3. `list-devices` states: `connected` (cabled now, usable) vs `paired`
(unreachable, never auto-bound). Wired transport alone decides; a
Wi-Fi-migrated CoreDevice tunnel does not count.
4. The multi-team signing pick rides the first affected tool result as a
one-shot note (the pre-existing notes channel). The `list-devices`
result shape is unchanged from main: devices and avds, nothing else.
5. Rejections are typed 400 validation errors end to end, so a batch
flow run skips one failing flow instead of aborting.

Also: the runner is a first-class device-owned service
(`stop-simulator-server` and `stop-all-simulator-servers` reap it,
detached xcodebuild child included; a crashed runner respawns on the
next call). A passcode-locked phone refuses launches; the devicectl
10002 hint also covers a pending system prompt on an unlocked phone.
Build failures surface xcodebuild's own `error:` lines with signing
hints (no registered devices, free-team app-id cap, missing
provisioning, the `errSecInternalComponent` partition-list fix). An app
XCTest reports as `.unknown` (a swipe-killed foreign app) is refused
with launch-app guidance. Status-bar pinning is skipped on hardware;
pixel-settle masks the top band.

## Testing

- Unit coverage, hardware-independent: UDID classification and
capability routing; usbmux framing and transport; devicectl list/hints
parsing incl. the silent iPhone-only filter; keychain detection against
real certificate fixtures; runner build/cache self-heals (poisoned
cache, concurrent checkout, fresh-team retry); crash/journal recovery;
the backgrounded-observation and reactivated contracts; keyboard guards
incl. the not-focused refusal; system-UI pre-flight; per-tool device
arms.
- Manual smoke on a real device: `scripts/e2e-ios-physical-device.mjs`.

## Docs and skills

1. `features/physical-ios-devices.mdx`: the user-facing walkthrough
(zero-config signing with the sign-in fallback, prerequisites,
app-scoped model, troubleshooting).
2. `fundamentals/supported-platforms.mdx`: physical iPhones in the
platform matrix (iPads not supported yet).
3. `reference/tools.mdx` and `reference/configuration.mdx`: list-devices
states and the `ARGENT_IOS_TEAM_ID` override.
4. Two skills ship with the package via `argent init`:
`argent-ios-device-setup` (setup ladder plus a troubleshooting table
keyed to real error texts) and `argent-ios-device-interact` (the
app-scoped hardware contract, supported subset with alternatives,
gesture recipes, pitfalls). The agent rule and sibling skills route to
them.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
  * Added experimental USB-connected physical iPhone support.
* Physical iPhones now support discovery, app lifecycle actions, URL
opening, accessibility snapshots, screenshots, taps, swipes, custom
gestures, keyboard input, waits, flows, and screenshot comparisons.
* Added automatic signing-team detection with optional
`ARGENT_IOS_TEAM_ID` configuration.
* Added clear handling for paired or unavailable devices and unsupported
hardware actions.

* **Documentation**
* Added setup, troubleshooting, capability, and physical-device usage
guidance.
* Clarified that physical iPads and several simulator-only tools and
gestures remain unsupported.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-09-03 14:33:11 +02:00

439 lines
16 KiB
TypeScript

import fs from "fs/promises";
import os from "os";
import path from "path";
import { PNG } from "pngjs";
import { describe, expect, it, vi } from "vitest";
import { ArtifactStore } from "@argent/registry";
import { executeScreenshotDiffTool, screenshotDiffTool } from "../src/tools/screenshot-diff";
import { RUNNER_COMMAND_TIMEOUT_MS } from "../src/utils/ios-device/runner-client";
describe("screenshotDiffTool", () => {
it("rejects public tuning options so defaults stay internal", () => {
const result = screenshotDiffTool.zodSchema!.safeParse({
baselinePath: "/tmp/baseline.png",
currentPath: "/tmp/current.png",
udid: "ABC",
outputDir: "/tmp",
includeTextAnalysis: false,
threshold: 0.2,
textChangeMinConfidence: 0.9,
maxRegions: 3,
});
expect(result.success).toBe(false);
});
it("requires udid and only declares the simulator-server service for live captures", () => {
expect(
screenshotDiffTool.zodSchema!.safeParse({
baselinePath: "/tmp/baseline.png",
currentPath: "/tmp/current.png",
outputDir: "/tmp",
}).success
).toBe(false);
// A pure static-PNG diff needs no SimulatorServer — requesting it
// unconditionally would fail on tvOS sims that have no such backend.
const staticParams = {
baselinePath: "/tmp/baseline.png",
currentPath: "/tmp/current.png",
udid: "ABC",
outputDir: "/tmp",
};
expect(screenshotDiffTool.zodSchema!.safeParse(staticParams).success).toBe(true);
expect(screenshotDiffTool.services(staticParams)).toEqual({});
// A live capture resolves and starts the SimulatorServer for the device.
const liveParams = {
baselinePath: "/tmp/baseline.png",
captureCurrent: true,
udid: "ABC",
outputDir: "/tmp",
};
expect(screenshotDiffTool.zodSchema!.safeParse(liveParams).success).toBe(true);
expect(screenshotDiffTool.services(liveParams)).toEqual({
simulatorServer: {
urn: "SimulatorServer:ABC",
options: {
device: {
id: "ABC",
platform: "android",
// A non-`emulator-*` serial resolves to a physical device.
kind: "device",
},
},
},
});
});
it("returns only the summary and diff artifact paths", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "argent-screenshot-diff-tool-"));
const baselinePath = path.join(dir, "baseline.png");
const currentPath = path.join(dir, "current.png");
await writePng(baselinePath, 2, 2, { r: 10, g: 20, b: 30 });
await writePng(currentPath, 2, 2, { r: 10, g: 20, b: 30 });
const result = await executeScreenshotDiffTool(
{},
{
baselinePath,
currentPath,
udid: "ABC",
outputDir: dir,
},
{ artifacts: new ArtifactStore() }
);
// Diff outputs leave as artifact handles so a remote client can download
// them; hostPath still points at the requested outputDir.
expect(result.summary).toContain("Screenshot diff summary");
expect(result.diffPath).toMatchObject({
__argentArtifact: true,
kind: "screenshot-diff",
hostPath: path.join(dir, "current-diff.png"),
mimeType: "image/png",
});
expect(result.contextDiffPath).toMatchObject({
__argentArtifact: true,
kind: "screenshot-diff-context",
hostPath: path.join(dir, "current-context-diff.png"),
mimeType: "image/png",
});
expect(Object.keys(result).sort()).toEqual(["contextDiffPath", "diffPath", "summary"]);
});
it("captures one live side at full resolution and copies it into outputDir", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "argent-screenshot-diff-live-"));
const baselinePath = path.join(dir, "baseline.png");
const capturedPath = path.join(dir, "captured.png");
await writePng(baselinePath, 2, 2, { r: 0, g: 0, b: 0 });
await writePng(capturedPath, 2, 2, { r: 0, g: 0, b: 0 });
const signal = AbortSignal.timeout(1000);
const captureScreenshot = vi.fn(async () => ({
url: "http://localhost/current.png",
path: capturedPath,
}));
const result = await executeScreenshotDiffTool(
{ simulatorServer: { apiUrl: "http://localhost:4949" } },
{
baselinePath,
captureCurrent: true,
udid: "ABC",
rotation: "LandscapeLeft",
outputDir: dir,
},
{ signal, artifacts: new ArtifactStore() },
captureScreenshot as never
);
expect(captureScreenshot).toHaveBeenCalledWith(
{ apiUrl: "http://localhost:4949" },
"LandscapeLeft",
signal,
1.0
);
const entries = await fs.readdir(dir);
const liveCaptures = entries.filter((name) => /^current-[a-f0-9]{8}\.live\.png$/.test(name));
expect(liveCaptures).toHaveLength(1);
const liveBaseName = path.parse(liveCaptures[0]!).name;
await expect(fs.stat(path.join(dir, liveCaptures[0]!))).resolves.toMatchObject({
size: expect.any(Number),
});
expect(result.diffPath).toMatchObject({
hostPath: path.join(dir, `${liveBaseName}-diff.png`),
});
});
it("falls back to the default scale when the full-resolution capture fails (Android framebuffer mismatch)", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "argent-screenshot-diff-fallback-"));
const baselinePath = path.join(dir, "baseline.png");
const capturedPath = path.join(dir, "captured.png");
await writePng(baselinePath, 2, 2, { r: 0, g: 0, b: 0 });
await writePng(capturedPath, 2, 2, { r: 0, g: 0, b: 0 });
// Full-res (scale 1.0) fails the way the Android simulator-server does;
// the default-scale retry (no scale arg) succeeds.
const captureScreenshot = vi.fn(
async (_api: unknown, _rotation: unknown, _signal: unknown, scale?: number) => {
if (scale === 1.0) {
throw new Error("Screenshot failed: wrong data size, expected 7853760 got 17627328.");
}
return { url: "http://localhost/current.png", path: capturedPath };
}
);
const result = await executeScreenshotDiffTool(
{ simulatorServer: { apiUrl: "http://localhost:4949" } },
{ baselinePath, captureCurrent: true, udid: "ABC", outputDir: dir },
{ artifacts: new ArtifactStore() },
captureScreenshot as never
);
// Full-res attempted first, then a default-scale retry without an explicit scale.
expect(captureScreenshot).toHaveBeenCalledTimes(2);
expect(captureScreenshot.mock.calls[0]![3]).toBe(1.0);
expect(captureScreenshot.mock.calls[1]![3]).toBeUndefined();
const liveCaptures = (await fs.readdir(dir)).filter((name) =>
/^current-[a-f0-9]{8}\.live\.png$/.test(name)
);
expect(liveCaptures).toHaveLength(1);
expect(result.diffPath).toBeTruthy();
});
it("propagates the error when both the full-res capture and the fallback fail", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "argent-screenshot-diff-bothfail-"));
const baselinePath = path.join(dir, "baseline.png");
await writePng(baselinePath, 2, 2, { r: 0, g: 0, b: 0 });
const captureScreenshot = vi.fn(
async (_api: unknown, _rotation: unknown, _signal: unknown, scale?: number) => {
throw new Error(scale === 1.0 ? "full-res failed" : "device offline");
}
);
await expect(
executeScreenshotDiffTool(
{ simulatorServer: { apiUrl: "http://localhost:4949" } },
{ baselinePath, captureCurrent: true, udid: "ABC", outputDir: dir },
{},
captureScreenshot as never
)
).rejects.toThrow("device offline");
expect(captureScreenshot).toHaveBeenCalledTimes(2);
});
it("uses a fresh hashed filename for each live capture so concurrent diffs do not collide", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "argent-screenshot-diff-unique-"));
const baselinePath = path.join(dir, "baseline.png");
const capturedPath = path.join(dir, "captured.png");
await writePng(baselinePath, 2, 2, { r: 0, g: 0, b: 0 });
await writePng(capturedPath, 2, 2, { r: 0, g: 0, b: 0 });
const captureScreenshot = vi.fn(async () => ({
url: "http://localhost/current.png",
path: capturedPath,
}));
await executeScreenshotDiffTool(
{ simulatorServer: { apiUrl: "http://localhost:4949" } },
{ baselinePath, captureCurrent: true, udid: "ABC", outputDir: dir },
{ artifacts: new ArtifactStore() },
captureScreenshot as never
);
await executeScreenshotDiffTool(
{ simulatorServer: { apiUrl: "http://localhost:4949" } },
{ baselinePath, captureCurrent: true, udid: "ABC", outputDir: dir },
{ artifacts: new ArtifactStore() },
captureScreenshot as never
);
const liveCaptures = (await fs.readdir(dir)).filter((name) =>
/^current-[a-f0-9]{8}\.live\.png$/.test(name)
);
expect(liveCaptures).toHaveLength(2);
expect(new Set(liveCaptures).size).toBe(2);
});
it("validates mutually exclusive saved and live inputs at execute time", async () => {
await expect(
executeScreenshotDiffTool(
{},
{
baselinePath: "/tmp/baseline.png",
currentPath: "/tmp/current.png",
captureCurrent: true,
udid: "ABC",
outputDir: "/tmp",
}
)
).rejects.toThrow("Provide either currentPath or captureCurrent, not both.");
});
// The boundary probe reports `presentOnHost: false` for ANY path that does not
// already exist here, so a local agent naming a fresh output directory looked
// exactly like a remote client's own directory and was silently redirected to
// a temp dir. A directory we can create next to an existing parent is ours.
it("creates and honors an outputDir that does not exist yet on this host", async () => {
const parent = await fs.mkdtemp(path.join(os.tmpdir(), "argent-screenshot-diff-fresh-"));
const baselinePath = path.join(parent, "baseline.png");
const currentPath = path.join(parent, "current.png");
await writePng(baselinePath, 2, 2, { r: 10, g: 20, b: 30 });
await writePng(currentPath, 2, 2, { r: 200, g: 20, b: 30 });
const outputDir = path.join(parent, "diff-out");
const result = await executeScreenshotDiffTool(
{},
{ baselinePath, currentPath, udid: "ABC", outputDir },
{
artifacts: new ArtifactStore(),
fileInputs: {
outputDir: { clientPath: outputDir, presentOnHost: false, viaUpload: false },
},
}
);
expect(result.diffPath).toMatchObject({
hostPath: path.join(outputDir, "current-diff.png"),
});
await expect(fs.stat(path.join(outputDir, "current-diff.png"))).resolves.toBeTruthy();
});
// The probe runs before the create, so a directory that appears in between —
// a concurrent diff on the same outputDir, or the agent creating it itself —
// reaches mkdir as EEXIST. That is the directory the caller asked for, not a
// reason to redirect them to a temp dir.
it("honors an outputDir that raced into existence after the probe", async () => {
const parent = await fs.mkdtemp(path.join(os.tmpdir(), "argent-screenshot-diff-race-"));
const baselinePath = path.join(parent, "baseline.png");
const currentPath = path.join(parent, "current.png");
await writePng(baselinePath, 2, 2, { r: 10, g: 20, b: 30 });
await writePng(currentPath, 2, 2, { r: 200, g: 20, b: 30 });
// Exists on disk, but the probe captured the earlier state.
const outputDir = path.join(parent, "diff-out");
await fs.mkdir(outputDir);
const result = await executeScreenshotDiffTool(
{},
{ baselinePath, currentPath, udid: "ABC", outputDir },
{
artifacts: new ArtifactStore(),
fileInputs: {
outputDir: { clientPath: outputDir, presentOnHost: false, viaUpload: false },
},
}
);
expect(result.diffPath).toMatchObject({
hostPath: path.join(outputDir, "current-diff.png"),
});
await expect(fs.stat(path.join(outputDir, "current-diff.png"))).resolves.toBeTruthy();
});
const PHYSICAL_UDID = "00008110-000978540290401E";
it("declares the runner service only for live captures on a physical iPhone", () => {
// A pure file-vs-file diff must not spin up the runner.
expect(
screenshotDiffTool.services({
baselinePath: "/tmp/baseline.png",
currentPath: "/tmp/current.png",
udid: PHYSICAL_UDID,
})
).toEqual({});
expect(
screenshotDiffTool.services({
baselinePath: "/tmp/baseline.png",
captureCurrent: true,
udid: PHYSICAL_UDID,
})
).toEqual({
iosDeviceRunner: {
urn: `IosDeviceRunner:${PHYSICAL_UDID}`,
options: { device: { id: PHYSICAL_UDID, platform: "ios", kind: "device" } },
},
});
});
it("captures the live side through the runner on a physical iPhone and ignores rotation", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "argent-screenshot-diff-device-"));
const baselinePath = path.join(dir, "baseline.png");
await writePng(baselinePath, 2, 2, { r: 10, g: 20, b: 30 });
const run = vi.fn(async () => ({
imageBase64: pngBytes(2, 2, { r: 10, g: 20, b: 30 }).toString("base64"),
}));
const result = await executeScreenshotDiffTool(
{ iosDeviceRunner: { run, udid: PHYSICAL_UDID } },
{
baselinePath,
captureCurrent: true,
udid: PHYSICAL_UDID,
rotation: "LandscapeLeft",
outputDir: dir,
},
{ artifacts: new ArtifactStore() }
);
// The rotation parameter is not forwarded. Hardware captures always follow
// the device's real orientation, the same behaviour as the screenshot tool.
expect(run).toHaveBeenCalledTimes(1);
expect(run).toHaveBeenCalledWith(
{ command: "screenshot" },
{ readOnly: true, timeoutMs: RUNNER_COMMAND_TIMEOUT_MS }
);
const liveCaptures = (await fs.readdir(dir)).filter((name) =>
/^current-[a-f0-9]{8}\.live\.png$/.test(name)
);
expect(liveCaptures).toHaveLength(1);
expect(result.summary).toContain("Screenshot diff summary");
});
it("demands the runner service when a direct caller requests a device live capture", async () => {
await expect(
executeScreenshotDiffTool(
{},
{ baselinePath: "/tmp/baseline.png", captureCurrent: true, udid: PHYSICAL_UDID }
)
).rejects.toThrow("requires an iosDeviceRunner service");
});
// The remote case must still fall back: a client-side path whose parent does
// not exist here cannot be created, so diffs go to a temp dir as before.
it("falls back to a temp dir when outputDir is not creatable on this host", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "argent-screenshot-diff-remote-"));
const baselinePath = path.join(dir, "baseline.png");
const currentPath = path.join(dir, "current.png");
await writePng(baselinePath, 2, 2, { r: 10, g: 20, b: 30 });
await writePng(currentPath, 2, 2, { r: 200, g: 20, b: 30 });
// Parent does not exist on this host — a remote client's own directory.
const outputDir = path.join(dir, "no-such-parent", "nested", "diff-out");
const result = await executeScreenshotDiffTool(
{},
{ baselinePath, currentPath, udid: "ABC", outputDir },
{
artifacts: new ArtifactStore(),
fileInputs: {
outputDir: { clientPath: outputDir, presentOnHost: false, viaUpload: false },
},
}
);
const diffHostPath = (result.diffPath as { hostPath: string }).hostPath;
expect(diffHostPath.startsWith(outputDir)).toBe(false);
expect(diffHostPath).toContain("argent-screenshot-diff");
});
});
function pngBytes(
width: number,
height: number,
fill: { r: number; g: number; b: number }
): Buffer {
const png = new PNG({ width, height });
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const offset = (width * y + x) * 4;
png.data[offset] = fill.r;
png.data[offset + 1] = fill.g;
png.data[offset + 2] = fill.b;
png.data[offset + 3] = 255;
}
}
return PNG.sync.write(png);
}
async function writePng(
filePath: string,
width: number,
height: number,
fill: { r: number; g: number; b: number }
): Promise<void> {
await fs.writeFile(filePath, pngBytes(width, height, fill));
}