fix(web): update everything no longer waits on slow servers, and shows progress in the sidebar (#19837)

Co-authored-by: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Theo BrowneandClaude Opus 5.5 authored and GitHub committed 2026-10-15 03:17:22 -07:00
1 parent 2d31acb975
commit 313f23e4ed
9 files changed
+922 -169

No files matched your search

@@ -0,0 +1,201 @@
import { useAtomValue } from "@effect/atom-react";
import { Atom } from "effect/reactivity";
import { type ReactNode, useCallback, useMemo, useSyncExternalStore } from "react";
import { cn } from "~/lib/utils";
import { serverEnvironment } from "~/state/server";
import { useServerUpdate } from "../ServerUpdateAction";
import { Button } from "../ui/button";
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
import {
describeUpdateCapsule,
formatUpdateElapsed,
RUN_STATUS_LABELS,
resolveUpdateRunMachineStatus,
type UpdateEverythingRun,
type UpdateRunLocalState,
type UpdateRunMachineView,
} from "./updateEverything.logic";
import {
dismissSettledUpdateRunMachines,
postponeUpdateRestart,
retryFailedUpdateRunServers,
} from "./updateEverythingRun";
/** The current time, rounded down to `intervalMs` so it changes once per
interval. With null it is read only when something else renders. */
function useNow(intervalMs: number | null): number {
const step = intervalMs ?? 60_000;
const subscribe = useCallback(
(onChange: () => void) => {
if (intervalMs === null) return () => {};
const timer = setInterval(onChange, intervalMs);
return () => clearInterval(timer);
},
[intervalMs],
);
return useSyncExternalStore(subscribe, () => Math.floor(Date.now() / step) * step);
}
function useUpdateRunMachineViews(run: UpdateEverythingRun): ReadonlyArray<UpdateRunMachineView> {
const viewsAtom = useMemo(
() =>
Atom.make((get) =>
run.machines.map((machine) => ({
machine,
status: resolveUpdateRunMachineStatus(
machine,
run.phase,
get(serverEnvironment.updateStateAtom(machine.environmentId)),
),
})),
),
[run],
);
return useAtomValue(viewsAtom);
}
function localStatusLabel(run: UpdateEverythingRun, local: UpdateRunLocalState, now: number) {
if (run.phase === "countdown" && run.restartAt !== null) {
return `restarts in ${Math.max(0, Math.ceil((run.restartAt - now) / 1000))}s`;
}
if (run.phase === "installing") return "restarting";
if (local?.status === "downloading") {
return `downloading${local.percent === null ? "" : ` ${Math.floor(local.percent)}%`}`;
}
return "restarts after the servers";
}
/**
* The sidebar update button while an "update everything" pass runs. It grows
* left into the free footer space and names the most urgent thing: this
* app's restart countdown, a slow machine, progress, or a failure. Click it
* for every machine. Time labels change once a second only during the
* countdown, and otherwise once every 30 seconds.
*/
export function SidebarUpdateCapsule({
run,
local,
icon,
onRestart,
}: {
readonly run: UpdateEverythingRun;
readonly local: UpdateRunLocalState;
readonly icon: ReactNode;
/** Installs this app's downloaded update after the user postponed it. */
readonly onRestart?: () => Promise<void>;
}) {
const machines = useUpdateRunMachineViews(run);
const hasActiveMachine = machines.some(
({ status }) => status !== "done" && status !== "failed" && status !== "waiting",
);
const now = useNow(run.phase === "countdown" ? 1_000 : hasActiveMachine ? 30_000 : null);
const view = describeUpdateCapsule(run, machines, local, now);
const updateServer = useServerUpdate();
const failed = machines.some(({ status }) => status === "failed");
const settled = !hasActiveMachine && run.localVersion === null;
const actionLabel =
view.action === "later" ? "Later" : view.action === "retry" ? "Retry" : "Dismiss";
const runAction = () => {
if (view.action === "later") postponeUpdateRestart();
else if (view.action === "retry") retryFailedUpdateRunServers(updateServer);
else dismissSettledUpdateRunMachines();
};
return (
<Popover>
<div
className={cn(
"relative flex h-8 min-w-0 flex-1 items-center rounded-full bg-sidebar-control-surface text-sidebar-foreground",
view.tone === "slow" && "ring-1 ring-warning/40 ring-inset",
view.tone === "failed" && "ring-1 ring-destructive/40 ring-inset",
)}
>
<PopoverTrigger
render={
<button
type="button"
aria-label={
view.slow ? `${view.label} ${view.slow.status} ${view.slow.elapsed}` : view.label
}
className="absolute inset-0 cursor-pointer rounded-full outline-hidden ring-ring hover:bg-sidebar-row-hover focus-visible:ring-2 focus-visible:ring-inset"
/>
}
/>
<span className="pointer-events-none relative min-w-0 flex-1 truncate pl-3 text-xs">
<span className={cn(view.tone === "failed" && "text-destructive")}>{view.label}</span>
{view.slow ? (
<span className="text-warning tabular-nums"> {view.slow.elapsed}</span>
) : null}
</span>
{/* The footer leaves little room, so an action takes the icon's place. */}
{view.action !== null ? (
<button
type="button"
className="relative shrink-0 cursor-pointer pr-3 pl-1.5 text-xs underline decoration-muted-foreground/60 underline-offset-3 hover:decoration-current"
onClick={runAction}
>
{actionLabel}
</button>
) : (
<span className="pointer-events-none relative grid size-8 shrink-0 place-items-center">
{icon}
</span>
)}
</div>
<PopoverPopup side="top" align="end" padding="compact" width="sm">
<div className="flex flex-col gap-1 text-xs">
{run.localVersion !== null ? (
<div className="flex items-center justify-between gap-3">
<span>This app</span>
<span className="text-muted-foreground tabular-nums">
{localStatusLabel(run, local, now)}
</span>
</div>
) : onRestart ? (
<div className="flex items-center justify-between gap-3">
<span>This app</span>
<Button size="xs" variant="outline" onClick={() => void onRestart()}>
Restart to update
</Button>
</div>
) : null}
{machines.map(({ machine, status }) => (
<div key={machine.environmentId} className="flex min-w-0 flex-col">
<div className="flex items-center justify-between gap-3">
<span className="truncate">{machine.label}</span>
<span
className={cn(
"shrink-0 tabular-nums",
status === "failed" ? "text-destructive" : "text-muted-foreground",
)}
>
{RUN_STATUS_LABELS[status]}
{status !== "done" && status !== "failed" && status !== "waiting"
? ` ${formatUpdateElapsed(now - machine.startedAt)}`
: ""}
</span>
</div>
{machine.failure !== null ? (
<span className="break-words text-muted-foreground">{machine.failure}</span>
) : null}
</div>
))}
{settled && failed ? (
<div className="mt-1 flex justify-end gap-1">
{view.action === "retry" ? (
<Button size="xs" variant="outline" onClick={runAction}>
Retry
</Button>
) : null}
<Button size="xs" variant="ghost" onClick={dismissSettledUpdateRunMachines}>
Dismiss
</Button>
</div>
) : null}
</div>
</PopoverPopup>
</Popover>
);
}
@@ -1,23 +1,12 @@
import { useAtomValue } from "@effect/atom-react";
import type { DesktopBridge, DesktopUpdateState } from "@t3tools/contracts";
import { Atom } from "effect/reactivity";
import { TriangleAlertIcon } from "lucide-react";
import {
type ComponentProps,
useCallback,
useEffect,
useId,
useMemo,
useRef,
useState,
} from "react";
import { type ComponentProps, useCallback, useEffect, useId, useRef, useState } from "react";
import { flushSync } from "react-dom";
import { isElectron } from "../../env";
import { useMediaQuery } from "../../hooks/useMediaQuery";
import { cn } from "../../lib/utils";
import { ensureLocalApi } from "../../localApi";
import { useDesktopUpdateState } from "../../state/desktopUpdate";
import { serverEnvironment } from "../../state/server";
import { stackedThreadToast, toastManager } from "../ui/toast";
import {
canCheckForUpdate,
@@ -43,13 +32,14 @@ import {
shouldShowDesktopUpdateCheckIcon,
} from "./DesktopUpdateStatusIcon";
import { SidebarUpdateReleaseNotes } from "./SidebarUpdateReleaseNotes";
import { SidebarUpdateCapsule } from "./SidebarUpdateCapsule";
import { UpdateEverythingDialog } from "./UpdateEverythingDialog";
import type { UpdateEverythingRun, UpdateRunLocalState } from "./updateEverything.logic";
import {
describeUpdateRun,
resolveUpdateRunMachineStatus,
type UpdateEverythingRun,
} from "./updateEverything.logic";
import { useUpdateEverythingRun } from "./updateEverythingRun";
clearSavedUpdateEverythingResult,
saveUpdateEverythingResult,
useUpdateEverythingRun,
} from "./updateEverythingRun";
import { type ReportLocalUpdateError, useUpdateEverything } from "./useUpdateEverything";
type SidebarUpdatePopoverChangeDetails = Parameters<
@@ -202,43 +192,6 @@ async function installLocalUpdate(
}
}
/** Tooltip lines for a running pass: this app first, then one per machine. */
function useUpdateRunTooltip(
run: UpdateEverythingRun | null,
state: DesktopUpdateState | null,
localReady: boolean,
): string | null {
const statusesAtom = useMemo(
() =>
Atom.make((get) =>
run === null
? []
: run.machines.map((machine) => ({
label: machine.label,
status: resolveUpdateRunMachineStatus(
machine,
run.phase,
get(serverEnvironment.updateStateAtom(machine.environmentId)),
),
})),
),
[run],
);
const statuses = useAtomValue(statusesAtom);
if (run === null) return null;
const local =
run.localVersion === null
? null
: state?.status === "downloading"
? `downloading${state.downloadPercent === null ? "" : ` ${Math.floor(state.downloadPercent)}%`}`
: run.phase === "installing"
? "restarting"
: localReady
? "restarts last"
: "waiting";
return describeUpdateRun(statuses, local).join("\n");
}
/**
* The sidebar update button. With only a local app update it downloads, then
* installs. When other machines' servers or any providers are behind, one
@@ -279,7 +232,6 @@ function SidebarUpdateControl() {
// Providers leave the list once queued, so the run keeps its own state.
const run = useUpdateEverythingRun();
const isRunningEverything = run !== null;
const runTooltip = useUpdateRunTooltip(run, state, action === "install");
const showCheckIcon = shouldShowDesktopUpdateCheckIcon({
isAnimationLatched: isCheckAnimationLatched,
isChecking: state?.status === "checking",
@@ -292,18 +244,15 @@ function SidebarUpdateControl() {
isDownloading,
showCheckIcon,
});
const tooltip =
runTooltip !== null
? runTooltip
: runsEverything
? everything.summary
: showUpdateDetails
? state
? getDesktopUpdateButtonTooltip(state)
: "Update available"
: showCheckIcon
? "Checking for updates…"
: "Check for updates";
const tooltip = runsEverything
? everything.summary
: showUpdateDetails
? state
? getDesktopUpdateButtonTooltip(state)
: "Update available"
: showCheckIcon
? "Checking for updates…"
: "Check for updates";
const disabled = showCheckIcon
? true
: runsEverything
@@ -312,7 +261,7 @@ function SidebarUpdateControl() {
? isDesktopUpdateButtonDisabled(state)
: !canCheckForUpdate(state);
const isInteractionDisabled = disabled || isActionPending || isRunningEverything;
// During a run the tooltip shows its progress instead of release notes.
// During a run the capsule shows its progress instead of release notes.
const showReleaseNotesPopover =
!isRunningEverything && shouldUseSidebarUpdateReleaseNotesPopover(showUpdateDetails, state);
@@ -442,6 +391,65 @@ function SidebarUpdateControl() {
// Web has no local app to check, so it only shows the button for remote work.
if (!isElectron && !runsEverything && !isRunningEverything) return null;
const statusIcon = (
<DesktopUpdateStatusIcon
key={showCheckIcon ? checkAnimationKey : iconStatus}
downloadPercent={state?.downloadPercent ?? null}
isCheckAnimating={showCheckIcon && !prefersReducedMotion}
onCheckAnimationIteration={handleCheckAnimationIteration}
status={iconStatus}
/>
);
const confirmDialog = (
<UpdateEverythingDialog
open={isConfirmingEverything}
onOpenChange={setIsConfirmingEverything}
summary={everything.summary}
lines={everything.lines}
restarts={everything.restarts}
skipped={everything.skipped}
onConfirm={() => void runEverything()}
/>
);
if (run !== null) {
const local: UpdateRunLocalState =
run.localVersion === null
? null
: state?.status === "downloading"
? { status: "downloading", percent: state.downloadPercent }
: { status: "waiting" };
return (
<SidebarMenuItem className="ml-auto flex min-w-0 flex-1">
<SidebarUpdateCapsule
run={run}
local={local}
icon={statusIcon}
// After "Later", this app's downloaded update can still be installed
// while the run follows the other machines.
{...(run.localVersion === null && action === "install" && window.desktopBridge
? {
onRestart: async () => {
// Like the countdown, keep following servers still restarting.
saveUpdateEverythingResult({
localVersion: localUpdateVersion,
updatedServers: 0,
updatedProviders: 0,
failures: [],
restarting: [],
});
if (!(await installLocalUpdate(window.desktopBridge!))) {
clearSavedUpdateEverythingResult();
}
},
}
: {})}
/>
{confirmDialog}
</SidebarMenuItem>
);
}
const updateButton = (
<button
type="button"
@@ -482,13 +490,7 @@ function SidebarUpdateControl() {
);
}}
>
<DesktopUpdateStatusIcon
key={showCheckIcon ? checkAnimationKey : iconStatus}
downloadPercent={state?.downloadPercent ?? null}
isCheckAnimating={showCheckIcon && !prefersReducedMotion}
onCheckAnimationIteration={handleCheckAnimationIteration}
status={iconStatus}
/>
{statusIcon}
</button>
);
@@ -559,15 +561,7 @@ function SidebarUpdateControl() {
</PopoverPopup>
) : null}
</Popover>
<UpdateEverythingDialog
open={isConfirmingEverything}
onOpenChange={setIsConfirmingEverything}
summary={everything.summary}
lines={everything.lines}
restarts={everything.restarts}
skipped={everything.skipped}
onConfirm={() => void runEverything()}
/>
{confirmDialog}
</SidebarMenuItem>
);
}
@@ -4,15 +4,38 @@ import { describe, expect, it } from "vite-plus/test";
import {
collectRestartingMachines,
collectServerUpdateTargets,
closeFinishedUpdateRun,
collectUpdateEverythingResult,
describeUpdateCapsule,
describeUpdateEverything,
getUpdateEverythingToastView,
resolveUpdateRunMachineStatus,
runUpdateEverything,
type UpdateEverythingMachine,
type UpdateEverythingRun,
type UpdateRunMachine,
type UpdateRunMachineStatus,
UPDATE_SLOW_AFTER_MS,
} from "./updateEverything.logic";
const runMachine = (overrides: Partial<UpdateRunMachine> = {}): UpdateRunMachine => ({
environmentId: EnvironmentId.make("alvin"),
label: "alvin",
updatesProviders: true,
server: {
environmentId: EnvironmentId.make("alvin"),
serverLabel: "alvin",
selfUpdate: "boot-service",
targetVersion: "0.0.50",
},
handedOffVersion: null,
startedAt: 0,
result: null,
failure: null,
providerFailure: null,
...overrides,
});
function machine(
id: string,
serverVersion: string,
@@ -175,14 +198,6 @@ describe("runUpdateEverything", () => {
});
describe("resolveUpdateRunMachineStatus", () => {
const runMachine = (overrides: Partial<UpdateRunMachine> = {}): UpdateRunMachine => ({
environmentId: EnvironmentId.make("alvin"),
label: "alvin",
updatesProviders: true,
updatesServer: true,
result: null,
...overrides,
});
const running = (stage: "downloading" | "installing" | "resuming") =>
({ status: "running", stage, fromVersion: "0.0.40", targetVersion: "0.0.50" }) as const;
@@ -206,6 +221,92 @@ describe("resolveUpdateRunMachineStatus", () => {
expect(resolveUpdateRunMachineStatus(runMachine({ result: "failed" }), "servers", idle)).toBe(
"failed",
);
// After this app relaunched, a handed-off server has no live update state.
expect(
resolveUpdateRunMachineStatus(
runMachine({ server: null, handedOffVersion: "0.0.50" }),
"servers",
idle,
),
).toBe("restarting");
});
});
describe("update capsule", () => {
const run = (overrides: Partial<UpdateEverythingRun> = {}): UpdateEverythingRun => ({
localVersion: null,
phase: "servers",
restartAt: null,
machines: [],
...overrides,
});
const view = (
label: string,
status: UpdateRunMachineStatus,
overrides: Partial<UpdateRunMachine> = {},
) => ({
machine: runMachine({ environmentId: EnvironmentId.make(label), label, ...overrides }),
status,
});
it("counts down this app's restart before anything else", () => {
expect(
describeUpdateCapsule(
run({ phase: "countdown", restartAt: 5_000, localVersion: "0.0.50" }),
[view("alvin", "restarting")],
{ status: "waiting" },
1_200,
),
).toEqual({ tone: "default", label: "Restart in 4s", action: "later" });
});
it("names the slowest machine once it passes the slow threshold", () => {
const machines = [
view("bb-1", "done"),
view("zbook", "downloading", { startedAt: 60_000 }),
view("alvin", "restarting", { startedAt: 0 }),
];
expect(describeUpdateCapsule(run(), machines, null, 60_000)).toEqual({
tone: "default",
label: "1 of 3 updated",
action: null,
});
expect(describeUpdateCapsule(run(), machines, null, UPDATE_SLOW_AFTER_MS + 6 * 60_000)).toEqual(
{
tone: "slow",
label: "alvin",
slow: { status: "restarting", elapsed: "9m" },
action: null,
},
);
});
it("offers a retry only for failed servers it can update again", () => {
expect(describeUpdateCapsule(run(), [view("alvin", "failed")], null, 0)).toEqual({
tone: "failed",
label: "alvin failed",
action: "retry",
});
expect(
describeUpdateCapsule(
run(),
[view("alvin", "failed", { server: null }), view("box", "failed", { server: null })],
null,
0,
),
).toEqual({ tone: "failed", label: "2 failed", action: "dismiss" });
});
it("ends the run only when every machine is done and this app is not installing", () => {
const done = runMachine({ result: "done" });
expect(closeFinishedUpdateRun(run({ machines: [done] }))).toBeNull();
expect(
closeFinishedUpdateRun(run({ machines: [done], localVersion: "0.0.50" })),
).not.toBeNull();
expect(
closeFinishedUpdateRun(run({ machines: [runMachine({ result: "failed" })] })),
).not.toBeNull();
expect(closeFinishedUpdateRun(run({ machines: [done], phase: "providers" }))).not.toBeNull();
});
});
@@ -231,6 +332,7 @@ describe("update everything summary", () => {
localVersion: "0.0.50",
updatedServers: 2,
updatedProviders: 1,
restarting: [],
failures: [
"This app: Could not download update: Network error.",
"alvin: Download failed.",
@@ -256,12 +358,25 @@ describe("update everything summary", () => {
});
it("reports a failure when nothing updated, and nothing when nothing finished", () => {
const empty = { localVersion: null, updatedServers: 0, updatedProviders: 0 };
const empty = { localVersion: null, updatedServers: 0, updatedProviders: 0, restarting: [] };
expect(
getUpdateEverythingToastView({ ...empty, failures: ["alvin: offline"] }, "0.0.50"),
).toEqual({ type: "error", title: "Update failed", description: "alvin: offline" });
expect(getUpdateEverythingToastView({ ...empty, failures: [] }, "0.0.50")).toBeNull();
});
it("names servers still restarting when this app relaunched", () => {
expect(
getUpdateEverythingToastView(
{ ...result, failures: [], restarting: ["alvin", "zbook"] },
"0.0.50",
),
).toEqual({
type: "success",
title: "Updated this app, 2 servers, and 1 provider",
description: "alvin and zbook are still restarting.",
});
});
});
describe("describeUpdateEverything", () => {
@@ -186,17 +186,35 @@ export interface UpdateRunMachine {
readonly environmentId: EnvironmentId;
readonly label: string;
readonly updatesProviders: boolean;
readonly updatesServer: boolean;
/** The server update this machine runs, kept so a failure can be retried.
Null for a provider-only machine, or a server this app handed off before
it relaunched. */
readonly server: ServerUpdateTarget | null;
/** The version a handed-off server comes back on. This app relaunched while
that server restarted, so its version is the only signal left. */
readonly handedOffVersion: string | null;
/** When its current update started, for the elapsed time. */
readonly startedAt: number;
/** Set when every update for this machine has finished. */
readonly result: "done" | "failed" | null;
/** Why it failed, when `result` is "failed". */
readonly failure: string | null;
/** This machine's provider failure, kept apart so a server retry does not clear it. */
readonly providerFailure: string | null;
}
/** A running "update everything" pass, kept while it runs. */
/**
* A running "update everything" pass, kept until every machine finished. A
* failed machine keeps it open, so the sidebar can offer a retry.
*/
export interface UpdateEverythingRun {
/** The version this app installs last, or null when it does not install. */
/** The version this app installs, or null when it does not install (or the
user chose to restart later). */
readonly localVersion: string | null;
/** Providers update first. Servers update after every provider finished. */
readonly phase: "providers" | "servers" | "installing";
/** Providers update first, then servers. "countdown" waits `restartAt` to
relaunch this app, which can still be postponed. */
readonly phase: "providers" | "servers" | "countdown" | "installing";
readonly restartAt: number | null;
readonly machines: ReadonlyArray<UpdateRunMachine>;
}
@@ -207,14 +225,117 @@ export function resolveUpdateRunMachineStatus(
serverState: ServerUpdateState,
): UpdateRunMachineStatus {
if (machine.result !== null) return machine.result;
if (machine.handedOffVersion !== null) return "restarting";
if (phase === "providers" && machine.updatesProviders) return "providers";
if (machine.updatesServer && serverState.status === "running") {
if (machine.server !== null && serverState.status === "running") {
return serverState.stage === "resuming" ? "restarting" : "downloading";
}
return "waiting";
}
const RUN_STATUS_LABELS: Record<UpdateRunMachineStatus, string> = {
/** A server is handed off once it restarts into its update: it finishes
without this app, so this app can relaunch. */
export function isServerUpdateHandedOff(state: ServerUpdateState): boolean {
return state.status === "running" && state.stage === "resuming";
}
/** Ends the run once nothing is left to show: every machine done and this
app not installing. Failures keep it open. */
export function closeFinishedUpdateRun(run: UpdateEverythingRun): UpdateEverythingRun | null {
return run.phase === "servers" &&
run.localVersion === null &&
run.machines.every((machine) => machine.result === "done")
? null
: run;
}
/** An update this long is slower than usual, so the sidebar points it out. */
export const UPDATE_SLOW_AFTER_MS = 3 * 60 * 1000;
/** Elapsed time in whole minutes, such as "6m" or "1h 4m". */
export function formatUpdateElapsed(ms: number): string {
const minutes = Math.floor(ms / 60_000);
if (minutes < 1) return "<1m";
if (minutes < 60) return `${minutes}m`;
return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
}
export interface UpdateRunMachineView {
readonly machine: UpdateRunMachine;
readonly status: UpdateRunMachineStatus;
}
/** This app's own part of a run, for the sidebar. */
export type UpdateRunLocalState =
| { readonly status: "downloading"; readonly percent: number | null }
| { readonly status: "waiting" }
| null;
/** What the expanded sidebar update button says, and its inline action. */
export interface UpdateCapsuleView {
readonly tone: "default" | "slow" | "failed";
readonly label: string;
/** For a slow machine, its status and elapsed time, such as "restarting" and "6m". */
readonly slow?: { readonly status: string; readonly elapsed: string };
readonly action: "later" | "retry" | "dismiss" | null;
}
const isActive = (status: UpdateRunMachineStatus) => status !== "done" && status !== "failed";
/**
* The one line the expanded update button shows for a run, most urgent
* first: this app's restart countdown, a slow machine, overall progress, and
* last any failure once nothing else is running.
*/
export function describeUpdateCapsule(
run: UpdateEverythingRun,
machines: ReadonlyArray<UpdateRunMachineView>,
local: UpdateRunLocalState,
now: number,
): UpdateCapsuleView {
if (run.phase === "countdown" && run.restartAt !== null) {
const seconds = Math.max(0, Math.ceil((run.restartAt - now) / 1000));
return { tone: "default", label: `Restart in ${seconds}s`, action: "later" };
}
if (run.phase === "installing") {
return { tone: "default", label: "Restarting…", action: null };
}
const active = machines.filter(({ status }) => isActive(status) && status !== "waiting");
const slowest = active.toSorted((a, b) => a.machine.startedAt - b.machine.startedAt)[0];
if (slowest && now - slowest.machine.startedAt >= UPDATE_SLOW_AFTER_MS) {
return {
tone: "slow",
label: slowest.machine.label,
slow: {
status: RUN_STATUS_LABELS[slowest.status],
elapsed: formatUpdateElapsed(now - slowest.machine.startedAt),
},
action: null,
};
}
const done = machines.filter(({ status }) => status === "done").length;
if (machines.some(({ status }) => isActive(status))) {
return { tone: "default", label: `${done} of ${machines.length} updated`, action: null };
}
if (local?.status === "downloading") {
return {
tone: "default",
label: `Downloading${local.percent === null ? "" : ` ${Math.floor(local.percent)}%`}`,
action: null,
};
}
const failed = machines.filter(({ status }) => status === "failed");
if (failed.length > 0) {
return {
tone: "failed",
label: failed.length === 1 ? `${failed[0]!.machine.label} failed` : `${failed.length} failed`,
action: failed.some(({ machine }) => machine.server !== null) ? "retry" : "dismiss",
};
}
return { tone: "default", label: `${done} of ${machines.length} updated`, action: null };
}
export const RUN_STATUS_LABELS: Record<UpdateRunMachineStatus, string> = {
providers: "updating providers",
waiting: "waiting",
downloading: "downloading",
@@ -223,22 +344,6 @@ const RUN_STATUS_LABELS: Record<UpdateRunMachineStatus, string> = {
failed: "failed",
};
/**
* Tooltip lines for a running pass, such as "alvin: restarting". `local` is
* this app's own state, such as "downloading 40%", or null when it does not
* install.
*/
export function describeUpdateRun(
machines: ReadonlyArray<{ readonly label: string; readonly status: UpdateRunMachineStatus }>,
local: string | null,
): ReadonlyArray<string> {
return [
"Updating…",
...(local === null ? [] : [`This app: ${local}`]),
...machines.map((machine) => `${machine.label}: ${RUN_STATUS_LABELS[machine.status]}`),
];
}
/** What one pass did. It is saved before this app installs, so it outlives the relaunch. */
export interface UpdateEverythingResult {
/** The version this app installed last, or null when it did not install. */
@@ -247,6 +352,8 @@ export interface UpdateEverythingResult {
readonly updatedProviders: number;
/** One line per failure, each naming its machine. */
readonly failures: ReadonlyArray<string>;
/** Servers still restarting into their update when this app relaunched. */
readonly restarting: ReadonlyArray<string>;
}
/** Counts what a pass updated and lists each failure with its machine. */
@@ -267,6 +374,7 @@ export function collectUpdateEverythingResult(input: {
localVersion: input.localVersion,
updatedServers: input.servers.filter(({ outcome }) => outcome.status === "updated").length,
updatedProviders: input.providers.filter((outcome) => outcome.status === "updated").length,
restarting: [],
failures: [
...input.localFailures.map((failure) => `This app: ${failure}`),
...input.servers.flatMap(({ label, outcome }) =>
@@ -297,13 +405,24 @@ export function getUpdateEverythingToastView(
countLabel(result.updatedServers, "server"),
countLabel(result.updatedProviders, "provider"),
].filter((part) => part !== null);
const restarting =
result.restarting.length === 0
? []
: [
`${joinList(result.restarting)} ${result.restarting.length === 1 ? "is" : "are"} still restarting.`,
];
if (result.failures.length === 0) {
return parts.length === 0 ? null : { type: "success", title: `Updated ${joinList(parts)}` };
if (parts.length === 0) return null;
return {
type: "success",
title: `Updated ${joinList(parts)}`,
...(restarting.length === 0 ? {} : { description: restarting.join("\n") }),
};
}
return {
type: "error",
title: parts.length === 0 ? "Update failed" : `Updated ${joinList(parts)}`,
description: result.failures.join("\n"),
description: [...result.failures, ...restarting].join("\n"),
};
}
@@ -1,5 +1,5 @@
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentId } from "@t3tools/contracts";
import { EnvironmentId } from "@t3tools/contracts";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { Atom } from "effect/reactivity";
@@ -8,11 +8,17 @@ import { useEffect } from "react";
import { APP_VERSION } from "~/branding";
import { appAtomRegistry } from "~/rpc/atomRegistry";
import { useDesktopUpdateState } from "~/state/desktopUpdate";
import { serverEnvironment } from "~/state/server";
import { resolveVersionMismatch } from "~/versionSkew";
import type { ServerUpdateOutcome, ServerUpdateTarget } from "../ServerUpdateAction";
import { stackedThreadToast, toastManager } from "../ui/toast";
import {
closeFinishedUpdateRun,
getUpdateEverythingToastView,
isServerUpdateHandedOff,
type UpdateEverythingResult,
type UpdateEverythingRun,
type UpdateRunMachine,
} from "./updateEverything.logic";
/** The running "update everything" pass, or null. Outlives the sidebar button. */
@@ -32,24 +38,148 @@ export function setUpdateEverythingRun(
appAtomRegistry.update(updateEverythingRunAtom, update);
}
/** Records the result of every update for one machine in the running pass. */
export function settleUpdateRunMachine(environmentId: EnvironmentId, failed: boolean): void {
function updateRunMachines(update: (machine: UpdateRunMachine) => UpdateRunMachine): void {
setUpdateEverythingRun(
(run) => run && closeFinishedUpdateRun({ ...run, machines: run.machines.map(update) }),
);
}
/** Records the result of every update for one machine. `failure` is null when
it succeeded. A server that updated is no longer retried, even when the
machine failed for its providers. The run ends once every machine is done. */
export function settleUpdateRunMachine(
environmentId: EnvironmentId,
failure: string | null,
{
serverUpdated = false,
providerFailure,
}: { readonly serverUpdated?: boolean; readonly providerFailure?: string | null } = {},
): void {
updateRunMachines((machine) =>
machine.environmentId === environmentId
? {
...machine,
result: failure === null ? "done" : "failed",
failure,
...(serverUpdated ? { server: null } : {}),
...(providerFailure === undefined ? {} : { providerFailure }),
}
: machine,
);
}
/** Retries each failed server update in the run. */
export function retryFailedUpdateRunServers(
update: (
target: ServerUpdateTarget,
options: { readonly quiet: boolean },
) => Promise<ServerUpdateOutcome>,
): void {
const failed = (appAtomRegistry.get(updateEverythingRunAtom)?.machines ?? []).flatMap(
(machine) =>
machine.result === "failed" && machine.server !== null
? [{ target: machine.server, providerFailure: machine.providerFailure }]
: [],
);
const targets = failed.map(({ target }) => target);
const retried = new Set(targets.map((target) => target.environmentId));
const startedAt = Date.now();
updateRunMachines((machine) =>
retried.has(machine.environmentId)
? { ...machine, result: null, failure: null, startedAt }
: machine,
);
for (const { target, providerFailure } of failed) {
void update(target, { quiet: true }).then((outcome) =>
settleUpdateRunMachine(
target.environmentId,
// A skipped retry (no permission, disconnected, interrupted) did not update.
outcome.status === "updated"
? providerFailure
: outcome.status === "failed"
? outcome.message
: "Could not start the update",
{ serverUpdated: outcome.status === "updated" },
),
);
}
}
/** Drops the finished machines, which ends a run that only kept failures. */
export function dismissSettledUpdateRunMachines(): void {
setUpdateEverythingRun(
(run) =>
run && {
run &&
closeFinishedUpdateRun({
...run,
machines: run.machines.map((machine) =>
machine.environmentId === environmentId
? { ...machine, result: failed ? "failed" : "done" }
: machine,
),
},
machines: run.machines.filter((machine) => machine.result === null),
}),
);
}
/** Resolves once a server restarts into its update, or its update `finished` first. */
export function waitForServerUpdateHandoff(
environmentId: EnvironmentId,
finished: Promise<unknown>,
): Promise<void> {
return new Promise((resolve) => {
let done = false;
const finish = () => {
if (done) return;
done = true;
queueMicrotask(() => unsubscribe());
resolve();
};
const unsubscribe = appAtomRegistry.subscribe(
serverEnvironment.updateStateAtom(environmentId),
(state) => {
if (isServerUpdateHandedOff(state)) finish();
},
{ immediate: true },
);
void finished.then(finish, finish);
});
}
let decideRestart: ((restart: boolean) => void) | null = null;
/**
* Counts down to this app's relaunch. Resolves true when the countdown ends,
* or false when the user chose to restart later with {@link postponeUpdateRestart}.
*/
export function waitForUpdateRestart(delayMs: number): Promise<boolean> {
return new Promise((resolve) => {
const decide = (restart: boolean) => {
clearTimeout(timer);
decideRestart = null;
resolve(restart);
};
const timer = setTimeout(() => decide(true), delayMs);
decideRestart = decide;
setUpdateEverythingRun(
(run) => run && { ...run, phase: "countdown", restartAt: Date.now() + delayMs },
);
});
}
/** Keeps this app on its version. Its downloaded update waits on the update button. */
export function postponeUpdateRestart(): void {
decideRestart?.(false);
}
const SAVED_RESULT_KEY = "t3code:update-everything-result:v1";
// A result older than this belongs to an install that never relaunched the app.
const SAVED_RESULT_MAX_AGE_MS = 10 * 60 * 1000;
// Covers a background service's 30-minute trial start, like the server update itself.
const HANDOFF_TIMEOUT_MS = 32 * 60 * 1000;
const HandedOffServer = Schema.Struct({
environmentId: EnvironmentId,
label: Schema.String,
targetVersion: Schema.String,
startedAt: Schema.Number,
});
type HandedOffServer = typeof HandedOffServer.Type;
const SavedResult = Schema.Struct({
savedAt: Schema.Number,
@@ -57,15 +187,47 @@ const SavedResult = Schema.Struct({
updatedServers: Schema.Number,
updatedProviders: Schema.Number,
failures: Schema.Array(Schema.String),
// Older saved results have no handed-off servers.
handedOff: Schema.optional(Schema.Array(HandedOffServer)),
});
const decodeSavedResult = Schema.decodeUnknownOption(Schema.fromJsonString(SavedResult));
/** Keeps a result through this app's relaunch. Call it right before the install. */
/**
* Keeps a result through this app's relaunch. Call it right before the
* install. Servers still restarting are saved too, so the sidebar keeps
* following them after the relaunch.
*/
export function saveUpdateEverythingResult(result: UpdateEverythingResult): void {
const run = appAtomRegistry.get(updateEverythingRunAtom);
const handedOff = (run?.machines ?? []).flatMap((machine): HandedOffServer[] => {
if (machine.result !== null) return [];
const state = appAtomRegistry.get(serverEnvironment.updateStateAtom(machine.environmentId));
// A desktop-managed server installs its own feed's version, which only its
// update state knows. A server followed from an earlier relaunch keeps its version.
const targetVersion =
machine.handedOffVersion ??
(state.status === "running" ? state.targetVersion : machine.server?.targetVersion);
if (targetVersion === undefined) return [];
return [
{
environmentId: machine.environmentId,
label: machine.label,
targetVersion,
startedAt: machine.startedAt,
},
];
});
try {
window.localStorage.setItem(
SAVED_RESULT_KEY,
JSON.stringify({ ...result, savedAt: Date.now() } satisfies typeof SavedResult.Type),
JSON.stringify({
savedAt: Date.now(),
localVersion: result.localVersion,
updatedServers: result.updatedServers,
updatedProviders: result.updatedProviders,
failures: result.failures,
handedOff,
} satisfies typeof SavedResult.Type),
);
} catch {
// Without storage the summary is lost with the relaunch; the update still runs.
@@ -80,7 +242,7 @@ export function clearSavedUpdateEverythingResult(): void {
}
}
function takeSavedUpdateEverythingResult(): UpdateEverythingResult | null {
function takeSavedUpdateEverythingResult(): typeof SavedResult.Type | null {
try {
const raw = window.localStorage.getItem(SAVED_RESULT_KEY);
if (raw === null) return null;
@@ -111,19 +273,90 @@ export function showUpdateEverythingResult(result: UpdateEverythingResult): void
);
}
/**
* Follows servers that were restarting when this app relaunched. Each is done
* once it reports its target version, or failed after the handoff timeout.
* One toast reports them all at the end.
*/
function followHandedOffServers(servers: ReadonlyArray<HandedOffServer>): void {
// A server already past the timeout still shows, then fails on its first timer tick.
if (servers.length === 0) return;
setUpdateEverythingRun(() => ({
localVersion: null,
phase: "servers",
restartAt: null,
machines: servers.map((server) => ({
environmentId: server.environmentId,
label: server.label,
updatesProviders: false,
server: null,
handedOffVersion: server.targetVersion,
startedAt: server.startedAt,
result: null,
failure: null,
providerFailure: null,
})),
}));
let remaining = servers.length;
let updatedServers = 0;
const failures: string[] = [];
for (const server of servers) {
let settled = false;
const settle = (failure: string | null) => {
if (settled) return;
settled = true;
clearTimeout(timer);
queueMicrotask(() => unsubscribe());
settleUpdateRunMachine(server.environmentId, failure);
if (failure === null) updatedServers += 1;
else failures.push(`${server.label}: ${failure}`);
remaining -= 1;
if (remaining === 0) {
showUpdateEverythingResult({
localVersion: null,
updatedServers,
updatedProviders: 0,
failures,
restarting: [],
});
}
};
const timer = setTimeout(
() => settle(`Not back after ${HANDOFF_TIMEOUT_MS / 60_000} minutes`),
server.startedAt + HANDOFF_TIMEOUT_MS - Date.now(),
);
const unsubscribe = appAtomRegistry.subscribe(
serverEnvironment.configValueAtom(server.environmentId),
(config) => {
if (
config !== null &&
resolveVersionMismatch(config.environment.serverVersion, server.targetVersion) === null
) {
settle(null);
}
},
{ immediate: true },
);
}
}
let notifiedNotAppliedVersion: string | null = null;
/**
* Desktop launch notices for updates: the summary of a pass that ended with
* this app's relaunch, and a warning when the last install did not apply.
* Mount once at the app root.
* Servers still restarting from that pass stay in the sidebar until they are
* back. Mount once at the app root.
*/
export function DesktopUpdateLaunchNotice() {
const notAppliedVersion = useDesktopUpdateState()?.notAppliedVersion ?? null;
useEffect(() => {
const result = takeSavedUpdateEverythingResult();
if (result) showUpdateEverythingResult(result);
const saved = takeSavedUpdateEverythingResult();
if (!saved) return;
const handedOff = saved.handedOff ?? [];
showUpdateEverythingResult({ ...saved, restarting: handedOff.map((server) => server.label) });
followHandedOffServers(handedOff);
}, []);
useEffect(() => {
@@ -12,8 +12,9 @@ import { serverEnvironment } from "~/state/server";
import { environmentSession } from "~/state/session";
import { getProviderUpdateRunOutcome } from "../ProviderUpdateLaunchNotification.logic";
import { useProviderUpdates } from "../ProviderUpdatesAction";
import { canUpdateServer, useServerUpdate } from "../ServerUpdateAction";
import { canUpdateServer, type ServerUpdateOutcome, useServerUpdate } from "../ServerUpdateAction";
import {
closeFinishedUpdateRun,
collectRestartingMachines,
collectServerUpdateTargets,
collectUpdateEverythingResult,
@@ -28,8 +29,13 @@ import {
setUpdateEverythingRun,
settleUpdateRunMachine,
showUpdateEverythingResult,
waitForServerUpdateHandoff,
waitForUpdateRestart,
} from "./updateEverythingRun";
/** How long this app counts down before it relaunches, so the user can postpone it. */
const UPDATE_RESTART_DELAY_MS = 5_000;
/** Where this app's own download or install reports a failure. */
export type ReportLocalUpdateError = (title: string, description: string) => void;
@@ -40,7 +46,9 @@ export type ReportLocalUpdateError = (title: string, description: string) => voi
* only once npm confirms that version. `run` performs the whole pass, including
* this app's own download and install when given. It updates quietly, tracks
* each machine in the run state, and reports one summary toast at the end.
* When this app installs, the summary waits for the relaunch.
* This app relaunches once every server restarts into its update, after a
* short countdown the user can postpone. The summary then waits for the
* relaunch, and servers still restarting are followed after it.
*/
export function useUpdateEverything(localUpdateVersion: string | null) {
const targetVersion = localUpdateVersion ?? APP_VERSION;
@@ -126,14 +134,19 @@ export function useUpdateEverything(localUpdateVersion: string | null) {
const reportLocalError: ReportLocalUpdateError = (title, description) => {
localFailures.push(`${title}: ${description}`);
};
const startedAt = Date.now();
const machinesById = new Map<UpdateRunMachine["environmentId"], UpdateRunMachine>();
for (const machine of providers.machines) {
machinesById.set(machine.environmentId, {
environmentId: machine.environmentId,
label: machine.label,
updatesProviders: true,
updatesServer: false,
server: null,
handedOffVersion: null,
startedAt,
result: null,
failure: null,
providerFailure: null,
});
}
for (const server of servers) {
@@ -142,17 +155,23 @@ export function useUpdateEverything(localUpdateVersion: string | null) {
environmentId: server.environmentId,
label: server.serverLabel,
updatesProviders: existing?.updatesProviders ?? false,
updatesServer: true,
server,
handedOffVersion: null,
startedAt,
result: null,
failure: null,
providerFailure: null,
});
}
const localVersion = installLocal ? localUpdateVersion : null;
setUpdateEverythingRun(() => ({
localVersion,
phase: "providers",
restartAt: null,
machines: Array.from(machinesById.values()),
}));
const failedProviderMachines = new Set<UpdateRunMachine["environmentId"]>();
const providerFailures = new Map<UpdateRunMachine["environmentId"], string>();
const finishedServers: Array<{ label: string; outcome: ServerUpdateOutcome }> = [];
try {
const outcome = await runUpdateEverything({
...(downloadLocal ? { downloadLocal: () => downloadLocal(reportLocalError) } : {}),
@@ -161,49 +180,94 @@ export function useUpdateEverything(localUpdateVersion: string | null) {
const outcomes = runs.map((run) => {
const runOutcome = getProviderUpdateRunOutcome(run);
// An interrupted update did not finish either, so its row is not "done".
if (runOutcome.status !== "updated") failedProviderMachines.add(run.environmentId);
if (runOutcome.status !== "updated") {
providerFailures.set(
run.environmentId,
runOutcome.status === "failed" ? runOutcome.line : "Provider update interrupted",
);
}
return runOutcome;
});
for (const machine of machinesById.values()) {
if (!machine.updatesServer) {
if (machine.server === null) {
settleUpdateRunMachine(
machine.environmentId,
failedProviderMachines.has(machine.environmentId),
providerFailures.get(machine.environmentId) ?? null,
);
}
}
setUpdateEverythingRun((run) => run && { ...run, phase: "servers" });
const serversStartedAt = Date.now();
setUpdateEverythingRun(
(run) =>
run && {
...run,
phase: "servers",
machines: run.machines.map((machine) =>
machine.server === null ? machine : { ...machine, startedAt: serversStartedAt },
),
},
);
return outcomes;
},
updateServers: () =>
Promise.all(
servers.map(async (server) => {
const serverOutcome = await updateServer(server, { quiet: true });
settleUpdateRunMachine(
server.environmentId,
serverOutcome.status === "failed" ||
failedProviderMachines.has(server.environmentId),
);
return { label: server.serverLabel, outcome: serverOutcome };
}),
),
updateServers: async () => {
const runs = servers.map(async (server) => {
const serverOutcome = await updateServer(server, { quiet: true });
settleUpdateRunMachine(
server.environmentId,
serverOutcome.status === "failed"
? serverOutcome.message
: (providerFailures.get(server.environmentId) ?? null),
{
serverUpdated: serverOutcome.status !== "failed",
providerFailure: providerFailures.get(server.environmentId) ?? null,
},
);
const finished = { label: server.serverLabel, outcome: serverOutcome };
finishedServers.push(finished);
return finished;
});
// Once a server restarts into its update it finishes on its own,
// so this app does not wait for it to come back.
await Promise.all(
servers.map((server, index) =>
waitForServerUpdateHandoff(server.environmentId, runs[index]!),
),
);
return runs;
},
});
const result = () =>
const result = (finished: ReadonlyArray<{ label: string; outcome: ServerUpdateOutcome }>) =>
collectUpdateEverythingResult({
localVersion: null,
localFailures,
servers: outcome.servers,
servers: finished,
providers: outcome.providers,
});
if (outcome.localReady && installLocal) {
setUpdateEverythingRun((run) => run && { ...run, phase: "installing" });
saveUpdateEverythingResult({ ...result(), localVersion });
if (await installLocal(reportLocalError)) return;
clearSavedUpdateEverythingResult();
if (await waitForUpdateRestart(UPDATE_RESTART_DELAY_MS)) {
setUpdateEverythingRun(
(run) => run && { ...run, phase: "installing", restartAt: null },
);
saveUpdateEverythingResult({ ...result(finishedServers), localVersion });
if (await installLocal(reportLocalError)) return;
clearSavedUpdateEverythingResult();
}
}
showUpdateEverythingResult(result());
} finally {
// This app is not relaunching, so the pass waits for every server.
setUpdateEverythingRun(
(run) =>
run &&
closeFinishedUpdateRun({
...run,
phase: "servers",
restartAt: null,
localVersion: null,
}),
);
showUpdateEverythingResult(result(await Promise.all(outcome.servers)));
} catch (error) {
setUpdateEverythingRun(() => null);
throw error;
}
},
};
+9 -1
View File
@@ -9,12 +9,20 @@ notice.
The update button at the bottom of the sidebar updates every connected machine
in one step. It updates outdated providers, then servers that are behind, then
the desktop app you are using, which restarts last. Servers move to the
the desktop app you are using. Servers move to the
version your desktop app is installing, or to your web app's version. A
background service stays on its current release channel. A remote desktop app
installs the latest release from its own channel. Hover the button to see what
it will update.
While it runs, the button widens to show progress. It names a machine that is
taking longer than usual, and offers **Retry** for a server that failed. Click
it to see every machine. The desktop app restarts once each server has started
its own restart, after a short countdown. Choose **Later** to keep working and
restart from the update button when you are ready. A server still restarting
finishes on its own, and the button keeps showing it after the desktop app
restarts.
Server updates appear only after that version is published to npm. Remote
desktop apps do not wait for npm. The confirmation lists each machine it skips
and why, such as a machine that is offline or needs a manual update. Use the
@@ -320,6 +320,13 @@ describe("server state projection", () => {
fromVersion: "0.0.30",
targetVersion: "0.0.31",
});
// A prepared desktop app update restarts only after the client commits it.
expect(
serverUpdateStateForProgressEvent("0.0.30", "0.0.31", {
type: "complete",
result: { targetVersion: "0.0.31", method: "desktop-app", desktopUpdateToken: "token" },
}).stage,
).toBe("installing");
});
it("keeps active update state and hides stale failures after a version change", () => {
+17 -5
View File
@@ -283,6 +283,11 @@ export const waitForDesktopUpdateTarget = Effect.fn("waitForDesktopUpdateTarget"
});
});
/**
* "resuming" means the server has its update and restarts without this
* client. A desktop app update is not there yet when its prepare step
* completes: the client still has to commit it, so it stays "installing".
*/
export function serverUpdateStateForProgressEvent(
fromVersion: string,
targetVersion: string,
@@ -290,7 +295,12 @@ export function serverUpdateStateForProgressEvent(
): Extract<ServerUpdateState, { status: "running" }> {
return {
status: "running",
stage: event.type === "complete" ? "resuming" : event.stage,
stage:
event.type !== "complete"
? event.stage
: event.result.method === "desktop-app" && event.result.desktopUpdateToken !== undefined
? "installing"
: "resuming",
fromVersion,
targetVersion,
};
@@ -753,11 +763,13 @@ export function createServerEnvironmentAtoms<R, E>(
.pipe(
Stream.runForEach((event) =>
Effect.sync(() => {
currentStage = event.type === "complete" ? "resuming" : event.stage;
atomRegistry.set(
stateAtom,
serverUpdateStateForProgressEvent(fromVersion, targetVersion, event),
const state = serverUpdateStateForProgressEvent(
fromVersion,
targetVersion,
event,
);
currentStage = state.stage;
atomRegistry.set(stateAtom, state);
}).pipe(
Effect.andThen(
event.type === "complete"