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
18export const flushCallbacks = Effect.yieldNow;
19
20export interface UpdatesHarnessOptions {
21 readonly checkForUpdates?: Effect.Effect<
22 void,
23 ElectronUpdater.ElectronUpdaterCheckForUpdatesError
24 >;
25 readonly beforeSetUpdateChannel?: Effect.Effect<void>;
26 readonly setUpdateChannelError?: DesktopAppSettings.DesktopSettingsWriteError;
27 readonly setDisableDifferentialDownload?: Effect.Effect<void>;
28 readonly downloadUpdate?: Effect.Effect<void>;
29 readonly quitAndInstall?: Effect.Effect<void, ElectronUpdater.ElectronUpdaterQuitAndInstallError>;
30 readonly stopBackend?: Effect.Effect<void>;
31 readonly startBackend?: Effect.Effect<void>;
32 readonly backendDesiredRunning?: boolean;
33 readonly backendInstances?: ReadonlyArray<DesktopBackendPool.DesktopBackendInstance>;
34 readonly env?: Record<string, string | undefined>;
35 readonly platform?: NodeJS.Platform;
36 readonly packageType?: string | undefined;
37 readonly installRecord?: string | undefined;
38}
39
40export function makeHarness(options: UpdatesHarnessOptions = {}) {
41 let checkCount = 0;
42 let quitAndInstallCount = 0;
43 let downloadCount = 0;
44 let allowDowngrade = false;
45 let fullChangelog = false;
46 const feedUrls: ElectronUpdater.ElectronUpdaterFeedUrl[] = [];
47 const listeners = new Map<string, Set<(...args: readonly unknown[]) => void>>();
48 const sentStates: DesktopUpdateState[] = [];
49 const installSteps: string[] = [];
50
51 const addListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
52 const eventListeners = listeners.get(eventName) ?? new Set();
53 eventListeners.add(listener);
54 listeners.set(eventName, eventListeners);
55 };
56
57 const removeListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
58 const eventListeners = listeners.get(eventName);
59 if (!eventListeners) {
60 return;
61 }
62 eventListeners.delete(listener);
63 if (eventListeners.size === 0) {
64 listeners.delete(eventName);
65 }
66 };
67
68 const layerUpdater = Layer.succeed(ElectronUpdater.ElectronUpdater, {
69 setFeedURL: (options) =>
70 Effect.sync(() => {
71 feedUrls.push(options);
72 }),
73 setAutoDownload: () => Effect.void,
74 setAutoInstallOnAppQuit: () => Effect.void,
75 setChannel: () => Effect.void,
76 setAllowPrerelease: () => Effect.void,
77 allowDowngrade: Effect.sync(() => allowDowngrade),
78 setAllowDowngrade: (value) =>
79 Effect.sync(() => {
80 allowDowngrade = value;
81 }),
82 setFullChangelog: (value) =>
83 Effect.sync(() => {
84 fullChangelog = value;
85 }),
86 setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
87 checkForUpdates: Effect.sync(() => {
88 checkCount += 1;
89 }).pipe(Effect.andThen(options.checkForUpdates ?? Effect.void)),
90 downloadUpdate: Effect.sync(() => {
91 downloadCount += 1;
92 }).pipe(Effect.andThen(options.downloadUpdate ?? Effect.void)),
93 quitAndInstall: () =>
94 Effect.sync(() => {
95 quitAndInstallCount += 1;
96 installSteps.push("quitAndInstall");
97 }).pipe(Effect.andThen(options.quitAndInstall ?? Effect.void)),
98 on: (eventName, listener) =>
99 Effect.acquireRelease(
100 Effect.sync(() => {
101 addListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
102 }),
103 () =>
104 Effect.sync(() => {
105 removeListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
106 }),
107 ).pipe(Effect.asVoid),
108 } satisfies ElectronUpdater.ElectronUpdater["Service"]);
109
110 const layerWindow = Layer.succeed(ElectronWindow.ElectronWindow, {
111 create: () => Effect.die("unexpected BrowserWindow creation"),
112 main: Effect.succeedNone,
113 currentMainOrFirst: Effect.succeedNone,
114 focusedMainOrFirst: Effect.succeedNone,
115 setMain: () => Effect.void,
116 clearMain: () => Effect.void,
117 prepareReveal: () => Effect.succeed(false),
118 reveal: () => Effect.void,
119 sendAll: (_channel, state) =>
120 Effect.sync(() => {
121 sentStates.push(state as DesktopUpdateState);
122 }),
123 destroyAll: Effect.sync(() => {
124 installSteps.push("destroyAll");
125 }),
126 syncAllAppearance: () => Effect.void,
127 } satisfies ElectronWindow.ElectronWindow["Service"]);
128
129 let backendDesiredRunning = options.backendDesiredRunning ?? true;
130 const stubBackendInstance: DesktopBackendPool.DesktopBackendInstance = {
131 id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
132 label: Effect.succeed("Windows"),
133 start: Effect.sync(() => {
134 backendDesiredRunning = true;
135 installSteps.push("startBackend");
136 }).pipe(Effect.andThen(options.startBackend ?? Effect.void)),
137 stop: () =>
138 Effect.sync(() => {
139 backendDesiredRunning = false;
140 }).pipe(Effect.andThen(options.stopBackend ?? Effect.void)),
141 currentConfig: Effect.succeedNone,
142 snapshot: Effect.sync(() => ({
143 desiredRunning: backendDesiredRunning,
144 ready: false,
145 activePid: Option.none(),
146 restartAttempt: 0,
147 restartScheduled: false,
148 })),
149 waitForReady: () => Effect.succeed(true),
150 };
151 const layerBackend = DesktopBackendPool.layerTest(
152 options.backendInstances ?? [stubBackendInstance],
153 );
154
155 const layerEnvironment = DesktopEnvironment.layer({
156 dirname: "/repo/apps/desktop/src",
157 homeDirectory: `/tmp/t3-desktop-updates-home-${process.pid}`,
158 platform: options.platform ?? "darwin",
159 processArch: "x64",
160 appVersion: "1.2.3",
161 appPath: "/repo",
162 isPackaged: true,
163 resourcesPath: "/missing/resources",
164 runningUnderArm64Translation: false,
165 }).pipe(
166 Layer.provide(
167 Layer.mergeAll(
168 NodeServices.layer,
169 DesktopConfig.layerTest({
170 T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
171 T3CODE_DESKTOP_MOCK_UPDATES: "true",
172 T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
173 ...options.env,
174 }),
175 ),
176 ),
177 );
178
179 let testSettings: DesktopAppSettings.DesktopSettings = {
180 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
181 };
182 const setUpdateChannelError = options.setUpdateChannelError;
183 const layerSettings =
184 setUpdateChannelError || options.beforeSetUpdateChannel
185 ? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
186 get: Effect.sync(() => testSettings),
187 load: Effect.sync(() => testSettings),
188 setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
189 setServerExposureMode: () => Effect.die("unexpected server exposure update"),
190 setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
191 setUpdateChannel: (channel) =>
192 setUpdateChannelError
193 ? Effect.fail(setUpdateChannelError)
194 : (options.beforeSetUpdateChannel ?? Effect.void).pipe(
195 Effect.andThen(
196 Effect.sync(() => {
197 const changed = testSettings.updateChannel !== channel;
198 testSettings = {
199 ...testSettings,
200 updateChannel: channel,
201 updateChannelConfiguredByUser: true,
202 };
203 return { settings: testSettings, changed };
204 }),
205 ),
206 ),
207 setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
208 setWslDistro: () => Effect.die("unexpected WSL distro change"),
209 setLocalEnvironmentEnabled: () => Effect.die("unexpected local environment toggle"),
210 setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
211 applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
212 applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
213 } satisfies DesktopAppSettings.DesktopAppSettings["Service"])
214 : DesktopAppSettings.layer;
215
216 const updateRestartMarkers = new Set<string>();
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 previousInstallRecord: () => previousInstallRecord,
279 downloadCount: () => downloadCount,
280 feedUrls: (): ElectronUpdater.ElectronUpdaterFeedUrl[] => feedUrls,
281 fullChangelog: () => fullChangelog,
282 listenerCount: () =>
283 Array.from(listeners.values()).reduce(
284 (total, eventListeners) => total + eventListeners.size,
285 0,
286 ),
287 sentStates,
288 emit: (eventName: string, payload?: unknown) => {
289 for (const listener of listeners.get(eventName) ?? []) {
290 listener(payload);
291 }
292 },
293 };
294}