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