Skip to content

Commit ca7c6fc

Browse files
thymikeeclaude
andauthored
fix(providers): secure web text entry, harden WebDriver transport and buttons, honor --relaunch (#4362)
* fix(platform-web): send fill and type text to agent-browser on stdin Web fill, fillRef, and typeText passed the typed text as agent-browser argv, which every host user can read in the process table, and copied that argv into error details. Text entry now runs as a one-entry batch read from stdin; a failed entry raises a typed text-entry-failed error whose details carry no text. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(provider-webdriver): retry session delete and keep status on non-JSON errors A gateway error with a non-JSON body (a 502 HTML page) threw before the status was read, so it carried no status, was never retried, and lost its dispatch disclosure. The status now decides as for a JSON error; the raw body is truncated evidence. DELETE /session/{id} had a single attempt, so one transient failure left a billed session with nothing left to retry it. It now uses the idempotent retry budget, and a W3C invalid session id answer reads as the session already ended. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(provider-webdriver): route system buttons and app opens per Appium driver UiAutomator2 registers no `mobile: pressButton`, so Android home and app-switcher now press KEYCODE_HOME and KEYCODE_APP_SWITCH through `mobile: pressKey`. XCUITest pressButton has no app-switcher button, so the iOS capability map now declares appSwitcher unsupported and the command refuses before the driver. openDevice sent `mobile: activateApp` with no app id, which both drivers reject; a leased session is already the foreground device, so it now sends nothing. An iOS deep link names its app `bundleId`, the field the XCUITest extension reads, instead of `package`. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(contracts): carry open --relaunch through the direct lifecycle binding The shared direct lifecycle closed before a relaunch only when an owner opted in, and otherwise never forwarded terminateRunningApp, so on Linux, web, HarmonyOS, Vega, and the CDP TV owner `open --relaunch` returned success after a plain open. `closeBeforeRelaunch` is now a required choice: the local direct owners close first, and an owner whose open restarts the app (CDP TV) receives terminateRunningApp. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(tv-cdp): drop unreadable CDP frames instead of throwing in the socket handler A non-JSON frame, a non-object message, or a throwing event listener threw inside the WebSocket message handler, which Node reports as an uncaught exception that ends the daemon. The handler now drops an unreadable frame with a debug diagnostic, isolates each listener, and the page log tolerates events that lack their payload fields. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(provider-webdriver): bound and type hosted app uploads, stream the build postHubAppUpload had no deadline, let a network failure escape as a raw TypeError, and reported a rejected credential as generic COMMAND_FAILED; appFileUploadForm read the whole build into memory. The upload now runs under a 15 minute deadline combined with the caller signal, wraps transport failures with a typed reason and their cause, answers 401/403 as UNAUTHORIZED, and streams the file through a file-backed blob. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(provider-webdriver): look up Device Farm artifacts in the session's region Artifact lookup preferred AWS_REGION over the region in the session ARN, so a session created with --aws-region in another region listed its artifacts against the wrong region and failed. The ARN names where the session ran and now decides; the environment is the fallback. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(platform-linux): launch an app binary detached from daemon pipes `open <binary>` ran the app through the captured command runner, which pipes stdio and appends every output chunk to memory until the child exits, so a long-running desktop app grew daemon memory without bound. The app now runs detached with ignored stdio; a spawn failure still emits the linux_app_launch diagnostic. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * style: format provider remediation changes Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * test(provider-webdriver): keep new cases within the file line limit Moves the session-delete release cases to runtime-session.test.ts and the app-open interactor cases to their own file, so neither existing test file passes the 1000-line lint limit. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * test: fix typecheck in the new web and CDP test cases Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(providers): address review findings on text entry, CDP frames, and transport - Web text entry checks that the one-entry batch answer echoes the command it sent, and its failure message no longer carries the backend's error text, which could quote the typed text. - A CDP frame whose method is not a string is dropped instead of answering a pending request; a listener's thrown value is described without String(), and null console arguments are skipped. - A 2xx WebDriver answer that is not JSON discloses dispatched unknown; a non-2xx JSON null body stays null. - Tests: upload deadline actually fires, the iOS app-switcher refusal names its operation, and Device Farm runs exactly two lookups. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(platform-web): drop backend output from text-entry failures A failed text-entry batch call could still quote the typed text through the generic error paths: stdout and stderr from a non-JSON answer or a non-zero exit, and the envelope's error text. Text-entry failures now keep only an allowlist of details (cmd, args, exitCode, dispatched, reason, timeoutMs, hint), a generic message, and no cause chain. A caller cancellation passes through unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(tv-cdp): load the diagnostics emitter only on the error path The listener guard imported host-kit diagnostics eagerly, which grew the tv-cdp eager import closure from 6 to 8 modules and failed the eager closure budget. The emitter now loads with a function-scoped import when an unreadable frame or a failing listener is reported. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(platform-web): scrub only executed backend output from text-entry failures The previous scrub rebuilt every text-entry failure with a generic message, which replaced setup guidance for a missing backend and the message of a canceled request. Redaction now happens where the output enters the error: a failure read from the executed batch's answer gets a generic message and loses stdout, stderr, the envelope error, and its cause; a run failure keeps its code and message and loses only the captured output; a failure from before the command ran passes through unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(platform-linux): report app launch exits and inject the detached launcher The detached `open <binary>` launch reported only a spawn failure and called the detached runner directly, past the provider's injectable executors. A launch that exits non-zero or is killed by a signal now emits the linux_app_launch diagnostic from the typed exit fields, and the launcher is a `launchDetached` provider seam beside `runCommand` with the detached runner as its default, so the app still never runs as a captured child. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * test(platform-linux): assert each launch exit outcome reports its own diagnostic The launch-report test counted three events across four exits, which a path reporting twice could mask. Each exit now runs in its own diagnostics scope, and the test checks the written event: a start error, exit code 3, and SIGKILL each emit exactly one event carrying that field, and a clean exit emits none. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(provider-webdriver): never read a non-JSON error page as an unsupported route Since the non-JSON error body became truncated evidence, a gateway's HTML 404, 405, or 501 page matched the bare-status unsupported-route rule, so app activation, termination, and orientation fell back to a sibling mutation that could repeat an action that already ran. A non-JSON error answer is now built from its status alone with dispatched unknown and never carries the route-unsupported reason. A JSON answer keeps the existing W3C-code-or-bare-status rule. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(platform-linux): launch through an injected executor unless a launcher is given A caller that injected runCommand but no launchDetached got the host-local detached runner, which silently bypassed its executor. The detached runner is now the default only beside the default runCmd; otherwise launches go through the injected executor. Also: the upload deadline comment now says it is a total deadline, the activation test no longer splits the #1774 comment from its test, and the unread `error` field on AgentBrowserBatchEntry is gone. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(platform-web): point a refused text entry at a fresh snapshot, not setup A live stale-ref fill showed text-entry-failed carrying the "run web setup" hint, but the backend ran and refused the entry. The hint now tells the caller to take a new snapshot and retry with its ref. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(platform-linux): keep the detached app launch on the ambient provider The ambient Linux tool provider named `runCommand: runCmd` explicitly, so after the injected-executor rule it launched apps through the captured runCmd instead of the detached runner. It now names no executor and takes the host-local defaults. A real-process test pins the ambient provider: the launched app's stderr is /dev/null, where it was a socket before. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * refactor(platform-linux): require a launcher beside an injected executor LinuxToolProviderOverrides is now a union: a caller that injects runCommand must also inject launchDetached, so the host-local detached runner never stands in beside an injected executor. The presence-keyed default and launchThroughExecutor are gone; fixtures that inject runCommand pass a launcher, and a compile-time pin keeps the refusal. The ambient-provider detachment test stays. A refused web text entry now hints per command: fill retries with a fresh snapshot ref, and type (which takes no ref) focuses the field again and retries. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * test(platform-web): pin each text-entry operation to its own hint The assertion chose the expected hint from the error message, so a regression that relabelled typeText as fill would still pass. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 --------- Co-authored-by: Claude <[email protected]>
1 parent 00c1d33 commit ca7c6fc

29 files changed

Lines changed: 1234 additions & 90 deletions

‎packages/contracts/src/application-lifecycle-interaction.test.ts‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import type { OpenApplicationInput } from './application-lifecycle-runtime.ts';
55
import {
66
bindDirectApplicationLifecycle,
77
bindLocalApplicationLifecycleInteractor,
8+
bindLocalDirectApplicationLifecycle,
89
bindProviderApplicationLifecycleInteractor,
910
invokeApplicationOpen,
1011
} from './application-lifecycle-interaction.ts';
@@ -74,6 +75,7 @@ test('direct lifecycle owners preserve the daemon runtime launch URL follow-up',
7475
binding,
7576
owner: 'Linux',
7677
openTargetIdentity: 'app-name',
78+
closeBeforeRelaunch: true,
7779
});
7880

7981
await lifecycle.openApplication(
@@ -92,6 +94,68 @@ test('direct lifecycle owners preserve the daemon runtime launch URL follow-up',
9294
expect(calls[1]?.options).toHaveProperty('launchArgs', undefined);
9395
});
9496

97+
/** An interactor that records each open and close it receives, in order. */
98+
function lifecycleRecordingInteractor(calls: string[]): Interactor {
99+
return {
100+
open: async (app: string, options?: { terminateRunningApp?: boolean }) => {
101+
calls.push(`open ${app} terminate=${String(options?.terminateRunningApp)}`);
102+
},
103+
openDevice: async () => undefined,
104+
close: async (app: string) => {
105+
calls.push(`close ${app}`);
106+
},
107+
setSetting: async () => undefined,
108+
} as unknown as Interactor;
109+
}
110+
111+
// The local direct owners (Linux, web, HarmonyOS, Vega) do not replace a running app on
112+
// open, so a relaunch that reached only `open` left the app running as it was.
113+
test('a local direct owner closes the running app before a relaunch open', async () => {
114+
const calls: string[] = [];
115+
const lifecycle = bindLocalDirectApplicationLifecycle({
116+
owner: 'Linux',
117+
openTargetIdentity: 'app-name',
118+
host: { resolve: async () => lifecycleRecordingInteractor(calls) },
119+
device: LINUX_DEVICE,
120+
signal: new AbortController().signal,
121+
});
122+
123+
await lifecycle.openApplication(
124+
openInput({ target: 'gedit', positionals: ['gedit'], appBundleId: undefined, relaunch: true }),
125+
);
126+
await lifecycle.openApplication(
127+
openInput({ target: 'gedit', positionals: ['gedit'], appBundleId: undefined }),
128+
);
129+
130+
expect(calls).toEqual([
131+
'close gedit',
132+
'open gedit terminate=undefined',
133+
'open gedit terminate=undefined',
134+
]);
135+
});
136+
137+
test('an owner whose open restarts the app receives the relaunch as terminateRunningApp', async () => {
138+
const calls: string[] = [];
139+
const lifecycle = bindDirectApplicationLifecycle({
140+
binding: bindProviderApplicationLifecycleInteractor({
141+
device: IOS_SIMULATOR,
142+
signal: new AbortController().signal,
143+
resolveInteractor: () => lifecycleRecordingInteractor(calls),
144+
}),
145+
owner: 'provider',
146+
openTargetIdentity: 'bundle-id',
147+
closeBeforeRelaunch: false,
148+
});
149+
150+
await lifecycle.openApplication(openInput({ relaunch: true }));
151+
await lifecycle.openApplication(openInput());
152+
153+
expect(calls).toEqual([
154+
'open com.example.app terminate=true',
155+
'open com.example.app terminate=false',
156+
]);
157+
});
158+
95159
test.each([
96160
{
97161
name: 'more than two positionals',

‎packages/contracts/src/application-lifecycle-interaction.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -268,8 +268,12 @@ export type DirectApplicationLifecycleParams = Readonly<{
268268
/** Names the owner in the failure reported for an operation it does not implement. */
269269
owner: string;
270270
openTargetIdentity: DirectOpenTargetIdentity;
271-
/** Owners whose native open does not replace a running application close it first. */
272-
closeBeforeRelaunch?: boolean;
271+
/**
272+
* How `open --relaunch` restarts a running application. `true`: the binding closes it before the
273+
* open, for owners whose native open does not replace a running application. `false`: the
274+
* interactor's open receives `terminateRunningApp` and owns the restart.
275+
*/
276+
closeBeforeRelaunch: boolean;
273277
/** Port reverse is the one non-direct operation a provider owner may still implement. */
274278
configureProviderPortReverse?: ApplicationLifecycleRuntimeOperations['configureProviderPortReverse'];
275279
}>;
@@ -327,6 +331,7 @@ async function openDirectApplication(
327331
positionals: input.positionals,
328332
appBundleId: input.appBundleId,
329333
execution: input.execution,
334+
...(params.closeBeforeRelaunch ? {} : { terminateRunningApp: input.relaunch }),
330335
});
331336
const followUpUrl = followUpRuntimeLaunchUrl(input);
332337
if (followUpUrl) {
@@ -405,6 +410,8 @@ export function bindLocalDirectApplicationLifecycle(
405410
return bindDirectApplicationLifecycle({
406411
owner: params.owner,
407412
openTargetIdentity: params.openTargetIdentity,
413+
// No local direct owner (Linux, web, HarmonyOS, Vega) replaces a running app on open.
414+
closeBeforeRelaunch: true,
408415
binding: bindLocalApplicationLifecycleInteractor({
409416
device: params.device,
410417
signal: params.signal,

‎packages/platform-linux/src/__tests__/tool-provider.test.ts‎

Lines changed: 149 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,30 @@
1-
import { bindTestCommandHost } from '@agent-device/test-kit';
2-
import { afterAll, beforeEach, test } from 'vitest';
1+
import { bindTestCommandHost, mkdtempForTest } from '@agent-device/test-kit';
2+
import fs from 'node:fs';
3+
import path from 'node:path';
4+
import { afterAll, beforeEach, test, vi } from 'vitest';
5+
import {
6+
countDiagnosticEventsByPhase,
7+
withDiagnosticsScope,
8+
} from '@agent-device/host-kit/diagnostics';
39
import assert from 'node:assert/strict';
410
import { pressLinux } from '../input-actions.ts';
5-
import { createLocalLinuxToolProvider, withLinuxToolProvider } from '../tool-provider.ts';
11+
import {
12+
createLocalLinuxToolProvider,
13+
resolveLinuxToolProvider,
14+
withLinuxToolProvider,
15+
type LinuxToolCommandExecutor,
16+
type LinuxToolDetachedLauncher,
17+
type LinuxToolProviderOverrides,
18+
} from '../tool-provider.ts';
19+
import type { ExecDetachedExit } from '@agent-device/host-kit/command';
620

721
bindTestCommandHost();
822

23+
/** For a provider that injects an executor and launches no app in the scenario. */
24+
const launchesNoApp: LinuxToolDetachedLauncher = (cmd) => {
25+
throw new Error(`this scenario launches no app: ${cmd}`);
26+
};
27+
928
const originalPlatform = process.platform;
1029
const originalEnv = { ...process.env };
1130

@@ -18,6 +37,7 @@ beforeEach(() => {
1837
test('scoped Linux tool provider handles input discovery and command execution', async () => {
1938
const commands: Array<[string, string[]]> = [];
2039
const provider = createLocalLinuxToolProvider({
40+
launchDetached: launchesNoApp,
2141
host: { env: { ...process.env, XDG_SESSION_TYPE: 'x11' }, cwd: process.cwd() },
2242
whichCommand: async (cmd) => cmd === 'xdotool',
2343
runCommand: async (cmd, args) => {
@@ -41,6 +61,7 @@ test('scoped Linux tool provider handles input discovery and command execution',
4161
test('xdotool press skips the --sync move when the pointer already sits on the target', async () => {
4262
const commands: Array<[string, string[]]> = [];
4363
const provider = createLocalLinuxToolProvider({
64+
launchDetached: launchesNoApp,
4465
host: { env: { ...process.env, XDG_SESSION_TYPE: 'x11' }, cwd: process.cwd() },
4566
whichCommand: async (cmd) => cmd === 'xdotool',
4667
runCommand: async (cmd, args) => {
@@ -64,6 +85,7 @@ test('xdotool press skips the --sync move when the pointer already sits on the t
6485
test('scoped Linux input provider handles semantic input without host tool discovery', async () => {
6586
const inputCalls: Array<[string, string, string, string]> = [];
6687
const provider = createLocalLinuxToolProvider({
88+
launchDetached: launchesNoApp,
6789
host: { env: { ...process.env, XDG_SESSION_TYPE: 'x11' }, cwd: process.cwd() },
6890
whichCommand: async (cmd) => {
6991
throw new Error(`unexpected input discovery: ${cmd}`);
@@ -93,6 +115,7 @@ test('scoped Linux input provider handles semantic input without host tool disco
93115

94116
test('Linux tool provider scopes do not share cached input tool resolution', async () => {
95117
const providerA = createLocalLinuxToolProvider({
118+
launchDetached: launchesNoApp,
96119
host: {
97120
env: { ...process.env, XDG_SESSION_TYPE: 'x11', WAYLAND_DISPLAY: '' },
98121
cwd: process.cwd(),
@@ -101,6 +124,7 @@ test('Linux tool provider scopes do not share cached input tool resolution', asy
101124
runCommand: async () => ({ exitCode: 0, stdout: '', stderr: '' }),
102125
});
103126
const providerB = createLocalLinuxToolProvider({
127+
launchDetached: launchesNoApp,
104128
host: {
105129
env: { ...process.env, XDG_SESSION_TYPE: 'wayland', WAYLAND_DISPLAY: 'wayland-0' },
106130
cwd: process.cwd(),
@@ -143,6 +167,7 @@ test('Linux tool provider scopes do not share cached input tool resolution', asy
143167
test('local Linux desktop provider translates semantic lifecycle calls to host tools', async () => {
144168
const commands: Array<[string, string[], boolean | undefined]> = [];
145169
const provider = createLocalLinuxToolProvider({
170+
launchDetached: launchesNoApp,
146171
host: { env: { ...process.env, XDG_SESSION_TYPE: 'x11' }, cwd: process.cwd() },
147172
whichCommand: async (cmd) => cmd === 'wmctrl',
148173
runCommand: async (cmd, args, options) => {
@@ -162,9 +187,129 @@ test('local Linux desktop provider translates semantic lifecycle calls to host t
162187
]);
163188
});
164189

190+
// `open <binary>` used to run the app as a piped child of the daemon, which kept every
191+
// byte the app printed in daemon memory for the app's whole life. The default launcher detaches,
192+
// for a provider built over a host and for the ambient one a call outside any runtime resolves.
193+
test.skipIf(!fs.existsSync('/proc/self/fd')).each([
194+
[
195+
'a host-built',
196+
() =>
197+
createLocalLinuxToolProvider({
198+
host: { env: process.env, cwd: process.cwd() },
199+
whichCommand: async (cmd) => cmd === 'fake-desktop-app',
200+
}),
201+
],
202+
['the ambient', () => resolveLinuxToolProvider()],
203+
] as const)(
204+
'%s Linux desktop provider launches an app binary detached from daemon pipes',
205+
async (_name, makeProvider) => {
206+
const binDir = await mkdtempForTest('linux-open-binary-');
207+
const report = path.join(binDir, 'stdout-target');
208+
fs.writeFileSync(
209+
path.join(binDir, 'fake-desktop-app'),
210+
`#!/bin/sh\nreadlink /proc/self/fd/2 > '${report}.tmp' && mv '${report}.tmp' '${report}'\n`,
211+
{ mode: 0o755 },
212+
);
213+
const originalPath = process.env['PATH'];
214+
process.env['PATH'] = `${binDir}${path.delimiter}${originalPath ?? ''}`;
215+
try {
216+
await makeProvider().desktop.openTarget('fake-desktop-app');
217+
218+
await vi.waitFor(() => assert.ok(fs.existsSync(report)));
219+
assert.equal(fs.readFileSync(report, 'utf8').trim(), '/dev/null');
220+
} finally {
221+
process.env['PATH'] = originalPath;
222+
}
223+
},
224+
);
225+
226+
test('local Linux desktop provider launches an app binary through its detached launcher', async () => {
227+
const launches: Array<[string, string[]]> = [];
228+
const captured: string[] = [];
229+
const provider = createLocalLinuxToolProvider({
230+
host: { env: process.env, cwd: process.cwd() },
231+
whichCommand: async (cmd) => cmd === 'demo-app',
232+
runCommand: async (cmd) => {
233+
captured.push(cmd);
234+
return { exitCode: 0, stdout: '', stderr: '' };
235+
},
236+
launchDetached: (cmd, args) => {
237+
launches.push([cmd, args]);
238+
return { exited: new Promise(() => {}) };
239+
},
240+
});
241+
242+
await provider.desktop.openTarget('demo-app');
243+
244+
assert.deepEqual(launches, [['demo-app', []]]);
245+
assert.deepEqual(captured, []);
246+
});
247+
248+
/** The `linux_app_launch` events one `openTarget` writes, once its launch has exited. */
249+
async function launchDiagnostics(exit: ExecDetachedExit): Promise<Record<string, unknown>[]> {
250+
const logPath = path.join(await mkdtempForTest('linux-launch-diagnostics-'), 'request.ndjson');
251+
let exited: Promise<ExecDetachedExit> | undefined;
252+
const provider = createLocalLinuxToolProvider({
253+
host: { env: process.env, cwd: process.cwd() },
254+
whichCommand: async () => true,
255+
launchDetached: () => {
256+
exited = Promise.resolve(exit);
257+
return { exited };
258+
},
259+
});
260+
return await withDiagnosticsScope({ command: 'open', debug: true, logPath }, async () => {
261+
await provider.desktop.openTarget('demo-app');
262+
await exited;
263+
const expected = countDiagnosticEventsByPhase(['linux_app_launch']);
264+
const read = () =>
265+
(fs.existsSync(logPath) ? fs.readFileSync(logPath, 'utf8').trim().split('\n') : [])
266+
.filter((line) => line.length > 0)
267+
.map((line) => JSON.parse(line) as { phase: string; data?: Record<string, unknown> })
268+
.filter((event) => event.phase === 'linux_app_launch');
269+
await vi.waitFor(() => assert.equal(read().length, expected));
270+
return read().map((event) => event.data ?? {});
271+
});
272+
}
273+
274+
test.each([
275+
[
276+
'a start failure',
277+
{ pid: 1, error: 'spawn demo-app ENOENT' },
278+
{ error: 'spawn demo-app ENOENT' },
279+
],
280+
['a non-zero exit', { pid: 2, exitCode: 3 }, { exitCode: 3 }],
281+
['a signal', { pid: 3, signal: 'SIGKILL' }, { signal: 'SIGKILL' }],
282+
] as const)(
283+
'local Linux desktop provider reports %s of a launched app once',
284+
async (_name, exit, field) => {
285+
assert.deepEqual(await launchDiagnostics(exit), [{ app: 'demo-app', ...field }]);
286+
},
287+
);
288+
289+
test('local Linux desktop provider reports nothing for a launched app that exits cleanly', async () => {
290+
assert.deepEqual(await launchDiagnostics({ pid: 4, exitCode: 0 }), []);
291+
});
292+
293+
// An injected executor owns process execution, so the type refuses one without its own launcher:
294+
// the host-local detached runner must never stand in beside it. The directive fails typecheck if
295+
// the refusal goes away.
296+
test('a Linux provider that injects runCommand must also inject launchDetached', () => {
297+
const runCommand: LinuxToolCommandExecutor = async () => ({
298+
exitCode: 0,
299+
stdout: '',
300+
stderr: '',
301+
});
302+
// @ts-expect-error runCommand without launchDetached
303+
const withoutLauncher: LinuxToolProviderOverrides = { runCommand };
304+
const withLauncher: LinuxToolProviderOverrides = { runCommand, launchDetached: launchesNoApp };
305+
assert.equal(withoutLauncher.launchDetached, undefined);
306+
assert.equal(withLauncher.launchDetached, launchesNoApp);
307+
});
308+
165309
test('local Linux desktop provider falls back to pkill when wmctrl is unavailable', async () => {
166310
const commands: Array<[string, string[], boolean | undefined]> = [];
167311
const provider = createLocalLinuxToolProvider({
312+
launchDetached: launchesNoApp,
168313
host: { env: { ...process.env, XDG_SESSION_TYPE: 'x11' }, cwd: process.cwd() },
169314
whichCommand: async () => false,
170315
runCommand: async (cmd, args, options) => {
@@ -181,6 +326,7 @@ test('local Linux desktop provider falls back to pkill when wmctrl is unavailabl
181326
test('local Linux screenshot provider translates capture to available host tool', async () => {
182327
const commands: Array<[string, string[]]> = [];
183328
const provider = createLocalLinuxToolProvider({
329+
launchDetached: launchesNoApp,
184330
host: { env: { ...process.env, XDG_SESSION_TYPE: 'x11' }, cwd: process.cwd() },
185331
whichCommand: async (cmd) => cmd === 'scrot',
186332
runCommand: async (cmd, args) => {

0 commit comments

Comments
 (0)