Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Manager.startup.test.ts

190 lines8.2 KB

1// @effect-diagnostics-next-line nodeBuiltinImport:off -- this test substitutes real stalled children for selected probes.
2import * as NodeChildProcess from "node:child_process";
3import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import { it } from "@effect/vitest";
6import { DEFAULT_TERMINAL_ID, type TerminalSessionSnapshot } from "@t3tools/contracts";
7import * as HostProcess from "@t3tools/shared/HostProcess";
8import type { PtyExitEvent, PtyProcess } from "@t3tools/shared/PtyAdapter";
9import { SpawnExecutableResolution } from "@t3tools/shared/shell";
10import * as Deferred from "effect/Deferred";
11import * as Effect from "effect/Effect";
12import * as Fiber from "effect/Fiber";
13import * as FileSystem from "effect/FileSystem";
14import * as Layer from "effect/Layer";
15import * as Path from "effect/Path";
16import * as TestClock from "effect/testing/TestClock";
17import { expect, vi } from "vite-plus/test";
18import * as ProcessRunner from "../processRunner.ts";
19import { makeWithOptions } from "./Manager.ts";
20​
21const node = Layer.mergeAll(NodeServices.layer, NodeCrypto.layer);
22const services = Layer.mergeAll(node, ProcessRunner.layer.pipe(Layer.provide(node)));
23​
24vi.mock("node:child_process", { spy: true });
25​
26function fakePtyProcess(): PtyProcess {
27 const exitListeners = new Set<(event: PtyExitEvent) => void>();
28 return {
29 pid: 42,
30 write: () => {},
31 resize: () => {},
32 kill: () => {
33 for (const listener of exitListeners) listener({ exitCode: 0, signal: null });
34 },
35 onData: () => () => {},
36 onExit: (listener) => {
37 exitListeners.add(listener);
38 return () => exitListeners.delete(listener);
39 },
40 };
42​
43it.layer(services, { excludeTestServices: true })("terminal startup deadlines", (it) => {
44 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
45 "starts local fallbacks while concurrent shell probes time out",
46 () =>
47 Effect.gen(function* () {
48 const fs = yield* FileSystem.FileSystem;
49 const path = yield* Path.Path;
50 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-terminal-probes-" });
51 const first = yield* Deferred.make<void>();
52 const second = yield* Deferred.make<void>();
53 const stalled: NodeChildProcess.ChildProcess[] = [];
54 const configured = path.join(root, "configured");
55 const preferred = path.join(root, "preferred");
56 const fallback = path.join(root, "local-shell");
57 yield* fs.writeFileString(fallback, "#!/bin/sh\nexit 0\n");
58 yield* fs.chmod(fallback, 0o755);
59 const real = yield* Effect.promise(() =>
60 vi.importActual<typeof NodeChildProcess>("node:child_process"),
61 );
62 const probe = vi.mocked(NodeChildProcess.execFile);
63 yield* Effect.addFinalizer(() => Effect.sync(() => probe.mockRestore()));
64 probe.mockImplementation((file, args, options, callback) => {
65 if (!args?.includes(configured) && !args?.includes(preferred)) {
66 return real.execFile(file, args, options, callback);
67 }
68 const child = real.execFile(file, ["-c", "exec /bin/sleep 60"], options, callback);
69 stalled.push(child);
70 if (stalled.length === 2) Deferred.doneUnsafe(first, Effect.void);
71 if (stalled.length === 4) Deferred.doneUnsafe(second, Effect.void);
72 return child;
73 });
74 const manager = yield* makeWithOptions({
75 logsDir: path.join(root, "logs"),
76 env: { T3CODE_TERMINAL_SHELL: configured, SHELL: fallback },
77 shellResolver: () => preferred,
78 ptyAdapter: { spawn: () => Effect.sync(fakePtyProcess) },
79 });
80 const openings = yield* Effect.forEach(["first", "second"], (threadId) =>
81 Effect.gen(function* () {
82 const cwd = path.join(root, threadId);
83 yield* fs.makeDirectory(cwd);
84 return yield* manager
85 .open({ cwd, threadId, terminalId: DEFAULT_TERMINAL_ID })
86 .pipe(Effect.forkChild({ startImmediately: true }));
87 }),
88 );
89 yield* Deferred.await(first);
90 yield* TestClock.adjust("2 seconds");
91 yield* Deferred.await(second);
92 yield* TestClock.adjust("2 seconds");
93​
94 const sessions = yield* Effect.forEach(openings, Fiber.join);
95 expect(sessions.map((session) => session.status)).toEqual(["running", "running"]);
96 const shells = yield* Effect.forEach(sessions, (session) => manager.getShell(session));
97 expect(shells).toEqual([fallback, fallback]);
98 expect(stalled.every((child) => child.killed)).toBe(true);
99 }).pipe(Effect.provide(TestClock.layer())),
100 );
101​
102 it.effect.each([
103 { name: "reports a timeout when no shell resolves", stalled: "lookup", fallback: false },
104 { name: "starts a fallback shell after a lookup stalls", stalled: "lookup", fallback: true },
105 {
106 name: "keeps the original PATH when the managed scan stalls",
107 stalled: "scan",
108 fallback: true,
109 },
110 ] as const)("$name", ({ stalled, fallback }) =>
111 Effect.gen(function* () {
112 const fs = yield* FileSystem.FileSystem;
113 const path = yield* Path.Path;
114 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-terminal-startup-" });
115 const cacheDir = path.join(cwd, "cache");
116 const receiptsDir = path.join(cacheDir, "acp-registry", "package-installs");
117 const waiting = yield* Deferred.make<void>();
118 const spawned: Array<{ shell: string; path: string | undefined }> = [];
119 let lookupRecovered = false;
120 const manager = yield* makeWithOptions({
121 logsDir: path.join(cwd, "logs"),
122 env: { PATH: "/usr/bin" },
123 shellResolver: () => "local-shell",
124 ...(stalled === "scan"
125 ? { managedBinaryCacheDir: cacheDir, managedBinaryToolsDir: path.join(cwd, "tools") }
126 : {}),
127 ptyAdapter: {
128 spawn: (input) =>
129 Effect.sync(() => {
130 spawned.push({ shell: input.shell, path: input.env.PATH });
131 return fakePtyProcess();
132 }),
133 },
134 }).pipe(
135 Effect.provideService(HostProcess.Platform, "linux"),
136 Effect.provideService(SpawnExecutableResolution, (command) => {
137 if (stalled === "lookup" && command === "stalled-shell" && !lookupRecovered) {
138 Deferred.doneUnsafe(waiting, Effect.void);
139 return new Promise(() => {});
140 }
141 return command === "local-shell" && (fallback || lookupRecovered) ? command : undefined;
142 }),
143 Effect.provideService(FileSystem.FileSystem, {
144 ...fs,
145 readDirectory: (directory, options) =>
146 stalled === "scan" && directory === receiptsDir
147 ? Deferred.succeed(waiting, undefined).pipe(Effect.andThen(Effect.never))
148 : fs.readDirectory(directory, options),
149 }),
150 );
151​
152 const input = {
153 cwd,
154 threadId: "thread",
155 terminalId: DEFAULT_TERMINAL_ID,
156 ...(stalled === "lookup" ? { env: { T3CODE_TERMINAL_SHELL: "stalled-shell" } } : {}),
157 };
158 const opening = yield* manager.open(input).pipe(Effect.forkChild({ startImmediately: true }));
159 yield* Deferred.await(waiting);
160 const disconnect = yield* Fiber.interrupt(opening).pipe(
161 Effect.forkChild({ startImmediately: true }),
162 );
163 yield* TestClock.adjust("16 seconds");
164 yield* Fiber.join(disconnect);
165​
166 const snapshots: TerminalSessionSnapshot[] = [];
167 const stop = yield* manager.attachStream(input, (event) =>
168 Effect.sync(() => {
169 if (event.type === "snapshot") snapshots.push(event.snapshot);
170 }),
171 );
172 stop();
173​
174 if (fallback) {
175 expect(snapshots).toEqual([expect.objectContaining({ status: "running" })]);
176 expect(spawned).toEqual([{ shell: "local-shell", path: "/usr/bin" }]);
177 } else {
178 expect(snapshots).toEqual([
179 expect.objectContaining({
180 status: "error",
181 error: "Terminal shell preparation timed out.",
182 }),
183 ]);
184 expect(spawned).toEqual([]);
185 lookupRecovered = true;
186 expect((yield* manager.open(input)).status).toBe("running");
187 }
188 }).pipe(Effect.provide(TestClock.layer())),
189 );
190});