Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopUpdates.ts

1,112 lines41.4 KB

1import {
2 DESKTOP_UPDATE_RESTART_MARKER_FILE,
3 DesktopUpdateChannelSchema,
4 type DesktopRuntimeInfo,
5 type DesktopUpdateActionResult,
6 type DesktopUpdateChannel,
7 type DesktopUpdateCheckResult,
8 type DesktopUpdateState,
9} from "@t3tools/contracts";
10import { errorTag } from "@t3tools/shared/observability";
11import * as Cause from "effect/Cause";
12import * as Context from "effect/Context";
13import * as DateTime from "effect/DateTime";
14import * as Duration from "effect/Duration";
15import * as Effect from "effect/Effect";
16import * as Exit from "effect/Exit";
17import * as FileSystem from "effect/FileSystem";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as PubSub from "effect/PubSub";
21import * as Ref from "effect/Ref";
22import * as Schema from "effect/Schema";
23import * as Scope from "effect/Scope";
24import * as Semaphore from "effect/Semaphore";
25import * as Stream from "effect/Stream";
26​
27import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
28import * as DesktopConfig from "../app/DesktopConfig.ts";
29import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
30import * as DesktopObservability from "../app/DesktopObservability.ts";
31import * as DesktopState from "../app/DesktopState.ts";
32import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
33import * as ElectronWindow from "../electron/ElectronWindow.ts";
34import * as IpcChannels from "../ipc/channels.ts";
35import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
36import { normalizeDesktopUpdateReleaseNotes } from "./releaseNotes.ts";
37import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
38import {
39 createInitialDesktopUpdateState,
40 reduceDesktopUpdateStateOnCheckFailure,
41 reduceDesktopUpdateStateOnCheckStart,
42 reduceDesktopUpdateStateOnDownloadComplete,
43 reduceDesktopUpdateStateOnDownloadFailure,
44 reduceDesktopUpdateStateOnDownloadProgress,
45 reduceDesktopUpdateStateOnDownloadStart,
46 reduceDesktopUpdateStateOnInstallFailure,
47 reduceDesktopUpdateStateOnNoUpdate,
48 reduceDesktopUpdateStateOnUpdateAvailable,
49} from "./updateMachine.ts";
50​
51const AUTO_UPDATE_STARTUP_DELAY = "15 seconds";
52const AUTO_UPDATE_POLL_INTERVAL = "4 minutes";
53const PREPARED_INSTALL_CHECK_WAIT = Duration.seconds(90);
54​
55type UpdateAction = "check" | "download" | "install" | "install-recovery" | "channel";
56​
57interface DesktopPreparedUpdateInstallResult extends DesktopUpdateActionResult {
58 readonly failed: boolean;
60​
61const AppUpdateYmlConfig = Schema.Record(Schema.String, Schema.String);
62type AppUpdateYmlConfig = typeof AppUpdateYmlConfig.Type;
63​
64const UpdateInfo = Schema.Struct({
65 version: Schema.String,
66 // Left unvalidated on purpose: a malformed release-notes payload must never
67 // fail the decode and block the update state transition. The shape is
68 // validated defensively in normalizeDesktopUpdateReleaseNotes.
69 releaseNotes: Schema.optional(Schema.Unknown),
70});
71​
72const DownloadProgressInfo = Schema.Struct({
73 percent: Schema.Number,
74});
75const decodeAppUpdateYmlConfig = Schema.decodeUnknownEffect(AppUpdateYmlConfig);
76const decodeUpdateInfo = Schema.decodeUnknownEffect(UpdateInfo);
77const decodeDownloadProgressInfo = Schema.decodeUnknownEffect(DownloadProgressInfo);
78​
79const currentIsoTimestamp = DateTime.now.pipe(Effect.map(DateTime.formatIso));
80​
81export class DesktopUpdateActionInProgressError extends Schema.TaggedError<DesktopUpdateActionInProgressError>()(
82 "DesktopUpdateActionInProgressError",
83 {
84 action: Schema.Literals(["check", "download", "install", "channel"]),
85 requestedChannel: DesktopUpdateChannelSchema,
86 },
87) {
88 override get message(): string {
89 return `Cannot change the desktop update channel to ${this.requestedChannel} while an update ${this.action} action is in progress.`;
90 }
92​
93export class DesktopUpdateChannelPersistenceError extends Schema.TaggedError<DesktopUpdateChannelPersistenceError>()(
94 "DesktopUpdateChannelPersistenceError",
95 {
96 channel: DesktopUpdateChannelSchema,
97 cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
98 },
99) {
100 override get message(): string {
101 return `Failed to persist the ${this.channel} desktop update channel.`;
102 }
104​
105export class DesktopUpdatePollerError extends Schema.TaggedError<DesktopUpdatePollerError>()(
106 "DesktopUpdatePollerError",
107 {
108 poller: Schema.Literals(["startup", "poll"]),
109 cause: Schema.Defect(),
110 },
111) {
112 override get message(): string {
113 return `Desktop update ${this.poller} poller failed.`;
114 }
116​
117export class DesktopUpdateEventHandlingError extends Schema.TaggedError<DesktopUpdateEventHandlingError>()(
118 "DesktopUpdateEventHandlingError",
119 {
120 event: Schema.Literals(["update-available", "download-progress", "update-downloaded"]),
121 cause: Schema.Defect(),
122 },
123) {
124 override get message(): string {
125 return `Failed to handle desktop update ${this.event} event.`;
126 }
128​
129export class DesktopUpdaterReportedError extends Schema.TaggedError<DesktopUpdaterReportedError>()(
130 "DesktopUpdaterReportedError",
131 {
132 operation: Schema.Literals(["check", "download", "install", "channel", "background"]),
133 cause: Schema.Defect(),
134 },
135) {
136 override get message(): string {
137 return `Desktop updater ${this.operation} operation reported an error.`;
138 }
140​
141export class DesktopUpdateUnexpectedActionError extends Schema.TaggedError<DesktopUpdateUnexpectedActionError>()(
142 "DesktopUpdateUnexpectedActionError",
143 {
144 action: Schema.Literals(["download", "install"]),
145 cause: Schema.Defect(),
146 },
147) {
148 override get message(): string {
149 return `Desktop update ${this.action} action failed unexpectedly.`;
150 }
152​
153export type DesktopUpdateConfigureError = never;
154​
155export const DesktopUpdateSetChannelError = Schema.Union([
156 DesktopUpdateActionInProgressError,
157 DesktopUpdateChannelPersistenceError,
158]);
159export type DesktopUpdateSetChannelError = typeof DesktopUpdateSetChannelError.Type;
160​
161export class DesktopUpdates extends Context.Service<
162 DesktopUpdates,
163 {
164 readonly getState: Effect.Effect<DesktopUpdateState>;
165 /** True while a check, download, install, or channel change holds the
166 updater's single action reservation. */
167 readonly isActionActive: Effect.Effect<boolean>;
168 /** True only while an install owns the updater action reservation. */
169 readonly isInstallActive: Effect.Effect<boolean>;
170 /** Current state plus a stream of every later state change. */
171 readonly subscribe: Effect.Effect<
172 {
173 readonly latest: DesktopUpdateState;
174 readonly changes: Stream.Stream<DesktopUpdateState>;
175 },
176 never,
177 Scope.Scope
178 >;
179 readonly emitState: Effect.Effect<void>;
180 readonly disabledReason: Effect.Effect<Option.Option<string>>;
181 readonly configure: Effect.Effect<void, DesktopUpdateConfigureError, Scope.Scope>;
182 readonly setChannel: (
183 channel: DesktopUpdateChannel,
184 ) => Effect.Effect<DesktopUpdateState, DesktopUpdateSetChannelError>;
185 readonly check: (reason: string) => Effect.Effect<DesktopUpdateCheckResult>;
186 readonly download: Effect.Effect<DesktopUpdateActionResult>;
187 readonly install: Effect.Effect<DesktopUpdateActionResult>;
188 readonly installPrepared: (
189 expectedVersion: string,
190 ) => Effect.Effect<DesktopPreparedUpdateInstallResult>;
191 }
192>()("@t3tools/desktop/updates/DesktopUpdates") {}
193​
194const {
195 logInfo: logUpdaterInfo,
196 logWarning: logUpdaterWarning,
197 logError: logUpdaterError,
198} = DesktopObservability.makeComponentLogger("desktop-updater");
199​
200function redactMessage(message: string): string {
201 // Updater HTTP errors append response bodies and headers after the first line.
202 return (message.split(/[\r\n]/, 1)[0] ?? "")
203 .replace(/\b(?:https?|file):\/\/[^\s"'<>]+/gi, "[redacted URL]")
204 .replace(/\b(?:Bearer|Basic)\s+[^\s,;]+/gi, "[redacted credential]")
205 .replace(
206 /\b(?:authorization|proxy-authorization|cookie|set-cookie)\s*[:=].*$/gi,
207 "[redacted header]",
208 )
209 .replace(
210 /\b[\w-]*(?:token|password|secret|credential|api[_-]?key)[\w-]*\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi,
211 "[redacted credential]",
212 )
213 .slice(0, 512);
215​
216function summarizeCause(cause: unknown, depth: number): string {
217 if (depth >= 3) return "[truncated cause]";
218 if (Cause.isCause(cause)) {
219 return cause.reasons
220 .slice(0, 3)
221 .map((reason) =>
222 reason._tag === "Fail"
223 ? summarizeCause(reason.error, depth + 1)
224 : reason._tag === "Die"
225 ? summarizeCause(reason.defect, depth + 1)
226 : "Interrupted",
227 )
228 .join("; ");
229 }
230 if (typeof cause === "string") return redactMessage(cause);
231 if (typeof cause !== "object" || cause === null) return errorTag(cause);
232​
233 const error = cause as {
234 readonly message?: unknown;
235 readonly code?: unknown;
236 readonly cause?: unknown;
237 };
238 const code =
239 typeof error.code === "string" && /^[A-Z][A-Z0-9_]{0,127}$/.test(error.code)
240 ? ` [${error.code}]`
241 : "";
242 const message = typeof error.message === "string" ? `: ${redactMessage(error.message)}` : "";
243 const nested =
244 error.cause === undefined ? "" : `; caused by ${summarizeCause(error.cause, depth + 1)}`;
245 return `${errorTag(cause)}${code}${message}${nested}`;
247​
248/** Log a bounded cause summary without stacks, response payloads, or request credentials. */
249export function describeUpdateErrorCause(cause: unknown): string {
250 try {
251 return summarizeCause(cause, 0).slice(0, 1024);
252 } catch {
253 return "UnknownError";
254 }
256​
257function parseAppUpdateYml(raw: string): Effect.Effect<Option.Option<AppUpdateYmlConfig>> {
258 const entries: Record<string, string> = {};
259 for (const line of raw.split("\n")) {
260 const match = line.match(/^(\w+):\s*(.+)$/);
261 if (match?.[1] && match[2]) {
262 entries[match[1]] = match[2].trim();
263 }
264 }
265​
266 return decodeAppUpdateYmlConfig(entries).pipe(
267 Effect.map((config) => (config.provider ? Option.some(config) : Option.none())),
268 Effect.orElseSucceed(() => Option.none<AppUpdateYmlConfig>()),
269 );
271​
272function createBaseUpdateState(
273 channel: DesktopUpdateChannel,
274 enabled: boolean,
275 environment: DesktopEnvironment.DesktopEnvironment["Service"],
276): DesktopUpdateState {
277 return {
278 ...createInitialDesktopUpdateState(environment.appVersion, environment.runtimeInfo, channel),
279 enabled,
280 status: enabled ? "idle" : "disabled",
281 };
283​
284function getCanRetryFromState(state: DesktopUpdateState): boolean {
285 return state.availableVersion !== null || state.downloadedVersion !== null;
287​
288function shouldBroadcastDownloadProgress(
289 currentState: DesktopUpdateState,
290 nextPercent: number,
291): boolean {
292 if (currentState.status !== "downloading") {
293 return true;
294 }
295​
296 const currentPercent = currentState.downloadPercent;
297 if (currentPercent === null) {
298 return true;
299 }
300​
301 const previousStep = Math.floor(currentPercent / 10);
302 const nextStep = Math.floor(nextPercent / 10);
303 return nextStep !== previousStep || nextPercent === 100;
305​
306function getAutoUpdateDisabledReason(args: {
307 isDevelopment: boolean;
308 isPackaged: boolean;
309 platform: NodeJS.Platform;
310 appImage?: string | undefined;
311 isDebPackage: boolean;
312 disabledByEnv: boolean;
313 hasUpdateFeedConfig: boolean;
314}): string | null {
315 if (!args.hasUpdateFeedConfig) {
316 return "Automatic updates are not available because no update feed is configured.";
317 }
318 if (args.isDevelopment || !args.isPackaged) {
319 return "Automatic updates are only available in packaged production builds.";
320 }
321 if (args.disabledByEnv) {
322 return "Automatic updates are disabled by the T3CODE_DISABLE_AUTO_UPDATE setting.";
323 }
324 if (args.platform === "linux" && !args.appImage && !args.isDebPackage) {
325 return "Automatic updates on Linux require the AppImage or the .deb package.";
326 }
327 return null;
329​
330function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean {
331 return runtimeInfo.hostArch === "arm64" && runtimeInfo.appArch === "x64";
333​
334/** @public Service construction is part of the canonical Effect module API. */
335export const make = Effect.gen(function* () {
336 const config = yield* DesktopConfig.DesktopConfig;
337 const pool = yield* DesktopBackendPool.DesktopBackendPool;
338 const desktopState = yield* DesktopState.DesktopState;
339 const electronUpdater = yield* ElectronUpdater.ElectronUpdater;
340 const electronWindow = yield* ElectronWindow.ElectronWindow;
341 const environment = yield* DesktopEnvironment.DesktopEnvironment;
342 const fileSystem = yield* FileSystem.FileSystem;
343 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
344​
345 const appUpdateYmlConfigRef = yield* Ref.make<Option.Option<AppUpdateYmlConfig>>(Option.none());
346 const activeUpdateActionRef = yield* Ref.make<Option.Option<UpdateAction>>(Option.none());
347 const finishedUpdateActions = yield* PubSub.unbounded<UpdateAction>();
348 const updaterConfiguredRef = yield* Ref.make(false);
349 const lastLoggedDownloadMilestoneRef = yield* Ref.make(-1);
350 const updateStateRef = yield* Ref.make<DesktopUpdateState>(
351 createInitialDesktopUpdateState(
352 environment.appVersion,
353 environment.runtimeInfo,
354 environment.defaultDesktopSettings.updateChannel,
355 ),
356 );
357​
358 const stateChanges = yield* PubSub.sliding<DesktopUpdateState>(16);
359 // Makes ref writes + publishes atomic against subscribe, so a snapshot
360 // never overlaps with the first change a subscriber receives.
361 const stateMutex = yield* Semaphore.make(1);
362​
363 const emitState = Ref.get(updateStateRef).pipe(
364 Effect.flatMap((state) => electronWindow.sendAll(IpcChannels.UPDATE_STATE_CHANNEL, state)),
365 );
366​
367 const setState = (state: DesktopUpdateState): Effect.Effect<void> =>
368 stateMutex
369 .withPermits(1)(
370 Ref.set(updateStateRef, state).pipe(Effect.andThen(PubSub.publish(stateChanges, state))),
371 )
372 .pipe(Effect.andThen(emitState));
373​
374 const updateState = (
375 f: (state: DesktopUpdateState) => DesktopUpdateState,
376 ): Effect.Effect<DesktopUpdateState> =>
377 Ref.get(updateStateRef).pipe(
378 Effect.flatMap((state) => {
379 const nextState = f(state);
380 return setState(nextState).pipe(Effect.as(nextState));
381 }),
382 );
383​
384 const readAppUpdateYml = fileSystem.readFileString(environment.appUpdateYmlPath, "utf-8").pipe(
385 Effect.option,
386 Effect.flatMap(
387 Option.match({
388 onNone: () => Effect.succeed(Option.none<AppUpdateYmlConfig>()),
389 onSome: parseAppUpdateYml,
390 }),
391 ),
392 );
393​
394 // The .deb carries electron-builder's resources/package-type marker.
395 // electron-updater reads the same file and installs updates with dpkg.
396 const isDebPackage =
397 environment.platform === "linux" && environment.isPackaged
398 ? yield* fileSystem
399 .readFileString(environment.path.join(environment.resourcesPath, "package-type"))
400 .pipe(
401 Effect.map((packageType) => packageType.trim() === "deb"),
402 Effect.orElseSucceed(() => false),
403 )
404 : false;
405​
406 const hasUpdateFeedConfig = Ref.get(appUpdateYmlConfigRef).pipe(
407 Effect.map((appUpdateYmlConfig) => Option.isSome(appUpdateYmlConfig) || config.mockUpdates),
408 );
409​
410 const resolveDisabledReason = Effect.gen(function* () {
411 const hasFeedConfig = yield* hasUpdateFeedConfig;
412 return Option.fromNullishOr(
413 getAutoUpdateDisabledReason({
414 isDevelopment: environment.isDevelopment,
415 isPackaged: environment.isPackaged,
416 platform: environment.platform,
417 appImage: Option.getOrUndefined(config.appImagePath),
418 isDebPackage,
419 disabledByEnv: config.disableAutoUpdate,
420 hasUpdateFeedConfig: hasFeedConfig,
421 }),
422 );
423 });
424​
425 const activeUpdateAction = Ref.get(activeUpdateActionRef);
426​
427 const tryStartUpdateAction = (action: UpdateAction): Effect.Effect<boolean> =>
428 Ref.modify(activeUpdateActionRef, (activeAction) =>
429 Option.isSome(activeAction) ? [false, activeAction] : [true, Option.some(action)],
430 );
431​
432 const tryStartChannelChange = Ref.modify(activeUpdateActionRef, (activeAction) =>
433 Option.isSome(activeAction)
434 ? [activeAction, activeAction]
435 : [Option.none<UpdateAction>(), Option.some<UpdateAction>("channel")],
436 );
437​
438 const finishUpdateAction = (action: UpdateAction): Effect.Effect<void> =>
439 Ref.modify(activeUpdateActionRef, (activeAction) => {
440 const finished = Option.isSome(activeAction) && activeAction.value === action;
441 return [finished, finished ? Option.none() : activeAction] as const;
442 }).pipe(
443 Effect.flatMap((finished) =>
444 finished ? PubSub.publish(finishedUpdateActions, action).pipe(Effect.asVoid) : Effect.void,
445 ),
446 );
447​
448 const applyAutoUpdaterChannel = Effect.fn("desktop.updates.applyAutoUpdaterChannel")(function* (
449 channel: DesktopUpdateChannel,
450 ) {
451 yield* Effect.annotateCurrentSpan({ channel });
452 const allowsPrerelease = channel === "nightly";
453 yield* electronUpdater.setChannel(channel);
454 yield* electronUpdater.setAllowPrerelease(allowsPrerelease);
455 yield* electronUpdater.setAllowDowngrade(allowsPrerelease);
456 yield* electronUpdater.setFullChangelog(allowsPrerelease);
457 yield* logUpdaterInfo("using update channel", {
458 channel,
459 allowPrerelease: allowsPrerelease,
460 allowDowngrade: allowsPrerelease,
461 fullChangelog: allowsPrerelease,
462 });
463 });
464​
465 const shouldEnableAutoUpdates = resolveDisabledReason.pipe(Effect.map(Option.isNone));
466​
467 const checkForUpdates = Effect.fn("desktop.updates.checkForUpdates")(function* (
468 reason: string,
469 actionReservation: "acquire" | "held" = "acquire",
470 ) {
471 yield* Effect.annotateCurrentSpan({ reason });
472 if (yield* Ref.get(desktopState.quitting)) return false;
473 if (!(yield* Ref.get(updaterConfiguredRef))) return false;
474​
475 const state = yield* Ref.get(updateStateRef);
476 if (state.status === "downloading") {
477 yield* logUpdaterInfo("skipping update check while update is active", {
478 reason,
479 status: state.status,
480 });
481 return false;
482 }
483​
484 if (actionReservation === "acquire" && !(yield* tryStartUpdateAction("check"))) return false;
485​
486 const check = Effect.gen(function* () {
487 const checkedAt = yield* currentIsoTimestamp;
488 yield* setState(reduceDesktopUpdateStateOnCheckStart(state, checkedAt));
489 yield* logUpdaterInfo("checking for updates", { reason });
490​
491 return yield* electronUpdater.checkForUpdates.pipe(
492 Effect.as(true),
493 Effect.catchTags({
494 ElectronUpdaterCheckForUpdatesError: Effect.fn(
495 "desktop.updates.handleCheckForUpdatesFailure",
496 )(function* (error) {
497 const failedAt = yield* currentIsoTimestamp;
498 yield* updateState((current) =>
499 reduceDesktopUpdateStateOnCheckFailure(current, error.message, failedAt),
500 );
501 yield* logUpdaterError(error.message, {
502 errorTag: error._tag,
503 cause: describeUpdateErrorCause(error.cause),
504 channel: error.channel,
505 });
506 return true;
507 }),
508 }),
509 );
510 });
511​
512 return yield* actionReservation === "held"
513 ? check
514 : check.pipe(
515 Effect.onInterrupt(() => setState(state)),
516 Effect.ensuring(finishUpdateAction("check")),
517 );
518 });
519​
520 const downloadAvailableUpdate = Effect.gen(function* () {
521 const state = yield* Ref.get(updateStateRef);
522 if (!(yield* Ref.get(updaterConfiguredRef)) || state.status !== "available") {
523 return { accepted: false, completed: false };
524 }
525​
526 if (!(yield* tryStartUpdateAction("download"))) {
527 return { accepted: false, completed: false };
528 }
529​
530 return yield* Effect.gen(function* () {
531 yield* setState(reduceDesktopUpdateStateOnDownloadStart(state));
532 yield* electronUpdater.setDisableDifferentialDownload(
533 isArm64HostRunningIntelBuild(environment.runtimeInfo),
534 );
535 yield* logUpdaterInfo("downloading update");
536 yield* electronUpdater.downloadUpdate;
537 return { accepted: true, completed: true };
538 }).pipe(
539 Effect.catchTags({
540 ElectronUpdaterDownloadUpdateError: Effect.fn("desktop.updates.handleDownloadFailure")(
541 function* (error) {
542 yield* updateState((current) =>
543 reduceDesktopUpdateStateOnDownloadFailure(current, error.message),
544 );
545 yield* logUpdaterError(error.message, {
546 errorTag: error._tag,
547 cause: describeUpdateErrorCause(error.cause),
548 channel: error.channel,
549 });
550 return { accepted: true, completed: false };
551 },
552 ),
553 }),
554 Effect.onInterrupt(() =>
555 updateState((current) => (current.status === "downloading" ? state : current)).pipe(
556 Effect.asVoid,
557 ),
558 ),
559 Effect.catchCause((cause) => {
560 if (Cause.hasInterruptsOnly(cause)) {
561 return Effect.failCause(cause);
562 }
563 const error = new DesktopUpdateUnexpectedActionError({ action: "download", cause });
564 return Effect.gen(function* () {
565 yield* updateState((current) =>
566 reduceDesktopUpdateStateOnDownloadFailure(current, error.message),
567 );
568 yield* logUpdaterError(error.message, {
569 errorTag: error._tag,
570 cause: describeUpdateErrorCause(error.cause),
571 action: error.action,
572 });
573 return { accepted: true, completed: false };
574 });
575 }),
576 Effect.ensuring(finishUpdateAction("download")),
577 );
578 }).pipe(Effect.withSpan("desktop.updates.downloadAvailableUpdate"));
579​
580 // Tells the primary backend that the coming stop is an update restart, so it
581 // keeps its managed tunnel for the backend the updated app starts. Best
582 // effort: without the marker the backend only re-provisions its tunnel.
583 const updateRestartMarkerDir = environment.path.join(environment.baseDir, "runtime");
584 const updateRestartMarkerPath = environment.path.join(
585 updateRestartMarkerDir,
586 DESKTOP_UPDATE_RESTART_MARKER_FILE,
587 );
588 const writeUpdateRestartMarker = fileSystem
589 .makeDirectory(updateRestartMarkerDir, { recursive: true })
590 .pipe(
591 Effect.andThen(fileSystem.writeFileString(updateRestartMarkerPath, "")),
592 Effect.catch((error) =>
593 logUpdaterWarning("Could not write the update restart marker.", { errorTag: error._tag }),
594 ),
595 );
596​
597 // A failed or interrupted install brings no updated backend, so a later
598 // quit must release the tunnel.
599 const removeUpdateRestartMarker = fileSystem
600 .remove(updateRestartMarkerPath, { force: true })
601 .pipe(Effect.ignore);
602​
603 const resetInstallAction = Effect.all(
604 [
605 finishUpdateAction("install"),
606 Ref.set(desktopState.quitting, false),
607 removeUpdateRestartMarker,
608 ],
609 { discard: true },
610 );
611​
612 const recoverFailedInstall = Effect.fn("desktop.updates.recoverFailedInstall")(function* (
613 message: string,
614 ) {
615 const ownsRecovery = yield* Ref.modify(activeUpdateActionRef, (activeAction) =>
616 Option.isSome(activeAction) && activeAction.value === "install"
617 ? ([true, Option.some<UpdateAction>("install-recovery")] as const)
618 : ([false, activeAction] as const),
619 );
620 if (!ownsRecovery) return;
621​
622 yield* Ref.set(desktopState.quitting, false);
623 yield* removeUpdateRestartMarker;
624 yield* Effect.gen(function* () {
625 const instances = yield* pool.list;
626 const restartExit = yield* Effect.forEach(instances, (instance) => instance.start, {
627 concurrency: "unbounded",
628 discard: true,
629 }).pipe(Effect.exit);
630 yield* updateState((current) => reduceDesktopUpdateStateOnInstallFailure(current, message));
631 if (Exit.isFailure(restartExit)) {
632 yield* logUpdaterError("Desktop update install recovery could not restart every backend.");
633 }
634 }).pipe(
635 Effect.catchCause(() =>
636 logUpdaterError("Desktop update install recovery failed unexpectedly."),
637 ),
638 Effect.ensuring(finishUpdateAction("install-recovery")),
639 );
640 });
641​
642 const installDownloadedUpdate = (expectedVersion?: string) =>
643 Effect.scoped(
644 Effect.gen(function* () {
645 const actionCompletions = yield* PubSub.subscribe(finishedUpdateActions);
646 let admission: "admitted" | "refused" | "wait-for-check" = "wait-for-check";
647 while (admission === "wait-for-check") {
648 admission = yield* stateMutex.withPermits(1)(
649 Effect.gen(function* () {
650 const state = yield* Ref.get(updateStateRef);
651 const activeAction = yield* Ref.get(activeUpdateActionRef);
652 const hasExpectedDownload =
653 state.downloadedVersion !== null &&
654 (expectedVersion === undefined || state.downloadedVersion === expectedVersion);
655 if (
656 (yield* Ref.get(desktopState.quitting)) ||
657 !(yield* Ref.get(updaterConfiguredRef)) ||
658 !hasExpectedDownload
659 ) {
660 return "refused" as const;
661 }
662 if (Option.isSome(activeAction)) {
663 return activeAction.value === "check" && expectedVersion !== undefined
664 ? ("wait-for-check" as const)
665 : ("refused" as const);
666 }
667 const hasInstallableDownload =
668 state.status === "downloaded" ||
669 (state.status === "error" &&
670 (state.errorContext === null || state.errorContext === "install"));
671 if (!hasInstallableDownload) return "refused" as const;
672 return (yield* tryStartUpdateAction("install"))
673 ? ("admitted" as const)
674 : ("refused" as const);
675 }),
676 );
677 if (admission === "wait-for-check") {
678 const finishedAction = yield* PubSub.take(actionCompletions).pipe(
679 Effect.timeoutOption(PREPARED_INSTALL_CHECK_WAIT),
680 );
681 if (Option.isNone(finishedAction)) {
682 admission = "refused";
683 }
684 }
685 }
686 if (admission === "refused") {
687 return { accepted: false, completed: false, failed: false };
688 }
689​
690 yield* Ref.set(desktopState.quitting, true);
691​
692 return yield* Effect.gen(function* () {
693 yield* writeUpdateRestartMarker;
694 // Stop every backend in the pool, not just the primary. With
695 // parallel WSL + Windows backends, leaving the WSL instance up
696 // means quitAndInstall's app.quit() exits before the pool's
697 // scope cascade has a chance to run its stop finalizer, so the
698 // WSL child gets hard-killed by the OS instead of receiving
699 // SIGTERM + grace. Stops run concurrently with the same 5s
700 // budget the primary had on its own.
701 const instances = yield* pool.list;
702 yield* Effect.forEach(
703 instances,
704 (instance) => instance.stop({ timeout: Duration.seconds(5) }),
705 { concurrency: "unbounded" },
706 );
707 yield* electronUpdater.quitAndInstall({
708 isSilent: true,
709 isForceRunAfter: true,
710 });
711 return { accepted: true, completed: false, failed: false };
712 }).pipe(
713 Effect.catchTags({
714 ElectronUpdaterQuitAndInstallError: Effect.fn("desktop.updates.handleInstallFailure")(
715 function* (error) {
716 yield* recoverFailedInstall(error.message);
717 yield* logUpdaterError(error.message, {
718 errorTag: error._tag,
719 cause: describeUpdateErrorCause(error.cause),
720 channel: error.channel,
721 isSilent: error.isSilent,
722 isForceRunAfter: error.isForceRunAfter,
723 });
724 return { accepted: true, completed: false, failed: true };
725 },
726 ),
727 }),
728 Effect.onInterrupt(() => resetInstallAction),
729 Effect.catchCause((cause) =>
730 Effect.gen(function* () {
731 if (Cause.hasInterruptsOnly(cause)) {
732 return yield* Effect.failCause(cause);
733 }
734 const error = new DesktopUpdateUnexpectedActionError({ action: "install", cause });
735 yield* recoverFailedInstall(error.message);
736 yield* logUpdaterError(error.message, {
737 errorTag: error._tag,
738 cause: describeUpdateErrorCause(error.cause),
739 action: error.action,
740 });
741 return { accepted: true, completed: false, failed: true };
742 }),
743 ),
744 );
745 }),
746 ).pipe(Effect.withSpan("desktop.updates.installDownloadedUpdate"));
747​
748 const installWithExpectedVersion = Effect.fn("desktop.updates.install")(function* (
749 expectedVersion?: string,
750 ) {
751 if (yield* Ref.get(desktopState.quitting)) {
752 return {
753 accepted: false,
754 completed: false,
755 failed: false,
756 state: yield* Ref.get(updateStateRef),
757 };
758 }
759 const result = yield* installDownloadedUpdate(expectedVersion);
760 return {
761 accepted: result.accepted,
762 completed: result.completed,
763 failed: result.failed,
764 state: yield* Ref.get(updateStateRef),
765 };
766 });
767​
768 const startUpdatePollers: Effect.Effect<void, never, Scope.Scope> = Effect.gen(function* () {
769 yield* Effect.sleep(AUTO_UPDATE_STARTUP_DELAY).pipe(
770 Effect.andThen(checkForUpdates("startup")),
771 Effect.catchCause((cause) => {
772 if (Cause.hasInterruptsOnly(cause)) {
773 return Effect.void;
774 }
775 const error = new DesktopUpdatePollerError({ poller: "startup", cause });
776 return logUpdaterError(error.message, {
777 errorTag: error._tag,
778 cause: describeUpdateErrorCause(error.cause),
779 poller: error.poller,
780 });
781 }),
782 Effect.forkScoped,
783 );
784 yield* Effect.sleep(AUTO_UPDATE_POLL_INTERVAL).pipe(
785 Effect.andThen(checkForUpdates("poll")),
786 Effect.forever,
787 Effect.catchCause((cause) => {
788 if (Cause.hasInterruptsOnly(cause)) {
789 return Effect.void;
790 }
791 const error = new DesktopUpdatePollerError({ poller: "poll", cause });
792 return logUpdaterError(error.message, {
793 errorTag: error._tag,
794 cause: describeUpdateErrorCause(error.cause),
795 poller: error.poller,
796 });
797 }),
798 Effect.forkScoped,
799 );
800 }).pipe(Effect.withSpan("desktop.updates.startPollers"));
801​
802 const handleUpdateAvailable = Effect.fn("desktop.updates.handleUpdateAvailable")(function* (
803 raw: unknown,
804 ) {
805 yield* decodeUpdateInfo(raw).pipe(
806 Effect.flatMap(
807 Effect.fn("desktop.updates.applyUpdateAvailable")(function* (info) {
808 const state = yield* Ref.get(updateStateRef);
809 if (resolveDefaultDesktopUpdateChannel(info.version) !== state.channel) {
810 yield* logUpdaterInfo("ignoring update that does not match selected channel", {
811 version: info.version,
812 channel: state.channel,
813 });
814 const checkedAt = yield* currentIsoTimestamp;
815 yield* setState(reduceDesktopUpdateStateOnNoUpdate(state, checkedAt));
816 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
817 return;
818 }
819​
820 const checkedAt = yield* currentIsoTimestamp;
821 const { releaseNotes, omittedReleaseCount } = normalizeDesktopUpdateReleaseNotes(
822 info.releaseNotes,
823 info.version,
824 state.channel,
825 );
826 yield* setState(
827 reduceDesktopUpdateStateOnUpdateAvailable(
828 state,
829 info.version,
830 checkedAt,
831 releaseNotes,
832 omittedReleaseCount,
833 ),
834 );
835 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
836 yield* logUpdaterInfo("update available", {
837 version: info.version,
838 releaseNoteGroups: releaseNotes.length,
839 omittedReleaseCount,
840 });
841 }),
842 ),
843 Effect.catchCause((cause) => {
844 if (Cause.hasInterruptsOnly(cause)) {
845 return Effect.void;
846 }
847 const error = new DesktopUpdateEventHandlingError({ event: "update-available", cause });
848 return logUpdaterWarning(error.message, {
849 errorTag: error._tag,
850 cause: describeUpdateErrorCause(error.cause),
851 event: error.event,
852 });
853 }),
854 );
855 });
856​
857 const handleUpdateNotAvailable = Effect.gen(function* () {
858 const checkedAt = yield* currentIsoTimestamp;
859 const state = yield* Ref.get(updateStateRef);
860 yield* setState(reduceDesktopUpdateStateOnNoUpdate(state, checkedAt));
861 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
862 yield* logUpdaterInfo("no updates available");
863 }).pipe(Effect.withSpan("desktop.updates.handleUpdateNotAvailable"));
864​
865 const handleUpdaterError = Effect.fn("desktop.updates.handleUpdaterError")(function* (
866 cause: unknown,
867 ) {
868 const activeAction = yield* activeUpdateAction;
869 const error = new DesktopUpdaterReportedError({
870 operation: Option.match(activeAction, {
871 onNone: () => "background" as const,
872 onSome: (action) => (action === "install-recovery" ? "install" : action),
873 }),
874 cause,
875 });
876 if (Option.isSome(activeAction) && activeAction.value === "install") {
877 yield* recoverFailedInstall(error.message);
878 yield* logUpdaterError(error.message, {
879 errorTag: error._tag,
880 cause: describeUpdateErrorCause(error.cause),
881 operation: error.operation,
882 });
883 return;
884 }
885​
886 if (Option.isNone(activeAction)) {
887 const checkedAt = yield* currentIsoTimestamp;
888 yield* updateState((current) => ({
889 ...current,
890 status: "error",
891 message: error.message,
892 checkedAt,
893 downloadPercent: null,
894 errorContext: current.errorContext,
895 canRetry: getCanRetryFromState(current),
896 }));
897 }
898​
899 yield* logUpdaterError(error.message, {
900 errorTag: error._tag,
901 cause: describeUpdateErrorCause(error.cause),
902 operation: error.operation,
903 });
904 });
905​
906 const handleDownloadProgress = Effect.fn("desktop.updates.handleDownloadProgress")(function* (
907 raw: unknown,
908 ) {
909 yield* decodeDownloadProgressInfo(raw).pipe(
910 Effect.flatMap(
911 Effect.fn("desktop.updates.applyDownloadProgress")(function* (progress) {
912 const state = yield* Ref.get(updateStateRef);
913 const percent = Math.floor(progress.percent);
914 if (shouldBroadcastDownloadProgress(state, progress.percent) || state.message !== null) {
915 yield* setState(reduceDesktopUpdateStateOnDownloadProgress(state, progress.percent));
916 }
917 const milestone = percent - (percent % 10);
918 const lastLoggedMilestone = yield* Ref.get(lastLoggedDownloadMilestoneRef);
919 if (milestone > lastLoggedMilestone) {
920 yield* Ref.set(lastLoggedDownloadMilestoneRef, milestone);
921 yield* logUpdaterInfo("download progress", { percent });
922 }
923 }),
924 ),
925 Effect.catchCause((cause) => {
926 if (Cause.hasInterruptsOnly(cause)) {
927 return Effect.void;
928 }
929 const error = new DesktopUpdateEventHandlingError({ event: "download-progress", cause });
930 return logUpdaterWarning(error.message, {
931 errorTag: error._tag,
932 cause: describeUpdateErrorCause(error.cause),
933 event: error.event,
934 });
935 }),
936 );
937 });
938​
939 const handleUpdateDownloaded = Effect.fn("desktop.updates.handleUpdateDownloaded")(function* (
940 raw: unknown,
941 ) {
942 yield* decodeUpdateInfo(raw).pipe(
943 Effect.flatMap(
944 Effect.fn("desktop.updates.applyUpdateDownloaded")(function* (info) {
945 const state = yield* Ref.get(updateStateRef);
946 yield* setState(reduceDesktopUpdateStateOnDownloadComplete(state, info.version));
947 yield* logUpdaterInfo("update downloaded", { version: info.version });
948 }),
949 ),
950 Effect.catchCause((cause) => {
951 if (Cause.hasInterruptsOnly(cause)) {
952 return Effect.void;
953 }
954 const error = new DesktopUpdateEventHandlingError({ event: "update-downloaded", cause });
955 return logUpdaterWarning(error.message, {
956 errorTag: error._tag,
957 cause: describeUpdateErrorCause(error.cause),
958 event: error.event,
959 });
960 }),
961 );
962 });
963​
964 return DesktopUpdates.of({
965 getState: Ref.get(updateStateRef),
966 isActionActive: activeUpdateAction.pipe(Effect.map(Option.isSome)),
967 isInstallActive: activeUpdateAction.pipe(
968 Effect.map((action) => Option.isSome(action) && action.value === "install"),
969 ),
970 subscribe: stateMutex.withPermits(1)(
971 Effect.gen(function* () {
972 const subscription = yield* PubSub.subscribe(stateChanges);
973 const latest = yield* Ref.get(updateStateRef);
974 return { latest, changes: Stream.fromSubscription(subscription) };
975 }),
976 ),
977 emitState,
978 disabledReason: resolveDisabledReason,
979 configure: Effect.gen(function* () {
980 const context = yield* Effect.context<never>();
981 const runEffect = (effect: Effect.Effect<void>) => {
982 void Effect.runPromiseWith(context)(effect);
983 };
984​
985 const appUpdateYmlConfig = yield* readAppUpdateYml;
986 yield* Ref.set(appUpdateYmlConfigRef, appUpdateYmlConfig);
987​
988 if (config.mockUpdates) {
989 yield* electronUpdater.setFeedURL({
990 provider: "generic",
991 url: `http://localhost:${config.mockUpdateServerPort}`,
992 } as ElectronUpdater.ElectronUpdaterFeedUrl);
993 }
994​
995 const settings = yield* desktopSettings.get;
996 const enabled = yield* shouldEnableAutoUpdates;
997 yield* setState(createBaseUpdateState(settings.updateChannel, enabled, environment));
998 if (!enabled) {
999 return;
1001 yield* Ref.set(updaterConfiguredRef, true);
1002​
1003 yield* electronUpdater.setAutoDownload(false);
1004 yield* electronUpdater.setAutoInstallOnAppQuit(false);
1005 yield* applyAutoUpdaterChannel(settings.updateChannel);
1006 yield* electronUpdater.setDisableDifferentialDownload(
1007 isArm64HostRunningIntelBuild(environment.runtimeInfo),
1008 );
1009​
1010 if (isArm64HostRunningIntelBuild(environment.runtimeInfo)) {
1011 yield* logUpdaterInfo(
1012 "Apple Silicon host detected while running Intel build; updates will switch to arm64 packages",
1013 );
1015​
1016 yield* electronUpdater.on("checking-for-update", () => {
1017 runEffect(
1018 logUpdaterInfo("looking for updates").pipe(
1019 Effect.withSpan("desktop.updates.handleCheckingForUpdate"),
1020 ),
1021 );
1022 });
1023 yield* electronUpdater.on("update-available", (info: unknown) => {
1024 runEffect(handleUpdateAvailable(info));
1025 });
1026 yield* electronUpdater.on("update-not-available", () => {
1027 runEffect(handleUpdateNotAvailable);
1028 });
1029 yield* electronUpdater.on("error", (error: unknown) => {
1030 runEffect(handleUpdaterError(error));
1031 });
1032 yield* electronUpdater.on("download-progress", (progress: unknown) => {
1033 runEffect(handleDownloadProgress(progress));
1034 });
1035 yield* electronUpdater.on("update-downloaded", (info: unknown) => {
1036 runEffect(handleUpdateDownloaded(info));
1037 });
1038​
1039 yield* startUpdatePollers;
1040 }).pipe(Effect.withSpan("desktop.updates.configure")),
1041 setChannel: Effect.fn("desktop.updates.setChannel")(function* (
1042 nextChannel: DesktopUpdateChannel,
1043 ) {
1044 yield* Effect.annotateCurrentSpan({ channel: nextChannel });
1045 const activeAction = yield* tryStartChannelChange;
1046 if (Option.isSome(activeAction)) {
1047 return yield* new DesktopUpdateActionInProgressError({
1048 action: activeAction.value === "install-recovery" ? "install" : activeAction.value,
1049 requestedChannel: nextChannel,
1050 });
1052​
1053 return yield* Effect.gen(function* () {
1054 const state = yield* Ref.get(updateStateRef);
1055 if (nextChannel === state.channel) {
1056 return state;
1058​
1059 yield* desktopSettings
1060 .setUpdateChannel(nextChannel)
1061 .pipe(
1062 Effect.mapError(
1063 (cause) => new DesktopUpdateChannelPersistenceError({ channel: nextChannel, cause }),
1064 ),
1065 );
1066​
1067 const enabled = yield* shouldEnableAutoUpdates;
1068 yield* setState(createBaseUpdateState(nextChannel, enabled, environment));
1069​
1070 if (!enabled || !(yield* Ref.get(updaterConfiguredRef))) {
1071 return yield* Ref.get(updateStateRef);
1073​
1074 yield* applyAutoUpdaterChannel(nextChannel);
1075 const allowDowngrade = yield* electronUpdater.allowDowngrade;
1076 yield* electronUpdater.setAllowDowngrade(true);
1077 yield* checkForUpdates("channel-change", "held").pipe(
1078 Effect.ensuring(electronUpdater.setAllowDowngrade(allowDowngrade).pipe(Effect.ignore)),
1079 );
1080 return yield* Ref.get(updateStateRef);
1081 }).pipe(Effect.ensuring(finishUpdateAction("channel")));
1082 }),
1083 check: Effect.fn("desktop.updates.check")(function* (reason: string) {
1084 yield* Effect.annotateCurrentSpan({ reason });
1085 if (!(yield* Ref.get(updaterConfiguredRef))) {
1086 return {
1087 checked: false,
1088 state: yield* Ref.get(updateStateRef),
1089 };
1091 const checked = yield* checkForUpdates(reason);
1092 return {
1093 checked,
1094 state: yield* Ref.get(updateStateRef),
1095 };
1096 }),
1097 download: Effect.gen(function* () {
1098 const result = yield* downloadAvailableUpdate;
1099 return {
1100 accepted: result.accepted,
1101 completed: result.completed,
1102 state: yield* Ref.get(updateStateRef),
1103 };
1104 }).pipe(Effect.withSpan("desktop.updates.download")),
1105 install: installWithExpectedVersion().pipe(
1106 Effect.map(({ accepted, completed, state }) => ({ accepted, completed, state })),
1107 ),
1108 installPrepared: (expectedVersion) => installWithExpectedVersion(expectedVersion),
1109 });
1110});
1111​
1112export const layer = Layer.effect(DesktopUpdates, make);