Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import type { DesktopUpdateState } from "@t3tools/contracts";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7
8import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
9import * as DesktopConfig from "../app/DesktopConfig.ts";
10import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
11import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
12import * as ElectronWindow from "../electron/ElectronWindow.ts";
13import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
14import * as DesktopState from "../app/DesktopState.ts";
15import * as DesktopUpdates from "./DesktopUpdates.ts";
16
17/** Shared DesktopUpdates test harness: a fully stubbed updater layer whose
18 electron-updater events are driven by hand via `emit`. Used by
19 DesktopUpdates.test.ts and DesktopRemoteUpdates.test.ts. */
20
21export const flushCallbacks = Effect.yieldNow;
22
23export interface UpdatesHarnessOptions {
24 readonly checkForUpdates?: Effect.Effect<
25 void,
26 ElectronUpdater.ElectronUpdaterCheckForUpdatesError
27 >;
28 readonly beforeSetUpdateChannel?: Effect.Effect<void>;
29 readonly setUpdateChannelError?: DesktopAppSettings.DesktopSettingsWriteError;
30 readonly setDisableDifferentialDownload?: Effect.Effect<void>;
31 readonly downloadUpdate?: Effect.Effect<void>;
32 readonly quitAndInstall?: Effect.Effect<void, ElectronUpdater.ElectronUpdaterQuitAndInstallError>;
33 readonly stopBackend?: Effect.Effect<void>;
34 readonly startBackend?: Effect.Effect<void>;
35 readonly env?: Record<string, string | undefined>;
36}
37
38export function makeHarness(options: UpdatesHarnessOptions = {}) {
39 let checkCount = 0;
40 let quitAndInstallCount = 0;
41 let downloadCount = 0;
42 let allowDowngrade = false;
43 let fullChangelog = false;
44 const feedUrls: ElectronUpdater.ElectronUpdaterFeedUrl[] = [];
45 const listeners = new Map<string, Set<(...args: readonly unknown[]) => void>>();
46 const sentStates: DesktopUpdateState[] = [];
47 const installSteps: string[] = [];
48
49 const addListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
50 const eventListeners = listeners.get(eventName) ?? new Set();
51 eventListeners.add(listener);
52 listeners.set(eventName, eventListeners);
53 };
54
55 const removeListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
56 const eventListeners = listeners.get(eventName);
57 if (!eventListeners) {
58 return;
59 }
60 eventListeners.delete(listener);
61 if (eventListeners.size === 0) {
62 listeners.delete(eventName);
63 }
64 };
65
66 const updaterLayer = Layer.succeed(ElectronUpdater.ElectronUpdater, {
67 setFeedURL: (options) =>
68 Effect.sync(() => {
69 feedUrls.push(options);
70 }),
71 setAutoDownload: () => Effect.void,
72 setAutoInstallOnAppQuit: () => Effect.void,
73 setChannel: () => Effect.void,
74 setAllowPrerelease: () => Effect.void,
75 allowDowngrade: Effect.sync(() => allowDowngrade),
76 setAllowDowngrade: (value) =>
77 Effect.sync(() => {
78 allowDowngrade = value;
79 }),
80 setFullChangelog: (value) =>
81 Effect.sync(() => {
82 fullChangelog = value;
83 }),
84 setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
85 checkForUpdates: Effect.sync(() => {
86 checkCount += 1;
87 }).pipe(Effect.andThen(options.checkForUpdates ?? Effect.void)),
88 downloadUpdate: Effect.sync(() => {
89 downloadCount += 1;
90 }).pipe(Effect.andThen(options.downloadUpdate ?? Effect.void)),
91 quitAndInstall: () =>
92 Effect.sync(() => {
93 quitAndInstallCount += 1;
94 installSteps.push("quitAndInstall");
95 }).pipe(Effect.andThen(options.quitAndInstall ?? Effect.void)),
96 on: (eventName, listener) =>
97 Effect.acquireRelease(
98 Effect.sync(() => {
99 addListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
100 }),
101 () =>
102 Effect.sync(() => {
103 removeListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
104 }),
105 ).pipe(Effect.asVoid),
106 } satisfies ElectronUpdater.ElectronUpdater["Service"]);
107
108 const windowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
109 create: () => Effect.die("unexpected BrowserWindow creation"),
110 main: Effect.succeedNone,
111 currentMainOrFirst: Effect.succeedNone,
112 focusedMainOrFirst: Effect.succeedNone,
113 setMain: () => Effect.void,
114 clearMain: () => Effect.void,
115 prepareReveal: () => Effect.succeed(false),
116 reveal: () => Effect.void,
117 sendAll: (_channel, state) =>
118 Effect.sync(() => {
119 sentStates.push(state as DesktopUpdateState);
120 }),
121 destroyAll: Effect.sync(() => {
122 installSteps.push("destroyAll");
123 }),
124 syncAllAppearance: () => Effect.void,
125 } satisfies ElectronWindow.ElectronWindow["Service"]);
126
127 const stubBackendInstance: DesktopBackendPool.DesktopBackendInstance = {
128 id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
129 label: Effect.succeed("Windows"),
130 start: Effect.sync(() => {
131 installSteps.push("startBackend");
132 }).pipe(Effect.andThen(options.startBackend ?? Effect.void)),
133 stop: () => options.stopBackend ?? Effect.void,
134 currentConfig: Effect.succeedNone,
135 snapshot: Effect.succeed({
136 desiredRunning: false,
137 ready: false,
138 activePid: Option.none(),
139 restartAttempt: 0,
140 restartScheduled: false,
141 }),
142 waitForReady: () => Effect.succeed(true),
143 };
144 const backendLayer = DesktopBackendPool.layerTest([stubBackendInstance]);
145
146 const environmentLayer = DesktopEnvironment.layer({
147 dirname: "/repo/apps/desktop/src",
148 homeDirectory: `/tmp/t3-desktop-updates-home-${process.pid}`,
149 platform: "darwin",
150 processArch: "x64",
151 appVersion: "1.2.3",
152 appPath: "/repo",
153 isPackaged: true,
154 resourcesPath: "/missing/resources",
155 runningUnderArm64Translation: false,
156 }).pipe(
157 Layer.provide(
158 Layer.mergeAll(
159 NodeServices.layer,
160 DesktopConfig.layerTest({
161 T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
162 T3CODE_DESKTOP_MOCK_UPDATES: "true",
163 T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
164 ...options.env,
165 }),
166 ),
167 ),
168 );
169
170 let testSettings: DesktopAppSettings.DesktopSettings = {
171 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
172 };
173 const setUpdateChannelError = options.setUpdateChannelError;
174 const settingsLayer =
175 setUpdateChannelError || options.beforeSetUpdateChannel
176 ? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
177 get: Effect.sync(() => testSettings),
178 load: Effect.sync(() => testSettings),
179 setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
180 setServerExposureMode: () => Effect.die("unexpected server exposure update"),
181 setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
182 setUpdateChannel: (channel) =>
183 setUpdateChannelError
184 ? Effect.fail(setUpdateChannelError)
185 : (options.beforeSetUpdateChannel ?? Effect.void).pipe(
186 Effect.andThen(
187 Effect.sync(() => {
188 const changed = testSettings.updateChannel !== channel;
189 testSettings = {
190 ...testSettings,
191 updateChannel: channel,
192 updateChannelConfiguredByUser: true,
193 };
194 return { settings: testSettings, changed };
195 }),
196 ),
197 ),
198 setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
199 setWslDistro: () => Effect.die("unexpected WSL distro change"),
200 setLocalEnvironmentEnabled: () => Effect.die("unexpected local environment toggle"),
201 setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
202 applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
203 applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
204 } satisfies DesktopAppSettings.DesktopAppSettings["Service"])
205 : DesktopAppSettings.layer;
206
207 // Tracks the restart markers installs leave, so installs stay free of real
208 // disk I/O that would outrun the tests' settle loops.
209 const updateRestartMarkers = new Set<string>();
210 const fileSystemLayer = FileSystem.layerNoop({
211 makeDirectory: () => Effect.void,
212 writeFileString: (path) =>
213 Effect.sync(() => {
214 updateRestartMarkers.add(path);
215 }),
216 remove: (path) =>
217 Effect.sync(() => {
218 updateRestartMarkers.delete(path);
219 }),
220 });
221
222 const layer = DesktopUpdates.layer.pipe(
223 Layer.provide(fileSystemLayer),
224 Layer.provideMerge(updaterLayer),
225 Layer.provideMerge(windowLayer),
226 Layer.provideMerge(backendLayer),
227 Layer.provideMerge(DesktopState.layer),
228 Layer.provideMerge(settingsLayer),
229 Layer.provideMerge(
230 DesktopConfig.layerTest({
231 T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
232 T3CODE_DESKTOP_MOCK_UPDATES: "true",
233 T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
234 ...options.env,
235 }),
236 ),
237 Layer.provideMerge(environmentLayer),
238 Layer.provideMerge(NodeServices.layer),
239 );
240
241 return {
242 layer,
243 checkCount: () => checkCount,
244 quitAndInstalls: () => quitAndInstallCount,
245 installSteps,
246 updateRestartMarkers,
247 downloadCount: () => downloadCount,
248 feedUrls: (): ElectronUpdater.ElectronUpdaterFeedUrl[] => feedUrls,
249 fullChangelog: () => fullChangelog,
250 listenerCount: () =>
251 Array.from(listeners.values()).reduce(
252 (total, eventListeners) => total + eventListeners.size,
253 0,
254 ),
255 sentStates,
256 emit: (eventName: string, payload?: unknown) => {
257 for (const listener of listeners.get(eventName) ?? []) {
258 listener(payload);
259 }
260 },
261 };
262}