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