@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 1,469 lines 56.6 KB
Raw
1 import {
2 DESKTOP_UPDATE_RESTART_MARKER_FILE,
3 DESKTOP_UPDATE_IN_PROGRESS_MARKER_FILE,
4 DESKTOP_UPDATE_IN_PROGRESS_TTL_MS,
5 DesktopUpdateChannelSchema,
6 type DesktopRuntimeInfo,
7 type DesktopUpdateActionResult,
8 type DesktopUpdateChannel,
9 type DesktopUpdateCheckResult,
10 type DesktopUpdateState,
11 } from "@t3tools/contracts";
12 import { errorTag } from "@t3tools/shared/observability";
13 import * as Cause from "effect/Cause";
14 import * as Context from "effect/Context";
15 import * as DateTime from "effect/DateTime";
16 import * as Duration from "effect/Duration";
17 import * as Effect from "effect/Effect";
18 import * as Exit from "effect/Exit";
19 import * as FileSystem from "effect/FileSystem";
20 import * as Layer from "effect/Layer";
21 import * as Option from "effect/Option";
22 import * as PubSub from "effect/PubSub";
23 import * as Ref from "effect/Ref";
24 import * as Schedule from "effect/Schedule";
25 import * as Schema from "effect/Schema";
26 import * as Scope from "effect/Scope";
27 import * as Semaphore from "effect/Semaphore";
28 import * as Stream from "effect/Stream";
29
30 import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
31 import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
32 import * as DesktopConfig from "../app/DesktopConfig.ts";
33 import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
34 import * as DesktopObservability from "../app/DesktopObservability.ts";
35 import * as DesktopState from "../app/DesktopState.ts";
36 import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
37 import * as ElectronWindow from "../electron/ElectronWindow.ts";
38 import * as IpcChannels from "../ipc/channels.ts";
39 import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
40 import * as DesktopSshEnvironment from "../ssh/DesktopSshEnvironment.ts";
41 import * as DesktopUpdatePolicy from "./DesktopUpdatePolicy.ts";
42 import {
43 normalizeDesktopUpdateReleaseNotes,
44 releaseNotesOfOfferedVersion,
45 } from "./releaseNotes.ts";
46 import { desktopUpdateChannelOf } from "@t3tools/shared/cliRelease";
47 import { compareSemverVersions } from "@t3tools/shared/semver";
48 import {
49 createInitialDesktopUpdateState,
50 reduceDesktopUpdateStateOnCheckFailure,
51 reduceDesktopUpdateStateOnCheckStart,
52 reduceDesktopUpdateStateOnDownloadComplete,
53 reduceDesktopUpdateStateOnDownloadFailure,
54 reduceDesktopUpdateStateOnDownloadProgress,
55 reduceDesktopUpdateStateOnDownloadStart,
56 reduceDesktopUpdateStateOnInstallFailure,
57 reduceDesktopUpdateStateOnNoUpdate,
58 reduceDesktopUpdateStateOnUpdateAvailable,
59 resolveNotAppliedInstallVersion,
60 } from "./updateMachine.ts";
61
62 const CHANNEL_CHANGE_RETRY_DELAY = Duration.seconds(1);
63 const CHANNEL_CHANGE_RETRIES = 30;
64 const AUTO_UPDATE_STARTUP_DELAY = "15 seconds";
65 const AUTO_UPDATE_POLL_INTERVAL = "4 hours";
66 const UPDATE_CHECK_WAIT = Duration.seconds(90);
67
68 type UpdateAction = "check" | "download" | "install" | "install-recovery" | "channel";
69
70 interface DesktopPreparedUpdateInstallResult extends DesktopUpdateActionResult {
71 readonly failed: boolean;
72 }
73
74 const AppUpdateYmlConfig = Schema.Record(Schema.String, Schema.String);
75 type AppUpdateYmlConfig = typeof AppUpdateYmlConfig.Type;
76
77 const UpdateInfo = Schema.Struct({
78 version: Schema.String,
79 // Malformed notes must not block update-state decoding; normalizeDesktopUpdateReleaseNotes validates separately.
80 releaseNotes: Schema.optional(Schema.Unknown),
81 releaseName: Schema.optional(Schema.NullOr(Schema.String)),
82 releaseDate: Schema.optional(Schema.String),
83 });
84
85 const DownloadProgressInfo = Schema.Struct({
86 percent: Schema.Number,
87 });
88 export const DESKTOP_UPDATE_INSTALL_RECORD_FILE = "desktop-update-install.json";
89 const DesktopUpdateInstallRecord = Schema.fromJsonString(
90 Schema.Struct({ fromVersion: Schema.String, targetVersion: Schema.String }),
91 );
92 const decodeInstallRecord = Schema.decodeUnknownEffect(DesktopUpdateInstallRecord);
93 const encodeInstallRecord = Schema.encodeEffect(DesktopUpdateInstallRecord);
94
95 const decodeAppUpdateYmlConfig = Schema.decodeUnknownEffect(AppUpdateYmlConfig);
96 const decodeUpdateInfo = Schema.decodeUnknownEffect(UpdateInfo);
97 const decodeDownloadProgressInfo = Schema.decodeUnknownEffect(DownloadProgressInfo);
98
99 const currentIsoTimestamp = DateTime.now.pipe(Effect.map(DateTime.formatIso));
100
101 export class DesktopUpdateActionInProgressError extends Schema.TaggedError<DesktopUpdateActionInProgressError>()(
102 "DesktopUpdateActionInProgressError",
103 {
104 action: Schema.Literals(["check", "download", "install", "channel"]),
105 requestedChannel: DesktopUpdateChannelSchema,
106 },
107 ) {
108 override get message(): string {
109 return `Cannot change the desktop update channel to ${this.requestedChannel} while an update ${this.action} action is in progress.`;
110 }
111 }
112
113 export class DesktopUpdateChannelPersistenceError extends Schema.TaggedError<DesktopUpdateChannelPersistenceError>()(
114 "DesktopUpdateChannelPersistenceError",
115 {
116 channel: DesktopUpdateChannelSchema,
117 cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
118 },
119 ) {
120 override get message(): string {
121 return `Failed to persist the ${this.channel} desktop update channel.`;
122 }
123 }
124
125 export class DesktopUpdatePollerError extends Schema.TaggedError<DesktopUpdatePollerError>()(
126 "DesktopUpdatePollerError",
127 {
128 poller: Schema.Literals(["startup", "poll"]),
129 cause: Schema.Defect(),
130 },
131 ) {
132 override get message(): string {
133 return `Desktop update ${this.poller} poller failed.`;
134 }
135 }
136
137 export class DesktopUpdateEventHandlingError extends Schema.TaggedError<DesktopUpdateEventHandlingError>()(
138 "DesktopUpdateEventHandlingError",
139 {
140 event: Schema.Literals(["update-available", "download-progress", "update-downloaded"]),
141 cause: Schema.Defect(),
142 },
143 ) {
144 override get message(): string {
145 return `Failed to handle desktop update ${this.event} event.`;
146 }
147 }
148
149 export class DesktopUpdaterReportedError extends Schema.TaggedError<DesktopUpdaterReportedError>()(
150 "DesktopUpdaterReportedError",
151 {
152 operation: Schema.Literals(["check", "download", "install", "channel", "background"]),
153 cause: Schema.Defect(),
154 },
155 ) {
156 override get message(): string {
157 return `Desktop updater ${this.operation} operation reported an error.`;
158 }
159 }
160
161 export class DesktopUpdateUnexpectedActionError extends Schema.TaggedError<DesktopUpdateUnexpectedActionError>()(
162 "DesktopUpdateUnexpectedActionError",
163 {
164 action: Schema.Literals(["download", "install"]),
165 cause: Schema.Defect(),
166 },
167 ) {
168 override get message(): string {
169 return `Desktop update ${this.action} action failed unexpectedly.`;
170 }
171 }
172
173 export class DesktopUpdateChannelManagedError extends Schema.TaggedError<DesktopUpdateChannelManagedError>()(
174 "DesktopUpdateChannelManagedError",
175 {
176 channel: DesktopUpdateChannelSchema,
177 policyMessage: Schema.String,
178 },
179 ) {
180 override get message(): string {
181 return `${this.policyMessage} The ${this.channel} channel is not available.`;
182 }
183 }
184
185 export const DesktopUpdateSetChannelError = Schema.Union([
186 DesktopUpdateActionInProgressError,
187 DesktopUpdateChannelPersistenceError,
188 DesktopUpdateChannelManagedError,
189 ]);
190 export type DesktopUpdateSetChannelError = typeof DesktopUpdateSetChannelError.Type;
191
192 export class DesktopUpdates extends Context.Service<
193 DesktopUpdates,
194 {
195 readonly getState: Effect.Effect<DesktopUpdateState>;
196 readonly isActionActive: Effect.Effect<boolean>;
197 readonly isInstallActive: Effect.Effect<boolean>;
198 readonly subscribe: Effect.Effect<
199 {
200 readonly latest: DesktopUpdateState;
201 readonly changes: Stream.Stream<DesktopUpdateState>;
202 },
203 never,
204 Scope.Scope
205 >;
206 readonly emitState: Effect.Effect<void>;
207 readonly disabledReason: Effect.Effect<Option.Option<string>>;
208 readonly configure: Effect.Effect<void, never, Scope.Scope>;
209 /** `minimumVersion` is a track switch's checked release; nothing older is offered after. */
210 readonly setChannel: (
211 channel: DesktopUpdateChannel,
212 options?: { readonly minimumVersion?: string | undefined },
213 ) => Effect.Effect<DesktopUpdateState, DesktopUpdateSetChannelError>;
214 /** `allowDowngrade` is for a guarded track switch, which checked that older release. */
215 readonly check: (
216 reason: string,
217 options?: { readonly allowDowngrade?: boolean },
218 ) => Effect.Effect<DesktopUpdateCheckResult>;
219 readonly download: Effect.Effect<DesktopUpdateActionResult>;
220 readonly install: Effect.Effect<DesktopUpdateActionResult>;
221 readonly installPrepared: (
222 expectedVersion: string,
223 ) => Effect.Effect<DesktopPreparedUpdateInstallResult>;
224 }
225 >()("@t3tools/desktop/updates/DesktopUpdates") {}
226
227 const {
228 logInfo: logUpdaterInfo,
229 logWarning: logUpdaterWarning,
230 logError: logUpdaterError,
231 } = DesktopObservability.makeComponentLogger("desktop-updater");
232
233 function redactMessage(message: string): string {
234 return (message.split(/[\r\n]/, 1)[0] ?? "")
235 .replace(/\b(?:https?|file):\/\/[^\s"'<>]+/gi, "[redacted URL]")
236 .replace(/\b(?:Bearer|Basic)\s+[^\s,;]+/gi, "[redacted credential]")
237 .replace(
238 /\b(?:authorization|proxy-authorization|cookie|set-cookie)\s*[:=].*$/gi,
239 "[redacted header]",
240 )
241 .replace(
242 /\b[\w-]*(?:token|password|secret|credential|api[_-]?key)[\w-]*\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi,
243 "[redacted credential]",
244 )
245 .slice(0, 512);
246 }
247
248 function summarizeCause(cause: unknown, depth: number): string {
249 if (depth >= 3) return "[truncated cause]";
250 if (Cause.isCause(cause)) {
251 return cause.reasons
252 .slice(0, 3)
253 .map((reason) =>
254 reason._tag === "Fail"
255 ? summarizeCause(reason.error, depth + 1)
256 : reason._tag === "Die"
257 ? summarizeCause(reason.defect, depth + 1)
258 : "Interrupted",
259 )
260 .join("; ");
261 }
262 if (typeof cause === "string") return redactMessage(cause);
263 if (typeof cause !== "object" || cause === null) return errorTag(cause);
264
265 const error = cause as {
266 readonly message?: unknown;
267 readonly code?: unknown;
268 readonly cause?: unknown;
269 };
270 const code =
271 typeof error.code === "string" && /^[A-Z][A-Z0-9_]{0,127}$/.test(error.code)
272 ? ` [${error.code}]`
273 : "";
274 const message = typeof error.message === "string" ? `: ${redactMessage(error.message)}` : "";
275 const nested =
276 error.cause === undefined ? "" : `; caused by ${summarizeCause(error.cause, depth + 1)}`;
277 return `${errorTag(cause)}${code}${message}${nested}`;
278 }
279
280 export function describeUpdateErrorCause(cause: unknown): string {
281 try {
282 return summarizeCause(cause, 0).slice(0, 1024);
283 } catch {
284 return "UnknownError";
285 }
286 }
287
288 function parseAppUpdateYml(raw: string): Effect.Effect<Option.Option<AppUpdateYmlConfig>> {
289 const entries: Record<string, string> = {};
290 for (const line of raw.split("\n")) {
291 const match = line.match(/^(\w+):\s*(.+)$/);
292 if (match?.[1] && match[2]) {
293 entries[match[1]] = match[2].trim();
294 }
295 }
296
297 return decodeAppUpdateYmlConfig(entries).pipe(
298 Effect.map((config) => (config.provider ? Option.some(config) : Option.none())),
299 Effect.orElseSucceed(() => Option.none<AppUpdateYmlConfig>()),
300 );
301 }
302
303 function createBaseUpdateState(
304 channel: DesktopUpdateChannel,
305 disabledReason: Option.Option<string>,
306 environment: DesktopEnvironment.DesktopEnvironment["Service"],
307 ): DesktopUpdateState {
308 const enabled = Option.isNone(disabledReason);
309 return {
310 ...createInitialDesktopUpdateState(environment.appVersion, environment.runtimeInfo, channel),
311 enabled,
312 status: enabled ? "idle" : "disabled",
313 message: Option.getOrNull(disabledReason),
314 };
315 }
316
317 function getCanRetryFromState(state: DesktopUpdateState): boolean {
318 return state.availableVersion !== null || state.downloadedVersion !== null;
319 }
320
321 function isOffered(state: DesktopUpdateState): boolean {
322 return state.status === "available" || state.status === "downloaded";
323 }
324
325 function shouldBroadcastDownloadProgress(
326 currentState: DesktopUpdateState,
327 nextPercent: number,
328 ): boolean {
329 if (currentState.status !== "downloading") {
330 return true;
331 }
332
333 const currentPercent = currentState.downloadPercent;
334 if (currentPercent === null) {
335 return true;
336 }
337
338 const previousStep = Math.floor(currentPercent / 10);
339 const nextStep = Math.floor(nextPercent / 10);
340 return nextStep !== previousStep || nextPercent === 100;
341 }
342
343 function getAutoUpdateDisabledReason(args: {
344 policy: DesktopUpdatePolicy.UpdatePolicy;
345 isDevelopment: boolean;
346 isPackaged: boolean;
347 platform: NodeJS.Platform;
348 appImage?: string | undefined;
349 isDebPackage: boolean;
350 disabledByEnv: boolean;
351 hasUpdateFeedConfig: boolean;
352 }): string | null {
353 if (args.policy.mode === "off") {
354 return args.policy.message ?? "Updates are turned off on this machine.";
355 }
356 if (!args.hasUpdateFeedConfig) {
357 return "Automatic updates are not available because no update feed is configured.";
358 }
359 if (args.isDevelopment || !args.isPackaged) {
360 return "Automatic updates are only available in packaged production builds.";
361 }
362 if (args.disabledByEnv) {
363 return "Automatic updates are disabled by the T3CODE_DISABLE_AUTO_UPDATE setting.";
364 }
365 if (args.platform === "linux" && !args.appImage && !args.isDebPackage) {
366 return "Automatic updates on Linux require the AppImage or the .deb package.";
367 }
368 return null;
369 }
370
371 const trackLabel = (channel: DesktopUpdateChannel) =>
372 channel === "nightly" ? "Nightly" : "Stable";
373
374 // Clients localize `trackMismatch`; this English text serves older renderers and remote reports.
375 const trackMismatchMessage = (build: DesktopUpdateChannel, saved: DesktopUpdateChannel) =>
376 `This ${trackLabel(build)} build can't update from the ${trackLabel(saved)} track on its own. Switch the update track back to ${trackLabel(build)}, or use Review beside Update track to retry the switch to ${trackLabel(saved)}.`;
377
378 function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean {
379 return runtimeInfo.hostArch === "arm64" && runtimeInfo.appArch === "x64";
380 }
381
382 /** @public */
383 export const make = Effect.gen(function* () {
384 const config = yield* DesktopConfig.DesktopConfig;
385 const pool = yield* DesktopBackendPool.DesktopBackendPool;
386 const sshEnvironment = yield* DesktopSshEnvironment.DesktopSshEnvironment;
387 const desktopState = yield* DesktopState.DesktopState;
388 const electronUpdater = yield* ElectronUpdater.ElectronUpdater;
389 const electronWindow = yield* ElectronWindow.ElectronWindow;
390 const environment = yield* DesktopEnvironment.DesktopEnvironment;
391 const fileSystem = yield* FileSystem.FileSystem;
392 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
393 const policy = yield* DesktopUpdatePolicy.DesktopUpdatePolicy;
394 // Any user can set the mock flag, so it never replaces an administrator's update source.
395 const mockUpdates = config.mockUpdates && policy.message === null;
396
397 const appUpdateYmlConfigRef = yield* Ref.make<Option.Option<AppUpdateYmlConfig>>(Option.none());
398 const activeUpdateActionRef = yield* Ref.make<Option.Option<UpdateAction>>(Option.none());
399 const installRunningBackendsRef = yield* Ref.make<
400 ReadonlyArray<DesktopBackendPool.DesktopBackendInstance>
401 >([]);
402 const finishedUpdateActions = yield* PubSub.unbounded<UpdateAction>();
403 const updaterConfiguredRef = yield* Ref.make(false);
404 const lastLoggedDownloadMilestoneRef = yield* Ref.make(-1);
405 const notAppliedVersionRef = yield* Ref.make(Option.none<string>());
406 // The release a track switch's database check cleared. A build crosses to another track only
407 // through such a switch, and never below that release: version order alone cannot tell whether
408 // a Stable knows a Nightly's migrations.
409 const releaseFloorRef = yield* Ref.make(Option.none<string>());
410 const offerable = (version: string, state: DesktopUpdateState) =>
411 Ref.get(releaseFloorRef).pipe(
412 Effect.map(
413 (floor) =>
414 desktopUpdateChannelOf(version) === state.channel &&
415 (Option.isSome(floor)
416 ? compareSemverVersions(version, floor.value) >= 0
417 : desktopUpdateChannelOf(environment.appVersion) === state.channel),
418 ),
419 );
420 const updateStateRef = yield* Ref.make<DesktopUpdateState>(
421 createInitialDesktopUpdateState(
422 environment.appVersion,
423 environment.runtimeInfo,
424 environment.defaultDesktopSettings.updateChannel,
425 ),
426 );
427
428 const stateChanges = yield* PubSub.sliding<DesktopUpdateState>(16);
429 // Serialize writes and publishes against subscription so snapshots cannot overlap the first change.
430 const stateMutex = yield* Semaphore.make(1);
431
432 const emitState = Ref.get(updateStateRef).pipe(
433 Effect.flatMap((state) => electronWindow.sendAll(IpcChannels.UPDATE_STATE_CHANNEL, state)),
434 );
435
436 const setState = (state: DesktopUpdateState): Effect.Effect<void> =>
437 stateMutex
438 .withPermits(1)(
439 Ref.set(updateStateRef, state).pipe(Effect.andThen(PubSub.publish(stateChanges, state))),
440 )
441 .pipe(Effect.andThen(emitState));
442
443 const updateState = (
444 f: (state: DesktopUpdateState) => DesktopUpdateState,
445 ): Effect.Effect<DesktopUpdateState> =>
446 Ref.get(updateStateRef).pipe(
447 Effect.flatMap((state) => {
448 const nextState = f(state);
449 return setState(nextState).pipe(Effect.as(nextState));
450 }),
451 );
452
453 const readAppUpdateYml = fileSystem.readFileString(environment.appUpdateYmlPath, "utf-8").pipe(
454 Effect.option,
455 Effect.flatMap(
456 Option.match({
457 onNone: () => Effect.succeed(Option.none<AppUpdateYmlConfig>()),
458 onSome: parseAppUpdateYml,
459 }),
460 ),
461 );
462
463 // electron-updater uses this marker to install .deb updates with dpkg.
464 const isDebPackage =
465 environment.platform === "linux" && environment.isPackaged
466 ? yield* fileSystem
467 .readFileString(environment.path.join(environment.resourcesPath, "package-type"))
468 .pipe(
469 Effect.map((packageType) => packageType.trim() === "deb"),
470 Effect.orElseSucceed(() => false),
471 )
472 : false;
473
474 const hasUpdateFeedConfig = Ref.get(appUpdateYmlConfigRef).pipe(
475 Effect.map(
476 (appUpdateYmlConfig) =>
477 Option.isSome(appUpdateYmlConfig) || mockUpdates || policy.feedUrl !== undefined,
478 ),
479 );
480
481 const resolveDisabledReason = Effect.gen(function* () {
482 const hasFeedConfig = yield* hasUpdateFeedConfig;
483 return Option.fromNullishOr(
484 getAutoUpdateDisabledReason({
485 policy,
486 isDevelopment: environment.isDevelopment,
487 isPackaged: environment.isPackaged,
488 platform: environment.platform,
489 appImage: Option.getOrUndefined(config.appImagePath),
490 isDebPackage,
491 disabledByEnv: config.disableAutoUpdate,
492 hasUpdateFeedConfig: hasFeedConfig,
493 }),
494 );
495 });
496
497 // Without nightly, an install on that channel stays put until its user picks stable: moving it
498 // silently would be a downgrade nobody asked for, and checking nightly would break the policy.
499 const channelBlockedReason = (channel: DesktopUpdateChannel): Option.Option<string> =>
500 channel === "nightly" && !policy.allowNightly
501 ? Option.some(
502 `${policy.message ?? "Nightly updates are turned off on this machine."} Switch to the stable channel to keep getting updates.`,
503 )
504 : Option.none();
505
506 // Without a release floor, a build on another track than its saved one never offers anything.
507 // A track the policy blocks is never named as the one to switch to.
508 const noOfferState = (state: DesktopUpdateState, checkedAt: string) =>
509 Effect.map(Ref.get(releaseFloorRef), (floor) => {
510 const buildChannel = desktopUpdateChannelOf(environment.appVersion);
511 if (Option.isSome(floor) || buildChannel === state.channel) {
512 return reduceDesktopUpdateStateOnNoUpdate(state, checkedAt);
513 }
514 const blocked = channelBlockedReason(buildChannel);
515 if (Option.isSome(blocked)) {
516 return reduceDesktopUpdateStateOnCheckFailure(state, blocked.value, checkedAt);
517 }
518 return reduceDesktopUpdateStateOnCheckFailure(
519 state,
520 trackMismatchMessage(buildChannel, state.channel),
521 checkedAt,
522 { buildChannel },
523 );
524 });
525
526 const resolveStateDisabledReason = (channel: DesktopUpdateChannel) =>
527 resolveDisabledReason.pipe(Effect.map(Option.orElse(() => channelBlockedReason(channel))));
528
529 const activeUpdateAction = Ref.get(activeUpdateActionRef);
530
531 const tryStartUpdateAction = (action: UpdateAction): Effect.Effect<boolean> =>
532 Ref.modify(activeUpdateActionRef, (activeAction) =>
533 Option.isSome(activeAction) ? [false, activeAction] : [true, Option.some(action)],
534 );
535
536 const tryStartChannelChange = Ref.modify(activeUpdateActionRef, (activeAction) =>
537 Option.isSome(activeAction)
538 ? [activeAction, activeAction]
539 : [Option.none<UpdateAction>(), Option.some<UpdateAction>("channel")],
540 );
541
542 const finishUpdateAction = (action: UpdateAction): Effect.Effect<void> =>
543 Ref.modify(activeUpdateActionRef, (activeAction) => {
544 const finished = Option.isSome(activeAction) && activeAction.value === action;
545 return [finished, finished ? Option.none() : activeAction] as const;
546 }).pipe(
547 Effect.flatMap((finished) =>
548 finished ? PubSub.publish(finishedUpdateActions, action).pipe(Effect.asVoid) : Effect.void,
549 ),
550 );
551
552 // Re-runs admit after each finished action, so a caller waiting on a check decides on its result.
553 const admitAfterCheck = Effect.fn("desktop.updates.admitAfterCheck")(function* (
554 admit: Effect.Effect<"admitted" | "refused" | "wait-for-check">,
555 ) {
556 const actionCompletions = yield* PubSub.subscribe(finishedUpdateActions);
557 let admission = yield* stateMutex.withPermits(1)(admit);
558 while (admission === "wait-for-check") {
559 const finishedAction = yield* PubSub.take(actionCompletions).pipe(
560 Effect.timeoutOption(UPDATE_CHECK_WAIT),
561 );
562 admission = Option.isNone(finishedAction)
563 ? "refused"
564 : yield* stateMutex.withPermits(1)(admit);
565 }
566 return admission;
567 });
568
569 const applyAutoUpdaterChannel = Effect.fn("desktop.updates.applyAutoUpdaterChannel")(function* (
570 channel: DesktopUpdateChannel,
571 ) {
572 yield* Effect.annotateCurrentSpan({ channel });
573 const allowsPrerelease = channel === "nightly";
574 yield* electronUpdater.setChannel(channel);
575 yield* electronUpdater.setAllowPrerelease(allowsPrerelease);
576 // An older build can lack migrations this one ran. Only a guarded track switch's own check
577 // may offer one.
578 yield* electronUpdater.setAllowDowngrade(false);
579 yield* electronUpdater.setFullChangelog(allowsPrerelease);
580 yield* logUpdaterInfo("using update channel", {
581 channel,
582 allowPrerelease: allowsPrerelease,
583 fullChangelog: allowsPrerelease,
584 });
585 });
586
587 // The flag is shared updater state, so callers flip it only while holding a reservation.
588 const runUpdaterCheck = Effect.fn("desktop.updates.runUpdaterCheck")(function* (
589 allowDowngrade: boolean,
590 ) {
591 const restoreDowngrade = yield* electronUpdater.allowDowngrade;
592 if (allowDowngrade) yield* electronUpdater.setAllowDowngrade(true);
593 return yield* electronUpdater.checkForUpdates.pipe(
594 Effect.ensuring(electronUpdater.setAllowDowngrade(restoreDowngrade).pipe(Effect.ignore)),
595 );
596 });
597
598 const checkForUpdates = Effect.fn("desktop.updates.checkForUpdates")(function* (
599 reason: string,
600 actionReservation: "acquire" | "held" = "acquire",
601 allowDowngrade = false,
602 ) {
603 yield* Effect.annotateCurrentSpan({ reason });
604 if (yield* Ref.get(desktopState.quitting)) return false;
605 if (!(yield* Ref.get(updaterConfiguredRef))) return false;
606
607 const state = yield* Ref.get(updateStateRef);
608 // A configured updater is disabled only by a channel the managed policy blocks.
609 if (state.status === "disabled") return false;
610 if (state.status === "downloading") {
611 yield* logUpdaterInfo("skipping update check while update is active", {
612 reason,
613 status: state.status,
614 });
615 return false;
616 }
617
618 if (actionReservation === "acquire" && !(yield* tryStartUpdateAction("check"))) return false;
619
620 const check = Effect.gen(function* () {
621 // An offer stays on screen while re-checking, so finding it again changes nothing.
622 if (!isOffered(state)) {
623 yield* setState(reduceDesktopUpdateStateOnCheckStart(state, yield* currentIsoTimestamp));
624 }
625 yield* logUpdaterInfo("checking for updates", { reason });
626
627 return yield* runUpdaterCheck(allowDowngrade).pipe(
628 Effect.as(true),
629 Effect.catchTags({
630 ElectronUpdaterCheckForUpdatesError: Effect.fn(
631 "desktop.updates.handleCheckForUpdatesFailure",
632 )(function* (error) {
633 const failedAt = yield* currentIsoTimestamp;
634 yield* updateState((current) =>
635 reduceDesktopUpdateStateOnCheckFailure(current, error.message, failedAt),
636 );
637 yield* logUpdaterError(error.message, {
638 errorTag: error._tag,
639 cause: describeUpdateErrorCause(error.cause),
640 channel: error.channel,
641 });
642 return true;
643 }),
644 }),
645 );
646 });
647
648 return yield* actionReservation === "held"
649 ? check
650 : check.pipe(
651 Effect.onInterrupt(() => setState(state)),
652 Effect.ensuring(finishUpdateAction("check")),
653 );
654 });
655
656 // Install refreshes before downloading, and a second check could pick a stale, older release.
657 const downloadAvailableUpdate = Effect.fn("desktop.updates.downloadAvailableUpdate")(function* (
658 refresh: boolean,
659 ) {
660 const admission = yield* Effect.scoped(
661 admitAfterCheck(
662 Effect.gen(function* () {
663 const state = yield* Ref.get(updateStateRef);
664 if (!(yield* Ref.get(updaterConfiguredRef)) || state.status !== "available") {
665 return "refused" as const;
666 }
667 const activeAction = yield* Ref.get(activeUpdateActionRef);
668 if (Option.isSome(activeAction)) {
669 return activeAction.value === "check"
670 ? ("wait-for-check" as const)
671 : ("refused" as const);
672 }
673 return (yield* tryStartUpdateAction("download"))
674 ? ("admitted" as const)
675 : ("refused" as const);
676 }),
677 ),
678 );
679 if (admission === "refused") {
680 return { accepted: false, completed: false };
681 }
682
683 const offered = yield* Ref.get(updateStateRef);
684 let state = offered;
685 return yield* Effect.gen(function* () {
686 if (refresh) {
687 // electron-updater downloads what its last check found, which can be hours old.
688 yield* logUpdaterInfo("checking for updates", { reason: "download" });
689 yield* runUpdaterCheck(
690 offered.channel !== desktopUpdateChannelOf(environment.appVersion),
691 ).pipe(
692 // A failed check keeps electron-updater's earlier result, so the known offer still downloads.
693 Effect.catchTags({
694 ElectronUpdaterCheckForUpdatesError: (error) =>
695 logUpdaterWarning(error.message, {
696 errorTag: error._tag,
697 cause: describeUpdateErrorCause(error.cause),
698 }),
699 }),
700 );
701 }
702 state = yield* Ref.get(updateStateRef);
703 if (state.status !== "available") {
704 return { accepted: true, completed: false };
705 }
706 yield* setState(reduceDesktopUpdateStateOnDownloadStart(state));
707 yield* electronUpdater.setDisableDifferentialDownload(
708 isArm64HostRunningIntelBuild(environment.runtimeInfo),
709 );
710 yield* logUpdaterInfo("downloading update");
711 yield* electronUpdater.downloadUpdate;
712 return { accepted: true, completed: true };
713 }).pipe(
714 Effect.catchTags({
715 ElectronUpdaterDownloadUpdateError: Effect.fn("desktop.updates.handleDownloadFailure")(
716 function* (error) {
717 const cause = describeUpdateErrorCause(error.cause);
718 yield* updateState((current) =>
719 reduceDesktopUpdateStateOnDownloadFailure(current, `${error.message} ${cause}`),
720 );
721 yield* logUpdaterError(error.message, {
722 errorTag: error._tag,
723 cause,
724 channel: error.channel,
725 });
726 return { accepted: true, completed: false };
727 },
728 ),
729 }),
730 Effect.onInterrupt(() =>
731 updateState((current) => (current.status === "downloading" ? state : current)).pipe(
732 Effect.asVoid,
733 ),
734 ),
735 Effect.catchCause((cause) => {
736 if (Cause.hasInterruptsOnly(cause)) {
737 return Effect.failCause(cause);
738 }
739 const error = new DesktopUpdateUnexpectedActionError({ action: "download", cause });
740 return Effect.gen(function* () {
741 yield* updateState((current) =>
742 reduceDesktopUpdateStateOnDownloadFailure(current, error.message),
743 );
744 yield* logUpdaterError(error.message, {
745 errorTag: error._tag,
746 cause: describeUpdateErrorCause(error.cause),
747 action: error.action,
748 });
749 return { accepted: true, completed: false };
750 });
751 }),
752 Effect.ensuring(finishUpdateAction("download")),
753 );
754 });
755
756 const updateRestartMarkerDir = environment.path.join(environment.baseDir, "runtime");
757 const updateRestartMarkerPath = environment.path.join(
758 updateRestartMarkerDir,
759 DESKTOP_UPDATE_RESTART_MARKER_FILE,
760 );
761 const writeUpdateRestartMarker = fileSystem
762 .makeDirectory(updateRestartMarkerDir, { recursive: true })
763 .pipe(
764 Effect.andThen(fileSystem.writeFileString(updateRestartMarkerPath, "")),
765 Effect.catch((error) =>
766 logUpdaterWarning("Could not write the update restart marker.", { errorTag: error._tag }),
767 ),
768 );
769
770 const updateInProgressMarkerPath = environment.path.join(
771 updateRestartMarkerDir,
772 DESKTOP_UPDATE_IN_PROGRESS_MARKER_FILE,
773 );
774 const encodeUpdateMarker = Schema.encodeEffect(
775 Schema.fromJsonString(Schema.Struct({ startedAt: Schema.Number, expiresAt: Schema.Number })),
776 );
777 const updateInProgressTempPath = `${updateInProgressMarkerPath}.tmp`;
778 const writeUpdateInProgressMarker = Effect.gen(function* () {
779 const startedAt = DateTime.toEpochMillis(yield* DateTime.now);
780 const contents = yield* encodeUpdateMarker({
781 startedAt,
782 expiresAt: startedAt + DESKTOP_UPDATE_IN_PROGRESS_TTL_MS,
783 });
784 yield* fileSystem.writeFileString(updateInProgressTempPath, contents);
785 yield* fileSystem.rename(updateInProgressTempPath, updateInProgressMarkerPath);
786 }).pipe(
787 Effect.ensuring(
788 fileSystem.remove(updateInProgressTempPath, { force: true }).pipe(Effect.ignore),
789 ),
790 Effect.catch((error) =>
791 logUpdaterWarning("Could not write the update-in-progress marker.", { errorTag: error._tag }),
792 ),
793 );
794 const removeUpdateInProgressMarker = fileSystem
795 .remove(updateInProgressMarkerPath, { force: true })
796 .pipe(Effect.ignore);
797
798 // Failed or interrupted installs leave no replacement backend; later quits must release the tunnel.
799 const removeUpdateRestartMarker = fileSystem
800 .remove(updateRestartMarkerPath, { force: true })
801 .pipe(Effect.ignore);
802
803 const installRecordPath = environment.path.join(
804 updateRestartMarkerDir,
805 DESKTOP_UPDATE_INSTALL_RECORD_FILE,
806 );
807 const writeInstallRecord = (targetVersion: string) =>
808 encodeInstallRecord({ fromVersion: environment.appVersion, targetVersion }).pipe(
809 Effect.flatMap((text) => fileSystem.writeFileString(installRecordPath, text)),
810 Effect.catch((error) =>
811 logUpdaterWarning("Could not record the update install.", { errorTag: error._tag }),
812 ),
813 );
814 const removeInstallRecord = fileSystem
815 .remove(installRecordPath, { force: true })
816 .pipe(Effect.ignore);
817
818 const readNotAppliedInstallVersion = fileSystem.readFileString(installRecordPath).pipe(
819 Effect.flatMap(decodeInstallRecord),
820 Effect.option,
821 Effect.map((record) =>
822 Option.flatMap(record, (value) =>
823 Option.fromNullishOr(resolveNotAppliedInstallVersion(value, environment.appVersion)),
824 ),
825 ),
826 Effect.tap((notAppliedVersion) =>
827 Option.isNone(notAppliedVersion) ? removeInstallRecord : Effect.void,
828 ),
829 );
830
831 const baseUpdateState = (channel: DesktopUpdateChannel, disabledReason: Option.Option<string>) =>
832 Ref.get(notAppliedVersionRef).pipe(
833 Effect.map((notAppliedVersion) => ({
834 ...createBaseUpdateState(channel, disabledReason, environment),
835 // Callers fall back to the channel's reason only when nothing else turns updates off.
836 ...(Option.isSome(disabledReason) &&
837 disabledReason.value === Option.getOrUndefined(channelBlockedReason(channel))
838 ? { channelBlockedByPolicy: true as const }
839 : {}),
840 ...Option.match(notAppliedVersion, {
841 onNone: () => ({}),
842 onSome: (version) => ({ notAppliedVersion: version }),
843 }),
844 })),
845 );
846
847 const resetInstallAction = Effect.all(
848 [
849 finishUpdateAction("install"),
850 Ref.set(desktopState.quitting, false),
851 Ref.set(installRunningBackendsRef, []),
852 removeUpdateRestartMarker,
853 removeUpdateInProgressMarker,
854 removeInstallRecord,
855 ],
856 { discard: true },
857 );
858
859 const recoverFailedInstall = Effect.fn("desktop.updates.recoverFailedInstall")(function* (
860 message: string,
861 ) {
862 const ownsRecovery = yield* Ref.modify(activeUpdateActionRef, (activeAction) =>
863 Option.isSome(activeAction) && activeAction.value === "install"
864 ? ([true, Option.some<UpdateAction>("install-recovery")] as const)
865 : ([false, activeAction] as const),
866 );
867 if (!ownsRecovery) return;
868
869 yield* Ref.set(desktopState.quitting, false);
870 yield* removeUpdateRestartMarker;
871 yield* removeUpdateInProgressMarker;
872 yield* removeInstallRecord;
873 yield* Effect.gen(function* () {
874 const runningInstances = yield* Ref.getAndSet(installRunningBackendsRef, []);
875 const instances = (yield* pool.list).filter((instance) =>
876 runningInstances.includes(instance),
877 );
878 const restartExit = yield* Effect.forEach(instances, (instance) => instance.start, {
879 concurrency: "unbounded",
880 discard: true,
881 }).pipe(Effect.exit);
882 yield* updateState((current) => reduceDesktopUpdateStateOnInstallFailure(current, message));
883 if (Exit.isFailure(restartExit)) {
884 yield* logUpdaterError("Desktop update install recovery could not restart every backend.");
885 }
886 }).pipe(
887 Effect.catchCause(() =>
888 logUpdaterError("Desktop update install recovery failed unexpectedly."),
889 ),
890 Effect.ensuring(finishUpdateAction("install-recovery")),
891 );
892 });
893
894 const installDownloadedUpdate = (expectedVersion?: string) =>
895 Effect.scoped(
896 Effect.gen(function* () {
897 const admission = yield* admitAfterCheck(
898 Effect.gen(function* () {
899 const state = yield* Ref.get(updateStateRef);
900 const activeAction = yield* Ref.get(activeUpdateActionRef);
901 const hasExpectedDownload =
902 state.downloadedVersion !== null &&
903 (expectedVersion === undefined || state.downloadedVersion === expectedVersion);
904 if (
905 (yield* Ref.get(desktopState.quitting)) ||
906 !(yield* Ref.get(updaterConfiguredRef)) ||
907 !hasExpectedDownload
908 ) {
909 return "refused" as const;
910 }
911 if (Option.isSome(activeAction)) {
912 return activeAction.value === "check"
913 ? ("wait-for-check" as const)
914 : ("refused" as const);
915 }
916 const hasInstallableDownload =
917 state.status === "downloaded" ||
918 (state.status === "error" &&
919 (state.errorContext === null || state.errorContext === "install"));
920 if (!hasInstallableDownload) return "refused" as const;
921 return (yield* tryStartUpdateAction("install"))
922 ? ("admitted" as const)
923 : ("refused" as const);
924 }),
925 );
926 if (admission === "refused") {
927 return { accepted: false, completed: false, failed: false };
928 }
929
930 yield* Ref.set(desktopState.quitting, true);
931 yield* Ref.set(installRunningBackendsRef, []);
932
933 return yield* Effect.gen(function* () {
934 yield* writeUpdateRestartMarker;
935 yield* writeUpdateInProgressMarker;
936 const { downloadedVersion } = yield* Ref.get(updateStateRef);
937 if (downloadedVersion !== null) yield* writeInstallRecord(downloadedVersion);
938 // Stop pooled backends and SSH tunnels before quitAndInstall can outrun their scope finalizers.
939 const instances = yield* pool.list;
940 // stop clears desiredRunning, so retain the recovery set beforehand.
941 const runningInstances = yield* Effect.filter(instances, (instance) =>
942 instance.snapshot.pipe(Effect.map((snapshot) => snapshot.desiredRunning)),
943 );
944 yield* Ref.set(installRunningBackendsRef, runningInstances);
945 yield* Effect.all(
946 [
947 Effect.forEach(
948 instances,
949 (instance) =>
950 instance.stop({ timeout: DesktopBackendManager.BACKEND_QUIT_STOP_TIMEOUT }),
951 { concurrency: "unbounded" },
952 ),
953 sshEnvironment.closeAllTunnels,
954 ],
955 { concurrency: "unbounded" },
956 );
957 yield* electronUpdater.quitAndInstall({
958 isSilent: true,
959 isForceRunAfter: true,
960 });
961 return { accepted: true, completed: false, failed: false };
962 }).pipe(
963 Effect.catchTags({
964 ElectronUpdaterQuitAndInstallError: Effect.fn("desktop.updates.handleInstallFailure")(
965 function* (error) {
966 yield* recoverFailedInstall(error.message);
967 yield* logUpdaterError(error.message, {
968 errorTag: error._tag,
969 cause: describeUpdateErrorCause(error.cause),
970 channel: error.channel,
971 isSilent: error.isSilent,
972 isForceRunAfter: error.isForceRunAfter,
973 });
974 return { accepted: true, completed: false, failed: true };
975 },
976 ),
977 }),
978 Effect.onInterrupt(() => resetInstallAction),
979 Effect.catchCause((cause) =>
980 Effect.gen(function* () {
981 if (Cause.hasInterruptsOnly(cause)) {
982 return yield* Effect.failCause(cause);
983 }
984 const error = new DesktopUpdateUnexpectedActionError({ action: "install", cause });
985 yield* recoverFailedInstall(error.message);
986 yield* logUpdaterError(error.message, {
987 errorTag: error._tag,
988 cause: describeUpdateErrorCause(error.cause),
989 action: error.action,
990 });
991 return { accepted: true, completed: false, failed: true };
992 }),
993 ),
994 );
995 }),
996 ).pipe(Effect.withSpan("desktop.updates.installDownloadedUpdate"));
997
998 const installWithExpectedVersion = Effect.fn("desktop.updates.install")(function* (
999 expectedVersion?: string,
1000 ) {
1001 if (yield* Ref.get(desktopState.quitting)) {
1002 return {
1003 accepted: false,
1004 completed: false,
1005 failed: false,
1006 state: yield* Ref.get(updateStateRef),
1007 };
1008 }
1009 let installVersion = expectedVersion;
1010 // A download can be hours old: a release published since replaces it before restarting.
1011 const retained = yield* Ref.get(updateStateRef);
1012 if (
1013 retained.downloadedVersion !== null &&
1014 (expectedVersion === undefined || retained.downloadedVersion === expectedVersion) &&
1015 (yield* checkForUpdates(
1016 "install",
1017 "acquire",
1018 retained.channel !== desktopUpdateChannelOf(environment.appVersion),
1019 )) &&
1020 (yield* Ref.get(updateStateRef)).status === "available"
1021 ) {
1022 const refreshed = yield* Ref.get(updateStateRef);
1023 // electron-updater compares a stale feed with the running build, not the retained download.
1024 if (
1025 refreshed.availableVersion === null ||
1026 compareSemverVersions(refreshed.availableVersion, retained.downloadedVersion) <= 0
1027 ) {
1028 yield* setState(retained);
1029 } else {
1030 const download = yield* downloadAvailableUpdate(false);
1031 if (!download.completed) {
1032 return {
1033 accepted: download.accepted,
1034 completed: false,
1035 failed: download.accepted,
1036 state: yield* Ref.get(updateStateRef),
1037 };
1038 }
1039 if (expectedVersion !== undefined) {
1040 installVersion = (yield* Ref.get(updateStateRef)).downloadedVersion ?? expectedVersion;
1041 }
1042 }
1043 }
1044 const result = yield* installDownloadedUpdate(installVersion);
1045 return {
1046 accepted: result.accepted,
1047 completed: result.completed,
1048 failed: result.failed,
1049 state: yield* Ref.get(updateStateRef),
1050 };
1051 });
1052
1053 const startUpdatePollers: Effect.Effect<void, never, Scope.Scope> = Effect.gen(function* () {
1054 yield* Effect.sleep(AUTO_UPDATE_STARTUP_DELAY).pipe(
1055 Effect.andThen(checkForUpdates("startup")),
1056 Effect.catchCause((cause) => {
1057 if (Cause.hasInterruptsOnly(cause)) {
1058 return Effect.void;
1059 }
1060 const error = new DesktopUpdatePollerError({ poller: "startup", cause });
1061 return logUpdaterError(error.message, {
1062 errorTag: error._tag,
1063 cause: describeUpdateErrorCause(error.cause),
1064 poller: error.poller,
1065 });
1066 }),
1067 Effect.forkScoped,
1068 );
1069 yield* Effect.sleep(AUTO_UPDATE_POLL_INTERVAL).pipe(
1070 Effect.andThen(checkForUpdates("poll")),
1071 Effect.forever,
1072 Effect.catchCause((cause) => {
1073 if (Cause.hasInterruptsOnly(cause)) {
1074 return Effect.void;
1075 }
1076 const error = new DesktopUpdatePollerError({ poller: "poll", cause });
1077 return logUpdaterError(error.message, {
1078 errorTag: error._tag,
1079 cause: describeUpdateErrorCause(error.cause),
1080 poller: error.poller,
1081 });
1082 }),
1083 Effect.forkScoped,
1084 );
1085 }).pipe(Effect.withSpan("desktop.updates.startPollers"));
1086
1087 const handleUpdateAvailable = Effect.fn("desktop.updates.handleUpdateAvailable")(function* (
1088 raw: unknown,
1089 ) {
1090 yield* decodeUpdateInfo(raw).pipe(
1091 Effect.flatMap(
1092 Effect.fn("desktop.updates.applyUpdateAvailable")(function* (info) {
1093 const state = yield* Ref.get(updateStateRef);
1094 if (!(yield* offerable(info.version, state))) {
1095 yield* logUpdaterInfo("ignoring update outside the selected channel or its floor", {
1096 version: info.version,
1097 channel: state.channel,
1098 });
1099 const checkedAt = yield* currentIsoTimestamp;
1100 yield* setState(yield* noOfferState(state, checkedAt));
1101 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
1102 return;
1103 }
1104 if (isOffered(state) && state.availableVersion === info.version) return;
1105
1106 const checkedAt = yield* currentIsoTimestamp;
1107 const { releaseNotes, omittedReleaseCount } = normalizeDesktopUpdateReleaseNotes(
1108 releaseNotesOfOfferedVersion(info),
1109 info.version,
1110 state.channel,
1111 info.releaseDate,
1112 );
1113 yield* setState(
1114 reduceDesktopUpdateStateOnUpdateAvailable(
1115 state,
1116 info.version,
1117 checkedAt,
1118 releaseNotes,
1119 omittedReleaseCount,
1120 ),
1121 );
1122 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
1123 yield* logUpdaterInfo("update available", {
1124 version: info.version,
1125 releaseNoteGroups: releaseNotes.length,
1126 omittedReleaseCount,
1127 });
1128 }),
1129 ),
1130 Effect.catchCause((cause) => {
1131 if (Cause.hasInterruptsOnly(cause)) {
1132 return Effect.void;
1133 }
1134 const error = new DesktopUpdateEventHandlingError({ event: "update-available", cause });
1135 return logUpdaterWarning(error.message, {
1136 errorTag: error._tag,
1137 cause: describeUpdateErrorCause(error.cause),
1138 event: error.event,
1139 });
1140 }),
1141 );
1142 });
1143
1144 const handleUpdateNotAvailable = Effect.gen(function* () {
1145 const checkedAt = yield* currentIsoTimestamp;
1146 const state = yield* Ref.get(updateStateRef);
1147 yield* setState(yield* noOfferState(state, checkedAt));
1148 yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
1149 yield* logUpdaterInfo("no updates available");
1150 }).pipe(Effect.withSpan("desktop.updates.handleUpdateNotAvailable"));
1151
1152 const handleUpdaterError = Effect.fn("desktop.updates.handleUpdaterError")(function* (
1153 cause: unknown,
1154 ) {
1155 const activeAction = yield* activeUpdateAction;
1156 const error = new DesktopUpdaterReportedError({
1157 operation: Option.match(activeAction, {
1158 onNone: () => "background" as const,
1159 onSome: (action) => (action === "install-recovery" ? "install" : action),
1160 }),
1161 cause,
1162 });
1163 if (Option.isSome(activeAction) && activeAction.value === "install") {
1164 yield* recoverFailedInstall(error.message);
1165 yield* logUpdaterError(error.message, {
1166 errorTag: error._tag,
1167 cause: describeUpdateErrorCause(error.cause),
1168 operation: error.operation,
1169 });
1170 return;
1171 }
1172
1173 if (Option.isNone(activeAction)) {
1174 const checkedAt = yield* currentIsoTimestamp;
1175 yield* updateState(({ trackMismatch: _trackMismatch, ...current }) => ({
1176 ...current,
1177 status: "error",
1178 message: error.message,
1179 checkedAt,
1180 downloadPercent: null,
1181 errorContext: current.errorContext,
1182 canRetry: getCanRetryFromState(current),
1183 }));
1184 }
1185
1186 yield* logUpdaterError(error.message, {
1187 errorTag: error._tag,
1188 cause: describeUpdateErrorCause(error.cause),
1189 operation: error.operation,
1190 });
1191 });
1192
1193 const handleDownloadProgress = Effect.fn("desktop.updates.handleDownloadProgress")(function* (
1194 raw: unknown,
1195 ) {
1196 yield* decodeDownloadProgressInfo(raw).pipe(
1197 Effect.flatMap(
1198 Effect.fn("desktop.updates.applyDownloadProgress")(function* (progress) {
1199 const state = yield* Ref.get(updateStateRef);
1200 const percent = Math.floor(progress.percent);
1201 if (shouldBroadcastDownloadProgress(state, progress.percent) || state.message !== null) {
1202 yield* setState(reduceDesktopUpdateStateOnDownloadProgress(state, progress.percent));
1203 }
1204 const milestone = percent - (percent % 10);
1205 const lastLoggedMilestone = yield* Ref.get(lastLoggedDownloadMilestoneRef);
1206 if (milestone > lastLoggedMilestone) {
1207 yield* Ref.set(lastLoggedDownloadMilestoneRef, milestone);
1208 yield* logUpdaterInfo("download progress", { percent });
1209 }
1210 }),
1211 ),
1212 Effect.catchCause((cause) => {
1213 if (Cause.hasInterruptsOnly(cause)) {
1214 return Effect.void;
1215 }
1216 const error = new DesktopUpdateEventHandlingError({ event: "download-progress", cause });
1217 return logUpdaterWarning(error.message, {
1218 errorTag: error._tag,
1219 cause: describeUpdateErrorCause(error.cause),
1220 event: error.event,
1221 });
1222 }),
1223 );
1224 });
1225
1226 const handleUpdateDownloaded = Effect.fn("desktop.updates.handleUpdateDownloaded")(function* (
1227 raw: unknown,
1228 ) {
1229 yield* decodeUpdateInfo(raw).pipe(
1230 Effect.flatMap(
1231 Effect.fn("desktop.updates.applyUpdateDownloaded")(function* (info) {
1232 const state = yield* Ref.get(updateStateRef);
1233 // A download can finish after its track switch moved on; never offer that build.
1234 if (!(yield* offerable(info.version, state))) {
1235 yield* logUpdaterInfo("ignoring download outside the selected channel or its floor", {
1236 version: info.version,
1237 channel: state.channel,
1238 });
1239 // Its progress events left the updater "downloading", which would block every check.
1240 if (state.status === "downloading") {
1241 yield* setState(
1242 reduceDesktopUpdateStateOnNoUpdate(state, yield* currentIsoTimestamp),
1243 );
1244 }
1245 return;
1246 }
1247 yield* setState(reduceDesktopUpdateStateOnDownloadComplete(state, info.version));
1248 yield* logUpdaterInfo("update downloaded", { version: info.version });
1249 }),
1250 ),
1251 Effect.catchCause((cause) => {
1252 if (Cause.hasInterruptsOnly(cause)) {
1253 return Effect.void;
1254 }
1255 const error = new DesktopUpdateEventHandlingError({ event: "update-downloaded", cause });
1256 return logUpdaterWarning(error.message, {
1257 errorTag: error._tag,
1258 cause: describeUpdateErrorCause(error.cause),
1259 event: error.event,
1260 });
1261 }),
1262 );
1263 });
1264
1265 return DesktopUpdates.of({
1266 getState: Ref.get(updateStateRef),
1267 isActionActive: activeUpdateAction.pipe(Effect.map(Option.isSome)),
1268 isInstallActive: activeUpdateAction.pipe(
1269 Effect.map((action) => Option.isSome(action) && action.value === "install"),
1270 ),
1271 subscribe: stateMutex.withPermits(1)(
1272 Effect.gen(function* () {
1273 const subscription = yield* PubSub.subscribe(stateChanges);
1274 const latest = yield* Ref.get(updateStateRef);
1275 return { latest, changes: Stream.fromSubscription(subscription) };
1276 }),
1277 ),
1278 emitState,
1279 disabledReason: Ref.get(updateStateRef).pipe(
1280 Effect.flatMap((state) => resolveStateDisabledReason(state.channel)),
1281 ),
1282 configure: Effect.gen(function* () {
1283 const context = yield* Effect.context<never>();
1284 // Runs synchronously up to the first await, so a check's outcome is applied before the
1285 // check's promise resolves and wakes the actions waiting on it.
1286 const runEffect = (effect: Effect.Effect<void>) => {
1287 void Effect.runPromiseWith(context)(effect);
1288 };
1289
1290 const appUpdateYmlConfig = yield* readAppUpdateYml;
1291 yield* Ref.set(appUpdateYmlConfigRef, appUpdateYmlConfig);
1292
1293 const notAppliedVersion = yield* readNotAppliedInstallVersion;
1294 yield* Ref.set(notAppliedVersionRef, notAppliedVersion);
1295 if (Option.isSome(notAppliedVersion)) {
1296 yield* logUpdaterWarning("the last update install did not apply", {
1297 version: environment.appVersion,
1298 targetVersion: notAppliedVersion.value,
1299 });
1300 }
1301
1302 if (mockUpdates) {
1303 yield* electronUpdater.setFeedURL({
1304 provider: "generic",
1305 url: `http://localhost:${config.mockUpdateServerPort}`,
1306 } as ElectronUpdater.ElectronUpdaterFeedUrl);
1307 } else if (policy.feedUrl !== undefined) {
1308 // The administrator's mirror replaces the GitHub feed baked into app-update.yml.
1309 yield* electronUpdater.setFeedURL({
1310 provider: "generic",
1311 url: policy.feedUrl,
1312 } as ElectronUpdater.ElectronUpdaterFeedUrl);
1313 }
1314
1315 const settings = yield* desktopSettings.get;
1316 const disabledReason = yield* resolveDisabledReason;
1317 // A blocked nightly channel still lets the user switch back to stable, so it stays updatable.
1318 yield* Ref.set(desktopState.canInstallUpdates, Option.isNone(disabledReason));
1319 yield* setState(
1320 yield* baseUpdateState(
1321 settings.updateChannel,
1322 Option.orElse(disabledReason, () => channelBlockedReason(settings.updateChannel)),
1323 ),
1324 );
1325 if (Option.isSome(disabledReason)) {
1326 return;
1327 }
1328 yield* Ref.set(updaterConfiguredRef, true);
1329
1330 yield* electronUpdater.setAutoDownload(false);
1331 yield* electronUpdater.setAutoInstallOnAppQuit(false);
1332 yield* applyAutoUpdaterChannel(settings.updateChannel);
1333 yield* electronUpdater.setDisableDifferentialDownload(
1334 isArm64HostRunningIntelBuild(environment.runtimeInfo),
1335 );
1336
1337 if (isArm64HostRunningIntelBuild(environment.runtimeInfo)) {
1338 yield* logUpdaterInfo(
1339 "Apple Silicon host detected while running Intel build; updates will switch to arm64 packages",
1340 );
1341 }
1342
1343 yield* electronUpdater.on("checking-for-update", () => {
1344 runEffect(
1345 logUpdaterInfo("looking for updates").pipe(
1346 Effect.withSpan("desktop.updates.handleCheckingForUpdate"),
1347 ),
1348 );
1349 });
1350 yield* electronUpdater.on("update-available", (info: unknown) => {
1351 runEffect(handleUpdateAvailable(info));
1352 });
1353 yield* electronUpdater.on("update-not-available", () => {
1354 runEffect(handleUpdateNotAvailable);
1355 });
1356 yield* electronUpdater.on("error", (error: unknown) => {
1357 runEffect(handleUpdaterError(error));
1358 });
1359 yield* electronUpdater.on("download-progress", (progress: unknown) => {
1360 runEffect(handleDownloadProgress(progress));
1361 });
1362 yield* electronUpdater.on("update-downloaded", (info: unknown) => {
1363 runEffect(handleUpdateDownloaded(info));
1364 });
1365
1366 yield* startUpdatePollers;
1367 }).pipe(Effect.withSpan("desktop.updates.configure")),
1368 setChannel: Effect.fn("desktop.updates.setChannel")(function* (
1369 nextChannel: DesktopUpdateChannel,
1370 options?: { readonly minimumVersion?: string | undefined },
1371 ) {
1372 yield* Effect.annotateCurrentSpan({ channel: nextChannel });
1373 if (Option.isSome(channelBlockedReason(nextChannel))) {
1374 return yield* new DesktopUpdateChannelManagedError({
1375 channel: nextChannel,
1376 policyMessage: policy.message ?? "Your administrator manages T3 Code updates.",
1377 });
1378 }
1379 // A background check holds the updater only briefly, so wait it out instead of refusing.
1380 const activeAction = yield* tryStartChannelChange.pipe(
1381 Effect.repeat({
1382 while: (active) => Option.isSome(active) && active.value === "check",
1383 schedule: Schedule.spaced(CHANNEL_CHANGE_RETRY_DELAY),
1384 times: CHANNEL_CHANGE_RETRIES,
1385 }),
1386 );
1387 if (Option.isSome(activeAction)) {
1388 return yield* new DesktopUpdateActionInProgressError({
1389 action: activeAction.value === "install-recovery" ? "install" : activeAction.value,
1390 requestedChannel: nextChannel,
1391 });
1392 }
1393
1394 return yield* Effect.gen(function* () {
1395 const previousFloor = yield* Ref.getAndSet(
1396 releaseFloorRef,
1397 Option.fromNullishOr(options?.minimumVersion),
1398 );
1399 const state = yield* Ref.get(updateStateRef);
1400 const retained = state.downloadedVersion ?? state.availableVersion;
1401 // A build from another track re-checks, so retrying a track switch finds an older release.
1402 // So does a retained offer below the new floor, which must not install.
1403 if (
1404 nextChannel === state.channel &&
1405 nextChannel === desktopUpdateChannelOf(environment.appVersion) &&
1406 (retained === null || (yield* offerable(retained, state)))
1407 ) {
1408 return state;
1409 }
1410
1411 yield* desktopSettings.setUpdateChannel(nextChannel).pipe(
1412 Effect.onError(() => Ref.set(releaseFloorRef, previousFloor)),
1413 Effect.mapError(
1414 (cause) => new DesktopUpdateChannelPersistenceError({ channel: nextChannel, cause }),
1415 ),
1416 );
1417
1418 const disabledReason = yield* resolveDisabledReason;
1419 yield* setState(yield* baseUpdateState(nextChannel, disabledReason));
1420
1421 if (Option.isSome(disabledReason) || !(yield* Ref.get(updaterConfiguredRef))) {
1422 return yield* Ref.get(updateStateRef);
1423 }
1424
1425 yield* applyAutoUpdaterChannel(nextChannel);
1426 // Only leaving the running build's track can need an older release.
1427 yield* checkForUpdates(
1428 "channel-change",
1429 "held",
1430 nextChannel !== desktopUpdateChannelOf(environment.appVersion),
1431 );
1432 return yield* Ref.get(updateStateRef);
1433 }).pipe(Effect.ensuring(finishUpdateAction("channel")));
1434 }),
1435 check: Effect.fn("desktop.updates.check")(function* (
1436 reason: string,
1437 options?: { readonly allowDowngrade?: boolean },
1438 ) {
1439 yield* Effect.annotateCurrentSpan({ reason });
1440 if (!(yield* Ref.get(updaterConfiguredRef))) {
1441 return {
1442 checked: false,
1443 state: yield* Ref.get(updateStateRef),
1444 };
1445 }
1446 const checked = yield* checkForUpdates(reason, "acquire", options?.allowDowngrade === true);
1447 return {
1448 checked,
1449 state: yield* Ref.get(updateStateRef),
1450 };
1451 }),
1452 download: Effect.gen(function* () {
1453 const result = yield* downloadAvailableUpdate(true);
1454 return {
1455 accepted: result.accepted,
1456 completed: result.completed,
1457 state: yield* Ref.get(updateStateRef),
1458 };
1459 }).pipe(Effect.withSpan("desktop.updates.download")),
1460 install: installWithExpectedVersion().pipe(
1461 Effect.map(({ accepted, completed, state }) => ({ accepted, completed, state })),
1462 ),
1463 installPrepared: Effect.fn("DesktopUpdates.installPrepared")(function (expectedVersion) {
1464 return installWithExpectedVersion(expectedVersion);
1465 }),
1466 });
1467 });
1468
1469 export const layer = Layer.effect(DesktopUpdates, make);