diff --git a/apps/desktop/src/electron/ElectronUpdater.ts b/apps/desktop/src/electron/ElectronUpdater.ts index 0cc22bb4b1633..5ea4817cc009c 100644 --- a/apps/desktop/src/electron/ElectronUpdater.ts +++ b/apps/desktop/src/electron/ElectronUpdater.ts @@ -1,10 +1,17 @@ +import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; -import { AppImageUpdater, autoUpdater } from "electron-updater"; +import { + AppImageUpdater, + autoUpdater, + type ResolvedUpdateFileInfo, + type UpdateInfo, +} from "electron-updater"; type AutoUpdater = typeof autoUpdater; type SpawnLog = (cmd: string, args?: Array, ...rest: Array) => Promise; @@ -28,6 +35,15 @@ const relaunchWithoutInheritedDescriptors = (updater: AppImageUpdater) => { }; }; +export interface ElectronUpdaterOfferedFiles { + readonly version: string; + readonly files: ReadonlyArray<{ + readonly pathname: string; + readonly infoUrl: string; + readonly sha512: string | undefined; + }>; +} + export type ElectronUpdaterFeedUrl = Parameters[0]; export class ElectronUpdaterCheckForUpdatesError extends Schema.TaggedError()( @@ -87,6 +103,8 @@ export class ElectronUpdater extends Context.Service< readonly setAllowDowngrade: (value: boolean) => Effect.Effect; readonly setFullChangelog: (value: boolean) => Effect.Effect; readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect; + readonly pendingDownloadDirectory: Effect.Effect>; + readonly offeredUpdateFiles: Effect.Effect>; readonly checkForUpdates: Effect.Effect; readonly downloadUpdate: Effect.Effect; readonly quitAndInstall: (options: { @@ -153,6 +171,44 @@ export const make = ElectronUpdater.of({ }); }, ), + // The private helper resolves the same directory as downloads, including updaterCacheDirName. + pendingDownloadDirectory: Effect.tryPromise({ + try: () => + ( + autoUpdater as unknown as { + getOrCreateDownloadHelper: () => Promise<{ readonly cacheDirForPendingUpdate: string }>; + } + ).getOrCreateDownloadHelper(), + catch: () => new Cause.NoSuchElementError("electron-updater has no download cache helper."), + }).pipe( + Effect.map((helper) => helper.cacheDirForPendingUpdate), + Effect.option, + ), + // downloadUpdate selects from these resolved URLs, not from the raw manifest file names. + offeredUpdateFiles: Effect.try({ + try: () => { + const offered = ( + autoUpdater as unknown as { + readonly updateInfoAndProvider: { + readonly info: UpdateInfo; + readonly provider: { + resolveFiles: (info: UpdateInfo) => Array; + }; + } | null; + } + ).updateInfoAndProvider; + if (offered == null) return Option.none(); + return Option.some({ + version: offered.info.version, + files: offered.provider.resolveFiles(offered.info).map((file) => ({ + pathname: file.url.pathname, + infoUrl: file.info.url, + sha512: file.info.sha512, + })), + }); + }, + catch: () => new Cause.NoSuchElementError("electron-updater could not resolve offered files."), + }).pipe(Effect.option, Effect.map(Option.flatten)), checkForUpdates: Effect.suspend(() => { const channel = autoUpdater.channel; return Effect.tryPromise({ diff --git a/apps/desktop/src/updates/DesktopUpdates.test.ts b/apps/desktop/src/updates/DesktopUpdates.test.ts index 33ed00a764738..1a2873943591e 100644 --- a/apps/desktop/src/updates/DesktopUpdates.test.ts +++ b/apps/desktop/src/updates/DesktopUpdates.test.ts @@ -1,5 +1,8 @@ +// @effect-diagnostics nodeBuiltinImport:off - Fixtures hash cached packages the way electron-updater does. +import * as NodeCrypto from "node:crypto"; import * as NodeModule from "node:module"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import { DESKTOP_UPDATE_RESTART_MARKER_FILE, DesktopUpdateStateSchema } from "@t3tools/contracts"; import { computeReleaseNotes } from "electron-updater/out/providers/GitHubProvider.js"; @@ -8,6 +11,7 @@ import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Logger from "effect/Logger"; import * as Option from "effect/Option"; @@ -26,6 +30,70 @@ import * as DesktopUpdatePolicy from "./DesktopUpdatePolicy.ts"; import * as DesktopUpdates from "./DesktopUpdates.ts"; import { flushCallbacks, makeHarness } from "./updatesTestHarness.ts"; +const sha512Of = (bytes: string) => NodeCrypto.createHash("sha512").update(bytes).digest("base64"); +const x64Package = "T3 Code 1.2.4 x64"; +const arm64Package = "T3 Code 1.2.4 arm64"; + +// What electron-updater leaves in `//pending` after a verified download. +const pendingDownloadCache = Effect.fn("test.pendingDownloadCache")(function* (cache: { + readonly packageBytes: string; + readonly fileName?: string; + readonly sha512?: string; +}) { + const fs = yield* FileSystem.FileSystem; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-updater-pending-" }); + const fileName = cache.fileName ?? "T3-Code-1.2.4-mac.zip"; + yield* fs.writeFileString(`${directory}/${fileName}`, cache.packageBytes); + yield* fs.writeFileString( + `${directory}/update-info.json`, + JSON.stringify({ fileName, sha512: cache.sha512 ?? sha512Of(cache.packageBytes) }), + ); + return directory; +}); + +// The provider resolves each manifest `files[].url` against the feed URL. +const offeredUpdateFiles = ( + feedUrl: string, + files: ReadonlyArray, +) => ({ + version: "1.2.4", + files: files.map(([url, packageBytes]) => ({ + pathname: new URL(url, feedUrl).pathname, + infoUrl: url, + sha512: sha512Of(packageBytes), + })), +}); + +const macUpdateFiles = offeredUpdateFiles("https://updates.example/", [ + ["T3-Code-1.2.4-arm64-mac.zip", arm64Package], + ["T3-Code-1.2.4-mac.zip", x64Package], +]); + +const checkWithPendingDownload = Effect.fn("test.checkWithPendingDownload")(function* (options: { + readonly cache: Parameters[0]; + readonly offeredUpdateFiles?: ReturnType; + readonly platform?: NodeJS.Platform; + readonly processArch?: string; +}) { + const { cache, ...harnessOptions } = options; + const harness = makeHarness({ + offeredUpdateFiles: macUpdateFiles, + ...harnessOptions, + pendingDownloadDirectory: yield* pendingDownloadCache(cache), + checkForUpdates: Effect.sync(() => harness.emit("update-available", { version: "1.2.4" })), + // electron-updater satisfies the download from its verified cache. + downloadUpdate: Effect.sync(() => harness.emit("update-downloaded", { version: "1.2.4" })), + }); + + return yield* Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + yield* updates.check("startup"); + yield* flushCallbacks; + return { state: yield* updates.getState, downloadCount: harness.downloadCount() }; + }).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); +}); + const encodeUpdateState = Schema.encodeEffect(DesktopUpdateStateSchema); type ReleaseFeed = Parameters[2]; @@ -181,6 +249,95 @@ describe("DesktopUpdates", () => { ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }); + it.effect.each([ + { name: "on an Intel Mac", processArch: "x64", cache: { packageBytes: x64Package } }, + { + name: "on an Apple Silicon Mac", + processArch: "arm64", + cache: { packageBytes: arm64Package, fileName: "T3-Code-1.2.4-arm64-mac.zip" }, + }, + { + // findFile falls back to the first file that is not a .pkg or .dmg. + name: "from a mirror whose package URLs have no extension", + processArch: "x64", + cache: { packageBytes: x64Package, fileName: "x64" }, + offeredUpdateFiles: offeredUpdateFiles("https://mirror.example/t3/download/", [ + ["T3-Code-1.2.4.dmg", "T3 Code 1.2.4 dmg"], + ["x64", x64Package], + ]), + }, + ])( + "restores a verified cached download after quitting without installing $name", + ({ name: _name, ...options }) => + Effect.gen(function* () { + const { state, downloadCount } = yield* checkWithPendingDownload(options); + + assert.equal(state.status, "downloaded"); + assert.equal(state.downloadedVersion, "1.2.4"); + assert.equal(downloadCount, 1); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("keeps other checks out while it validates a cached download", () => + Effect.gen(function* () { + const readStarted = yield* Deferred.make(); + const releaseRead = yield* Deferred.make(); + const harness = makeHarness({ + offeredUpdateFiles: macUpdateFiles, + pendingDownloadDirectory: yield* pendingDownloadCache({ packageBytes: x64Package }), + beforePendingDownloadRead: Deferred.succeed(readStarted, undefined).pipe( + Effect.flatMap((first) => (first ? Deferred.await(releaseRead) : Effect.void)), + ), + checkForUpdates: Effect.sync(() => harness.emit("update-available", { version: "1.2.4" })), + downloadUpdate: Effect.sync(() => harness.emit("update-downloaded", { version: "1.2.4" })), + }); + + yield* Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + const startupCheck = yield* updates.check("startup").pipe(Effect.forkScoped); + yield* Deferred.await(readStarted); + + const manualCheck = yield* updates.check("manual"); + assert.isFalse(manualCheck.checked); + assert.equal(harness.checkCount(), 1); + + yield* Deferred.succeed(releaseRead, undefined); + yield* Fiber.join(startupCheck); + yield* flushCallbacks; + assert.equal((yield* updates.getState).status, "downloaded"); + assert.equal(harness.downloadCount(), 1); + }).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect.each([ + { name: "a cached package for another release", cache: { packageBytes: "T3 Code 1.2.3 x64" } }, + // The harness is an Intel Mac, so electron-updater would fetch the x64 zip instead. + { name: "a cached package for another architecture", cache: { packageBytes: arm64Package } }, + { + name: "a cached package whose bytes are damaged", + cache: { packageBytes: "T3 Code 1.2.4 x6", sha512: sha512Of(x64Package) }, + }, + { + // Both resolved paths contain the feed's /x64/, so electron-updater picks the first .exe. + name: "an x64 installer listed after arm64 on an /x64/ feed", + platform: "win32" as const, + cache: { packageBytes: x64Package, fileName: "T3-Code-Setup-1.2.4-x64.exe" }, + offeredUpdateFiles: offeredUpdateFiles("https://mirror.example/t3/x64/", [ + ["T3-Code-Setup-1.2.4-arm64.exe", arm64Package], + ["T3-Code-Setup-1.2.4-x64.exe", x64Package], + ]), + }, + ])("keeps the update click-to-download with $name", (options) => + Effect.gen(function* () { + const { state, downloadCount } = yield* checkWithPendingDownload(options); + + assert.equal(state.status, "available"); + assert.equal(downloadCount, 0); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + it.effect.each([ { name: "shows no notes for a Stable release missing from the releases feed", diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts index 775a9ff6b04ff..0c03d73080ee3 100644 --- a/apps/desktop/src/updates/DesktopUpdates.ts +++ b/apps/desktop/src/updates/DesktopUpdates.ts @@ -1,3 +1,6 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off - Effect's Digest has no streaming sha512 for update packages. +import * as NodeCrypto from "node:crypto"; + import { DESKTOP_UPDATE_RESTART_MARKER_FILE, DESKTOP_UPDATE_IN_PROGRESS_MARKER_FILE, @@ -82,6 +85,10 @@ const UpdateInfo = Schema.Struct({ releaseDate: Schema.optional(Schema.String), }); +const CachedDownloadInfo = Schema.fromJsonString( + Schema.Struct({ fileName: Schema.String, sha512: Schema.String }), +); + const DownloadProgressInfo = Schema.Struct({ percent: Schema.Number, }); @@ -95,6 +102,7 @@ const encodeInstallRecord = Schema.encodeEffect(DesktopUpdateInstallRecord); const decodeAppUpdateYmlConfig = Schema.decodeUnknownEffect(AppUpdateYmlConfig); const decodeUpdateInfo = Schema.decodeUnknownEffect(UpdateInfo); const decodeDownloadProgressInfo = Schema.decodeUnknownEffect(DownloadProgressInfo); +const decodeCachedDownloadInfo = Schema.decodeUnknownEffect(CachedDownloadInfo); const currentIsoTimestamp = DateTime.now.pipe(Effect.map(DateTime.formatIso)); @@ -372,6 +380,41 @@ function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean return runtimeInfo.hostArch === "arm64" && runtimeInfo.appArch === "x64"; } +// Mirrors electron-updater 6.8.9's MacUpdater.filterFilesForArch and Provider.findFile: resuming +// a cached artifact the updater would not select makes it download the selected one instead. +function selectUpdateFile( + files: ElectronUpdater.ElectronUpdaterOfferedFiles["files"], + platform: NodeJS.Platform, + isDebPackage: boolean, + runtimeInfo: DesktopRuntimeInfo, +) { + // findFile matches process.arch, which "other" does not preserve. + if (runtimeInfo.appArch === "other") return undefined; + const mentions = (file: (typeof files)[number], text: string) => + file.pathname.includes(text) || file.infoUrl.includes(text); + let candidates = files; + if (platform === "darwin") { + const isArm64File = (file: (typeof files)[number]) => mentions(file, "arm64"); + const preferArm64 = runtimeInfo.hostArch === "arm64" && files.some(isArm64File); + candidates = files.filter((file) => isArm64File(file) === preferArm64); + } + const [extension, excluded] = + platform === "darwin" + ? ["zip", ["pkg", "dmg"]] + : platform === "win32" + ? ["exe", undefined] + : isDebPackage + ? ["deb", ["appimage", "rpm", "pacman"]] + : ["appimage", ["rpm", "deb", "pacman"]]; + const hasExtension = (file: (typeof files)[number], ext: string) => + file.pathname.toLowerCase().endsWith(`.${ext}`); + const packageFiles = candidates.filter((file) => hasExtension(file, extension)); + const selected = + packageFiles.find((file) => mentions(file, runtimeInfo.appArch)) ?? packageFiles[0]; + if (selected !== undefined || excluded === undefined) return selected ?? candidates[0]; + return candidates.find((file) => !excluded.some((ext) => hasExtension(file, ext))); +} + /** @public */ export const make = Effect.gen(function* () { const config = yield* DesktopConfig.DesktopConfig; @@ -618,41 +661,20 @@ export const make = Effect.gen(function* () { ); }); - return yield* actionReservation === "held" - ? check - : check.pipe( - Effect.onInterrupt(() => setState(state)), - Effect.ensuring(finishUpdateAction("check")), - ); + if (actionReservation === "held") return yield* check; + // The restore validates the cache against the offer this check left, so no other check may + // replace that offer before the download starts. + return yield* check.pipe( + Effect.onInterrupt(() => setState(state)), + Effect.tap(() => resumeCachedDownload), + Effect.ensuring(finishUpdateAction("check")), + ); }); - // Install refreshes before downloading, and a second check could pick a stale, older release. - const downloadAvailableUpdate = Effect.fn("desktop.updates.downloadAvailableUpdate")(function* ( + // Holder of the download reservation; releases it when the download settles. + const downloadReservedUpdate = Effect.fn("desktop.updates.downloadReservedUpdate")(function* ( refresh: boolean, ) { - const admission = yield* Effect.scoped( - admitAfterCheck( - Effect.gen(function* () { - const state = yield* Ref.get(updateStateRef); - if (!(yield* Ref.get(updaterConfiguredRef)) || state.status !== "available") { - return "refused" as const; - } - const activeAction = yield* Ref.get(activeUpdateActionRef); - if (Option.isSome(activeAction)) { - return activeAction.value === "check" - ? ("wait-for-check" as const) - : ("refused" as const); - } - return (yield* tryStartUpdateAction("download")) - ? ("admitted" as const) - : ("refused" as const); - }), - ), - ); - if (admission === "refused") { - return { accepted: false, completed: false }; - } - const offered = yield* Ref.get(updateStateRef); let state = offered; return yield* Effect.gen(function* () { @@ -726,6 +748,96 @@ export const make = Effect.gen(function* () { ); }); + // Install refreshes before downloading, and a second check could pick a stale, older release. + const downloadAvailableUpdate = Effect.fn("desktop.updates.downloadAvailableUpdate")(function* ( + refresh: boolean, + ) { + const admission = yield* Effect.scoped( + admitAfterCheck( + Effect.gen(function* () { + const state = yield* Ref.get(updateStateRef); + if (!(yield* Ref.get(updaterConfiguredRef)) || state.status !== "available") { + return "refused" as const; + } + const activeAction = yield* Ref.get(activeUpdateActionRef); + if (Option.isSome(activeAction)) { + return activeAction.value === "check" + ? ("wait-for-check" as const) + : ("refused" as const); + } + return (yield* tryStartUpdateAction("download")) + ? ("admitted" as const) + : ("refused" as const); + }), + ), + ); + if (admission === "refused") { + return { accepted: false, completed: false }; + } + return yield* downloadReservedUpdate(refresh); + }); + + // A launch that quit without installing leaves its verified package in electron-updater's cache. + // downloadUpdate re-hashes it and emits update-downloaded without fetching it again. + const resumeCachedDownload = Effect.gen(function* () { + const offered = yield* electronUpdater.offeredUpdateFiles; + if (Option.isNone(offered)) return; + const { version } = offered.value; + const sha512 = selectUpdateFile( + offered.value.files, + environment.platform, + isDebPackage, + environment.runtimeInfo, + )?.sha512; + if (sha512 === undefined) return; + const stillOffered = Ref.get(updateStateRef).pipe( + Effect.flatMap((state) => + state.status === "available" && state.availableVersion === version + ? offerable(version, state) + : Effect.succeed(false), + ), + ); + if (!(yield* stillOffered)) return; + + const pendingDirectory = yield* electronUpdater.pendingDownloadDirectory; + if (Option.isNone(pendingDirectory)) return; + const cached = yield* fileSystem + .readFileString(environment.path.join(pendingDirectory.value, "update-info.json")) + .pipe(Effect.flatMap(decodeCachedDownloadInfo), Effect.option); + if (Option.isNone(cached) || cached.value.sha512 !== sha512) return; + // Damaged bytes would make downloadUpdate discard the cache and fetch the package again. + const packageSha512 = yield* Effect.suspend(() => { + const hash = NodeCrypto.createHash("sha512"); + return fileSystem + .stream(environment.path.join(pendingDirectory.value, cached.value.fileName)) + .pipe( + Stream.runForEach((chunk) => Effect.sync(() => hash.update(chunk))), + Effect.map(() => hash.digest("base64")), + Effect.option, + ); + }); + if (Option.getOrUndefined(packageSha512) !== sha512) return; + if ((yield* Ref.get(desktopState.quitting)) || !(yield* stillOffered)) return; + + yield* logUpdaterInfo("restoring cached update download", { version }); + // An interrupt between the handover and the download's own release would strand the reservation. + yield* Effect.uninterruptibleMask((restore) => + Ref.modify(activeUpdateActionRef, (activeAction) => + Option.isSome(activeAction) && activeAction.value === "check" + ? ([true, Option.some("download")] as const) + : ([false, activeAction] as const), + ).pipe( + Effect.flatMap((claimedFromCheck) => + claimedFromCheck + ? restore(downloadReservedUpdate(false)).pipe( + Effect.ensuring(finishUpdateAction("download")), + ) + : Effect.void, + ), + ), + ); + }).pipe(Effect.withSpan("desktop.updates.resumeCachedDownload")); + const updateRestartMarkerDir = environment.path.join(environment.baseDir, "runtime"); const updateRestartMarkerPath = environment.path.join( updateRestartMarkerDir, diff --git a/apps/desktop/src/updates/updatesTestHarness.ts b/apps/desktop/src/updates/updatesTestHarness.ts index b118d15ced674..e59bc6cdc0d00 100644 --- a/apps/desktop/src/updates/updatesTestHarness.ts +++ b/apps/desktop/src/updates/updatesTestHarness.ts @@ -29,6 +29,11 @@ export interface UpdatesHarnessOptions { readonly setUpdateChannelError?: DesktopAppSettings.DesktopSettingsWriteError; readonly setDisableDifferentialDownload?: Effect.Effect; readonly downloadUpdate?: Effect.Effect; + /** electron-updater's pending cache directory; its files are read from disk. */ + readonly pendingDownloadDirectory?: string; + readonly beforePendingDownloadRead?: Effect.Effect; + /** What electron-updater's provider resolved for the offered release. */ + readonly offeredUpdateFiles?: ElectronUpdater.ElectronUpdaterOfferedFiles; readonly quitAndInstall?: Effect.Effect; readonly stopBackend?: Effect.Effect; readonly startBackend?: Effect.Effect; @@ -36,6 +41,7 @@ export interface UpdatesHarnessOptions { readonly backendInstances?: ReadonlyArray; readonly env?: Record; readonly platform?: NodeJS.Platform; + readonly processArch?: string; readonly packageType?: string | undefined; readonly installRecord?: string | undefined; readonly policy?: DesktopUpdatePolicy.UpdatePolicy; @@ -94,6 +100,10 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { fullChangelog = value; }), setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void, + pendingDownloadDirectory: Effect.succeed( + Option.fromUndefinedOr(options.pendingDownloadDirectory), + ), + offeredUpdateFiles: Effect.succeed(Option.fromUndefinedOr(options.offeredUpdateFiles)), checkForUpdates: Effect.sync(() => { checkCount += 1; checkAllowedDowngrade.push(allowDowngrade); @@ -183,7 +193,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { dirname: "/repo/apps/desktop/src", homeDirectory: `/tmp/t3-desktop-updates-home-${process.pid}`, platform: options.platform ?? "darwin", - processArch: "x64", + processArch: options.processArch ?? "x64", appVersion: options.appVersion ?? "1.2.3", appPath: "/repo", isPackaged: true, @@ -249,46 +259,66 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { let previousInstallRecord = options.installRecord; const isInstallRecord = (path: string) => path.endsWith(DesktopUpdates.DESKTOP_UPDATE_INSTALL_RECORD_FILE); - const layerFileSystem = FileSystem.layerNoop({ - readFileString: (path) => { - const installRecord = isInstallRecord(path) - ? (installRecords.get(path) ?? previousInstallRecord) - : undefined; - if (installRecord !== undefined) return Effect.succeed(installRecord); - return path === "/missing/resources/package-type" && options.packageType !== undefined - ? Effect.succeed(options.packageType) - : Effect.fail( - PlatformError.systemError({ - module: "FileSystem", - method: "readFileString", - _tag: "NotFound", - pathOrDescriptor: path, - }), - ); - }, - makeDirectory: () => Effect.void, - writeFileString: (path, data) => - Effect.sync(() => { - if (isInstallRecord(path)) installRecords.set(path, data); - else { - if (path.endsWith("/desktop-update-restart")) updateRestartMarkers.add(path); - updateMarkerContents.set(path, data); - } - }), - rename: (from, to) => - Effect.sync(() => { - const contents = updateMarkerContents.get(from); - if (contents !== undefined) updateMarkerContents.set(to, contents); - updateMarkerContents.delete(from); - }), - remove: (path) => - Effect.sync(() => { - updateRestartMarkers.delete(path); - updateMarkerContents.delete(path); - installRecords.delete(path); - if (isInstallRecord(path)) previousInstallRecord = undefined; - }), - }); + const pendingDownloadDirectory = options.pendingDownloadDirectory; + // The service joins with the native separator, which is a backslash on Windows runners. + const isPendingDownloadPath = (path: string) => + pendingDownloadDirectory !== undefined && + (path.startsWith(`${pendingDownloadDirectory}/`) || + path.startsWith(`${pendingDownloadDirectory}\\`)); + const layerFileSystem = Layer.effect( + FileSystem.FileSystem, + Effect.gen(function* () { + const disk = yield* FileSystem.FileSystem; + const missing = FileSystem.makeNoop({}); + return FileSystem.makeNoop({ + stream: (path, options) => + isPendingDownloadPath(path) ? disk.stream(path, options) : missing.stream(path, options), + readFileString: (path) => { + if (isPendingDownloadPath(path)) { + return (options.beforePendingDownloadRead ?? Effect.void).pipe( + Effect.andThen(disk.readFileString(path)), + ); + } + const installRecord = isInstallRecord(path) + ? (installRecords.get(path) ?? previousInstallRecord) + : undefined; + if (installRecord !== undefined) return Effect.succeed(installRecord); + return path === "/missing/resources/package-type" && options.packageType !== undefined + ? Effect.succeed(options.packageType) + : Effect.fail( + PlatformError.systemError({ + module: "FileSystem", + method: "readFileString", + _tag: "NotFound", + pathOrDescriptor: path, + }), + ); + }, + makeDirectory: () => Effect.void, + writeFileString: (path, data) => + Effect.sync(() => { + if (isInstallRecord(path)) installRecords.set(path, data); + else { + if (path.endsWith("/desktop-update-restart")) updateRestartMarkers.add(path); + updateMarkerContents.set(path, data); + } + }), + rename: (from, to) => + Effect.sync(() => { + const contents = updateMarkerContents.get(from); + if (contents !== undefined) updateMarkerContents.set(to, contents); + updateMarkerContents.delete(from); + }), + remove: (path) => + Effect.sync(() => { + updateRestartMarkers.delete(path); + updateMarkerContents.delete(path); + installRecords.delete(path); + if (isInstallRecord(path)) previousInstallRecord = undefined; + }), + }); + }), + ).pipe(Layer.provide(NodeServices.layer)); const layer = DesktopUpdates.layer.pipe( Layer.provide(layerFileSystem),