Files
Mateusz Ścianek b8afbed183 feat(tv): Apple TV (tvOS) and Android TV support (#374)
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>
2026-07-01 14:59:37 +02:00

359 lines
12 KiB
TypeScript

import { describe, it, expect, vi } from "vitest";
import type { Registry, ToolContext } from "@argent/registry";
import { createRunSequenceTool } from "../src/tools/run-sequence";
// A minimal registry stub: records every invokeTool call and returns a marker.
function makeMockRegistry() {
const calls: Array<{ tool: string; args: Record<string, unknown> }> = [];
const registry = {
invokeTool: vi.fn(async (tool: string, args: Record<string, unknown>) => {
calls.push({ tool, args });
return { ok: true };
}),
// The execute body pre-flights each step's capability via getTool; these
// tvOS/test tools aren't registered in the stub, so undefined (→ skip the
// capability gate) is the right answer here.
getTool: vi.fn(() => undefined),
} as any;
return { registry, calls };
}
function mockRegistry(invokeImpl?: (id: string, args: unknown) => unknown): Registry {
return {
// No capability declared → run-sequence skips the per-step assertSupported.
getTool: vi.fn(() => undefined),
invokeTool: vi.fn(async (id: string, args: unknown) => invokeImpl?.(id, args) ?? { ok: true }),
} as unknown as Registry;
}
const TVOS_UDID = "DDDDDDDD-DDDD-DDDD-DDDD-DDDDDDDDDDDD";
// iOS-shaped udid so `resolveDevice` classifies it as an iOS simulator without
// touching a real device (classification is purely shape-based).
const IOS = "11111111-1111-1111-1111-111111111111";
describe("run-sequence", () => {
it("allows TV steps and dispatches them in order with the shared udid injected", async () => {
const { registry, calls } = makeMockRegistry();
const tool = createRunSequenceTool(registry);
const result = await tool.execute!(
{},
{
udid: TVOS_UDID,
steps: [
{ tool: "tv-remote", args: { button: "right" } },
{ tool: "keyboard", args: { text: "hello" } },
{ tool: "tv-remote", args: { button: "select" } },
],
}
);
expect(result.completed).toBe(3);
expect(result.total).toBe(3);
// Every step ran through the registry with udid auto-injected.
expect(calls.map((c) => c.tool)).toEqual(["tv-remote", "keyboard", "tv-remote"]);
for (const c of calls) {
expect(c.args.udid).toBe(TVOS_UDID);
}
expect(calls[0]!.args).toMatchObject({ button: "right", udid: TVOS_UDID });
});
it("rejects a tool that isn't in the allow-list and stops the sequence", async () => {
const { registry, calls } = makeMockRegistry();
const tool = createRunSequenceTool(registry);
const result = await tool.execute!(
{},
{
udid: TVOS_UDID,
steps: [
{ tool: "tv-remote", args: { button: "down" } },
{ tool: "screenshot", args: {} },
{ tool: "tv-remote", args: { button: "select" } },
],
}
);
// First step ran; the disallowed second step halts execution before the third.
expect(result.completed).toBe(1);
expect(calls.map((c) => c.tool)).toEqual(["tv-remote"]);
const failed = result.steps[1];
expect(failed && "error" in failed && failed.error).toMatch(/not allowed/);
});
it("declares no eager service so a tvOS udid never spawns simulator-server", () => {
const { registry } = makeMockRegistry();
const tool = createRunSequenceTool(registry);
// The registry resolves each step's services lazily; run-sequence itself
// declares none — declaring simulator-server would hang for a tvOS udid.
expect(tool.services({ udid: TVOS_UDID, steps: [] } as any)).toEqual({});
});
it("runs each step in order, injecting the shared udid", async () => {
const registry = mockRegistry();
const tool = createRunSequenceTool(registry);
const result = await tool.execute(
{},
{
udid: IOS,
steps: [
{ tool: "gesture-tap", args: { x: 0.5, y: 0.3 }, delayMs: 0 },
{ tool: "keyboard", args: { text: "hi" }, delayMs: 0 },
],
}
);
expect(result).toMatchObject({ completed: 2, total: 2 });
expect(registry.invokeTool).toHaveBeenNthCalledWith(1, "gesture-tap", {
x: 0.5,
y: 0.3,
udid: IOS,
});
expect(registry.invokeTool).toHaveBeenNthCalledWith(2, "keyboard", { text: "hi", udid: IOS });
});
it("stops at an unrecognized tool without invoking it", async () => {
const registry = mockRegistry();
const tool = createRunSequenceTool(registry);
const result = await tool.execute(
{},
{ udid: IOS, steps: [{ tool: "not-a-tool", args: {}, delayMs: 0 }] }
);
expect(result.completed).toBe(0);
expect(result.steps[0]).toMatchObject({
tool: "not-a-tool",
error: expect.stringContaining("not allowed"),
});
expect(registry.invokeTool).not.toHaveBeenCalled();
});
it("stops the sequence when an await-ui-element step reports an unmet condition", async () => {
const registry = mockRegistry((id: string) => {
if (id === "await-ui-element") {
return {
success: false,
elapsed: 5000,
note: "no element matched the selector before timeout",
};
}
return { tapped: true };
});
const tool = createRunSequenceTool(registry);
const result = await tool.execute(
{},
{
udid: IOS,
steps: [
{ tool: "gesture-tap", args: { x: 0.5, y: 0.9 } },
{
tool: "await-ui-element",
args: { condition: "visible", selector: { text: "Continue" } },
},
{ tool: "gesture-tap", args: { x: 0.5, y: 0.5 } },
],
}
);
// The trailing tap must NOT run.
expect(registry.invokeTool).toHaveBeenCalledTimes(2);
expect(result.steps).toHaveLength(2);
const last = result.steps[1] as { tool: string; error?: string };
expect(last.tool).toBe("await-ui-element");
expect(last.error).toMatch(/condition not met/i);
expect(last.error).toMatch(/no element matched/i);
expect(result.completed).toBe(1);
expect(result.total).toBe(3);
});
it("continues past an await-ui-element step whose condition is met", async () => {
const registry = mockRegistry((id: string) => {
if (id === "await-ui-element") return { success: true, elapsed: 120 };
return { tapped: true };
});
const tool = createRunSequenceTool(registry);
const result = await tool.execute(
{},
{
udid: IOS,
steps: [
{ tool: "gesture-tap", args: { x: 0.5, y: 0.9 } },
{
tool: "await-ui-element",
args: { condition: "visible", selector: { text: "Continue" } },
},
{ tool: "gesture-tap", args: { x: 0.5, y: 0.5 } },
],
}
);
expect(registry.invokeTool).toHaveBeenCalledTimes(3);
expect(result.completed).toBe(3);
expect(result.steps.every((s) => "result" in s)).toBe(true);
});
it("only the await-ui-element tool's success:false halts — other tools are unaffected", async () => {
// A non-wait step returning a success:false-shaped object must NOT stop the run.
const registry = mockRegistry(() => ({ success: false }));
const tool = createRunSequenceTool(registry);
const result = await tool.execute(
{},
{
udid: IOS,
steps: [
{ tool: "gesture-tap", args: { x: 0.5, y: 0.9 } },
{ tool: "gesture-tap", args: { x: 0.5, y: 0.5 } },
],
}
);
expect(registry.invokeTool).toHaveBeenCalledTimes(2);
expect(result.completed).toBe(2);
});
it("forwards the request abort signal into each sub-tool invocation", async () => {
const registry = mockRegistry(() => ({ tapped: true }));
const tool = createRunSequenceTool(registry);
const controller = new AbortController();
await tool.execute(
{},
{ udid: IOS, steps: [{ tool: "gesture-tap", args: { x: 0.5, y: 0.9 } }] },
{ signal: controller.signal } as unknown as ToolContext
);
expect(registry.invokeTool).toHaveBeenCalledTimes(1);
const opts = (registry.invokeTool as ReturnType<typeof vi.fn>).mock.calls[0][2];
expect(opts.signal).toBe(controller.signal);
});
it("does not run any step when the signal is already aborted", async () => {
const registry = mockRegistry(() => ({ tapped: true }));
const tool = createRunSequenceTool(registry);
const controller = new AbortController();
controller.abort();
const result = await tool.execute(
{},
{
udid: IOS,
steps: [{ tool: "gesture-tap", args: { x: 0.5, y: 0.9 } }],
},
{ signal: controller.signal } as unknown as ToolContext
);
expect(registry.invokeTool).not.toHaveBeenCalled();
expect(result.completed).toBe(0);
});
it("propagates the request's telemetry attribution to every sub-tool", async () => {
const registry = mockRegistry();
const tool = createRunSequenceTool(registry);
const release = vi.fn();
const recordChildInvocation = vi.fn((_id: string, _args?: unknown) => release);
const ctx = { artifacts: {}, recordChildInvocation } as unknown as ToolContext;
await tool.execute(
{},
{
udid: IOS,
steps: [
{ tool: "gesture-tap", args: { x: 0.5, y: 0.3 }, delayMs: 0 },
{ tool: "gesture-swipe", args: { fromX: 0.5 }, delayMs: 0 },
],
},
ctx
);
// One recorded child invocation per step, each with its own id.
expect(recordChildInvocation).toHaveBeenCalledTimes(2);
const ids = recordChildInvocation.mock.calls.map((c) => c[0]);
expect(new Set(ids).size).toBe(2);
// Each step's own args (with the injected udid) reach the recorder so it can
// attribute the gesture to the right platform.
expect(recordChildInvocation).toHaveBeenNthCalledWith(
1,
ids[0],
expect.objectContaining({ x: 0.5, y: 0.3, udid: IOS })
);
expect(recordChildInvocation).toHaveBeenNthCalledWith(
2,
ids[1],
expect.objectContaining({ fromX: 0.5, udid: IOS })
);
// Each sub-tool is dispatched under its minted id, with the recorder
// forwarded so deeper nesting keeps the attribution.
expect(registry.invokeTool).toHaveBeenNthCalledWith(
1,
"gesture-tap",
expect.objectContaining({ x: 0.5, y: 0.3, udid: IOS }),
expect.objectContaining({ toolInvocationId: ids[0], recordChildInvocation })
);
expect(registry.invokeTool).toHaveBeenNthCalledWith(
2,
"gesture-swipe",
expect.objectContaining({ fromX: 0.5, udid: IOS }),
expect.objectContaining({ toolInvocationId: ids[1], recordChildInvocation })
);
expect(release).toHaveBeenCalledTimes(2);
});
it("forwards the request's abort signal to each sub-tool so a long step is cancellable", async () => {
const registry = mockRegistry();
const tool = createRunSequenceTool(registry);
const controller = new AbortController();
const ctx = { artifacts: {}, signal: controller.signal } as unknown as ToolContext;
await tool.execute(
{},
{ udid: IOS, steps: [{ tool: "tv-remote", args: { button: "right" }, delayMs: 0 }] },
ctx
);
// The sub-tool must receive `signal` via its options — otherwise its own
// `throwIfAborted` is a no-op and a long step runs to completion after the
// client disconnects. (No attribution context here, so this is the
// pass-through branch.)
expect(registry.invokeTool).toHaveBeenCalledWith(
"tv-remote",
expect.objectContaining({ button: "right", udid: IOS }),
expect.objectContaining({ signal: controller.signal })
);
});
it("stops before the next step once the signal is aborted", async () => {
const controller = new AbortController();
// Abort as soon as the first step runs; the loop must not dispatch the second.
const registry = mockRegistry(() => {
controller.abort();
return { ok: true };
});
const tool = createRunSequenceTool(registry);
const ctx = { artifacts: {}, signal: controller.signal } as unknown as ToolContext;
const result = await tool.execute(
{},
{
udid: IOS,
steps: [
{ tool: "tv-remote", args: { button: "up" }, delayMs: 0 },
{ tool: "tv-remote", args: { button: "down" }, delayMs: 0 },
],
},
ctx
);
expect(result.completed).toBe(1);
expect(registry.invokeTool).toHaveBeenCalledTimes(1);
});
});