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
| 1 | import { |
| 2 | managedNightlyDeniedMessage, |
| 3 | managedUpdatesDenial, |
| 4 | } from "@t3tools/client-runtime/contract-labels"; |
| 5 | import type { ServerUpdateState } from "@t3tools/client-runtime/state/server"; |
| 6 | import { |
| 7 | type DesktopUpdateChannel, |
| 8 | type EnvironmentId, |
| 9 | type ServerConfig, |
| 10 | type ServerSelfUpdateCapability, |
| 11 | } from "@t3tools/contracts"; |
| 12 | import { cliReleaseChannelOf, desktopUpdateChannelOf } from "@t3tools/shared/cliRelease"; |
| 13 | import { compareSemverVersions } from "@t3tools/shared/semver"; |
| 14 | import { msg } from "gt-react"; |
| 15 | |
| 16 | import { m, type MessageResolver } from "~/i18n/messages"; |
| 17 | import { |
| 18 | resolveServerSelfUpdateCapability, |
| 19 | resolveVersionMismatch, |
| 20 | supportsDesktopAppUpdate, |
| 21 | } from "~/versionSkew"; |
| 22 | import type { ServerUpdateOutcome, ServerUpdateTarget } from "../ServerUpdateAction"; |
| 23 | |
| 24 | export interface UpdateEverythingMachine { |
| 25 | readonly environmentId: EnvironmentId; |
| 26 | readonly label: string; |
| 27 | readonly serverConfig: { |
| 28 | readonly environment: ServerConfig["environment"]; |
| 29 | readonly settings: Pick<ServerConfig["settings"], "continueThreadsAfterServerUpdate">; |
| 30 | readonly managedPolicy?: ServerConfig["managedPolicy"]; |
| 31 | } | null; |
| 32 | readonly connected: boolean; |
| 33 | readonly hostedByThisApp: boolean; |
| 34 | readonly canMaintain: boolean; |
| 35 | readonly updateState: ServerUpdateState; |
| 36 | } |
| 37 | |
| 38 | export interface RestartingMachine { |
| 39 | readonly environmentId: EnvironmentId; |
| 40 | readonly continuesThreads: boolean; |
| 41 | } |
| 42 | |
| 43 | export function collectRestartingMachines( |
| 44 | machines: ReadonlyArray<UpdateEverythingMachine>, |
| 45 | servers: ReadonlyArray<Pick<ServerUpdateTarget, "environmentId">>, |
| 46 | installsLocal: boolean, |
| 47 | ): RestartingMachine[] { |
| 48 | const updated = new Set(servers.map((server) => server.environmentId)); |
| 49 | return machines.flatMap((machine) => { |
| 50 | const config = machine.serverConfig; |
| 51 | if ( |
| 52 | config === null || |
| 53 | !machine.connected || |
| 54 | !(updated.has(machine.environmentId) || (installsLocal && machine.hostedByThisApp)) |
| 55 | ) { |
| 56 | return []; |
| 57 | } |
| 58 | return [ |
| 59 | { |
| 60 | environmentId: machine.environmentId, |
| 61 | continuesThreads: config.settings.continueThreadsAfterServerUpdate === true, |
| 62 | }, |
| 63 | ]; |
| 64 | }); |
| 65 | } |
| 66 | |
| 67 | export interface SkippedMachine { |
| 68 | readonly environmentId: EnvironmentId; |
| 69 | readonly label: string; |
| 70 | readonly reason: string; |
| 71 | } |
| 72 | |
| 73 | /** Skip current and app-hosted servers; the latter update with the app and would relaunch mid-run. |
| 74 | * Desktop-managed servers use their own feed. Each server's updater checks that it can install the |
| 75 | * release before it restarts, so no registry precheck runs here. */ |
| 76 | export function collectServerUpdateTargets( |
| 77 | machines: ReadonlyArray<UpdateEverythingMachine>, |
| 78 | targetVersion: string, |
| 79 | resolve: MessageResolver = m, |
| 80 | ): { |
| 81 | readonly targets: ServerUpdateTarget[]; |
| 82 | readonly skipped: SkippedMachine[]; |
| 83 | } { |
| 84 | const targets: ServerUpdateTarget[] = []; |
| 85 | const skipped: SkippedMachine[] = []; |
| 86 | for (const machine of machines) { |
| 87 | const config = machine.serverConfig; |
| 88 | if (machine.hostedByThisApp) continue; |
| 89 | if ( |
| 90 | config !== null && |
| 91 | resolveVersionMismatch(config.environment.serverVersion, targetVersion) === null |
| 92 | ) { |
| 93 | continue; |
| 94 | } |
| 95 | const skip = (reason: string) => |
| 96 | skipped.push({ environmentId: machine.environmentId, label: machine.label, reason }); |
| 97 | const unavailable = unavailableReason(machine, resolve); |
| 98 | if (config === null || unavailable !== null) { |
| 99 | skip(unavailable ?? resolve(msg("not connected"))); |
| 100 | continue; |
| 101 | } |
| 102 | const selfUpdate = resolveServerSelfUpdateCapability(config); |
| 103 | const managedDenial = managedMachineUpdateDenial( |
| 104 | config, |
| 105 | selfUpdate === "desktop-managed" ? undefined : targetVersion, |
| 106 | resolve, |
| 107 | ); |
| 108 | if (managedDenial !== undefined) { |
| 109 | skip(managedDenial); |
| 110 | continue; |
| 111 | } |
| 112 | const desktopAppUpdate = supportsDesktopAppUpdate(config); |
| 113 | if (selfUpdate === null) { |
| 114 | skip(resolve(msg("needs a manual update"))); |
| 115 | continue; |
| 116 | } |
| 117 | if (selfUpdate === "desktop-managed" && !desktopAppUpdate) { |
| 118 | skip(resolve(msg("needs a newer desktop app"))); |
| 119 | continue; |
| 120 | } |
| 121 | const serverChannel = cliReleaseChannelOf(config.environment.serverVersion); |
| 122 | // A desktop app installs its own track's newest release. Nightly builds run ahead of Stable, so a |
| 123 | // Nightly host behind a Stable target has something newer; a Stable host may not. |
| 124 | if ( |
| 125 | serverChannel !== cliReleaseChannelOf(targetVersion) && |
| 126 | (selfUpdate !== "desktop-managed" || serverChannel === "stable") |
| 127 | ) { |
| 128 | skip(resolve(msg("on the {channel} channel", { channel: serverChannel }))); |
| 129 | continue; |
| 130 | } |
| 131 | const target: ServerUpdateTarget = { |
| 132 | environmentId: machine.environmentId, |
| 133 | serverLabel: machine.label, |
| 134 | selfUpdate, |
| 135 | installation: config.environment.capabilities.serverInstallation, |
| 136 | desktopAppUpdate, |
| 137 | targetVersion, |
| 138 | }; |
| 139 | targets.push(target); |
| 140 | } |
| 141 | return { targets, skipped }; |
| 142 | } |
| 143 | |
| 144 | function unavailableReason( |
| 145 | machine: UpdateEverythingMachine, |
| 146 | resolve: MessageResolver, |
| 147 | ): string | null { |
| 148 | if (machine.serverConfig === null || !machine.connected) return resolve(msg("not connected")); |
| 149 | if (!machine.canMaintain) return resolve(msg("no permission")); |
| 150 | if (machine.updateState.status === "running") return resolve(msg("already updating")); |
| 151 | return null; |
| 152 | } |
| 153 | |
| 154 | /** The latest release on the track a fleet switches to, as npm reports it. */ |
| 155 | export interface ChannelSwitchRelease { |
| 156 | readonly channel: DesktopUpdateChannel; |
| 157 | readonly version: string; |
| 158 | readonly databaseMigration: number | undefined; |
| 159 | } |
| 160 | |
| 161 | /** Components pass `useMessages()` so labels follow a language switch. */ |
| 162 | export const channelSwitchLabel = (channel: DesktopUpdateChannel, resolve: MessageResolver = m) => |
| 163 | channel === "nightly" |
| 164 | ? resolve(msg("Nightly", { $context: "release track" })) |
| 165 | : resolve(msg("Stable", { $context: "release track" })); |
| 166 | |
| 167 | /** Stable and Nightly each build their own commits, so either can hold migrations the other lacks. |
| 168 | * Crossing tracks needs proof that the target release knows every migration the database holds. */ |
| 169 | const crossesTrack = (fromVersion: string, release: ChannelSwitchRelease) => |
| 170 | desktopUpdateChannelOf(fromVersion) !== release.channel; |
| 171 | |
| 172 | type ChannelSwitchBlock = "server-predates-checks" | "release-predates-checks" | "unsupported"; |
| 173 | |
| 174 | function channelSwitchBlock( |
| 175 | fromVersion: string, |
| 176 | release: ChannelSwitchRelease, |
| 177 | currentMigration: number | undefined, |
| 178 | ): ChannelSwitchBlock | null { |
| 179 | if (!crossesTrack(fromVersion, release)) return null; |
| 180 | // Servers and releases from before this check report no migration number. |
| 181 | if (currentMigration === undefined) return "server-predates-checks"; |
| 182 | if (release.databaseMigration === undefined) return "release-predates-checks"; |
| 183 | return currentMigration > release.databaseMigration ? "unsupported" : null; |
| 184 | } |
| 185 | |
| 186 | function channelSwitchBlockReason( |
| 187 | fromVersion: string, |
| 188 | release: ChannelSwitchRelease, |
| 189 | currentMigration: number | undefined, |
| 190 | resolve: MessageResolver, |
| 191 | ): string | null { |
| 192 | const block = channelSwitchBlock(fromVersion, release, currentMigration); |
| 193 | if (block === null) return null; |
| 194 | const from = channelSwitchLabel(desktopUpdateChannelOf(fromVersion), resolve); |
| 195 | const to = channelSwitchLabel(release.channel, resolve); |
| 196 | const version = release.version; |
| 197 | switch (block) { |
| 198 | case "server-predates-checks": |
| 199 | return resolve( |
| 200 | msg("its server predates database checks; update it on {from} first", { from }), |
| 201 | ); |
| 202 | case "release-predates-checks": |
| 203 | return resolve( |
| 204 | msg("{version} predates database checks; wait for a newer {to} release", { version, to }), |
| 205 | ); |
| 206 | case "unsupported": |
| 207 | return resolve( |
| 208 | msg( |
| 209 | "its database has changes {version} does not support yet; stay on {from} until {to} has them", |
| 210 | { version, from, to }, |
| 211 | ), |
| 212 | ); |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | function localChannelSwitchBlockReason( |
| 217 | fromVersion: string, |
| 218 | release: ChannelSwitchRelease, |
| 219 | block: ChannelSwitchBlock, |
| 220 | resolve: MessageResolver, |
| 221 | ): string { |
| 222 | const from = channelSwitchLabel(desktopUpdateChannelOf(fromVersion), resolve); |
| 223 | const to = channelSwitchLabel(release.channel, resolve); |
| 224 | const version = release.version; |
| 225 | switch (block) { |
| 226 | case "server-predates-checks": |
| 227 | return resolve( |
| 228 | msg( |
| 229 | "This app cannot switch: its server predates database checks; update it on {from} first.", |
| 230 | { from }, |
| 231 | ), |
| 232 | ); |
| 233 | case "release-predates-checks": |
| 234 | return resolve( |
| 235 | msg( |
| 236 | "This app cannot switch: {version} predates database checks; wait for a newer {to} release.", |
| 237 | { version, to }, |
| 238 | ), |
| 239 | ); |
| 240 | case "unsupported": |
| 241 | return resolve( |
| 242 | msg( |
| 243 | "This app cannot switch: its database has changes {version} does not support yet; stay on {from} until {to} has them.", |
| 244 | { version, from, to }, |
| 245 | ), |
| 246 | ); |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | /** This app's reinstall restarts every server it hosts, so each of their databases must allow the |
| 251 | * switch. `backendCount` is the desktop's own inventory: a backend still starting has no client |
| 252 | * entry yet. A cached config can outlive its connection, so only a connected server's head counts. |
| 253 | * With Local environment off this app runs no server, so its reinstall restarts none. */ |
| 254 | export function localSwitchBlockReason( |
| 255 | appVersion: string, |
| 256 | release: ChannelSwitchRelease, |
| 257 | hosted: ReadonlyArray<{ |
| 258 | readonly connected: boolean; |
| 259 | readonly databaseMigration: number | undefined; |
| 260 | }>, |
| 261 | backendCount: number, |
| 262 | localEnvironmentEnabled: boolean, |
| 263 | resolve: MessageResolver = m, |
| 264 | ): string | null { |
| 265 | if (!localEnvironmentEnabled || !crossesTrack(appVersion, release)) return null; |
| 266 | if ( |
| 267 | hosted.length === 0 || |
| 268 | hosted.length < backendCount || |
| 269 | hosted.some((server) => !server.connected) |
| 270 | ) { |
| 271 | return resolve( |
| 272 | msg( |
| 273 | "This app cannot switch: its server is not connected, so its database cannot be checked.", |
| 274 | ), |
| 275 | ); |
| 276 | } |
| 277 | const block = hosted |
| 278 | .map((server) => channelSwitchBlock(appVersion, release, server.databaseMigration)) |
| 279 | .find((reason): reason is ChannelSwitchBlock => reason !== null); |
| 280 | return block === undefined |
| 281 | ? null |
| 282 | : localChannelSwitchBlockReason(appVersion, release, block, resolve); |
| 283 | } |
| 284 | |
| 285 | /** |
| 286 | * The server refuses these with the same message; say so before the run instead of after. |
| 287 | * `targetVersion` is undefined when the server picks its own version, as desktop apps do. |
| 288 | */ |
| 289 | function managedMachineUpdateDenial( |
| 290 | config: NonNullable<UpdateEverythingMachine["serverConfig"]>, |
| 291 | targetVersion: string | undefined, |
| 292 | resolve: MessageResolver, |
| 293 | ): string | undefined { |
| 294 | const policy = config.managedPolicy; |
| 295 | return ( |
| 296 | managedUpdatesDenial(policy, resolve) ?? |
| 297 | (policy !== undefined && |
| 298 | policy.limits?.updates?.allowNightly === false && |
| 299 | targetVersion !== undefined && |
| 300 | cliReleaseChannelOf(targetVersion) !== "stable" |
| 301 | ? managedNightlyDeniedMessage(policy.organization, resolve) |
| 302 | : undefined) |
| 303 | ); |
| 304 | } |
| 305 | |
| 306 | /** Servers move to the release; desktop-managed hosts reinstall their app on its track. A desktop |
| 307 | * host already current gets a track-only request, since its saved track may still differ. */ |
| 308 | export function collectChannelSwitchTargets( |
| 309 | machines: ReadonlyArray<UpdateEverythingMachine>, |
| 310 | release: ChannelSwitchRelease, |
| 311 | resolve: MessageResolver = m, |
| 312 | ): { readonly targets: ServerUpdateTarget[]; readonly skipped: SkippedMachine[] } { |
| 313 | const targets: ServerUpdateTarget[] = []; |
| 314 | const skipped: SkippedMachine[] = []; |
| 315 | for (const machine of machines) { |
| 316 | const config = machine.serverConfig; |
| 317 | if (machine.hostedByThisApp) continue; |
| 318 | const skip = (reason: string) => |
| 319 | skipped.push({ environmentId: machine.environmentId, label: machine.label, reason }); |
| 320 | const target = ( |
| 321 | selfUpdate: ServerSelfUpdateCapability, |
| 322 | targetVersion: string, |
| 323 | ): ServerUpdateTarget => ({ |
| 324 | environmentId: machine.environmentId, |
| 325 | serverLabel: machine.label, |
| 326 | selfUpdate, |
| 327 | installation: config?.environment.capabilities.serverInstallation, |
| 328 | desktopAppUpdate: config !== null && supportsDesktopAppUpdate(config), |
| 329 | targetVersion, |
| 330 | ...(selfUpdate === "desktop-managed" ? { channel: release.channel } : {}), |
| 331 | ...(release.databaseMigration === undefined |
| 332 | ? {} |
| 333 | : { targetDatabaseMigration: release.databaseMigration }), |
| 334 | }); |
| 335 | const serverVersion = config?.environment.serverVersion; |
| 336 | const sameTrack = serverVersion !== undefined && isOnTrack(serverVersion, release.channel); |
| 337 | if ( |
| 338 | config !== null && |
| 339 | sameTrack && |
| 340 | resolveVersionMismatch(serverVersion, release.version) === null |
| 341 | ) { |
| 342 | const move = trackSwitchMove(config, true, resolve); |
| 343 | if ( |
| 344 | !("skip" in move) && |
| 345 | move.selfUpdate === "desktop-managed" && |
| 346 | unavailableReason(machine, resolve) === null && |
| 347 | managedMachineUpdateDenial(config, release.version, resolve) === undefined |
| 348 | ) { |
| 349 | targets.push({ ...target(move.selfUpdate, serverVersion), trackOnly: true }); |
| 350 | } |
| 351 | continue; |
| 352 | } |
| 353 | const unavailable = unavailableReason(machine, resolve); |
| 354 | if (config === null || serverVersion === undefined || unavailable !== null) { |
| 355 | skip(unavailable ?? resolve(msg("not connected"))); |
| 356 | continue; |
| 357 | } |
| 358 | const managedDenial = managedMachineUpdateDenial(config, release.version, resolve); |
| 359 | if (managedDenial !== undefined) { |
| 360 | skip(managedDenial); |
| 361 | continue; |
| 362 | } |
| 363 | const move = trackSwitchMove(config, sameTrack, resolve); |
| 364 | if ("skip" in move) { |
| 365 | skip(move.skip); |
| 366 | continue; |
| 367 | } |
| 368 | const blocked = channelSwitchBlockReason( |
| 369 | serverVersion, |
| 370 | release, |
| 371 | config.environment.databaseMigration, |
| 372 | resolve, |
| 373 | ); |
| 374 | if (blocked !== null) { |
| 375 | skip(blocked); |
| 376 | continue; |
| 377 | } |
| 378 | // Service launchers only accept newer versions, so leaving for an older release is manual. |
| 379 | if ( |
| 380 | move.selfUpdate === "boot-service" && |
| 381 | compareSemverVersions(release.version, serverVersion) <= 0 |
| 382 | ) { |
| 383 | skip( |
| 384 | resolve( |
| 385 | msg("run `{command}` there", { |
| 386 | command: `t3 update --channel ${release.channel === "nightly" ? "nightly" : "stable"} --allow-downgrade`, |
| 387 | }), |
| 388 | ), |
| 389 | ); |
| 390 | continue; |
| 391 | } |
| 392 | targets.push(target(move.selfUpdate, release.version)); |
| 393 | } |
| 394 | return { targets, skipped }; |
| 395 | } |
| 396 | |
| 397 | /** A remote host on the other track that a switch can still move, for retrying a partial switch. */ |
| 398 | export function awaitsTrackSwitch( |
| 399 | machine: Pick<UpdateEverythingMachine, "serverConfig" | "hostedByThisApp">, |
| 400 | channel: DesktopUpdateChannel, |
| 401 | ): boolean { |
| 402 | const config = machine.serverConfig; |
| 403 | return ( |
| 404 | !machine.hostedByThisApp && |
| 405 | config !== null && |
| 406 | !isOnTrack(config.environment.serverVersion, channel) && |
| 407 | !("skip" in trackSwitchMove(config, false, m)) |
| 408 | ); |
| 409 | } |
| 410 | |
| 411 | function isOnTrack(version: string, channel: DesktopUpdateChannel): boolean { |
| 412 | return cliReleaseChannelOf(version) !== "preview" && desktopUpdateChannelOf(version) === channel; |
| 413 | } |
| 414 | |
| 415 | /** How a switch moves a host, or why it never can from here, whatever the release. */ |
| 416 | function trackSwitchMove( |
| 417 | config: NonNullable<UpdateEverythingMachine["serverConfig"]>, |
| 418 | sameTrack: boolean, |
| 419 | resolve: MessageResolver, |
| 420 | ): { readonly selfUpdate: ServerSelfUpdateCapability } | { readonly skip: string } { |
| 421 | if (cliReleaseChannelOf(config.environment.serverVersion) === "preview") { |
| 422 | return { skip: resolve(msg("runs a preview build")) }; |
| 423 | } |
| 424 | const selfUpdate = resolveServerSelfUpdateCapability(config); |
| 425 | if (selfUpdate === null) return { skip: resolve(msg("needs a manual update")) }; |
| 426 | if (selfUpdate !== "desktop-managed") return { selfUpdate }; |
| 427 | if (config.environment.capabilities.desktopAppChannelSwitch !== true) { |
| 428 | return { skip: resolve(msg("needs a newer desktop app")) }; |
| 429 | } |
| 430 | // Squirrel.Mac renames the bundle for the new track and then cannot relaunch it. |
| 431 | if (!sameTrack && config.environment.platform.os === "darwin") { |
| 432 | return { skip: resolve(msg("switch the Mac app on that Mac")) }; |
| 433 | } |
| 434 | return { selfUpdate }; |
| 435 | } |
| 436 | |
| 437 | export interface UpdateEverythingSteps<Providers, Servers> { |
| 438 | readonly downloadLocal?: () => Promise<boolean>; |
| 439 | readonly updateProviders: () => Promise<Providers>; |
| 440 | readonly stageServers?: () => ReadonlyMap<EnvironmentId, Promise<unknown>>; |
| 441 | readonly updateServers: ( |
| 442 | staged: ReadonlyMap<EnvironmentId, Promise<unknown>>, |
| 443 | ) => Promise<Servers>; |
| 444 | } |
| 445 | |
| 446 | /** Finish provider installs before server restarts; servers stage meanwhile and each server's |
| 447 | * update waits only on its own stage. Install this app last when localReady; failed downloads skip |
| 448 | * only that install. */ |
| 449 | export async function runUpdateEverything<Providers, Servers>( |
| 450 | steps: UpdateEverythingSteps<Providers, Servers>, |
| 451 | ): Promise<{ |
| 452 | readonly localReady: boolean; |
| 453 | readonly providers: Providers; |
| 454 | readonly servers: Servers; |
| 455 | }> { |
| 456 | const staged = new Map( |
| 457 | Array.from(steps.stageServers?.() ?? [], ([id, stage]) => [id, stage.catch(() => undefined)]), |
| 458 | ); |
| 459 | const [localReady, remote] = await Promise.all([ |
| 460 | steps.downloadLocal?.() ?? Promise.resolve(true), |
| 461 | steps |
| 462 | .updateProviders() |
| 463 | .then(async (providers) => ({ providers, servers: await steps.updateServers(staged) })), |
| 464 | ]); |
| 465 | return { localReady, ...remote }; |
| 466 | } |
| 467 | |
| 468 | export type UpdateRunMachineStatus = |
| 469 | | "providers" |
| 470 | | "waiting" |
| 471 | | "downloading" |
| 472 | | "restarting" |
| 473 | | "done" |
| 474 | | "failed"; |
| 475 | |
| 476 | export interface UpdateRunMachine { |
| 477 | readonly environmentId: EnvironmentId; |
| 478 | readonly label: string; |
| 479 | readonly updatesProviders: boolean; |
| 480 | readonly server: ServerUpdateTarget | null; |
| 481 | readonly handedOffVersion: string | null; |
| 482 | readonly startedAt: number; |
| 483 | readonly result: "done" | "failed" | null; |
| 484 | readonly failure: string | null; |
| 485 | readonly providerFailure: string | null; |
| 486 | } |
| 487 | |
| 488 | export interface UpdateEverythingRun { |
| 489 | /** Track switches retry through their planner, which re-checks each database. */ |
| 490 | readonly trackSwitch?: boolean; |
| 491 | readonly localVersion: string | null; |
| 492 | readonly phase: "providers" | "servers" | "countdown" | "installing"; |
| 493 | readonly restartAt: number | null; |
| 494 | readonly machines: ReadonlyArray<UpdateRunMachine>; |
| 495 | } |
| 496 | |
| 497 | export function resolveUpdateRunMachineStatus( |
| 498 | machine: UpdateRunMachine, |
| 499 | phase: UpdateEverythingRun["phase"], |
| 500 | serverState: ServerUpdateState, |
| 501 | ): UpdateRunMachineStatus { |
| 502 | if (machine.result !== null) return machine.result; |
| 503 | if (machine.handedOffVersion !== null) return "restarting"; |
| 504 | if (phase === "providers" && machine.updatesProviders) return "providers"; |
| 505 | if (machine.server !== null && serverState.status === "running") { |
| 506 | return serverState.stage === "resuming" ? "restarting" : "downloading"; |
| 507 | } |
| 508 | return "waiting"; |
| 509 | } |
| 510 | |
| 511 | export function isServerUpdateHandedOff(state: ServerUpdateState): boolean { |
| 512 | return state.status === "running" && state.stage === "resuming"; |
| 513 | } |
| 514 | |
| 515 | export function closeFinishedUpdateRun(run: UpdateEverythingRun): UpdateEverythingRun | null { |
| 516 | return run.phase === "servers" && |
| 517 | run.localVersion === null && |
| 518 | run.machines.every((machine) => machine.result === "done") |
| 519 | ? null |
| 520 | : run; |
| 521 | } |
| 522 | |
| 523 | const UPDATE_SLOW_AFTER_MS = 3 * 60 * 1000; |
| 524 | |
| 525 | export function formatUpdateElapsed(ms: number, resolve: MessageResolver = m): string { |
| 526 | const minutes = Math.floor(ms / 60_000); |
| 527 | if (minutes < 1) return resolve(msg("<1m")); |
| 528 | if (minutes < 60) return resolve(msg("{minutes}m", { minutes })); |
| 529 | return resolve( |
| 530 | msg("{hours}h {minutes}m", { hours: Math.floor(minutes / 60), minutes: minutes % 60 }), |
| 531 | ); |
| 532 | } |
| 533 | |
| 534 | export interface UpdateRunMachineView { |
| 535 | readonly machine: UpdateRunMachine; |
| 536 | readonly status: UpdateRunMachineStatus; |
| 537 | } |
| 538 | |
| 539 | export type UpdateRunLocalState = |
| 540 | | { readonly status: "downloading"; readonly percent: number | null } |
| 541 | | { readonly status: "waiting" } |
| 542 | | null; |
| 543 | |
| 544 | export interface UpdateCapsuleView { |
| 545 | readonly tone: "default" | "slow" | "failed"; |
| 546 | readonly label: string; |
| 547 | readonly slow?: { readonly status: string; readonly elapsed: string }; |
| 548 | readonly action: "later" | "retry" | "dismiss" | null; |
| 549 | } |
| 550 | |
| 551 | const isActive = (status: UpdateRunMachineStatus) => status !== "done" && status !== "failed"; |
| 552 | |
| 553 | export function describeUpdateCapsule( |
| 554 | run: UpdateEverythingRun, |
| 555 | machines: ReadonlyArray<UpdateRunMachineView>, |
| 556 | local: UpdateRunLocalState, |
| 557 | now: number, |
| 558 | resolve: MessageResolver = m, |
| 559 | ): UpdateCapsuleView { |
| 560 | if (run.phase === "countdown" && run.restartAt !== null) { |
| 561 | const seconds = Math.max(0, Math.ceil((run.restartAt - now) / 1000)); |
| 562 | return { |
| 563 | tone: "default", |
| 564 | label: resolve(msg("Restart in {seconds}s", { seconds })), |
| 565 | action: "later", |
| 566 | }; |
| 567 | } |
| 568 | if (run.phase === "installing") { |
| 569 | return { tone: "default", label: resolve(msg("Restarting…")), action: null }; |
| 570 | } |
| 571 | const active = machines.filter(({ status }) => isActive(status) && status !== "waiting"); |
| 572 | const slowest = active.toSorted((a, b) => a.machine.startedAt - b.machine.startedAt)[0]; |
| 573 | if (slowest && now - slowest.machine.startedAt >= UPDATE_SLOW_AFTER_MS) { |
| 574 | return { |
| 575 | tone: "slow", |
| 576 | label: slowest.machine.label, |
| 577 | slow: { |
| 578 | status: resolve(RUN_STATUS_LABELS[slowest.status]), |
| 579 | elapsed: formatUpdateElapsed(now - slowest.machine.startedAt, resolve), |
| 580 | }, |
| 581 | action: null, |
| 582 | }; |
| 583 | } |
| 584 | const done = machines.filter(({ status }) => status === "done").length; |
| 585 | if (machines.some(({ status }) => isActive(status))) { |
| 586 | return { |
| 587 | tone: "default", |
| 588 | label: resolve(msg("{done} of {total} updated", { done, total: machines.length })), |
| 589 | action: null, |
| 590 | }; |
| 591 | } |
| 592 | if (local?.status === "downloading") { |
| 593 | return { |
| 594 | tone: "default", |
| 595 | label: |
| 596 | local.percent === null |
| 597 | ? resolve(msg("Downloading")) |
| 598 | : resolve(msg("Downloading {percent}%", { percent: Math.floor(local.percent) })), |
| 599 | action: null, |
| 600 | }; |
| 601 | } |
| 602 | const failed = machines.filter(({ status }) => status === "failed"); |
| 603 | if (failed.length > 0) { |
| 604 | return { |
| 605 | tone: "failed", |
| 606 | label: |
| 607 | failed.length === 1 |
| 608 | ? resolve(msg("{machine} failed", { machine: failed[0]!.machine.label })) |
| 609 | : resolve( |
| 610 | msg("{count, plural, one {{count} failed} other {{count} failed}}", { |
| 611 | count: failed.length, |
| 612 | }), |
| 613 | ), |
| 614 | action: |
| 615 | !run.trackSwitch && failed.some(({ machine }) => machine.server !== null) |
| 616 | ? "retry" |
| 617 | : "dismiss", |
| 618 | }; |
| 619 | } |
| 620 | return { |
| 621 | tone: "default", |
| 622 | label: resolve(msg("{done} of {total} updated", { done, total: machines.length })), |
| 623 | action: null, |
| 624 | }; |
| 625 | } |
| 626 | |
| 627 | /** `msg()` strings: resolve them with `m` or `useMessages()` where they show. */ |
| 628 | export const RUN_STATUS_LABELS: Record<UpdateRunMachineStatus, string> = { |
| 629 | providers: msg("updating providers"), |
| 630 | waiting: msg("waiting"), |
| 631 | downloading: msg("downloading"), |
| 632 | restarting: msg("restarting"), |
| 633 | done: msg("done"), |
| 634 | failed: msg("failed"), |
| 635 | }; |
| 636 | |
| 637 | export interface UpdateEverythingResult { |
| 638 | readonly localVersion: string | null; |
| 639 | readonly updatedServers: number; |
| 640 | readonly updatedProviders: number; |
| 641 | readonly failures: ReadonlyArray<string>; |
| 642 | readonly restarting: ReadonlyArray<string>; |
| 643 | } |
| 644 | |
| 645 | export function collectUpdateEverythingResult(input: { |
| 646 | readonly localVersion: string | null; |
| 647 | readonly localFailures: ReadonlyArray<string>; |
| 648 | readonly servers: ReadonlyArray<{ |
| 649 | readonly label: string; |
| 650 | readonly outcome: ServerUpdateOutcome; |
| 651 | }>; |
| 652 | readonly providers: ReadonlyArray< |
| 653 | | { readonly status: "interrupted" | "updated" } |
| 654 | | { readonly status: "failed"; readonly line: string } |
| 655 | >; |
| 656 | }): UpdateEverythingResult { |
| 657 | return { |
| 658 | localVersion: input.localVersion, |
| 659 | updatedServers: input.servers.filter(({ outcome }) => outcome.status === "updated").length, |
| 660 | updatedProviders: input.providers.filter((outcome) => outcome.status === "updated").length, |
| 661 | restarting: [], |
| 662 | failures: [ |
| 663 | ...input.localFailures.map((failure) => m(msg("This app: {failure}", { failure }))), |
| 664 | ...input.servers.flatMap(({ label, outcome }) => |
| 665 | outcome.status === "failed" ? [`${label}: ${outcome.message}`] : [], |
| 666 | ), |
| 667 | ...input.providers.flatMap((outcome) => (outcome.status === "failed" ? [outcome.line] : [])), |
| 668 | ], |
| 669 | }; |
| 670 | } |
| 671 | |
| 672 | export function getUpdateEverythingToastView( |
| 673 | result: UpdateEverythingResult, |
| 674 | appVersion: string, |
| 675 | ): { |
| 676 | readonly type: "success" | "error"; |
| 677 | readonly title: string; |
| 678 | readonly description?: string; |
| 679 | } | null { |
| 680 | const updated = updateTargetsSentence( |
| 681 | "updated", |
| 682 | { |
| 683 | app: result.localVersion !== null && result.localVersion === appVersion, |
| 684 | servers: result.updatedServers, |
| 685 | providers: result.updatedProviders, |
| 686 | }, |
| 687 | m, |
| 688 | ); |
| 689 | const restarting = |
| 690 | result.restarting.length === 0 |
| 691 | ? [] |
| 692 | : [ |
| 693 | m( |
| 694 | msg( |
| 695 | "{count, plural, one {{machines} is still restarting.} other {{machines} are still restarting.}}", |
| 696 | { count: result.restarting.length, machines: joinList(result.restarting, m) }, |
| 697 | ), |
| 698 | ), |
| 699 | ]; |
| 700 | if (result.failures.length === 0) { |
| 701 | if (updated === null) return null; |
| 702 | return { |
| 703 | type: "success", |
| 704 | title: updated, |
| 705 | ...(restarting.length === 0 ? {} : { description: restarting.join("\n") }), |
| 706 | }; |
| 707 | } |
| 708 | return { |
| 709 | type: "error", |
| 710 | title: updated === null ? m(msg("Update failed")) : updated, |
| 711 | description: [...result.failures, ...restarting].join("\n"), |
| 712 | }; |
| 713 | } |
| 714 | |
| 715 | export interface UpdateEverythingPlan { |
| 716 | readonly localVersion: string | null; |
| 717 | /** Machines whose servers this app hosts; this app's update restarts them. */ |
| 718 | readonly localMachines: ReadonlyArray<{ |
| 719 | readonly environmentId: EnvironmentId; |
| 720 | readonly label: string; |
| 721 | }>; |
| 722 | readonly servers: ReadonlyArray< |
| 723 | Pick<ServerUpdateTarget, "environmentId" | "serverLabel" | "selfUpdate" | "targetVersion"> |
| 724 | >; |
| 725 | readonly providerMachines: ReadonlyArray<{ |
| 726 | readonly environmentId: EnvironmentId; |
| 727 | readonly label: string; |
| 728 | readonly providers: ReadonlyArray<string>; |
| 729 | }>; |
| 730 | readonly skipped: ReadonlyArray<SkippedMachine>; |
| 731 | } |
| 732 | |
| 733 | export interface UpdateEverythingRow { |
| 734 | readonly environmentId: EnvironmentId | null; |
| 735 | readonly label: string; |
| 736 | readonly app: "this-app" | "server" | "desktop-app" | null; |
| 737 | readonly skipped: string | null; |
| 738 | readonly providers: ReadonlyArray<string>; |
| 739 | } |
| 740 | |
| 741 | /** "Update this app, 2 servers, and 3 providers" as one sentence per combination; null when nothing. */ |
| 742 | function updateTargetsSentence( |
| 743 | verb: "update" | "updated", |
| 744 | targets: { readonly app: boolean; readonly servers: number; readonly providers: number }, |
| 745 | resolve: MessageResolver, |
| 746 | ): string | null { |
| 747 | const { app, servers, providers } = targets; |
| 748 | const values = { servers, providers }; |
| 749 | const update = verb === "update"; |
| 750 | if (app && servers > 0 && providers > 0) { |
| 751 | return update |
| 752 | ? resolve( |
| 753 | msg( |
| 754 | "Update this app, {servers, plural, one {{servers} server} other {{servers} servers}}, and {providers, plural, one {{providers} provider} other {{providers} providers}}", |
| 755 | values, |
| 756 | ), |
| 757 | ) |
| 758 | : resolve( |
| 759 | msg( |
| 760 | "Updated this app, {servers, plural, one {{servers} server} other {{servers} servers}}, and {providers, plural, one {{providers} provider} other {{providers} providers}}", |
| 761 | values, |
| 762 | ), |
| 763 | ); |
| 764 | } |
| 765 | if (app && servers > 0) { |
| 766 | return update |
| 767 | ? resolve( |
| 768 | msg( |
| 769 | "Update this app and {servers, plural, one {{servers} server} other {{servers} servers}}", |
| 770 | values, |
| 771 | ), |
| 772 | ) |
| 773 | : resolve( |
| 774 | msg( |
| 775 | "Updated this app and {servers, plural, one {{servers} server} other {{servers} servers}}", |
| 776 | values, |
| 777 | ), |
| 778 | ); |
| 779 | } |
| 780 | if (app && providers > 0) { |
| 781 | return update |
| 782 | ? resolve( |
| 783 | msg( |
| 784 | "Update this app and {providers, plural, one {{providers} provider} other {{providers} providers}}", |
| 785 | values, |
| 786 | ), |
| 787 | ) |
| 788 | : resolve( |
| 789 | msg( |
| 790 | "Updated this app and {providers, plural, one {{providers} provider} other {{providers} providers}}", |
| 791 | values, |
| 792 | ), |
| 793 | ); |
| 794 | } |
| 795 | if (servers > 0 && providers > 0) { |
| 796 | return update |
| 797 | ? resolve( |
| 798 | msg( |
| 799 | "Update {servers, plural, one {{servers} server} other {{servers} servers}} and {providers, plural, one {{providers} provider} other {{providers} providers}}", |
| 800 | values, |
| 801 | ), |
| 802 | ) |
| 803 | : resolve( |
| 804 | msg( |
| 805 | "Updated {servers, plural, one {{servers} server} other {{servers} servers}} and {providers, plural, one {{providers} provider} other {{providers} providers}}", |
| 806 | values, |
| 807 | ), |
| 808 | ); |
| 809 | } |
| 810 | if (app) return update ? resolve(msg("Update this app")) : resolve(msg("Updated this app")); |
| 811 | if (servers > 0) { |
| 812 | return update |
| 813 | ? resolve( |
| 814 | msg("Update {servers, plural, one {{servers} server} other {{servers} servers}}", values), |
| 815 | ) |
| 816 | : resolve( |
| 817 | msg( |
| 818 | "Updated {servers, plural, one {{servers} server} other {{servers} servers}}", |
| 819 | values, |
| 820 | ), |
| 821 | ); |
| 822 | } |
| 823 | if (providers > 0) { |
| 824 | return update |
| 825 | ? resolve( |
| 826 | msg( |
| 827 | "Update {providers, plural, one {{providers} provider} other {{providers} providers}}", |
| 828 | values, |
| 829 | ), |
| 830 | ) |
| 831 | : resolve( |
| 832 | msg( |
| 833 | "Updated {providers, plural, one {{providers} provider} other {{providers} providers}}", |
| 834 | values, |
| 835 | ), |
| 836 | ); |
| 837 | } |
| 838 | return null; |
| 839 | } |
| 840 | |
| 841 | function joinList(parts: ReadonlyArray<string>, resolve: MessageResolver): string { |
| 842 | if (parts.length <= 1) return parts.join(""); |
| 843 | if (parts.length === 2) { |
| 844 | return resolve(msg("{first} and {second}", { first: parts[0], second: parts[1] })); |
| 845 | } |
| 846 | return resolve( |
| 847 | msg("{items}, and {last}", { items: parts.slice(0, -1).join(", "), last: parts.at(-1) }), |
| 848 | ); |
| 849 | } |
| 850 | |
| 851 | /** One row per machine: this app's machines first, then servers, provider-only, and skipped. */ |
| 852 | export function describeUpdateEverything( |
| 853 | plan: UpdateEverythingPlan, |
| 854 | resolve: MessageResolver = m, |
| 855 | ): { |
| 856 | readonly summary: string; |
| 857 | readonly version: string | null; |
| 858 | readonly providerCount: number; |
| 859 | readonly rows: ReadonlyArray<UpdateEverythingRow>; |
| 860 | } { |
| 861 | const providerCount = plan.providerMachines.reduce( |
| 862 | (count, machine) => count + machine.providers.length, |
| 863 | 0, |
| 864 | ); |
| 865 | const summary = |
| 866 | updateTargetsSentence( |
| 867 | "update", |
| 868 | { |
| 869 | app: Boolean(plan.localVersion), |
| 870 | servers: plan.servers.length, |
| 871 | providers: providerCount, |
| 872 | }, |
| 873 | resolve, |
| 874 | ) ?? resolve(msg("Update {items}", { items: "" })); |
| 875 | |
| 876 | const rows = new Map<EnvironmentId | null, UpdateEverythingRow>(); |
| 877 | const update = ( |
| 878 | environmentId: EnvironmentId | null, |
| 879 | label: string, |
| 880 | change: Partial<UpdateEverythingRow>, |
| 881 | ) => { |
| 882 | const row = rows.get(environmentId) ?? { |
| 883 | environmentId, |
| 884 | label, |
| 885 | app: null, |
| 886 | skipped: null, |
| 887 | providers: [], |
| 888 | }; |
| 889 | rows.set(environmentId, { ...row, ...change }); |
| 890 | }; |
| 891 | if (plan.localVersion) { |
| 892 | if (plan.localMachines.length === 0) { |
| 893 | update(null, resolve(msg("This app")), { app: "this-app" }); |
| 894 | } |
| 895 | for (const machine of plan.localMachines) { |
| 896 | update(machine.environmentId, machine.label, { app: "this-app" }); |
| 897 | } |
| 898 | } |
| 899 | for (const server of plan.servers) { |
| 900 | update(server.environmentId, server.serverLabel, { |
| 901 | app: server.selfUpdate === "desktop-managed" ? "desktop-app" : "server", |
| 902 | }); |
| 903 | } |
| 904 | for (const machine of plan.providerMachines) { |
| 905 | update(machine.environmentId, machine.label, { providers: machine.providers }); |
| 906 | } |
| 907 | for (const machine of plan.skipped) { |
| 908 | update(machine.environmentId, machine.label, { skipped: machine.reason }); |
| 909 | } |
| 910 | |
| 911 | return { |
| 912 | summary, |
| 913 | version: |
| 914 | plan.localVersion ?? |
| 915 | plan.servers.find((server) => server.selfUpdate !== "desktop-managed")?.targetVersion ?? |
| 916 | null, |
| 917 | providerCount, |
| 918 | rows: Array.from(rows.values()), |
| 919 | }; |
| 920 | } |