Skip to content

Commit c89972c

Browse files
committed
fix(adb): evaluate the full activity start report
Evaluate stdout and stderr together, giving hard errors and non-ok wait statuses precedence over an attempted Starting line. Retain raw streams and typed partial launch facts when Activity Manager refuses or times out; retain successful raw output too. Validation: parser/provider tests and public MCP app/activity starts through a fake executable at the real process boundary. Real Android device behavior was not verified; device-reported timeout remains distinct from a host deadline. Fixes #2225
1 parent 5ab0cbb commit c89972c

7 files changed

Lines changed: 390 additions & 30 deletions

File tree

‎src/adb/AdbProvider.ts‎

Lines changed: 42 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,11 @@ import {
2323
type AnalysisExecution,
2424
} from "../application/AnalysisProvider.js";
2525
import type {
26+
AdbActivityStartPartialObservation,
2627
AdbAcquiredFilePartialObservation,
2728
AdbRequest,
2829
} from "../domain/adb/adbDeviceAnalysis.js";
30+
import { adbResultSchemas } from "../domain/adb/adbDeviceAnalysis.js";
2931
import {
3032
AnalysisArtifactChangedError,
3133
AnalysisCancelledError,
@@ -1985,28 +1987,55 @@ export class AdbProvider {
19851987
signal,
19861988
);
19871989
if (!started.ok) return started;
1988-
const verdict = parseAmStartOutput(started.value.stdout);
1989-
if (verdict.status === "refused")
1990+
const verdict = parseAmStartOutput(
1991+
started.value.stdout,
1992+
started.value.stderr,
1993+
);
1994+
const result = {
1995+
...resultFields,
1996+
started_activity: verdict.startedActivity,
1997+
reported_activity: verdict.activity,
1998+
reported_status: verdict.reportedStatus,
1999+
};
2000+
if (verdict.status === "refused") {
2001+
const partialObservation: AdbActivityStartPartialObservation =
2002+
operation === "start_adb_app"
2003+
? {
2004+
provider_id: "adb",
2005+
operation,
2006+
result: adbResultSchemas.start_adb_app.parse(result),
2007+
}
2008+
: {
2009+
provider_id: "adb",
2010+
operation,
2011+
result: adbResultSchemas.start_adb_activity.parse(result),
2012+
};
19902013
return err(
19912014
new AnalysisUnsupportedTargetError(
19922015
operation,
19932016
serial,
19942017
verdict.reason ?? "am start refused the intent",
2018+
{
2019+
capturedOutput: {
2020+
stdout: started.value.stdout,
2021+
stderr: started.value.stderr,
2022+
truncated: false,
2023+
},
2024+
partialObservation,
2025+
},
19952026
),
19962027
);
2028+
}
19972029
return ok(
1998-
createAnalysisExecution(
1999-
{
2000-
...resultFields,
2001-
started_activity: verdict.startedActivity,
2002-
},
2003-
provider,
2004-
{
2005-
limitations: [
2006-
"Starting an activity changes device state; am start -W waits for launch completion but no lifecycle observation is captured",
2007-
],
2030+
createAnalysisExecution(result, provider, {
2031+
rawResult: {
2032+
stdout: started.value.stdout,
2033+
stderr: started.value.stderr,
20082034
},
2009-
) as AnalysisExecution,
2035+
limitations: [
2036+
"Starting an activity changes device state; am start -W waits for launch completion but no lifecycle observation is captured",
2037+
],
2038+
}) as AnalysisExecution,
20102039
);
20112040
}
20122041

‎src/adb/AdbShellOutput.test.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import { describe, expect, it } from "vitest";
2+
3+
import { parseAmStartOutput } from "./AdbShellOutput.js";
4+
5+
const starting =
6+
"Starting: Intent { act=android.intent.action.MAIN cmp=com.example/.Main }";
7+
8+
describe("parseAmStartOutput", () => {
9+
it("recognizes a CRLF wait-timeout report", () => {
10+
expect(
11+
parseAmStartOutput(
12+
`${starting}\r\nStatus: timeout\r\nActivity: com.example/.Main\r\nComplete\r\n`,
13+
),
14+
).toMatchObject({
15+
status: "refused",
16+
activity: "com.example/.Main",
17+
reportedStatus: "timeout",
18+
reason: "am start reported status: timeout",
19+
});
20+
});
21+
22+
it("treats every non-ok status as refusal, including a later status after ok", () => {
23+
expect(
24+
parseAmStartOutput(`${starting}\nStatus: ok\nStatus: timeout\n`),
25+
).toMatchObject({
26+
status: "refused",
27+
reportedStatus: "timeout",
28+
reason: "am start reported status: timeout",
29+
});
30+
expect(
31+
parseAmStartOutput(`${starting}\nStatus: future-value\n`),
32+
).toMatchObject({
33+
status: "refused",
34+
reportedStatus: "future-value",
35+
});
36+
});
37+
38+
it("gives hard errors in either stream priority over status and attempt", () => {
39+
expect(
40+
parseAmStartOutput(
41+
`${starting}\nStatus: timeout\nActivity: com.example/.Main\n`,
42+
"Exception: Activity class does not exist\n",
43+
),
44+
).toEqual({
45+
status: "refused",
46+
startedActivity: "act=android.intent.action.MAIN cmp=com.example/.Main",
47+
activity: "com.example/.Main",
48+
reportedStatus: "timeout",
49+
reason: "Activity class does not exist",
50+
});
51+
expect(
52+
parseAmStartOutput(
53+
`${starting}\nStatus: ok\nError: Activity class does not exist\n`,
54+
),
55+
).toMatchObject({
56+
status: "refused",
57+
reason: "Activity class does not exist",
58+
});
59+
});
60+
61+
it("keeps Starting-only output compatible and refuses no-attempt output", () => {
62+
expect(parseAmStartOutput(starting)).toMatchObject({
63+
status: "started",
64+
reportedStatus: null,
65+
activity: null,
66+
});
67+
expect(
68+
parseAmStartOutput("Status: ok\nWarning: Activity not started\n"),
69+
).toMatchObject({
70+
status: "refused",
71+
startedActivity: null,
72+
reportedStatus: "ok",
73+
});
74+
});
75+
});

‎src/adb/AdbShellOutput.ts‎

Lines changed: 63 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -320,32 +320,80 @@ export const parseResolveActivityOutput = (stdout: string): string | null => {
320320
return lines.length === 0 ? null : lines[lines.length - 1]!;
321321
};
322322

323+
/** Parsed facts and verdict from the full `am start -W` report. */
324+
export interface AmStartOutput {
325+
readonly status: "started" | "refused";
326+
readonly startedActivity: string | null;
327+
readonly activity: string | null;
328+
readonly reportedStatus: string | null;
329+
readonly reason: string | null;
330+
}
331+
323332
/**
324-
* Parse `am start` output. Success prints `Starting: Intent { ... }`;
325-
* refusals print lines starting with `Error:` or `Warning:` and activity
326-
* classes that do not exist name the component.
333+
* Parse the complete `am start -W` report. `Starting:` records an attempt;
334+
* hard errors and any non-ok Activity Manager status determine the verdict.
327335
*/
328336
export const parseAmStartOutput = (
329337
stdout: string,
330-
): {
331-
readonly status: "started" | "refused";
332-
readonly startedActivity: string | null;
333-
readonly reason: string | null;
334-
} => {
335-
const text = stdout.trim();
336-
const starting = /^Starting:\s+Intent\s*\{(.*)\}\s*$/mu.exec(text);
337-
if (starting !== null)
338+
stderr = "",
339+
): AmStartOutput => {
340+
const normalizedStdout = stdout.replaceAll("\r\n", "\n");
341+
const starting = /^Starting:[ \t]+Intent[ \t]*\{(.*)\}[ \t]*$/mu.exec(
342+
normalizedStdout,
343+
);
344+
const startedActivity = starting?.[1]?.trim() ?? null;
345+
const activityMatch = /^Activity:[ \t]*(.*)$/mu.exec(normalizedStdout);
346+
const activity = activityMatch?.[1]?.trim() || null;
347+
const statuses = [...normalizedStdout.matchAll(/^Status:[ \t]*(.*)$/gmu)].map(
348+
(match) => match[1]!.trim(),
349+
);
350+
const nonOkStatus = statuses.find((status) => status.toLowerCase() !== "ok");
351+
const reportedStatus = nonOkStatus ?? statuses[0] ?? null;
352+
const error = [normalizedStdout, stderr.replaceAll("\r\n", "\n")]
353+
.flatMap((stream) => stream.split("\n"))
354+
.map((line) => line.trim())
355+
.map((line) => ({
356+
line,
357+
match: /^(?:Error|Exception)(?::|\b)(.*)$/iu.exec(line),
358+
}))
359+
.find(({ match }) => match !== null);
360+
const errorReason = error?.match?.[1]?.trim() || error?.line || null;
361+
const statusReason =
362+
nonOkStatus === ""
363+
? "am start reported an empty status"
364+
: nonOkStatus === undefined
365+
? null
366+
: `am start reported status: ${nonOkStatus}`;
367+
const reason =
368+
errorReason ??
369+
statusReason ??
370+
(/^Warning:/mu.test(normalizedStdout.trim())
371+
? normalizedStdout.trim().slice(0, 512)
372+
: null);
373+
if (errorReason !== null || nonOkStatus !== undefined)
374+
return {
375+
status: "refused",
376+
startedActivity,
377+
activity,
378+
reportedStatus,
379+
reason: reason ?? "am start did not report a successful launch",
380+
};
381+
if (startedActivity !== null)
338382
return {
339383
status: "started",
340-
startedActivity: starting[1]!.trim(),
384+
startedActivity,
385+
activity,
386+
reportedStatus,
341387
reason: null,
342388
};
343-
const error = /^(?:Error|Warning|Exception)(?::|\b)(.*)$/mu.exec(text);
389+
const text = `${normalizedStdout}\n${stderr.replaceAll("\r\n", "\n")}`.trim();
344390
return {
345391
status: "refused",
346-
startedActivity: null,
392+
startedActivity,
393+
activity,
394+
reportedStatus,
347395
reason:
348-
error?.[1]?.trim() ??
396+
reason ??
349397
(text === "" ? "am start returned no activity" : text.slice(0, 512)),
350398
};
351399
};

‎src/contracts/adb/adbToolContracts.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -326,7 +326,7 @@ export const ADB_TOOL_CONTRACTS = [
326326
name: "start_adb_app",
327327
...toolContractMetadata("start_adb_app"),
328328
description:
329-
"Start one installed app by launching its declared launcher activity: the component is resolved through `cmd package resolve-activity --brief`, then started with `am start -n`. A device-mutating tool for dynamic-analysis workflows; pair with `read_adb_logcat` (pid filter) and `list_adb_processes` to observe the started app, and `stop_adb_app` to end the run.",
329+
"Start one installed app's resolved launcher activity with `am start -W -n`. A device-mutating tool for dynamic analysis. The full wait report determines success; failures retain launch-attempt facts and raw output. Pair with `read_adb_logcat` (pid filter) and `list_adb_processes` to observe the app, and `stop_adb_app` to end the run.",
330330
kind: "adb-provider",
331331
inputSchema: adbInputSchemas.start_adb_app,
332332
outputSchema: evidenceResultOf(adbResultSchemas.start_adb_app),
@@ -341,7 +341,7 @@ export const ADB_TOOL_CONTRACTS = [
341341
name: "start_adb_activity",
342342
...toolContractMetadata("start_adb_activity"),
343343
description:
344-
"Start an intent with `am start`: one action, optional data URI, optional explicit component, and up to 16 typed extras (string, boolean, int, long, float). A device-mutating tool; the activity manager's Starting/Error verdict is preserved verbatim.",
344+
"Start an intent with `am start -W`: one action, optional data URI, optional explicit component, and up to 16 typed extras (string, boolean, int, long, float). A device-mutating tool; the full wait report determines success, with failed-attempt facts and raw output retained.",
345345
kind: "adb-provider",
346346
inputSchema: adbInputSchemas.start_adb_activity,
347347
outputSchema: evidenceResultOf(adbResultSchemas.start_adb_activity),

‎src/domain/adb/adbDeviceAnalysis.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -679,6 +679,8 @@ export const adbResultSchemas = {
679679
package_name: packageNameSchema,
680680
component: z.string().min(1),
681681
started_activity: z.string().nullable(),
682+
reported_activity: z.string().nullable().optional(),
683+
reported_status: z.string().nullable().optional(),
682684
}),
683685
start_adb_activity: z.strictObject({
684686
client,
@@ -694,6 +696,8 @@ export const adbResultSchemas = {
694696
}),
695697
),
696698
started_activity: z.string().nullable(),
699+
reported_activity: z.string().nullable().optional(),
700+
reported_status: z.string().nullable().optional(),
697701
}),
698702
stop_adb_app: z.strictObject({
699703
client,
@@ -702,6 +706,19 @@ export const adbResultSchemas = {
702706
}),
703707
} as const;
704708

709+
/** Launch-attempt facts retained when Activity Manager does not report success. */
710+
export type AdbActivityStartPartialObservation =
711+
| {
712+
readonly provider_id: "adb";
713+
readonly operation: "start_adb_app";
714+
readonly result: z.infer<typeof adbResultSchemas.start_adb_app>;
715+
}
716+
| {
717+
readonly provider_id: "adb";
718+
readonly operation: "start_adb_activity";
719+
readonly result: z.infer<typeof adbResultSchemas.start_adb_activity>;
720+
};
721+
705722
/** Acquired package facts retained when cancellation leaves caller-owned output. */
706723
export type AdbPackagePullPartialObservation = {
707724
readonly provider_id: "adb";

‎src/domain/analysisErrorBase.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@ import type { Evidence } from "./evidence.js";
114114
import type { AndroidPartialObservation } from "./android/androidPartialObservation.js";
115115
import type { FirmwarePartialObservation } from "./firmware/firmwareAnalysis.js";
116116
import type {
117+
AdbActivityStartPartialObservation,
117118
AdbAcquiredFilePartialObservation,
118119
AdbPackagePullPartialObservation,
119120
} from "./adb/adbDeviceAnalysis.js";
@@ -143,5 +144,6 @@ export type AnalysisPartialObservation =
143144
| AndroidPartialObservation
144145
| FirmwarePartialObservation
145146
| NativeUiObservationResult
147+
| AdbActivityStartPartialObservation
146148
| AdbAcquiredFilePartialObservation
147149
| AdbPackagePullPartialObservation;

0 commit comments

Comments
 (0)