Skip to content
Merged
111 changes: 108 additions & 3 deletions packages/remote/src/__tests__/daemon-artifacts-capture.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ type MaterializationCase = {
name: string;
command: string;
positionals?: string[];
flags?: { kind: string };
registered?: string;
localPath: string;
field?: string;
Expand Down Expand Up @@ -140,12 +141,69 @@ test.for<MaterializationCase>([
expected: 'cwd/clip.mp4',
},
{
name: 'a perf cpu profile stop accepts the echo of its start destination',
name: 'a perf cpu profile stop refuses a hostile response localPath',
command: 'perf',
positionals: ['cpu', 'profile', 'stop'],
localPath: 'client/cpu.trace',
field: 'outPath',
localPath: '../../etc/x',
fileName: 'cpu.trace',
expected: 'client/cpu.trace',
generatedName: /^perf-[0-9a-f-]{36}$/,
},
{
name: 'a trace stop refuses an absolute response localPath',
command: 'trace',
positionals: ['stop'],
field: 'outPath',
localPath: '/etc/x',
fileName: '../../x',
generatedName: /^trace-[0-9a-f-]{36}\.log$/,
},
{
name: 'a perf cpu profile report keeps a json suffix, not the daemon-supplied name',
command: 'perf',
positionals: ['cpu', 'profile', 'report', 'xctrace'],
field: 'outPath',
localPath: '/etc/x',
fileName: 'report.sh',
generatedName: /^perf-[0-9a-f-]{36}\.json$/,
},
{
name: 'an xctrace capture stop keeps an archive suffix',
command: 'perf',
positionals: ['trace', 'stop', 'xctrace'],
field: 'outPath',
localPath: '/etc/x',
fileName: 'capture.exe',
generatedName: /^perf-[0-9a-f-]{36}\.tar\.gz$/,
},
{
name: 'a perf memory snapshot keeps the suffix of its kind',
command: 'perf',
positionals: ['memory', 'snapshot'],
flags: { kind: 'android-hprof' },
field: 'outPath',
localPath: '/etc/x',
fileName: 'heap.sh',
generatedName: /^perf-[0-9a-f-]{36}\.hprof$/,
},
{
name: 'a perfetto trace stop keeps the suffix of its kind',
command: 'perf',
positionals: ['trace', 'stop'],
flags: { kind: 'perfetto' },
field: 'outPath',
localPath: '/etc/x',
fileName: 'x.sh',
generatedName: /^perf-[0-9a-f-]{36}\.perfetto-trace$/,
},
{
name: 'a trace stop with its own --out writes there',
command: 'trace',
positionals: ['stop', 'client/t.trace'],
field: 'outPath',
registered: 'client/t.trace',
localPath: '/etc/x',
expected: 'client/t.trace',
},
...(process.platform === 'win32' ? [] : posixNameCases),
])('remote artifact materialization: $name', async (c, t) => {
Expand All @@ -163,6 +221,7 @@ test.for<MaterializationCase>([
command: c.command,
session: 'capture',
positionals: c.positionals ?? ['stop'],
...(c.flags ? { flags: c.flags } : {}),
meta: {
cwd: inRoot('cwd'),
...(c.registered ? { clientArtifactPaths: { [field]: inRoot(c.registered) } } : {}),
Expand Down Expand Up @@ -199,6 +258,52 @@ test.for<MaterializationCase>([
}
});

test('a directory-shaped trace response is refused and keeps the existing output file', async (t) => {
if (await skipWhenLoopbackUnavailable(t, 'remote artifact download')) return;
const root = mkdtempForTestSync('agent-device-remote-artifact-capture-dir-');
const outPath = path.join(root, 't.trace');
fs.writeFileSync(outPath, 'previous-bytes');
let requests = 0;
const server = http.createServer((_req, res) => {
requests += 1;
res.writeHead(500).end();
});
try {
const port = await listenOnLoopback(server);
await expect(
materializeRemoteArtifacts(
{ baseUrl: `http://127.0.0.1:${port}`, token: 'secret' },
{
token: 'secret',
command: 'trace',
session: 'capture',
positionals: ['stop', outPath],
meta: { cwd: root, clientArtifactPaths: { outPath } },
},
{
ok: true,
data: {
artifacts: [
{
artifactId: 'a1',
field: 'outPath',
artifactType: 'test-artifacts',
path: '/daemon/x',
},
],
},
},
createTestHostEnvironment(),
path.join(root, 'state'),
),
).rejects.toMatchObject({ details: { reason: 'remote_capture_output_directory_shaped' } });
expect(requests).toBe(0);
expect(fs.readFileSync(outPath, 'utf8')).toBe('previous-bytes');
} finally {
await closeLoopbackServer(server);
}
});

type InvalidNameCase = {
name: string;
field: string;
Expand Down
86 changes: 58 additions & 28 deletions packages/remote/src/daemon-artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,12 @@ async function downloadResponseArtifacts(
return { ok: true, data: nextData };
}

/** Why a remote trace or perf capture is refused before any local path is prepared. */
const REMOTE_CAPTURE_OUTPUT_REASONS = {
// The daemon returned a directory-shaped artifact for a trace or perf output, which is one file.
directoryShaped: { reason: 'remote_capture_output_directory_shaped' },
} as const satisfies ReasonTable<'remote transfer'>;

async function downloadOneArtifact(
endpoint: RemoteDaemonArtifactEndpoint,
req: DaemonWireRequest,
Expand All @@ -602,6 +608,13 @@ async function downloadOneArtifact(
},
): Promise<void> {
if (typeof artifact.field !== 'string' || isClientOwnedResponseField(artifact.field)) return;
if (isCaptureOutPath(req, artifact) && artifact.artifactType === 'test-artifacts') {
throw new AppError(
'COMMAND_FAILED',
`The remote ${req.command} capture came back as a directory, so the client wrote nothing.`,
{ reason: REMOTE_CAPTURE_OUTPUT_REASONS.directoryShaped.reason },
);
}
const destination = resolveMaterializedArtifactPath(artifact, req, host);
if (!destination || destination.path.includes('\0')) {
dropped.push({ field: artifact.field, reason: 'artifact_name_invalid' });
Expand Down Expand Up @@ -730,29 +743,13 @@ function withoutScriptFieldOwner(
return kept;
}

/**
* Whether this request finishes a trace or perf capture whose destination the daemon echoes
* from an earlier request. The finishing actions mirror `request-finalization.ts`.
*/
function finishesEarlierClientCapture(req: DaemonWireRequest): boolean {
const [first, second, third] = (req.positionals ?? []).map((value) => value.toLowerCase());
switch (req.command) {
case 'trace':
return first === 'stop';
case 'perf':
return third === 'stop' || third === 'report' || (first === 'trace' && second === 'stop');
default:
return false;
}
}

function isRecordStop(req: DaemonWireRequest): boolean {
return req.command === 'record' && req.positionals?.[0]?.toLowerCase() === 'stop';
}

/**
* A path from this request wins. A record stop without one can use only a plain name in cwd.
* Trace and perf stop or report can still use an echoed destination from an earlier request.
* Trace and perf output without one goes to a locally named file in cwd.
* A NUL in a response file name cannot provide a fallback destination.
*/
function resolveMaterializedArtifactPath(
Expand All @@ -762,22 +759,55 @@ function resolveMaterializedArtifactPath(
): { path: string; fallback: boolean } | undefined {
const requestedPath = req.meta?.clientArtifactPaths?.[artifact.field];
if (hasNonEmptyString(requestedPath)) return { path: requestedPath, fallback: false };
if (isRecordStop(req)) {
const requested = artifact.field === 'outPath' ? req.positionals[1] : undefined;
if (hasNonEmptyString(requested)) {
return { path: resolveAbsoluteClientPath(requested, req.meta?.cwd, host), fallback: false };
}
if (typeof artifact.fileName === 'string' && artifact.fileName.includes('\0')) return undefined;
const fileName = localFileName(artifact.fileName) ?? `recording-${crypto.randomUUID()}`;
return { path: path.resolve(req.meta?.cwd ?? host.cwd, fileName), fallback: true };
}
if (hasNonEmptyString(artifact.localPath) && finishesEarlierClientCapture(req)) {
return { path: artifact.localPath, fallback: false };
if (isRecordStop(req)) return resolveRecordStopPath(artifact, req, host);
if (isCaptureOutPath(req, artifact)) {
return { path: generatedCapturePath(req, host), fallback: false };
}
Comment thread
thymikee marked this conversation as resolved.
Resolved
const fallbackPath = resolveOrdinaryArtifactFallbackPath(artifact, req.meta?.cwd ?? host.cwd);
return fallbackPath ? { path: fallbackPath, fallback: false } : undefined;
}

function isCaptureOutPath(req: DaemonWireRequest, artifact: DaemonArtifact): boolean {
return (req.command === 'trace' || req.command === 'perf') && artifact.field === 'outPath';
}

function resolveRecordStopPath(
artifact: DaemonArtifact,
req: DaemonWireRequest,
host: HostEnvironment,
): { path: string; fallback: boolean } | undefined {
const requested = artifact.field === 'outPath' ? req.positionals?.[1] : undefined;
if (hasNonEmptyString(requested)) {
return { path: resolveAbsoluteClientPath(requested, req.meta?.cwd, host), fallback: false };
}
if (typeof artifact.fileName === 'string' && artifact.fileName.includes('\0')) return undefined;
const fileName = localFileName(artifact.fileName) ?? `recording-${crypto.randomUUID()}`;
return { path: path.resolve(req.meta?.cwd ?? host.cwd, fileName), fallback: true };
}

function generatedCapturePath(req: DaemonWireRequest, host: HostEnvironment): string {
const name = `${req.command}-${crypto.randomUUID()}${generatedCaptureSuffix(req)}`;
return path.resolve(req.meta?.cwd ?? host.cwd, name);
}

const CAPTURE_KIND_SUFFIXES = new Map([
['xctrace', '.tar.gz'],
['perfetto', '.perfetto-trace'],
['simpleperf', '.perf.data'],
['android-hprof', '.hprof'],
['memgraph', '.memgraph'],
]);

/** The suffix comes from the local command and capture kind, never from a daemon-supplied name. */
function generatedCaptureSuffix(req: DaemonWireRequest): string {
if (req.command === 'trace') return '.log';
const words = (req.positionals ?? []).map((value) => value.toLowerCase());
if (words[0] === 'cpu' && words[2] === 'report') return '.json';
const flagKind = typeof req.flags?.kind === 'string' ? req.flags.kind.toLowerCase() : undefined;
const kind = flagKind ?? words.find((word) => CAPTURE_KIND_SUFFIXES.has(word));
return (kind && CAPTURE_KIND_SUFFIXES.get(kind)) || '';
}
Comment thread
thymikee marked this conversation as resolved.
Resolved

function resolveOrdinaryArtifactFallbackPath(
artifact: DaemonArtifact,
cwd: string,
Expand Down
4 changes: 2 additions & 2 deletions src/commands/schema/cli-help-workflows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,10 +163,10 @@ Diagnostics and traces:
perf xctrace keeps the .trace artifact on disk; CPU report returns a bounded weighted top-function summary. Do not dump .trace contents into context.
For Android native CPU/trace evidence, use perf artifacts instead of raw adb/simpleperf/perfetto output:
agent-device perf cpu profile start --kind simpleperf --out /tmp/cpu.perf.data
agent-device perf cpu profile stop --kind simpleperf
agent-device perf cpu profile stop --kind simpleperf --out /tmp/cpu.perf.data
agent-device perf cpu profile report --kind simpleperf --out /tmp/cpu-report.json
agent-device perf trace start --kind perfetto --out /tmp/app.perfetto-trace
agent-device perf trace stop --kind perfetto
agent-device perf trace stop --kind perfetto --out /tmp/app.perfetto-trace
Treat native perf output as the agent evidence: for example, state=stopped, outPath=/tmp/app.perfetto-trace, sizeBytes=5392410, method=adb-shell-perfetto. The 5.3 MB raw trace stays in the artifact.
Keep the saved Simpleperf profile at its stop output path until you generate the report.
CPU reports return at most ten top functions in structured data and print five in default CLI output.
Expand Down
12 changes: 6 additions & 6 deletions test/wire-compat/ledger.json
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@
"packages/remote/src/daemon-artifacts.ts#downloadRemoteArtifact": "sha256:3f3b6c01601c54ab2c76c8cb0946de623da4d24ba32254c75ae8a3993f66adcf",
"packages/remote/src/daemon-artifacts.ts#isRemoteDaemon": "sha256:0f6a714c5f60ce4e8548d811b516d8b6241eca9f7e5414733732da395b8a00e7",
"packages/remote/src/daemon-artifacts.ts#materializeRemoteArtifacts": "sha256:ec5fba6dc0c74701c058bd72f3797b907574b51d73816cfa686985e0bf3bc794",
"packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath": "sha256:06dc215c06a9d2ea5a3821faf31b297a2e2f63928672c08c637b132beee726be",
"packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath": "sha256:19bb1646a1e2044844f4ec632a4218d7924955e6907437a3bd0824781bffb6e6",
"packages/remote/src/daemon-artifacts.ts#resolveOrdinaryArtifactFallbackPath": "sha256:e8b1cb5243194e1d4fc7e376979ca5aae3aaf55cfdd33102e1410b2033fb3a4f",
"packages/remote/src/remote-request-diagnostics.ts#DiagnosticsHandoff": "sha256:53cf957caab9bf59c7743373aa544e2e0904dc49db7d1ca84b03fe6be19f35ce",
"packages/remote/src/remote-request-diagnostics.ts#RemoteDaemonErrorPayload": "sha256:8fbcbcdf4bae7b66a08e465a72593794f36364759f18f1a814cd39dfdb76f309",
Expand Down Expand Up @@ -248,7 +248,7 @@
"packages/daemon-contracts/src/daemon-resolution.ts#DaemonCapability": "sha256:2a5acf280a72e3d54c5ad7b52aece3ced37a30e4e721ef106a98e3bbd18ddbc3",
"packages/daemon-contracts/src/daemon-resolution.ts#readDaemonCapabilities": "sha256:e410d36be74d307f7e5d8ddae63af5aae77f8eef77951ce9eeb7724f2fefae88",
"packages/remote/src/daemon-artifacts.ts#downloadResponseArtifacts": "sha256:5259010d194d123cb1a9f0eee38bbaef12337613c80b531c5f554953b8c1ada1",
"packages/remote/src/daemon-artifacts.ts#downloadOneArtifact": "sha256:9460cc0d14310109e198612e18d2f1b5ba5e146e5f12fe58195fd97dba37bdc0",
"packages/remote/src/daemon-artifacts.ts#downloadOneArtifact": "sha256:6e8daf83c809a30f95594ab77f0e5e02fe30f0000d73d0c6d6ac39b225320e7c",
"packages/remote/src/daemon-artifacts.ts#DroppedArtifact": "sha256:c340f0a9a4b99d0664f8c32ac78b3a054c95e7f171cf3531331f7cdc143e0cfb",
"packages/remote/src/session-script-destination.ts#SessionScriptDelivery": "sha256:741fafbb8e2b43e2e967b2f4206f1d60017a636f63e3cde68b6258fd4efefa18",
"packages/remote/src/script-version-publisher.ts#publishScriptVersion": "sha256:c5fd24804377237c8da43a5e17e5469496e7ac76f01a3a6099859e815a6c9c04",
Expand Down Expand Up @@ -569,8 +569,8 @@
},
{
"declaration": "packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath",
"digest": "sha256:06dc215c06a9d2ea5a3821faf31b297a2e2f63928672c08c637b132beee726be",
"rationale": "#4518 and #4661 change client-side destination selection. Authorized destinations keep precedence. Fallbacks reject NUL names, and ordinary captures reject explicit non-string names and Windows drive-qualified basenames under Windows path rules. Daemons send the same artifact fields with the same framing."
"digest": "sha256:19bb1646a1e2044844f4ec632a4218d7924955e6907437a3bd0824781bffb6e6",
"rationale": "#4518, #4661 and #5338 change client-side destination selection. Authorized destinations keep precedence. Fallbacks reject NUL names, and ordinary captures reject explicit non-string names and Windows drive-qualified basenames under Windows path rules. A trace or perf output without a requested path goes to a generated file in cwd, with a suffix from the local command and capture kind and never from a daemon-supplied name. Daemons send the same artifact fields with the same framing."
},
{
"declaration": "packages/daemon/src/server/http/http-server.ts#MAX_HTTP_RPC_BODY_BYTES",
Expand Down Expand Up @@ -774,8 +774,8 @@
},
{
"declaration": "packages/remote/src/daemon-artifacts.ts#downloadOneArtifact",
"digest": "sha256:9460cc0d14310109e198612e18d2f1b5ba5e146e5f12fe58195fd97dba37bdc0",
"rationale": "The file and directory download paths inherit the client-local handoff through their endpoint. Routes, headers and body framing are unchanged."
"digest": "sha256:6e8daf83c809a30f95594ab77f0e5e02fe30f0000d73d0c6d6ac39b225320e7c",
"rationale": "The file and directory download paths inherit the client-local handoff through their endpoint. #5338 writes a trace or perf capture to its client-chosen or generated path as one file and refuses a directory-shaped answer for it before any local path is prepared; suite directory delivery is unchanged. This is a client-local choice. Routes, headers and body framing are unchanged."
},
{
"declaration": "packages/remote/src/artifact-download.ts#RemoteArtifactRequest",
Expand Down
1 change: 1 addition & 0 deletions website/docs/docs/error-reasons.md
Original file line number Diff line number Diff line change
Expand Up @@ -1126,6 +1126,7 @@ These reasons can come from more than one command.
| --- | --- |
| `artifact_too_large` | The remote artifact is larger than the bytes this download may hold. |
| `remote_script_lifecycle_unsupported` | `--save-script` was asked for on a command whose script lifecycle the daemon does not remote. |
| `remote_capture_output_directory_shaped` | The daemon returned a directory-shaped artifact for a trace or perf output, which is one file. |
| `artifact_preparation_deadline_exceeded` | Preparing the artifact for upload, the read and the hop together, outlived its budget. |
| `cross-origin-redirect` | The upload endpoint answered with a redirect to an origin the caller never named. |

Expand Down
2 changes: 1 addition & 1 deletion website/docs/docs/remote-proxy.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ Remote screenshots, recordings, performance captures, and trace logs use generat
the daemon. When you specify an output path through the CLI, SDK, or MCP, it selects the download
destination on your machine. A recording is different: it downloads to the path named by the
`record stop` request, or otherwise to the working directory with a warning. The directory of a
`record start` path does not carry over; the working-directory fallback keeps only its file name. Direct RPC callers receive artifact IDs and download each result with
`record start` path does not carry over; the working-directory fallback keeps only its file name. A `trace stop <path>` or `perf ... stop --out <path>` download uses its own path; the path of the earlier `start` does not carry over, and without one the file goes to the working directory under a generated `trace-<uuid>` or `perf-<uuid>` name. A trace gets `.log`. A perf download gets a suffix only when the command names it: `.json` for a CPU profile report, `.tar.gz` for an xctrace capture, or `.perfetto-trace`, `.perf.data`, `.hprof`, or `.memgraph` for an explicit `--kind`; otherwise the file has no extension. Direct RPC callers receive artifact IDs and download each result with
`GET /artifacts/<id>` using the same authentication. For an artifact from a leased session, also
send the lease id in the `x-agent-device-lease-id` header: without it, `GET /artifacts` does not
list the artifact and the download fails with `UNAUTHORIZED` and reason `LEASE_OUTPUT_MISMATCH`.
Expand Down
Loading