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