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 Deferred from "effect/Deferred";
15import * as Duration from "effect/Duration";
16import * as Effect from "effect/Effect";
17import * as Exit from "effect/Exit";
18import * as FileSystem from "effect/FileSystem";
19import * as Layer from "effect/Layer";
20import * as Option from "effect/Option";
21import * as PubSub from "effect/PubSub";
22import * as Ref from "effect/Ref";
23import * as Schema from "effect/Schema";
24import * as Scope from "effect/Scope";
25import * as Semaphore from "effect/Semaphore";
26import * as Stream from "effect/Stream";
27
28import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
29import * as DesktopConfig from "../app/DesktopConfig.ts";
30import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
31import * as DesktopObservability from "../app/DesktopObservability.ts";
32import * as DesktopState from "../app/DesktopState.ts";
33import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
34import * as ElectronWindow from "../electron/ElectronWindow.ts";
35import * as IpcChannels from "../ipc/channels.ts";
36import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
37import { normalizeDesktopUpdateReleaseNotes } from "./releaseNotes.ts";
38import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
39import {
40 createInitialDesktopUpdateState,
41 reduceDesktopUpdateStateOnCheckFailure,
42 reduceDesktopUpdateStateOnCheckStart,
43 reduceDesktopUpdateStateOnDownloadComplete,
44 reduceDesktopUpdateStateOnDownloadFailure,
45 reduceDesktopUpdateStateOnDownloadProgress,
46 reduceDesktopUpdateStateOnDownloadStart,
47 reduceDesktopUpdateStateOnInstallFailure,
48 reduceDesktopUpdateStateOnNoUpdate,
49 reduceDesktopUpdateStateOnUpdateAvailable,
50 resolveNotAppliedInstallVersion,
51} from "./updateMachine.ts";
52
53const AUTO_UPDATE_STARTUP_DELAY = "15 seconds";
54const AUTO_UPDATE_POLL_INTERVAL = "4 minutes";
55const PREPARED_INSTALL_CHECK_WAIT = Duration.seconds(90);
56
57type UpdateAction = "check" | "download" | "install" | "install-recovery" | "channel";
58
59interface DesktopPreparedUpdateInstallResult extends DesktopUpdateActionResult {
60 readonly failed: boolean;
61}
62
63const AppUpdateYmlConfig = Schema.Record(Schema.String, Schema.String);
64type AppUpdateYmlConfig = typeof AppUpdateYmlConfig.Type;
65
66const UpdateInfo = Schema.Struct({
67 version: Schema.String,
68 // Left unvalidated on purpose: a malformed release-notes payload must never
69 // fail the decode and block the update state transition. The shape is
70 // validated defensively in normalizeDesktopUpdateReleaseNotes.
71 releaseNotes: Schema.optional(Schema.Unknown),
72});
73
74const DownloadProgressInfo = Schema.Struct({
75 percent: Schema.Number,
76});
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 }
100}
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 }
112}
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 }
124}
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 }
136}
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 }
148}
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 }
160}
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 readonly isActionActive: Effect.Effect<boolean>;
175 readonly isInstallActive: Effect.Effect<boolean>;
176 readonly subscribe: Effect.Effect<
177 {
178 readonly latest: DesktopUpdateState;
179 readonly changes: Stream.Stream<DesktopUpdateState>;
180 },
181 never,
182 Scope.Scope
183 >;
184 readonly emitState: Effect.Effect<void>;
185 readonly disabledReason: Effect.Effect<Option.Option<string>>;
186 readonly configure: Effect.Effect<void, DesktopUpdateConfigureError, Scope.Scope>;
187 /** Waits until `configure` has run, so the channel and availability are settled. */
188 readonly whenConfigured: Effect.Effect<void>;
189 readonly setChannel: (
190 channel: DesktopUpdateChannel,
191 ) => Effect.Effect<DesktopUpdateState, DesktopUpdateSetChannelError>;
192 readonly check: (reason: string) => Effect.Effect<DesktopUpdateCheckResult>;
193 readonly download: Effect.Effect<DesktopUpdateActionResult>;
194 readonly install: Effect.Effect<DesktopUpdateActionResult>;
195 readonly installPrepared: (
196 expectedVersion: string,
197 ) => Effect.Effect<DesktopPreparedUpdateInstallResult>;
198 }
199>()("@t3tools/desktop/updates/DesktopUpdates") {}
200
201const {
202 logInfo: logUpdaterInfo,
203 logWarning: logUpdaterWarning,
204 logError: logUpdaterError,
205} = DesktopObservability.makeComponentLogger("desktop-updater");
206
207function redactMessage(message: string): string {
208 return (message.split(/[\r\n]/, 1)[0] ?? "")
209 .replace(/\b(?:https?|file):\/\/[^\s"'<>]+/gi, "[redacted URL]")
210 .replace(/\b(?:Bearer|Basic)\s+[^\s,;]+/gi, "[redacted credential]")
211 .replace(
212 /\b(?:authorization|proxy-authorization|cookie|set-cookie)\s*[:=].*$/gi,
213 "[redacted header]",
214 )
215 .replace(
216 /\b[\w-]*(?:token|password|secret|credential|api[_-]?key)[\w-]*\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi,
217 "[redacted credential]",
218 )
219 .slice(0, 512);
220}
221
222function summarizeCause(cause: unknown, depth: number): string {
223 if (depth >= 3) return "[truncated cause]";
224 if (Cause.isCause(cause)) {
225 return cause.reasons
226 .slice(0, 3)
227 .map((reason) =>
228 reason._tag === "Fail"
229 ? summarizeCause(reason.error, depth + 1)
230 : reason._tag === "Die"
231 ? summarizeCause(reason.defect, depth + 1)
232 : "Interrupted",
233 )
234 .join("; ");
235 }
236 if (typeof cause === "string") return redactMessage(cause);
237 if (typeof cause !== "object" || cause === null) return errorTag(cause);
238
239 const error = cause as {
240 readonly message?: unknown;
241 readonly code?: unknown;
242 readonly cause?: unknown;
243 };
244 const code =
245 typeof error.code === "string" && /^[A-Z][A-Z0-9_]{0,127}$/.test(error.code)
246 ? ` [${error.code}]`
247 : "";
248 const message = typeof error.message === "string" ? `: ${redactMessage(error.message)}` : "";
249 const nested =
250 error.cause === undefined ? "" : `; caused by ${summarizeCause(error.cause, depth + 1)}`;
251 return `${errorTag(cause)}${code}${message}${nested}`;
252}
253
254export function describeUpdateErrorCause(cause: unknown): string {
255 try {
256 return summarizeCause(cause, 0).slice(0, 1024);
257 } catch {
258 return "UnknownError";
259 }
260}
261
262function parseAppUpdateYml(raw: string): Effect.Effect<Option.Option<AppUpdateYmlConfig>> {
263 const entries: Record<string, string> = {};
264 for (const line of raw.split("\n")) {
265 const match = line.match(/^(\w+):\s*(.+)$/);
266 if (match?.[1] && match[2]) {
267 entries[match[1]] = match[2].trim();
268 }
269 }
270
271 return decodeAppUpdateYmlConfig(entries).pipe(
272 Effect.map((config) => (config.provider ? Option.some(config) : Option.none())),
273 Effect.orElseSucceed(() => Option.none<AppUpdateYmlConfig>()),
274 );
275}
276
277function createBaseUpdateState(
278 channel: DesktopUpdateChannel,
279 enabled: boolean,
280 environment: DesktopEnvironment.DesktopEnvironment["Service"],
281): DesktopUpdateState {
282 return {
283 ...createInitialDesktopUpdateState(environment.appVersion, environment.runtimeInfo, channel),
284 enabled,
285 status: enabled ? "idle" : "disabled",
286 };
287}
288
289function getCanRetryFromState(state: DesktopUpdateState): boolean {
290 return state.availableVersion !== null || state.downloadedVersion !== null;
291}
292
293function shouldBroadcastDownloadProgress(
294 currentState: DesktopUpdateState,
295 nextPercent: number,
296): boolean {
297 if (currentState.status !== "downloading") {
298 return true;
299 }
300
301 const currentPercent = currentState.downloadPercent;
302 if (currentPercent === null) {
303 return true;
304 }
305
306 const previousStep = Math.floor(currentPercent / 10);
307 const nextStep = Math.floor(nextPercent / 10);
308 return nextStep !== previousStep || nextPercent === 100;
309}
310
311function getAutoUpdateDisabledReason(args: {
312 isDevelopment: boolean;
313 isPackaged: boolean;
314 platform: NodeJS.Platform;
315 appImage?: string | undefined;
316 isDebPackage: boolean;
317 disabledByEnv: boolean;
318 hasUpdateFeedConfig: boolean;
319}): string | null {
320 if (!args.hasUpdateFeedConfig) {
321 return "Automatic updates are not available because no update feed is configured.";
322 }
323 if (args.isDevelopment || !args.isPackaged) {
324 return "Automatic updates are only available in packaged production builds.";
325 }
326 if (args.disabledByEnv) {
327 return "Automatic updates are disabled by the T3CODE_DISABLE_AUTO_UPDATE setting.";
328 }
329 if (args.platform === "linux" && !args.appImage && !args.isDebPackage) {
330 return "Automatic updates on Linux require the AppImage or the .deb package.";
331 }
332 return null;
333}
334
335function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean {
336 return runtimeInfo.hostArch === "arm64" && runtimeInfo.appArch === "x64";
337}
338
339/** @public Service construction is part of the canonical Effect module API. */
340export const make = Effect.gen(function* () {
341 const config = yield* DesktopConfig.DesktopConfig;
342 const pool = yield* DesktopBackendPool.DesktopBackendPool;
343 const desktopState = yield* DesktopState.DesktopState;
344 const electronUpdater = yield* ElectronUpdater.ElectronUpdater;
345 const electronWindow = yield* ElectronWindow.ElectronWindow;
346 const environment = yield* DesktopEnvironment.DesktopEnvironment;
347 const fileSystem = yield* FileSystem.FileSystem;
348 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
349
350 const appUpdateYmlConfigRef = yield* Ref.make<Option.Option<AppUpdateYmlConfig>>(Option.none());
351 const activeUpdateActionRef = yield* Ref.make<Option.Option<UpdateAction>>(Option.none());
352 const installRunningBackendsRef = yield* Ref.make<
353 ReadonlyArray<DesktopBackendPool.DesktopBackendInstance>
354 >([]);
355 const finishedUpdateActions = yield* PubSub.unbounded<UpdateAction>();
356 const updaterConfiguredRef = yield* Ref.make(false);
357 const configureDone = yield* Deferred.make<void>();
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 const updateRestartMarkerDir = environment.path.join(environment.baseDir, "runtime");
591 const updateRestartMarkerPath = environment.path.join(
592 updateRestartMarkerDir,
593 DESKTOP_UPDATE_RESTART_MARKER_FILE,
594 );
595 const writeUpdateRestartMarker = fileSystem
596 .makeDirectory(updateRestartMarkerDir, { recursive: true })
597 .pipe(
598 Effect.andThen(fileSystem.writeFileString(updateRestartMarkerPath, "")),
599 Effect.catch((error) =>
600 logUpdaterWarning("Could not write the update restart marker.", { errorTag: error._tag }),
601 ),
602 );
603
604 // A failed or interrupted install brings no updated backend, so a later
605 // quit must release the tunnel.
606 const removeUpdateRestartMarker = fileSystem
607 .remove(updateRestartMarkerPath, { force: true })
608 .pipe(Effect.ignore);
609
610 const installRecordPath = environment.path.join(
611 updateRestartMarkerDir,
612 DESKTOP_UPDATE_INSTALL_RECORD_FILE,
613 );
614 const writeInstallRecord = (targetVersion: string) =>
615 encodeInstallRecord({ fromVersion: environment.appVersion, targetVersion }).pipe(
616 Effect.flatMap((text) => fileSystem.writeFileString(installRecordPath, text)),
617 Effect.catch((error) =>
618 logUpdaterWarning("Could not record the update install.", { errorTag: error._tag }),
619 ),
620 );
621 const removeInstallRecord = fileSystem
622 .remove(installRecordPath, { force: true })
623 .pipe(Effect.ignore);
624
625 const readNotAppliedInstallVersion = fileSystem.readFileString(installRecordPath).pipe(
626 Effect.flatMap(decodeInstallRecord),
627 Effect.option,
628 Effect.map((record) =>
629 Option.flatMap(record, (value) =>
630 Option.fromNullishOr(resolveNotAppliedInstallVersion(value, environment.appVersion)),
631 ),
632 ),
633 Effect.tap((notAppliedVersion) =>
634 Option.isNone(notAppliedVersion) ? removeInstallRecord : Effect.void,
635 ),
636 );
637
638 const baseUpdateState = (channel: DesktopUpdateChannel, enabled: boolean) =>
639 Ref.get(notAppliedVersionRef).pipe(
640 Effect.map((notAppliedVersion) => ({
641 ...createBaseUpdateState(channel, enabled, environment),
642 ...Option.match(notAppliedVersion, {
643 onNone: () => ({}),
644 onSome: (version) => ({ notAppliedVersion: version }),
645 }),
646 })),
647 );
648
649 const resetInstallAction = Effect.all(
650 [
651 finishUpdateAction("install"),
652 Ref.set(desktopState.quitting, false),
653 Ref.set(installRunningBackendsRef, []),
654 removeUpdateRestartMarker,
655 removeInstallRecord,
656 ],
657 { discard: true },
658 );
659
660 const recoverFailedInstall = Effect.fn("desktop.updates.recoverFailedInstall")(function* (
661 message: string,
662 ) {
663 const ownsRecovery = yield* Ref.modify(activeUpdateActionRef, (activeAction) =>
664 Option.isSome(activeAction) && activeAction.value === "install"
665 ? ([true, Option.some<UpdateAction>("install-recovery")] as const)
666 : ([false, activeAction] as const),
667 );
668 if (!ownsRecovery) return;
669
670 yield* Ref.set(desktopState.quitting, false);
671 yield* removeUpdateRestartMarker;
672 yield* removeInstallRecord;
673 yield* Effect.gen(function* () {
674 const runningInstances = yield* Ref.getAndSet(installRunningBackendsRef, []);
675 const instances = (yield* pool.list).filter((instance) =>
676 runningInstances.includes(instance),
677 );
678 const restartExit = yield* Effect.forEach(instances, (instance) => instance.start, {
679 concurrency: "unbounded",
680 discard: true,
681 }).pipe(Effect.exit);
682 yield* updateState((current) => reduceDesktopUpdateStateOnInstallFailure(current, message));
683 if (Exit.isFailure(restartExit)) {
684 yield* logUpdaterError("Desktop update install recovery could not restart every backend.");
685 }
686 }).pipe(
687 Effect.catchCause(() =>
688 logUpdaterError("Desktop update install recovery failed unexpectedly."),
689 ),
690 Effect.ensuring(finishUpdateAction("install-recovery")),
691 );
692 });
693
694 const installDownloadedUpdate = (expectedVersion?: string) =>
695 Effect.scoped(
696 Effect.gen(function* () {
697 const actionCompletions = yield* PubSub.subscribe(finishedUpdateActions);
698 let admission: "admitted" | "refused" | "wait-for-check" = "wait-for-check";
699 while (admission === "wait-for-check") {
700 admission = yield* stateMutex.withPermits(1)(
701 Effect.gen(function* () {
702 const state = yield* Ref.get(updateStateRef);
703 const activeAction = yield* Ref.get(activeUpdateActionRef);
704 const hasExpectedDownload =
705 state.downloadedVersion !== null &&
706 (expectedVersion === undefined || state.downloadedVersion === expectedVersion);
707 if (
708 (yield* Ref.get(desktopState.quitting)) ||
709 !(yield* Ref.get(updaterConfiguredRef)) ||
710 !hasExpectedDownload
711 ) {
712 return "refused" as const;
713 }
714 if (Option.isSome(activeAction)) {
715 return activeAction.value === "check" && expectedVersion !== undefined
716 ? ("wait-for-check" as const)
717 : ("refused" as const);
718 }
719 const hasInstallableDownload =
720 state.status === "downloaded" ||
721 (state.status === "error" &&
722 (state.errorContext === null || state.errorContext === "install"));
723 if (!hasInstallableDownload) return "refused" as const;
724 return (yield* tryStartUpdateAction("install"))
725 ? ("admitted" as const)
726 : ("refused" as const);
727 }),
728 );
729 if (admission === "wait-for-check") {
730 const finishedAction = yield* PubSub.take(actionCompletions).pipe(
731 Effect.timeoutOption(PREPARED_INSTALL_CHECK_WAIT),
732 );
733 if (Option.isNone(finishedAction)) {
734 admission = "refused";
735 }
736 }
737 }
738 if (admission === "refused") {
739 return { accepted: false, completed: false, failed: false };
740 }
741
742 yield* Ref.set(desktopState.quitting, true);
743 yield* Ref.set(installRunningBackendsRef, []);
744
745 return yield* Effect.gen(function* () {
746 yield* writeUpdateRestartMarker;
747 const { downloadedVersion } = yield* Ref.get(updateStateRef);
748 if (downloadedVersion !== null) yield* writeInstallRecord(downloadedVersion);
749 // Stop every backend in the pool, not just the primary. With parallel
750 // WSL + Windows backends, leaving the WSL instance up means
751 // quitAndInstall's app.quit() exits before the pool's scope cascade
752 // has a chance to run its stop finalizer, so the WSL child gets
753 // hard-killed by the OS instead of receiving SIGTERM + grace.
754 const instances = yield* pool.list;
755 // stop clears desiredRunning, so retain the recovery set beforehand.
756 const runningInstances = yield* Effect.filter(instances, (instance) =>
757 instance.snapshot.pipe(Effect.map((snapshot) => snapshot.desiredRunning)),
758 );
759 yield* Ref.set(installRunningBackendsRef, runningInstances);
760 yield* Effect.forEach(
761 instances,
762 (instance) => instance.stop({ timeout: Duration.seconds(5) }),
763 { concurrency: "unbounded" },
764 );
765 yield* electronUpdater.quitAndInstall({
766 isSilent: true,
767 isForceRunAfter: true,
768 });
769 return { accepted: true, completed: false, failed: false };
770 }).pipe(
771 Effect.catchTags({
772 ElectronUpdaterQuitAndInstallError: Effect.fn("desktop.updates.handleInstallFailure")(
773 function* (error) {
774 yield* recoverFailedInstall(error.message);
775 yield* logUpdaterError(error.message, {
776 errorTag: error._tag,
777 cause: describeUpdateErrorCause(error.cause),
778 channel: error.channel,
779 isSilent: error.isSilent,
780 isForceRunAfter: error.isForceRunAfter,
781 });
782 return { accepted: true, completed: false, failed: true };
783 },
784 ),
785 }),
786 Effect.onInterrupt(() => resetInstallAction),
787 Effect.catchCause((cause) =>
788 Effect.gen(function* () {
789 if (Cause.hasInterruptsOnly(cause)) {
790 return yield* Effect.failCause(cause);
791 }
792 const error = new DesktopUpdateUnexpectedActionError({ action: "install", cause });
793 yield* recoverFailedInstall(error.message);
794 yield* logUpdaterError(error.message, {
795 errorTag: error._tag,
796 cause: describeUpdateErrorCause(error.cause),
797 action: error.action,
798 });
799 return { accepted: true, completed: false, failed: true };
800 }),
801 ),
802 );
803 }),
804 ).pipe(Effect.withSpan("desktop.updates.installDownloadedUpdate"));
805
806 const installWithExpectedVersion = Effect.fn("desktop.updates.install")(function* (
807 expectedVersion?: string,
808 ) {
809 if (yield* Ref.get(desktopState.quitting)) {
810 return {
811 accepted: false,
812 completed: false,
813 failed: false,
814 state: yield* Ref.get(updateStateRef),
815 };
816 }
817 const result = yield* installDownloadedUpdate(expectedVersion);
818 return {
819 accepted: result.accepted,
820 completed: result.completed,
821 failed: result.failed,
822 state: yield* Ref.get(updateStateRef),
823 };
824 });
825
826 const startUpdatePollers: Effect.Effect<void, never, Scope.Scope> = Effect.gen(function* () {
827 yield* Effect.sleep(AUTO_UPDATE_STARTUP_DELAY).pipe(
828 Effect.andThen(checkForUpdates("startup")),
829 Effect.catchCause((cause) => {
830 if (Cause.hasInterruptsOnly(cause)) {
831 return Effect.void;
832 }
833 const error = new DesktopUpdatePollerError({ poller: "startup", cause });
834 return logUpdaterError(error.message, {
835 errorTag: error._tag,
836 cause: describeUpdateErrorCause(error.cause),
837 poller: error.poller,
838 });
839 }),
840 Effect.forkScoped,
841 );
842 yield* Effect.sleep(AUTO_UPDATE_POLL_INTERVAL).pipe(
843 Effect.andThen(checkForUpdates("poll")),
844 Effect.forever,
845 Effect.catchCause((cause) => {
846 if (Cause.hasInterruptsOnly(cause)) {
847 return Effect.void;
848 }
849 const error = new DesktopUpdatePollerError({ poller: "poll", cause });
850 return logUpdaterError(error.message, {
851 errorTag: error._tag,
852 cause: describeUpdateErrorCause(error.cause),
853 poller: error.poller,
854 });
855 }),
856 Effect.forkScoped,
857 );
858 }).pipe(Effect.withSpan("desktop.updates.startPollers"));
859
860 const handleUpdateAvailable = Effect.fn("desktop.updates.handleUpdateAvailable")(function* (
861 raw: unknown,
862 ) {
863 yield* decodeUpdateInfo(raw).pipe(
864 Effect.flatMap(
865 Effect.fn("desktop.updates.applyUpdateAvailable")(function* (info) {
866 const state = yield* Ref.get(updateStateRef);
867 if (resolveDefaultDesktopUpdateChannel(info.version) !== state.channel) {
868 yield* logUpdaterInfo("ignoring update that does not match selected channel", {
869 version: info.version,
870 channel: state.channel,
871 });
872 const checkedAt = yield* currentIsoTimestamp;
873 yield* setState(reduceDesktopUpdateStateOnNoUpdate(state, checkedAt));
874 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
875 return;
876 }
877
878 const checkedAt = yield* currentIsoTimestamp;
879 const { releaseNotes, omittedReleaseCount } = normalizeDesktopUpdateReleaseNotes(
880 info.releaseNotes,
881 info.version,
882 state.channel,
883 );
884 yield* setState(
885 reduceDesktopUpdateStateOnUpdateAvailable(
886 state,
887 info.version,
888 checkedAt,
889 releaseNotes,
890 omittedReleaseCount,
891 ),
892 );
893 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
894 yield* logUpdaterInfo("update available", {
895 version: info.version,
896 releaseNoteGroups: releaseNotes.length,
897 omittedReleaseCount,
898 });
899 }),
900 ),
901 Effect.catchCause((cause) => {
902 if (Cause.hasInterruptsOnly(cause)) {
903 return Effect.void;
904 }
905 const error = new DesktopUpdateEventHandlingError({ event: "update-available", cause });
906 return logUpdaterWarning(error.message, {
907 errorTag: error._tag,
908 cause: describeUpdateErrorCause(error.cause),
909 event: error.event,
910 });
911 }),
912 );
913 });
914
915 const handleUpdateNotAvailable = Effect.gen(function* () {
916 const checkedAt = yield* currentIsoTimestamp;
917 const state = yield* Ref.get(updateStateRef);
918 yield* setState(reduceDesktopUpdateStateOnNoUpdate(state, checkedAt));
919 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
920 yield* logUpdaterInfo("no updates available");
921 }).pipe(Effect.withSpan("desktop.updates.handleUpdateNotAvailable"));
922
923 const handleUpdaterError = Effect.fn("desktop.updates.handleUpdaterError")(function* (
924 cause: unknown,
925 ) {
926 const activeAction = yield* activeUpdateAction;
927 const error = new DesktopUpdaterReportedError({
928 operation: Option.match(activeAction, {
929 onNone: () => "background" as const,
930 onSome: (action) => (action === "install-recovery" ? "install" : action),
931 }),
932 cause,
933 });
934 if (Option.isSome(activeAction) && activeAction.value === "install") {
935 yield* recoverFailedInstall(error.message);
936 yield* logUpdaterError(error.message, {
937 errorTag: error._tag,
938 cause: describeUpdateErrorCause(error.cause),
939 operation: error.operation,
940 });
941 return;
942 }
943
944 if (Option.isNone(activeAction)) {
945 const checkedAt = yield* currentIsoTimestamp;
946 yield* updateState((current) => ({
947 ...current,
948 status: "error",
949 message: error.message,
950 checkedAt,
951 downloadPercent: null,
952 errorContext: current.errorContext,
953 canRetry: getCanRetryFromState(current),
954 }));
955 }
956
957 yield* logUpdaterError(error.message, {
958 errorTag: error._tag,
959 cause: describeUpdateErrorCause(error.cause),
960 operation: error.operation,
961 });
962 });
963
964 const handleDownloadProgress = Effect.fn("desktop.updates.handleDownloadProgress")(function* (
965 raw: unknown,
966 ) {
967 yield* decodeDownloadProgressInfo(raw).pipe(
968 Effect.flatMap(
969 Effect.fn("desktop.updates.applyDownloadProgress")(function* (progress) {
970 const state = yield* Ref.get(updateStateRef);
971 const percent = Math.floor(progress.percent);
972 if (shouldBroadcastDownloadProgress(state, progress.percent) || state.message !== null) {
973 yield* setState(reduceDesktopUpdateStateOnDownloadProgress(state, progress.percent));
974 }
975 const milestone = percent - (percent % 10);
976 const lastLoggedMilestone = yield* Ref.get(lastLoggedDownloadMilestoneRef);
977 if (milestone > lastLoggedMilestone) {
978 yield* Ref.set(lastLoggedDownloadMilestoneRef, milestone);
979 yield* logUpdaterInfo("download progress", { percent });
980 }
981 }),
982 ),
983 Effect.catchCause((cause) => {
984 if (Cause.hasInterruptsOnly(cause)) {
985 return Effect.void;
986 }
987 const error = new DesktopUpdateEventHandlingError({ event: "download-progress", cause });
988 return logUpdaterWarning(error.message, {
989 errorTag: error._tag,
990 cause: describeUpdateErrorCause(error.cause),
991 event: error.event,
992 });
993 }),
994 );
995 });
996
997 const handleUpdateDownloaded = Effect.fn("desktop.updates.handleUpdateDownloaded")(function* (
998 raw: unknown,
999 ) {
1000 yield* decodeUpdateInfo(raw).pipe(
1001 Effect.flatMap(
1002 Effect.fn("desktop.updates.applyUpdateDownloaded")(function* (info) {
1003 const state = yield* Ref.get(updateStateRef);
1004 yield* setState(reduceDesktopUpdateStateOnDownloadComplete(state, info.version));
1005 yield* logUpdaterInfo("update downloaded", { version: info.version });
1006 }),
1007 ),
1008 Effect.catchCause((cause) => {
1009 if (Cause.hasInterruptsOnly(cause)) {
1010 return Effect.void;
1011 }
1012 const error = new DesktopUpdateEventHandlingError({ event: "update-downloaded", cause });
1013 return logUpdaterWarning(error.message, {
1014 errorTag: error._tag,
1015 cause: describeUpdateErrorCause(error.cause),
1016 event: error.event,
1017 });
1018 }),
1019 );
1020 });
1021
1022 return DesktopUpdates.of({
1023 getState: Ref.get(updateStateRef),
1024 isActionActive: activeUpdateAction.pipe(Effect.map(Option.isSome)),
1025 isInstallActive: activeUpdateAction.pipe(
1026 Effect.map((action) => Option.isSome(action) && action.value === "install"),
1027 ),
1028 subscribe: stateMutex.withPermits(1)(
1029 Effect.gen(function* () {
1030 const subscription = yield* PubSub.subscribe(stateChanges);
1031 const latest = yield* Ref.get(updateStateRef);
1032 return { latest, changes: Stream.fromSubscription(subscription) };
1033 }),
1034 ),
1035 emitState,
1036 disabledReason: resolveDisabledReason,
1037 configure: Effect.gen(function* () {
1038 const context = yield* Effect.context<never>();
1039 const runEffect = (effect: Effect.Effect<void>) => {
1040 void Effect.runPromiseWith(context)(effect);
1041 };
1042
1043 const appUpdateYmlConfig = yield* readAppUpdateYml;
1044 yield* Ref.set(appUpdateYmlConfigRef, appUpdateYmlConfig);
1045
1046 const notAppliedVersion = yield* readNotAppliedInstallVersion;
1047 yield* Ref.set(notAppliedVersionRef, notAppliedVersion);
1048 if (Option.isSome(notAppliedVersion)) {
1049 yield* logUpdaterWarning("the last update install did not apply", {
1050 version: environment.appVersion,
1051 targetVersion: notAppliedVersion.value,
1052 });
1053 }
1054
1055 if (config.mockUpdates) {
1056 yield* electronUpdater.setFeedURL({
1057 provider: "generic",
1058 url: `http://localhost:${config.mockUpdateServerPort}`,
1059 } as ElectronUpdater.ElectronUpdaterFeedUrl);
1060 }
1061
1062 const settings = yield* desktopSettings.get;
1063 const enabled = yield* shouldEnableAutoUpdates;
1064 yield* setState(yield* baseUpdateState(settings.updateChannel, enabled));
1065 if (!enabled) {
1066 return;
1067 }
1068 yield* Ref.set(updaterConfiguredRef, true);
1069
1070 yield* electronUpdater.setAutoDownload(false);
1071 yield* electronUpdater.setAutoInstallOnAppQuit(false);
1072 yield* applyAutoUpdaterChannel(settings.updateChannel);
1073 yield* electronUpdater.setDisableDifferentialDownload(
1074 isArm64HostRunningIntelBuild(environment.runtimeInfo),
1075 );
1076
1077 if (isArm64HostRunningIntelBuild(environment.runtimeInfo)) {
1078 yield* logUpdaterInfo(
1079 "Apple Silicon host detected while running Intel build; updates will switch to arm64 packages",
1080 );
1081 }
1082
1083 yield* electronUpdater.on("checking-for-update", () => {
1084 runEffect(
1085 logUpdaterInfo("looking for updates").pipe(
1086 Effect.withSpan("desktop.updates.handleCheckingForUpdate"),
1087 ),
1088 );
1089 });
1090 yield* electronUpdater.on("update-available", (info: unknown) => {
1091 runEffect(handleUpdateAvailable(info));
1092 });
1093 yield* electronUpdater.on("update-not-available", () => {
1094 runEffect(handleUpdateNotAvailable);
1095 });
1096 yield* electronUpdater.on("error", (error: unknown) => {
1097 runEffect(handleUpdaterError(error));
1098 });
1099 yield* electronUpdater.on("download-progress", (progress: unknown) => {
1100 runEffect(handleDownloadProgress(progress));
1101 });
1102 yield* electronUpdater.on("update-downloaded", (info: unknown) => {
1103 runEffect(handleUpdateDownloaded(info));
1104 });
1105
1106 yield* startUpdatePollers;
1107 }).pipe(
1108 Effect.ensuring(Deferred.succeed(configureDone, undefined)),
1109 Effect.withSpan("desktop.updates.configure"),
1110 ),
1111 whenConfigured: Deferred.await(configureDone),
1112 setChannel: Effect.fn("desktop.updates.setChannel")(function* (
1113 nextChannel: DesktopUpdateChannel,
1114 ) {
1115 yield* Effect.annotateCurrentSpan({ channel: nextChannel });
1116 const activeAction = yield* tryStartChannelChange;
1117 if (Option.isSome(activeAction)) {
1118 return yield* new DesktopUpdateActionInProgressError({
1119 action: activeAction.value === "install-recovery" ? "install" : activeAction.value,
1120 requestedChannel: nextChannel,
1121 });
1122 }
1123
1124 return yield* Effect.gen(function* () {
1125 const state = yield* Ref.get(updateStateRef);
1126 if (nextChannel === state.channel) {
1127 return state;
1128 }
1129
1130 yield* desktopSettings
1131 .setUpdateChannel(nextChannel)
1132 .pipe(
1133 Effect.mapError(
1134 (cause) => new DesktopUpdateChannelPersistenceError({ channel: nextChannel, cause }),
1135 ),
1136 );
1137
1138 const enabled = yield* shouldEnableAutoUpdates;
1139 yield* setState(yield* baseUpdateState(nextChannel, enabled));
1140
1141 if (!enabled || !(yield* Ref.get(updaterConfiguredRef))) {
1142 return yield* Ref.get(updateStateRef);
1143 }
1144
1145 yield* applyAutoUpdaterChannel(nextChannel);
1146 const allowDowngrade = yield* electronUpdater.allowDowngrade;
1147 yield* electronUpdater.setAllowDowngrade(true);
1148 yield* checkForUpdates("channel-change", "held").pipe(
1149 Effect.ensuring(electronUpdater.setAllowDowngrade(allowDowngrade).pipe(Effect.ignore)),
1150 );
1151 return yield* Ref.get(updateStateRef);
1152 }).pipe(Effect.ensuring(finishUpdateAction("channel")));
1153 }),
1154 check: Effect.fn("desktop.updates.check")(function* (reason: string) {
1155 yield* Effect.annotateCurrentSpan({ reason });
1156 if (!(yield* Ref.get(updaterConfiguredRef))) {
1157 return {
1158 checked: false,
1159 state: yield* Ref.get(updateStateRef),
1160 };
1161 }
1162 const checked = yield* checkForUpdates(reason);
1163 return {
1164 checked,
1165 state: yield* Ref.get(updateStateRef),
1166 };
1167 }),
1168 download: Effect.gen(function* () {
1169 const result = yield* downloadAvailableUpdate;
1170 return {
1171 accepted: result.accepted,
1172 completed: result.completed,
1173 state: yield* Ref.get(updateStateRef),
1174 };
1175 }).pipe(Effect.withSpan("desktop.updates.download")),
1176 install: installWithExpectedVersion().pipe(
1177 Effect.map(({ accepted, completed, state }) => ({ accepted, completed, state })),
1178 ),
1179 installPrepared: (expectedVersion) => installWithExpectedVersion(expectedVersion),
1180 });
1181});
1182
1183export const layer = Layer.effect(DesktopUpdates, make);