Skip to content

Commit c2d656a

Browse files
authored
fix(desktop): pass the launch token as one argument (e2e-inc#2365)
* fix(desktop): pass the launch token as one argument An app whose environment macOS hides got -E2EDesktopLaunch <token> as two argv entries, and a Chromium browser opened the bare token as a URL. It now gets -E2EDesktopLaunch=<token>. The claim and the sweep read both forms, so an app an older version left running is still swept. * refactor(desktop): share one spelling of the token argument Drop the two-entry reader: only one nightly shipped that form. Correct the pending native-driver changeset in place. * refactor(desktop): look processes up by the launch token alone processesCarrying took NAME=token, built at four TypeScript call sites, and the driver stripped the name back off to match the argument form. It now takes the token; the driver spells both forms.
1 parent 187a39c commit c2d656a

10 files changed

Lines changed: 54 additions & 44 deletions

File tree

‎.changeset/desktop-native-driver.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,4 @@
44
'@e2e-dev/desktop-darwin-x64': minor
55
---
66

7-
**Breaking:** the desktop engine no longer runs agent-desktop. It drives macOS through its own Rust driver, loaded into the test process through NAPI-RS and shipped for each Mac in `@e2e-dev/desktop-darwin-arm64` and `@e2e-dev/desktop-darwin-x64`, which npm installs with the engine. Nothing is downloaded on the first run, and the `desktop({ binary })` option is gone: remove it from your config. Keys and typing now reach an app in the background, so `press` and the keyboard capability no longer need `headed: true`. Without `headed`, a `ControlOrMeta` shortcut reaches only the app's menu bar, so Copy, Paste, and Select All still need `headed: true`. An open context menu or pop-up menu is read as part of its window, and a row scrolled out of its list reads as hidden. `desktop.press(key)` presses a key into an app with no control that takes keyboard focus, and `getAttribute` reads a node's `label` and `identifier`. Apple's own apps, Mac App Store apps, and builds signed with `restrict`, whose environment macOS hides, can be launched by `appPath` as well as by `bundleId`; they get `-E2EDesktopLaunch <token>` as their last launch arguments, which is how the engine finds the copy it launched. On Windows and Linux, a run that includes a desktop target now stops with `UNSUPPORTED_CAPABILITY` instead of `INVALID_CONFIG`: the config is valid, and the engine does not support the OS.
7+
**Breaking:** the desktop engine no longer runs agent-desktop. It drives macOS through its own Rust driver, loaded into the test process through NAPI-RS and shipped for each Mac in `@e2e-dev/desktop-darwin-arm64` and `@e2e-dev/desktop-darwin-x64`, which npm installs with the engine. Nothing is downloaded on the first run, and the `desktop({ binary })` option is gone: remove it from your config. Keys and typing now reach an app in the background, so `press` and the keyboard capability no longer need `headed: true`. Without `headed`, a `ControlOrMeta` shortcut reaches only the app's menu bar, so Copy, Paste, and Select All still need `headed: true`. An open context menu or pop-up menu is read as part of its window, and a row scrolled out of its list reads as hidden. `desktop.press(key)` presses a key into an app with no control that takes keyboard focus, and `getAttribute` reads a node's `label` and `identifier`. Apple's own apps, Mac App Store apps, and builds signed with `restrict`, whose environment macOS hides, can be launched by `appPath` as well as by `bundleId`; they get `-E2EDesktopLaunch=<token>` as their last launch argument, which is how the engine finds the copy it launched. On Windows and Linux, a run that includes a desktop target now stops with `UNSUPPORTED_CAPABILITY` instead of `INVALID_CONFIG`: the config is valid, and the engine does not support the OS.

‎crates/e2e-desktop-napi/src/launch.rs‎

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,16 @@ use std::time::{Duration, Instant};
1717
/// The variable that carries a launch's token into the process it starts.
1818
pub const TOKEN_VARIABLE: &str = "E2E_DESKTOP_LAUNCH";
1919

20-
/// The argument that carries a launch's token into an app whose environment macOS hides, followed by the token.
21-
pub const TOKEN_ARGUMENT: &str = "-E2EDesktopLaunch";
20+
/// The environment entry of a launch's token.
21+
pub fn token_marker(token: &str) -> String {
22+
format!("{TOKEN_VARIABLE}={token}")
23+
}
24+
25+
/// The argument that carries a launch's token into an app whose environment macOS hides: `-E2EDesktopLaunch=<token>`,
26+
/// one entry, so no app reads the token as a file or a URL to open.
27+
pub fn token_argument(token: &str) -> String {
28+
format!("-E2EDesktopLaunch={token}")
29+
}
2230

2331
/// What `launch` was asked to start.
2432
pub struct LaunchRequest {
@@ -120,8 +128,8 @@ fn hides_environment(bundle: &str) -> bool {
120128
/// Apple's App Store apps (Numbers, Pages, Xcode: signed by Apple Mac OS
121129
/// Application Signing, with no platform identifier), and builds signed with
122130
/// the `restrict` flag. Every Mac App Store app carries that signature, so
123-
/// each gets the token as arguments too, which the claim reads only when the
124-
/// environment is hidden.
131+
/// each gets the token as an argument too, which the claim reads only when
132+
/// the environment is hidden.
125133
fn hidden_by(signature: &str) -> bool {
126134
signature.lines().any(|line| {
127135
line.starts_with("Platform identifier=")
@@ -134,8 +142,8 @@ fn hidden_by(signature: &str) -> bool {
134142
/// environment given (LaunchServices hands the app the environment of the
135143
/// process that asks), and finds the process it started: the new copy whose
136144
/// environment carries the launch token. An app whose environment macOS
137-
/// hides also gets the token as its last arguments (`-E2EDesktopLaunch
138-
/// <token>`, a user default AppKit ignores), which stay readable. A copy
145+
/// hides also gets the token as its last argument
146+
/// (`-E2EDesktopLaunch=<token>`, which AppKit ignores), which stays readable. A copy
139147
/// with neither is never taken: it may be one the user opened meanwhile.
140148
pub fn launch(request: LaunchRequest) -> Outcome<Launched> {
141149
let started = request.asked;
@@ -163,10 +171,10 @@ pub fn launch(request: LaunchRequest) -> Outcome<Launched> {
163171
if !request.activate {
164172
command.arg("-g");
165173
}
166-
command.arg("--env").arg(format!("{TOKEN_VARIABLE}={token}"));
174+
command.arg("--env").arg(token_marker(&token));
167175
command.arg(&bundle).arg("--args").args(&request.arguments);
168176
if hides_environment(&bundle) {
169-
command.arg(TOKEN_ARGUMENT).arg(&token);
177+
command.arg(token_argument(&token));
170178
}
171179
command.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::piped());
172180
// The lookup and `codesign` above can take a while: an app the caller gave up on is never started.
@@ -195,14 +203,14 @@ pub fn launch(request: LaunchRequest) -> Outcome<Launched> {
195203
}
196204
}
197205

198-
let marker = format!("{TOKEN_VARIABLE}={token}");
206+
let marker = token_marker(&token);
199207
let claim_until = (Instant::now() + request.claim).min(started + request.timeout);
200208
loop {
201209
let fresh: Vec<i32> = running_copies(&bundle_id).into_iter().filter(|pid| !before.contains(pid)).collect();
202210
for pid in &fresh {
203211
let ours = match crate::process::carries(*pid, &marker) {
204212
Some(carried) => carried,
205-
None => crate::process::argument_pair(*pid, TOKEN_ARGUMENT, &token),
213+
None => crate::process::holds_argument(*pid, &token_argument(&token)),
206214
};
207215
if ours {
208216
return Ok(launched(*pid, &bundle, &bundle_id));
@@ -224,7 +232,12 @@ fn launched(pid: i32, bundle: &str, bundle_id: &str) -> Launched {
224232

225233
#[cfg(test)]
226234
mod tests {
227-
use super::hidden_by;
235+
use super::{hidden_by, token_argument};
236+
237+
#[test]
238+
fn spells_the_launch_token_as_one_argument() {
239+
assert_eq!(token_argument("8ff2bdfb-142f"), "-E2EDesktopLaunch=8ff2bdfb-142f");
240+
}
228241

229242
#[test]
230243
fn tells_which_signatures_hide_the_environment() {

‎crates/e2e-desktop-napi/src/lib.rs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -82,11 +82,11 @@ pub fn process_started(pid: i32) -> Option<f64> {
8282
process::started(pid).map(|micros| micros as f64)
8383
}
8484

85-
/// Every process whose environment holds `marker` (`NAME=value`); `null` when the processes cannot be listed. It reads
85+
/// Every process that carries the launch `token`; `null` when the processes cannot be listed. It reads
8686
/// every process, which takes tens of milliseconds, so it runs on a blocking thread, off the JavaScript thread.
8787
#[napi]
88-
pub async fn processes_carrying(marker: String) -> Option<Vec<i32>> {
89-
spawn_blocking(move || process::carrying(&marker)).await.ok().flatten()
88+
pub async fn processes_carrying(token: String) -> Option<Vec<i32>> {
89+
spawn_blocking(move || process::carrying(&token)).await.ok().flatten()
9090
}
9191

9292
/// Drops the refs of a process that quit.

‎crates/e2e-desktop-napi/src/process.rs‎

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -83,18 +83,19 @@ fn environment(pid: i32) -> Option<Vec<String>> {
8383
procargs(pid)?.1
8484
}
8585

86-
/// Whether a process's arguments hold `name` followed by `value`.
87-
pub fn argument_pair(pid: i32, name: &str, value: &str) -> bool {
88-
procargs(pid).is_some_and(|(arguments, _)| arguments.windows(2).any(|pair| pair[0] == name && pair[1] == value))
86+
/// Whether one of a process's arguments is `argument`, whole.
87+
pub fn holds_argument(pid: i32, argument: &str) -> bool {
88+
procargs(pid).is_some_and(|(arguments, _)| arguments.iter().any(|entry| entry == argument))
8989
}
9090

9191
/// Whether a process's environment holds `marker` (`NAME=value`); `None` when it cannot be read.
9292
pub fn carries(pid: i32, marker: &str) -> Option<bool> {
9393
environment(pid).map(|entries| entries.iter().any(|entry| entry == marker))
9494
}
9595

96-
/// Every process of this user whose environment holds `marker`; `None` when the processes cannot be listed.
97-
pub fn carrying(marker: &str) -> Option<Vec<i32>> {
96+
/// Every process of this user that carries the launch `token`, in its environment or, where macOS hides that, in its
97+
/// arguments; `None` when the processes cannot be listed.
98+
pub fn carrying(token: &str) -> Option<Vec<i32>> {
9899
let count = unsafe { libc::proc_listallpids(std::ptr::null_mut(), 0) };
99100
if count <= 0 {
100101
return None;
@@ -106,11 +107,11 @@ pub fn carrying(marker: &str) -> Option<Vec<i32>> {
106107
}
107108
pids.truncate(filled as usize);
108109
let own = std::process::id() as i32;
109-
// A launch token also rides in the arguments of an app whose environment macOS hides.
110-
let token = marker.strip_prefix(crate::launch::TOKEN_VARIABLE).and_then(|rest| rest.strip_prefix('='));
111-
let holds = |pid: i32| match carries(pid, marker) {
110+
let marker = crate::launch::token_marker(token);
111+
let argument = crate::launch::token_argument(token);
112+
let holds = |pid: i32| match carries(pid, &marker) {
112113
Some(carried) => carried,
113-
None => token.is_some_and(|token| argument_pair(pid, crate::launch::TOKEN_ARGUMENT, token)),
114+
None => holds_argument(pid, &argument),
114115
};
115116
Some(pids.into_iter().filter(|pid| *pid > 0 && *pid != own && holds(*pid)).collect())
116117
}
@@ -142,8 +143,8 @@ mod tests {
142143

143144
#[test]
144145
fn reads_a_hidden_environment_as_none_and_keeps_the_arguments() {
145-
let (arguments, environment) = parse_procargs(&buffer("/System/App", &["/System/App", "-E2EDesktopLaunch", "tok"], &[])).unwrap();
146-
assert_eq!(arguments, ["-E2EDesktopLaunch", "tok"]);
146+
let (arguments, environment) = parse_procargs(&buffer("/System/App", &["/System/App", "-E2EDesktopLaunch=tok"], &[])).unwrap();
147+
assert_eq!(arguments, ["-E2EDesktopLaunch=tok"]);
147148
assert!(environment.is_none());
148149
}
149150

‎docs/desktop.mdx‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -75,9 +75,9 @@ The launched app gets only a minimal environment (`HOME`, `USER`, `LOGNAME`,
7575
`E2E_DESKTOP_LAUNCH` for process tracking), so your secrets, model keys, and
7676
CI tokens never leak into it. macOS hides that variable in its own apps,
7777
in Apple's App Store apps (Numbers, Pages, Xcode), and in builds signed
78-
with the `restrict` flag, so those also get `-E2EDesktopLaunch <token>` as
79-
their last launch arguments. The engine tells App Store apps by their
80-
signature, so every Mac App Store app gets those arguments.
78+
with the `restrict` flag, so those also get `-E2EDesktopLaunch=<token>` as
79+
their last launch argument. The engine tells App Store apps by their
80+
signature, so every Mac App Store app gets that argument.
8181

8282
```ts title="e2e.config.ts"
8383
import type { E2EConfig } from 'e2e';

‎packages/desktop/README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,8 @@ test('signs in', async ({ app, screen }) => {
6262
`LANG`, `LC_*`, and `__CF_USER_TEXT_ENCODING` of the run's environment, and
6363
`E2E_DESKTOP_LAUNCH`, the token the engine finds its copy by. An app whose
6464
environment macOS hides (its own apps, Mac App Store apps, and
65-
builds signed with `restrict`) gets the token as its last arguments too,
66-
`-E2EDesktopLaunch <token>`.
65+
builds signed with `restrict`) gets the token as its last argument too,
66+
`-E2EDesktopLaunch=<token>`.
6767
- An observation is one snapshot of the app's window. Roles map
6868
onto the ARIA names other engines use (`textbox`, `checkbox`, `combobox`,
6969
`button`); the developer id (`AXIdentifier`) is the node's test id, so

‎packages/desktop/src/driver.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,8 +99,8 @@ export interface DesktopDriver {
9999
screenLocked(): boolean | null;
100100
/** When a process started, in microseconds since the epoch; null when it is not running. */
101101
processStarted(pid: number): number | null;
102-
/** Every process whose environment holds `marker` (`NAME=value`); null when the processes cannot be listed. */
103-
processesCarrying(marker: string): Promise<readonly number[] | null>;
102+
/** Every process that carries the launch `token`, in its environment or its arguments; null when the processes cannot be listed. */
103+
processesCarrying(token: string): Promise<readonly number[] | null>;
104104
/** Drops the refs of a process that quit. */
105105
forgetProcess(pid: number): void;
106106
launch(options: {

‎packages/desktop/src/launch-ownership.ts‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,6 @@ const execFileAsync = promisify(execFile);
2020
/** How often a launch checks whether the app's window can be read yet. */
2121
export const LAUNCH_POLL_MS = 100;
2222

23-
/** The environment variable that carries a launch's token into the process it starts. */
24-
export const LAUNCH_TOKEN = 'E2E_DESKTOP_LAUNCH';
25-
2623
/** The prefix of every worker's private state directory, which a later run sweeps once its worker is gone. */
2724
export const STATE_PREFIX = 'e2e-desktop-worker-';
2825

@@ -120,7 +117,7 @@ export async function sweepStateDirectories(driver: DesktopDriver): Promise<void
120117
const owned: number[] = [];
121118
let known = true;
122119
if (typeof launched.token === 'string' && launched.token !== '') {
123-
const carriers = await driver.processesCarrying(`${LAUNCH_TOKEN}=${launched.token}`);
120+
const carriers = await driver.processesCarrying(launched.token);
124121
if (carriers === null) known = false;
125122
else owned.push(...carriers);
126123
}

‎packages/desktop/src/surface.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ import {
3939
} from '@e2e-dev/core/engine';
4040
import { call, DriverFailure, loadNativeDriver, translate, type DesktopDriver, type Envelope, type Launched, type RawWindow } from './driver.ts';
4141
import { toCombo } from './keys.ts';
42-
import { abandon, alive, APP_FILE, checkBundle, inheritedEnv, killed, LAUNCH_POLL_MS, LAUNCH_TOKEN, OWNER_FILE, sleep, STATE_PREFIX, sweepStateDirectories } from './launch-ownership.ts';
42+
import { abandon, alive, APP_FILE, checkBundle, inheritedEnv, killed, LAUNCH_POLL_MS, OWNER_FILE, sleep, STATE_PREFIX, sweepStateDirectories } from './launch-ownership.ts';
4343
import { launchArgumentList } from './launch-arguments.ts';
4444
import { ROOT_ID, projectSnapshot, type NodeBinding, type ProjectedScreen, type RawSnapshot, type Rect } from './nodes.ts';
4545
import type { DesktopPlatform, ResolvedDesktopOptions } from './options.ts';
@@ -596,7 +596,7 @@ export class DesktopSurface {
596596
return;
597597
}
598598
// A process carrying the launch's token is its own, whether or not the driver reported it.
599-
const carriers = await this.requireDriver().processesCarrying(`${LAUNCH_TOKEN}=${pending.token}`);
599+
const carriers = await this.requireDriver().processesCarrying(pending.token);
600600
if (carriers === null) {
601601
throw new EngineError('ENGINE_FAILURE', `could not tell whether a launch of ${pending.target} started the app: looking for its token among the processes failed; quitting tries again`, { retryable: false });
602602
}
@@ -643,7 +643,7 @@ export class DesktopSurface {
643643
let failed = false;
644644
while (Date.now() < until && !signal.aborted) {
645645
await new Promise((resolve) => setTimeout(resolve, LATE_APP_POLL_MS));
646-
const carriers = await this.requireDriver().processesCarrying(`${LAUNCH_TOKEN}=${token}`);
646+
const carriers = await this.requireDriver().processesCarrying(token);
647647
if (carriers === null) failed = true;
648648
else if (carriers.length > 0) return carriers;
649649
}
@@ -669,7 +669,7 @@ export class DesktopSurface {
669669
// Gone between the two looks; still there, its start unreadable, it is the app only if it carries the token.
670670
if (!alive(pid)) return false;
671671
}
672-
const carriers = this.token === undefined ? null : await driver.processesCarrying(`${LAUNCH_TOKEN}=${this.token}`);
672+
const carriers = this.token === undefined ? null : await driver.processesCarrying(this.token);
673673
if (carriers === null) throw new EngineError('ENGINE_FAILURE', `could not tell whether process ${pid} is still the app the engine launched; quitting tries again`, { retryable: false });
674674
return carriers.includes(pid);
675675
}

‎packages/desktop/tests/helpers/fake-driver.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -132,10 +132,9 @@ export class FakeDriver implements DesktopDriver {
132132
return this.startTimes.get(pid) ?? 1_000_000 + pid;
133133
}
134134

135-
processesCarrying(marker: string): Promise<readonly number[] | null> {
136-
this.calls.push({ method: 'processesCarrying', args: [marker] });
135+
processesCarrying(token: string): Promise<readonly number[] | null> {
136+
this.calls.push({ method: 'processesCarrying', args: [token] });
137137
if (this.lookupFails) return Promise.resolve(null);
138-
const token = marker.slice(marker.indexOf('=') + 1);
139138
return Promise.resolve([...this.carriers].filter(([pid, carried]) => carried === token && alive(pid)).map(([pid]) => pid));
140139
}
141140

0 commit comments

Comments
 (0)