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