Open History to see the last commit
1import { expect, it } from "@effect/vitest";
2import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import * as Net from "@t3tools/shared/Net";
5import * as Deferred from "effect/Deferred";
6import * as Effect from "effect/Effect";
7import * as Fiber from "effect/Fiber";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as PlatformError from "effect/PlatformError";
11import * as Sink from "effect/Sink";
12import * as Stream from "effect/Stream";
13import * as HttpClient from "effect/http/HttpClient";
14import * as HttpClientResponse from "effect/http/HttpClientResponse";
15import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
16import * as TestClock from "effect/testing/TestClock";
17import * as ServerConfig from "../config.ts";
18import * as DeviceHost from "./DeviceHost.ts";
19import * as SshDeviceHost from "./SshDeviceHost.ts";
20
21it.effect("preserves installed status after probes and cleans failed agent activation", () =>
22 Effect.gen(function* () {
23 const fs = yield* FileSystem.FileSystem;
24 const home = yield* fs.makeTempDirectoryScoped();
25 const modes: string[] = [];
26 const owners: string[] = [];
27 const tunnelArgs: string[][] = [];
28 const tunnelStdins: unknown[] = [];
29 const commandArgs: string[][] = [];
30 let forwards = 0;
31 let failForward = true;
32 let rejectConfig = true;
33 const releases: Array<string | undefined> = [];
34 const spawner = ChildProcessSpawner.make((command) =>
35 Effect.gen(function* () {
36 if (command._tag !== "StandardCommand") return yield* Effect.die("Unexpected command");
37 const forwarding = command.args.includes("-L");
38 (forwarding ? tunnelArgs : commandArgs).push(command.args.map(String));
39 if (forwarding) tunnelStdins.push(command.options.stdin);
40 let output = "";
41 let exitCode = 0;
42 if (forwarding) {
43 if (failForward) {
44 failForward = false;
45 return yield* PlatformError.systemError({
46 _tag: "AlreadyExists",
47 module: "ChildProcess",
48 method: "spawn",
49 description: "Port already bound",
50 });
51 }
52 forwards++;
53 yield* Effect.addFinalizer(() =>
54 Effect.sync(() => {
55 forwards--;
56 }),
57 );
58 } else {
59 const stdin = command.options.stdin;
60 if (
61 !stdin ||
62 typeof stdin !== "object" ||
63 !("stream" in stdin) ||
64 !Stream.isStream(stdin.stream)
65 )
66 return yield* Effect.die("Missing script");
67 const script = yield* stdin.stream.pipe(
68 Stream.decodeText(),
69 Stream.runFold(
70 () => "",
71 (a, b) => a + b,
72 ),
73 );
74 const mode = /const mode = "([^"]+)"/.exec(script)?.[1] ?? "";
75 modes.push(mode);
76 owners.push(/const owner = "([^"]+)"/.exec(script)?.[1] ?? "");
77 output = JSON.stringify({
78 nodePath: "/node",
79 platforms: [{ platform: "ios", available: true }],
80 hubPort: 1234,
81 hubToken: "hub-token",
82 helpers: { serveSimAxSettings: null, serveSimCli: null },
83 ...(mode === "agent-start"
84 ? { daemonPort: 1235, token: "fixture", entryPath: "/agent.mjs" }
85 : {}),
86 });
87 if (mode === "") {
88 output = `${"verbose-prefix ".repeat(400)}PANIC: emulator SDK is broken\n`;
89 exitCode = 1;
90 }
91 }
92 return ChildProcessSpawner.makeHandle({
93 pid: ChildProcessSpawner.ProcessId(123),
94 stdout: Stream.make(new TextEncoder().encode(output)),
95 stderr: Stream.empty,
96 all: Stream.empty,
97 exitCode: forwarding
98 ? Effect.never
99 : Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
100 exitStatus: forwarding
101 ? Effect.never
102 : Effect.succeed({ _tag: "Exited", code: ChildProcessSpawner.ExitCode(exitCode) }),
103 isRunning: Effect.succeed(forwarding),
104 kill: () => Effect.void,
105 stdin: Sink.drain,
106 getInputFd: () => Sink.drain,
107 getOutputFd: () => Stream.empty,
108 unref: Effect.succeed(Effect.void),
109 });
110 }),
111 );
112 const host = yield* SshDeviceHost.make(
113 { kind: "ssh", id: "test", label: "Test", target: "test.example" },
114 () =>
115 rejectConfig
116 ? Effect.fail(
117 new DeviceHost.DeviceHostError({
118 hostId: "test",
119 step: "configuring agent access",
120 cause: new Error("fixture failure"),
121 }),
122 )
123 : Effect.void,
124 ).pipe(
125 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(home, home), Net.layer)),
126 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
127 Effect.provideService(
128 HttpClient.HttpClient,
129 HttpClient.make((request) =>
130 Effect.sync(() => {
131 if (!request.url.endsWith("/rpc"))
132 return HttpClientResponse.fromWeb(request, new Response("ok"));
133 releases.push(request.headers.authorization);
134 return HttpClientResponse.fromWeb(request, Response.json({ result: { ok: true } }));
135 }),
136 ),
137 ),
138 );
139 yield* host.ensureReady(() => Effect.void);
140 yield* SshDeviceHost.probe({
141 kind: "ssh",
142 id: "test",
143 label: "Test",
144 target: "test.example",
145 }).pipe(
146 Effect.provide(ServerConfig.layerTest(home, home)),
147 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
148 );
149 expect(new Set(owners).size).toBe(1);
150 expect(owners[0]).toMatch(/^[a-f0-9]{24}$/);
151 expect(forwards).toBe(1);
152 expect(modes.filter((mode) => mode === "start")).toHaveLength(2);
153 const ready = yield* host.current;
154 expect(ready).not.toBeNull();
155 if (ready) {
156 const failed = yield* ready.run("emulator", ["-list-avds"]);
157 expect(failed.code).toBe(1);
158 expect(failed.stdout).toMatch(/^\[truncated\]/);
159 expect(failed.stderr).toBe(failed.stdout.trim());
160 expect(failed.stderr).toMatch(/PANIC: emulator SDK is broken$/);
161 }
162 yield* host.platformAvailability("ios");
163 expect((yield* host.summary).hubInstalled).toBe(true);
164 const failed = yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.result);
165 expect(failed._tag).toBe("Failure");
166 expect(forwards).toBe(0);
167 expect(modes.at(-1)).toBe("stop-agent");
168 expect(yield* host.current).toBeNull();
169 rejectConfig = false;
170 yield* host.ensureAgentReady(() => Effect.void);
171 yield* host.platformAvailability("ios");
172 expect((yield* host.summary).agentDeviceInstalled).toBe(true);
173 // Close releases agent sessions through the forwarded daemon.
174 const agentReady = yield* host.current;
175 yield* agentReady!.releaseAgentSession!("t3-session", "device");
176 expect(releases).toEqual(["Bearer fixture"]);
177 yield* host.stopAgent;
178 expect(forwards).toBe(1);
179 const multiplexingOff = ["ControlMaster=no", "ControlPath=none", "ControlPersist=no"];
180 expect(tunnelArgs.length).toBeGreaterThan(0);
181 for (const args of tunnelArgs) {
182 for (const option of multiplexingOff) {
183 const index = args.indexOf(option);
184 expect(index).toBeGreaterThan(0);
185 expect(args[index - 1]).toBe("-o");
186 }
187 // The tunnel lives only as long as the server holds the write end of its stdin.
188 expect(args).not.toContain("-N");
189 expect(args.slice(args.indexOf("test.example") + 1)).toEqual([
190 "sh",
191 "-c",
192 "'exec cat >/dev/null'",
193 ]);
194 }
195 expect(tunnelStdins).toEqual(tunnelArgs.map(() => "pipe"));
196 expect(commandArgs.length).toBeGreaterThan(0);
197 for (const args of commandArgs) {
198 for (const option of multiplexingOff) expect(args).not.toContain(option);
199 }
200 yield* host.stop;
201 expect(forwards).toBe(0);
202 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
203);
204
205it.effect("releases the forward of a bootstrap interrupted before its hub answered", () =>
206 Effect.gen(function* () {
207 const fs = yield* FileSystem.FileSystem;
208 const home = yield* fs.makeTempDirectoryScoped();
209 const probing = yield* Deferred.make<void>();
210 let holdReadiness = true;
211 let forwards = 0;
212 const spawner = ChildProcessSpawner.make((command) =>
213 Effect.gen(function* () {
214 const forwarding = command._tag === "StandardCommand" && command.args.includes("-L");
215 if (forwarding) {
216 forwards++;
217 yield* Effect.addFinalizer(() =>
218 Effect.sync(() => {
219 forwards--;
220 }),
221 );
222 }
223 const output = forwarding
224 ? ""
225 : JSON.stringify({
226 nodePath: "/node",
227 platforms: [{ platform: "ios", available: true }],
228 hubPort: 1234,
229 hubToken: "hub-token",
230 helpers: { serveSimAxSettings: null, serveSimCli: null },
231 });
232 return ChildProcessSpawner.makeHandle({
233 pid: ChildProcessSpawner.ProcessId(123),
234 stdout: Stream.make(new TextEncoder().encode(output)),
235 stderr: Stream.empty,
236 all: Stream.empty,
237 exitCode: forwarding ? Effect.never : Effect.succeed(ChildProcessSpawner.ExitCode(0)),
238 exitStatus: forwarding
239 ? Effect.never
240 : Effect.succeed({ _tag: "Exited", code: ChildProcessSpawner.ExitCode(0) }),
241 isRunning: Effect.succeed(forwarding),
242 kill: () => Effect.void,
243 stdin: Sink.drain,
244 getInputFd: () => Sink.drain,
245 getOutputFd: () => Stream.empty,
246 unref: Effect.succeed(Effect.void),
247 });
248 }),
249 );
250 const publishing = yield* Deferred.make<void>();
251 let holdReadyStatus = false;
252 const host = yield* SshDeviceHost.make(
253 {
254 kind: "ssh",
255 id: "test",
256 label: "Test",
257 target: "test.example",
258 },
259 undefined,
260 (status) =>
261 status === "ready" && holdReadyStatus
262 ? Deferred.succeed(publishing, undefined).pipe(Effect.andThen(Effect.never))
263 : Effect.void,
264 ).pipe(
265 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(home, home), Net.layer)),
266 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
267 Effect.provideService(
268 HttpClient.HttpClient,
269 HttpClient.make((request) =>
270 Effect.gen(function* () {
271 if (holdReadiness) {
272 yield* Deferred.succeed(probing, undefined);
273 return yield* Effect.never;
274 }
275 return HttpClientResponse.fromWeb(request, new Response("ok"));
276 }),
277 ),
278 ),
279 );
280 const first = yield* host.ensureReady(() => Effect.void).pipe(Effect.forkChild);
281 yield* Deferred.await(probing);
282 yield* Fiber.interrupt(first);
283 expect(forwards).toBe(0);
284 holdReadiness = false;
285 yield* host.ensureReady(() => Effect.void);
286 yield* host.stop;
287 expect(forwards).toBe(0);
288 holdReadyStatus = true;
289 const second = yield* host.ensureReady(() => Effect.void).pipe(Effect.forkChild);
290 yield* Deferred.await(publishing);
291 yield* Fiber.interrupt(second);
292 holdReadyStatus = false;
293 yield* host.ensureReady(() => Effect.void);
294 expect(forwards).toBe(1);
295 yield* host.stop;
296 expect(forwards).toBe(0);
297 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
298);
299
300it.effect("lists Android devices without probing the host again once it reports Android", () =>
301 Effect.gen(function* () {
302 const fs = yield* FileSystem.FileSystem;
303 const home = yield* fs.makeTempDirectoryScoped();
304 const modes: string[] = [];
305 let androidInstalled = false;
306 const spawner = ChildProcessSpawner.make((command) =>
307 Effect.gen(function* () {
308 if (command._tag !== "StandardCommand") return yield* Effect.die("Unexpected command");
309 const forwarding = command.args.includes("-L");
310 let output = "";
311 if (!forwarding) {
312 const stdin = command.options.stdin;
313 const script =
314 stdin && typeof stdin === "object" && "stream" in stdin && Stream.isStream(stdin.stream)
315 ? yield* stdin.stream.pipe(
316 Stream.decodeText(),
317 Stream.runFold(
318 () => "",
319 (a, b) => a + b,
320 ),
321 )
322 : "";
323 const mode = /const mode = "([^"]+)"/.exec(script)?.[1] ?? "";
324 modes.push(mode);
325 output =
326 mode === ""
327 ? "Pixel_8\n"
328 : JSON.stringify({
329 nodePath: "/node",
330 platforms: [
331 { platform: "ios", available: true },
332 { platform: "android", available: androidInstalled },
333 ],
334 hubPort: 1234,
335 hubToken: "hub-token",
336 helpers: { serveSimAxSettings: null, serveSimCli: null },
337 });
338 }
339 return ChildProcessSpawner.makeHandle({
340 pid: ChildProcessSpawner.ProcessId(123),
341 stdout: Stream.make(new TextEncoder().encode(output)),
342 stderr: Stream.empty,
343 all: Stream.empty,
344 exitCode: forwarding ? Effect.never : Effect.succeed(ChildProcessSpawner.ExitCode(0)),
345 exitStatus: forwarding
346 ? Effect.never
347 : Effect.succeed({ _tag: "Exited", code: ChildProcessSpawner.ExitCode(0) }),
348 isRunning: Effect.succeed(forwarding),
349 kill: () => Effect.void,
350 stdin: Sink.drain,
351 getInputFd: () => Sink.drain,
352 getOutputFd: () => Stream.empty,
353 unref: Effect.succeed(Effect.void),
354 });
355 }),
356 );
357 const host = yield* SshDeviceHost.make({
358 kind: "ssh",
359 id: "test",
360 label: "Test",
361 target: "test.example",
362 }).pipe(
363 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(home, home), Net.layer)),
364 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
365 Effect.provideService(
366 HttpClient.HttpClient,
367 HttpClient.make((request) =>
368 Effect.succeed(
369 HttpClientResponse.fromWeb(
370 request,
371 new Response(
372 request.url.endsWith("/api/devices")
373 ? JSON.stringify({ simulators: [], emulators: [] })
374 : "ok",
375 ),
376 ),
377 ),
378 ),
379 ),
380 );
381 const ready = yield* host.ensureReady(() => Effect.void);
382 const androidNames = ready.devices.list.pipe(
383 Effect.map((list) =>
384 list.devices.filter((device) => device.platform === "android").map((device) => device.name),
385 ),
386 );
387
388 modes.splice(0);
389
390 expect(yield* androidNames).toEqual([]);
391 expect(modes.splice(0)).toEqual(["probe"]);
392 expect(yield* androidNames).toEqual([]);
393 expect(modes.splice(0)).toEqual(["probe"]);
394
395 // The SDK appears after connecting, so the next listing still probes the host.
396 androidInstalled = true;
397 expect(yield* androidNames).toEqual(["Pixel_8"]);
398 expect(modes.splice(0)).toEqual(["probe", ""]);
399
400 // Android is now known to be available, so listing only runs `emulator -list-avds`.
401 expect(yield* androidNames).toEqual(["Pixel_8"]);
402 expect(modes.splice(0)).toEqual([""]);
403
404 androidInstalled = false;
405 expect((yield* host.platformAvailability("android")).available).toBe(false);
406 expect(modes.splice(0)).toEqual(["probe"]);
407 expect(yield* androidNames).toEqual([]);
408 expect(modes.splice(0)).toEqual(["probe"]);
409
410 androidInstalled = true;
411 yield* host.inspect;
412 expect(modes.splice(0)).toEqual(["probe"]);
413 expect(yield* androidNames).toEqual(["Pixel_8"]);
414 expect(modes.splice(0)).toEqual([""]);
415 yield* host.stop;
416 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
417);
418
419it.effect(
420 "keeps the SSH forward through slow health probes and reconnects once the hub stays down",
421 () =>
422 Effect.gen(function* () {
423 const fs = yield* FileSystem.FileSystem;
424 const home = yield* fs.makeTempDirectoryScoped();
425 let forwardSpawns = 0;
426 let hubAnswers = true;
427 const spawner = ChildProcessSpawner.make((command) =>
428 Effect.gen(function* () {
429 if (command._tag !== "StandardCommand") return yield* Effect.die("Unexpected command");
430 const forwarding = command.args.includes("-L");
431 // A fresh forward reaches a working hub again.
432 if (forwarding && ++forwardSpawns > 1) hubAnswers = true;
433 const output = JSON.stringify({
434 nodePath: "/node",
435 platforms: [{ platform: "ios", available: true }],
436 hubPort: 1234,
437 hubToken: "hub-token",
438 helpers: { serveSimAxSettings: null, serveSimCli: null },
439 });
440 return ChildProcessSpawner.makeHandle({
441 pid: ChildProcessSpawner.ProcessId(123),
442 stdout: Stream.make(new TextEncoder().encode(output)),
443 stderr: Stream.empty,
444 all: Stream.empty,
445 exitCode: forwarding ? Effect.never : Effect.succeed(ChildProcessSpawner.ExitCode(0)),
446 exitStatus: forwarding
447 ? Effect.never
448 : Effect.succeed({ _tag: "Exited", code: ChildProcessSpawner.ExitCode(0) }),
449 isRunning: Effect.succeed(forwarding),
450 kill: () => Effect.void,
451 stdin: Sink.drain,
452 getInputFd: () => Sink.drain,
453 getOutputFd: () => Stream.empty,
454 unref: Effect.succeed(Effect.void),
455 });
456 }),
457 );
458 const host = yield* SshDeviceHost.make({
459 kind: "ssh",
460 id: "test",
461 label: "Test",
462 target: "test.example",
463 }).pipe(
464 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(home, home), Net.layer)),
465 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
466 Effect.provideService(
467 HttpClient.HttpClient,
468 HttpClient.make((request) =>
469 hubAnswers
470 ? Effect.succeed(HttpClientResponse.fromWeb(request, new Response("ok")))
471 : Effect.never,
472 ),
473 ),
474 );
475 yield* host.ensureReady(() => Effect.void);
476 expect(forwardSpawns).toBe(1);
477
478 // A loaded host can miss a probe or two without being gone; the forward stays up.
479 hubAnswers = false;
480 yield* TestClock.adjust("30 seconds");
481 hubAnswers = true;
482 yield* TestClock.adjust("2 minutes");
483 expect(forwardSpawns).toBe(1);
484
485 // A hub that keeps missing probes is still replaced.
486 hubAnswers = false;
487 // Recovery reset the miss count, so two new misses do not reconnect yet.
488 yield* TestClock.adjust("30 seconds");
489 expect(forwardSpawns).toBe(1);
490 yield* TestClock.adjust("30 seconds");
491 expect(forwardSpawns).toBe(2);
492 yield* host.stop;
493 }).pipe(
494 Effect.scoped,
495 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, TestClock.layer())),
496 ),
497);
498
499it.effect.each([
500 {
501 name: "a Windows PowerShell login shell",
502 exitCode: 1,
503 stderr: "sh : The term 'sh' is not recognized as the name of a cmdlet\r\n",
504 shellEcho: "%OS%\r\nWindows_NT\r\n",
505 nodePlatform: null,
506 windows: true,
507 },
508 {
509 name: "a Windows cmd login shell",
510 exitCode: 1,
511 stderr: "'sh' is not recognized as an internal or external command,\r\n",
512 shellEcho: "Windows_NT $env:OS\r\n",
513 nodePlatform: null,
514 windows: true,
515 },
516 {
517 name: "a Windows cmd login shell returning 9009",
518 exitCode: 9009,
519 stderr: "'sh' is not recognized as an internal or external command,\r\n",
520 shellEcho: "Windows_NT $env:OS\r\n",
521 nodePlatform: null,
522 windows: true,
523 },
524 {
525 name: "a Windows Git Bash login shell without a spawnable npm",
526 exitCode: 1,
527 stderr: "npm is missing from the non-interactive SSH PATH\n",
528 shellEcho: "%OS% :OS\n",
529 nodePlatform: "win32",
530 windows: true,
531 },
532 {
533 name: "a Linux host without npm",
534 exitCode: 1,
535 stderr: "npm is missing from the non-interactive SSH PATH\n",
536 shellEcho: "%OS% :OS\n",
537 nodePlatform: "linux",
538 windows: false,
539 },
540 {
541 name: "a POSIX host without Node",
542 exitCode: 1,
543 stderr: "Node is missing from the non-interactive SSH PATH\n",
544 shellEcho: "%OS% :OS\n",
545 nodePlatform: null,
546 windows: false,
547 },
548 {
549 name: "an unrecognized SSH failure",
550 exitCode: 255,
551 stderr: "Connection refused\n",
552 shellEcho: "Windows_NT\n",
553 nodePlatform: "win32",
554 windows: false,
555 },
556 {
557 name: "a ProxyCommand permission error",
558 exitCode: 255,
559 stderr: "bash: /usr/local/bin/proxy: Permission denied\n",
560 shellEcho: "",
561 nodePlatform: null,
562 windows: false,
563 },
564 {
565 name: "an untrusted host key",
566 exitCode: 255,
567 stderr: "Host key verification failed.\r\n",
568 shellEcho: "Windows_NT\n",
569 nodePlatform: "win32",
570 windows: false,
571 connect: { reason: "host_key_unknown", detail: "Host key verification failed." },
572 },
573 {
574 name: "a changed host key",
575 exitCode: 255,
576 stderr:
577 "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @\n@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\nIT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!\nHost key verification failed.\n",
578 shellEcho: "",
579 nodePlatform: null,
580 windows: false,
581 connect: {
582 reason: "host_key_changed",
583 detail: "@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @",
584 },
585 },
586 {
587 name: "a rejected login",
588 exitCode: 255,
589 stderr: "me@test.example: Permission denied (publickey).\n",
590 shellEcho: "",
591 nodePlatform: null,
592 windows: false,
593 connect: { reason: "auth", detail: "me@test.example: Permission denied (publickey)." },
594 },
595 {
596 name: "an unresolvable host name",
597 exitCode: 255,
598 stderr: "ssh: Could not resolve hostname test.example: Name or service not known\n",
599 shellEcho: "",
600 nodePlatform: null,
601 windows: false,
602 connect: {
603 reason: "resolve",
604 detail: "ssh: Could not resolve hostname test.example: Name or service not known",
605 },
606 },
607 {
608 name: "a refused connection",
609 exitCode: 255,
610 stderr: "ssh: connect to host test.example port 22: Connection refused\n",
611 shellEcho: "",
612 nodePlatform: null,
613 windows: false,
614 connect: {
615 reason: "connect",
616 detail: "ssh: connect to host test.example port 22: Connection refused",
617 },
618 },
619])(
620 "probe failure on $name keeps the SSH cause",
621 ({ exitCode, stderr, shellEcho, nodePlatform, windows, connect }) =>
622 Effect.gen(function* () {
623 const fs = yield* FileSystem.FileSystem;
624 const home = yield* fs.makeTempDirectoryScoped();
625 const shellChecks: string[] = [];
626 const spawner = ChildProcessSpawner.make((command) =>
627 Effect.gen(function* () {
628 if (command._tag !== "StandardCommand") return yield* Effect.die("Unexpected command");
629 const remote = command.args.slice(command.args.indexOf("test.example") + 1).join(" ");
630 const shellCheck = remote === "echo %OS% $env:OS";
631 const platformCheck = remote === "node -p process.platform";
632 if (shellCheck || platformCheck) shellChecks.push(remote);
633 return ChildProcessSpawner.makeHandle({
634 pid: ChildProcessSpawner.ProcessId(123),
635 stdout: Stream.make(
636 new TextEncoder().encode(
637 shellCheck ? shellEcho : platformCheck ? `${nodePlatform ?? ""}\n` : "",
638 ),
639 ),
640 stderr: Stream.make(
641 new TextEncoder().encode(shellCheck || platformCheck ? "" : stderr),
642 ),
643 all: Stream.empty,
644 exitCode: Effect.succeed(
645 ChildProcessSpawner.ExitCode(
646 shellCheck ? 0 : platformCheck ? (nodePlatform === null ? 1 : 0) : exitCode,
647 ),
648 ),
649 exitStatus: Effect.succeed({
650 _tag: "Exited",
651 code: ChildProcessSpawner.ExitCode(
652 shellCheck ? 0 : platformCheck ? (nodePlatform === null ? 1 : 0) : exitCode,
653 ),
654 }),
655 isRunning: Effect.succeed(false),
656 kill: () => Effect.void,
657 stdin: Sink.drain,
658 getInputFd: () => Sink.drain,
659 getOutputFd: () => Stream.empty,
660 unref: Effect.succeed(Effect.void),
661 });
662 }),
663 );
664 const failure = yield* SshDeviceHost.probe({
665 kind: "ssh",
666 id: "test",
667 label: "Test",
668 target: "test.example",
669 }).pipe(
670 Effect.provide(ServerConfig.layerTest(home, home)),
671 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
672 Effect.flip,
673 );
674 expect(failure).toMatchObject({ _tag: "DeviceHostError", step: "probe" });
675 const sshFailure = { _tag: "SshCommandError", exitCode, stderr };
676 expect(failure.cause).toMatchObject(
677 windows
678 ? { _tag: "SshWindowsHostError", cause: sshFailure }
679 : connect
680 ? { _tag: "SshConnectError", ...connect, target: "test.example", cause: sshFailure }
681 : sshFailure,
682 );
683 // A transport failure has no remote shell to ask.
684 if (exitCode === 255) expect(shellChecks).toEqual([]);
685 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
686);