mirror of
https://github.com/software-mansion/argent.git
synced 2026-09-14 19:27:14 +08:00
afd722924f
## Problem
Only one flow could be recorded at a time, anywhere on the machine.
Recording state was three module globals in `flow-utils.ts` — harmless
in a per-client process, but the tool-server is a **host-wide singleton
per install bundle**. Every MCP client, every subagent sharing a
parent's connection, every `argent` CLI call and every project on the
machine attaches to the same process, the same `Registry`, and those
same three globals. HTTP requests are served concurrently with no
serialization.
Three failures followed, all reproduced against the pre-change code:
1. **A second recording clobbered the first.** `startRecordingSession`
just overwrote, so the first agent's next `flow-add-step` silently
appended into the *other* agent's flow file — in a different project.
2. **Any agent could finish any agent's recording.**
`flow-finish-recording`'s schema was literally `z.object({})`.
3. **Replay stomped recording.** `resolveFlowFilePath` called
`setActiveProjectRoot`, so a `flow-execute` in project B rebound the
global root mid-recording of project A. Already worked around, locally
only, in `flow-add-step`.
## Approach
Recording state is now a `Map` keyed by the resolved flow file path,
`<project_root>/.argent/flows/<name>.yaml` — the identity of the
artifact being built, so "same key" means "same output file" and two
sessions on one key are a genuine collision rather than an accident of
scoping. `flow-add-step`, `flow-add-echo` and `flow-finish-recording`
each take `name` + `project_root`, so every call is self-contained;
required rather than optional-with-fallback, since a fallback would
succeed while an agent is alone and fail only once a second recording
exists.
`resolveFlowFilePath` is pure, which fixes defect 3 and retires
`FLOW_PROJECT_ROOT_REQUIRED` (the state it guarded can no longer exist).
Rejected alternatives — keying by device udid (flows are deliberately
device-portable, and `flow-add-echo`/`flow-finish-recording` have no
device at all), an opaque `recordingId` (an agent that loses the token
cannot recover), and per-caller identity from the transport
(`ToolContext` carries no caller identity, and subagents share their
parent's MCP connection, so it would fail the exact scenario being
fixed).
### Locking, and why readers needed more than a lock
Every mutation of one flow file runs under a lock keyed by that path —
appends, `flow-start-recording`'s truncate-and-register, and
`flow-finish-recording`'s read-summarize-clear. Keyed by file rather
than owned by the session, because a restart *replaces* the session: a
session-owned lock cannot exclude the operation that supersedes it. Per
file, not global, so two recordings never queue behind each other. An
append whose session was finished, restarted or evicted meanwhile fails
with `FLOW_NO_ACTIVE_RECORDING` rather than writing into a different
take.
The lock serializes writers only, and no reader of a flow YAML can join
it — `flow-execute`'s own load, its `run:` fragment load,
`flow-read-prerequisite`, `flow-add-step`'s sibling-fragment check, and
the `argent` CLI reading from another process entirely, where an
in-process lock cannot reach. Both writers used a plain `fs.writeFile`,
which opens `O_TRUNC`, so a reader could land between the truncate and
the write. That case is silent: `parseFlow("")` returns `{ steps: [] }`
with no error and `summarize` derives `ok` from "no failures", so a
`flow-execute` racing an append reports a **top-level PASS having
replayed zero steps**. Both writes now go through a sibling temp file
and a rename, so a reader sees either the whole old file or the whole
new one — and unlike the lock, that also holds cross-process.
### `stop-all-simulator-servers` gets a `devices` scope
Every agent is told to call this at session end, and unscoped it walked
the whole registry — so agent A wrapping up tore down agent B's devtools
mid-recording, degrading B's flow to brittle coordinate taps. It now
takes an optional `devices` scope and reports `unmatched` ids, so a
mistyped id doesn't read as a clean machine.
Which namespaces count as "owned by a device" turned out to be the
load-bearing part, because nothing cascades to most of them and
`unmatched` turns any omission into an actively wrong diagnosis — a
correct device id reported as a typo. The set now covers `AXService`
(the in-sim ax daemon, spawned `--timeout 3600`; an iOS session that
only ran boot/launch/describe owns this and nothing else),
`ScreenRecordingSession` (an ffmpeg child plus the touch-visualizer
overlay it enabled on the device), `NativeProfilerSession` (an xctrace
child, or an on-device perfetto process and its trace file) and
`JsRuntimeDebugger` (a bound loopback server, the CDP socket to Metro, a
log handle). The debugger URNs interpose the Metro port —
`<ns>:<port>:<deviceId>` — so the matcher understands both shapes,
consuming only the first colon so a wireless adb serial after the port
still compares whole.
`stop-simulator-server` shared none of this and had drifted: it looked
URNs up with an exact, case-sensitive `services.get()`, so a lower-cased
UDID silently no-op'd there while the scoped stop-all reaped it. Both
tools now share one matcher. Their namespace *sets* stay deliberately
different, documented where they are defined — `stop-simulator-server`
is also the documented recovery for a wedged transport, and widening it
to devtools/AX would make a routine retry drop the native-devtools
connection another agent's recording depends on, which is the hazard the
`devices` scope exists to prevent.
## Verification
**End-to-end, three devices, one shared tool-server** (iPhone 16 Pro,
iPhone 17 Pro, Pixel 3a): three interleaved recordings, plus an
unrelated `flow-execute` in a fourth project while all three were live.
Both iOS devices held their own live native-devtools concurrently (two
per-UDID sockets, `connected: true`). Each YAML contained exactly its
own steps in order, taps captured as selectors rather than coordinates,
and neither picked up another's or the third root's path. All three
replayed green — also through the **released 0.17.0 CLI** against the
modified server, which checks wire compatibility. A device-scoped
teardown of sim 1 left sim 2 and the emulator running.
Re-run against the final build:
- Two interleaved recordings across two project roots on one device,
with a **separate process** polling one of the flow files as fast as it
could for the duration. Zero empty or truncated observations; each YAML
held exactly its own steps; both replayed green (6/6 and 5/5). Against
the pre-change in-place write the same reader observes zero-step reads
interleaved among the real ones — the silent-PASS input.
- A scoped teardown of the iPhone reaped `AXService` and
`NativeDevtools` for that UDID only, reported no `unmatched`, and left
the second sim and the emulator running. Lower-casing the UDID matched;
a genuinely bogus id was still reported.
- With a screen recording live on the Pixel 3a, a scoped teardown reaped
`ScreenRecordingSession` and the **ffmpeg child actually exited** (1 →
0). Before the fix it survived to the 180 s cap while the tool called
the correct serial a typo.
The pre-change repros were re-run afterwards to confirm observed
behavior changed, not just the tests.
`npx vitest run` in `packages/tool-server` (295 files, 3154 tests) and
`packages/argent-cli` (280), `tsc --build`, `tsc --noEmit` on both test
projects, eslint and prettier — all green.
## Review notes
Several rounds of review found real defects in this change; each was
reproduced before fixing and re-verified after. Worth knowing when
reading the diff, since the tests exist to pin them:
- `flow-start-recording` truncated the `.yaml` outside any lock, so a
step from the take being discarded landed in the freshly reset file and
was reported as success (26-29 of 200 runs).
- `flow-finish-recording` never took the lock; its `await fs.readFile`
was a yield during which a concurrent append committed, leaving the
reported summary disagreeing with disk (11-16 of 200).
- A failed finish destroyed the recording. Hand-editing the `.yaml`
mid-recording is a documented workflow, so `parseFlow` can legitimately
throw — and the error told the agent to call `flow-start-recording`,
which truncates the very take it would recover.
- `unmatched` reported a device this session had just stopped, because
`disposeService` returns a node to IDLE and keeps it.
- A bare IP claimed every wireless-adb device at that address, since an
adb serial is itself `ip:port`.
- The eviction backstop stamped with `Date.now()`; ties at millisecond
resolution let it drop the session that was just used.
- `requireRecordingSession` ended with "Call flow-start-recording first"
— reached for a key that was finished, superseded or evicted as well as
one never started, and on those branches the file on disk is fully
populated while that call truncates it and reports no `restarted`.
- The atomic write regressed twice on its own terms: its scratch name
was derived from the flow file's basename, which has no length cap, so a
long flow name that appended fine before failed `ENAMETOOLONG`; and the
cleanup guard began after the temp file was created, leaking a scratch
file into a committed directory on any write that failed after opening.
- Two tests passed against implementations they claimed to reject: the
`stop-simulator-server` narrowness guard used a udid that classifies as
*android*, where the iOS-only services it guards can never appear, so
widening the iOS branch kept it green; and the client-mode finish
asserted only the *shape* of `savedTo`, never its content, though that
directive is the only thing that lands the file in client mode.
## Notes for reviewers
- Client/remote persist mode is the least-exercised path, and now has
its own concurrency tests (overlapping appends, and a restart
superseding an in-flight one) — it previously had none. The
`project_root` key is byte-stable across the file boundary (`kind:
"probe"` passes it through unchanged), which is what keeps a remote
recording addressable from `flow-add-step`, which declares no file
input.
- Two spellings of one flow file still mint two sessions — and two
independent locks — over one file, which bypasses every guarantee here.
Two ways in: the root spelled two ways (a symlink, or a case variant on
APFS), and the likelier one, the *name* cased two ways on a
case-insensitive volume. Neither is normalized away because the correct
normalization is the filesystem's: case-folding the key would wrongly
merge two distinct flows on ext4, and resolving symlinks is impossible
in client mode, where the root does not exist on this host. Documented
at `getFlowPath`.
- No recording tool can detect that another agent took its key.
`flow-add-step`, `flow-add-echo` and `flow-finish-recording` all
re-resolve the key on every call, so after a takeover they act on
whichever take is now live and report success: an append lands in the
other agent's file, and a finish finishes and clears it. The only case
that fails loudly is the narrow one the liveness check covers - an
append already IN FLIGHT when the restart lands. There is no caller
identity to key ownership on (see the rejected alternatives above), so
this is spelled out for the agent under "Pick a name unique to your
task" in `argent-create-flow` rather than mechanized.
- Skew hazard in one direction only: a *new* client against an *older*
tool-server. Zod strips the undeclared `name`/`project_root`, and the
old server falls back to its module globals — so concurrent recordings
silently collapse onto one session. The other direction (released 0.17.0
CLI against this server) was verified end-to-end.
- `packages/argent-private/docs/reference.md` still describes
`flow-add-step` as appending to "the current recording", and names two
tool ids that do not exist (`flow-insert-echo`/`flow-run` are file
names; the ids are `flow-add-echo`/`flow-execute`). It is a submodule,
so the fix cannot ride on this branch.
- A restart reported `discardedSteps` from the superseded session's
in-memory flow while it truncates the *file*. Hand-editing the `.yaml`
mid-recording is documented, so the two diverge: four steps wiped, one
reported. It now counts the file, and reports no number at all when that
file cannot be read or parsed - 0 is the answer a genuinely empty take
gives. Client mode still counts from memory (this host cannot see the
client's file), and the description now says which mode it is promising.
- `ChromiumJsRuntimeDebugger` cascades from `ChromiumCdp` and was
therefore already being torn down - silently, while `NetworkInspector`
and `ReactProfilerSession` cascade the same way and were named.
`stopped` is documented as the services that were live and got shut
down, so it is listed now too.
- The client-mode case named for a superseded in-flight append restarted
*between* calls, so the next append re-resolved the key and succeeded -
the guard was never reached, and neutering it left the whole file green.
It now parks an append in its live sub-tool call across the restart.
- `stop-tools.test.ts`' mock handed the tool the live service map where
the real `getSnapshot` copies, so a cascade rewrote the state the sweep
was still reading and the answer depended on map insertion order. The
mock copies and recurses like `_teardown` now, and the cascade case runs
under both orders.
- Prose the code contradicted, each verified against source before
rewriting: Vega owns `JsRuntimeDebugger`/`NetworkInspector` once the
debugger has run (and can match anything at all through an ERROR node);
"nothing here cascades" was denied twice in its own file; an iOS
boot/launch/describe session owns `NativeDevtools` too; `:tcp` is
mintable but unreached in production; the tool-server is a singleton
*per install bundle*, not per machine; `argent flow list` does enumerate
`.argent/flows`; the stop-tools comments narrated a "before" that only
existed on this branch.
Found while verifying, out of scope, worth their own issues: a `tool:
flow-execute` self-reference recurses past both cycle guards (`run:` is
guarded, a nested `flow-execute` reseeds the stack); react-profiler
artifacts collide host-wide on a second-resolution filename;
`stop-metro` is port-scoped and kills another agent's bundler;
`debugger-reload-metro`'s HTTP fallback broadcasts to every attached
client. A tool's `capability` is enforced only by the HTTP layer, not by
`registry.invokeTool`, so a call that reaches the registry another way -
`flow-add-step` takes `command` as a bare string - can resolve a service
the tool declares it does not support, leaving an ERROR node behind
(e.g. `SimulatorServer:<vega serial>`).
---------
Co-authored-by: Hubert Gancarczyk <claude-hubert.gancarczyk@swmansion.com>
385 lines
16 KiB
TypeScript
385 lines
16 KiB
TypeScript
import { createServer, type Server } from "node:http";
|
|
import { describe, it, expect, afterEach } from "vitest";
|
|
import { FAILURE_CODES, getFailureSignal, type FailureCode } from "@argent/registry";
|
|
|
|
import { assertValidProjectRoot, assertSafeFlowName } from "../src/tools/flows/flow-utils";
|
|
import { createFlowAddStepTool } from "../src/tools/flows/flow-add-step";
|
|
import { flowInsertEchoTool } from "../src/tools/flows/flow-insert-echo";
|
|
import { createRunFlowTool } from "../src/tools/flows/flow-run";
|
|
import type { DeviceInfo, Registry } from "@argent/registry";
|
|
import { makeChromiumImpl } from "../src/tools/keyboard/platforms/chromium";
|
|
import { chromiumCdpBlueprint } from "../src/blueprints/chromium-cdp";
|
|
import { ensureCdpReachable, discoverPrimaryPage } from "../src/chromium-server/cdp-session";
|
|
import { readViewport } from "../src/chromium-server/viewport";
|
|
import { captureScreenshot } from "../src/chromium-server/screenshot";
|
|
import type { CDPClient } from "../src/utils/debugger/cdp-client";
|
|
import { injectVegaText, injectVegaNamedKey } from "../src/utils/vega-input";
|
|
import {
|
|
readAndroidNativeProfilerMetadata,
|
|
androidNativeProfilerMetadataPath,
|
|
} from "../src/utils/android-profiler/session-metadata";
|
|
import { profilerStackQueryTool } from "../src/tools/profiler/query/profiler-stack-query";
|
|
import { tmpdir } from "node:os";
|
|
import { mkdtemp, writeFile, rm } from "node:fs/promises";
|
|
import { join } from "node:path";
|
|
|
|
/**
|
|
* Telemetry only reads a FailureError's signal when it propagates out of a tool's
|
|
* `execute` (the registry's `toolFailed` event walks the cause chain via
|
|
* `getFailureSignal`). These tests pin the `error_code` of representative
|
|
* newly-classified throw sites — across the flows, keyboard, chromium (blueprint
|
|
* factory + CDP discovery), vega input, and native-profiler (metadata + stack
|
|
* query) areas — so a regression that drops or mis-codes a classification is
|
|
* caught in CI rather than only in a one-off manual run.
|
|
*
|
|
* Each site here is reachable on a real telemetry path (a registered tool's
|
|
* execute, or a helper it calls un-swallowed) and driven with only a bare stub,
|
|
* a local HTTP server, or a temp file — no live device. Families that require a
|
|
* live CDP WebSocket or a booted device (electron boot, tab-open, vega adb/CLI
|
|
* paths) are exercised in the end-to-end suites, not here.
|
|
*/
|
|
|
|
/** Await a promise expected to reject and return the thrown error. */
|
|
async function captureError(p: Promise<unknown>): Promise<unknown> {
|
|
try {
|
|
await p;
|
|
} catch (e) {
|
|
return e;
|
|
}
|
|
throw new Error("expected the call to throw, but it resolved");
|
|
}
|
|
|
|
/** Run a synchronous function expected to throw and return the thrown error. */
|
|
function captureSync(fn: () => unknown): unknown {
|
|
try {
|
|
fn();
|
|
} catch (e) {
|
|
return e;
|
|
}
|
|
throw new Error("expected the call to throw, but it returned");
|
|
}
|
|
|
|
function expectCode(err: unknown, code: FailureCode): void {
|
|
expect(getFailureSignal(err)?.error_code).toBe(code);
|
|
}
|
|
|
|
const openServers: Server[] = [];
|
|
|
|
/** Start a local HTTP server on an ephemeral port and return its port. */
|
|
function startServer(handler: (path: string, res: import("node:http").ServerResponse) => void) {
|
|
return new Promise<number>((resolve) => {
|
|
const srv = createServer((req, res) => handler(req.url ?? "/", res));
|
|
openServers.push(srv);
|
|
srv.listen(0, "127.0.0.1", () => resolve((srv.address() as { port: number }).port));
|
|
});
|
|
}
|
|
|
|
afterEach(async () => {
|
|
// Tear down any local servers a case spun up.
|
|
await Promise.all(openServers.splice(0).map((s) => new Promise<void>((r) => s.close(() => r()))));
|
|
});
|
|
|
|
describe("flow-utils classifications", () => {
|
|
it("classifies a relative project_root as FLOW_PROJECT_ROOT_INVALID", () => {
|
|
expectCode(
|
|
captureSync(() => assertValidProjectRoot("relative/path")),
|
|
FAILURE_CODES.FLOW_PROJECT_ROOT_INVALID
|
|
);
|
|
});
|
|
|
|
it("classifies a project_root containing '..' as FLOW_PROJECT_ROOT_INVALID", () => {
|
|
expectCode(
|
|
captureSync(() => assertValidProjectRoot("/a/../b")),
|
|
FAILURE_CODES.FLOW_PROJECT_ROOT_INVALID
|
|
);
|
|
});
|
|
|
|
it("classifies an unsafe flow name as FLOW_NAME_INVALID", () => {
|
|
expectCode(
|
|
captureSync(() => assertSafeFlowName("bad name!")),
|
|
FAILURE_CODES.FLOW_NAME_INVALID
|
|
);
|
|
});
|
|
});
|
|
|
|
describe("flow tool project_root classifications", () => {
|
|
// Every flow tool takes `project_root` from the caller, so the invalid-root
|
|
// throw is reachable from a tool's execute — not just from the helper above.
|
|
// Root validation happens inside getFlowPath, which runs BEFORE the recording
|
|
// is looked up (`requireRecordingSession` keys the session map by that path),
|
|
// so a bad root reports FLOW_PROJECT_ROOT_INVALID rather than the
|
|
// FLOW_NO_ACTIVE_RECORDING it would earn if the lookup came first — even
|
|
// though no recording was ever started here.
|
|
const RELATIVE_ROOT = "relative/project";
|
|
const DOTDOT_ROOT = "/tmp/project/../../etc";
|
|
|
|
// Both tools throw on the root before any tool dispatch or file read, so a
|
|
// bare stub registry is never actually used.
|
|
const registry = {} as unknown as Registry;
|
|
|
|
it("classifies flow-add-step with a relative project_root as FLOW_PROJECT_ROOT_INVALID", async () => {
|
|
const addStep = createFlowAddStepTool(registry);
|
|
const err = await captureError(
|
|
addStep.execute(
|
|
{},
|
|
{ name: "some-flow", project_root: RELATIVE_ROOT, command: "gesture-tap" }
|
|
)
|
|
);
|
|
expectCode(err, FAILURE_CODES.FLOW_PROJECT_ROOT_INVALID);
|
|
// The root is judged first: no "No active recording" for an unstarted flow.
|
|
expect((err as Error).message).not.toMatch(/No active recording/);
|
|
});
|
|
|
|
it("classifies flow-add-step with a '..'-bearing project_root as FLOW_PROJECT_ROOT_INVALID", async () => {
|
|
const addStep = createFlowAddStepTool(registry);
|
|
expectCode(
|
|
await captureError(
|
|
addStep.execute(
|
|
{},
|
|
{ name: "some-flow", project_root: DOTDOT_ROOT, command: "gesture-tap" }
|
|
)
|
|
),
|
|
FAILURE_CODES.FLOW_PROJECT_ROOT_INVALID
|
|
);
|
|
});
|
|
|
|
it("classifies flow-add-echo with a relative project_root as FLOW_PROJECT_ROOT_INVALID", async () => {
|
|
expectCode(
|
|
await captureError(
|
|
flowInsertEchoTool.execute(
|
|
{},
|
|
{ name: "some-flow", project_root: RELATIVE_ROOT, message: "label" }
|
|
)
|
|
),
|
|
FAILURE_CODES.FLOW_PROJECT_ROOT_INVALID
|
|
);
|
|
});
|
|
|
|
it("classifies flow-execute with a relative project_root as FLOW_PROJECT_ROOT_INVALID", async () => {
|
|
const runFlow = createRunFlowTool(registry);
|
|
expectCode(
|
|
await captureError(runFlow.execute({}, { name: "some-flow", project_root: RELATIVE_ROOT })),
|
|
FAILURE_CODES.FLOW_PROJECT_ROOT_INVALID
|
|
);
|
|
});
|
|
|
|
it("classifies flow-execute with a '..'-bearing project_root as FLOW_PROJECT_ROOT_INVALID", async () => {
|
|
const runFlow = createRunFlowTool(registry);
|
|
expectCode(
|
|
await captureError(runFlow.execute({}, { name: "some-flow", project_root: DOTDOT_ROOT })),
|
|
FAILURE_CODES.FLOW_PROJECT_ROOT_INVALID
|
|
);
|
|
});
|
|
});
|
|
|
|
describe("keyboard classifications", () => {
|
|
// The chromium typing path lives in makeChromiumImpl's handler, which resolves
|
|
// the CDP service then validates the key/char before touching it. A stub
|
|
// registry (service resolves to a bare object) reaches the classified throw
|
|
// without a live browser.
|
|
const registry = { resolveService: async () => ({}) } as unknown as Registry;
|
|
const { handler } = makeChromiumImpl(registry);
|
|
const device = {
|
|
id: "chromium-cdp-9222",
|
|
platform: "chromium",
|
|
kind: "app",
|
|
} as unknown as DeviceInfo;
|
|
|
|
it("classifies an unknown named key as KEYBOARD_KEY_UNSUPPORTED", async () => {
|
|
expectCode(
|
|
await captureError(handler({}, { udid: device.id, key: "not-a-key" }, device)),
|
|
FAILURE_CODES.KEYBOARD_KEY_UNSUPPORTED
|
|
);
|
|
});
|
|
|
|
it("classifies an unmappable character as KEYBOARD_CHARACTER_UNSUPPORTED", async () => {
|
|
expectCode(
|
|
await captureError(handler({}, { udid: device.id, text: "\u{1F600}" }, device)),
|
|
FAILURE_CODES.KEYBOARD_CHARACTER_UNSUPPORTED
|
|
);
|
|
});
|
|
});
|
|
|
|
describe("chromium blueprint factory classifications", () => {
|
|
const device = (id: string) => ({ id, platform: "chromium" as const, kind: "app" as const });
|
|
|
|
it("classifies a malformed chromium device id as CHROMIUM_DEVICE_ID_INVALID", async () => {
|
|
// A well-formed id that agrees between options and URN passes the (uncoded)
|
|
// wiring guards, then the port parse fails — exercising the reachable
|
|
// CHROMIUM_DEVICE_ID_INVALID branch.
|
|
expectCode(
|
|
await captureError(
|
|
chromiumCdpBlueprint.factory({}, device("chromium-cdp-bogus"), {
|
|
device: device("chromium-cdp-bogus"),
|
|
})
|
|
),
|
|
FAILURE_CODES.CHROMIUM_DEVICE_ID_INVALID
|
|
);
|
|
});
|
|
});
|
|
|
|
describe("chromium CDP discovery classifications", () => {
|
|
// These drive the discovery helpers against a local HTTP server standing in
|
|
// for the debug port, exercising the reachable throw sites the way the tools
|
|
// do (ensureCdpReachable / discoverPrimaryPage bubble out of chromium tool
|
|
// execute → toolFailed → getFailureSignal).
|
|
|
|
it("classifies a 200 with a non-JSON body as CHROMIUM_CDP_INVALID_RESPONSE", async () => {
|
|
// A non-CDP service squatting the debug port answers 200 but the body can't
|
|
// be parsed — the reached-but-malformed case (regression guard for the
|
|
// res.json() parse that used to escape unclassified to the generic bucket).
|
|
const port = await startServer((_path, res) => {
|
|
res.writeHead(200, { "Content-Type": "text/html" });
|
|
res.end("<html>not a CDP endpoint</html>");
|
|
});
|
|
const err = await captureError(ensureCdpReachable(port));
|
|
expectCode(err, FAILURE_CODES.CHROMIUM_CDP_INVALID_RESPONSE);
|
|
expect(getFailureSignal(err)?.network_failure).toBe("invalid_response");
|
|
});
|
|
|
|
it("classifies a non-2xx status as CHROMIUM_CDP_INVALID_RESPONSE", async () => {
|
|
const port = await startServer((_path, res) => {
|
|
res.writeHead(500);
|
|
res.end("boom");
|
|
});
|
|
expectCode(
|
|
await captureError(ensureCdpReachable(port)),
|
|
FAILURE_CODES.CHROMIUM_CDP_INVALID_RESPONSE
|
|
);
|
|
});
|
|
|
|
it("classifies a refused connection as CHROMIUM_CDP_UNREACHABLE", async () => {
|
|
// Bind then immediately release a port so the connect is refused.
|
|
const port = await startServer(() => {});
|
|
await new Promise<void>((r) => openServers.splice(0)[0]!.close(() => r()));
|
|
const err = await captureError(ensureCdpReachable(port));
|
|
expectCode(err, FAILURE_CODES.CHROMIUM_CDP_UNREACHABLE);
|
|
expect(getFailureSignal(err)?.network_failure).toBe("connection_refused");
|
|
});
|
|
|
|
it("classifies an endpoint with no page targets as CHROMIUM_CDP_NO_PAGE_TARGET", async () => {
|
|
const port = await startServer((path, res) => {
|
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
// /json/version resolves; /json/list has no page targets.
|
|
if (path.startsWith("/json/version")) {
|
|
res.end(JSON.stringify({ webSocketDebuggerUrl: "ws://127.0.0.1/devtools/browser/x" }));
|
|
} else {
|
|
res.end(JSON.stringify([]));
|
|
}
|
|
});
|
|
expectCode(
|
|
await captureError(discoverPrimaryPage(port)),
|
|
FAILURE_CODES.CHROMIUM_CDP_NO_PAGE_TARGET
|
|
);
|
|
});
|
|
});
|
|
|
|
describe("chromium CDP-command malformed-response classifications", () => {
|
|
// A CDP command that round-trips but returns a payload missing the expected
|
|
// field is classified `error_kind: "unknown"` (a malformed response from a
|
|
// source we don't own), never `network`. These helpers are called
|
|
// un-swallowed from the chromium tools' execute, so the signal reaches
|
|
// telemetry. A stub CDPClient whose `send` resolves to `{}` reaches the
|
|
// classified throw without a live browser. This pins the convention that
|
|
// CHROMIUM_TAB_OPEN_FAILED (Target.createTarget with no targetId) also follows.
|
|
const stubCdp = (payload: unknown) => ({ send: async () => payload }) as unknown as CDPClient;
|
|
|
|
it("classifies a viewport read with no value as CHROMIUM_VIEWPORT_READ_FAILED (unknown)", async () => {
|
|
const err = await captureError(readViewport(stubCdp({})));
|
|
expectCode(err, FAILURE_CODES.CHROMIUM_VIEWPORT_READ_FAILED);
|
|
expect(getFailureSignal(err)?.error_kind).toBe("unknown");
|
|
});
|
|
|
|
it("classifies a screenshot with no data as CHROMIUM_SCREENSHOT_FAILED (unknown)", async () => {
|
|
const err = await captureError(
|
|
captureScreenshot({ cdp: stubCdp({}), deviceId: "chromium-cdp-9222" })
|
|
);
|
|
expectCode(err, FAILURE_CODES.CHROMIUM_SCREENSHOT_FAILED);
|
|
expect(getFailureSignal(err)?.error_kind).toBe("unknown");
|
|
});
|
|
});
|
|
|
|
describe("vega input classifications", () => {
|
|
// Both validate before any `adb`/inputd I/O, so they throw synchronously on
|
|
// bad input on the real typing path — no device needed to pin the code.
|
|
it("classifies newline-bearing text as VEGA_TEXT_INVALID", async () => {
|
|
expectCode(await captureError(injectVegaText("line1\nline2")), FAILURE_CODES.VEGA_TEXT_INVALID);
|
|
});
|
|
|
|
it("classifies an unknown named key as KEYBOARD_KEY_UNSUPPORTED", async () => {
|
|
expectCode(
|
|
await captureError(injectVegaNamedKey("not-a-real-key")),
|
|
FAILURE_CODES.KEYBOARD_KEY_UNSUPPORTED
|
|
);
|
|
});
|
|
});
|
|
|
|
describe("native-profiler metadata classifications", () => {
|
|
// readAndroidNativeProfilerMetadata is called un-swallowed on the profiler-load
|
|
// path; a corrupt or structurally-invalid sidecar propagates to telemetry.
|
|
let dir = "";
|
|
afterEach(async () => {
|
|
if (dir) await rm(dir, { recursive: true, force: true });
|
|
dir = "";
|
|
});
|
|
|
|
it("classifies a corrupt JSON metadata sidecar as PROFILER_NATIVE_METADATA_INVALID", async () => {
|
|
dir = await mkdtemp(join(tmpdir(), "argent-meta-"));
|
|
const pftrace = join(dir, "native-profiler-s1.pftrace");
|
|
await writeFile(androidNativeProfilerMetadataPath(pftrace), "{ not valid json", "utf8");
|
|
expectCode(
|
|
await captureError(readAndroidNativeProfilerMetadata(pftrace)),
|
|
FAILURE_CODES.PROFILER_NATIVE_METADATA_INVALID
|
|
);
|
|
});
|
|
|
|
it("classifies a structurally-invalid metadata sidecar as PROFILER_NATIVE_METADATA_INVALID", async () => {
|
|
dir = await mkdtemp(join(tmpdir(), "argent-meta-"));
|
|
const pftrace = join(dir, "native-profiler-s2.pftrace");
|
|
// Valid JSON, wrong shape (empty appProcess) → the validate branch.
|
|
await writeFile(
|
|
androidNativeProfilerMetadataPath(pftrace),
|
|
JSON.stringify({ platform: "android", appProcess: "", wallClockStartMs: null }),
|
|
"utf8"
|
|
);
|
|
expectCode(
|
|
await captureError(readAndroidNativeProfilerMetadata(pftrace)),
|
|
FAILURE_CODES.PROFILER_NATIVE_METADATA_INVALID
|
|
);
|
|
});
|
|
});
|
|
|
|
describe("native-profiler stack-query classifications", () => {
|
|
// The tool's execute has no try/catch, so these codes propagate to telemetry.
|
|
// A bare session stub is enough — the throws fire before any trace I/O.
|
|
const session = (api: object) => ({ session: api }) as never;
|
|
|
|
it("classifies a query with no parsed data as PROFILER_DATA_NOT_LOADED", async () => {
|
|
expectCode(
|
|
await captureError(
|
|
profilerStackQueryTool.execute(session({ platform: "ios", parsedData: null }), {
|
|
device_id: "x",
|
|
mode: "thread_breakdown",
|
|
top_n: 15,
|
|
})
|
|
),
|
|
FAILURE_CODES.PROFILER_DATA_NOT_LOADED
|
|
);
|
|
});
|
|
|
|
it("classifies hang_stacks without hang_index as PROFILER_QUERY_REQUIRED_PARAM_MISSING", async () => {
|
|
expectCode(
|
|
await captureError(
|
|
profilerStackQueryTool.execute(
|
|
session({
|
|
platform: "ios",
|
|
parsedData: { cpuSamples: [], uiHangs: [], cpuHotspots: [], memoryLeaks: [] },
|
|
}),
|
|
{ device_id: "x", mode: "hang_stacks", top_n: 15 }
|
|
)
|
|
),
|
|
FAILURE_CODES.PROFILER_QUERY_REQUIRED_PARAM_MISSING
|
|
);
|
|
});
|
|
});
|