The best way to control Claude Code, Codex and more from any computer or phone
fix(web): update everything no longer waits on slow servers, and shows progress in the sidebar (#19837)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Theo Browne committed
Oct 15, 2026 at 03:17 UTC
313f23e4edaca9d07c66117baffdabd88c91e0ef
9 files changed
+922
-169
apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx
new
+201
@@ -0,0 +1,201 @@
1
+import { useAtomValue } from "@effect/atom-react";
2
+import { Atom } from "effect/reactivity";
3
+import { type ReactNode, useCallback, useMemo, useSyncExternalStore } from "react";
4
+
5
+import { cn } from "~/lib/utils";
6
+import { serverEnvironment } from "~/state/server";
7
+import { useServerUpdate } from "../ServerUpdateAction";
8
+import { Button } from "../ui/button";
9
+import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
10
+import {
11
+ describeUpdateCapsule,
12
+ formatUpdateElapsed,
13
+ RUN_STATUS_LABELS,
14
+ resolveUpdateRunMachineStatus,
15
+ type UpdateEverythingRun,
16
+ type UpdateRunLocalState,
17
+ type UpdateRunMachineView,
18
+} from "./updateEverything.logic";
19
+import {
20
+ dismissSettledUpdateRunMachines,
21
+ postponeUpdateRestart,
22
+ retryFailedUpdateRunServers,
23
+} from "./updateEverythingRun";
24
+
25
+/** The current time, rounded down to `intervalMs` so it changes once per
26
+ interval. With null it is read only when something else renders. */
27
+function useNow(intervalMs: number | null): number {
28
+ const step = intervalMs ?? 60_000;
29
+ const subscribe = useCallback(
30
+ (onChange: () => void) => {
31
+ if (intervalMs === null) return () => {};
32
+ const timer = setInterval(onChange, intervalMs);
33
+ return () => clearInterval(timer);
34
+ },
35
+ [intervalMs],
36
+ );
37
+ return useSyncExternalStore(subscribe, () => Math.floor(Date.now() / step) * step);
38
+}
39
+
40
+function useUpdateRunMachineViews(run: UpdateEverythingRun): ReadonlyArray<UpdateRunMachineView> {
41
+ const viewsAtom = useMemo(
42
+ () =>
43
+ Atom.make((get) =>
44
+ run.machines.map((machine) => ({
45
+ machine,
46
+ status: resolveUpdateRunMachineStatus(
47
+ machine,
48
+ run.phase,
49
+ get(serverEnvironment.updateStateAtom(machine.environmentId)),
50
+ ),
51
+ })),
52
+ ),
53
+ [run],
54
+ );
55
+ return useAtomValue(viewsAtom);
56
+}
57
+
58
+function localStatusLabel(run: UpdateEverythingRun, local: UpdateRunLocalState, now: number) {
59
+ if (run.phase === "countdown" && run.restartAt !== null) {
60
+ return `restarts in ${Math.max(0, Math.ceil((run.restartAt - now) / 1000))}s`;
61
+ }
62
+ if (run.phase === "installing") return "restarting";
63
+ if (local?.status === "downloading") {
64
+ return `downloading${local.percent === null ? "" : ` ${Math.floor(local.percent)}%`}`;
65
+ }
66
+ return "restarts after the servers";
67
+}
68
+
69
+/**
70
+ * The sidebar update button while an "update everything" pass runs. It grows
71
+ * left into the free footer space and names the most urgent thing: this
72
+ * app's restart countdown, a slow machine, progress, or a failure. Click it
73
+ * for every machine. Time labels change once a second only during the
74
+ * countdown, and otherwise once every 30 seconds.
75
+ */
76
+export function SidebarUpdateCapsule({
77
+ run,
78
+ local,
79
+ icon,
80
+ onRestart,
81
+}: {
82
+ readonly run: UpdateEverythingRun;
83
+ readonly local: UpdateRunLocalState;
84
+ readonly icon: ReactNode;
85
+ /** Installs this app's downloaded update after the user postponed it. */
86
+ readonly onRestart?: () => Promise<void>;
87
+}) {
88
+ const machines = useUpdateRunMachineViews(run);
89
+ const hasActiveMachine = machines.some(
90
+ ({ status }) => status !== "done" && status !== "failed" && status !== "waiting",
91
+ );
92
+ const now = useNow(run.phase === "countdown" ? 1_000 : hasActiveMachine ? 30_000 : null);
93
+ const view = describeUpdateCapsule(run, machines, local, now);
94
+ const updateServer = useServerUpdate();
95
+ const failed = machines.some(({ status }) => status === "failed");
96
+ const settled = !hasActiveMachine && run.localVersion === null;
97
+
98
+ const actionLabel =
99
+ view.action === "later" ? "Later" : view.action === "retry" ? "Retry" : "Dismiss";
100
+ const runAction = () => {
101
+ if (view.action === "later") postponeUpdateRestart();
102
+ else if (view.action === "retry") retryFailedUpdateRunServers(updateServer);
103
+ else dismissSettledUpdateRunMachines();
104
+ };
105
+
106
+ return (
107
+ <Popover>
108
+ <div
109
+ className={cn(
110
+ "relative flex h-8 min-w-0 flex-1 items-center rounded-full bg-sidebar-control-surface text-sidebar-foreground",
111
+ view.tone === "slow" && "ring-1 ring-warning/40 ring-inset",
112
+ view.tone === "failed" && "ring-1 ring-destructive/40 ring-inset",
113
+ )}
114
+ >
115
+ <PopoverTrigger
116
+ render={
117
+ <button
118
+ type="button"
119
+ aria-label={
120
+ view.slow ? `${view.label} ${view.slow.status} ${view.slow.elapsed}` : view.label
121
+ }
122
+ 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"
123
+ />
124
+ }
125
+ />
126
+ <span className="pointer-events-none relative min-w-0 flex-1 truncate pl-3 text-xs">
127
+ <span className={cn(view.tone === "failed" && "text-destructive")}>{view.label}</span>
128
+ {view.slow ? (
129
+ <span className="text-warning tabular-nums"> {view.slow.elapsed}</span>
130
+ ) : null}
131
+ </span>
132
+ {/* The footer leaves little room, so an action takes the icon's place. */}
133
+ {view.action !== null ? (
134
+ <button
135
+ type="button"
136
+ className="relative shrink-0 cursor-pointer pr-3 pl-1.5 text-xs underline decoration-muted-foreground/60 underline-offset-3 hover:decoration-current"
137
+ onClick={runAction}
138
+ >
139
+ {actionLabel}
140
+ </button>
141
+ ) : (
142
+ <span className="pointer-events-none relative grid size-8 shrink-0 place-items-center">
143
+ {icon}
144
+ </span>
145
+ )}
146
+ </div>
147
+ <PopoverPopup side="top" align="end" padding="compact" width="sm">
148
+ <div className="flex flex-col gap-1 text-xs">
149
+ {run.localVersion !== null ? (
150
+ <div className="flex items-center justify-between gap-3">
151
+ <span>This app</span>
152
+ <span className="text-muted-foreground tabular-nums">
153
+ {localStatusLabel(run, local, now)}
154
+ </span>
155
+ </div>
156
+ ) : onRestart ? (
157
+ <div className="flex items-center justify-between gap-3">
158
+ <span>This app</span>
159
+ <Button size="xs" variant="outline" onClick={() => void onRestart()}>
160
+ Restart to update
161
+ </Button>
162
+ </div>
163
+ ) : null}
164
+ {machines.map(({ machine, status }) => (
165
+ <div key={machine.environmentId} className="flex min-w-0 flex-col">
166
+ <div className="flex items-center justify-between gap-3">
167
+ <span className="truncate">{machine.label}</span>
168
+ <span
169
+ className={cn(
170
+ "shrink-0 tabular-nums",
171
+ status === "failed" ? "text-destructive" : "text-muted-foreground",
172
+ )}
173
+ >
174
+ {RUN_STATUS_LABELS[status]}
175
+ {status !== "done" && status !== "failed" && status !== "waiting"
176
+ ? ` ${formatUpdateElapsed(now - machine.startedAt)}`
177
+ : ""}
178
+ </span>
179
+ </div>
180
+ {machine.failure !== null ? (
181
+ <span className="break-words text-muted-foreground">{machine.failure}</span>
182
+ ) : null}
183
+ </div>
184
+ ))}
185
+ {settled && failed ? (
186
+ <div className="mt-1 flex justify-end gap-1">
187
+ {view.action === "retry" ? (
188
+ <Button size="xs" variant="outline" onClick={runAction}>
189
+ Retry
190
+ </Button>
191
+ ) : null}
192
+ <Button size="xs" variant="ghost" onClick={dismissSettledUpdateRunMachines}>
193
+ Dismiss
194
+ </Button>
195
+ </div>
196
+ ) : null}
197
+ </div>
198
+ </PopoverPopup>
199
+ </Popover>
200
+ );
201
+}
apps/web/src/components/sidebar/SidebarUpdatePill.tsx
+78
-84
@@ -1,23 +1,12 @@
1
-import { useAtomValue } from "@effect/atom-react";
1
import type { DesktopBridge, DesktopUpdateState } from "@t3tools/contracts";
3
-import { Atom } from "effect/reactivity";
2
import { TriangleAlertIcon } from "lucide-react";
5
-import {
6
- type ComponentProps,
7
- useCallback,
8
- useEffect,
9
- useId,
10
- useMemo,
11
- useRef,
12
- useState,
13
-} from "react";
3
+import { type ComponentProps, useCallback, useEffect, useId, useRef, useState } from "react";
4
import { flushSync } from "react-dom";
5
import { isElectron } from "../../env";
6
import { useMediaQuery } from "../../hooks/useMediaQuery";
7
import { cn } from "../../lib/utils";
8
import { ensureLocalApi } from "../../localApi";
9
import { useDesktopUpdateState } from "../../state/desktopUpdate";
20
-import { serverEnvironment } from "../../state/server";
10
import { stackedThreadToast, toastManager } from "../ui/toast";
11
import {
12
canCheckForUpdate,
@@ -43,13 +32,14 @@ import {
32
shouldShowDesktopUpdateCheckIcon,
33
} from "./DesktopUpdateStatusIcon";
34
import { SidebarUpdateReleaseNotes } from "./SidebarUpdateReleaseNotes";
35
+import { SidebarUpdateCapsule } from "./SidebarUpdateCapsule";
36
import { UpdateEverythingDialog } from "./UpdateEverythingDialog";
37
+import type { UpdateEverythingRun, UpdateRunLocalState } from "./updateEverything.logic";
38
import {
48
- describeUpdateRun,
49
- resolveUpdateRunMachineStatus,
50
- type UpdateEverythingRun,
51
-} from "./updateEverything.logic";
52
-import { useUpdateEverythingRun } from "./updateEverythingRun";
39
+ clearSavedUpdateEverythingResult,
40
+ saveUpdateEverythingResult,
41
+ useUpdateEverythingRun,
42
+} from "./updateEverythingRun";
43
import { type ReportLocalUpdateError, useUpdateEverything } from "./useUpdateEverything";
44
45
type SidebarUpdatePopoverChangeDetails = Parameters<
@@ -202,43 +192,6 @@ async function installLocalUpdate(
192
}
193
}
194
205
-/** Tooltip lines for a running pass: this app first, then one per machine. */
206
-function useUpdateRunTooltip(
207
- run: UpdateEverythingRun | null,
208
- state: DesktopUpdateState | null,
209
- localReady: boolean,
210
-): string | null {
211
- const statusesAtom = useMemo(
212
- () =>
213
- Atom.make((get) =>
214
- run === null
215
- ? []
216
- : run.machines.map((machine) => ({
217
- label: machine.label,
218
- status: resolveUpdateRunMachineStatus(
219
- machine,
220
- run.phase,
221
- get(serverEnvironment.updateStateAtom(machine.environmentId)),
222
- ),
223
- })),
224
- ),
225
- [run],
226
- );
227
- const statuses = useAtomValue(statusesAtom);
228
- if (run === null) return null;
229
- const local =
230
- run.localVersion === null
231
- ? null
232
- : state?.status === "downloading"
233
- ? `downloading${state.downloadPercent === null ? "" : ` ${Math.floor(state.downloadPercent)}%`}`
234
- : run.phase === "installing"
235
- ? "restarting"
236
- : localReady
237
- ? "restarts last"
238
- : "waiting";
239
- return describeUpdateRun(statuses, local).join("\n");
240
-}
241
-
195
/**
196
* The sidebar update button. With only a local app update it downloads, then
197
* installs. When other machines' servers or any providers are behind, one
@@ -279,7 +232,6 @@ function SidebarUpdateControl() {
232
// Providers leave the list once queued, so the run keeps its own state.
233
const run = useUpdateEverythingRun();
234
const isRunningEverything = run !== null;
282
- const runTooltip = useUpdateRunTooltip(run, state, action === "install");
235
const showCheckIcon = shouldShowDesktopUpdateCheckIcon({
236
isAnimationLatched: isCheckAnimationLatched,
237
isChecking: state?.status === "checking",
@@ -292,18 +244,15 @@ function SidebarUpdateControl() {
244
isDownloading,
245
showCheckIcon,
246
});
295
- const tooltip =
296
- runTooltip !== null
297
- ? runTooltip
298
- : runsEverything
299
- ? everything.summary
300
- : showUpdateDetails
301
- ? state
302
- ? getDesktopUpdateButtonTooltip(state)
303
- : "Update available"
304
- : showCheckIcon
305
- ? "Checking for updates…"
306
- : "Check for updates";
247
+ const tooltip = runsEverything
248
+ ? everything.summary
249
+ : showUpdateDetails
250
+ ? state
251
+ ? getDesktopUpdateButtonTooltip(state)
252
+ : "Update available"
253
+ : showCheckIcon
254
+ ? "Checking for updates…"
255
+ : "Check for updates";
256
const disabled = showCheckIcon
257
? true
258
: runsEverything
@@ -312,7 +261,7 @@ function SidebarUpdateControl() {
261
? isDesktopUpdateButtonDisabled(state)
262
: !canCheckForUpdate(state);
263
const isInteractionDisabled = disabled || isActionPending || isRunningEverything;
315
- // During a run the tooltip shows its progress instead of release notes.
264
+ // During a run the capsule shows its progress instead of release notes.
265
const showReleaseNotesPopover =
266
!isRunningEverything && shouldUseSidebarUpdateReleaseNotesPopover(showUpdateDetails, state);
267
@@ -442,6 +391,65 @@ function SidebarUpdateControl() {
391
// Web has no local app to check, so it only shows the button for remote work.
392
if (!isElectron && !runsEverything && !isRunningEverything) return null;
393
394
+ const statusIcon = (
395
+ <DesktopUpdateStatusIcon
396
+ key={showCheckIcon ? checkAnimationKey : iconStatus}
397
+ downloadPercent={state?.downloadPercent ?? null}
398
+ isCheckAnimating={showCheckIcon && !prefersReducedMotion}
399
+ onCheckAnimationIteration={handleCheckAnimationIteration}
400
+ status={iconStatus}
401
+ />
402
+ );
403
+ const confirmDialog = (
404
+ <UpdateEverythingDialog
405
+ open={isConfirmingEverything}
406
+ onOpenChange={setIsConfirmingEverything}
407
+ summary={everything.summary}
408
+ lines={everything.lines}
409
+ restarts={everything.restarts}
410
+ skipped={everything.skipped}
411
+ onConfirm={() => void runEverything()}
412
+ />
413
+ );
414
+
415
+ if (run !== null) {
416
+ const local: UpdateRunLocalState =
417
+ run.localVersion === null
418
+ ? null
419
+ : state?.status === "downloading"
420
+ ? { status: "downloading", percent: state.downloadPercent }
421
+ : { status: "waiting" };
422
+ return (
423
+ <SidebarMenuItem className="ml-auto flex min-w-0 flex-1">
424
+ <SidebarUpdateCapsule
425
+ run={run}
426
+ local={local}
427
+ icon={statusIcon}
428
+ // After "Later", this app's downloaded update can still be installed
429
+ // while the run follows the other machines.
430
+ {...(run.localVersion === null && action === "install" && window.desktopBridge
431
+ ? {
432
+ onRestart: async () => {
433
+ // Like the countdown, keep following servers still restarting.
434
+ saveUpdateEverythingResult({
435
+ localVersion: localUpdateVersion,
436
+ updatedServers: 0,
437
+ updatedProviders: 0,
438
+ failures: [],
439
+ restarting: [],
440
+ });
441
+ if (!(await installLocalUpdate(window.desktopBridge!))) {
442
+ clearSavedUpdateEverythingResult();
443
+ }
444
+ },
445
+ }
446
+ : {})}
447
+ />
448
+ {confirmDialog}
449
+ </SidebarMenuItem>
450
+ );
451
+ }
452
+
453
const updateButton = (
454
<button
455
type="button"
@@ -482,13 +490,7 @@ function SidebarUpdateControl() {
490
);
491
}}
492
>
485
- <DesktopUpdateStatusIcon
486
- key={showCheckIcon ? checkAnimationKey : iconStatus}
487
- downloadPercent={state?.downloadPercent ?? null}
488
- isCheckAnimating={showCheckIcon && !prefersReducedMotion}
489
- onCheckAnimationIteration={handleCheckAnimationIteration}
490
- status={iconStatus}
491
- />
493
+ {statusIcon}
494
</button>
495
);
496
@@ -559,15 +561,7 @@ function SidebarUpdateControl() {
561
</PopoverPopup>
562
) : null}
563
</Popover>
562
- <UpdateEverythingDialog
563
- open={isConfirmingEverything}
564
- onOpenChange={setIsConfirmingEverything}
565
- summary={everything.summary}
566
- lines={everything.lines}
567
- restarts={everything.restarts}
568
- skipped={everything.skipped}
569
- onConfirm={() => void runEverything()}
570
- />
564
+ {confirmDialog}
565
</SidebarMenuItem>
566
);
567
}
apps/web/src/components/sidebar/updateEverything.logic.test.ts
+124
-9
@@ -4,15 +4,38 @@ import { describe, expect, it } from "vite-plus/test";
4
import {
5
collectRestartingMachines,
6
collectServerUpdateTargets,
7
+ closeFinishedUpdateRun,
8
collectUpdateEverythingResult,
9
+ describeUpdateCapsule,
10
describeUpdateEverything,
11
getUpdateEverythingToastView,
12
resolveUpdateRunMachineStatus,
13
runUpdateEverything,
14
type UpdateEverythingMachine,
15
+ type UpdateEverythingRun,
16
type UpdateRunMachine,
17
+ type UpdateRunMachineStatus,
18
+ UPDATE_SLOW_AFTER_MS,
19
} from "./updateEverything.logic";
20
21
+const runMachine = (overrides: Partial<UpdateRunMachine> = {}): UpdateRunMachine => ({
22
+ environmentId: EnvironmentId.make("alvin"),
23
+ label: "alvin",
24
+ updatesProviders: true,
25
+ server: {
26
+ environmentId: EnvironmentId.make("alvin"),
27
+ serverLabel: "alvin",
28
+ selfUpdate: "boot-service",
29
+ targetVersion: "0.0.50",
30
+ },
31
+ handedOffVersion: null,
32
+ startedAt: 0,
33
+ result: null,
34
+ failure: null,
35
+ providerFailure: null,
36
+ ...overrides,
37
+});
38
+
39
function machine(
40
id: string,
41
serverVersion: string,
@@ -175,14 +198,6 @@ describe("runUpdateEverything", () => {
198
});
199
200
describe("resolveUpdateRunMachineStatus", () => {
178
- const runMachine = (overrides: Partial<UpdateRunMachine> = {}): UpdateRunMachine => ({
179
- environmentId: EnvironmentId.make("alvin"),
180
- label: "alvin",
181
- updatesProviders: true,
182
- updatesServer: true,
183
- result: null,
184
- ...overrides,
185
- });
201
const running = (stage: "downloading" | "installing" | "resuming") =>
202
({ status: "running", stage, fromVersion: "0.0.40", targetVersion: "0.0.50" }) as const;
203
@@ -206,6 +221,92 @@ describe("resolveUpdateRunMachineStatus", () => {
221
expect(resolveUpdateRunMachineStatus(runMachine({ result: "failed" }), "servers", idle)).toBe(
222
"failed",
223
);
224
+ // After this app relaunched, a handed-off server has no live update state.
225
+ expect(
226
+ resolveUpdateRunMachineStatus(
227
+ runMachine({ server: null, handedOffVersion: "0.0.50" }),
228
+ "servers",
229
+ idle,
230
+ ),
231
+ ).toBe("restarting");
232
+ });
233
+});
234
+
235
+describe("update capsule", () => {
236
+ const run = (overrides: Partial<UpdateEverythingRun> = {}): UpdateEverythingRun => ({
237
+ localVersion: null,
238
+ phase: "servers",
239
+ restartAt: null,
240
+ machines: [],
241
+ ...overrides,
242
+ });
243
+ const view = (
244
+ label: string,
245
+ status: UpdateRunMachineStatus,
246
+ overrides: Partial<UpdateRunMachine> = {},
247
+ ) => ({
248
+ machine: runMachine({ environmentId: EnvironmentId.make(label), label, ...overrides }),
249
+ status,
250
+ });
251
+
252
+ it("counts down this app's restart before anything else", () => {
253
+ expect(
254
+ describeUpdateCapsule(
255
+ run({ phase: "countdown", restartAt: 5_000, localVersion: "0.0.50" }),
256
+ [view("alvin", "restarting")],
257
+ { status: "waiting" },
258
+ 1_200,
259
+ ),
260
+ ).toEqual({ tone: "default", label: "Restart in 4s", action: "later" });
261
+ });
262
+
263
+ it("names the slowest machine once it passes the slow threshold", () => {
264
+ const machines = [
265
+ view("bb-1", "done"),
266
+ view("zbook", "downloading", { startedAt: 60_000 }),
267
+ view("alvin", "restarting", { startedAt: 0 }),
268
+ ];
269
+ expect(describeUpdateCapsule(run(), machines, null, 60_000)).toEqual({
270
+ tone: "default",
271
+ label: "1 of 3 updated",
272
+ action: null,
273
+ });
274
+ expect(describeUpdateCapsule(run(), machines, null, UPDATE_SLOW_AFTER_MS + 6 * 60_000)).toEqual(
275
+ {
276
+ tone: "slow",
277
+ label: "alvin",
278
+ slow: { status: "restarting", elapsed: "9m" },
279
+ action: null,
280
+ },
281
+ );
282
+ });
283
+
284
+ it("offers a retry only for failed servers it can update again", () => {
285
+ expect(describeUpdateCapsule(run(), [view("alvin", "failed")], null, 0)).toEqual({
286
+ tone: "failed",
287
+ label: "alvin failed",
288
+ action: "retry",
289
+ });
290
+ expect(
291
+ describeUpdateCapsule(
292
+ run(),
293
+ [view("alvin", "failed", { server: null }), view("box", "failed", { server: null })],
294
+ null,
295
+ 0,
296
+ ),
297
+ ).toEqual({ tone: "failed", label: "2 failed", action: "dismiss" });
298
+ });
299
+
300
+ it("ends the run only when every machine is done and this app is not installing", () => {
301
+ const done = runMachine({ result: "done" });
302
+ expect(closeFinishedUpdateRun(run({ machines: [done] }))).toBeNull();
303
+ expect(
304
+ closeFinishedUpdateRun(run({ machines: [done], localVersion: "0.0.50" })),
305
+ ).not.toBeNull();
306
+ expect(
307
+ closeFinishedUpdateRun(run({ machines: [runMachine({ result: "failed" })] })),
308
+ ).not.toBeNull();
309
+ expect(closeFinishedUpdateRun(run({ machines: [done], phase: "providers" }))).not.toBeNull();
310
});
311
});
312
@@ -231,6 +332,7 @@ describe("update everything summary", () => {
332
localVersion: "0.0.50",
333
updatedServers: 2,
334
updatedProviders: 1,
335
+ restarting: [],
336
failures: [
337
"This app: Could not download update: Network error.",
338
"alvin: Download failed.",
@@ -256,12 +358,25 @@ describe("update everything summary", () => {
358
});
359
360
it("reports a failure when nothing updated, and nothing when nothing finished", () => {
259
- const empty = { localVersion: null, updatedServers: 0, updatedProviders: 0 };
361
+ const empty = { localVersion: null, updatedServers: 0, updatedProviders: 0, restarting: [] };
362
expect(
363
getUpdateEverythingToastView({ ...empty, failures: ["alvin: offline"] }, "0.0.50"),
364
).toEqual({ type: "error", title: "Update failed", description: "alvin: offline" });
365
expect(getUpdateEverythingToastView({ ...empty, failures: [] }, "0.0.50")).toBeNull();
366
});
367
+
368
+ it("names servers still restarting when this app relaunched", () => {
369
+ expect(
370
+ getUpdateEverythingToastView(
371
+ { ...result, failures: [], restarting: ["alvin", "zbook"] },
372
+ "0.0.50",
373
+ ),
374
+ ).toEqual({
375
+ type: "success",
376
+ title: "Updated this app, 2 servers, and 1 provider",
377
+ description: "alvin and zbook are still restarting.",
378
+ });
379
+ });
380
});
381
382
describe("describeUpdateEverything", () => {
apps/web/src/components/sidebar/updateEverything.logic.ts
+144
-25
@@ -186,17 +186,35 @@ export interface UpdateRunMachine {
186
readonly environmentId: EnvironmentId;
187
readonly label: string;
188
readonly updatesProviders: boolean;
189
- readonly updatesServer: boolean;
189
+ /** The server update this machine runs, kept so a failure can be retried.
190
+ Null for a provider-only machine, or a server this app handed off before
191
+ it relaunched. */
192
+ readonly server: ServerUpdateTarget | null;
193
+ /** The version a handed-off server comes back on. This app relaunched while
194
+ that server restarted, so its version is the only signal left. */
195
+ readonly handedOffVersion: string | null;
196
+ /** When its current update started, for the elapsed time. */
197
+ readonly startedAt: number;
198
/** Set when every update for this machine has finished. */
199
readonly result: "done" | "failed" | null;
200
+ /** Why it failed, when `result` is "failed". */
201
+ readonly failure: string | null;
202
+ /** This machine's provider failure, kept apart so a server retry does not clear it. */
203
+ readonly providerFailure: string | null;
204
}
205
194
-/** A running "update everything" pass, kept while it runs. */
206
+/**
207
+ * A running "update everything" pass, kept until every machine finished. A
208
+ * failed machine keeps it open, so the sidebar can offer a retry.
209
+ */
210
export interface UpdateEverythingRun {
196
- /** The version this app installs last, or null when it does not install. */
211
+ /** The version this app installs, or null when it does not install (or the
212
+ user chose to restart later). */
213
readonly localVersion: string | null;
198
- /** Providers update first. Servers update after every provider finished. */
199
- readonly phase: "providers" | "servers" | "installing";
214
+ /** Providers update first, then servers. "countdown" waits `restartAt` to
215
+ relaunch this app, which can still be postponed. */
216
+ readonly phase: "providers" | "servers" | "countdown" | "installing";
217
+ readonly restartAt: number | null;
218
readonly machines: ReadonlyArray<UpdateRunMachine>;
219
}
220
@@ -207,14 +225,117 @@ export function resolveUpdateRunMachineStatus(
225
serverState: ServerUpdateState,
226
): UpdateRunMachineStatus {
227
if (machine.result !== null) return machine.result;
228
+ if (machine.handedOffVersion !== null) return "restarting";
229
if (phase === "providers" && machine.updatesProviders) return "providers";
211
- if (machine.updatesServer && serverState.status === "running") {
230
+ if (machine.server !== null && serverState.status === "running") {
231
return serverState.stage === "resuming" ? "restarting" : "downloading";
232
}
233
return "waiting";
234
}
235
217
-const RUN_STATUS_LABELS: Record<UpdateRunMachineStatus, string> = {
236
+/** A server is handed off once it restarts into its update: it finishes
237
+ without this app, so this app can relaunch. */
238
+export function isServerUpdateHandedOff(state: ServerUpdateState): boolean {
239
+ return state.status === "running" && state.stage === "resuming";
240
+}
241
+
242
+/** Ends the run once nothing is left to show: every machine done and this
243
+ app not installing. Failures keep it open. */
244
+export function closeFinishedUpdateRun(run: UpdateEverythingRun): UpdateEverythingRun | null {
245
+ return run.phase === "servers" &&
246
+ run.localVersion === null &&
247
+ run.machines.every((machine) => machine.result === "done")
248
+ ? null
249
+ : run;
250
+}
251
+
252
+/** An update this long is slower than usual, so the sidebar points it out. */
253
+export const UPDATE_SLOW_AFTER_MS = 3 * 60 * 1000;
254
+
255
+/** Elapsed time in whole minutes, such as "6m" or "1h 4m". */
256
+export function formatUpdateElapsed(ms: number): string {
257
+ const minutes = Math.floor(ms / 60_000);
258
+ if (minutes < 1) return "<1m";
259
+ if (minutes < 60) return `${minutes}m`;
260
+ return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
261
+}
262
+
263
+export interface UpdateRunMachineView {
264
+ readonly machine: UpdateRunMachine;
265
+ readonly status: UpdateRunMachineStatus;
266
+}
267
+
268
+/** This app's own part of a run, for the sidebar. */
269
+export type UpdateRunLocalState =
270
+ | { readonly status: "downloading"; readonly percent: number | null }
271
+ | { readonly status: "waiting" }
272
+ | null;
273
+
274
+/** What the expanded sidebar update button says, and its inline action. */
275
+export interface UpdateCapsuleView {
276
+ readonly tone: "default" | "slow" | "failed";
277
+ readonly label: string;
278
+ /** For a slow machine, its status and elapsed time, such as "restarting" and "6m". */
279
+ readonly slow?: { readonly status: string; readonly elapsed: string };
280
+ readonly action: "later" | "retry" | "dismiss" | null;
281
+}
282
+
283
+const isActive = (status: UpdateRunMachineStatus) => status !== "done" && status !== "failed";
284
+
285
+/**
286
+ * The one line the expanded update button shows for a run, most urgent
287
+ * first: this app's restart countdown, a slow machine, overall progress, and
288
+ * last any failure once nothing else is running.
289
+ */
290
+export function describeUpdateCapsule(
291
+ run: UpdateEverythingRun,
292
+ machines: ReadonlyArray<UpdateRunMachineView>,
293
+ local: UpdateRunLocalState,
294
+ now: number,
295
+): UpdateCapsuleView {
296
+ if (run.phase === "countdown" && run.restartAt !== null) {
297
+ const seconds = Math.max(0, Math.ceil((run.restartAt - now) / 1000));
298
+ return { tone: "default", label: `Restart in ${seconds}s`, action: "later" };
299
+ }
300
+ if (run.phase === "installing") {
301
+ return { tone: "default", label: "Restarting…", action: null };
302
+ }
303
+ const active = machines.filter(({ status }) => isActive(status) && status !== "waiting");
304
+ const slowest = active.toSorted((a, b) => a.machine.startedAt - b.machine.startedAt)[0];
305
+ if (slowest && now - slowest.machine.startedAt >= UPDATE_SLOW_AFTER_MS) {
306
+ return {
307
+ tone: "slow",
308
+ label: slowest.machine.label,
309
+ slow: {
310
+ status: RUN_STATUS_LABELS[slowest.status],
311
+ elapsed: formatUpdateElapsed(now - slowest.machine.startedAt),
312
+ },
313
+ action: null,
314
+ };
315
+ }
316
+ const done = machines.filter(({ status }) => status === "done").length;
317
+ if (machines.some(({ status }) => isActive(status))) {
318
+ return { tone: "default", label: `${done} of ${machines.length} updated`, action: null };
319
+ }
320
+ if (local?.status === "downloading") {
321
+ return {
322
+ tone: "default",
323
+ label: `Downloading${local.percent === null ? "" : ` ${Math.floor(local.percent)}%`}`,
324
+ action: null,
325
+ };
326
+ }
327
+ const failed = machines.filter(({ status }) => status === "failed");
328
+ if (failed.length > 0) {
329
+ return {
330
+ tone: "failed",
331
+ label: failed.length === 1 ? `${failed[0]!.machine.label} failed` : `${failed.length} failed`,
332
+ action: failed.some(({ machine }) => machine.server !== null) ? "retry" : "dismiss",
333
+ };
334
+ }
335
+ return { tone: "default", label: `${done} of ${machines.length} updated`, action: null };
336
+}
337
+
338
+export const RUN_STATUS_LABELS: Record<UpdateRunMachineStatus, string> = {
339
providers: "updating providers",
340
waiting: "waiting",
341
downloading: "downloading",
@@ -223,22 +344,6 @@ const RUN_STATUS_LABELS: Record<UpdateRunMachineStatus, string> = {
344
failed: "failed",
345
};
346
226
-/**
227
- * Tooltip lines for a running pass, such as "alvin: restarting". `local` is
228
- * this app's own state, such as "downloading 40%", or null when it does not
229
- * install.
230
- */
231
-export function describeUpdateRun(
232
- machines: ReadonlyArray<{ readonly label: string; readonly status: UpdateRunMachineStatus }>,
233
- local: string | null,
234
-): ReadonlyArray<string> {
235
- return [
236
- "Updating…",
237
- ...(local === null ? [] : [`This app: ${local}`]),
238
- ...machines.map((machine) => `${machine.label}: ${RUN_STATUS_LABELS[machine.status]}`),
239
- ];
240
-}
241
-
347
/** What one pass did. It is saved before this app installs, so it outlives the relaunch. */
348
export interface UpdateEverythingResult {
349
/** The version this app installed last, or null when it did not install. */
@@ -247,6 +352,8 @@ export interface UpdateEverythingResult {
352
readonly updatedProviders: number;
353
/** One line per failure, each naming its machine. */
354
readonly failures: ReadonlyArray<string>;
355
+ /** Servers still restarting into their update when this app relaunched. */
356
+ readonly restarting: ReadonlyArray<string>;
357
}
358
359
/** Counts what a pass updated and lists each failure with its machine. */
@@ -267,6 +374,7 @@ export function collectUpdateEverythingResult(input: {
374
localVersion: input.localVersion,
375
updatedServers: input.servers.filter(({ outcome }) => outcome.status === "updated").length,
376
updatedProviders: input.providers.filter((outcome) => outcome.status === "updated").length,
377
+ restarting: [],
378
failures: [
379
...input.localFailures.map((failure) => `This app: ${failure}`),
380
...input.servers.flatMap(({ label, outcome }) =>
@@ -297,13 +405,24 @@ export function getUpdateEverythingToastView(
405
countLabel(result.updatedServers, "server"),
406
countLabel(result.updatedProviders, "provider"),
407
].filter((part) => part !== null);
408
+ const restarting =
409
+ result.restarting.length === 0
410
+ ? []
411
+ : [
412
+ `${joinList(result.restarting)} ${result.restarting.length === 1 ? "is" : "are"} still restarting.`,
413
+ ];
414
if (result.failures.length === 0) {
301
- return parts.length === 0 ? null : { type: "success", title: `Updated ${joinList(parts)}` };
415
+ if (parts.length === 0) return null;
416
+ return {
417
+ type: "success",
418
+ title: `Updated ${joinList(parts)}`,
419
+ ...(restarting.length === 0 ? {} : { description: restarting.join("\n") }),
420
+ };
421
}
422
return {
423
type: "error",
424
title: parts.length === 0 ? "Update failed" : `Updated ${joinList(parts)}`,
306
- description: result.failures.join("\n"),
425
+ description: [...result.failures, ...restarting].join("\n"),
426
};
427
}
428
apps/web/src/components/sidebar/updateEverythingRun.tsx
+249
-16
@@ -1,5 +1,5 @@
1
import { useAtomValue } from "@effect/atom-react";
2
-import type { EnvironmentId } from "@t3tools/contracts";
2
+import { EnvironmentId } from "@t3tools/contracts";
3
import * as Option from "effect/Option";
4
import * as Schema from "effect/Schema";
5
import { Atom } from "effect/reactivity";
@@ -8,11 +8,17 @@ import { useEffect } from "react";
8
import { APP_VERSION } from "~/branding";
9
import { appAtomRegistry } from "~/rpc/atomRegistry";
10
import { useDesktopUpdateState } from "~/state/desktopUpdate";
11
+import { serverEnvironment } from "~/state/server";
12
+import { resolveVersionMismatch } from "~/versionSkew";
13
+import type { ServerUpdateOutcome, ServerUpdateTarget } from "../ServerUpdateAction";
14
import { stackedThreadToast, toastManager } from "../ui/toast";
15
import {
16
+ closeFinishedUpdateRun,
17
getUpdateEverythingToastView,
18
+ isServerUpdateHandedOff,
19
type UpdateEverythingResult,
20
type UpdateEverythingRun,
21
+ type UpdateRunMachine,
22
} from "./updateEverything.logic";
23
24
/** The running "update everything" pass, or null. Outlives the sidebar button. */
@@ -32,24 +38,148 @@ export function setUpdateEverythingRun(
38
appAtomRegistry.update(updateEverythingRunAtom, update);
39
}
40
35
-/** Records the result of every update for one machine in the running pass. */
36
-export function settleUpdateRunMachine(environmentId: EnvironmentId, failed: boolean): void {
41
+function updateRunMachines(update: (machine: UpdateRunMachine) => UpdateRunMachine): void {
42
+ setUpdateEverythingRun(
43
+ (run) => run && closeFinishedUpdateRun({ ...run, machines: run.machines.map(update) }),
44
+ );
45
+}
46
+
47
+/** Records the result of every update for one machine. `failure` is null when
48
+ it succeeded. A server that updated is no longer retried, even when the
49
+ machine failed for its providers. The run ends once every machine is done. */
50
+export function settleUpdateRunMachine(
51
+ environmentId: EnvironmentId,
52
+ failure: string | null,
53
+ {
54
+ serverUpdated = false,
55
+ providerFailure,
56
+ }: { readonly serverUpdated?: boolean; readonly providerFailure?: string | null } = {},
57
+): void {
58
+ updateRunMachines((machine) =>
59
+ machine.environmentId === environmentId
60
+ ? {
61
+ ...machine,
62
+ result: failure === null ? "done" : "failed",
63
+ failure,
64
+ ...(serverUpdated ? { server: null } : {}),
65
+ ...(providerFailure === undefined ? {} : { providerFailure }),
66
+ }
67
+ : machine,
68
+ );
69
+}
70
+
71
+/** Retries each failed server update in the run. */
72
+export function retryFailedUpdateRunServers(
73
+ update: (
74
+ target: ServerUpdateTarget,
75
+ options: { readonly quiet: boolean },
76
+ ) => Promise<ServerUpdateOutcome>,
77
+): void {
78
+ const failed = (appAtomRegistry.get(updateEverythingRunAtom)?.machines ?? []).flatMap(
79
+ (machine) =>
80
+ machine.result === "failed" && machine.server !== null
81
+ ? [{ target: machine.server, providerFailure: machine.providerFailure }]
82
+ : [],
83
+ );
84
+ const targets = failed.map(({ target }) => target);
85
+ const retried = new Set(targets.map((target) => target.environmentId));
86
+ const startedAt = Date.now();
87
+ updateRunMachines((machine) =>
88
+ retried.has(machine.environmentId)
89
+ ? { ...machine, result: null, failure: null, startedAt }
90
+ : machine,
91
+ );
92
+ for (const { target, providerFailure } of failed) {
93
+ void update(target, { quiet: true }).then((outcome) =>
94
+ settleUpdateRunMachine(
95
+ target.environmentId,
96
+ // A skipped retry (no permission, disconnected, interrupted) did not update.
97
+ outcome.status === "updated"
98
+ ? providerFailure
99
+ : outcome.status === "failed"
100
+ ? outcome.message
101
+ : "Could not start the update",
102
+ { serverUpdated: outcome.status === "updated" },
103
+ ),
104
+ );
105
+ }
106
+}
107
+
108
+/** Drops the finished machines, which ends a run that only kept failures. */
109
+export function dismissSettledUpdateRunMachines(): void {
110
setUpdateEverythingRun(
111
(run) =>
39
- run && {
112
+ run &&
113
+ closeFinishedUpdateRun({
114
...run,
41
- machines: run.machines.map((machine) =>
42
- machine.environmentId === environmentId
43
- ? { ...machine, result: failed ? "failed" : "done" }
44
- : machine,
45
- ),
46
- },
115
+ machines: run.machines.filter((machine) => machine.result === null),
116
+ }),
117
);
118
}
119
120
+/** Resolves once a server restarts into its update, or its update `finished` first. */
121
+export function waitForServerUpdateHandoff(
122
+ environmentId: EnvironmentId,
123
+ finished: Promise<unknown>,
124
+): Promise<void> {
125
+ return new Promise((resolve) => {
126
+ let done = false;
127
+ const finish = () => {
128
+ if (done) return;
129
+ done = true;
130
+ queueMicrotask(() => unsubscribe());
131
+ resolve();
132
+ };
133
+ const unsubscribe = appAtomRegistry.subscribe(
134
+ serverEnvironment.updateStateAtom(environmentId),
135
+ (state) => {
136
+ if (isServerUpdateHandedOff(state)) finish();
137
+ },
138
+ { immediate: true },
139
+ );
140
+ void finished.then(finish, finish);
141
+ });
142
+}
143
+
144
+let decideRestart: ((restart: boolean) => void) | null = null;
145
+
146
+/**
147
+ * Counts down to this app's relaunch. Resolves true when the countdown ends,
148
+ * or false when the user chose to restart later with {@link postponeUpdateRestart}.
149
+ */
150
+export function waitForUpdateRestart(delayMs: number): Promise<boolean> {
151
+ return new Promise((resolve) => {
152
+ const decide = (restart: boolean) => {
153
+ clearTimeout(timer);
154
+ decideRestart = null;
155
+ resolve(restart);
156
+ };
157
+ const timer = setTimeout(() => decide(true), delayMs);
158
+ decideRestart = decide;
159
+ setUpdateEverythingRun(
160
+ (run) => run && { ...run, phase: "countdown", restartAt: Date.now() + delayMs },
161
+ );
162
+ });
163
+}
164
+
165
+/** Keeps this app on its version. Its downloaded update waits on the update button. */
166
+export function postponeUpdateRestart(): void {
167
+ decideRestart?.(false);
168
+}
169
+
170
const SAVED_RESULT_KEY = "t3code:update-everything-result:v1";
171
// A result older than this belongs to an install that never relaunched the app.
172
const SAVED_RESULT_MAX_AGE_MS = 10 * 60 * 1000;
173
+// Covers a background service's 30-minute trial start, like the server update itself.
174
+const HANDOFF_TIMEOUT_MS = 32 * 60 * 1000;
175
+
176
+const HandedOffServer = Schema.Struct({
177
+ environmentId: EnvironmentId,
178
+ label: Schema.String,
179
+ targetVersion: Schema.String,
180
+ startedAt: Schema.Number,
181
+});
182
+type HandedOffServer = typeof HandedOffServer.Type;
183
184
const SavedResult = Schema.Struct({
185
savedAt: Schema.Number,
@@ -57,15 +187,47 @@ const SavedResult = Schema.Struct({
187
updatedServers: Schema.Number,
188
updatedProviders: Schema.Number,
189
failures: Schema.Array(Schema.String),
190
+ // Older saved results have no handed-off servers.
191
+ handedOff: Schema.optional(Schema.Array(HandedOffServer)),
192
});
193
const decodeSavedResult = Schema.decodeUnknownOption(Schema.fromJsonString(SavedResult));
194
63
-/** Keeps a result through this app's relaunch. Call it right before the install. */
195
+/**
196
+ * Keeps a result through this app's relaunch. Call it right before the
197
+ * install. Servers still restarting are saved too, so the sidebar keeps
198
+ * following them after the relaunch.
199
+ */
200
export function saveUpdateEverythingResult(result: UpdateEverythingResult): void {
201
+ const run = appAtomRegistry.get(updateEverythingRunAtom);
202
+ const handedOff = (run?.machines ?? []).flatMap((machine): HandedOffServer[] => {
203
+ if (machine.result !== null) return [];
204
+ const state = appAtomRegistry.get(serverEnvironment.updateStateAtom(machine.environmentId));
205
+ // A desktop-managed server installs its own feed's version, which only its
206
+ // update state knows. A server followed from an earlier relaunch keeps its version.
207
+ const targetVersion =
208
+ machine.handedOffVersion ??
209
+ (state.status === "running" ? state.targetVersion : machine.server?.targetVersion);
210
+ if (targetVersion === undefined) return [];
211
+ return [
212
+ {
213
+ environmentId: machine.environmentId,
214
+ label: machine.label,
215
+ targetVersion,
216
+ startedAt: machine.startedAt,
217
+ },
218
+ ];
219
+ });
220
try {
221
window.localStorage.setItem(
222
SAVED_RESULT_KEY,
68
- JSON.stringify({ ...result, savedAt: Date.now() } satisfies typeof SavedResult.Type),
223
+ JSON.stringify({
224
+ savedAt: Date.now(),
225
+ localVersion: result.localVersion,
226
+ updatedServers: result.updatedServers,
227
+ updatedProviders: result.updatedProviders,
228
+ failures: result.failures,
229
+ handedOff,
230
+ } satisfies typeof SavedResult.Type),
231
);
232
} catch {
233
// Without storage the summary is lost with the relaunch; the update still runs.
@@ -80,7 +242,7 @@ export function clearSavedUpdateEverythingResult(): void {
242
}
243
}
244
83
-function takeSavedUpdateEverythingResult(): UpdateEverythingResult | null {
245
+function takeSavedUpdateEverythingResult(): typeof SavedResult.Type | null {
246
try {
247
const raw = window.localStorage.getItem(SAVED_RESULT_KEY);
248
if (raw === null) return null;
@@ -111,19 +273,90 @@ export function showUpdateEverythingResult(result: UpdateEverythingResult): void
273
);
274
}
275
276
+/**
277
+ * Follows servers that were restarting when this app relaunched. Each is done
278
+ * once it reports its target version, or failed after the handoff timeout.
279
+ * One toast reports them all at the end.
280
+ */
281
+function followHandedOffServers(servers: ReadonlyArray<HandedOffServer>): void {
282
+ // A server already past the timeout still shows, then fails on its first timer tick.
283
+ if (servers.length === 0) return;
284
+ setUpdateEverythingRun(() => ({
285
+ localVersion: null,
286
+ phase: "servers",
287
+ restartAt: null,
288
+ machines: servers.map((server) => ({
289
+ environmentId: server.environmentId,
290
+ label: server.label,
291
+ updatesProviders: false,
292
+ server: null,
293
+ handedOffVersion: server.targetVersion,
294
+ startedAt: server.startedAt,
295
+ result: null,
296
+ failure: null,
297
+ providerFailure: null,
298
+ })),
299
+ }));
300
+ let remaining = servers.length;
301
+ let updatedServers = 0;
302
+ const failures: string[] = [];
303
+ for (const server of servers) {
304
+ let settled = false;
305
+ const settle = (failure: string | null) => {
306
+ if (settled) return;
307
+ settled = true;
308
+ clearTimeout(timer);
309
+ queueMicrotask(() => unsubscribe());
310
+ settleUpdateRunMachine(server.environmentId, failure);
311
+ if (failure === null) updatedServers += 1;
312
+ else failures.push(`${server.label}: ${failure}`);
313
+ remaining -= 1;
314
+ if (remaining === 0) {
315
+ showUpdateEverythingResult({
316
+ localVersion: null,
317
+ updatedServers,
318
+ updatedProviders: 0,
319
+ failures,
320
+ restarting: [],
321
+ });
322
+ }
323
+ };
324
+ const timer = setTimeout(
325
+ () => settle(`Not back after ${HANDOFF_TIMEOUT_MS / 60_000} minutes`),
326
+ server.startedAt + HANDOFF_TIMEOUT_MS - Date.now(),
327
+ );
328
+ const unsubscribe = appAtomRegistry.subscribe(
329
+ serverEnvironment.configValueAtom(server.environmentId),
330
+ (config) => {
331
+ if (
332
+ config !== null &&
333
+ resolveVersionMismatch(config.environment.serverVersion, server.targetVersion) === null
334
+ ) {
335
+ settle(null);
336
+ }
337
+ },
338
+ { immediate: true },
339
+ );
340
+ }
341
+}
342
+
343
let notifiedNotAppliedVersion: string | null = null;
344
345
/**
346
* Desktop launch notices for updates: the summary of a pass that ended with
347
* this app's relaunch, and a warning when the last install did not apply.
119
- * Mount once at the app root.
348
+ * Servers still restarting from that pass stay in the sidebar until they are
349
+ * back. Mount once at the app root.
350
*/
351
export function DesktopUpdateLaunchNotice() {
352
const notAppliedVersion = useDesktopUpdateState()?.notAppliedVersion ?? null;
353
354
useEffect(() => {
125
- const result = takeSavedUpdateEverythingResult();
126
- if (result) showUpdateEverythingResult(result);
355
+ const saved = takeSavedUpdateEverythingResult();
356
+ if (!saved) return;
357
+ const handedOff = saved.handedOff ?? [];
358
+ showUpdateEverythingResult({ ...saved, restarting: handedOff.map((server) => server.label) });
359
+ followHandedOffServers(handedOff);
360
}, []);
361
362
useEffect(() => {
apps/web/src/components/sidebar/useUpdateEverything.ts
+93
-29
@@ -12,8 +12,9 @@ import { serverEnvironment } from "~/state/server";
12
import { environmentSession } from "~/state/session";
13
import { getProviderUpdateRunOutcome } from "../ProviderUpdateLaunchNotification.logic";
14
import { useProviderUpdates } from "../ProviderUpdatesAction";
15
-import { canUpdateServer, useServerUpdate } from "../ServerUpdateAction";
15
+import { canUpdateServer, type ServerUpdateOutcome, useServerUpdate } from "../ServerUpdateAction";
16
import {
17
+ closeFinishedUpdateRun,
18
collectRestartingMachines,
19
collectServerUpdateTargets,
20
collectUpdateEverythingResult,
@@ -28,8 +29,13 @@ import {
29
setUpdateEverythingRun,
30
settleUpdateRunMachine,
31
showUpdateEverythingResult,
32
+ waitForServerUpdateHandoff,
33
+ waitForUpdateRestart,
34
} from "./updateEverythingRun";
35
36
+/** How long this app counts down before it relaunches, so the user can postpone it. */
37
+const UPDATE_RESTART_DELAY_MS = 5_000;
38
+
39
/** Where this app's own download or install reports a failure. */
40
export type ReportLocalUpdateError = (title: string, description: string) => void;
41
@@ -40,7 +46,9 @@ export type ReportLocalUpdateError = (title: string, description: string) => voi
46
* only once npm confirms that version. `run` performs the whole pass, including
47
* this app's own download and install when given. It updates quietly, tracks
48
* each machine in the run state, and reports one summary toast at the end.
43
- * When this app installs, the summary waits for the relaunch.
49
+ * This app relaunches once every server restarts into its update, after a
50
+ * short countdown the user can postpone. The summary then waits for the
51
+ * relaunch, and servers still restarting are followed after it.
52
*/
53
export function useUpdateEverything(localUpdateVersion: string | null) {
54
const targetVersion = localUpdateVersion ?? APP_VERSION;
@@ -126,14 +134,19 @@ export function useUpdateEverything(localUpdateVersion: string | null) {
134
const reportLocalError: ReportLocalUpdateError = (title, description) => {
135
localFailures.push(`${title}: ${description}`);
136
};
137
+ const startedAt = Date.now();
138
const machinesById = new Map<UpdateRunMachine["environmentId"], UpdateRunMachine>();
139
for (const machine of providers.machines) {
140
machinesById.set(machine.environmentId, {
141
environmentId: machine.environmentId,
142
label: machine.label,
143
updatesProviders: true,
135
- updatesServer: false,
144
+ server: null,
145
+ handedOffVersion: null,
146
+ startedAt,
147
result: null,
148
+ failure: null,
149
+ providerFailure: null,
150
});
151
}
152
for (const server of servers) {
@@ -142,17 +155,23 @@ export function useUpdateEverything(localUpdateVersion: string | null) {
155
environmentId: server.environmentId,
156
label: server.serverLabel,
157
updatesProviders: existing?.updatesProviders ?? false,
145
- updatesServer: true,
158
+ server,
159
+ handedOffVersion: null,
160
+ startedAt,
161
result: null,
162
+ failure: null,
163
+ providerFailure: null,
164
});
165
}
166
const localVersion = installLocal ? localUpdateVersion : null;
167
setUpdateEverythingRun(() => ({
168
localVersion,
169
phase: "providers",
170
+ restartAt: null,
171
machines: Array.from(machinesById.values()),
172
}));
155
- const failedProviderMachines = new Set<UpdateRunMachine["environmentId"]>();
173
+ const providerFailures = new Map<UpdateRunMachine["environmentId"], string>();
174
+ const finishedServers: Array<{ label: string; outcome: ServerUpdateOutcome }> = [];
175
try {
176
const outcome = await runUpdateEverything({
177
...(downloadLocal ? { downloadLocal: () => downloadLocal(reportLocalError) } : {}),
@@ -161,49 +180,94 @@ export function useUpdateEverything(localUpdateVersion: string | null) {
180
const outcomes = runs.map((run) => {
181
const runOutcome = getProviderUpdateRunOutcome(run);
182
// An interrupted update did not finish either, so its row is not "done".
164
- if (runOutcome.status !== "updated") failedProviderMachines.add(run.environmentId);
183
+ if (runOutcome.status !== "updated") {
184
+ providerFailures.set(
185
+ run.environmentId,
186
+ runOutcome.status === "failed" ? runOutcome.line : "Provider update interrupted",
187
+ );
188
+ }
189
return runOutcome;
190
});
191
for (const machine of machinesById.values()) {
168
- if (!machine.updatesServer) {
192
+ if (machine.server === null) {
193
settleUpdateRunMachine(
194
machine.environmentId,
171
- failedProviderMachines.has(machine.environmentId),
195
+ providerFailures.get(machine.environmentId) ?? null,
196
);
197
}
198
}
175
- setUpdateEverythingRun((run) => run && { ...run, phase: "servers" });
199
+ const serversStartedAt = Date.now();
200
+ setUpdateEverythingRun(
201
+ (run) =>
202
+ run && {
203
+ ...run,
204
+ phase: "servers",
205
+ machines: run.machines.map((machine) =>
206
+ machine.server === null ? machine : { ...machine, startedAt: serversStartedAt },
207
+ ),
208
+ },
209
+ );
210
return outcomes;
211
},
178
- updateServers: () =>
179
- Promise.all(
180
- servers.map(async (server) => {
181
- const serverOutcome = await updateServer(server, { quiet: true });
182
- settleUpdateRunMachine(
183
- server.environmentId,
184
- serverOutcome.status === "failed" ||
185
- failedProviderMachines.has(server.environmentId),
186
- );
187
- return { label: server.serverLabel, outcome: serverOutcome };
188
- }),
189
- ),
212
+ updateServers: async () => {
213
+ const runs = servers.map(async (server) => {
214
+ const serverOutcome = await updateServer(server, { quiet: true });
215
+ settleUpdateRunMachine(
216
+ server.environmentId,
217
+ serverOutcome.status === "failed"
218
+ ? serverOutcome.message
219
+ : (providerFailures.get(server.environmentId) ?? null),
220
+ {
221
+ serverUpdated: serverOutcome.status !== "failed",
222
+ providerFailure: providerFailures.get(server.environmentId) ?? null,
223
+ },
224
+ );
225
+ const finished = { label: server.serverLabel, outcome: serverOutcome };
226
+ finishedServers.push(finished);
227
+ return finished;
228
+ });
229
+ // Once a server restarts into its update it finishes on its own,
230
+ // so this app does not wait for it to come back.
231
+ await Promise.all(
232
+ servers.map((server, index) =>
233
+ waitForServerUpdateHandoff(server.environmentId, runs[index]!),
234
+ ),
235
+ );
236
+ return runs;
237
+ },
238
});
191
- const result = () =>
239
+ const result = (finished: ReadonlyArray<{ label: string; outcome: ServerUpdateOutcome }>) =>
240
collectUpdateEverythingResult({
241
localVersion: null,
242
localFailures,
195
- servers: outcome.servers,
243
+ servers: finished,
244
providers: outcome.providers,
245
});
246
if (outcome.localReady && installLocal) {
199
- setUpdateEverythingRun((run) => run && { ...run, phase: "installing" });
200
- saveUpdateEverythingResult({ ...result(), localVersion });
201
- if (await installLocal(reportLocalError)) return;
202
- clearSavedUpdateEverythingResult();
247
+ if (await waitForUpdateRestart(UPDATE_RESTART_DELAY_MS)) {
248
+ setUpdateEverythingRun(
249
+ (run) => run && { ...run, phase: "installing", restartAt: null },
250
+ );
251
+ saveUpdateEverythingResult({ ...result(finishedServers), localVersion });
252
+ if (await installLocal(reportLocalError)) return;
253
+ clearSavedUpdateEverythingResult();
254
+ }
255
}
204
- showUpdateEverythingResult(result());
205
- } finally {
256
+ // This app is not relaunching, so the pass waits for every server.
257
+ setUpdateEverythingRun(
258
+ (run) =>
259
+ run &&
260
+ closeFinishedUpdateRun({
261
+ ...run,
262
+ phase: "servers",
263
+ restartAt: null,
264
+ localVersion: null,
265
+ }),
266
+ );
267
+ showUpdateEverythingResult(result(await Promise.all(outcome.servers)));
268
+ } catch (error) {
269
setUpdateEverythingRun(() => null);
270
+ throw error;
271
}
272
},
273
};
docs/user/updating.md
+9
-1
@@ -9,12 +9,20 @@ notice.
9
10
The update button at the bottom of the sidebar updates every connected machine
11
in one step. It updates outdated providers, then servers that are behind, then
12
-the desktop app you are using, which restarts last. Servers move to the
12
+the desktop app you are using. Servers move to the
13
version your desktop app is installing, or to your web app's version. A
14
background service stays on its current release channel. A remote desktop app
15
installs the latest release from its own channel. Hover the button to see what
16
it will update.
17
18
+While it runs, the button widens to show progress. It names a machine that is
19
+taking longer than usual, and offers **Retry** for a server that failed. Click
20
+it to see every machine. The desktop app restarts once each server has started
21
+its own restart, after a short countdown. Choose **Later** to keep working and
22
+restart from the update button when you are ready. A server still restarting
23
+finishes on its own, and the button keeps showing it after the desktop app
24
+restarts.
25
+
26
Server updates appear only after that version is published to npm. Remote
27
desktop apps do not wait for npm. The confirmation lists each machine it skips
28
and why, such as a machine that is offline or needs a manual update. Use the
packages/client-runtime/src/state/server.test.ts
+7
@@ -320,6 +320,13 @@ describe("server state projection", () => {
320
fromVersion: "0.0.30",
321
targetVersion: "0.0.31",
322
});
323
+ // A prepared desktop app update restarts only after the client commits it.
324
+ expect(
325
+ serverUpdateStateForProgressEvent("0.0.30", "0.0.31", {
326
+ type: "complete",
327
+ result: { targetVersion: "0.0.31", method: "desktop-app", desktopUpdateToken: "token" },
328
+ }).stage,
329
+ ).toBe("installing");
330
});
331
332
it("keeps active update state and hides stale failures after a version change", () => {
packages/client-runtime/src/state/server.ts
+17
-5
@@ -283,6 +283,11 @@ export const waitForDesktopUpdateTarget = Effect.fn("waitForDesktopUpdateTarget"
283
});
284
});
285
286
+/**
287
+ * "resuming" means the server has its update and restarts without this
288
+ * client. A desktop app update is not there yet when its prepare step
289
+ * completes: the client still has to commit it, so it stays "installing".
290
+ */
291
export function serverUpdateStateForProgressEvent(
292
fromVersion: string,
293
targetVersion: string,
@@ -290,7 +295,12 @@ export function serverUpdateStateForProgressEvent(
295
): Extract<ServerUpdateState, { status: "running" }> {
296
return {
297
status: "running",
293
- stage: event.type === "complete" ? "resuming" : event.stage,
298
+ stage:
299
+ event.type !== "complete"
300
+ ? event.stage
301
+ : event.result.method === "desktop-app" && event.result.desktopUpdateToken !== undefined
302
+ ? "installing"
303
+ : "resuming",
304
fromVersion,
305
targetVersion,
306
};
@@ -753,11 +763,13 @@ export function createServerEnvironmentAtoms<R, E>(
763
.pipe(
764
Stream.runForEach((event) =>
765
Effect.sync(() => {
756
- currentStage = event.type === "complete" ? "resuming" : event.stage;
757
- atomRegistry.set(
758
- stateAtom,
759
- serverUpdateStateForProgressEvent(fromVersion, targetVersion, event),
766
+ const state = serverUpdateStateForProgressEvent(
767
+ fromVersion,
768
+ targetVersion,
769
+ event,
770
);
771
+ currentStage = state.stage;
772
+ atomRegistry.set(stateAtom, state);
773
}).pipe(
774
Effect.andThen(
775
event.type === "complete"