@e2e-dev/desktop 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +79 -2
- package/dist/.build.json +1 -0
- package/dist/binary.d.ts +25 -0
- package/dist/binary.js +209 -0
- package/dist/cli.d.ts +82 -0
- package/dist/cli.js +170 -0
- package/dist/desktop.d.ts +25 -0
- package/dist/desktop.js +27 -0
- package/dist/engine-entry.d.ts +12 -0
- package/dist/engine-entry.js +8 -0
- package/dist/engine.d.ts +18 -0
- package/dist/engine.js +109 -0
- package/dist/fixtures.d.ts +6 -0
- package/dist/fixtures.js +2 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.js +18 -0
- package/dist/keys.d.ts +8 -0
- package/dist/keys.js +79 -0
- package/dist/nodes.d.ts +95 -0
- package/dist/nodes.js +290 -0
- package/dist/options.d.ts +67 -0
- package/dist/options.js +53 -0
- package/dist/png.d.ts +24 -0
- package/dist/png.js +144 -0
- package/dist/runner-test.d.ts +15 -0
- package/dist/runner-test.js +45 -0
- package/dist/surface.d.ts +270 -0
- package/dist/surface.js +1439 -0
- package/package.json +71 -3
package/dist/surface.js
ADDED
|
@@ -0,0 +1,1439 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One worker's desktop session: the macOS app the target declares, driven
|
|
3
|
+
* through agent-desktop's accessibility commands. The app is launched in the
|
|
4
|
+
* background, and every action goes through the accessibility API, so the
|
|
5
|
+
* user's pointer, focus, and typing stay where they are, unless the target
|
|
6
|
+
* opts into physical input with `headed`.
|
|
7
|
+
*/
|
|
8
|
+
import { execFile } from 'node:child_process';
|
|
9
|
+
import { randomUUID } from 'node:crypto';
|
|
10
|
+
import { existsSync } from 'node:fs';
|
|
11
|
+
import { mkdir, mkdtemp, readdir, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
12
|
+
import { tmpdir } from 'node:os';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import { promisify } from 'node:util';
|
|
15
|
+
import { EngineError, resolveExpression, } from '@e2e-dev/core/engine';
|
|
16
|
+
import { AGENT_DESKTOP_VERSION, installPinned, pinnedExecutable, pinnedInstalled, resolveExecutable } from './binary.js';
|
|
17
|
+
import { AgentDesktopCli, AgentDesktopFailure, translate } from './cli.js';
|
|
18
|
+
import { toCombo } from './keys.js';
|
|
19
|
+
import { ROOT_ID, projectSnapshot } from './nodes.js';
|
|
20
|
+
import { encodePng, windowImage } from './png.js';
|
|
21
|
+
const execFileAsync = promisify(execFile);
|
|
22
|
+
/** The least budget agent-desktop gets for its own wait, however little the operation has left. */
|
|
23
|
+
const MIN_TOOL_MS = 200;
|
|
24
|
+
/** How much of an operation's budget is kept back so agent-desktop answers before the process is killed. */
|
|
25
|
+
const ANSWER_MARGIN_MS = 400;
|
|
26
|
+
/** How often a launch checks whether the app's window can be read yet. */
|
|
27
|
+
const LAUNCH_POLL_MS = 100;
|
|
28
|
+
/** The environment variable that carries a launch's token into the process it starts. */
|
|
29
|
+
const LAUNCH_TOKEN = 'E2E_DESKTOP_LAUNCH';
|
|
30
|
+
/** The cause of a launch agent-desktop handed to a copy already running: it started nothing of the engine's. */
|
|
31
|
+
const HANDED_OVER = new Error('the launch handed over to a copy already running');
|
|
32
|
+
/** How long a quit looks for the process of a launch whose outcome was unknown. */
|
|
33
|
+
const PENDING_SETTLE_MS = 3_000;
|
|
34
|
+
/** How much of a quit's budget is kept for a killed process to exit. */
|
|
35
|
+
const EXIT_WAIT_MS = 500;
|
|
36
|
+
/** How long a launch waits for its process to appear, and then for the app's window to become readable, before it reports why it did not. */
|
|
37
|
+
const LAUNCH_READY_MS = 10_000;
|
|
38
|
+
/**
|
|
39
|
+
* How long agent-desktop may look for an option in a list. A select of an
|
|
40
|
+
* option that exists answers in well under a second; one of an option that
|
|
41
|
+
* does not exist opens the list's menu and waits out the whole deadline.
|
|
42
|
+
*/
|
|
43
|
+
const SELECT_WAIT_MS = 3_000;
|
|
44
|
+
/** How long a menu may take to close after Escape. */
|
|
45
|
+
const MENU_CLOSE_MS = 1_000;
|
|
46
|
+
/** The cause of an input that was never sent, because the operation's budget ran out first. */
|
|
47
|
+
const NOT_SENT = new Error('the operation ran out of budget before anything was sent');
|
|
48
|
+
/** The cause of an `open` that exited with an error, or never ran: LaunchServices started nothing. */
|
|
49
|
+
const NOT_STARTED = new Error('open started nothing');
|
|
50
|
+
/** The cause of a read that found the app's windows but could read none of them. */
|
|
51
|
+
const UNREADABLE = new Error('no window of the app could be read');
|
|
52
|
+
/** The cause of a read of an app that quit since it launched. */
|
|
53
|
+
const QUIT = new Error('the app quit');
|
|
54
|
+
/** The prefix of every worker's private agent-desktop state directory, which a later run sweeps once its worker is gone. */
|
|
55
|
+
const STATE_PREFIX = 'e2e-agent-desktop-';
|
|
56
|
+
/** The file in a state directory that names the process that owns it. */
|
|
57
|
+
const OWNER_FILE = 'owner';
|
|
58
|
+
/** The file in a state directory that names the app the worker launched and its launch token, so a sweep can quit an app a killed worker left running. */
|
|
59
|
+
const APP_FILE = 'app.json';
|
|
60
|
+
/** How old a state directory with no owner file must be before a sweep removes it. */
|
|
61
|
+
const ORPHAN_AGE_MS = 24 * 60 * 60 * 1000;
|
|
62
|
+
/**
|
|
63
|
+
* The variables of the run's environment the app under test and
|
|
64
|
+
* agent-desktop get, and nothing else: the run's secrets, model keys, and CI
|
|
65
|
+
* tokens never reach a process the runner does not control. `LC_*` passes
|
|
66
|
+
* too.
|
|
67
|
+
*/
|
|
68
|
+
const INHERITED_ENV = new Set(['HOME', 'USER', 'LOGNAME', 'SHELL', 'PATH', 'TMPDIR', 'LANG', '__CF_USER_TEXT_ENCODING']);
|
|
69
|
+
/** Launch arguments every launch gets first: no window or document the app saved at its last quit comes back. */
|
|
70
|
+
const FRESH_STATE_ARGUMENTS = ['-ApplePersistenceIgnoreState', 'YES'];
|
|
71
|
+
/** How many node bindings stay usable; the oldest go first. */
|
|
72
|
+
const MAX_BINDINGS = 4096;
|
|
73
|
+
/** Codes a snapshot fails with while the app has no window to read: not launched yet, or still opening. */
|
|
74
|
+
const NO_WINDOW_CODES = new Set(['APP_NOT_FOUND', 'WINDOW_NOT_FOUND']);
|
|
75
|
+
function sleep(ms, signal) {
|
|
76
|
+
if (ms <= 0 || signal.aborted)
|
|
77
|
+
return Promise.resolve();
|
|
78
|
+
return new Promise((resolve) => {
|
|
79
|
+
const timer = setTimeout(done, ms);
|
|
80
|
+
function done() {
|
|
81
|
+
clearTimeout(timer);
|
|
82
|
+
signal.removeEventListener('abort', done);
|
|
83
|
+
resolve();
|
|
84
|
+
}
|
|
85
|
+
signal.addEventListener('abort', done, { once: true });
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
function notActionable(text) {
|
|
89
|
+
return new EngineError('NOT_ACTIONABLE', text, { retryable: false });
|
|
90
|
+
}
|
|
91
|
+
function unsupported(text) {
|
|
92
|
+
return new EngineError('UNSUPPORTED_CAPABILITY', text, { retryable: false });
|
|
93
|
+
}
|
|
94
|
+
function invalidState(text) {
|
|
95
|
+
return new EngineError('INVALID_STATE', text, { retryable: false });
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* The operation with one deadline: `timeoutMs` reads what is left of the
|
|
99
|
+
* budget the call started with, so every command an action sends (a select
|
|
100
|
+
* that tries several ways, a type that clears first) shares one budget
|
|
101
|
+
* instead of each getting the whole of it.
|
|
102
|
+
*/
|
|
103
|
+
function withDeadline(operation) {
|
|
104
|
+
const deadline = Date.now() + operation.timeoutMs;
|
|
105
|
+
return {
|
|
106
|
+
...operation,
|
|
107
|
+
get timeoutMs() {
|
|
108
|
+
return Math.max(0, deadline - Date.now());
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/** Constrains a caller-supplied artifact label to a safe filename. */
|
|
113
|
+
function sanitizeFilename(name) {
|
|
114
|
+
return name.replaceAll(/[^A-Za-z0-9._-]/g, '_').slice(0, 64) || 'artifact';
|
|
115
|
+
}
|
|
116
|
+
/** Every query kind an expression uses, in it and in the expressions it is built from. */
|
|
117
|
+
function queryKinds(expression, kinds = new Set()) {
|
|
118
|
+
switch (expression.kind) {
|
|
119
|
+
case 'query':
|
|
120
|
+
kinds.add(expression.query.kind);
|
|
121
|
+
if (expression.scope !== undefined)
|
|
122
|
+
queryKinds(expression.scope, kinds);
|
|
123
|
+
break;
|
|
124
|
+
case 'filter':
|
|
125
|
+
queryKinds(expression.source, kinds);
|
|
126
|
+
if (expression.has !== undefined)
|
|
127
|
+
queryKinds(expression.has, kinds);
|
|
128
|
+
if (expression.hasNot !== undefined)
|
|
129
|
+
queryKinds(expression.hasNot, kinds);
|
|
130
|
+
break;
|
|
131
|
+
case 'index':
|
|
132
|
+
case 'frame':
|
|
133
|
+
queryKinds(expression.source, kinds);
|
|
134
|
+
break;
|
|
135
|
+
case 'union':
|
|
136
|
+
queryKinds(expression.left, kinds);
|
|
137
|
+
queryKinds(expression.right, kinds);
|
|
138
|
+
break;
|
|
139
|
+
default:
|
|
140
|
+
break;
|
|
141
|
+
}
|
|
142
|
+
return kinds;
|
|
143
|
+
}
|
|
144
|
+
/** The label a select names: a bare string, or `{ label }`; a `value` is a desktop option's label too, since a native list has no other value. */
|
|
145
|
+
function optionLabel(option) {
|
|
146
|
+
if (typeof option === 'string')
|
|
147
|
+
return option;
|
|
148
|
+
if (option.label !== undefined)
|
|
149
|
+
return option.label;
|
|
150
|
+
if (option.value !== undefined)
|
|
151
|
+
return option.value;
|
|
152
|
+
throw unsupported('a desktop list selects an option by its label; select by { index } is not supported');
|
|
153
|
+
}
|
|
154
|
+
export class DesktopSurface {
|
|
155
|
+
options;
|
|
156
|
+
platform;
|
|
157
|
+
cli;
|
|
158
|
+
home;
|
|
159
|
+
app = {};
|
|
160
|
+
projectRoot = process.cwd();
|
|
161
|
+
/** The app's bundle id or name: the target's `bundleId`, or the bundle id read from its `appPath`. */
|
|
162
|
+
launchTarget;
|
|
163
|
+
/** The `.app` bundle an `appPath` names, resolved; the launched process must run from it. */
|
|
164
|
+
bundle;
|
|
165
|
+
/** The process name agent-desktop reported at launch, which window lookups filter by before they keep the launched process's own. */
|
|
166
|
+
appName;
|
|
167
|
+
/** The process the engine launched, which it alone quits; another instance of the same app is never touched. */
|
|
168
|
+
pid;
|
|
169
|
+
/** agent-desktop's identity of that process, which a later process given the same id does not share. */
|
|
170
|
+
instance;
|
|
171
|
+
/**
|
|
172
|
+
* A launch whose outcome is unknown (it timed out, or failed after it may
|
|
173
|
+
* have started the app): its token, so the next quit can still find and
|
|
174
|
+
* end the process it started.
|
|
175
|
+
*/
|
|
176
|
+
pending;
|
|
177
|
+
attempt;
|
|
178
|
+
/** The launch or quit running now, which the next one waits for. */
|
|
179
|
+
lifecycle = Promise.resolve();
|
|
180
|
+
/** The window a test chose with `desktop.useWindow`, which every read and command then uses until the app quits. */
|
|
181
|
+
chosenWindow;
|
|
182
|
+
/** The window of the newest screen handed to the harness, by observe or locate: the one a point is measured in. */
|
|
183
|
+
pointWindow;
|
|
184
|
+
/** The newest binding of every node id an observation or a locate handed out, newest last. */
|
|
185
|
+
bindings = new Map();
|
|
186
|
+
/** The id handed out for each node identity since the app launched; see `projectSnapshot`. */
|
|
187
|
+
ids = new Map();
|
|
188
|
+
sequence = 0;
|
|
189
|
+
toolVersion = AGENT_DESKTOP_VERSION;
|
|
190
|
+
/** The run's environment cut to `INHERITED_ENV`: all the app and agent-desktop are given of it. */
|
|
191
|
+
appEnv = {};
|
|
192
|
+
constructor(options, platform) {
|
|
193
|
+
this.options = options;
|
|
194
|
+
this.platform = platform;
|
|
195
|
+
}
|
|
196
|
+
// --- lifecycle ---
|
|
197
|
+
/** Downloads the pinned agent-desktop once per machine, unless the target names its own. */
|
|
198
|
+
async prepare(info) {
|
|
199
|
+
if (this.options.binary === undefined)
|
|
200
|
+
await installPinned(info.env, info.signal, info.log);
|
|
201
|
+
// One worker per target: two would share one screen and one app.
|
|
202
|
+
return { workers: 1 };
|
|
203
|
+
}
|
|
204
|
+
async init(info) {
|
|
205
|
+
this.projectRoot = info.projectRoot;
|
|
206
|
+
this.app = info.app;
|
|
207
|
+
const executable = await resolveExecutable(this.options.binary, info.projectRoot, info.env);
|
|
208
|
+
this.appEnv = inheritedEnv(info.env);
|
|
209
|
+
// agent-desktop keeps the text of plain fields in its state directory: a worker that was killed left its own behind.
|
|
210
|
+
await sweepStateDirectories();
|
|
211
|
+
// A private state directory per worker, named for the process that owns it so a later sweep can tell it was left behind.
|
|
212
|
+
this.home = await mkdtemp(path.join(tmpdir(), STATE_PREFIX));
|
|
213
|
+
await writeFile(path.join(this.home, OWNER_FILE), String(process.pid));
|
|
214
|
+
// agent-desktop starts the app it launches with its own environment, so it gets the trimmed one too.
|
|
215
|
+
this.cli = new AgentDesktopCli(executable, { ...this.appEnv, AGENT_DESKTOP_HOME: this.home });
|
|
216
|
+
const status = await this.run(['status'], { label: 'agent-desktop status', input: false, signal: info.signal, timeoutMs: 15_000 });
|
|
217
|
+
if (typeof status.version === 'string')
|
|
218
|
+
this.toolVersion = status.version;
|
|
219
|
+
const accessibility = status.permissions?.accessibility?.state;
|
|
220
|
+
if (accessibility !== undefined && accessibility !== 'granted') {
|
|
221
|
+
throw new EngineError('ENGINE_FAILURE', 'agent-desktop has no Accessibility permission. In System Settings > Privacy & Security > Accessibility, allow the app that starts e2e (your terminal, IDE, or CI agent), then run again', { retryable: false });
|
|
222
|
+
}
|
|
223
|
+
this.launchTarget = await this.resolveLaunchTarget(info.signal);
|
|
224
|
+
info.log(`agent-desktop ${this.toolVersion} on macOS`);
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* The app's bundle id or name. An `appPath` on macOS is an `.app` bundle,
|
|
228
|
+
* which is what gets launched even when `bundleId` is set too: its
|
|
229
|
+
* `CFBundleIdentifier`, which `list-apps` reports for the process that
|
|
230
|
+
* bundle starts, and which must then equal `bundleId`.
|
|
231
|
+
*/
|
|
232
|
+
async resolveLaunchTarget(signal) {
|
|
233
|
+
if (this.app.appPath === undefined)
|
|
234
|
+
return this.app.bundleId;
|
|
235
|
+
const bundle = path.resolve(this.projectRoot, this.app.appPath);
|
|
236
|
+
const checked = await checkBundle(bundle, this.app.bundleId, signal);
|
|
237
|
+
if ('problem' in checked)
|
|
238
|
+
throw new EngineError('ENGINE_FAILURE', checked.problem, { retryable: false });
|
|
239
|
+
this.bundle = await realpath(bundle);
|
|
240
|
+
return checked.bundleId;
|
|
241
|
+
}
|
|
242
|
+
async startAttempt(context) {
|
|
243
|
+
if (this.attempt !== undefined)
|
|
244
|
+
throw invalidState('an attempt is already running on this desktop engine');
|
|
245
|
+
this.attempt = { artifactsDir: context.artifactsDir, screenshots: 0, ...(context.screen === undefined ? {} : { screen: context.screen }) };
|
|
246
|
+
this.forget();
|
|
247
|
+
context.environment({ platform: this.platform, 'agent-desktop': this.toolVersion });
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Quits the app the attempt launched, so the next test starts from a
|
|
251
|
+
* closed app as the first one did. A quit that fails is reported, and the
|
|
252
|
+
* engine keeps the process as its own, so `dispose` tries again.
|
|
253
|
+
*/
|
|
254
|
+
async endAttempt(context) {
|
|
255
|
+
this.attempt = undefined;
|
|
256
|
+
this.forget();
|
|
257
|
+
await this.quit(context.signal, context.timeoutMs);
|
|
258
|
+
}
|
|
259
|
+
async dispose(context) {
|
|
260
|
+
let quit = false;
|
|
261
|
+
try {
|
|
262
|
+
await this.quit(context.signal, context.timeoutMs);
|
|
263
|
+
quit = true;
|
|
264
|
+
}
|
|
265
|
+
finally {
|
|
266
|
+
// An app that would not quit, or a launch whose process was never found, stays named in the launch record, which the next run's sweep quits; the text agent-desktop kept of the app's fields goes either way.
|
|
267
|
+
const leftRunning = !quit && (this.pid !== undefined || this.pending !== undefined);
|
|
268
|
+
if (this.home !== undefined)
|
|
269
|
+
await (leftRunning ? keepOnlyRecord(this.home) : rm(this.home, { recursive: true, force: true })).catch(() => undefined);
|
|
270
|
+
this.home = undefined;
|
|
271
|
+
this.cli = undefined;
|
|
272
|
+
this.attempt = undefined;
|
|
273
|
+
this.forget();
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
async doctor(info) {
|
|
277
|
+
const checks = [];
|
|
278
|
+
const executable = this.options.binary === undefined ? pinnedExecutable(info.env) : path.resolve(info.projectRoot, this.options.binary);
|
|
279
|
+
if (executable === undefined)
|
|
280
|
+
return [{ id: 'agent-desktop', status: 'fail', message: `agent-desktop has no release for ${process.platform} on ${process.arch}` }];
|
|
281
|
+
if (this.options.binary === undefined ? !(await pinnedInstalled(info.env)) : !existsSync(executable)) {
|
|
282
|
+
checks.push(this.options.binary === undefined
|
|
283
|
+
? {
|
|
284
|
+
id: 'agent-desktop',
|
|
285
|
+
status: 'warn',
|
|
286
|
+
message: `agent-desktop ${AGENT_DESKTOP_VERSION} is downloaded on the first run, to ${executable}; the Accessibility and Screen Recording checks need it, so run e2e doctor again after the first run`,
|
|
287
|
+
}
|
|
288
|
+
: { id: 'agent-desktop', status: 'fail', message: `desktop({ binary }) names ${executable}, which does not exist` });
|
|
289
|
+
}
|
|
290
|
+
else {
|
|
291
|
+
const cli = new AgentDesktopCli(executable, inheritedEnv(info.env));
|
|
292
|
+
try {
|
|
293
|
+
const status = await cli.run({ args: ['status'], input: false, signal: info.signal, timeoutMs: 15_000, label: 'agent-desktop status' });
|
|
294
|
+
checks.push({ id: 'agent-desktop', status: 'pass', message: `agent-desktop ${status.version ?? 'unknown version'} at ${executable}` });
|
|
295
|
+
const accessibility = status.permissions?.accessibility?.state;
|
|
296
|
+
const screen = status.permissions?.screen_recording?.state;
|
|
297
|
+
checks.push(accessibility === 'granted'
|
|
298
|
+
? { id: 'accessibility', status: 'pass', message: 'Accessibility permission granted' }
|
|
299
|
+
: { id: 'accessibility', status: 'fail', message: 'Allow the app that starts e2e in System Settings > Privacy & Security > Accessibility' }, screen === 'granted'
|
|
300
|
+
? { id: 'screen-recording', status: 'pass', message: 'Screen Recording permission granted' }
|
|
301
|
+
: { id: 'screen-recording', status: 'warn', message: 'Screenshots need Screen Recording: allow the app that starts e2e in System Settings > Privacy & Security > Screen Recording' });
|
|
302
|
+
}
|
|
303
|
+
catch (cause) {
|
|
304
|
+
checks.push({ id: 'agent-desktop', status: 'fail', message: `agent-desktop at ${executable} did not answer: ${cause.message}` });
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
if (info.app.appPath !== undefined) {
|
|
308
|
+
const bundle = path.resolve(info.projectRoot, info.app.appPath);
|
|
309
|
+
// What init checks of the bundle, so a bundle doctor passes is one init accepts.
|
|
310
|
+
const checked = existsSync(bundle) ? await checkBundle(bundle, info.app.bundleId, info.signal) : { problem: `app.appPath ${bundle} does not exist; build the app or fix the path` };
|
|
311
|
+
checks.push('problem' in checked ? { id: 'app-path', status: 'fail', message: checked.problem } : { id: 'app-path', status: 'pass', message: bundle });
|
|
312
|
+
}
|
|
313
|
+
return checks;
|
|
314
|
+
}
|
|
315
|
+
// --- the app ---
|
|
316
|
+
/**
|
|
317
|
+
* `app.open()`: the copy of the app the engine launched is quit, and the
|
|
318
|
+
* app launched fresh, in the background unless `headed`, with the target's
|
|
319
|
+
* launch arguments. A copy the engine did not launch (the developer's own)
|
|
320
|
+
* is left alone, and never read or driven. A launch that failed after the
|
|
321
|
+
* app started still leaves the engine owning the new process, so the end
|
|
322
|
+
* of the attempt quits it.
|
|
323
|
+
*/
|
|
324
|
+
async restart(context) {
|
|
325
|
+
// The budget counts from the call, so time spent waiting for another launch or quit is part of it.
|
|
326
|
+
const operation = withDeadline(context);
|
|
327
|
+
await this.serially(() => this.launchFresh(operation));
|
|
328
|
+
}
|
|
329
|
+
/** `restart` once no other launch or quit of this surface is running. */
|
|
330
|
+
async launchFresh(operation) {
|
|
331
|
+
const target = this.launchTarget;
|
|
332
|
+
if (target === undefined)
|
|
333
|
+
throw unsupported("launching the app needs the target's app.bundleId or app.appPath");
|
|
334
|
+
await this.quitNow(operation.signal, operation.timeoutMs);
|
|
335
|
+
// Marks the process this launch starts, so it is told apart from every other copy by evidence, never by timing.
|
|
336
|
+
const launch = { target, token: randomUUID(), before: await this.runningCopies(target, operation) };
|
|
337
|
+
// Written before anything is sent, so the app stays findable by its token if this worker is killed mid-launch or never finds its process.
|
|
338
|
+
await this.writeRecord({ token: launch.token });
|
|
339
|
+
try {
|
|
340
|
+
if (this.bundle === undefined)
|
|
341
|
+
await this.launchById(launch, operation);
|
|
342
|
+
else
|
|
343
|
+
await this.openBundle(this.bundle, launch, operation);
|
|
344
|
+
}
|
|
345
|
+
catch (cause) {
|
|
346
|
+
// A launch agent-desktop refused, or one never sent, started nothing; nor did one handed to a copy already running.
|
|
347
|
+
const refused = cause instanceof EngineError && ((cause.cause instanceof AgentDesktopFailure && cause.cause.notDelivered) || cause.cause === HANDED_OVER || cause.cause === NOT_SENT || cause.cause === NOT_STARTED);
|
|
348
|
+
if (this.pid === undefined && !refused)
|
|
349
|
+
this.pending = launch;
|
|
350
|
+
throw cause;
|
|
351
|
+
}
|
|
352
|
+
// The process now shown to be the launch's, with when it started, so a later run can quit it even when its environment cannot be read, and never a later process given the same id.
|
|
353
|
+
const started = this.pid === undefined ? undefined : await startedAt(this.pid, operation.signal);
|
|
354
|
+
if (this.pid !== undefined && started !== undefined)
|
|
355
|
+
await this.writeRecord({ token: launch.token, pid: this.pid, started });
|
|
356
|
+
this.forget();
|
|
357
|
+
await this.windowReadable(operation);
|
|
358
|
+
}
|
|
359
|
+
/** Puts the launch record in the state directory, renamed into place so a worker killed mid-write never leaves half a record. */
|
|
360
|
+
async writeRecord(record) {
|
|
361
|
+
if (this.home === undefined)
|
|
362
|
+
return;
|
|
363
|
+
const file = path.join(this.home, APP_FILE);
|
|
364
|
+
await writeFile(`${file}.partial`, JSON.stringify(record));
|
|
365
|
+
await rename(`${file}.partial`, file);
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* The process ids of the app's copies running now. Undefined when
|
|
369
|
+
* agent-desktop listed the apps only in part: then no copy can be shown to
|
|
370
|
+
* be new, and a launch is told by its token alone.
|
|
371
|
+
*/
|
|
372
|
+
async runningCopies(target, operation) {
|
|
373
|
+
// agent-desktop matches the app the way its launch does (any case, the localized name too), so every copy the launch could hand over to is listed.
|
|
374
|
+
const { apps, complete } = await this.run(['list-apps', '--app', target], { label: 'list apps', input: false, signal: operation.signal, timeoutMs: operation.timeoutMs });
|
|
375
|
+
if (complete === false)
|
|
376
|
+
return undefined;
|
|
377
|
+
return new Set((apps ?? []).filter((app) => typeof app.pid === 'number').map((app) => app.pid));
|
|
378
|
+
}
|
|
379
|
+
/** Launches an installed app by bundle id or name through agent-desktop, which reports the process it started. */
|
|
380
|
+
async launchById(launch, operation) {
|
|
381
|
+
const { target, token } = launch;
|
|
382
|
+
// In the background unless physical input is on: the app never takes the keyboard from whoever is at the Mac.
|
|
383
|
+
const args = ['launch', target, '--no-attach', ...(this.options.headed ? ['--activate'] : []), '--timeout', String(this.toolBudget(operation)), `--env=${LAUNCH_TOKEN}=${token}`];
|
|
384
|
+
for (const argument of [...FRESH_STATE_ARGUMENTS, ...(this.app.launchArguments ?? [])])
|
|
385
|
+
args.push(`--arg=${argument}`);
|
|
386
|
+
let launched;
|
|
387
|
+
try {
|
|
388
|
+
launched = await this.run(args, { label: `launch ${target}`, input: true, signal: operation.signal, timeoutMs: operation.timeoutMs, raw: true });
|
|
389
|
+
}
|
|
390
|
+
catch (cause) {
|
|
391
|
+
if (cause instanceof AgentDesktopFailure && cause.code === 'APP_NOT_FOUND' && cause.notDelivered) {
|
|
392
|
+
throw new EngineError('ENGINE_FAILURE', `no installed app has the name or bundle id "${target}"; check the target's app.bundleId`, { retryable: false, cause });
|
|
393
|
+
}
|
|
394
|
+
throw translate(cause, `launch ${target}`, true);
|
|
395
|
+
}
|
|
396
|
+
if (typeof launched.pid !== 'number')
|
|
397
|
+
throw new EngineError('ENGINE_FAILURE', `agent-desktop launched ${target} but reported no process id, so the engine cannot tell its copy from another`, { retryable: false });
|
|
398
|
+
// A launch handed to a copy already running is not this launch's, and is never driven or quit: a process that ran before the launch, or one whose readable environment lacks the token.
|
|
399
|
+
// An unreadable environment (a macOS system app) leaves agent-desktop's report, of a fresh instance it started, standing.
|
|
400
|
+
const carries = await carriesToken(launched.pid, token, operation.signal);
|
|
401
|
+
if (launch.before?.has(launched.pid) === true || carries === false) {
|
|
402
|
+
throw new EngineError('ENGINE_FAILURE', `launching ${target} handed over to a copy already running (process ${launched.pid}), which the engine does not drive or quit; quit that copy and run again`, { retryable: false, cause: HANDED_OVER });
|
|
403
|
+
}
|
|
404
|
+
// With no token to read and no whole list of the copies that ran before, nothing shows the process is new: it may be a copy already running.
|
|
405
|
+
if (carries === undefined && launch.before === undefined) {
|
|
406
|
+
throw new EngineError('ENGINE_FAILURE', `launched ${target}, but process ${launched.pid} cannot be shown to be this launch's: its environment cannot be read, and agent-desktop listed the running apps only in part before the launch. The engine does not drive or quit it; run again`, { retryable: false, cause: HANDED_OVER });
|
|
407
|
+
}
|
|
408
|
+
this.appName = launched.app ?? target;
|
|
409
|
+
this.pid = launched.pid;
|
|
410
|
+
this.instance = typeof launched.process_instance === 'string' ? launched.process_instance : undefined;
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* Starts a new process of the `.app` bundle an `appPath` names, by its
|
|
414
|
+
* path: launching by bundle id would let LaunchServices pick another copy
|
|
415
|
+
* with the same id (an installed release, another checkout's build). The
|
|
416
|
+
* process is then found by its launch token among the app's running copies
|
|
417
|
+
* (see `claim`), since `open` reports no process id; one
|
|
418
|
+
* that cannot be found within `LAUNCH_READY_MS` fails the open, and stays
|
|
419
|
+
* pending, so the end of the attempt still looks for it.
|
|
420
|
+
*/
|
|
421
|
+
async openBundle(bundle, launch, operation) {
|
|
422
|
+
if (operation.timeoutMs <= 0)
|
|
423
|
+
throw new EngineError('OPERATION_TIMEOUT', `opening ${bundle}: the operation's budget ran out before it was sent`, { retryable: false, cause: NOT_SENT });
|
|
424
|
+
// `-g` keeps the app in the background unless physical input is on; `open` hands the app its own environment, so it runs with the trimmed one.
|
|
425
|
+
const args = [...(this.options.headed ? [] : ['-g']), '-n', '--env', `${LAUNCH_TOKEN}=${launch.token}`, bundle, '--args', ...FRESH_STATE_ARGUMENTS, ...(this.app.launchArguments ?? [])];
|
|
426
|
+
try {
|
|
427
|
+
await execFileAsync('open', args, { signal: operation.signal, timeout: operation.timeoutMs, env: this.appEnv });
|
|
428
|
+
}
|
|
429
|
+
catch (cause) {
|
|
430
|
+
const failure = cause;
|
|
431
|
+
// A cancelled open may have started the app all the same: the launch stays pending.
|
|
432
|
+
if (operation.signal.aborted)
|
|
433
|
+
throw new EngineError('CANCELLED', `opening ${bundle} was cancelled`, { retryable: false, cause });
|
|
434
|
+
// `open` answered that it could not open the bundle (a missing executable, a bad signature), or could not run: nothing started, so there is nothing to look for.
|
|
435
|
+
if ((typeof failure.code === 'number' && failure.killed !== true) || failure.code === 'ENOENT') {
|
|
436
|
+
const reason = typeof failure.stderr === 'string' && failure.stderr.trim() !== '' ? failure.stderr.trim() : failure.message;
|
|
437
|
+
throw new EngineError('ENGINE_FAILURE', `opening ${bundle} failed: ${reason}`, { retryable: false, cause: NOT_STARTED });
|
|
438
|
+
}
|
|
439
|
+
// Stopped by the budget or a cancellation: the app may be starting.
|
|
440
|
+
throw new EngineError('ACTION_MAY_HAVE_COMMITTED', `opening ${bundle} did not finish: ${failure.message}`, { retryable: false, cause });
|
|
441
|
+
}
|
|
442
|
+
const until = Date.now() + Math.min(operation.timeoutMs, LAUNCH_READY_MS);
|
|
443
|
+
try {
|
|
444
|
+
while ((await this.claim(launch, operation)) !== true) {
|
|
445
|
+
if (Date.now() + LAUNCH_POLL_MS >= until || operation.signal.aborted) {
|
|
446
|
+
throw new EngineError('ACTION_MAY_HAVE_COMMITTED', `${bundle} was opened, but no process of ${launch.target} carries this launch's token, so none can be shown to be its own. A build whose environment macOS hides cannot be told from another copy; launch it by app.bundleId instead`, { retryable: false });
|
|
447
|
+
}
|
|
448
|
+
await sleep(LAUNCH_POLL_MS, operation.signal);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
catch (cause) {
|
|
452
|
+
// `open` ran, so the app may be starting whatever went wrong after it: the launch stays pending, and the end of the attempt looks for it.
|
|
453
|
+
if (operation.signal.aborted)
|
|
454
|
+
throw new EngineError('CANCELLED', `looking for the process ${bundle} started was cancelled`, { retryable: false, cause });
|
|
455
|
+
if (cause instanceof EngineError && cause.code === 'ACTION_MAY_HAVE_COMMITTED')
|
|
456
|
+
throw cause;
|
|
457
|
+
throw new EngineError('ACTION_MAY_HAVE_COMMITTED', `${bundle} was opened, but looking for its process failed: ${cause.message}`, { retryable: false, cause });
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* Takes as the engine's own the running copy of the app this launch
|
|
462
|
+
* started: the one that carries its token in its environment. False when
|
|
463
|
+
* there is none (yet); undefined when agent-desktop listed the apps only
|
|
464
|
+
* in part and none carries the token, which shows nothing: the launch's
|
|
465
|
+
* copy may be among the ones left out. A copy without the token is never
|
|
466
|
+
* taken, not even the one new copy whose environment cannot be read: being
|
|
467
|
+
* new does not show this launch started it, and the developer's own copy
|
|
468
|
+
* may be the one that just started.
|
|
469
|
+
*/
|
|
470
|
+
async claim(launch, operation) {
|
|
471
|
+
const { target, token, before } = launch;
|
|
472
|
+
const { apps, complete } = await this.run(['list-apps', '--app', target], { label: 'list apps', input: false, signal: operation.signal, timeoutMs: operation.timeoutMs });
|
|
473
|
+
for (const app of apps ?? []) {
|
|
474
|
+
if (typeof app.pid !== 'number')
|
|
475
|
+
continue;
|
|
476
|
+
// A copy that ran before the launch is never its own, whatever its environment says.
|
|
477
|
+
if (before?.has(app.pid) === true)
|
|
478
|
+
continue;
|
|
479
|
+
if ((await carriesToken(app.pid, token, operation.signal)) === true)
|
|
480
|
+
return this.take(app, target);
|
|
481
|
+
}
|
|
482
|
+
return complete === false ? undefined : false;
|
|
483
|
+
}
|
|
484
|
+
take(app, target) {
|
|
485
|
+
this.appName = app.name ?? target;
|
|
486
|
+
this.pid = app.pid;
|
|
487
|
+
this.instance = app.process_instance;
|
|
488
|
+
return true;
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* Waits until the launched app's window can be read: a window exists soon
|
|
492
|
+
* after the launch, but its accessibility element can arrive a moment
|
|
493
|
+
* later, and an observation then would show the agent an empty screen. A
|
|
494
|
+
* window that stays unreadable for `LAUNCH_READY_MS` fails the open: every
|
|
495
|
+
* later step would only time out on an empty screen. Any other failure of a
|
|
496
|
+
* read is reported as it is. An app in the background is never brought
|
|
497
|
+
* forward: one that opens no window there (a document-based app opens its
|
|
498
|
+
* first one only when it comes forward) fails the open, and needs `headed`.
|
|
499
|
+
*/
|
|
500
|
+
async windowReadable(operation) {
|
|
501
|
+
const budgetBound = operation.timeoutMs < LAUNCH_READY_MS;
|
|
502
|
+
const deadline = Date.now() + Math.min(operation.timeoutMs, LAUNCH_READY_MS);
|
|
503
|
+
let sawWindow = false;
|
|
504
|
+
while (Date.now() < deadline) {
|
|
505
|
+
if (operation.signal.aborted)
|
|
506
|
+
throw new EngineError('CANCELLED', `opening ${this.appName ?? 'the app'} was cancelled`, { retryable: false });
|
|
507
|
+
let screen;
|
|
508
|
+
try {
|
|
509
|
+
// Each read gets what is left of the readiness wait, not of the whole operation, shared by its commands.
|
|
510
|
+
screen = await this.capture(withDeadline({ ...operation, timeoutMs: Math.max(deadline - Date.now(), 0) }));
|
|
511
|
+
}
|
|
512
|
+
catch (cause) {
|
|
513
|
+
// The last read ran out of budget: the window never became readable in time.
|
|
514
|
+
if (cause instanceof EngineError && cause.code === 'OPERATION_TIMEOUT')
|
|
515
|
+
break;
|
|
516
|
+
// A window not readable yet, or an app that quit, is what this wait looks at below.
|
|
517
|
+
if (!(cause instanceof EngineError && (cause.cause === UNREADABLE || cause.cause === QUIT)))
|
|
518
|
+
throw cause;
|
|
519
|
+
if (cause.cause === UNREADABLE)
|
|
520
|
+
sawWindow = true;
|
|
521
|
+
}
|
|
522
|
+
if (screen !== undefined)
|
|
523
|
+
return;
|
|
524
|
+
// An app that quit (or crashed) on its own never shows a window.
|
|
525
|
+
if (this.pid !== undefined && !alive(this.pid)) {
|
|
526
|
+
this.forget();
|
|
527
|
+
this.pid = undefined;
|
|
528
|
+
this.instance = undefined;
|
|
529
|
+
throw new EngineError('ENGINE_FAILURE', `${this.appName ?? 'the app'} quit right after it launched, before it showed a window`, { retryable: false });
|
|
530
|
+
}
|
|
531
|
+
await sleep(Math.min(LAUNCH_POLL_MS, Math.max(deadline - Date.now(), 0)), operation.signal);
|
|
532
|
+
}
|
|
533
|
+
// The open's own budget ran out first: that is a timeout, not a window that cannot be read.
|
|
534
|
+
if (budgetBound)
|
|
535
|
+
throw new EngineError('OPERATION_TIMEOUT', `${this.appName ?? 'the app'} launched, but the open ran out of time before its window could be read`, { retryable: false });
|
|
536
|
+
if (!sawWindow && !this.options.headed) {
|
|
537
|
+
throw new EngineError('ENGINE_FAILURE', `${this.appName ?? 'the app'} launched in the background and opened no window. Some apps, such as document-based ones, show a window only once they come forward; set desktop({ headed: true }) for them`, { retryable: false });
|
|
538
|
+
}
|
|
539
|
+
throw new EngineError('ENGINE_FAILURE', `${this.appName ?? 'the app'} launched, but its window cannot be read through accessibility. On macOS the screen may be locked, or the window may be off screen`, { retryable: false });
|
|
540
|
+
}
|
|
541
|
+
/** The windows of the app the engine launched, for the `desktop` fixture; none while it is not running. */
|
|
542
|
+
async windows(signal, timeoutMs) {
|
|
543
|
+
const windows = await this.ownWindows({ signal, timeoutMs });
|
|
544
|
+
return windows.map((window) => ({ id: window.id, title: window.title ?? '', focused: window.is_focused === true }));
|
|
545
|
+
}
|
|
546
|
+
/**
|
|
547
|
+
* `desktop.useWindow()`: reads and acts in the window `id` names from now
|
|
548
|
+
* on, until the app quits, rather than the focused one. With no id, goes
|
|
549
|
+
* back to the focused window.
|
|
550
|
+
*/
|
|
551
|
+
async useWindow(id, signal, timeoutMs) {
|
|
552
|
+
if (id !== undefined) {
|
|
553
|
+
const windows = await this.ownWindows({ signal, timeoutMs });
|
|
554
|
+
if (!windows.some((window) => window.id === id))
|
|
555
|
+
throw notActionable(`the app has no window ${id}; desktop.windows() lists the ones it has`);
|
|
556
|
+
}
|
|
557
|
+
this.chosenWindow = id;
|
|
558
|
+
// A point taken in the window read before is not in this one's coordinates: the next point action measures from the window now in use.
|
|
559
|
+
this.pointWindow = undefined;
|
|
560
|
+
}
|
|
561
|
+
chosenClosed() {
|
|
562
|
+
return invalidState(`the window desktop.useWindow() chose (${this.chosenWindow ?? ''}) is closed; choose another, or call desktop.useWindow() to go back to the focused one`);
|
|
563
|
+
}
|
|
564
|
+
/** `desktop.closeApp()`: the app quit, as at the end of every test. */
|
|
565
|
+
async closeApp(signal, timeoutMs) {
|
|
566
|
+
await this.quit(signal, timeoutMs);
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* Quits the app the engine launched, forcefully: a test needs it gone, not
|
|
570
|
+
* asked to save. It is ended by its process id, so another instance of the
|
|
571
|
+
* same app (the developer's own copy) is left alone, and waited for, so the
|
|
572
|
+
* next launch cannot find it still running. The process is looked up
|
|
573
|
+
* first: one that exited on its own, or whose id the OS gave to another
|
|
574
|
+
* process since, is not running any more, and nothing is killed. Until the
|
|
575
|
+
* process is known to be gone, the engine keeps it as its own, so a quit
|
|
576
|
+
* that failed is tried again.
|
|
577
|
+
*/
|
|
578
|
+
/**
|
|
579
|
+
* Runs launches and quits of this surface one at a time: two at once would
|
|
580
|
+
* each launch a copy into the one process id and launch record the engine
|
|
581
|
+
* keeps, and the end of the attempt would quit only one of them.
|
|
582
|
+
*/
|
|
583
|
+
serially(run) {
|
|
584
|
+
const next = this.lifecycle.then(run, run);
|
|
585
|
+
this.lifecycle = next.catch(() => undefined);
|
|
586
|
+
return next;
|
|
587
|
+
}
|
|
588
|
+
/** `quitNow` once no other launch or quit of this surface is running. */
|
|
589
|
+
quit(signal, timeoutMs) {
|
|
590
|
+
return this.serially(() => this.quitNow(signal, timeoutMs));
|
|
591
|
+
}
|
|
592
|
+
async quitNow(signal, timeoutMs) {
|
|
593
|
+
const deadline = Date.now() + timeoutMs;
|
|
594
|
+
const pending = this.pending;
|
|
595
|
+
if (this.pid === undefined && pending !== undefined) {
|
|
596
|
+
// A launch whose outcome was unknown: look for the process it started, which may still be registering, under this quit's own budget.
|
|
597
|
+
// Short of the quit's budget by `EXIT_WAIT_MS`, so a process found at the end can still be seen to exit.
|
|
598
|
+
const until = Date.now() + Math.min(Math.max(timeoutMs - EXIT_WAIT_MS, 0), PENDING_SETTLE_MS);
|
|
599
|
+
// The pending launch stays until it is claimed or the wait's last answer found none: an answer that listed the apps in part proves nothing, and a lookup that ran out of time is no answer.
|
|
600
|
+
let lastShowedNone = false;
|
|
601
|
+
while (Date.now() < until && !signal.aborted) {
|
|
602
|
+
const found = await this.claim(pending, { signal, timeoutMs: Math.max(until - Date.now(), 0) }).catch((cause) => {
|
|
603
|
+
if (cause instanceof EngineError && cause.code === 'OPERATION_TIMEOUT')
|
|
604
|
+
return 'timeout';
|
|
605
|
+
throw cause;
|
|
606
|
+
});
|
|
607
|
+
if (found === true)
|
|
608
|
+
break;
|
|
609
|
+
if (found !== 'timeout')
|
|
610
|
+
lastShowedNone = found === false;
|
|
611
|
+
await sleep(Math.min(LAUNCH_POLL_MS, Math.max(until - Date.now(), 0)), signal);
|
|
612
|
+
}
|
|
613
|
+
if (signal.aborted)
|
|
614
|
+
throw new EngineError('CANCELLED', `looking for the process a launch of ${pending.target} started was cancelled`, { retryable: false });
|
|
615
|
+
if (this.pid === undefined) {
|
|
616
|
+
// A process carrying the launch's token is its own, whether or not the app list shows it yet.
|
|
617
|
+
const carriers = await processesCarrying(pending.token, signal);
|
|
618
|
+
if (carriers === undefined) {
|
|
619
|
+
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 });
|
|
620
|
+
}
|
|
621
|
+
if (!(await killed(carriers, deadline, signal))) {
|
|
622
|
+
throw new EngineError('ENGINE_FAILURE', `the process a launch of ${pending.target} started did not exit; quitting tries again`, { retryable: false });
|
|
623
|
+
}
|
|
624
|
+
if (carriers.length === 0 && !lastShowedNone) {
|
|
625
|
+
throw new EngineError('ENGINE_FAILURE', `could not tell whether a launch of ${pending.target} started the app: listing the apps ran out of time or listed them only in part; quitting tries again`, { retryable: false });
|
|
626
|
+
}
|
|
627
|
+
this.pending = undefined;
|
|
628
|
+
if (this.home !== undefined)
|
|
629
|
+
await rm(path.join(this.home, APP_FILE), { force: true }).catch(() => undefined);
|
|
630
|
+
if (carriers.length > 0)
|
|
631
|
+
return;
|
|
632
|
+
throw new EngineError('ENGINE_FAILURE', `a launch of ${pending.target} failed, and no process it started was found; if the app is running, quit it by hand`, { retryable: false });
|
|
633
|
+
}
|
|
634
|
+
this.pending = undefined;
|
|
635
|
+
}
|
|
636
|
+
const { pid, instance, appName } = this;
|
|
637
|
+
this.forget();
|
|
638
|
+
if (pid === undefined || appName === undefined)
|
|
639
|
+
return;
|
|
640
|
+
const { apps, complete } = await this.run(['list-apps', '--app', appName], { label: `find ${appName}`, input: false, signal, timeoutMs });
|
|
641
|
+
const running = apps?.some((app) => app.pid === pid && (instance === undefined || app.process_instance === instance)) === true;
|
|
642
|
+
// An inventory that skipped some processes cannot say the app is gone; it stays the engine's, to quit again.
|
|
643
|
+
if (!running && complete === false)
|
|
644
|
+
throw new EngineError('ENGINE_FAILURE', `could not tell whether the app (process ${pid}) is still running: agent-desktop listed the apps only in part`, { retryable: false });
|
|
645
|
+
if (running && !(await killed([pid], deadline, signal)))
|
|
646
|
+
throw new EngineError('ENGINE_FAILURE', `the app (process ${pid}) did not exit`, { retryable: false });
|
|
647
|
+
this.pid = undefined;
|
|
648
|
+
this.instance = undefined;
|
|
649
|
+
if (this.home !== undefined)
|
|
650
|
+
await rm(path.join(this.home, APP_FILE), { force: true }).catch(() => undefined);
|
|
651
|
+
}
|
|
652
|
+
/** Every binding of the screen before: after a launch or a quit, none names a control that still exists. */
|
|
653
|
+
forget() {
|
|
654
|
+
this.pointWindow = undefined;
|
|
655
|
+
this.chosenWindow = undefined;
|
|
656
|
+
this.bindings.clear();
|
|
657
|
+
this.ids.clear();
|
|
658
|
+
}
|
|
659
|
+
/** The node id for an identity: the one it had before, else a new one, never handed out before since the app launched. */
|
|
660
|
+
idFor(identity) {
|
|
661
|
+
let id = identity === undefined ? undefined : this.ids.get(identity);
|
|
662
|
+
if (id === undefined) {
|
|
663
|
+
id = `n${(this.sequence += 1)}`;
|
|
664
|
+
if (identity !== undefined)
|
|
665
|
+
this.ids.set(identity, id);
|
|
666
|
+
}
|
|
667
|
+
return id;
|
|
668
|
+
}
|
|
669
|
+
/**
|
|
670
|
+
* Projects a snapshot of one window, its node identities scoped to that
|
|
671
|
+
* window. An identity of that window the snapshot no longer has is retired:
|
|
672
|
+
* a control that went, or now has a look-alike sibling, never passes its id
|
|
673
|
+
* on to another. Another window's identities stay, so its controls keep
|
|
674
|
+
* their ids when it is read again.
|
|
675
|
+
*/
|
|
676
|
+
projectWindow(raw) {
|
|
677
|
+
const window = raw.window?.id ?? '';
|
|
678
|
+
const used = new Set();
|
|
679
|
+
const screen = projectSnapshot(raw, (identity) => {
|
|
680
|
+
if (identity === undefined)
|
|
681
|
+
return this.idFor(undefined);
|
|
682
|
+
const scoped = `${window}|${identity}`;
|
|
683
|
+
used.add(scoped);
|
|
684
|
+
return this.idFor(scoped);
|
|
685
|
+
});
|
|
686
|
+
for (const identity of this.ids.keys())
|
|
687
|
+
if (identity.startsWith(`${window}|`) && !used.has(identity))
|
|
688
|
+
this.ids.delete(identity);
|
|
689
|
+
return screen;
|
|
690
|
+
}
|
|
691
|
+
// --- reading the screen ---
|
|
692
|
+
/**
|
|
693
|
+
* One snapshot of a window of the app the engine launched, projected: the
|
|
694
|
+
* window `windowId` names, else the one the test chose (and no other while
|
|
695
|
+
* it is chosen), else the focused one, the visible ones, and the rest, in
|
|
696
|
+
* that order, the first one accessibility can read. `forMask` is a
|
|
697
|
+
* read that only places secure fields: it reads every node even with
|
|
698
|
+
* `snapshot: 'interactive'`, which leaves out a secure node with no action
|
|
699
|
+
* of its own, and hands out no ids, so the ids of the screen the harness
|
|
700
|
+
* holds stay as they are. Undefined, an empty screen, before `app.open()`
|
|
701
|
+
* and while the running app has no window; a copy of the app the engine
|
|
702
|
+
* did not launch is never read. A read that fails is no empty screen,
|
|
703
|
+
* which would let a negative assertion pass: an app that quit is
|
|
704
|
+
* `INVALID_STATE`, as is a chosen window that closed, and windows none of
|
|
705
|
+
* which could be read are a retryable `NODE_STALE`, so a locator reads
|
|
706
|
+
* again until its deadline.
|
|
707
|
+
*/
|
|
708
|
+
async capture(operation, windowId = this.chosenWindow, forMask = false) {
|
|
709
|
+
const windows = await this.ownWindows(operation);
|
|
710
|
+
const chosen = windowId !== undefined && windowId === this.chosenWindow;
|
|
711
|
+
if (chosen && !windows.some((window) => window.id === windowId))
|
|
712
|
+
throw this.chosenClosed();
|
|
713
|
+
if (windows.length === 0 && this.pid !== undefined)
|
|
714
|
+
await this.requireRunning(operation);
|
|
715
|
+
const candidates = windowId === undefined
|
|
716
|
+
? [...windows.filter((window) => window.is_focused === true), ...windows.filter((window) => window.is_focused !== true && window.visible !== false), ...windows.filter((window) => window.is_focused !== true && window.visible === false)]
|
|
717
|
+
: windows.filter((window) => window.id === windowId);
|
|
718
|
+
for (const window of candidates) {
|
|
719
|
+
const args = ['snapshot', '--window-id', window.id, '--include-bounds', '--max-depth', String(this.options.maxDepth), '--timeout-ms', String(this.toolBudget(operation))];
|
|
720
|
+
if (this.options.interactiveOnly && !forMask)
|
|
721
|
+
args.push('-i');
|
|
722
|
+
try {
|
|
723
|
+
const raw = await this.run(args, { label: 'snapshot', input: false, signal: operation.signal, timeoutMs: operation.timeoutMs, raw: true });
|
|
724
|
+
if (!forMask)
|
|
725
|
+
return this.projectWindow(raw);
|
|
726
|
+
let scratch = 0;
|
|
727
|
+
return projectSnapshot(raw, () => `mask${(scratch += 1)}`);
|
|
728
|
+
}
|
|
729
|
+
catch (cause) {
|
|
730
|
+
// A panel accessibility cannot read, or a window that just closed: try the next one.
|
|
731
|
+
if (cause instanceof AgentDesktopFailure && NO_WINDOW_CODES.has(cause.code)) {
|
|
732
|
+
if (chosen)
|
|
733
|
+
throw this.chosenClosed();
|
|
734
|
+
continue;
|
|
735
|
+
}
|
|
736
|
+
if (cause instanceof AgentDesktopFailure && cause.details.kind === 'window_without_accessibility_element')
|
|
737
|
+
continue;
|
|
738
|
+
throw translate(cause, 'snapshot', false);
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
if (candidates.length === 0)
|
|
742
|
+
return undefined;
|
|
743
|
+
throw new EngineError('NODE_STALE', `no window of ${this.appName ?? 'the app'} could be read through accessibility (on macOS the screen may be locked), or each closed while it was read`, { retryable: true, cause: UNREADABLE });
|
|
744
|
+
}
|
|
745
|
+
/**
|
|
746
|
+
* Throws unless the process the engine launched still runs: its id alone
|
|
747
|
+
* does not show that, since another process can take the id over once the
|
|
748
|
+
* app quits, so the app list must show the same process instance. A list
|
|
749
|
+
* that left copies out shows nothing, and the read is tried again.
|
|
750
|
+
*/
|
|
751
|
+
async requireRunning(operation) {
|
|
752
|
+
const { pid, instance, appName } = this;
|
|
753
|
+
if (pid === undefined)
|
|
754
|
+
return;
|
|
755
|
+
const quit = () => new EngineError('INVALID_STATE', `${appName ?? 'the app'} quit (process ${pid}); open it again with app.open()`, { retryable: false, cause: QUIT });
|
|
756
|
+
if (!alive(pid))
|
|
757
|
+
throw quit();
|
|
758
|
+
if (instance === undefined || appName === undefined)
|
|
759
|
+
return;
|
|
760
|
+
const { apps, complete } = await this.run(['list-apps', '--app', appName], { label: `find ${appName}`, input: false, signal: operation.signal, timeoutMs: operation.timeoutMs });
|
|
761
|
+
if (apps?.some((app) => app.pid === pid && app.process_instance === instance) === true)
|
|
762
|
+
return;
|
|
763
|
+
if (complete === false)
|
|
764
|
+
throw new EngineError('NODE_STALE', `could not tell whether ${appName} still runs: agent-desktop listed the apps only in part`, { retryable: true, cause: UNREADABLE });
|
|
765
|
+
throw quit();
|
|
766
|
+
}
|
|
767
|
+
/** The windows of the process the engine launched; none before `app.open()` or after the app quit. */
|
|
768
|
+
async ownWindows(operation) {
|
|
769
|
+
const { pid, appName } = this;
|
|
770
|
+
if (pid === undefined || appName === undefined)
|
|
771
|
+
return [];
|
|
772
|
+
let listed;
|
|
773
|
+
try {
|
|
774
|
+
listed = await this.run(['list-windows', '--app', appName], { label: 'list windows', input: false, signal: operation.signal, timeoutMs: operation.timeoutMs, raw: true });
|
|
775
|
+
}
|
|
776
|
+
catch (cause) {
|
|
777
|
+
if (cause instanceof AgentDesktopFailure && NO_WINDOW_CODES.has(cause.code))
|
|
778
|
+
return [];
|
|
779
|
+
throw translate(cause, 'list windows', false);
|
|
780
|
+
}
|
|
781
|
+
const { instance } = this;
|
|
782
|
+
return listed.filter((window) => window.pid === pid && (instance === undefined || window.process_instance === instance));
|
|
783
|
+
}
|
|
784
|
+
/** The window of the launched process a command reads or acts in: the one the test chose, else the focused one, else the first visible one. */
|
|
785
|
+
async ownWindow(operation) {
|
|
786
|
+
const windows = await this.ownWindows(operation);
|
|
787
|
+
if (this.chosenWindow !== undefined)
|
|
788
|
+
return windows.find((window) => window.id === this.chosenWindow);
|
|
789
|
+
return windows.find((window) => window.is_focused === true) ?? windows.find((window) => window.visible !== false) ?? windows[0];
|
|
790
|
+
}
|
|
791
|
+
async observe(context, options) {
|
|
792
|
+
const operation = withDeadline(context);
|
|
793
|
+
const screen = await this.capture(operation);
|
|
794
|
+
if (screen === undefined) {
|
|
795
|
+
return { root: { ref: { id: ROOT_ID, revision: '' }, role: 'window' }, viewport: { width: 0, height: 0 } };
|
|
796
|
+
}
|
|
797
|
+
this.pointWindow = screen.windowId;
|
|
798
|
+
this.remember(screen.bindings.values());
|
|
799
|
+
const pixels = options?.pixels === true ? await this.pixelsFor(screen, operation).catch((cause) => {
|
|
800
|
+
if (cause instanceof EngineError && cause.code === 'OPERATION_TIMEOUT')
|
|
801
|
+
throw cause;
|
|
802
|
+
return undefined;
|
|
803
|
+
}) : undefined;
|
|
804
|
+
return {
|
|
805
|
+
...this.snapshotOf(screen),
|
|
806
|
+
...(pixels === undefined ? {} : { pixels: pixels.pixels, maskedRegionCount: pixels.masked }),
|
|
807
|
+
};
|
|
808
|
+
}
|
|
809
|
+
snapshotOf(screen) {
|
|
810
|
+
const app = this.appName;
|
|
811
|
+
const location = app === undefined ? screen.title : screen.title === undefined ? app : `${app} › ${screen.title}`;
|
|
812
|
+
return {
|
|
813
|
+
root: screen.root,
|
|
814
|
+
viewport: screen.viewport,
|
|
815
|
+
...(screen.truncated ? { truncated: true } : {}),
|
|
816
|
+
...(location === undefined ? {} : { location }),
|
|
817
|
+
};
|
|
818
|
+
}
|
|
819
|
+
async locate(expression, context) {
|
|
820
|
+
// agent-desktop reports no placeholder for a macOS field, so a placeholder query would match nothing, and a negative assertion on it pass.
|
|
821
|
+
if (queryKinds(expression).has('placeholder')) {
|
|
822
|
+
throw unsupported("macOS accessibility reports no placeholder to match; a field with no label is named by its placeholder, so find it with getByRole('textbox', name) or getByLabel(name)");
|
|
823
|
+
}
|
|
824
|
+
const operation = withDeadline(context);
|
|
825
|
+
const screen = await this.capture(operation);
|
|
826
|
+
if (screen === undefined)
|
|
827
|
+
return [];
|
|
828
|
+
const sink = this.attempt?.screen;
|
|
829
|
+
if (sink !== undefined) {
|
|
830
|
+
try {
|
|
831
|
+
sink(this.snapshotOf(screen));
|
|
832
|
+
}
|
|
833
|
+
catch {
|
|
834
|
+
// The trace is evidence; a sink that throws never fails the step.
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
// A read cut short (by its budget, or at the depth limit) can leave out a match: no match would not prove a control absent, and one would not prove it the only one. The locator reads again until its deadline.
|
|
838
|
+
if (screen.truncated) {
|
|
839
|
+
throw new EngineError('NODE_STALE', `the window was read only in part (it ran out of time, or is deeper than the ${this.options.maxDepth} levels a snapshot reads; desktop({ maxDepth }) raises that), so the matches cannot be counted`, { retryable: true });
|
|
840
|
+
}
|
|
841
|
+
const matches = resolveExpression(expression, [screen.root]);
|
|
842
|
+
this.pointWindow = screen.windowId;
|
|
843
|
+
this.remember(matches.flatMap((match) => screen.bindings.get(match.ref.id) ?? []));
|
|
844
|
+
return matches;
|
|
845
|
+
}
|
|
846
|
+
// --- acting ---
|
|
847
|
+
binding(ref) {
|
|
848
|
+
const binding = this.bindings.get(ref.id);
|
|
849
|
+
if (binding === undefined)
|
|
850
|
+
throw new EngineError('NODE_STALE', `node ${ref.id} is not on the screen`, { retryable: true });
|
|
851
|
+
// A node read before desktop.useWindow() chose another window is not on the screen in use: the harness locates it again there.
|
|
852
|
+
if (this.chosenWindow !== undefined && binding.windowId !== this.chosenWindow) {
|
|
853
|
+
throw new EngineError('NODE_STALE', `node ${ref.id} is in another window than the one desktop.useWindow() chose`, { retryable: true });
|
|
854
|
+
}
|
|
855
|
+
return binding;
|
|
856
|
+
}
|
|
857
|
+
/**
|
|
858
|
+
* Keeps the newest binding of each node: an id names the same control in
|
|
859
|
+
* every snapshot, and the newest snapshot's agent-desktop ref is the one to
|
|
860
|
+
* act on. A control that has since gone keeps its last ref, which
|
|
861
|
+
* agent-desktop refuses as stale.
|
|
862
|
+
*/
|
|
863
|
+
remember(bindings) {
|
|
864
|
+
const fresh = new Set();
|
|
865
|
+
for (const binding of bindings) {
|
|
866
|
+
this.bindings.delete(binding.id);
|
|
867
|
+
this.bindings.set(binding.id, binding);
|
|
868
|
+
fresh.add(binding.id);
|
|
869
|
+
}
|
|
870
|
+
// The oldest go first, but never one just read: a screen larger than the cap keeps every node.
|
|
871
|
+
for (const oldest of this.bindings.keys()) {
|
|
872
|
+
if (this.bindings.size <= MAX_BINDINGS)
|
|
873
|
+
break;
|
|
874
|
+
if (!fresh.has(oldest))
|
|
875
|
+
this.bindings.delete(oldest);
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
refOf(binding, action) {
|
|
879
|
+
if (binding.ref === undefined)
|
|
880
|
+
throw notActionable(`node ${binding.id} (${binding.role ?? 'unknown'}) is not a control agent-desktop can ${action}`);
|
|
881
|
+
return binding.ref;
|
|
882
|
+
}
|
|
883
|
+
async perform(ref, action, context) {
|
|
884
|
+
const operation = withDeadline(context);
|
|
885
|
+
if (ref.id === ROOT_ID) {
|
|
886
|
+
if (action.kind !== 'swipe')
|
|
887
|
+
throw notActionable(`the window takes swipe only, not ${action.kind}; act on a node`);
|
|
888
|
+
// The root is the window as it is now: read it again, since a locate or a restart may have moved on from the last observation.
|
|
889
|
+
const screen = await this.capture(operation);
|
|
890
|
+
if (screen !== undefined)
|
|
891
|
+
this.remember(screen.bindings.values());
|
|
892
|
+
const target = screen?.scrollTarget;
|
|
893
|
+
if (target === undefined)
|
|
894
|
+
throw notActionable('the window has nothing that scrolls');
|
|
895
|
+
await this.scroll(this.binding({ id: target, revision: '' }), action.direction, action.momentum, operation);
|
|
896
|
+
return this.settle(operation);
|
|
897
|
+
}
|
|
898
|
+
const binding = this.binding(ref);
|
|
899
|
+
switch (action.kind) {
|
|
900
|
+
case 'tap':
|
|
901
|
+
await this.refCommand('click', binding, operation);
|
|
902
|
+
break;
|
|
903
|
+
case 'doubleTap':
|
|
904
|
+
// agent-desktop double-clicks with the real pointer only; declared with `headed` alone.
|
|
905
|
+
await this.refCommand('double-click', binding, operation, [], undefined, true);
|
|
906
|
+
break;
|
|
907
|
+
case 'secondaryTap':
|
|
908
|
+
await this.refCommand('right-click', binding, operation);
|
|
909
|
+
break;
|
|
910
|
+
case 'focus':
|
|
911
|
+
await this.refCommand('focus', binding, operation);
|
|
912
|
+
break;
|
|
913
|
+
case 'clear':
|
|
914
|
+
await this.refCommand('clear', binding, operation);
|
|
915
|
+
break;
|
|
916
|
+
case 'check':
|
|
917
|
+
case 'uncheck':
|
|
918
|
+
// agent-desktop reads the live state, so a box already right sends nothing; the observed state may be stale.
|
|
919
|
+
await this.refCommand(action.kind, binding, operation);
|
|
920
|
+
break;
|
|
921
|
+
case 'scrollIntoView':
|
|
922
|
+
await this.refCommand('scroll-to', binding, operation);
|
|
923
|
+
break;
|
|
924
|
+
case 'hover':
|
|
925
|
+
await this.refCommand('hover', binding, operation, [], undefined, true);
|
|
926
|
+
break;
|
|
927
|
+
case 'fill':
|
|
928
|
+
await this.refCommand('set-value', binding, operation, [], action.value);
|
|
929
|
+
break;
|
|
930
|
+
case 'press': {
|
|
931
|
+
// A key agent-desktop cannot press is refused before focus moves.
|
|
932
|
+
const combo = toCombo(action.key);
|
|
933
|
+
const window = binding.windowId;
|
|
934
|
+
if (window === undefined)
|
|
935
|
+
throw notActionable(`node ${binding.id} was read in no window to press a key into`);
|
|
936
|
+
await this.refCommand('focus', binding, operation);
|
|
937
|
+
try {
|
|
938
|
+
// The key goes to the process, which hands it to its key window: with more than one window, the control's must be the one shown focused.
|
|
939
|
+
const windows = (await this.ownWindows(operation)).filter((candidate) => candidate.visible !== false);
|
|
940
|
+
const home = windows.find((candidate) => candidate.id === window);
|
|
941
|
+
if (home === undefined)
|
|
942
|
+
throw notActionable(`the window node ${binding.id} was read in is gone`);
|
|
943
|
+
if (windows.length > 1 && home.is_focused !== true) {
|
|
944
|
+
throw notActionable(`node ${binding.id} is in a window that cannot be shown to be the app's key window, so the key could land in another window`);
|
|
945
|
+
}
|
|
946
|
+
// Focusing can hand focus on (a dialog it opens): the key goes only when the control still holds it. A control with an identity keeps its id; a look-alike has a new id in every read, so it is found by role and place.
|
|
947
|
+
const now = await this.capture(operation, window);
|
|
948
|
+
const held = [...(now?.bindings.values() ?? [])].some((candidate) => candidate.states?.focused === true && (binding.stable ? candidate.id === binding.id : candidate.role === binding.role && sameRect(candidate.rect, binding.rect)));
|
|
949
|
+
if (!held)
|
|
950
|
+
throw notActionable(`node ${binding.id} did not keep keyboard focus, so the key would land on another control`);
|
|
951
|
+
await this.sendKey(combo, window, `press ${action.key}`, operation);
|
|
952
|
+
}
|
|
953
|
+
catch (cause) {
|
|
954
|
+
// The focus already moved: a retry of the whole press would focus the control a second time, which an app's focus handler sees.
|
|
955
|
+
if (cause instanceof EngineError && cause.retryable) {
|
|
956
|
+
throw new EngineError('ACTION_MAY_HAVE_COMMITTED', `press ${action.key}: ${cause.message} (the control was already focused)`, { retryable: false, cause });
|
|
957
|
+
}
|
|
958
|
+
throw cause;
|
|
959
|
+
}
|
|
960
|
+
break;
|
|
961
|
+
}
|
|
962
|
+
case 'selectOption':
|
|
963
|
+
await this.select(binding, optionLabel(action.value), operation);
|
|
964
|
+
break;
|
|
965
|
+
case 'swipe':
|
|
966
|
+
await this.scroll(binding, action.direction, action.momentum, operation);
|
|
967
|
+
break;
|
|
968
|
+
case 'longPress':
|
|
969
|
+
case 'setInputFiles':
|
|
970
|
+
case 'dragTo':
|
|
971
|
+
// Not declared in `actions` (engine.ts), so the harness never sends them; kept exhaustive.
|
|
972
|
+
throw unsupported(`the desktop engine cannot perform ${action.kind}`);
|
|
973
|
+
}
|
|
974
|
+
await this.settle(operation);
|
|
975
|
+
}
|
|
976
|
+
/** The agent reads the screen right after acting, so its actions let the UI settle first; a test's own steps verify with `expect`. */
|
|
977
|
+
async settle(operation) {
|
|
978
|
+
if (operation.origin === 'agent')
|
|
979
|
+
await sleep(Math.min(this.options.settleMs, operation.timeoutMs), operation.signal);
|
|
980
|
+
}
|
|
981
|
+
/** One command on a node's ref, failures translated. */
|
|
982
|
+
async refCommand(command, binding, operation, extra = [], stdin, headed = false) {
|
|
983
|
+
try {
|
|
984
|
+
await this.tryRef(command, binding, operation, extra, stdin, headed);
|
|
985
|
+
}
|
|
986
|
+
catch (cause) {
|
|
987
|
+
throw translate(cause, command, true);
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
/** One command on a node's ref, a failure left as agent-desktop reported it so a caller can try another way when nothing was sent. */
|
|
991
|
+
async tryRef(command, binding, operation, extra = [], stdin, headed = false) {
|
|
992
|
+
const args = [command, this.refOf(binding, command), '--timeout-ms', String(this.toolBudget(operation))];
|
|
993
|
+
if (stdin !== undefined)
|
|
994
|
+
args.push('--stdin');
|
|
995
|
+
if (headed)
|
|
996
|
+
args.push('--headed');
|
|
997
|
+
// Last, so a value after `--` is never read as a flag.
|
|
998
|
+
args.push(...extra);
|
|
999
|
+
return await this.run(args, { label: command, input: true, signal: operation.signal, timeoutMs: operation.timeoutMs, raw: true, ...(stdin === undefined ? {} : { stdin }) });
|
|
1000
|
+
}
|
|
1001
|
+
/**
|
|
1002
|
+
* Chooses an option of a list or dropdown with agent-desktop's `select`,
|
|
1003
|
+
* never by setting the value, which would put a missing option in an
|
|
1004
|
+
* editable combo box as free text. A stale ref is `NODE_STALE`, so the
|
|
1005
|
+
* harness locates the list again. For a pop-up button agent-desktop opens
|
|
1006
|
+
* the menu to find the option; when it cannot, it leaves the menu open,
|
|
1007
|
+
* which is closed again here. A failure after the menu opened stays one
|
|
1008
|
+
* that may have chosen something: a menu left open does not show which
|
|
1009
|
+
* control opened it, or that the option is missing.
|
|
1010
|
+
*/
|
|
1011
|
+
async select(binding, label, operation) {
|
|
1012
|
+
const ref = this.refOf(binding, 'select');
|
|
1013
|
+
try {
|
|
1014
|
+
await this.run(['select', ref, '--timeout-ms', String(Math.min(this.toolBudget(operation), SELECT_WAIT_MS)), '--', label], { label: 'select', input: true, signal: operation.signal, timeoutMs: operation.timeoutMs, raw: true });
|
|
1015
|
+
}
|
|
1016
|
+
catch (cause) {
|
|
1017
|
+
// `select` answers ELEMENT_NOT_FOUND for an option it cannot find; a list that is gone is a stale ref.
|
|
1018
|
+
if (cause instanceof AgentDesktopFailure && cause.notDelivered && cause.code === 'ELEMENT_NOT_FOUND')
|
|
1019
|
+
throw notActionable(`the list has no option "${label}"`);
|
|
1020
|
+
// A menu that cannot be closed leaves the select's own failure to report.
|
|
1021
|
+
if (cause instanceof AgentDesktopFailure && !cause.notDelivered && (await this.closeOpenMenu(binding.windowId, operation).catch(() => false))) {
|
|
1022
|
+
throw new EngineError('ACTION_MAY_HAVE_COMMITTED', `select "${label}": agent-desktop opened the list's menu and did not choose it; the list may have no option "${label}". The menu was closed`, { retryable: false, cause });
|
|
1023
|
+
}
|
|
1024
|
+
throw translate(cause, `select "${label}"`, true);
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
/**
|
|
1028
|
+
* Closes a menu the launched process has open, with Escape. True only when
|
|
1029
|
+
* a menu was open and is closed now; false when there was none, or it
|
|
1030
|
+
* cannot be told whose it is (another copy shares the app's name).
|
|
1031
|
+
*/
|
|
1032
|
+
async closeOpenMenu(window, operation) {
|
|
1033
|
+
const { appName, pid } = this;
|
|
1034
|
+
if (appName === undefined || pid === undefined || window === undefined)
|
|
1035
|
+
return false;
|
|
1036
|
+
const menus = async () => {
|
|
1037
|
+
const listed = await this.run(['list-surfaces', '--app', appName], { label: 'list surfaces', input: false, signal: operation.signal, timeoutMs: operation.timeoutMs }).catch(() => undefined);
|
|
1038
|
+
if (listed?.pid !== pid)
|
|
1039
|
+
return undefined;
|
|
1040
|
+
return (listed.surfaces ?? []).filter((surface) => surface.type?.includes('menu') === true).length;
|
|
1041
|
+
};
|
|
1042
|
+
if (((await menus()) ?? 0) === 0)
|
|
1043
|
+
return false;
|
|
1044
|
+
await this.sendKey('escape', window, 'close menu', operation);
|
|
1045
|
+
// A menu takes a moment to close after Escape.
|
|
1046
|
+
const until = Date.now() + Math.min(MENU_CLOSE_MS, operation.timeoutMs);
|
|
1047
|
+
for (;;) {
|
|
1048
|
+
if ((await menus()) === 0)
|
|
1049
|
+
return true;
|
|
1050
|
+
if (Date.now() + LAUNCH_POLL_MS >= until)
|
|
1051
|
+
return false;
|
|
1052
|
+
await sleep(LAUNCH_POLL_MS, operation.signal);
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
async scroll(binding, direction, momentum, operation) {
|
|
1056
|
+
const amount = momentum === 'fast' ? 10 : momentum === 'slow' ? 2 : 5;
|
|
1057
|
+
await this.refCommand('scroll', binding, operation, ['--direction', direction, '--amount', String(amount)]);
|
|
1058
|
+
}
|
|
1059
|
+
/** Physical pointer input at a point in the window: only with `headed`, and only then declared. */
|
|
1060
|
+
async performAt(point, action, context) {
|
|
1061
|
+
const operation = withDeadline(context);
|
|
1062
|
+
// The point is in the observed window's coordinates: find that window where it is now (it may have moved), or the app's own window before any observation.
|
|
1063
|
+
const observed = this.pointWindow;
|
|
1064
|
+
const target = observed === undefined ? await this.ownWindow(operation) : (await this.ownWindows(operation)).find((candidate) => candidate.id === observed);
|
|
1065
|
+
const window = target?.bounds;
|
|
1066
|
+
if (target === undefined || window === undefined)
|
|
1067
|
+
throw notActionable('the window the point was taken from is no longer on screen; observe again');
|
|
1068
|
+
if (point.x < 0 || point.y < 0 || point.x >= window.width || point.y >= window.height) {
|
|
1069
|
+
throw notActionable(`(${point.x}, ${point.y}) is outside the ${window.width}x${window.height} window; a click there would land on another app`);
|
|
1070
|
+
}
|
|
1071
|
+
// Physical input lands on whatever is frontmost at the point: bring the window forward first.
|
|
1072
|
+
await this.run(['focus-window', '--window-id', target.id, '--headed'], { label: 'focus window', input: true, signal: operation.signal, timeoutMs: operation.timeoutMs });
|
|
1073
|
+
// Coming forward can move the window (onto another space, out from under the menu bar): the click is measured from where it is now.
|
|
1074
|
+
const focused = (await this.ownWindows(operation)).find((candidate) => candidate.id === target.id)?.bounds;
|
|
1075
|
+
if (focused === undefined)
|
|
1076
|
+
throw notActionable('the window the point was taken from closed as it was brought forward; observe again');
|
|
1077
|
+
if (point.x >= focused.width || point.y >= focused.height) {
|
|
1078
|
+
throw notActionable(`(${point.x}, ${point.y}) is outside the ${focused.width}x${focused.height} window; a click there would land on another app`);
|
|
1079
|
+
}
|
|
1080
|
+
// Unrounded: agent-desktop takes fractional points, and rounding could carry a point past the window's edge.
|
|
1081
|
+
const xy = `--xy=${focused.x + point.x},${focused.y + point.y}`;
|
|
1082
|
+
const args = action.kind === 'hover'
|
|
1083
|
+
? ['hover', xy, '--headed']
|
|
1084
|
+
: ['mouse-click', xy, '--headed', ...(action.kind === 'doubleTap' ? ['--count', '2'] : []), ...(action.kind === 'secondaryTap' ? ['--button', 'right'] : [])];
|
|
1085
|
+
if (action.kind !== 'hover' && action.kind !== 'tap' && action.kind !== 'doubleTap' && action.kind !== 'secondaryTap') {
|
|
1086
|
+
throw unsupported(`the desktop engine cannot perform ${action.kind} at a point`);
|
|
1087
|
+
}
|
|
1088
|
+
await this.run(args, { label: action.kind, input: true, signal: operation.signal, timeoutMs: operation.timeoutMs });
|
|
1089
|
+
await this.settle(operation);
|
|
1090
|
+
}
|
|
1091
|
+
/** The keyboard capability's `type` (declared with `headed` only): keystrokes into the focused field, which a fresh snapshot names. */
|
|
1092
|
+
async typeText(text, options, context) {
|
|
1093
|
+
const operation = withDeadline(context);
|
|
1094
|
+
const screen = await this.capture(operation);
|
|
1095
|
+
const focused = screen === undefined ? undefined : [...screen.bindings.values()].find((binding) => binding.ref !== undefined && binding.states?.focused === true);
|
|
1096
|
+
if (focused === undefined)
|
|
1097
|
+
throw notActionable('no field has keyboard focus; tap or focus the field first');
|
|
1098
|
+
if (options.replace)
|
|
1099
|
+
await this.refCommand('clear', focused, operation);
|
|
1100
|
+
// Keystrokes, which only physical input sends: without it agent-desktop sets the text, and the app's key handlers never run.
|
|
1101
|
+
const type = () => this.tryRef('type', focused, operation, [], text, true);
|
|
1102
|
+
if (options.replace)
|
|
1103
|
+
await afterChange('type', type);
|
|
1104
|
+
else
|
|
1105
|
+
await type().catch((cause) => Promise.reject(translate(cause, 'type', true)));
|
|
1106
|
+
await this.settle(operation);
|
|
1107
|
+
}
|
|
1108
|
+
/** One key to whatever holds focus in the app; agent-desktop sends it to the process without focusing its window. */
|
|
1109
|
+
async pressKey(key, context) {
|
|
1110
|
+
const operation = withDeadline(context);
|
|
1111
|
+
const combo = toCombo(key);
|
|
1112
|
+
const window = await this.ownWindow(operation);
|
|
1113
|
+
if (window === undefined)
|
|
1114
|
+
throw this.chosenWindow === undefined ? invalidState('the app is not running; open it with app.open()') : this.chosenClosed();
|
|
1115
|
+
await this.sendKey(combo, window.id, `press ${key}`, operation);
|
|
1116
|
+
}
|
|
1117
|
+
/**
|
|
1118
|
+
* Sends one key combo to the launched process's window. agent-desktop
|
|
1119
|
+
* sends a key to a named window only while that window is active, which
|
|
1120
|
+
* an app in the background never is, and refuses it before sending. A key
|
|
1121
|
+
* is never sent by the app's name instead: the name does not pin the
|
|
1122
|
+
* process, so the key could reach another copy. With `headed`,
|
|
1123
|
+
* agent-desktop brings the window forward first.
|
|
1124
|
+
*/
|
|
1125
|
+
async sendKey(combo, window, label, operation) {
|
|
1126
|
+
const call = { label, input: true, signal: operation.signal, timeoutMs: operation.timeoutMs };
|
|
1127
|
+
if (this.options.headed) {
|
|
1128
|
+
await this.run(['press', combo, '--window-id', window, '--headed'], call);
|
|
1129
|
+
return;
|
|
1130
|
+
}
|
|
1131
|
+
try {
|
|
1132
|
+
await this.run(['press', combo, '--window-id', window], { ...call, raw: true });
|
|
1133
|
+
}
|
|
1134
|
+
catch (cause) {
|
|
1135
|
+
if (cause instanceof AgentDesktopFailure && cause.notDelivered && cause.details.cause === 'exact_window_focus_unconfirmed') {
|
|
1136
|
+
throw notActionable(`${label}: agent-desktop sends a key only to the active window, and the app runs in the background, so nothing was sent; set desktop({ headed: true }) to press keys`);
|
|
1137
|
+
}
|
|
1138
|
+
throw translate(cause, label, true);
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
// --- pixels ---
|
|
1142
|
+
async screenshot(label, context) {
|
|
1143
|
+
const operation = withDeadline(context);
|
|
1144
|
+
const attempt = this.attempt;
|
|
1145
|
+
if (attempt === undefined)
|
|
1146
|
+
throw invalidState('screenshot outside an attempt');
|
|
1147
|
+
const screen = await this.capture(operation);
|
|
1148
|
+
if (screen === undefined)
|
|
1149
|
+
throw invalidState('the app has no window to capture; open it with app.open()');
|
|
1150
|
+
const { pixels } = await this.pixelsFor(screen, operation);
|
|
1151
|
+
attempt.screenshots += 1;
|
|
1152
|
+
const relative = path.join('screenshots', `${String(attempt.screenshots).padStart(3, '0')}-${sanitizeFilename(label ?? 'screenshot')}.png`);
|
|
1153
|
+
await mkdir(path.join(attempt.artifactsDir, 'screenshots'), { recursive: true });
|
|
1154
|
+
await writeFile(path.join(attempt.artifactsDir, relative), pixels.data);
|
|
1155
|
+
return relative;
|
|
1156
|
+
}
|
|
1157
|
+
/**
|
|
1158
|
+
* The window's pixels with every secure field painted over. The fields
|
|
1159
|
+
* come from the snapshot taken just before, and the window is read again
|
|
1160
|
+
* after the capture: a secure field without bounds, a partial snapshot, or
|
|
1161
|
+
* a field that moved in between withholds the image rather than ship it
|
|
1162
|
+
* unproven.
|
|
1163
|
+
*/
|
|
1164
|
+
async pixelsFor(observed, operation) {
|
|
1165
|
+
if (observed.windowId === undefined)
|
|
1166
|
+
throw notActionable('the observed surface has no window to capture');
|
|
1167
|
+
// The secure fields come from a whole read of the window, never an interactive one, which can leave a secure node out.
|
|
1168
|
+
const screen = this.options.interactiveOnly ? await this.capture(operation, observed.windowId, true) : observed;
|
|
1169
|
+
if (screen?.windowId === undefined)
|
|
1170
|
+
throw new EngineError('ENGINE_FAILURE', 'the window could not be read whole to find its secure fields; screenshot withheld', { retryable: false });
|
|
1171
|
+
const secure = screen.secureRects;
|
|
1172
|
+
if (secure === undefined)
|
|
1173
|
+
throw new EngineError('ENGINE_FAILURE', 'a secure field on screen has no bounds to mask; screenshot withheld', { retryable: false });
|
|
1174
|
+
// A snapshot cut short can leave out a secure field, which would then go unmasked.
|
|
1175
|
+
if (screen.truncated)
|
|
1176
|
+
throw new EngineError('ENGINE_FAILURE', 'the snapshot did not read the whole window, so a secure field may be missing from it; screenshot withheld', { retryable: false });
|
|
1177
|
+
const directory = await mkdtemp(path.join(this.home ?? tmpdir(), 'shot-'));
|
|
1178
|
+
try {
|
|
1179
|
+
const file = path.join(directory, 'window.png');
|
|
1180
|
+
const shot = await this.run(['screenshot', '--window-id', screen.windowId, file], { label: 'screenshot', input: false, signal: operation.signal, timeoutMs: operation.timeoutMs });
|
|
1181
|
+
// The snapshot and the capture are two commands: read the window again, and withhold the image if a secure field moved, came, or went between them.
|
|
1182
|
+
const after = await this.capture(operation, screen.windowId, true);
|
|
1183
|
+
if (after === undefined || after.windowId !== screen.windowId || after.truncated || !sameRects(after.secureRects, secure) || after.viewport.width !== screen.viewport.width || after.viewport.height !== screen.viewport.height) {
|
|
1184
|
+
throw new EngineError('ENGINE_FAILURE', 'the window changed while it was captured, so its secure fields cannot be placed; screenshot withheld', { retryable: false });
|
|
1185
|
+
}
|
|
1186
|
+
const scale = typeof shot.scale_factor === 'number' && shot.scale_factor > 0 ? shot.scale_factor : 1;
|
|
1187
|
+
const raw = new Uint8Array(await readFile(file));
|
|
1188
|
+
const expected = { width: Math.round(screen.viewport.width * scale), height: Math.round(screen.viewport.height * scale) };
|
|
1189
|
+
const rects = secure.map((rect) => ({ x: rect.x * scale, y: rect.y * scale, width: rect.width * scale, height: rect.height * scale }));
|
|
1190
|
+
const image = windowImage(raw, expected, rects);
|
|
1191
|
+
if (image === undefined) {
|
|
1192
|
+
throw new EngineError('ENGINE_FAILURE', `the window capture does not match the window's ${expected.width}x${expected.height} pixels, so its secure fields cannot be placed; screenshot withheld`, { retryable: false });
|
|
1193
|
+
}
|
|
1194
|
+
return { pixels: { data: encodePng(image), mediaType: 'image/png', width: image.width, height: image.height, scale }, masked: rects.length };
|
|
1195
|
+
}
|
|
1196
|
+
finally {
|
|
1197
|
+
await rm(directory, { recursive: true, force: true });
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
// --- plumbing ---
|
|
1201
|
+
/** agent-desktop's own wait inside one command: the operation's budget less a margin, so it answers before it is killed. */
|
|
1202
|
+
toolBudget(operation) {
|
|
1203
|
+
return Math.max(operation.timeoutMs - ANSWER_MARGIN_MS, MIN_TOOL_MS);
|
|
1204
|
+
}
|
|
1205
|
+
/**
|
|
1206
|
+
* Runs one command. A failure is translated onto the engine contract
|
|
1207
|
+
* unless `raw` asks for agent-desktop's own, which a caller reads to try
|
|
1208
|
+
* another way.
|
|
1209
|
+
*/
|
|
1210
|
+
async run(args, call) {
|
|
1211
|
+
const cli = this.cli;
|
|
1212
|
+
if (cli === undefined)
|
|
1213
|
+
throw invalidState('the desktop engine is not initialized');
|
|
1214
|
+
// Nothing is sent once the operation's budget is spent: a later rung of a fallback never starts past the deadline.
|
|
1215
|
+
if (call.timeoutMs <= 0)
|
|
1216
|
+
throw new EngineError('OPERATION_TIMEOUT', `${call.label}: the operation's budget ran out before it was sent`, { retryable: false, cause: NOT_SENT });
|
|
1217
|
+
try {
|
|
1218
|
+
return await cli.run({ args, input: call.input, signal: call.signal, timeoutMs: call.timeoutMs, label: call.label, ...(call.stdin === undefined ? {} : { stdin: call.stdin }) });
|
|
1219
|
+
}
|
|
1220
|
+
catch (cause) {
|
|
1221
|
+
if (call.raw === true && cause instanceof AgentDesktopFailure)
|
|
1222
|
+
throw cause;
|
|
1223
|
+
throw translate(cause, call.label, call.input);
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
/**
|
|
1228
|
+
* Whether a process carries a launch token in its environment, read with
|
|
1229
|
+
* `ps -E` (and from `/proc` on Linux, where the unit tests also run).
|
|
1230
|
+
* Undefined where the environment cannot be read (a macOS system app, a
|
|
1231
|
+
* build signed with the `restrict` flag, a lookup that failed): no evidence
|
|
1232
|
+
* either way.
|
|
1233
|
+
*/
|
|
1234
|
+
async function carriesToken(pid, token, signal) {
|
|
1235
|
+
const marker = `${LAUNCH_TOKEN}=${token}`;
|
|
1236
|
+
if (process.platform === 'linux') {
|
|
1237
|
+
const environ = await readFile(`/proc/${pid}/environ`, 'utf8').catch(() => undefined);
|
|
1238
|
+
if (environ === undefined || environ === '')
|
|
1239
|
+
return undefined;
|
|
1240
|
+
const entries = environ.split('\0');
|
|
1241
|
+
if (entries.includes(marker))
|
|
1242
|
+
return true;
|
|
1243
|
+
return entries.some((entry) => /^(HOME|PATH|USER)=/.test(entry)) ? false : undefined;
|
|
1244
|
+
}
|
|
1245
|
+
const { stdout } = await execFileAsync('ps', ['-E', '-p', String(pid), '-o', 'command='], { signal }).catch(() => ({ stdout: '' }));
|
|
1246
|
+
const words = stdout.split(/\s+/);
|
|
1247
|
+
if (words.includes(marker))
|
|
1248
|
+
return true;
|
|
1249
|
+
// macOS hides the environment of a restricted process, and `ps -E` then prints the command alone: that is no evidence either way.
|
|
1250
|
+
return words.some((word) => /^(HOME|PATH|USER)=/.test(word)) ? false : undefined;
|
|
1251
|
+
}
|
|
1252
|
+
/**
|
|
1253
|
+
* The processes whose environment carries a launch token: the app the
|
|
1254
|
+
* launch that made it started, whatever its process id. A process whose
|
|
1255
|
+
* environment cannot be read is never among them. Undefined when the
|
|
1256
|
+
* processes could not be listed, which shows nothing.
|
|
1257
|
+
*/
|
|
1258
|
+
async function processesCarrying(token, signal) {
|
|
1259
|
+
const marker = `${LAUNCH_TOKEN}=${token}`;
|
|
1260
|
+
if (process.platform === 'linux') {
|
|
1261
|
+
const entries = await readdir('/proc').catch(() => undefined);
|
|
1262
|
+
if (entries === undefined)
|
|
1263
|
+
return undefined;
|
|
1264
|
+
const found = [];
|
|
1265
|
+
for (const entry of entries) {
|
|
1266
|
+
if (!/^\d+$/.test(entry))
|
|
1267
|
+
continue;
|
|
1268
|
+
const environ = await readFile(`/proc/${entry}/environ`, 'utf8').catch(() => '');
|
|
1269
|
+
if (environ.split('\0').includes(marker))
|
|
1270
|
+
found.push(Number(entry));
|
|
1271
|
+
}
|
|
1272
|
+
return found;
|
|
1273
|
+
}
|
|
1274
|
+
const listed = await execFileAsync('ps', ['-E', '-ww', '-ax', '-o', 'pid=,command='], { signal, maxBuffer: 256 * 1024 * 1024 }).catch(() => undefined);
|
|
1275
|
+
if (listed === undefined)
|
|
1276
|
+
return undefined;
|
|
1277
|
+
return listed.stdout
|
|
1278
|
+
.split('\n')
|
|
1279
|
+
.map((line) => line.trim().split(/\s+/))
|
|
1280
|
+
.filter((words) => words.includes(marker))
|
|
1281
|
+
.map((words) => Number(words[0]))
|
|
1282
|
+
.filter((pid) => Number.isInteger(pid) && pid > 0 && pid !== process.pid);
|
|
1283
|
+
}
|
|
1284
|
+
/**
|
|
1285
|
+
* What `init` needs of an `appPath` bundle: an Info.plist naming the
|
|
1286
|
+
* bundle id the launched process is found by, which is the target's
|
|
1287
|
+
* `bundleId` when that is set too, and a signature that lets the launch
|
|
1288
|
+
* token be read: macOS hides the environment of its own apps and of a build
|
|
1289
|
+
* signed with the `restrict` flag, so the copy `open` starts could not be
|
|
1290
|
+
* told from another.
|
|
1291
|
+
*/
|
|
1292
|
+
async function checkBundle(bundle, bundleId, signal) {
|
|
1293
|
+
const plist = path.join(bundle, 'Contents', 'Info.plist');
|
|
1294
|
+
if (!existsSync(plist))
|
|
1295
|
+
return { problem: `app.appPath ${bundle} is not an app bundle: it has no Contents/Info.plist. Build the app first` };
|
|
1296
|
+
// plutil exits with an error when the key is missing or the file is no plist.
|
|
1297
|
+
const { stdout } = await execFileAsync('plutil', ['-extract', 'CFBundleIdentifier', 'raw', '-o', '-', plist], { signal }).catch(() => ({ stdout: '' }));
|
|
1298
|
+
const declared = stdout.trim();
|
|
1299
|
+
if (declared === '')
|
|
1300
|
+
return { problem: `${plist} declares no CFBundleIdentifier` };
|
|
1301
|
+
if (bundleId !== undefined && bundleId !== declared) {
|
|
1302
|
+
return { problem: `app.bundleId "${bundleId}" is not the CFBundleIdentifier "${declared}" of app.appPath ${bundle}; the build at appPath is what app.open() launches` };
|
|
1303
|
+
}
|
|
1304
|
+
// codesign prints the signature to stderr, and fails on a bundle that is not signed, which hides nothing.
|
|
1305
|
+
const signature = await execFileAsync('codesign', ['-dv', bundle], { signal }).then(({ stderr }) => stderr, (cause) => (typeof cause.stderr === 'string' ? cause.stderr : ''));
|
|
1306
|
+
if (/^Platform identifier=/m.test(signature) || /flags=0x[\da-f]+\([^)]*\brestrict\b/.test(signature)) {
|
|
1307
|
+
return {
|
|
1308
|
+
problem: `app.appPath ${bundle} is a macOS app or a build signed with the restrict flag, whose environment macOS hides, so the engine cannot tell the copy it opens from another; set app.bundleId "${declared}" and leave out appPath, so agent-desktop's launch reports the process it starts`,
|
|
1309
|
+
};
|
|
1310
|
+
}
|
|
1311
|
+
return { bundleId: declared };
|
|
1312
|
+
}
|
|
1313
|
+
/** The run's environment cut to the variables the app and agent-desktop may see (`INHERITED_ENV`, and `LC_*`). */
|
|
1314
|
+
function inheritedEnv(env) {
|
|
1315
|
+
const kept = {};
|
|
1316
|
+
for (const [name, value] of Object.entries(env)) {
|
|
1317
|
+
if (value !== undefined && (INHERITED_ENV.has(name) || name.startsWith('LC_')))
|
|
1318
|
+
kept[name] = value;
|
|
1319
|
+
}
|
|
1320
|
+
return kept;
|
|
1321
|
+
}
|
|
1322
|
+
/**
|
|
1323
|
+
* Removes the state directories workers left behind: agent-desktop writes
|
|
1324
|
+
* the text of plain fields there, and a worker that was killed never
|
|
1325
|
+
* removed its own. A directory goes once the process its owner file names
|
|
1326
|
+
* is gone, or, with no owner file, once it is a day old. One still in use
|
|
1327
|
+
* is never touched. The app such a worker launched and left running is
|
|
1328
|
+
* quit too: every process whose environment carries the token its launch
|
|
1329
|
+
* record names, and the process the record names when it is still the one
|
|
1330
|
+
* that started then. A process shown to be the launch's by neither is left
|
|
1331
|
+
* alone. When the processes cannot be looked up, or one does not exit, the
|
|
1332
|
+
* record stays, without the field text, for the next run to try again.
|
|
1333
|
+
*/
|
|
1334
|
+
async function sweepStateDirectories() {
|
|
1335
|
+
const root = tmpdir();
|
|
1336
|
+
const entries = await readdir(root).catch(() => []);
|
|
1337
|
+
for (const entry of entries) {
|
|
1338
|
+
if (!entry.startsWith(STATE_PREFIX))
|
|
1339
|
+
continue;
|
|
1340
|
+
const directory = path.join(root, entry);
|
|
1341
|
+
const owner = Number((await readFile(path.join(directory, OWNER_FILE), 'utf8').catch(() => '')).trim());
|
|
1342
|
+
const stale = Number.isInteger(owner) && owner > 0 ? !alive(owner) : await stat(directory).then((info) => Date.now() - info.mtimeMs > ORPHAN_AGE_MS, () => false);
|
|
1343
|
+
if (!stale)
|
|
1344
|
+
continue;
|
|
1345
|
+
// A record cut short by the kill that left it names no process: the directory still goes.
|
|
1346
|
+
const parsed = await readFile(path.join(directory, APP_FILE), 'utf8').then((text) => JSON.parse(text)).catch(() => undefined);
|
|
1347
|
+
const launched = typeof parsed === 'object' && parsed !== null ? parsed : {};
|
|
1348
|
+
const signal = AbortSignal.timeout(5_000);
|
|
1349
|
+
const owned = [];
|
|
1350
|
+
let known = true;
|
|
1351
|
+
if (typeof launched.token === 'string' && launched.token !== '') {
|
|
1352
|
+
const carriers = await processesCarrying(launched.token, signal);
|
|
1353
|
+
if (carriers === undefined)
|
|
1354
|
+
known = false;
|
|
1355
|
+
else
|
|
1356
|
+
owned.push(...carriers);
|
|
1357
|
+
}
|
|
1358
|
+
const { pid, started } = launched;
|
|
1359
|
+
if (typeof pid === 'number' && typeof started === 'string' && alive(pid)) {
|
|
1360
|
+
const now = await startedAt(pid, signal);
|
|
1361
|
+
// Running, but when it started cannot be read: whether it is the launch's process is unknown.
|
|
1362
|
+
if (now === undefined)
|
|
1363
|
+
known = false;
|
|
1364
|
+
else if (now === started && !owned.includes(pid))
|
|
1365
|
+
owned.push(pid);
|
|
1366
|
+
}
|
|
1367
|
+
const settled = known && (await killed(owned, Date.now() + 2_000, signal));
|
|
1368
|
+
await (settled ? rm(directory, { recursive: true, force: true }) : keepOnlyRecord(directory)).catch(() => undefined);
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
/** Removes everything in a state directory but its owner file and launch record: the text agent-desktop kept of the app's fields. */
|
|
1372
|
+
async function keepOnlyRecord(directory) {
|
|
1373
|
+
for (const entry of await readdir(directory).catch(() => [])) {
|
|
1374
|
+
if (entry !== OWNER_FILE && entry !== APP_FILE)
|
|
1375
|
+
await rm(path.join(directory, entry), { recursive: true, force: true });
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
/** Kills each process and waits until all of them exited; false when one still runs at `until`. */
|
|
1379
|
+
async function killed(pids, until, signal) {
|
|
1380
|
+
for (const pid of pids) {
|
|
1381
|
+
try {
|
|
1382
|
+
process.kill(pid, 'SIGKILL');
|
|
1383
|
+
}
|
|
1384
|
+
catch {
|
|
1385
|
+
// Gone already.
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
while (pids.some((pid) => alive(pid))) {
|
|
1389
|
+
if (signal.aborted || Date.now() >= until)
|
|
1390
|
+
return false;
|
|
1391
|
+
await sleep(LAUNCH_POLL_MS, signal);
|
|
1392
|
+
}
|
|
1393
|
+
return true;
|
|
1394
|
+
}
|
|
1395
|
+
/**
|
|
1396
|
+
* When a process started, as `ps` prints it: with its id, what tells it
|
|
1397
|
+
* from a later process the OS gives the same id. Undefined when it is not
|
|
1398
|
+
* running or `ps` failed.
|
|
1399
|
+
*/
|
|
1400
|
+
async function startedAt(pid, signal) {
|
|
1401
|
+
const { stdout } = await execFileAsync('ps', ['-o', 'lstart=', '-p', String(pid)], { signal, env: { ...process.env, LC_ALL: 'C' } }).catch(() => ({ stdout: '' }));
|
|
1402
|
+
const text = stdout.trim();
|
|
1403
|
+
return text === '' ? undefined : text;
|
|
1404
|
+
}
|
|
1405
|
+
/**
|
|
1406
|
+
* Runs the input that follows one that already changed the app (a clear
|
|
1407
|
+
* before a type): its failure, whatever agent-desktop says it sent, is
|
|
1408
|
+
* `ACTION_MAY_HAVE_COMMITTED`, so the step is never repeated as if nothing
|
|
1409
|
+
* happened.
|
|
1410
|
+
*/
|
|
1411
|
+
async function afterChange(label, run) {
|
|
1412
|
+
try {
|
|
1413
|
+
await run();
|
|
1414
|
+
}
|
|
1415
|
+
catch (cause) {
|
|
1416
|
+
throw new EngineError('ACTION_MAY_HAVE_COMMITTED', `${label}: ${cause.message} (an earlier command of this step changed the app)`, { retryable: false, cause });
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
/** Whether two rects are the same; two missing rects are not. */
|
|
1420
|
+
function sameRect(a, b) {
|
|
1421
|
+
return a !== undefined && b !== undefined && a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
|
|
1422
|
+
}
|
|
1423
|
+
/** Whether two lists of secure-field rects are the same, in order. */
|
|
1424
|
+
function sameRects(a, b) {
|
|
1425
|
+
return a !== undefined && a.length === b.length && a.every((rect, index) => {
|
|
1426
|
+
const other = b[index];
|
|
1427
|
+
return rect.x === other.x && rect.y === other.y && rect.width === other.width && rect.height === other.height;
|
|
1428
|
+
});
|
|
1429
|
+
}
|
|
1430
|
+
/** Whether a process still runs: it answers signal 0, or exists but belongs to another user. */
|
|
1431
|
+
function alive(pid) {
|
|
1432
|
+
try {
|
|
1433
|
+
process.kill(pid, 0);
|
|
1434
|
+
return true;
|
|
1435
|
+
}
|
|
1436
|
+
catch (cause) {
|
|
1437
|
+
return cause.code === 'EPERM';
|
|
1438
|
+
}
|
|
1439
|
+
}
|