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