Repository navigation
Expand file tree
/
Copy pathdoctor.ts
More file actions
266 lines (247 loc) · 9.46 KB
/
Copy pathdoctor.ts
File metadata and controls
266 lines (247 loc) · 9.46 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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
import path from 'node:path';
import type { DeviceInfo } from '@agent-device/kernel/device';
import { normalizeError } from '@agent-device/kernel/errors';
import type { DoctorCheck } from '@agent-device/contracts/observability';
import type { HostDiagnosticsContext } from '@agent-device/contracts/host-diagnostics';
import { commandOutput, firstOutputLine } from '@agent-device/provision-kit/toolchain-probe';
import { resolveAndroidAdbExecutor, runAdbShell, type AndroidAdbExecutor } from './adb-executor.ts';
import {
isAndroidTestImeActive,
readAndroidDefaultInputMethod,
ANDROID_TEST_IME_SETTINGS_KEYS,
} from './ime-lifecycle.ts';
import { resolveAndroidImeHelperArtifact } from './ime-helper.ts';
import {
requireAndroidAdbHost,
type AndroidAdbEnvironment,
type AndroidAdbFileHost,
} from './adb-host.ts';
const ANDROID_PROBE_TIMEOUT_MS = 2000;
const WINDOWS_ADB_ON_POSIX_HOST_REASON = 'android_adb_windows_binary_on_posix_host';
type AndroidLicenseState = 'accepted' | 'missing' | 'unknown';
type AndroidToolchainProbe = {
license: AndroidLicenseState;
sdkRoot: string | undefined;
versionLine: string | undefined;
};
export async function androidToolchainCheck(
environment: AndroidAdbEnvironment,
hostPlatform: NodeJS.Platform,
files: Pick<AndroidAdbFileHost, 'access'> = requireAndroidAdbHost().files,
): Promise<DoctorCheck> {
const sdkRoot = environment.ANDROID_HOME || environment.ANDROID_SDK_ROOT;
const license = await androidLicenseState(sdkRoot, files);
const versionOutput = await commandOutput('adb', ['version']);
const versionLine = versionOutput === undefined ? undefined : firstOutputLine(versionOutput);
if (!versionOutput || !versionLine) return missingAndroidAdbCheck(sdkRoot, license);
const adbPath = androidAdbInstallPath(versionOutput);
if (hostPlatform !== 'win32' && adbPath && isWindowsHostPath(adbPath)) {
return windowsAdbOnPosixHostCheck({ adbPath, sdkRoot, versionLine });
}
return androidAdbCheck({
license,
sdkRoot,
versionLine,
});
}
/** The android family's device diagnostics: Metro reverse mapping plus orphaned test-IME. */
export async function androidDeviceChecks(
device: DeviceInfo,
context: HostDiagnosticsContext,
): Promise<readonly DoctorCheck[]> {
if (device.platform !== 'android') return [];
// The provider-scope override travels opaquely through the neutral context; this family is
// the one owner that narrows it back to its own executor type.
const adb = resolveAndroidAdbExecutor(
device,
context.transportOverrides.androidAdb as AndroidAdbExecutor | undefined,
);
const checks: DoctorCheck[] = [];
if (context.shouldProbeMetro) {
checks.push(await probeAndroidReverse(adb, device.id, context.metroPort));
}
checks.push(await probeAndroidTestIme(adb, device));
return checks;
}
async function probeAndroidTestIme(
adb: AndroidAdbExecutor,
device: DeviceInfo,
): Promise<DoctorCheck> {
try {
const currentIme = await readAndroidDefaultInputMethod(adb);
const helperActiveInThisProcess = isAndroidTestImeActive(device);
const isHelperCurrentIme = currentIme === (await resolveAndroidImeHelperServiceComponent());
if (isHelperCurrentIme && !helperActiveInThisProcess) {
return await buildOrphanedTestImeCheck(adb, device, currentIme);
}
return buildActiveTestImeCheck(device, currentIme, helperActiveInThisProcess);
} catch (error) {
return buildTestImeProbeFailureCheck(error);
}
}
async function resolveAndroidImeHelperServiceComponent(): Promise<string | undefined> {
try {
return (await resolveAndroidImeHelperArtifact()).manifest.serviceComponent;
} catch {
return undefined;
}
}
// Test IME is active but no session in this process owns it: orphaned by a crashed daemon run.
async function buildOrphanedTestImeCheck(
adb: AndroidAdbExecutor,
device: DeviceInfo,
currentIme: string,
): Promise<DoctorCheck> {
const previousImeResult = await runAdbShell(
adb,
['settings', 'get', 'secure', ANDROID_TEST_IME_SETTINGS_KEYS.previousIme],
{ allowFailure: true, timeoutMs: ANDROID_PROBE_TIMEOUT_MS },
);
const previousIme = previousImeResult.stdout.trim();
const restoreTarget = previousIme && previousIme !== 'null' ? previousIme : undefined;
return {
id: 'android-test-ime',
status: 'fail',
summary: `Android test IME helper is the active input method on ${device.id}, but no active session owns it -- likely left over from a crashed session.`,
hint: 'A stuck test IME leaves the real keyboard unavailable on this device until restored.',
command: restoreTarget
? `adb -s ${device.id} shell ime set ${restoreTarget}`
: `adb -s ${device.id} shell ime list -s`,
evidence: { currentIme, previousIme: restoreTarget },
};
}
function buildActiveTestImeCheck(
device: DeviceInfo,
currentIme: string,
helperActiveInThisProcess: boolean,
): DoctorCheck {
return {
id: 'android-test-ime',
status: 'pass',
summary: helperActiveInThisProcess
? `Android test IME helper is active for this session on ${device.id}.`
: `Android test IME helper is not active on ${device.id}; the device's normal IME is in use.`,
evidence: { currentIme },
};
}
function buildTestImeProbeFailureCheck(error: unknown): DoctorCheck {
const normalized = normalizeError(error);
return {
id: 'android-test-ime',
status: 'warn',
summary: 'Could not inspect the Android test IME helper state.',
hint: normalized.message,
evidence: { code: normalized.code },
};
}
async function probeAndroidReverse(
adb: AndroidAdbExecutor,
serial: string,
metroPort: number,
): Promise<DoctorCheck> {
try {
const result = await adb(['reverse', '--list'], {
allowFailure: true,
timeoutMs: ANDROID_PROBE_TIMEOUT_MS,
});
const expected = `tcp:${metroPort} tcp:${metroPort}`;
const hasReverse = result.stdout.includes(expected);
return {
id: 'android-reverse',
status: hasReverse ? 'pass' : 'warn',
summary: hasReverse
? `Android adb reverse exists for Metro port ${metroPort}.`
: `Android adb reverse is missing for Metro port ${metroPort}.`,
command: hasReverse
? undefined
: `adb -s ${serial} reverse tcp:${metroPort} tcp:${metroPort}`,
evidence: { stdout: result.stdout.trim() },
};
} catch (error) {
const normalized = normalizeError(error);
return {
id: 'android-reverse',
status: 'warn',
summary: 'Could not inspect Android adb reverse mappings.',
hint: normalized.message,
evidence: { code: normalized.code },
};
}
}
/** The binary path adb reports for itself on its `Installed as` version line. */
function androidAdbInstallPath(versionOutput: string): string | undefined {
return /^Installed as (.+)$/m.exec(versionOutput)?.[1]?.trim();
}
/** A drive-letter or UNC path, which only a Windows binary reports. */
function isWindowsHostPath(candidate: string): boolean {
return /^(?:[A-Za-z]:[\\/]|\\\\)/.test(candidate);
}
/**
* A Windows adb.exe reached from a Linux host (WSL interop) answers `adb version`, but it resolves
* every host path it is handed as a Windows path, so pulls, pushes, and installs miss the Linux files.
*/
function windowsAdbOnPosixHostCheck(
probe: Readonly<{ adbPath: string; sdkRoot: string | undefined; versionLine: string }>,
): DoctorCheck {
return {
id: 'toolchain',
status: 'fail',
summary: `Android toolchain: adb on PATH is the Windows binary ${probe.adbPath}, which cannot use this host's file paths.`,
hint: 'Under WSL, install Linux Android platform-tools, put them first on PATH, and point ANDROID_HOME at a Linux SDK instead of one under /mnt/<drive>.',
evidence: {
reason: WINDOWS_ADB_ON_POSIX_HOST_REASON,
adbPath: probe.adbPath,
adbVersion: probe.versionLine,
androidHome: probe.sdkRoot ?? null,
},
};
}
function androidAdbCheck(probe: AndroidToolchainProbe): DoctorCheck {
return {
id: 'toolchain',
status: androidToolchainStatus(probe),
summary: probe.versionLine
? `Android toolchain: ${probe.versionLine}; ${androidSdkSummary(probe.sdkRoot)}.`
: 'Android toolchain: adb is present but version check failed.',
hint:
probe.license === 'missing'
? 'Accept Android SDK licenses before installing/building apps.'
: undefined,
command: probe.license === 'missing' ? 'sdkmanager --licenses' : undefined,
evidence: {
adbVersion: probe.versionLine ?? null,
androidHome: probe.sdkRoot ?? null,
license: probe.license,
},
};
}
function androidToolchainStatus(probe: AndroidToolchainProbe): DoctorCheck['status'] {
return probe.versionLine && probe.sdkRoot && probe.license !== 'missing' ? 'pass' : 'info';
}
function androidSdkSummary(sdkRoot: string | undefined): string {
return sdkRoot ? 'ANDROID_HOME/ANDROID_SDK_ROOT set' : 'ANDROID_HOME unset';
}
function missingAndroidAdbCheck(
sdkRoot: string | undefined,
license: AndroidLicenseState,
): DoctorCheck {
return {
id: 'toolchain',
status: 'info',
summary: 'Android toolchain: adb not found on PATH.',
hint: 'Install Android platform-tools or add adb to PATH.',
evidence: { androidHome: sdkRoot ?? null, license },
};
}
async function androidLicenseState(
sdkRoot: string | undefined,
files: Pick<AndroidAdbFileHost, 'access'>,
): Promise<AndroidLicenseState> {
if (!sdkRoot) return 'unknown';
try {
await files.access(path.join(sdkRoot, 'licenses', 'android-sdk-license'));
return 'accepted';
} catch {
return 'missing';
}
}