Skip to content

Commit 1b762c8

Browse files
TonybynMp4claude
andcommitted
fix(desktop): report updater install failures on the first click
- electron-updater emits `error` and returns instead of throwing when an install check fails, so quitAndInstall now captures that event as its own failure and the global error listener skips it - Log a fixed reason for the known pre-install checks, and `no-new-privs` when an installer command fails in a Linux process that can't gain root Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 3d243ef commit 1b762c8

5 files changed

Lines changed: 227 additions & 28 deletions

File tree

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

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ const { autoUpdaterMock } = vi.hoisted(() => ({
1414
checkForUpdates: vi.fn(() => Promise.resolve(null)),
1515
downloadUpdate: vi.fn(() => Promise.resolve([])),
1616
on: vi.fn(),
17+
prependListener: vi.fn(),
1718
quitAndInstall: vi.fn(),
1819
removeListener: vi.fn(),
1920
setFeedURL: vi.fn(),
@@ -40,6 +41,7 @@ describe("ElectronUpdater", () => {
4041
autoUpdaterMock.downloadUpdate.mockClear();
4142
autoUpdaterMock.downloadUpdate.mockImplementation(() => Promise.resolve([]));
4243
autoUpdaterMock.on.mockClear();
44+
autoUpdaterMock.prependListener.mockClear();
4345
autoUpdaterMock.quitAndInstall.mockClear();
4446
autoUpdaterMock.removeListener.mockClear();
4547
autoUpdaterMock.setFeedURL.mockClear();
@@ -136,4 +138,42 @@ describe("ElectronUpdater", () => {
136138
assert.deepEqual(autoUpdaterMock.quitAndInstall.mock.calls, [[true, false]]);
137139
}).pipe(Effect.provide(ElectronUpdater.layer)),
138140
);
141+
142+
it.effect("fails quit-and-install with an error the updater emits during the call", () =>
143+
Effect.gen(function* () {
144+
const cause = new Error("No update filepath provided, can't quit and install");
145+
const otherError = new Error("background check failed");
146+
const errorListener = vi.fn();
147+
autoUpdaterMock.quitAndInstall.mockImplementationOnce(() => {
148+
const [eventName, captureInstallError] = autoUpdaterMock.prependListener.mock.calls[0] as [
149+
string,
150+
(error: unknown) => void,
151+
];
152+
assert.equal(eventName, "error");
153+
captureInstallError(cause);
154+
});
155+
const updater = yield* ElectronUpdater.ElectronUpdater;
156+
157+
const error = yield* Effect.scoped(
158+
Effect.gen(function* () {
159+
yield* updater.on("error", errorListener);
160+
const [, registeredListener] = autoUpdaterMock.on.mock.calls[0] as [
161+
string,
162+
(error: unknown) => void,
163+
];
164+
const error = yield* updater
165+
.quitAndInstall({ isSilent: true, isForceRunAfter: true })
166+
.pipe(Effect.flip);
167+
registeredListener(cause);
168+
registeredListener(otherError);
169+
return error;
170+
}),
171+
);
172+
173+
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterQuitAndInstallError);
174+
assert.strictEqual(error.cause, cause);
175+
assert.deepEqual(errorListener.mock.calls, [[otherError]]);
176+
assert.equal(autoUpdaterMock.removeListener.mock.calls[0]?.[0], "error");
177+
}).pipe(Effect.provide(ElectronUpdater.layer)),
178+
);
139179
});

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

Lines changed: 44 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,18 @@ export class ElectronUpdater extends Context.Service<
8080
}
8181
>()("@t3tools/desktop/electron/ElectronUpdater") {}
8282

83+
type UpdaterListener = (...args: Array<unknown>) => void;
84+
// autoUpdater is a lazy getter that loads the platform updater on first access.
85+
const updaterEvents = () =>
86+
autoUpdater as unknown as {
87+
on: (eventName: string, listener: UpdaterListener) => void;
88+
prependListener: (eventName: string, listener: UpdaterListener) => void;
89+
removeListener: (eventName: string, listener: UpdaterListener) => void;
90+
};
91+
92+
// Errors that quitAndInstall captured and reports itself.
93+
const installErrors = new WeakSet<object>();
94+
8395
/** @public Service construction is part of the canonical Effect module API. */
8496
export const make = ElectronUpdater.of({
8597
setFeedURL: (options) =>
@@ -140,30 +152,45 @@ export const make = ElectronUpdater.of({
140152
quitAndInstall: ({ isSilent, isForceRunAfter }) =>
141153
Effect.suspend(() => {
142154
const channel = autoUpdater.channel;
143-
return Effect.try({
144-
try: () => autoUpdater.quitAndInstall(isSilent, isForceRunAfter),
145-
catch: (cause) =>
146-
new ElectronUpdaterQuitAndInstallError({
147-
channel,
148-
isSilent,
149-
isForceRunAfter,
150-
cause,
151-
}),
152-
});
155+
const fail = (cause: unknown) =>
156+
Effect.fail(
157+
new ElectronUpdaterQuitAndInstallError({ channel, isSilent, isForceRunAfter, cause }),
158+
);
159+
// electron-updater reports most install failures by emitting `error`
160+
// synchronously and returning instead of throwing. Capture those as this
161+
// call's failure so the caller can report it before returning.
162+
const reported: Array<unknown> = [];
163+
const captureInstallError = (error: unknown) => {
164+
reported.push(error);
165+
if (error instanceof Object) installErrors.add(error);
166+
};
167+
updaterEvents().prependListener("error", captureInstallError);
168+
try {
169+
autoUpdater.quitAndInstall(isSilent, isForceRunAfter);
170+
} catch (cause) {
171+
return fail(cause);
172+
} finally {
173+
updaterEvents().removeListener("error", captureInstallError);
174+
}
175+
return reported.length > 0 ? fail(reported[0]) : Effect.void;
153176
}),
154177
on: (eventName, listener) => {
155-
const eventTarget = autoUpdater as unknown as {
156-
on: (eventName: string, listener: (...args: Array<unknown>) => void) => void;
157-
removeListener: (eventName: string, listener: (...args: Array<unknown>) => void) => void;
158-
};
159-
const untypedListener = listener as unknown as (...args: Array<unknown>) => void;
178+
const untypedListener = listener as unknown as UpdaterListener;
179+
// quitAndInstall already reports the errors it captured.
180+
const filteredListener =
181+
eventName === "error"
182+
? (error: unknown, ...rest: Array<unknown>) => {
183+
if (error instanceof Object && installErrors.has(error)) return;
184+
untypedListener(error, ...rest);
185+
}
186+
: untypedListener;
160187
return Effect.acquireRelease(
161188
Effect.sync(() => {
162-
eventTarget.on(eventName, untypedListener);
189+
updaterEvents().on(eventName, filteredListener);
163190
}),
164191
() =>
165192
Effect.sync(() => {
166-
eventTarget.removeListener(eventName, untypedListener);
193+
updaterEvents().removeListener(eventName, filteredListener);
167194
}),
168195
).pipe(Effect.asVoid);
169196
},

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

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -661,6 +661,102 @@ describe("DesktopUpdates", () => {
661661
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
662662
});
663663

664+
it.effect("reports a failed install check on the first install click", () => {
665+
const harness = makeHarness({
666+
quitAndInstall: Effect.fail(
667+
new ElectronUpdater.ElectronUpdaterQuitAndInstallError({
668+
channel: "latest",
669+
isSilent: true,
670+
isForceRunAfter: true,
671+
cause: new Error("No update filepath provided, can't quit and install"),
672+
}),
673+
),
674+
});
675+
const loggedAnnotations: Array<Record<string, unknown>> = [];
676+
const logger = Logger.make(({ fiber }) => {
677+
const annotations = fiber.getRef(References.CurrentLogAnnotations);
678+
if (annotations.errorTag === "ElectronUpdaterQuitAndInstallError") {
679+
loggedAnnotations.push(annotations);
680+
}
681+
});
682+
683+
return Effect.scoped(
684+
Effect.gen(function* () {
685+
const updates = yield* DesktopUpdates.DesktopUpdates;
686+
yield* updates.configure;
687+
harness.emit("update-downloaded", { version: "1.2.4" });
688+
yield* flushCallbacks;
689+
690+
const result = yield* updates.install;
691+
assert.isTrue(result.accepted);
692+
assert.isFalse(result.completed);
693+
assert.equal(result.state.errorContext, "install");
694+
assert.isNotNull(result.state.message);
695+
assert.equal(loggedAnnotations.at(-1)?.reason, "no-installer-path");
696+
}),
697+
).pipe(
698+
Effect.provide(
699+
Layer.mergeAll(
700+
TestClock.layer(),
701+
harness.layer,
702+
Logger.layer([logger], { mergeWithExisting: false }),
703+
),
704+
),
705+
);
706+
});
707+
708+
it.effect("blames no_new_privs when a Linux installer command fails under it", () =>
709+
Effect.gen(function* () {
710+
const loggedReason = (noNewPrivs: 0 | 1) => {
711+
const harness = makeHarness({
712+
platform: "linux",
713+
packageType: "deb",
714+
procSelfStatus: `Name:\tt3code\nNoNewPrivs:\t${noNewPrivs}\nSeccomp:\t0\n`,
715+
quitAndInstall: Effect.fail(
716+
new ElectronUpdater.ElectronUpdaterQuitAndInstallError({
717+
channel: "latest",
718+
isSilent: true,
719+
isForceRunAfter: true,
720+
cause: new Error("Command pkexec exited with code 127"),
721+
}),
722+
),
723+
});
724+
const loggedAnnotations: Array<Record<string, unknown>> = [];
725+
const logger = Logger.make(({ fiber }) => {
726+
const annotations = fiber.getRef(References.CurrentLogAnnotations);
727+
if (annotations.errorTag === "ElectronUpdaterQuitAndInstallError") {
728+
loggedAnnotations.push(annotations);
729+
}
730+
});
731+
return Effect.scoped(
732+
Effect.gen(function* () {
733+
const updates = yield* DesktopUpdates.DesktopUpdates;
734+
yield* updates.configure;
735+
harness.emit("update-downloaded", { version: "1.2.4" });
736+
yield* flushCallbacks;
737+
yield* updates.install;
738+
return loggedAnnotations.at(-1);
739+
}),
740+
).pipe(
741+
Effect.provide(
742+
Layer.mergeAll(
743+
TestClock.layer(),
744+
harness.layer,
745+
Logger.layer([logger], { mergeWithExisting: false }),
746+
),
747+
),
748+
);
749+
};
750+
751+
const flagged = yield* loggedReason(1);
752+
assert.equal(flagged?.reason, "no-new-privs");
753+
assert.equal(flagged?.exitStatus, 127);
754+
const unflagged = yield* loggedReason(0);
755+
assert.isUndefined(unflagged?.reason);
756+
assert.equal(unflagged?.exitStatus, 127);
757+
}),
758+
);
759+
664760
it.effect("holds the install reservation until failed-install recovery finishes", () => {
665761
const recoveryStarted = Deferred.makeUnsafe<void>();
666762
const releaseRecovery = Deferred.makeUnsafe<void>();

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

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -196,17 +196,30 @@ const {
196196
logError: logUpdaterError,
197197
} = DesktopObservability.makeComponentLogger("desktop-updater");
198198

199+
// Fixed electron-updater messages for install checks that fail before any
200+
// installer command runs. These errors carry no code or exit status.
201+
const UPDATER_INSTALL_FAILURE_REASONS = [
202+
["No update filepath provided", "no-installer-path"],
203+
["Neither dpkg nor apt command found", "no-package-manager"],
204+
] as const;
205+
199206
// electron-updater messages can embed the feed or download URL, credentials
200207
// included, so an updater failure logs only these bounded fields of its cause:
201-
// the error code (`ERR_UPDATER_*`, `HTTP_ERROR_404`, `ENOTFOUND`) and the exit
202-
// status of a failed installer command such as a dismissed pkexec prompt.
208+
// the error code (`ERR_UPDATER_*`, `HTTP_ERROR_404`, `ENOTFOUND`), the exit
209+
// status of a failed installer command such as a dismissed pkexec prompt, and
210+
// a fixed reason for known install checks.
203211
function describeUpdaterFailureCause(cause: unknown): {
204212
readonly errorCode?: string;
205213
readonly exitStatus?: number;
214+
readonly reason?: string;
206215
} {
207216
if (!(cause instanceof Error)) return {};
208217
const exitStatus = / exited with code (\d{1,3})$/.exec(cause.message)?.[1];
218+
const reason = UPDATER_INSTALL_FAILURE_REASONS.find(([prefix]) =>
219+
cause.message.startsWith(prefix),
220+
)?.[1];
209221
return {
222+
...(reason ? { reason } : {}),
210223
...("code" in cause &&
211224
typeof cause.code === "string" &&
212225
/^[A-Z][A-Z0-9_]{0,63}$/.test(cause.code)
@@ -343,6 +356,17 @@ export const make = Effect.gen(function* () {
343356
}),
344357
);
345358

359+
// A Linux process with the no_new_privs flag can never gain root through
360+
// pkexec or sudo, and the flag is permanent. Chromium sets it on processes
361+
// that app.relaunch() starts.
362+
const hasNoNewPrivs =
363+
environment.platform === "linux"
364+
? fileSystem.readFileString("/proc/self/status", "utf-8").pipe(
365+
Effect.map((status) => /^NoNewPrivs:\s*1$/m.test(status)),
366+
Effect.orElseSucceed(() => false),
367+
)
368+
: Effect.succeed(false);
369+
346370
const readAppUpdateYml = fileSystem.readFileString(environment.appUpdateYmlPath, "utf-8").pipe(
347371
Effect.option,
348372
Effect.flatMap(
@@ -675,12 +699,20 @@ export const make = Effect.gen(function* () {
675699
ElectronUpdaterQuitAndInstallError: Effect.fn("desktop.updates.handleInstallFailure")(
676700
function* (error) {
677701
yield* recoverFailedInstall(error.message);
702+
const causeContext = describeUpdaterFailureCause(error.cause);
703+
// An installer command that exits under no_new_privs failed to
704+
// get root, whatever the command printed.
705+
const reason =
706+
causeContext.exitStatus !== undefined && (yield* hasNoNewPrivs)
707+
? "no-new-privs"
708+
: causeContext.reason;
678709
yield* logUpdaterError(error.message, {
679710
errorTag: error._tag,
680711
channel: error.channel,
681712
isSilent: error.isSilent,
682713
isForceRunAfter: error.isForceRunAfter,
683-
...describeUpdaterFailureCause(error.cause),
714+
...causeContext,
715+
...(reason ? { reason } : {}),
684716
});
685717
return { accepted: true, completed: false, failed: true };
686718
},

‎apps/desktop/src/updates/updatesTestHarness.ts‎

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ export interface UpdatesHarnessOptions {
3737
readonly platform?: NodeJS.Platform;
3838
/** Contents of the resources/package-type marker a Linux package ships. */
3939
readonly packageType?: string | undefined;
40+
/** Contents of /proc/self/status. */
41+
readonly procSelfStatus?: string | undefined;
4042
}
4143

4244
export function makeHarness(options: UpdatesHarnessOptions = {}) {
@@ -215,14 +217,16 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
215217
readFileString: (path) =>
216218
path === "/missing/resources/package-type" && options.packageType !== undefined
217219
? Effect.succeed(options.packageType)
218-
: Effect.fail(
219-
PlatformError.systemError({
220-
module: "FileSystem",
221-
method: "readFileString",
222-
_tag: "NotFound",
223-
pathOrDescriptor: path,
224-
}),
225-
),
220+
: path === "/proc/self/status" && options.procSelfStatus !== undefined
221+
? Effect.succeed(options.procSelfStatus)
222+
: Effect.fail(
223+
PlatformError.systemError({
224+
module: "FileSystem",
225+
method: "readFileString",
226+
_tag: "NotFound",
227+
pathOrDescriptor: path,
228+
}),
229+
),
226230
makeDirectory: () => Effect.void,
227231
writeFileString: (path) =>
228232
Effect.sync(() => {

0 commit comments

Comments
 (0)