Skip to content

Commit 601e501

Browse files
committed
fix(desktop): preserve AppImages when updates fail
1 parent 061543e commit 601e501

7 files changed

Lines changed: 290 additions & 4 deletions

File tree

Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
// @effect-diagnostics nodeBuiltinImport:off -- Real files exercise the CommonJS updater installation boundary.
2+
import * as NodeCrypto from "node:crypto";
3+
import * as NodeModule from "node:module";
4+
import * as NodeOS from "node:os";
5+
import * as NodePath from "node:path";
6+
7+
import { AppImageUpdater } from "electron-updater/out/AppImageUpdater.js";
8+
import { DownloadedUpdateHelper } from "electron-updater/out/DownloadedUpdateHelper.js";
9+
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
10+
11+
// The dependency uses CommonJS; spy on the same Node modules it loads.
12+
const require = NodeModule.createRequire(import.meta.url);
13+
const fs = require("node:fs") as typeof import("node:fs");
14+
const childProcess = require("node:child_process") as typeof import("node:child_process");
15+
const roots: string[] = [];
16+
const oldBinary = "working AppImage";
17+
const newBinary = "verified replacement AppImage";
18+
19+
class TestUpdater extends AppImageUpdater {
20+
override spawnLog = vi.fn(async () => true);
21+
22+
async prepare(installer: string, sha512: string) {
23+
this.downloadedUpdateHelper = new DownloadedUpdateHelper(NodePath.dirname(installer));
24+
await this.downloadedUpdateHelper.setDownloadedFile(
25+
installer,
26+
null,
27+
{ version: "1.1.0", files: [], path: "", sha512, releaseDate: "2026-09-08" },
28+
{
29+
url: new URL("https://example.com/update.AppImage"),
30+
info: { url: "update.AppImage", sha512 },
31+
},
32+
NodePath.basename(installer),
33+
false,
34+
);
35+
}
36+
}
37+
38+
async function fixture(name = "t3code.AppImage") {
39+
const root = fs.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-appimage-"));
40+
roots.push(root);
41+
const installed = NodePath.join(root, name);
42+
const cache = NodePath.join(root, "cache");
43+
fs.mkdirSync(cache);
44+
const installer = NodePath.join(cache, "T3-Code-1.1.0.AppImage");
45+
fs.writeFileSync(installed, oldBinary, { mode: 0o755 });
46+
fs.writeFileSync(installer, newBinary, { mode: 0o755 });
47+
vi.stubEnv("APPIMAGE", installed);
48+
const updater = new TestUpdater(null, { version: "1.0.0" });
49+
updater.logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
50+
const errors = vi.fn();
51+
updater.on("error", errors);
52+
await updater.prepare(
53+
installer,
54+
NodeCrypto.createHash("sha512").update(newBinary).digest("base64"),
55+
);
56+
return { root, installed, installer, updater, errors };
57+
}
58+
59+
beforeEach(() => vi.useFakeTimers({ toFake: ["setImmediate"] }));
60+
61+
afterEach(() => {
62+
vi.useRealTimers();
63+
vi.restoreAllMocks();
64+
vi.unstubAllEnvs();
65+
for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
66+
});
67+
68+
describe("AppImage installation", () => {
69+
it.each(["empty", "corrupt", "ENOSPC"])(
70+
"preserves the old executable after a %s copy",
71+
async (fault) => {
72+
const { installed, installer, updater, errors, root } = await fixture();
73+
const badCopy = (destination: import("node:fs").PathLike) => {
74+
fs.writeFileSync(destination, fault === "corrupt" ? "x".repeat(newBinary.length) : "");
75+
if (fault === "ENOSPC")
76+
throw Object.assign(new Error("No space left on device"), { code: "ENOSPC" });
77+
};
78+
vi.spyOn(fs, "copyFileSync").mockImplementation((_source, destination) =>
79+
badCopy(destination),
80+
);
81+
// Reproduce the reported successful-but-empty cross-filesystem mv on the unpatched updater.
82+
vi.spyOn(childProcess, "execFileSync").mockImplementation((command, args) => {
83+
if (command !== "mv" || !Array.isArray(args)) throw new Error("Unexpected process launch");
84+
badCopy(String(args[2]));
85+
fs.unlinkSync(installer);
86+
return Buffer.alloc(0);
87+
});
88+
89+
updater.quitAndInstall(true, true);
90+
91+
expect(fs.readFileSync(installed, "utf8")).toBe(oldBinary);
92+
expect(fs.readFileSync(installer, "utf8")).toBe(newBinary);
93+
expect(updater.spawnLog).not.toHaveBeenCalled();
94+
expect(vi.getTimerCount()).toBe(0);
95+
expect(errors).toHaveBeenCalledOnce();
96+
expect(fs.readdirSync(root).sort()).toEqual(["cache", "t3code.AppImage"]);
97+
},
98+
);
99+
100+
it.each(["t3code.AppImage", "T3-Code-1.0.0.AppImage"])(
101+
"atomically installs and relaunches %s",
102+
async (name) => {
103+
const { installed, installer, updater } = await fixture(name);
104+
const destination =
105+
name === "t3code.AppImage"
106+
? installed
107+
: NodePath.join(NodePath.dirname(installed), NodePath.basename(installer));
108+
const rename = fs.renameSync;
109+
const swapped = vi.spyOn(fs, "renameSync").mockImplementation((source, target) => {
110+
expect(fs.readFileSync(installed, "utf8")).toBe(oldBinary);
111+
expect(fs.readFileSync(source, "utf8")).toBe(newBinary);
112+
expect(fs.statSync(source).dev).toBe(fs.statSync(NodePath.dirname(String(target))).dev);
113+
rename(source, target);
114+
});
115+
const renamed = vi.fn();
116+
updater.on("appimage-filename-updated", renamed);
117+
118+
expect(updater.install(true, true)).toBe(true);
119+
120+
expect(swapped).toHaveBeenCalledOnce();
121+
expect(fs.readFileSync(destination, "utf8")).toBe(newBinary);
122+
// eslint-disable-next-line t3code/no-global-process-runtime -- Check permissions on the real fixture filesystem.
123+
if (NodeOS.platform() !== "win32") expect(fs.statSync(destination).mode & 0o777).toBe(0o755);
124+
expect(updater.spawnLog).toHaveBeenCalledWith(
125+
destination,
126+
[],
127+
expect.objectContaining({ APPIMAGE_SILENT_INSTALL: "true" }),
128+
);
129+
expect(renamed.mock.calls).toEqual(destination === installed ? [] : [[destination]]);
130+
},
131+
);
132+
133+
it("keeps the executable and download retryable when the atomic rename fails", async () => {
134+
const { installed, installer, updater, errors } = await fixture();
135+
const rename = vi.spyOn(fs, "renameSync").mockImplementationOnce(() => {
136+
throw Object.assign(new Error("Permission denied"), { code: "EACCES" });
137+
});
138+
139+
updater.quitAndInstall(true, true);
140+
141+
expect(fs.readFileSync(installed, "utf8")).toBe(oldBinary);
142+
expect(fs.readFileSync(installer, "utf8")).toBe(newBinary);
143+
expect(errors).toHaveBeenCalledOnce();
144+
expect(updater.spawnLog).not.toHaveBeenCalled();
145+
expect(vi.getTimerCount()).toBe(0);
146+
rename.mockRestore();
147+
expect(updater.install(true, true)).toBe(true);
148+
expect(fs.readFileSync(installed, "utf8")).toBe(newBinary);
149+
});
150+
});

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import { assert, describe, it } from "@effect/vitest";
22
import * as Effect from "effect/Effect";
3+
import * as Layer from "effect/Layer";
4+
import * as Logger from "effect/Logger";
5+
import * as References from "effect/References";
36
import { beforeEach, vi } from "vite-plus/test";
47

58
const { autoUpdaterMock } = vi.hoisted(() => ({
@@ -11,6 +14,7 @@ const { autoUpdaterMock } = vi.hoisted(() => ({
1114
channel: "latest",
1215
disableDifferentialDownload: false,
1316
fullChangelog: false,
17+
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
1418
checkForUpdates: vi.fn(() => Promise.resolve(null)),
1519
downloadUpdate: vi.fn(() => Promise.resolve([])),
1620
on: vi.fn(),
@@ -27,6 +31,34 @@ vi.mock("electron-updater", () => ({
2731
import * as ElectronUpdater from "./ElectronUpdater.ts";
2832

2933
describe("ElectronUpdater", () => {
34+
it.effect(
35+
"routes updater install logs through desktop observability and restores the logger",
36+
() => {
37+
const previousLogger = autoUpdaterMock.logger;
38+
const records: unknown[] = [];
39+
const logger = Logger.make(({ message, fiber }) => {
40+
records.push({
41+
message,
42+
component: fiber.getRef(References.CurrentLogAnnotations).component,
43+
span: fiber.currentSpan?._tag === "Span" ? fiber.currentSpan.name : undefined,
44+
});
45+
});
46+
return Effect.gen(function* () {
47+
yield* Effect.sync(() => autoUpdaterMock.logger.info("Installed verified AppImage")).pipe(
48+
Effect.provide(ElectronUpdater.layer.pipe(Layer.provide(Logger.layer([logger])))),
49+
);
50+
assert.deepEqual(records, [
51+
{
52+
message: ["Installed verified AppImage"],
53+
component: "desktop-updater",
54+
span: "desktop.updater.log",
55+
},
56+
]);
57+
assert.strictEqual(autoUpdaterMock.logger, previousLogger);
58+
});
59+
},
60+
);
61+
3062
beforeEach(() => {
3163
autoUpdaterMock.allowDowngrade = false;
3264
autoUpdaterMock.allowPrerelease = false;

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

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import * as Scope from "effect/Scope";
66

77
import { autoUpdater } from "electron-updater";
88

9+
import * as DesktopObservability from "../app/DesktopObservability.ts";
10+
911
type AutoUpdater = typeof autoUpdater;
1012

1113
export type ElectronUpdaterFeedUrl = Parameters<AutoUpdater["setFeedURL"]>[0];
@@ -169,4 +171,28 @@ export const make = ElectronUpdater.of({
169171
},
170172
});
171173

172-
export const layer = Layer.succeed(ElectronUpdater, make);
174+
export const layer = Layer.effect(
175+
ElectronUpdater,
176+
Effect.gen(function* () {
177+
const runSync = Effect.runSyncWith(yield* Effect.context<never>());
178+
const logger = DesktopObservability.makeComponentLogger("desktop-updater");
179+
const log = (effect: Effect.Effect<void>) =>
180+
runSync(effect.pipe(Effect.withSpan("desktop.updater.log")));
181+
const previousLogger = autoUpdater.logger;
182+
yield* Effect.acquireRelease(
183+
Effect.sync(() => {
184+
autoUpdater.logger = {
185+
info: (message) => log(logger.logInfo(String(message))),
186+
warn: (message) => log(logger.logWarning(String(message))),
187+
error: (message) => log(logger.logError(String(message))),
188+
debug: (message) => log(logger.logDebug(String(message))),
189+
};
190+
}),
191+
() =>
192+
Effect.sync(() => {
193+
autoUpdater.logger = previousLogger;
194+
}),
195+
);
196+
return make;
197+
}),
198+
);

‎apps/desktop/src/main.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,6 @@ const electronLayer = Layer.mergeAll(
127127
ElectronSafeStorage.layer,
128128
ElectronShell.layer,
129129
ElectronTheme.layer,
130-
ElectronUpdater.layer,
131130
ElectronWindow.layer,
132131
DesktopIpc.layer(Electron.ipcMain),
133132
);
@@ -140,6 +139,7 @@ const desktopFoundationLayer = Layer.mergeAll(
140139
DesktopConnectionCatalogStore.layer.pipe(Layer.provideMerge(DesktopSavedEnvironments.layer)),
141140
DesktopAssets.layer,
142141
DesktopObservability.layer,
142+
ElectronUpdater.layer.pipe(Layer.provide(DesktopObservability.layer)),
143143
).pipe(Layer.provideMerge(desktopEnvironmentLayer));
144144

145145
const desktopSshLayer = desktopSshEnvironmentLayer.pipe(

‎patches/[email protected]‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
diff --git a/out/AppImageUpdater.js b/out/AppImageUpdater.js
2+
index 25cef3598cd278cc2a7f1432377c7a50048824b9..b8427a0e622766755faaa0d616f361e5a284e265 100644
3+
--- a/out/AppImageUpdater.js
4+
+++ b/out/AppImageUpdater.js
5+
@@ -6,6 +6,7 @@ const child_process_1 = require("child_process");
6+
const fs_extra_1 = require("fs-extra");
7+
const fs_1 = require("fs");
8+
const path = require("path");
9+
+const crypto = require("crypto");
10+
const BaseUpdater_1 = require("./BaseUpdater");
11+
const FileWithEmbeddedBlockMapDifferentialDownloader_1 = require("./differentialDownloader/FileWithEmbeddedBlockMapDifferentialDownloader");
12+
const Provider_1 = require("./providers/Provider");
13+
@@ -74,8 +75,6 @@ class AppImageUpdater extends BaseUpdater_1.BaseUpdater {
14+
if (appImageFile == null) {
15+
throw (0, builder_util_runtime_1.newError)("APPIMAGE env is not defined", "ERR_UPDATER_OLD_FILE_NOT_FOUND");
16+
}
17+
- // https://stackoverflow.com/a/1712051/1910191
18+
- (0, fs_1.unlinkSync)(appImageFile);
19+
let destination;
20+
const existingBaseName = path.basename(appImageFile);
21+
const installerPath = this.installerPath;
22+
@@ -92,7 +91,53 @@ class AppImageUpdater extends BaseUpdater_1.BaseUpdater {
23+
else {
24+
destination = path.join(path.dirname(appImageFile), path.basename(installerPath));
25+
}
26+
- (0, child_process_1.execFileSync)("mv", ["-f", installerPath, destination]);
27+
+ // Stage beside the destination: cache and AppImage may be on different filesystems.
28+
+ const stageDir = fs_1.mkdtempSync(path.join(path.dirname(destination), ".t3-update-"));
29+
+ const staged = path.join(stageDir, "update.AppImage");
30+
+ this._logger.info(`Staging AppImage update for ${destination}`);
31+
+ try {
32+
+ const size = fs_1.statSync(installerPath).size;
33+
+ fs_1.copyFileSync(installerPath, staged);
34+
+ if (size === 0 || fs_1.statSync(staged).size !== size) {
35+
+ throw new Error("Staged AppImage size mismatch");
36+
+ }
37+
+ const fd = fs_1.openSync(staged, "r+");
38+
+ try {
39+
+ const hash = crypto.createHash("sha512");
40+
+ const buffer = Buffer.allocUnsafe(1024 * 1024);
41+
+ let bytes;
42+
+ while ((bytes = fs_1.readSync(fd, buffer, 0, buffer.length, null)) > 0) {
43+
+ hash.update(buffer.subarray(0, bytes));
44+
+ }
45+
+ if (hash.digest("base64") !== this.downloadedUpdateHelper.downloadedFileInfo.sha512) {
46+
+ throw new Error("Staged AppImage sha512 mismatch");
47+
+ }
48+
+ fs_1.fchmodSync(fd, 0o755);
49+
+ fs_1.fsyncSync(fd);
50+
+ }
51+
+ finally {
52+
+ fs_1.closeSync(fd);
53+
+ }
54+
+ fs_1.renameSync(staged, destination);
55+
+ this._logger.info(`Installed verified AppImage at ${destination}`);
56+
+ }
57+
+ finally {
58+
+ try {
59+
+ fs_1.rmSync(stageDir, { recursive: true, force: true });
60+
+ }
61+
+ catch (error) {
62+
+ this._logger.warn(`Could not remove AppImage staging directory: ${error}`);
63+
+ }
64+
+ }
65+
+ // Cleanup must not turn a committed replacement into a failed install.
66+
+ for (const obsolete of destination === appImageFile ? [installerPath] : [installerPath, appImageFile]) {
67+
+ try {
68+
+ fs_1.unlinkSync(obsolete);
69+
+ }
70+
+ catch (error) {
71+
+ this._logger.warn(`Could not remove obsolete AppImage ${obsolete}: ${error}`);
72+
+ }
73+
+ }
74+
if (destination !== appImageFile) {
75+
this.emit("appimage-filename-updated", destination);
76+
}

‎pnpm-lock.yaml‎

Lines changed: 3 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎pnpm-workspace.yaml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,7 @@ patchedDependencies:
174174
"@react-navigation/[email protected]": patches/@react-navigation%[email protected]
175175
176176
177+
177178
178179
179180

0 commit comments

Comments
 (0)