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