@parcha/agentrun-computer 0.1.0-beta.35 → 0.1.0-beta.37

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.
Files changed (148) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +423 -323
  3. package/box/Dockerfile +3 -1
  4. package/box/agentrun-archil +59 -7
  5. package/box/build-agent37.mjs +177 -0
  6. package/box/build-daytona.py +20 -4
  7. package/dist/agent37.d.ts +165 -0
  8. package/dist/agent37.js +759 -0
  9. package/dist/attach.d.ts +146 -0
  10. package/dist/attach.js +469 -0
  11. package/dist/browser.d.ts +61 -10
  12. package/dist/browser.js +125 -3
  13. package/dist/browserbase.d.ts +46 -23
  14. package/dist/browserbase.js +162 -17
  15. package/dist/chrome.d.ts +3 -4
  16. package/dist/chrome.js +6 -11
  17. package/dist/client.d.ts +33 -1
  18. package/dist/client.js +53 -0
  19. package/dist/computerd-linux-amd64 +0 -0
  20. package/dist/computerd-linux-arm64 +0 -0
  21. package/dist/conformance/agent37.d.ts +96 -0
  22. package/dist/conformance/agent37.js +154 -0
  23. package/dist/conformance/cases/apps.d.ts +5 -0
  24. package/dist/conformance/cases/apps.js +160 -73
  25. package/dist/conformance/cases/health.js +14 -0
  26. package/dist/conformance/cases/index.js +2 -0
  27. package/dist/conformance/cases/provider.js +27 -1
  28. package/dist/conformance/cases/screen.d.ts +3 -0
  29. package/dist/conformance/cases/screen.js +18 -0
  30. package/dist/conformance/cases/settings.d.ts +29 -23
  31. package/dist/conformance/cases/settings.js +76 -58
  32. package/dist/conformance/cases/touch.js +19 -17
  33. package/dist/conformance/cases/ui.d.ts +2 -0
  34. package/dist/conformance/cases/ui.js +475 -0
  35. package/dist/conformance/cli.d.ts +9 -0
  36. package/dist/conformance/cli.js +28 -3
  37. package/dist/conformance/daytona.d.ts +4 -0
  38. package/dist/conformance/daytona.js +5 -0
  39. package/dist/conformance/e2b.d.ts +6 -0
  40. package/dist/conformance/e2b.js +9 -2
  41. package/dist/conformance/fixture.d.ts +1 -1
  42. package/dist/conformance/fixture.js +25 -1
  43. package/dist/conformance/modal.d.ts +17 -13
  44. package/dist/conformance/modal.js +18 -9
  45. package/dist/conformance/orgo.d.ts +3 -3
  46. package/dist/conformance/orgo.js +6 -8
  47. package/dist/conformance/phone-harness.d.ts +6 -2
  48. package/dist/conformance/phone-harness.js +21 -4
  49. package/dist/conformance/report.js +1 -1
  50. package/dist/conformance/runner.js +23 -4
  51. package/dist/conformance/sweep.d.ts +50 -0
  52. package/dist/conformance/sweep.js +187 -0
  53. package/dist/conformance/types.d.ts +11 -3
  54. package/dist/conformance/ui-fixture.d.ts +56 -0
  55. package/dist/conformance/ui-fixture.js +43 -0
  56. package/dist/create-requests.d.ts +51 -0
  57. package/dist/create-requests.js +121 -0
  58. package/dist/daytona.d.ts +15 -5
  59. package/dist/daytona.js +58 -38
  60. package/dist/descriptor.d.ts +29 -2
  61. package/dist/descriptor.js +13 -0
  62. package/dist/descriptors/agent37.d.ts +41 -0
  63. package/dist/descriptors/agent37.js +28 -0
  64. package/dist/descriptors/browserbase.d.ts +1 -0
  65. package/dist/descriptors/browserbase.js +2 -0
  66. package/dist/descriptors/daytona.d.ts +23 -2
  67. package/dist/descriptors/daytona.js +34 -2
  68. package/dist/descriptors/index.d.ts +66 -3
  69. package/dist/descriptors/index.js +5 -3
  70. package/dist/descriptors/kernel.d.ts +1 -0
  71. package/dist/descriptors/kernel.js +2 -0
  72. package/dist/descriptors/modal.d.ts +4 -0
  73. package/dist/descriptors/modal.js +11 -1
  74. package/dist/descriptors/orgo.d.ts +13 -1
  75. package/dist/descriptors/orgo.js +9 -3
  76. package/dist/descriptors/phone-harness.d.ts +6 -1
  77. package/dist/descriptors/phone-harness.js +5 -2
  78. package/dist/docker/egress.d.ts +4 -3
  79. package/dist/docker/egress.js +7 -6
  80. package/dist/docker.d.ts +7 -4
  81. package/dist/docker.js +278 -34
  82. package/dist/e2b.d.ts +9 -165
  83. package/dist/e2b.js +282 -1342
  84. package/dist/fake-ui-driver.d.ts +97 -0
  85. package/dist/fake-ui-driver.js +717 -0
  86. package/dist/host.d.ts +182 -0
  87. package/dist/host.js +1 -0
  88. package/dist/hosted/process.d.ts +67 -0
  89. package/dist/hosted/process.js +228 -0
  90. package/dist/hosted/provider.d.ts +146 -0
  91. package/dist/hosted/provider.js +1364 -0
  92. package/dist/hosted/scripts.d.ts +76 -0
  93. package/dist/{child.js → hosted/scripts.js} +93 -12
  94. package/dist/index.d.ts +11 -7
  95. package/dist/index.js +10 -7
  96. package/dist/janitor.d.ts +5 -4
  97. package/dist/janitor.js +1 -1
  98. package/dist/kernel.d.ts +17 -27
  99. package/dist/kernel.js +94 -18
  100. package/dist/kinds.d.ts +17 -5
  101. package/dist/kinds.js +20 -4
  102. package/dist/labels.d.ts +10 -2
  103. package/dist/labels.js +30 -7
  104. package/dist/local-chrome.d.ts +5 -5
  105. package/dist/local-chrome.js +10 -5
  106. package/dist/modal.d.ts +23 -181
  107. package/dist/modal.js +273 -1232
  108. package/dist/mount-archil.d.ts +25 -3
  109. package/dist/mount-archil.js +39 -8
  110. package/dist/orgo-channel.d.ts +3 -2
  111. package/dist/orgo-channel.js +5 -2
  112. package/dist/orgo-desktop.d.ts +23 -9
  113. package/dist/orgo-desktop.js +328 -66
  114. package/dist/orgo-names.d.ts +129 -3
  115. package/dist/orgo-names.js +211 -8
  116. package/dist/orgo-workspaces.d.ts +47 -0
  117. package/dist/orgo-workspaces.js +94 -0
  118. package/dist/orgo.d.ts +27 -10
  119. package/dist/orgo.js +411 -81
  120. package/dist/phone-harness.d.ts +31 -21
  121. package/dist/phone-harness.js +510 -681
  122. package/dist/png.d.ts +4 -0
  123. package/dist/png.js +27 -0
  124. package/dist/protocol.d.ts +338 -30
  125. package/dist/protocol.js +96 -3
  126. package/dist/provider.d.ts +97 -7
  127. package/dist/provider.js +24 -3
  128. package/dist/result.d.ts +1 -1
  129. package/dist/surface/api.d.ts +248 -0
  130. package/dist/surface/api.js +1 -0
  131. package/dist/surface/core.d.ts +42 -0
  132. package/dist/surface/core.js +393 -0
  133. package/dist/surface/index.d.ts +5 -0
  134. package/dist/surface/index.js +3 -0
  135. package/dist/surface/outline.d.ts +8 -0
  136. package/dist/surface/outline.js +50 -0
  137. package/dist/surface/script.d.ts +10 -0
  138. package/dist/surface/script.js +92 -0
  139. package/dist/ui-engine.d.ts +114 -0
  140. package/dist/ui-engine.js +798 -0
  141. package/package.json +17 -1
  142. package/dist/child.d.ts +0 -42
  143. package/dist/conformance/e2b-diagnose.d.ts +0 -16
  144. package/dist/conformance/e2b-diagnose.js +0 -61
  145. package/dist/conformance/e2b-sweep.d.ts +0 -18
  146. package/dist/conformance/e2b-sweep.js +0 -132
  147. package/dist/conformance/modal-sweep.d.ts +0 -22
  148. package/dist/conformance/modal-sweep.js +0 -213
@@ -0,0 +1,717 @@
1
+ // A fake ui driver: scripted apps answered over the wire, with no Mac and no phone. It speaks protocol 0.2's hello,
2
+ // ping, apps and ui groups as JSON-RPC lines (the stdio binding's framing), and runs the ui group through UiEngine, so
3
+ // it keeps every rule a real driver keeps: refs that survive while their element exists, points refused as stale when
4
+ // the window changed under them, an act that settles before it answers, and expect polled until it holds.
5
+ //
6
+ // const { client, hello, driver } = await fakeUiConnection(); // in process, over a real line stream
7
+ // runConformance(fakeUiProvider(), { image: "fake-ui", only: ["ui"] }) // as a provider, each connection its own refs
8
+ // node packages/computer/dist/fake-ui-driver.js [apps.json] // the same driver on stdin and stdout
9
+ //
10
+ // Its default app is the ui fixture (conformance/ui-fixture.ts). Pass apps of your own to script others.
11
+ import { readFileSync } from "node:fs";
12
+ import { PassThrough } from "node:stream";
13
+ import { crc32, deflateSync } from "node:zlib";
14
+ import { socketStreams } from "./attach.js";
15
+ import { DaemonClient } from "./client.js";
16
+ import { UI_FIXTURE } from "./conformance/ui-fixture.js";
17
+ import { isCommand } from "./entry.js";
18
+ import { CANCEL_METHOD, JSONRPC_CODES, LAUNCH_WINDOW_MS, MAX_LINE_BYTES, PROTOCOL_VERSION, } from "./protocol.js";
19
+ import { CreateRequests, endedWords, otherSpecWords, specDiffer } from "./create-requests.js";
20
+ import { checkLifetime, kindRefusals } from "./provider.js";
21
+ import { fail, ok } from "./result.js";
22
+ import { featureOff, UiEngine } from "./ui-engine.js";
23
+ export { NEXT_ANIMATE_MS, NEXT_MS, SAVED_MS, UI_FIXTURE } from "./conformance/ui-fixture.js";
24
+ const SCREEN = { width: 1440, height: 900, scale: 2 };
25
+ /** The methods the fake answers; any other is method-not-found on the wire. */
26
+ export const FAKE_UI_METHODS = new Set(["hello", "ping", "apps.list", "apps.launch", "apps.terminate", "ui.observe", "ui.act"]);
27
+ /** Error kinds as JSON-RPC codes (wire.md, Errors). */
28
+ const codeOf = (kind) => kind === "invalid" ? JSONRPC_CODES.invalidParams : kind === "aborted" ? JSONRPC_CODES.requestCancelled : JSONRPC_CODES.server;
29
+ /** A PNG of one colour, width x height: enough for a caller to decode its size. */
30
+ function solidPng(width, height, [r, g, b]) {
31
+ const row = Buffer.alloc(1 + width * 3);
32
+ for (let x = 0; x < width; x++)
33
+ row.set([r, g, b], 1 + x * 3);
34
+ const raw = Buffer.concat(Array.from({ length: height }, () => row));
35
+ const chunk = (type, data) => {
36
+ const length = Buffer.alloc(4);
37
+ length.writeUInt32BE(data.length);
38
+ const typed = Buffer.concat([Buffer.from(type, "latin1"), data]);
39
+ const crc = Buffer.alloc(4);
40
+ crc.writeUInt32BE(crc32(typed) >>> 0);
41
+ return Buffer.concat([length, typed, crc]);
42
+ };
43
+ const ihdr = Buffer.alloc(13);
44
+ ihdr.writeUInt32BE(width, 0);
45
+ ihdr.writeUInt32BE(height, 4);
46
+ ihdr.set([8, 2, 0, 0, 0], 8);
47
+ return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", ihdr), chunk("IDAT", deflateSync(raw)), chunk("IEND", Buffer.alloc(0))]);
48
+ }
49
+ /** A colour for a screen's name, so two screens' images differ. */
50
+ const colourOf = (name) => {
51
+ let hash = 0;
52
+ for (const char of name)
53
+ hash = (hash * 31 + char.charCodeAt(0)) >>> 0;
54
+ return [hash & 0xff, (hash >> 8) & 0xff, (hash >> 16) & 0xff];
55
+ };
56
+ /** The scripted apps, and the protocol methods they answer. */
57
+ export class FakeUiDriver {
58
+ apps;
59
+ os;
60
+ kind;
61
+ groups;
62
+ /** Every method called, in order, with its params: what a test asserts reached the computer. */
63
+ calls = [];
64
+ #features;
65
+ #quietMs;
66
+ #blind;
67
+ #windowAfterMs;
68
+ #blink;
69
+ #running = new Map();
70
+ #front;
71
+ #frames = 0;
72
+ constructor(options = {}) {
73
+ const apps = options.apps ?? [UI_FIXTURE];
74
+ this.apps = new Map(apps.map((app) => [app.id, app]));
75
+ this.os = options.os ?? "macos";
76
+ this.kind = options.kind ?? "desktop";
77
+ this.groups = options.groups ?? ["apps", "ui"];
78
+ const touch = this.kind === "android" || this.kind === "ios";
79
+ this.#features = {
80
+ "apps.background": touch ? { off: "an app a phone opens comes to the front" } : true,
81
+ "ui.tree": true,
82
+ "ui.image": true,
83
+ "ui.background": true,
84
+ "ui.foreground": true,
85
+ "ui.nav": touch ? true : { off: "a desktop has no system back, home or app switch" },
86
+ ...options.features,
87
+ };
88
+ this.#quietMs = options.quietMs ?? 50;
89
+ this.#blind = options.blindBackground ?? false;
90
+ this.#windowAfterMs = options.windowAfterMs ?? 0;
91
+ this.#blink = options.blink ?? false;
92
+ }
93
+ /** Whether the app runs with no window left: a press closed its last one (UiSource.closed). */
94
+ async closed(app) {
95
+ return this.#running.get(app)?.windows.length === 0;
96
+ }
97
+ /** A connection's own ui engine: its refs and states are that connection's alone (wire.md, The ui group). */
98
+ engine() {
99
+ return new UiEngine(this, { quietMs: this.#quietMs, pollMs: 20 });
100
+ }
101
+ hello() {
102
+ return { protocol: PROTOCOL_VERSION, version: "fake", os: this.os, kind: this.kind, arch: "arm64", groups: [...this.groups], screen: SCREEN, osVersion: this.os === "android" ? "15 (API 35)" : "26.1 (25B78)", features: this.#features, device: { maker: "AgentRun", model: "Fake ui driver" } };
103
+ }
104
+ /** The screen an app's window in front shows now, by its name; undefined when it is not running or has no window. */
105
+ screenOf(app) {
106
+ return this.#running.get(app)?.windows.at(-1)?.screen;
107
+ }
108
+ /** Moves an app's window in front, or changes its size (points): a point read before a size change is then stale. */
109
+ place(app, bounds) {
110
+ const win = this.#running.get(app)?.windows.at(-1);
111
+ if (win !== undefined)
112
+ win.bounds = bounds;
113
+ }
114
+ /** Ends every app, and every effect its windows had pending. */
115
+ close() {
116
+ for (const state of this.#running.values())
117
+ this.#end(state);
118
+ this.#running.clear();
119
+ this.#front = undefined;
120
+ }
121
+ /** Ends an app's windows: each one's pending effects are cancelled. */
122
+ #end(state) {
123
+ for (const win of [...state.windows])
124
+ this.#closeWindow(state, win);
125
+ }
126
+ /** Closes one window: its pending effects are cancelled, so a delayed press in it never lands anywhere else. */
127
+ #closeWindow(state, win) {
128
+ for (const timer of win.timers)
129
+ clearTimeout(timer);
130
+ win.timers.clear();
131
+ state.windows = state.windows.filter((one) => one !== win);
132
+ }
133
+ /** A new window of the app on a screen, in front: its checked and focused start from the script, and nothing else is shared. */
134
+ #openWindow(state, app, id, screen, bounds) {
135
+ // look() shows checked and focused from the window's state alone, never the script's flags: the state starts from them.
136
+ const scriptedWith = (flag) => Object.values(app.screens).flatMap((one) => one.elements.filter((element) => element.flags?.includes(flag)).map((element) => element.key));
137
+ const focus = app.screens[screen]?.elements.find((element) => element.flags?.includes("focused"))?.key;
138
+ const win = { id, screen, history: [], values: new Map(), checked: new Set(scriptedWith("checked")), ...(focus === undefined ? {} : { focus }), animateUntil: 0, bounds, timers: new Set() };
139
+ state.windows.push(win);
140
+ return win;
141
+ }
142
+ /** Runs effect ms from now as a pending effect of window: never once the window closed (its timers are cancelled then). */
143
+ #later(state, win, ms, effect) {
144
+ const timer = setTimeout(() => {
145
+ win.timers.delete(timer);
146
+ if (state.windows.includes(win))
147
+ effect();
148
+ }, ms);
149
+ win.timers.add(timer);
150
+ }
151
+ /** One method call on a connection, as a computer answers it; ui calls go through that connection's engine. */
152
+ async handle(engine, method, params, signal = new AbortController().signal) {
153
+ this.calls.push([method, params]);
154
+ const p = (params ?? {});
155
+ switch (method) {
156
+ case "hello":
157
+ return ok(this.hello());
158
+ case "ping":
159
+ return ok({});
160
+ case "apps.list":
161
+ return ok({ apps: [...this.apps.values()].map(({ id, name }) => ({ id, name })), foreground: this.#front ?? null });
162
+ case "apps.launch": {
163
+ const launched = this.#launch(p);
164
+ return launched.ok ? this.windowOf(p.id, signal) : launched;
165
+ }
166
+ case "apps.terminate": {
167
+ if (typeof p.id !== "string")
168
+ return fail("invalid", "apps.terminate: id is not a string");
169
+ const state = this.#running.get(p.id);
170
+ if (state !== undefined)
171
+ this.#end(state);
172
+ this.#running.delete(p.id);
173
+ if (this.#front === p.id)
174
+ this.#front = undefined;
175
+ return ok({});
176
+ }
177
+ case "ui.observe":
178
+ return engine.observe(params, signal);
179
+ case "ui.act":
180
+ return engine.act(params, signal);
181
+ default:
182
+ return fail("unsupported", `${method} is not a method this computer answers: it offers apps and ui`);
183
+ }
184
+ }
185
+ #launch(p) {
186
+ if (typeof p.id !== "string")
187
+ return fail("invalid", "apps.launch: id is not a string");
188
+ const app = this.apps.get(p.id);
189
+ if (app === undefined)
190
+ return fail("not_found", `${p.id} is not installed`);
191
+ if (p.background === true) {
192
+ const off = this.#features["apps.background"];
193
+ if (off !== true)
194
+ return fail("unsupported", `apps.launch: apps.background is off here${off === undefined ? "" : `: ${off.off}`}`);
195
+ }
196
+ if (!this.#running.has(app.id)) {
197
+ const offset = 40 * this.#running.size;
198
+ this.#running.set(app.id, { app: app.id, windows: [], windowAt: Date.now() + this.#windowAfterMs, origin: [100 + offset, 80 + offset, ...app.size], opened: 0, mains: 0 });
199
+ }
200
+ const state = this.#running.get(app.id);
201
+ // A running app with no window opens its main one, on its first screen: at launch, and again once its last one
202
+ // closed, as a Mac app does when launched.
203
+ if (state.windows.length === 0) {
204
+ state.mains += 1;
205
+ this.#openWindow(state, app, state.mains === 1 ? `${app.id}#main` : `${app.id}#main-${state.mains}`, app.start, [...state.origin]);
206
+ }
207
+ if (p.background !== true)
208
+ this.#front = app.id;
209
+ return ok({});
210
+ }
211
+ /**
212
+ * apps.launch's answer once the app it started has a window (wire.md, apps.launch): ok when it shows, timeout naming
213
+ * the app when none came within LAUNCH_WINDOW_MS. A test's driver that answers before its window overrides it.
214
+ */
215
+ async windowOf(id, signal) {
216
+ const until = Date.now() + LAUNCH_WINDOW_MS;
217
+ for (;;) {
218
+ const state = this.#running.get(id);
219
+ if (state === undefined)
220
+ return fail("not_found", `${id} ended before it showed a window`);
221
+ if (Date.now() >= state.windowAt)
222
+ return ok({});
223
+ if (Date.now() >= until)
224
+ return fail("timeout", `${this.apps.get(id)?.name ?? id} (${id}) showed no window within ${LAUNCH_WINDOW_MS / 1000} s of apps.launch`);
225
+ await new Promise((resolve) => setTimeout(resolve, Math.min(20, Math.max(1, state.windowAt - Date.now()))));
226
+ if (signal.aborted)
227
+ return fail("aborted", "apps.launch was cancelled");
228
+ }
229
+ }
230
+ // --- the ui source ---------------------------------------------------------------------------------------------
231
+ features() {
232
+ return this.#features;
233
+ }
234
+ async look(target) {
235
+ const touch = this.kind === "android" || this.kind === "ios";
236
+ // A window named alone is found in whichever running app has it, as a desktop's window list names it; a phone sees
237
+ // only the app in front.
238
+ const owner = target?.app === undefined && target?.window !== undefined && !touch ? [...this.#running].find(([, state]) => state.windows.some((one) => one.id === target.window))?.[0] : undefined;
239
+ const id = target?.app ?? owner ?? this.#front;
240
+ // A phone reads only the app in front, as its accessibility tree does: an app behind is not found.
241
+ const front = this.#front ?? "home";
242
+ if (touch && target?.app !== undefined && target.app !== front)
243
+ return fail("not_found", `${target.app} is not in front on this phone (${front} is): launch it with apps.launch first`);
244
+ if (id === undefined || (id === "home" && this.#front === undefined)) {
245
+ if (target?.window !== undefined && target.window !== "home#main")
246
+ return fail("not_found", `the home screen has no window ${target.window}; its window is home#main`);
247
+ // With no app in front a computer shows its home screen or desktop (after nav home, or terminating the app in
248
+ // front): a window to observe and settle on, as on a real one.
249
+ const [width, height] = [this.hello().screen?.width ?? 0, this.hello().screen?.height ?? 0];
250
+ return ok({ app: { id: "home", name: touch ? "Home screen" : "Desktop" }, window: { id: "home#main", bounds: [0, 0, width, height] }, elements: [], frame: "home" });
251
+ }
252
+ const state = this.#running.get(id);
253
+ const app = this.apps.get(id);
254
+ if (state === undefined || app === undefined)
255
+ return fail("not_found", `${id} is not running: launch it with apps.launch`);
256
+ if (Date.now() < state.windowAt)
257
+ return fail("not_found", `${id} is running and has no window yet`);
258
+ if (state.windows.length === 0)
259
+ return fail("not_found", `${id} is running with no window: its last one closed, and apps.launch opens it again`);
260
+ const shown = target?.window === undefined ? state.windows.at(-1) : state.windows.find((one) => one.id === target.window);
261
+ if (shown === undefined)
262
+ return fail("not_found", `${id} has no window ${target?.window}; its windows are ${state.windows.map((one) => one.id).join(", ")}`);
263
+ const screen = app.screens[shown.screen];
264
+ // Between two screens the window slides: each look shows its elements a point or two lower than the last, as a real
265
+ // transition moves them, so a settle on the tree waits it out.
266
+ const between = Date.now() < shown.animateUntil;
267
+ const slide = between ? 1 + (this.#frames % 2) : 0;
268
+ // Values, checked and focused are the window's alone (checked and focused seeded from the script when it opened):
269
+ // the scripted flags never show through, and another window's never do.
270
+ const elements = screen.elements.map(({ press: _press, enter: _enter, route: _route, counts: _counts, takesBack: _takesBack, flags: scriptedFlags, ...element }) => {
271
+ const value = shown.values.get(element.key) ?? element.value;
272
+ const flags = [...(scriptedFlags ?? []).filter((flag) => flag !== "checked" && flag !== "focused"), ...(shown.checked.has(element.key) ? ["checked"] : []), ...(shown.focus === element.key ? ["focused"] : [])];
273
+ const [x, y, w, h] = element.bounds;
274
+ return { ...element, bounds: [x, y + slide, w, h], ...(value === undefined ? {} : { value }), ...(flags.length > 0 ? { flags } : {}) };
275
+ });
276
+ return ok({
277
+ app: { id, name: app.name },
278
+ window: { id: shown.id, ...(screen.title === undefined ? {} : { title: screen.title }), bounds: shown.bounds },
279
+ elements,
280
+ // A blinking caret changes what the window draws on every look, and nothing in its tree.
281
+ frame: between ? `between:${this.#frames++}` : this.#blink && shown.focus !== undefined ? `${shown.screen}|caret:${this.#frames++ % 2}` : shown.screen,
282
+ });
283
+ }
284
+ async image(view, maxEdge) {
285
+ const [, , w, h] = view.window.bounds;
286
+ const fit = Math.min(1, maxEdge / Math.max(w, h));
287
+ const [width, height] = [Math.max(1, Math.round(w * fit)), Math.max(1, Math.round(h * fit))];
288
+ return ok({ format: "png", width, height, data: solidPng(width, height, colourOf(view.frame ?? "")).toString("base64") });
289
+ }
290
+ async run(step, { element, view, foreground }) {
291
+ const running = this.#running.get(view.app.id);
292
+ if (running === undefined) {
293
+ // The home screen or desktop: nav runs (there is nowhere further to go), anything else has nothing to land on.
294
+ if ("nav" in step)
295
+ return ok({ route: "semantic", verified: true });
296
+ return fail("unsupported", `the fake's ${view.app.name.toLowerCase()} takes no input but nav: launch an app with apps.launch`);
297
+ }
298
+ const state = running;
299
+ const app = this.apps.get(view.app.id);
300
+ // The window the step lands in, which it changes alone: a press there goes, opens or closes from it.
301
+ const win = state.windows.find((one) => one.id === view.window.id);
302
+ if (win === undefined)
303
+ return fail("stale", `${view.window.id} closed before this step ran: observe again`);
304
+ const shown = app.screens[win.screen];
305
+ const scripted = (key) => shown.elements.find((one) => one.key === key);
306
+ /** A disabled element takes no effect by any route: by its ref it is refused, by a point or the focus it is ignored. */
307
+ const disabled = (one) => one.flags?.includes("disabled") ?? false;
308
+ /** The route an input step (a pointer, typing, a key) takes, or why it may not run, in the off features' words. */
309
+ const pointer = (target) => {
310
+ const only = target?.route === "foreground";
311
+ const backgroundOff = featureOff(this.#features, "ui.background");
312
+ if (only && this.#blind && !foreground && backgroundOff === undefined)
313
+ return ok("background");
314
+ if (!only && backgroundOff === undefined)
315
+ return ok("background");
316
+ const why = only ? `${target?.name ?? "it"} takes foreground input only` : backgroundOff;
317
+ const foregroundOff = featureOff(this.#features, "ui.foreground");
318
+ if (foregroundOff !== undefined)
319
+ return fail("unsupported", `no route reaches it: ${why}, and ${foregroundOff}`);
320
+ if (!foreground)
321
+ return fail("denied", `${why}, so only the foreground route reaches it, which moves the user's pointer, and this call does not allow it: pass foreground: true`);
322
+ return ok("foreground");
323
+ };
324
+ /** A pointer step by its route: an element it reaches is pressed, and a counting one verified by its count. */
325
+ /**
326
+ * Whether input by this route has an effect on the element: a disabled control takes it and does nothing, and a
327
+ * view that takes real input only never sees input posted by another route (blindBackground lets one through).
328
+ * Every input step (a point, typing, a key) applies its effect only through this.
329
+ */
330
+ const takes = (one, route) => !disabled(one) && !(one.route === "foreground" && route !== "foreground");
331
+ const land = (hit, route, right = false) => {
332
+ if (hit === undefined || right || !takes(hit, route))
333
+ return { route, verified: false };
334
+ this.#press(state, win, hit);
335
+ if (hit.counts !== true)
336
+ return { route, verified: false };
337
+ win.values.set(hit.key, String(Number(win.values.get(hit.key) ?? hit.value ?? "0") + 1));
338
+ return { route, verified: true };
339
+ };
340
+ const target = scripted(element?.key);
341
+ if (target !== undefined && disabled(target))
342
+ return fail("refused", `${target.name ?? "the element"} is disabled: a step on it does nothing, so none ran`);
343
+ if ("press" in step || ("perform" in step && step.action === target?.actions?.[0])) {
344
+ if (target?.route === "foreground") {
345
+ const route = pointer(target);
346
+ return route.ok ? ok(land(target, route.value)) : route;
347
+ }
348
+ this.#press(state, win, target);
349
+ return ok({ route: "semantic", verified: this.#shownAtOnce(target) });
350
+ }
351
+ if ("perform" in step) {
352
+ if (!(target?.actions ?? []).includes(step.action))
353
+ return fail("unsupported", `${target?.name ?? "the element"} has no action ${step.action}`);
354
+ return ok({ route: "semantic", verified: false });
355
+ }
356
+ if ("set" in step) {
357
+ const scriptedTarget = target;
358
+ const toggle = scriptedTarget.role === "switch" || scriptedTarget.role === "checkbox";
359
+ if (toggle && step.value !== "on" && step.value !== "off")
360
+ return fail("invalid", `a ${scriptedTarget.role} is set to "on" or "off", not ${JSON.stringify(step.value)}`);
361
+ if (!toggle && scriptedTarget.role !== "textbox" && scriptedTarget.role !== "searchbox")
362
+ return fail("unsupported", `a ${scriptedTarget.role} has no value to set`);
363
+ // A view that takes real input only is set by real input, as a press is: never by the semantic route.
364
+ const via = scriptedTarget.route === "foreground" ? pointer(scriptedTarget) : ok("semantic");
365
+ if (!via.ok)
366
+ return via;
367
+ if (!takes(scriptedTarget, via.value))
368
+ return ok({ route: via.value, verified: false });
369
+ if (toggle && step.value === "on")
370
+ win.checked.add(scriptedTarget.key);
371
+ else if (toggle)
372
+ win.checked.delete(scriptedTarget.key);
373
+ else {
374
+ const was = win.values.get(scriptedTarget.key);
375
+ win.values.set(scriptedTarget.key, step.value);
376
+ // An app that refuses the value takes it back a moment later: the set ran, and does not hold (SET_HOLD_MS).
377
+ if (scriptedTarget.takesBack !== undefined) {
378
+ this.#later(state, win, scriptedTarget.takesBack, () => {
379
+ if (was === undefined)
380
+ win.values.delete(scriptedTarget.key);
381
+ else
382
+ win.values.set(scriptedTarget.key, was);
383
+ });
384
+ }
385
+ }
386
+ return ok({ route: via.value, verified: true });
387
+ }
388
+ if ("click" in step) {
389
+ // A point lands on what the app draws there, whether or not the view carries its elements (ui.tree off).
390
+ const hit = target ?? (Array.isArray(step.click) ? shown.elements.findLast((one) => this.#inside(one.bounds, step.click)) : undefined);
391
+ const route = pointer(hit);
392
+ if (!route.ok)
393
+ return route;
394
+ // A double or triple click lands as many times; a right click once.
395
+ let landed = land(hit, route.value, step.button === "right");
396
+ for (let more = step.button === "right" ? 0 : (step.count ?? 1) - 1; more > 0; more--)
397
+ landed = land(hit, route.value);
398
+ return ok(landed);
399
+ }
400
+ if ("type" in step) {
401
+ const field = (one) => one.role === "textbox" || one.role === "searchbox";
402
+ if (target !== undefined && !field(target))
403
+ return fail("refused", `${step.into} is a ${target.role}, not a text field: type into a field`);
404
+ const into = target ?? scripted(win.focus);
405
+ const route = pointer(into);
406
+ if (!route.ok)
407
+ return route;
408
+ if (into === undefined || !takes(into, route.value) || !field(into))
409
+ return ok({ route: route.value, verified: false });
410
+ // A field named by its ref is focused first, as a tap does, which runs what pressing it does: a field whose
411
+ // press opens another screen leaves the focus there, and nothing is typed.
412
+ if (target !== undefined) {
413
+ this.#press(state, win, target);
414
+ if (win.focus !== target.key)
415
+ return fail("refused", `${step.into} did not take focus: nothing typed`);
416
+ }
417
+ win.values.set(into.key, `${win.values.get(into.key) ?? into.value ?? ""}${step.type}`);
418
+ return ok({ route: route.value, verified: true });
419
+ }
420
+ if ("key" in step) {
421
+ const focused = scripted(win.focus);
422
+ const route = pointer(focused);
423
+ if (!route.ok)
424
+ return route;
425
+ if (step.key === "enter" && focused?.enter !== undefined && takes(focused, route.value))
426
+ this.#apply(state, win, focused.enter);
427
+ return ok({ route: route.value, verified: false });
428
+ }
429
+ if ("nav" in step) {
430
+ if (step.nav === "back") {
431
+ const back = win.history.pop();
432
+ if (back !== undefined)
433
+ win.screen = back;
434
+ }
435
+ else if (step.nav === "home")
436
+ this.#front = undefined;
437
+ return ok({ route: "semantic", verified: true });
438
+ }
439
+ if ("scroll" in step)
440
+ return ok({ route: "semantic", verified: false });
441
+ const route = pointer(undefined);
442
+ return route.ok ? ok({ route: route.value, verified: false }) : route;
443
+ }
444
+ #inside([x, y, w, h], [px, py]) {
445
+ return px >= x && py >= y && px < x + w && py < y + h;
446
+ }
447
+ /** Whether a press's effect is there to read back as soon as it ran: a toggle, a focus, or a screen opened at once. */
448
+ #shownAtOnce(element) {
449
+ if (["switch", "checkbox", "textbox", "searchbox"].includes(element.role))
450
+ return true;
451
+ return element.press !== undefined && (element.press.after ?? 0) === 0;
452
+ }
453
+ #press(state, win, element) {
454
+ if (element.role === "switch" || element.role === "checkbox") {
455
+ if (win.checked.has(element.key))
456
+ win.checked.delete(element.key);
457
+ else
458
+ win.checked.add(element.key);
459
+ }
460
+ if (element.role === "textbox" || element.role === "searchbox")
461
+ win.focus = element.key;
462
+ if (element.press !== undefined)
463
+ this.#apply(state, win, element.press);
464
+ }
465
+ /**
466
+ * A press's effect, from the window it landed in: go to a screen in that window, open another window, or close that
467
+ * one. A delayed effect is that window's pending effect: it never lands once the window closed.
468
+ */
469
+ #apply(state, win, effect) {
470
+ const go = () => {
471
+ if (effect.close === true)
472
+ return this.#closeWindow(state, win);
473
+ if (effect.open !== undefined) {
474
+ state.opened += 1;
475
+ const [x, y, w, h] = state.origin;
476
+ const app = this.apps.get(state.app);
477
+ this.#openWindow(state, app, `${state.app}#${state.opened + 1}`, effect.open, [x + 30 * state.opened, y + 30 * state.opened, w, h]);
478
+ return;
479
+ }
480
+ if (effect.go === undefined)
481
+ return;
482
+ win.history.push(win.screen);
483
+ win.screen = effect.go;
484
+ win.focus = undefined;
485
+ win.animateUntil = Date.now() + (effect.animateMs ?? 0);
486
+ };
487
+ if (!effect.after)
488
+ return go();
489
+ this.#later(state, win, effect.after, go);
490
+ }
491
+ }
492
+ /**
493
+ * Serves a driver's methods as JSON-RPC lines from input to output (the stdio binding's framing): requests run at once,
494
+ * replies in any order, $/cancelRequest aborts one, a line over the limit or not JSON gets its error reply.
495
+ */
496
+ export function serveUiLines(driver, input, output) {
497
+ const engine = driver.engine();
498
+ const running = new Map();
499
+ let buffered = "";
500
+ /** A line already over the limit: dropped up to its newline, then answered once. */
501
+ let overLong = false;
502
+ const reply = (message) => {
503
+ if (output.writable)
504
+ output.write(`${JSON.stringify(message)}\n`);
505
+ };
506
+ const error = (id, kind, message, code = codeOf(kind)) => reply({ jsonrpc: "2.0", id: id ?? null, error: { code, message, data: { kind } } });
507
+ const line = async (text) => {
508
+ if (Buffer.byteLength(text) > MAX_LINE_BYTES)
509
+ return error(null, "limit", "the request is over the line limit", JSONRPC_CODES.invalidRequest);
510
+ let parsed;
511
+ try {
512
+ parsed = JSON.parse(text);
513
+ }
514
+ catch {
515
+ return error(null, "invalid", "the line is not JSON", JSONRPC_CODES.parse);
516
+ }
517
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
518
+ return error(null, "invalid", "a request is a JSON object", JSONRPC_CODES.invalidRequest);
519
+ const message = parsed;
520
+ if (message.method === CANCEL_METHOD) {
521
+ running.get(message.params?.id ?? "")?.abort();
522
+ return;
523
+ }
524
+ if (typeof message.method !== "string" || message.id === undefined)
525
+ return error(message.id, "invalid", "a request has a method and an id", JSONRPC_CODES.invalidRequest);
526
+ const controller = new AbortController();
527
+ running.set(message.id, controller);
528
+ try {
529
+ const answered = await driver.handle(engine, message.method, message.params, controller.signal);
530
+ if (answered.ok)
531
+ return reply({ jsonrpc: "2.0", id: message.id, result: answered.value });
532
+ const kind = answered.error.code;
533
+ const code = FAKE_UI_METHODS.has(message.method) ? codeOf(kind) : JSONRPC_CODES.methodNotFound;
534
+ return error(message.id, kind, answered.error.message, code);
535
+ }
536
+ finally {
537
+ running.delete(message.id);
538
+ }
539
+ };
540
+ input.setEncoding("utf8");
541
+ input.on("data", (chunk) => {
542
+ buffered += chunk;
543
+ for (let at = buffered.indexOf("\n"); at >= 0; at = buffered.indexOf("\n")) {
544
+ const text = buffered.slice(0, at).replace(/\r$/, "");
545
+ buffered = buffered.slice(at + 1);
546
+ if (overLong) {
547
+ overLong = false;
548
+ error(null, "limit", "the request is over the line limit", JSONRPC_CODES.invalidRequest);
549
+ }
550
+ else if (text.trim() !== "")
551
+ void line(text);
552
+ }
553
+ // A character is a byte or more, so a buffer longer than the limit in characters is over it in bytes.
554
+ if (buffered.length > MAX_LINE_BYTES) {
555
+ overLong = true;
556
+ buffered = "";
557
+ }
558
+ });
559
+ input.on("end", () => {
560
+ for (const controller of running.values())
561
+ controller.abort();
562
+ output.end();
563
+ });
564
+ }
565
+ /** Serves a driver over an attach socket (spec/computer/attach.md): the driver's end of the binding, as a driver that dialed out. */
566
+ export function serveUiSocket(driver, socket) {
567
+ const { readable, writable } = socketStreams(socket);
568
+ serveUiLines(driver, readable, writable);
569
+ }
570
+ /** A connection over a real line stream to a driver: its client after hello. Closing it leaves the driver's apps running. */
571
+ export async function connectUi(driver) {
572
+ const requests = new PassThrough();
573
+ const replies = new PassThrough();
574
+ serveUiLines(driver, requests, replies);
575
+ const client = new DaemonClient({ readable: replies, writable: requests });
576
+ const hello = await client.call("hello", { client: "fake-ui-driver" });
577
+ if (!hello.ok)
578
+ return hello;
579
+ return ok({ client, hello: hello.value, close: async () => client.close() });
580
+ }
581
+ /** A fake ui computer of its own in this process: its connection (after hello), and its driver, ended on close. */
582
+ export async function fakeUiConnection(options = {}) {
583
+ const driver = new FakeUiDriver(options);
584
+ const connected = await connectUi(driver);
585
+ if (!connected.ok)
586
+ throw new Error(`the fake ui driver's hello failed: ${connected.error.message}`);
587
+ return {
588
+ ...connected.value,
589
+ driver,
590
+ close: async () => {
591
+ await connected.value.close();
592
+ driver.close();
593
+ },
594
+ };
595
+ }
596
+ /**
597
+ * A provider whose computers are fake ui drivers in this process, for the conformance suite and for tools that need a
598
+ * provider: the options' groups (apps and ui by default), no daemon, deleted on release. Every computer has the options' apps and features; `make`
599
+ * builds each one's driver (a subclass, for a test of what a broken driver fails).
600
+ */
601
+ export function fakeUiProvider(options = {}, make = (given) => new FakeUiDriver(given)) {
602
+ const drivers = new Map();
603
+ const labelsOf = new Map();
604
+ const deadlines = new Map();
605
+ /** Every computer a request made, ended or not: a request id makes one computer, ever. */
606
+ const made = new Set();
607
+ /** The request id checked, and a create of a request in flight shared (create-requests.ts). */
608
+ const requests = new CreateRequests();
609
+ const capabilities = {
610
+ kind: options.kind ?? "desktop",
611
+ lifetime: "vendor",
612
+ network: ["none", "open"],
613
+ isolation: "machine",
614
+ os: options.os ?? "macos",
615
+ daemon: "none",
616
+ groups: options.groups ?? ["apps", "ui"],
617
+ maxLifetimeMs: 60 * 60_000,
618
+ release: ["delete"],
619
+ };
620
+ const networks = new Map();
621
+ /** The spec each computer was made with, kept past its end: a retry of its request is held to all of it. */
622
+ const specs = new Map();
623
+ const missing = (id) => fail("not_found", `no fake ui computer ${id}`);
624
+ const end = (id) => {
625
+ drivers.get(id)?.close();
626
+ drivers.delete(id);
627
+ labelsOf.delete(id);
628
+ deadlines.delete(id);
629
+ networks.delete(id);
630
+ };
631
+ /** Whether the computer is there: one past its deadline is ended then (its lifetime is the vendor's), and is not. */
632
+ const live = (id) => {
633
+ const deadline = deadlines.get(id);
634
+ if (deadline !== undefined && deadline.getTime() <= Date.now())
635
+ end(id);
636
+ return drivers.has(id);
637
+ };
638
+ const allowRefused = "a fake ui computer's network is none or open, never an allowlist";
639
+ return {
640
+ id: "fake-ui",
641
+ version: "fake",
642
+ drivers,
643
+ capabilities: () => capabilities,
644
+ check: (spec) => [
645
+ ...kindRefusals(capabilities),
646
+ ...checkLifetime(spec.lifetimeMs, capabilities),
647
+ ...(spec.network === "none" || spec.network === "open" ? [] : [{ field: "network", message: typeof spec.network === "object" ? allowRefused : `network is "none" or "open", not ${JSON.stringify(spec.network)}` }]),
648
+ ],
649
+ async create(spec, context) {
650
+ const refusals = this.check(spec);
651
+ // One computer per request id, named for it (provider.md, Idempotent create): what the fake's vendor holds is
652
+ // every computer a request made, ended or not.
653
+ return requests.create(spec, context, {
654
+ refuse: fail,
655
+ ...(refusals.length > 0 ? { refused: refusals.map((refusal) => refusal.message).join("; ") } : {}),
656
+ make: async (id) => {
657
+ if (made.has(id)) {
658
+ if (!live(id))
659
+ return fail("exists", endedWords(id));
660
+ // The fake's vendor holds the whole spec a computer was made with: a retry is held to all of it.
661
+ const differ = specDiffer(spec, specs.get(id), { seen: "read back" });
662
+ if (differ.length > 0)
663
+ return fail("exists", otherSpecWords(id, "was made", differ));
664
+ return ok({ id, name: id });
665
+ }
666
+ made.add(id);
667
+ specs.set(id, spec);
668
+ drivers.set(id, make(options));
669
+ labelsOf.set(id, { ...spec.labels });
670
+ deadlines.set(id, new Date(Date.now() + (spec.lifetimeMs ?? capabilities.maxLifetimeMs)));
671
+ networks.set(id, spec.network);
672
+ return ok({ id, name: id });
673
+ },
674
+ });
675
+ },
676
+ async attach(ref) {
677
+ const id = "id" in ref ? ref.id : [...labelsOf].find(([found, labels]) => live(found) && Object.entries(ref.labels).every(([key, value]) => labels[key] === value))?.[0];
678
+ if (id === undefined || !live(id))
679
+ return missing("id" in ref ? ref.id : JSON.stringify(ref.labels));
680
+ return ok({ id, name: id, spec: { image: "fake-ui", user: "501", network: networks.get(id) ?? "none", kind: capabilities.kind, deadline: deadlines.get(id) } });
681
+ },
682
+ async list(labels) {
683
+ const matching = [...labelsOf].filter(([id, have]) => live(id) && Object.entries(labels).every(([key, value]) => have[key] === value));
684
+ return ok(matching.map(([id, have]) => ({ ref: { id, name: id }, labels: have, deadline: deadlines.get(id), state: "running", network: networks.get(id) ?? "none" })));
685
+ },
686
+ async network(ref, policy) {
687
+ if (!live(ref.id))
688
+ return missing(ref.id);
689
+ const now = networks.get(ref.id) ?? "none";
690
+ if (policy !== undefined && policy !== "none" && policy !== "open")
691
+ return fail("refused", allowRefused);
692
+ // A remote computer's network is fixed at create: asking for the one it has is ok, a change is refused.
693
+ if (policy !== undefined && policy !== now)
694
+ return fail("refused", `${ref.id}'s network is ${now}, fixed when it was made: create a computer with network ${policy}`);
695
+ return ok(now);
696
+ },
697
+ async connect(ref) {
698
+ if (!live(ref.id))
699
+ return missing(ref.id);
700
+ return connectUi(drivers.get(ref.id));
701
+ },
702
+ async release(ref, how) {
703
+ if (how === "stop")
704
+ return fail("unsupported", "a fake ui computer is deleted on release, never stopped");
705
+ end(ref.id);
706
+ return ok(undefined);
707
+ },
708
+ };
709
+ }
710
+ // node dist/fake-ui-driver.js [apps.json]: the driver on stdin and stdout, its apps from a JSON file of FakeApp[].
711
+ if (isCommand(import.meta)) {
712
+ const file = process.argv[2];
713
+ const apps = file === undefined ? undefined : JSON.parse(readFileSync(file, "utf8"));
714
+ const driver = new FakeUiDriver(apps === undefined ? {} : { apps });
715
+ serveUiLines(driver, process.stdin, process.stdout);
716
+ process.stdin.on("end", () => driver.close());
717
+ }