Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - The channel reads real file descriptors.
2import * as NodeFS from "node:fs";
3import * as NodeOS from "node:os";
4import * as NodePath from "node:path";
5
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import { expect, it } from "@effect/vitest";
8import * as Context from "effect/Context";
9import * as Effect from "effect/Effect";
10import * as Exit from "effect/Exit";
11import * as Layer from "effect/Layer";
12
13import * as ServerConfig from "../config.ts";
14import * as DesktopBrowserChannel from "./DesktopBrowserChannel.ts";
15
16const key = { threadId: "thread-1", tabId: "tab-1" };
17
18/** The channel over two files: what the desktop sent, and where commands go. */
19const channelOver = (events: ReadonlyArray<Record<string, unknown>>) =>
20 Effect.gen(function* () {
21 const directory = yield* Effect.acquireRelease(
22 Effect.sync(() =>
23 NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-desktop-browser-channel-")),
24 ),
25 (directory) => Effect.sync(() => NodeFS.rmSync(directory, { recursive: true, force: true })),
26 );
27 const inbound = NodePath.join(directory, "events.ndjson");
28 NodeFS.writeFileSync(inbound, events.map((event) => `${JSON.stringify(event)}\n`).join(""));
29 const control = yield* Effect.acquireRelease(
30 Effect.sync(() => NodeFS.openSync(NodePath.join(directory, "commands.ndjson"), "w")),
31 (fd) => Effect.sync(() => NodeFS.closeSync(fd)),
32 );
33 const base = yield* ServerConfig.ServerConfig.pipe(
34 Effect.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-desktop-browser-" })),
35 );
36 const config = Layer.succeed(ServerConfig.ServerConfig, {
37 ...base,
38 desktopBrowserFd: NodeFS.openSync(inbound, "r"),
39 desktopBrowserControlFd: control,
40 });
41 // Built in the caller's scope, so the channel outlives this setup.
42 const context = yield* Layer.build(DesktopBrowserChannel.layer.pipe(Layer.provide(config)));
43 return Context.get(context, DesktopBrowserChannel.DesktopBrowserChannel);
44 });
45
46it.layer(NodeServices.layer)("DesktopBrowserChannel", (it) => {
47 it.effect("refuses an endpoint for a tab that is no longer attached", () =>
48 Effect.gen(function* () {
49 const channel = yield* channelOver([
50 { type: "attached", ...key },
51 { type: "detached", ...key },
52 ]);
53 // Whether or not the reader has reached these lines yet, the tab is not attached.
54 const exit = yield* Effect.exit(Effect.scoped(channel.endpoint(key)));
55 expect(Exit.isFailure(exit)).toBe(true);
56 }).pipe(Effect.scoped),
57 );
58});