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