Repository navigation
Expand file tree
/
Copy pathandroid-search-diagnostic.ts
More file actions
147 lines (147 loc) · 6.17 KB
/
Copy pathandroid-search-diagnostic.ts
File metadata and controls
147 lines (147 loc) · 6.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import fs from 'node:fs';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { runCmdSync } from '@agent-device/host-kit/command';
import { normalizeError } from '@agent-device/kernel/errors';
type DiagnosticData = { pass?: boolean; text?: string };
const [serial, stateDir, outputDir] = process.argv.slice(2);
if (!serial || !stateDir || !outputDir) {
throw new Error('Usage: android-search-diagnostic.ts <serial> <state-dir> <output-dir>');
}
fs.mkdirSync(outputDir, { recursive: true });
const session = `readiness-search-diagnostic-${randomUUID()}`;
const startedAt = Date.now();
const deadline = startedAt + 180_000;
const commandResults: Record<string, { exitCode: number; data?: DiagnosticData }> = {};
const commandRecords: unknown[] = [];
const targetFlags = ['--platform', 'android', '--serial', serial];
const sessionFlags = ['--state-dir', stateDir, '--session', session, '--json', '--debug'];
function capture(name: string, executable: string, args: string[], cleanup = false) {
const remaining = deadline - Date.now() - (cleanup ? 0 : 15_000);
if (remaining <= 0) throw new Error('Diagnostic wall-clock budget exhausted');
let result;
let failure;
try {
result = runCmdSync(executable, args, {
allowFailure: true,
timeoutMs: Math.min(15_000, remaining),
maxBuffer: 8 * 1024 * 1024,
});
} catch (error) {
failure = normalizeError(error);
result = { exitCode: -1, stdout: '', stderr: String(error) };
}
fs.writeFileSync(path.join(outputDir, `${name}.stdout.txt`), result.stdout);
fs.writeFileSync(path.join(outputDir, `${name}.stderr.txt`), result.stderr);
let json;
try {
json = JSON.parse(result.stdout);
} catch {
json = undefined;
}
const record = { exitCode: result.exitCode, data: json?.data as DiagnosticData | undefined };
commandResults[name] = record;
commandRecords.push({ name, executable, args, exitCode: result.exitCode, failure });
return record;
}
function cli(name: string, args: string[], cleanup = false) {
const cliArgs = ['bin/agent-device.mjs', ...args, ...targetFlags, ...sessionFlags];
return capture(name, process.execPath, cliArgs, cleanup);
}
function adb(name: string, args: string[]) {
return capture(name, 'adb', ['-s', serial, ...args]);
}
function deviceState(prefix: string) {
adb(`${prefix}-window`, ['shell', 'dumpsys', 'window', 'windows']);
adb(`${prefix}-activity`, ['shell', 'dumpsys', 'activity', 'activities']);
adb(`${prefix}-ime`, ['shell', 'dumpsys', 'input_method']);
}
let diagnosticError: string | undefined;
try {
adb('image', ['shell', 'getprop']);
const resolver = ['shell', 'cmd', 'package', 'resolve-activity', '--brief'];
const intent = ['-a', 'android.settings.APP_SEARCH_SETTINGS'];
const category = ['-c', 'android.intent.category.DEFAULT'];
adb('search-resolution', [...resolver, ...intent, ...category]);
const resolution = fs.readFileSync(path.join(outputDir, 'search-resolution.stdout.txt'), 'utf8');
const resolvedPackage = /^([A-Za-z0-9_.]+)\/[A-Za-z0-9_.$]+$/m.exec(resolution)?.[1];
adb('search-configured-package', [
'shell',
'cmd',
'overlay',
'lookup',
'com.android.settings',
'com.android.settings:string/config_settingsintelligence_package_name',
]);
const configured = fs
.readFileSync(path.join(outputDir, 'search-configured-package.stdout.txt'), 'utf8')
.trim();
const configuredPackage = /^[A-Za-z][A-Za-z0-9_.]*$/.test(configured) ? configured : undefined;
const packages = new Set([
'com.android.settings',
'com.android.settings.intelligence',
'com.google.android.settings.intelligence',
...(resolvedPackage ? [resolvedPackage] : []),
...(configuredPackage ? [configuredPackage] : []),
]);
for (const packageName of packages) {
adb(`package-${packageName}`, ['shell', 'dumpsys', 'package', packageName]);
}
cli('open', ['open', 'settings', '--relaunch']);
cli('before-tree', ['snapshot', '-i', '--raw']);
cli('search-attrs', ['get', 'attrs', 'text="Search Settings"', '--raw']);
deviceState('before-click');
cli('search-click', ['click', 'text="Search Settings"']);
deviceState('after-click');
cli('after-click-keyboard', ['keyboard', 'status']);
cli('after-click-tree', ['snapshot', '-i', '--raw']);
cli('after-click-image', ['screenshot', path.resolve(outputDir, 'after-click.png')]);
const editor = cli('editor-wait', ['wait', 'role=text-field', '5000']);
const focus = cli('editor-focused', ['is', 'focused', 'role=text-field']);
if (editor.exitCode === 0 && focus.exitCode === 0 && focus.data?.pass === true) {
cli('type', ['type', 'Display']);
cli('query-wait', ['wait', 'role=text-field text="Display"', '5000']);
cli('query-readback', ['get', 'text', 'role=text-field']);
cli('after-type-tree', ['snapshot', '-i', '--raw']);
cli('after-type-image', ['screenshot', path.resolve(outputDir, 'after-type.png')]);
}
} catch (error) {
diagnosticError = String(error);
} finally {
try {
const tail = ['logcat', '-d', '-t', '500', '-v', 'threadtime'];
const filters = ['ActivityTaskManager:I', 'ActivityManager:I', 'AndroidRuntime:E', '*:S'];
adb('logcat', [...tail, ...filters]);
} catch (error) {
diagnosticError ??= String(error);
}
try {
cli('close', ['close'], true);
} catch (error) {
diagnosticError ??= String(error);
}
}
const editorFocused =
commandResults['editor-focused']?.exitCode === 0 &&
commandResults['editor-focused']?.data?.pass === true;
const queryReadback = commandResults['query-readback']?.data?.text;
const passed = ['open', 'search-click', 'editor-wait', 'type', 'query-wait', 'query-readback'];
const semanticSuccess =
!diagnosticError &&
passed.every((name) => commandResults[name]?.exitCode === 0) &&
editorFocused &&
queryReadback === 'Display';
const cleanupSucceeded = commandResults.close?.exitCode === 0;
const summary = {
head: process.env.GITHUB_SHA,
session,
startedAt,
finishedAt: Date.now(),
diagnosticError,
semanticSuccess,
cleanupSucceeded,
commands: commandRecords,
};
fs.writeFileSync(path.join(outputDir, 'summary.json'), JSON.stringify(summary, null, 2) + '\n');
console.log(JSON.stringify(summary, null, 2));
process.exitCode = semanticSuccess && cleanupSucceeded ? 0 : 2;