mirror of
https://github.com/software-mansion/argent.git
synced 2026-09-14 19:27:14 +08:00
b8afbed183
Adds end-to-end support for driving **Apple TV (tvOS)** and **Android TV (leanback)** targets through argent, using a focus-driven interaction model (TVs have no touchscreen — interaction is moving a focus highlight with the remote). This PR was reworked after review to **reuse the existing cross-platform tool surface and the `tv-remote` tool from the Vega/Fire TV work (#366)** rather than ship a separate family of `tv-*` tools. ## What this delivers TV targets are driven by the **same cross-platform tools as every other platform**, routed through the existing `dispatchByPlatform` fork mechanism — there are no dedicated `tv-describe`/`tv-navigate`/`tv-type`/`tv-set-focus` tools: - **`describe`** — on a `runtimeKind: "tv"` target, returns the focus-driven view (focused + focusable elements) instead of a tap tree. On Android TV it auto-falls-back to the full `uiautomator` tree when the RN focus engine exposes nothing. - **`tv-remote`** — the cross-platform remote/D-pad tool from #366, now extended with `ios` (Apple TV HID daemon) and `android` (Android TV adb keyevents) branches alongside the existing `vega` branch. Single button, a `repeat`, or a whole path (`["up","right","select"]`) in one call. - **`keyboard`** — types into the focused field on a TV target (named keys are rejected there — they're navigation, which belongs to `tv-remote`). - **`button`** stays hardware-only (phones/tablets); it is not a TV tool. **Apple TV** runs two native daemons (in-sim AX service + host-side HID daemon), shipped via the `argent-private` submodule. **Android TV** reuses the same tool surface, adb-backed (`input keyevent`, `uiautomator dump`, `input text`). ## Remote vocabulary parity `tv-remote` exposes the full 16-button vocabulary (`up`/`down`/`left`/`right`/`select`/`back`/`home`/`menu`/`playPause`/`rewind`/`fastForward`/`next`/`previous`/`volumeUp`/`volumeDown`/`mute`): | | Apple TV | Android TV | Vega | |---|---|---|---| | D-pad / select / back / menu / home / playPause | ✅ | ✅ | ✅ | | media-transport + volume/mute | ❌ rejected | ✅ | ✅ | Media-transport/volume keys **genuinely work on Android TV** (real keycodes — verified live: `volumeUp` moved `STREAM_MUSIC`, `mute` toggled per `dumpsys audio`). On the **Apple TV simulator** they are **rejected with a clear error**: on-device testing confirmed the tvOS sim's HID stack silently drops Consumer-Control events, so returning success would be a lie. ## Key design points - **tvOS UDIDs are UUID-shaped and indistinguishable from iOS by shape.** Handled with `runtimeKind` detection (tvOS runtime string for Apple TV; `pm list features` leanback/television for Android TV — *not* `ro.build.characteristics`, which lies on TV emulators). - Converted launch-app / restart-app / screenshot / screenshot-diff / run-sequence from **eager** to **lazy** service resolution, so a tvOS target never spins up (and hangs on) the iOS-only simulator-server / native-devtools blueprints. - Native injection selects the platform-matched (TVOSSIMULATOR) dylib slice; daemons recycle across sim reboots and app relaunches so injection and focus survive. - SKILL.md footprint minimized per review: the two TV skills were collapsed into a single lean **`argent-tv-interact`** (~40 lines). ## Verification - `npm run build`, ESLint, Prettier, and the full tool-server suite (**1565 tests**) all pass; CI green (incl. the Apple TV / Android TV / Vega e2e jobs). - Core flows verified live against real apps on both an Apple TV 4K simulator and a Google ATV emulator. ## Dependency / merge order Pins the `argent-private` submodule to the tip of its `feat/tv-support` branch (software-mansion/argent-private#20). **Merge that PR to `main` first, then bump the submodule pointer here to the merged SHA before merging this PR.** 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
269 lines
9.7 KiB
TypeScript
269 lines
9.7 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";
|
|
|
|
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,
|
|
hostPath: path.join(dir, "current-diff.png"),
|
|
mimeType: "image/png",
|
|
});
|
|
expect(result.contextDiffPath).toMatchObject({
|
|
__argentArtifact: true,
|
|
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.");
|
|
});
|
|
});
|
|
|
|
async function writePng(
|
|
filePath: string,
|
|
width: number,
|
|
height: number,
|
|
fill: { r: number; g: number; b: number }
|
|
): Promise<void> {
|
|
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;
|
|
}
|
|
}
|
|
|
|
await fs.writeFile(filePath, PNG.sync.write(png));
|
|
}
|