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