1import type { DesktopWslState } from "@t3tools/contracts";
2import * as Cause from "effect/Cause";
3import * as AsyncResult from "effect/reactivity/AsyncResult";
4import { AtomRegistry } from "effect/reactivity";
5import { describe, expect, it, vi } from "vite-plus/test";
6
7import { createDesktopWslStateAtom } from "./desktopWslState";
8
9const wslState: DesktopWslState = {
10 available: true,
11 distro: null,
12 distros: [
13 {
14 isDefault: true,
15 name: "Ubuntu",
16 version: 2,
17 },
18 ],
19 enabled: true,
20 preflightError: null,
21 wslOnly: false,
22};
23
24describe("desktopWslState", () => {
25 it("retains the loaded snapshot when the settings screen remounts", async () => {
26 const getWslState = vi.fn(async () => wslState);
27 const atom = createDesktopWslStateAtom(() => ({ getWslState }));
28 const registry = AtomRegistry.make();
29
30 const unmount = registry.mount(atom);
31 await vi.waitFor(() => {
32 expect(AsyncResult.value(registry.get(atom))).toEqual(
33 expect.objectContaining({ _tag: "Some", value: wslState }),
34 );
35 });
36 unmount();
37
38 const remount = registry.mount(atom);
39 expect(AsyncResult.value(registry.get(atom))).toEqual(
40 expect.objectContaining({ _tag: "Some", value: wslState }),
41 );
42 expect(getWslState).toHaveBeenCalledTimes(1);
43
44 remount();
45 registry.dispose();
46 });
47
48 it("retains the desktop bridge failure as the load error cause", async () => {
49 const cause = new Error("wsl unavailable");
50 const atom = createDesktopWslStateAtom(() => ({
51 getWslState: async () => Promise.reject(cause),
52 }));
53 const registry = AtomRegistry.make();
54 registry.mount(atom);
55
56 await vi.waitFor(() => expect(AsyncResult.isFailure(registry.get(atom))).toBe(true));
57 const result = registry.get(atom);
58 if (!AsyncResult.isFailure(result)) throw new Error("Expected WSL state load to fail.");
59
60 expect(Cause.squash(result.cause)).toEqual(
61 expect.objectContaining({
62 _tag: "DesktopWslStateLoadError",
63 cause,
64 }),
65 );
66 registry.dispose();
67 });
68
69 it("replaces cached state with refreshed live desktop state", async () => {
70 const refreshedState: DesktopWslState = {
71 ...wslState,
72 preflightError: "WSL backend stopped unexpectedly.",
73 };
74 let currentState = wslState;
75 const getWslState = vi.fn(async () => currentState);
76 const atom = createDesktopWslStateAtom(() => ({ getWslState }));
77 const registry = AtomRegistry.make();
78 registry.mount(atom);
79
80 await vi.waitFor(() => {
81 expect(AsyncResult.value(registry.get(atom))).toEqual(
82 expect.objectContaining({ _tag: "Some", value: wslState }),
83 );
84 });
85
86 currentState = refreshedState;
87 registry.refresh(atom);
88
89 await vi.waitFor(() => {
90 expect(AsyncResult.value(registry.get(atom))).toEqual(
91 expect.objectContaining({ _tag: "Some", value: refreshedState }),
92 );
93 });
94 expect(getWslState).toHaveBeenCalledTimes(2);
95 registry.dispose();
96 });
97});