Skip to content

Commit d445fdb

Browse files
RakshithBhat03claudejuliusmarminge
authored
fix(desktop): restart prompt returns after relaunching with a downloaded update (#18095)
Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Julius Marminge <[email protected]>
1 parent 3b7d39e commit d445fdb

5 files changed

Lines changed: 480 additions & 14 deletions

File tree

‎apps/desktop/src/electron/ElectronUpdater.test.ts‎

Lines changed: 224 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,27 @@
1+
// @effect-diagnostics nodeBuiltinImport:off -- Build real electron-updater disk fixtures with its SHA-512 encoding.
2+
import * as NodeServices from "@effect/platform-node/NodeServices";
3+
import * as NodeCrypto from "node:crypto";
4+
import * as NodeEvents from "node:events";
5+
import * as NodeModule from "node:module";
6+
import * as NodePath from "node:path";
7+
import * as Deferred from "effect/Deferred";
8+
import * as FileSystem from "effect/FileSystem";
9+
import * as Option from "effect/Option";
10+
import { AppImageUpdater } from "electron-updater/out/AppImageUpdater.js";
11+
import { DebUpdater } from "electron-updater/out/DebUpdater.js";
12+
import { MacUpdater } from "electron-updater/out/MacUpdater.js";
13+
import { GenericProvider } from "electron-updater/out/providers/GenericProvider.js";
14+
import type { UpdateDownloadedEvent } from "electron-updater/out/types.js";
15+
import { NsisUpdater } from "electron-updater/out/NsisUpdater.js";
16+
import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
17+
import { flushCallbacks, makeHarness } from "../updates/updatesTestHarness.ts";
118
import { assert, describe, it } from "@effect/vitest";
219
import * as Effect from "effect/Effect";
320
import type { VerifyUpdateCodeSignature } from "electron-updater";
421
import { beforeEach, vi } from "vite-plus/test";
522

6-
const { autoUpdaterMock } = vi.hoisted(() => ({
23+
const { autoUpdaterMock, updaterOverride } = vi.hoisted(() => ({
24+
updaterOverride: { current: undefined as import("electron-updater").AppUpdater | undefined },
725
autoUpdaterMock: {
826
allowDowngrade: false,
927
allowPrerelease: false,
@@ -24,7 +42,9 @@ const { autoUpdaterMock } = vi.hoisted(() => ({
2442
}));
2543

2644
vi.mock("electron-updater", () => ({
27-
autoUpdater: autoUpdaterMock,
45+
get autoUpdater() {
46+
return updaterOverride.current ?? autoUpdaterMock;
47+
},
2848
}));
2949

3050
import * as ElectronUpdater from "./ElectronUpdater.ts";
@@ -221,3 +241,205 @@ describe("ElectronUpdater", () => {
221241
);
222242
});
223243
});
244+
245+
describe("installed electron-updater cache recovery", () => {
246+
it.effect.each([
247+
{
248+
name: "Intel Mac",
249+
platform: "darwin",
250+
Updater: MacUpdater,
251+
selected: "x64.zip",
252+
other: "arm64.zip",
253+
rosetta: false,
254+
},
255+
{
256+
name: "Apple Silicon running Intel",
257+
platform: "darwin",
258+
Updater: MacUpdater,
259+
selected: "arm64.zip",
260+
other: "x64.zip",
261+
rosetta: true,
262+
},
263+
{
264+
name: "Windows",
265+
platform: "win32",
266+
Updater: NsisUpdater,
267+
selected: "x64.exe",
268+
other: "arm64.exe",
269+
rosetta: false,
270+
},
271+
{
272+
name: "Debian",
273+
platform: "linux",
274+
Updater: DebUpdater,
275+
selected: "x64.deb",
276+
other: "x64.AppImage",
277+
rosetta: false,
278+
},
279+
{
280+
name: "AppImage",
281+
platform: "linux",
282+
Updater: AppImageUpdater,
283+
selected: "x64.AppImage",
284+
other: "x64.deb",
285+
rosetta: false,
286+
},
287+
] as const)("restores only the package selected by $name", (scenario) =>
288+
Effect.scoped(
289+
Effect.gen(function* () {
290+
const fs = yield* FileSystem.FileSystem;
291+
const directory = yield* fs.makeTempDirectoryScoped();
292+
const cacheDirectory = NodePath.join(directory, "custom-updater-cache", "pending");
293+
const configPath = NodePath.join(directory, "app-update.yml");
294+
yield* fs.writeFileString(configPath, "updaterCacheDirName: custom-updater-cache\n");
295+
yield* fs.makeDirectory(cacheDirectory, { recursive: true });
296+
297+
const require = NodeModule.createRequire(import.meta.url);
298+
require("electron");
299+
const electronModule = require.cache[require.resolve("electron")]!;
300+
const childProcess = require("node:child_process") as typeof import("node:child_process");
301+
const originalElectron = electronModule.exports;
302+
const originalArch = Object.getOwnPropertyDescriptor(process, "arch")!;
303+
yield* Effect.acquireRelease(
304+
Effect.sync(() => {
305+
// MacUpdater's native Squirrel bridge and host probes are OS boundaries.
306+
electronModule.exports = { autoUpdater: new NodeEvents.EventEmitter() };
307+
Object.defineProperty(process, "arch", { value: "x64", configurable: true });
308+
return vi
309+
.spyOn(childProcess, "execFileSync")
310+
.mockReturnValue(scenario.rosetta ? "sysctl.proc_translated: 1" : "x86_64");
311+
}),
312+
(probe) =>
313+
Effect.sync(() => {
314+
probe.mockRestore();
315+
Object.defineProperty(process, "arch", originalArch);
316+
electronModule.exports = originalElectron;
317+
updaterOverride.current = undefined;
318+
}),
319+
);
320+
321+
const extensions =
322+
scenario.platform === "darwin"
323+
? ["arm64.dmg", "x64.dmg", "arm64.zip", "x64.zip"]
324+
: scenario.platform === "win32"
325+
? ["arm64.exe", "x64.exe"]
326+
: ["arm64.AppImage", "x64.AppImage", "arm64.deb", "x64.deb"];
327+
const files = extensions.map((extension) => {
328+
const url = `T3-Code-1.2.4-${extension}`;
329+
return { url, sha512: NodeCrypto.createHash("sha512").update(url).digest("base64") };
330+
});
331+
const info = {
332+
version: "1.2.4",
333+
releaseDate: "2026-10-01T00:00:00Z",
334+
files,
335+
path: files[0]!.url,
336+
sha512: files[0]!.sha512,
337+
};
338+
yield* Effect.acquireRelease(
339+
Effect.sync(() =>
340+
vi.spyOn(GenericProvider.prototype, "getLatestVersion").mockResolvedValue(info),
341+
),
342+
(feed) => Effect.sync(() => feed.mockRestore()),
343+
);
344+
345+
// A fresh instance for each launch forces disk validation rather than in-memory reuse.
346+
yield* Effect.forEach([scenario.other, scenario.selected], (cachedExtension) =>
347+
Effect.scoped(
348+
Effect.gen(function* () {
349+
const cached = files.find((file) => file.url.endsWith(`-${cachedExtension}`))!;
350+
yield* fs.writeFileString(NodePath.join(cacheDirectory, cached.url), cached.url);
351+
yield* fs.writeFileString(
352+
NodePath.join(cacheDirectory, "update-info.json"),
353+
JSON.stringify({
354+
fileName: cached.url,
355+
sha512: cached.sha512,
356+
isAdminRightsRequired: false,
357+
}),
358+
);
359+
const updater = new scenario.Updater(undefined, {
360+
version: "1.2.3",
361+
name: "T3 Code",
362+
isPackaged: true,
363+
appUpdateConfigPath: configPath,
364+
userDataPath: directory,
365+
baseCachePath: directory,
366+
whenReady: () => Promise.resolve(),
367+
relaunch: vi.fn(),
368+
quit: vi.fn(),
369+
onQuit: vi.fn(),
370+
});
371+
updater.logger = null;
372+
const networkDownload = vi.fn(() =>
373+
Promise.reject(new Error("unexpected network download")),
374+
);
375+
Object.assign(updater, { httpExecutor: { download: networkDownload } });
376+
if (updater instanceof MacUpdater) {
377+
// Keep real selection, executeDownload, and hash validation; stop at native handoff.
378+
Object.assign(updater, {
379+
updateDownloaded: async (_file: unknown, event: UpdateDownloadedEvent) => {
380+
updater.emit("update-downloaded", event);
381+
return [];
382+
},
383+
});
384+
}
385+
updaterOverride.current = updater;
386+
assert.deepEqual(
387+
yield* ElectronUpdater.make.pendingDownloadDirectory,
388+
Option.some(cacheDirectory),
389+
);
390+
391+
const inspected = Deferred.makeUnsafe<void>();
392+
const downloadFinished = Deferred.makeUnsafe<void>();
393+
const download = vi.spyOn(updater, "downloadUpdate");
394+
const harness = makeHarness({
395+
platform: scenario.platform,
396+
runningUnderArm64Translation: scenario.rosetta,
397+
env: scenario.selected.endsWith("AppImage")
398+
? { APPIMAGE: "/test/T3-Code.AppImage" }
399+
: {},
400+
updater: {
401+
...ElectronUpdater.make,
402+
downloadUpdate: ElectronUpdater.make.downloadUpdate.pipe(
403+
Effect.ensuring(Deferred.succeed(downloadFinished, undefined)),
404+
),
405+
},
406+
fileSystem: {
407+
...fs,
408+
readFileString: (path, encoding) =>
409+
path === "/missing/resources/package-type" && scenario.selected.endsWith("deb")
410+
? Effect.succeed("deb")
411+
: fs.readFileString(path, encoding),
412+
exists: (path) =>
413+
fs.exists(path).pipe(Effect.tap(() => Deferred.succeed(inspected, undefined))),
414+
},
415+
});
416+
yield* Effect.scoped(
417+
Effect.gen(function* () {
418+
const updates = yield* DesktopUpdates.DesktopUpdates;
419+
yield* updates.configure;
420+
// AppImage activation reads the host environment; the fixture is intentionally not installed.
421+
vi.spyOn(updater, "isUpdaterActive").mockReturnValue(true);
422+
assert.isTrue((yield* updates.check("startup")).checked);
423+
yield* Deferred.await(inspected);
424+
yield* flushCallbacks;
425+
426+
if (cachedExtension === scenario.other) {
427+
assert.equal(download.mock.calls.length, 0);
428+
assert.equal((yield* updates.getState).status, "available");
429+
} else {
430+
yield* Deferred.await(downloadFinished);
431+
yield* flushCallbacks;
432+
assert.equal(download.mock.calls.length, 1);
433+
assert.equal((yield* updates.getState).status, "downloaded");
434+
assert.equal((yield* updates.getState).downloadedVersion, "1.2.4");
435+
}
436+
assert.equal(networkDownload.mock.calls.length, 0);
437+
}),
438+
).pipe(Effect.provide(harness.layer));
439+
}),
440+
),
441+
);
442+
}),
443+
).pipe(Effect.provide(NodeServices.layer)),
444+
);
445+
});

‎apps/desktop/src/electron/ElectronUpdater.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import * as Context from "effect/Context";
22
import * as Effect from "effect/Effect";
33
import * as Layer from "effect/Layer";
4+
import * as Option from "effect/Option";
45
import * as Schema from "effect/Schema";
56
import * as Scope from "effect/Scope";
67

@@ -68,6 +69,7 @@ export class ElectronUpdater extends Context.Service<
6869
readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;
6970
readonly setFullChangelog: (value: boolean) => Effect.Effect<void>;
7071
readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>;
72+
readonly pendingDownloadDirectory: Effect.Effect<Option.Option<string>>;
7173
readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>;
7274
readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>;
7375
readonly quitAndInstall: (options: {
@@ -163,6 +165,17 @@ export const make = ElectronUpdater.of({
163165
autoUpdater.disableDifferentialDownload = value;
164166
return Effect.void;
165167
}),
168+
// Use the updater's helper so cache lookup follows the same configuration as downloads.
169+
pendingDownloadDirectory: Effect.tryPromise(() =>
170+
(
171+
autoUpdater as unknown as {
172+
getOrCreateDownloadHelper: () => Promise<{ readonly cacheDirForPendingUpdate: string }>;
173+
}
174+
).getOrCreateDownloadHelper(),
175+
).pipe(
176+
Effect.map((helper) => helper.cacheDirForPendingUpdate),
177+
Effect.option,
178+
),
166179
checkForUpdates: Effect.suspend(() => {
167180
const channel = autoUpdater.channel;
168181
return Effect.tryPromise({

‎apps/desktop/src/updates/DesktopUpdates.test.ts‎

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,116 @@ describe("DesktopUpdates", () => {
273273
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
274274
});
275275

276+
it.effect("reuses an update an earlier launch downloaded once its check finishes", () => {
277+
const releaseCheck = Deferred.makeUnsafe<void>();
278+
const harness = makeHarness({
279+
cachedDownloadSha512: "sha-1.2.4",
280+
// electron-updater reports update-available while the check is running.
281+
checkForUpdates: Effect.sync(() =>
282+
harness.emit("update-available", {
283+
version: "1.2.4",
284+
files: [{ url: "T3-Code-1.2.4.zip", sha512: "sha-1.2.4" }],
285+
}),
286+
).pipe(Effect.andThen(Deferred.await(releaseCheck))),
287+
downloadUpdate: Effect.sync(() => harness.emit("update-downloaded", { version: "1.2.4" })),
288+
});
289+
290+
return Effect.scoped(
291+
Effect.gen(function* () {
292+
const updates = yield* DesktopUpdates.DesktopUpdates;
293+
yield* updates.configure;
294+
295+
const check = yield* Effect.forkChild(updates.check("startup"));
296+
yield* flushCallbacks;
297+
assert.equal(harness.downloadCount(), 0);
298+
assert.equal((yield* updates.getState).status, "available");
299+
300+
yield* Deferred.succeed(releaseCheck, undefined);
301+
yield* Fiber.join(check);
302+
yield* flushCallbacks;
303+
304+
assert.equal(harness.downloadCount(), 1);
305+
const state = yield* updates.getState;
306+
assert.equal(state.status, "downloaded");
307+
assert.equal(state.downloadedVersion, "1.2.4");
308+
}),
309+
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
310+
});
311+
312+
it.effect.each([
313+
{ name: "a newer release", cachedDownloadSha512: "older-release" },
314+
{ name: "an interrupted download", cachedFileExists: false },
315+
{ name: "unfinished metadata", cachedDownloadInfo: "{" },
316+
])("keeps $name click-to-download", (cache) => {
317+
const harness = makeHarness({ cachedDownloadSha512: "release-sha", ...cache });
318+
319+
return Effect.scoped(
320+
Effect.gen(function* () {
321+
const updates = yield* DesktopUpdates.DesktopUpdates;
322+
yield* updates.configure;
323+
harness.emit("update-available", {
324+
version: "1.2.5",
325+
files: [{ url: "T3-Code-1.2.5.zip", sha512: "release-sha" }],
326+
});
327+
yield* flushCallbacks;
328+
329+
assert.equal(harness.downloadCount(), 0);
330+
assert.equal((yield* updates.getState).status, "available");
331+
assert.isTrue((yield* updates.download).accepted);
332+
assert.equal(harness.downloadCount(), 1);
333+
}),
334+
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
335+
});
336+
337+
it.effect.each(["quitting", "newer release", "no longer available"] as const)(
338+
"abandons pending cache recovery after %s",
339+
(change) => {
340+
const releaseCheck = Deferred.makeUnsafe<void>();
341+
const harness = makeHarness({
342+
cachedDownloadSha512: "cached-release",
343+
checkForUpdates: Effect.sync(() =>
344+
harness.emit("update-available", {
345+
version: "1.2.4",
346+
files: [{ url: "T3-Code-1.2.4.zip", sha512: "cached-release" }],
347+
}),
348+
).pipe(Effect.andThen(Deferred.await(releaseCheck))),
349+
});
350+
351+
return Effect.scoped(
352+
Effect.gen(function* () {
353+
const updates = yield* DesktopUpdates.DesktopUpdates;
354+
yield* updates.configure;
355+
const check = yield* Effect.forkChild(updates.check("startup"));
356+
yield* flushCallbacks;
357+
assert.equal((yield* updates.getState).status, "available");
358+
assert.equal(harness.downloadCount(), 0);
359+
360+
if (change === "quitting") {
361+
const desktop = yield* DesktopState.DesktopState;
362+
yield* Ref.set(desktop.quitting, true);
363+
} else if (change === "newer release") {
364+
harness.emit("update-available", {
365+
version: "1.2.5",
366+
files: [{ url: "T3-Code-1.2.5.zip", sha512: "new-release" }],
367+
});
368+
} else {
369+
harness.emit("update-not-available");
370+
}
371+
yield* flushCallbacks;
372+
yield* Deferred.succeed(releaseCheck, undefined);
373+
yield* Fiber.join(check);
374+
yield* flushCallbacks;
375+
376+
assert.equal(harness.downloadCount(), 0);
377+
assert.equal(
378+
(yield* updates.getState).status,
379+
change === "no longer available" ? "up-to-date" : "available",
380+
);
381+
}),
382+
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
383+
},
384+
);
385+
276386
it.effect("preserves a queued installer when the feed has no update", () => {
277387
const harness = makeHarness();
278388

0 commit comments

Comments
 (0)