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