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

DesktopUpdates.ts

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