The best way to control Claude Code, Codex and more from any computer or phone

main
ts 175 lines 5.82 KB
Raw
1 import { EnvironmentId } from "@t3tools/contracts";
2 import { describe, expect, it, vi } from "vite-plus/test";
3
4 const query = vi.hoisted(() => vi.fn());
5 vi.mock(
6 import("@t3tools/client-runtime/state/runtime"),
7 () =>
8 ({
9 executeAtomQuery: query,
10 }) as never,
11 );
12 vi.mock(import("./state/primaryEnvironment"), async () => {
13 const { Atom } = await import("effect/reactivity");
14 return { localEnvironmentIdAtom: Atom.make(EnvironmentId.make("host")) } as never;
15 });
16 vi.mock(import("./state/server"), async () => {
17 const { Atom } = await import("effect/reactivity");
18 return {
19 themeServerEnvironmentThemesAtom: Atom.make([{ id: "nightfall", background: "revision-1" }]),
20 } as never;
21 });
22 vi.mock(import("./state/session"), async () => {
23 const { Atom } = await import("effect/reactivity");
24 return {
25 environmentSession: {
26 preparedConnectionValueAtom: Atom.family(() =>
27 Atom.make({ _tag: "Some", value: { httpBaseUrl: "https://example.com/" } }),
28 ),
29 },
30 } as never;
31 });
32 vi.mock(
33 import("./state/assets"),
34 () =>
35 ({
36 assetEnvironment: { createUrl: vi.fn() },
37 }) as never,
38 );
39
40 import { applyThemeBackground, startThemeBackground } from "./themeBackground";
41 import {
42 CUSTOM_THEMES_STORAGE_KEY,
43 getThemeDefinition,
44 invalidateCustomThemes,
45 THEME_PREVIEW_ID,
46 } from "./themePalette";
47
48 const BACKGROUND = "--theme-background-image";
49 const image = new Blob(["image"], { type: "image/png" });
50 const offline = () => Promise.reject(new TypeError("Failed to fetch"));
51 const loaded = async () => ({ ok: true, blob: async () => image });
52
53 function setup(storage: Record<string, string> = {}) {
54 vi.useFakeTimers();
55 const properties = new Map<string, string>();
56 const browser = Object.assign(new EventTarget(), {
57 localStorage: { getItem: (key: string) => storage[key] ?? null },
58 });
59 vi.stubGlobal("window", browser);
60 invalidateCustomThemes();
61 vi.stubGlobal("document", {
62 documentElement: {
63 dataset: { themeId: "nightfall" },
64 style: {
65 setProperty: (name: string, value: string) => properties.set(name, value),
66 removeProperty: (name: string) => properties.delete(name),
67 },
68 },
69 });
70 query.mockResolvedValue({ _tag: "Success", value: { relativeUrl: "/background.png" } });
71 const fetchBackground = vi.fn<() => Promise<unknown>>(offline);
72 vi.stubGlobal("fetch", fetchBackground);
73 const stop = startThemeBackground();
74 return {
75 properties,
76 browser,
77 fetchBackground,
78 stop,
79 [Symbol.dispose]() {
80 stop();
81 applyThemeBackground(undefined);
82 vi.unstubAllGlobals();
83 invalidateCustomThemes();
84 vi.useRealTimers();
85 },
86 };
87 }
88
89 describe("theme backgrounds", () => {
90 it("retries a failed download after 1, 2, 4 and 8 seconds", async () => {
91 using t = setup();
92 t.fetchBackground
93 .mockImplementationOnce(async () => new Response(null, { status: 503 }))
94 .mockImplementationOnce(offline)
95 .mockImplementationOnce(offline)
96 .mockImplementationOnce(offline)
97 .mockImplementation(loaded);
98
99 applyThemeBackground("nightfall");
100 await vi.advanceTimersByTimeAsync(0);
101 for (const [delay, attempts] of [
102 [1_000, 1],
103 [2_000, 2],
104 [4_000, 3],
105 [8_000, 4],
106 ] as const) {
107 await vi.advanceTimersByTimeAsync(delay - 1);
108 expect(t.fetchBackground).toHaveBeenCalledTimes(attempts);
109 expect(t.properties.has(BACKGROUND)).toBe(false);
110 await vi.advanceTimersByTimeAsync(1);
111 }
112 expect(t.fetchBackground).toHaveBeenCalledTimes(5);
113 expect(t.properties.get(BACKGROUND)).toMatch(/^url\("blob:/);
114 });
115
116 it("loads the background once when the browser comes back online after retries stop", async () => {
117 using t = setup();
118 applyThemeBackground("nightfall");
119 await vi.advanceTimersByTimeAsync(30_000);
120 expect(t.fetchBackground).toHaveBeenCalledTimes(5);
121 expect(t.properties.has(BACKGROUND)).toBe(false);
122
123 t.fetchBackground.mockImplementation(loaded);
124 t.browser.dispatchEvent(new Event("online"));
125 await vi.advanceTimersByTimeAsync(0);
126 expect(t.properties.get(BACKGROUND)).toMatch(/^url\("blob:/);
127
128 t.browser.dispatchEvent(new Event("online"));
129 await vi.advanceTimersByTimeAsync(30_000);
130 expect(t.fetchBackground).toHaveBeenCalledTimes(6);
131 });
132
133 it("keeps the shown background under a draft preview when the browser comes back online", async () => {
134 using t = setup();
135 t.fetchBackground.mockImplementation(loaded);
136 applyThemeBackground("nightfall");
137 await vi.advanceTimersByTimeAsync(0);
138 const shown = t.properties.get(BACKGROUND);
139 expect(shown).toMatch(/^url\("blob:/);
140
141 document.documentElement.dataset.themeId = THEME_PREVIEW_ID;
142 t.browser.dispatchEvent(new Event("online"));
143 await vi.advanceTimersByTimeAsync(0);
144 expect(t.properties.get(BACKGROUND)).toBe(shown);
145 });
146
147 it.each(["theme change", "disposal"])("stops retrying after %s", async (reason) => {
148 using t = setup();
149 applyThemeBackground("nightfall");
150 await vi.advanceTimersByTimeAsync(0);
151 if (reason === "theme change") applyThemeBackground(undefined);
152 else t.stop();
153 await vi.advanceTimersByTimeAsync(30_000);
154 expect(t.fetchBackground).toHaveBeenCalledTimes(1);
155 });
156
157 it("shows no published background when a saved theme shares its id", async () => {
158 using t = setup({
159 [CUSTOM_THEMES_STORAGE_KEY]: JSON.stringify([
160 {
161 id: "nightfall",
162 label: "Nightfall",
163 appearance: "dark",
164 colors: { canvas: "#162327", accent: "#cc3344" },
165 },
166 ]),
167 });
168 t.fetchBackground.mockImplementation(loaded);
169 expect(getThemeDefinition("nightfall")?.colors.accent).toBeDefined();
170 applyThemeBackground("nightfall");
171 await vi.advanceTimersByTimeAsync(0);
172 expect(t.fetchBackground).not.toHaveBeenCalled();
173 expect(t.properties.has(BACKGROUND)).toBe(false);
174 });
175 });