Open History to see the last commit
1import { EnvironmentId, type ServerSelfUpdateCapability } from "@t3tools/contracts";
2import { describe, expect, it } from "vite-plus/test";
3
4import {
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
21const 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
39function machine(
40 id: string,
41 serverVersion: string,
42 selfUpdate: ServerSelfUpdateCapability | undefined,
43 overrides: Partial<UpdateEverythingMachine> = {},
44): UpdateEverythingMachine {
45 return {
46 environmentId: EnvironmentId.make(id),
47 label: id,
48 serverConfig: {
49 environment: {
50 environmentId: EnvironmentId.make(id),
51 label: id,
52 platform: { os: "linux", arch: "x64" },
53 serverVersion,
54 capabilities: {
55 repositoryIdentity: true,
56 ...(selfUpdate ? { serverSelfUpdate: selfUpdate } : {}),
57 ...(selfUpdate === "desktop-managed" ? { desktopAppUpdate: true } : {}),
58 },
59 },
60 settings: { continueThreadsAfterServerUpdate: false },
61 },
62 connected: true,
63 hostedByThisApp: false,
64 canMaintain: true,
65 updateState: { status: "idle" },
66 ...overrides,
67 };
68}
69
70describe("collectServerUpdateTargets", () => {
71 it("updates remote servers that can move to the target and names every skipped one", () => {
72 const { targets, skipped } = collectServerUpdateTargets(
73 [
74 machine("this-app", "0.0.40", "desktop-managed", { hostedByThisApp: true }),
75 machine("service", "0.0.40", "boot-service"),
76 machine("nightly-service", "0.0.49-nightly.20261001.3", "boot-service"),
77 machine("other-desktop", "0.0.49-nightly.20261001.3", "desktop-managed"),
78 machine("offline", "0.0.40", "boot-service", { connected: false }),
79 machine("never-connected", "0.0.40", "boot-service", { serverConfig: null }),
80 machine("no-scope", "0.0.40", "boot-service", { canMaintain: false }),
81 machine("busy", "0.0.40", "boot-service", {
82 updateState: {
83 status: "running",
84 stage: "downloading",
85 fromVersion: "0.0.40",
86 targetVersion: "0.0.50",
87 },
88 }),
89 machine("current", "0.0.50", "boot-service"),
90 machine("current-offline", "0.0.50", "boot-service", { connected: false }),
91 machine("manual", "0.0.40", undefined),
92 ],
93 "0.0.50",
94 );
95
96 expect(targets.map((target) => [target.serverLabel, target.targetVersion])).toEqual([
97 ["service", "0.0.50"],
98 ["other-desktop", "0.0.50"],
99 ]);
100 expect(skipped.map((entry) => [entry.label, entry.reason])).toEqual([
101 ["nightly-service", "on the nightly channel"],
102 ["offline", "not connected"],
103 ["never-connected", "not connected"],
104 ["no-scope", "no permission"],
105 ["busy", "already updating"],
106 ["manual", "needs a manual update"],
107 ]);
108 });
109});
110
111describe("collectRestartingMachines", () => {
112 it("lists updated servers, and this app's servers only when it installs", () => {
113 const withContinuation = (
114 id: string,
115 overrides: Partial<UpdateEverythingMachine> = {},
116 enabled = false,
117 ) => {
118 const base = machine(id, "0.0.40", "boot-service", overrides);
119 return {
120 ...base,
121 serverConfig: {
122 environment: {
123 ...base.serverConfig!.environment,
124 capabilities: {
125 ...base.serverConfig!.environment.capabilities,
126 threadRestartContinuation: true,
127 },
128 },
129 settings: { continueThreadsAfterServerUpdate: enabled },
130 },
131 };
132 };
133 const machines = [
134 withContinuation("this-app", { hostedByThisApp: true }, true),
135 withContinuation("alvin", {}, true),
136 withContinuation("opted-out", {}, false),
137 machine("old", "0.0.40", "boot-service"),
138 withContinuation("providers-only"),
139 ];
140 const servers = ["alvin", "opted-out", "old"].map((id) => ({
141 environmentId: EnvironmentId.make(id),
142 }));
143
144 expect(collectRestartingMachines(machines, servers, true)).toEqual([
145 { environmentId: "this-app", continuesThreads: true },
146 { environmentId: "alvin", continuesThreads: true },
147 { environmentId: "opted-out", continuesThreads: false },
148 { environmentId: "old", continuesThreads: false },
149 ]);
150 expect(
151 collectRestartingMachines(machines, servers, false).map((entry) => entry.environmentId),
152 ).toEqual(["alvin", "opted-out", "old"]);
153 });
154});
155
156describe("runUpdateEverything", () => {
157 it("restarts servers after providers finish and returns every result", async () => {
158 const calls: string[] = [];
159 let finishProviders = (_value: string) => {};
160 const run = runUpdateEverything({
161 downloadLocal: async () => {
162 calls.push("download");
163 return true;
164 },
165 updateProviders: () =>
166 new Promise<string>((resolve) => {
167 calls.push("providers");
168 finishProviders = resolve;
169 }),
170 updateServers: async () => {
171 calls.push("servers");
172 return 2;
173 },
174 });
175
176 await new Promise((resolve) => setTimeout(resolve, 0));
177 expect(calls).toEqual(["download", "providers"]);
178 finishProviders("provider results");
179 expect(await run).toEqual({ localReady: true, providers: "provider results", servers: 2 });
180 expect(calls).toEqual(["download", "providers", "servers"]);
181 });
182
183 it("still updates remote machines when the local download fails", async () => {
184 const calls: string[] = [];
185 const result = await runUpdateEverything({
186 downloadLocal: async () => false,
187 updateProviders: async () => {
188 calls.push("providers");
189 },
190 updateServers: async () => {
191 calls.push("servers");
192 },
193 });
194
195 expect(calls).toEqual(["providers", "servers"]);
196 expect(result.localReady).toBe(false);
197 });
198});
199
200describe("resolveUpdateRunMachineStatus", () => {
201 const running = (stage: "downloading" | "installing" | "resuming") =>
202 ({ status: "running", stage, fromVersion: "0.0.40", targetVersion: "0.0.50" }) as const;
203
204 it("follows the run phase, then the server's own update stage", () => {
205 const idle = { status: "idle" } as const;
206 expect(resolveUpdateRunMachineStatus(runMachine(), "providers", idle)).toBe("providers");
207 expect(resolveUpdateRunMachineStatus(runMachine(), "servers", idle)).toBe("waiting");
208 expect(resolveUpdateRunMachineStatus(runMachine(), "servers", running("installing"))).toBe(
209 "downloading",
210 );
211 expect(resolveUpdateRunMachineStatus(runMachine(), "servers", running("resuming"))).toBe(
212 "restarting",
213 );
214 expect(
215 resolveUpdateRunMachineStatus(
216 runMachine({ updatesProviders: false }),
217 "providers",
218 running("downloading"),
219 ),
220 ).toBe("downloading");
221 expect(resolveUpdateRunMachineStatus(runMachine({ result: "failed" }), "servers", idle)).toBe(
222 "failed",
223 );
224 expect(
225 resolveUpdateRunMachineStatus(
226 runMachine({ server: null, handedOffVersion: "0.0.50" }),
227 "servers",
228 idle,
229 ),
230 ).toBe("restarting");
231 });
232});
233
234describe("update capsule", () => {
235 const run = (overrides: Partial<UpdateEverythingRun> = {}): UpdateEverythingRun => ({
236 localVersion: null,
237 phase: "servers",
238 restartAt: null,
239 machines: [],
240 ...overrides,
241 });
242 const view = (
243 label: string,
244 status: UpdateRunMachineStatus,
245 overrides: Partial<UpdateRunMachine> = {},
246 ) => ({
247 machine: runMachine({ environmentId: EnvironmentId.make(label), label, ...overrides }),
248 status,
249 });
250
251 it("counts down this app's restart before anything else", () => {
252 expect(
253 describeUpdateCapsule(
254 run({ phase: "countdown", restartAt: 5_000, localVersion: "0.0.50" }),
255 [view("alvin", "restarting")],
256 { status: "waiting" },
257 1_200,
258 ),
259 ).toEqual({ tone: "default", label: "Restart in 4s", action: "later" });
260 });
261
262 it("names the slowest machine once it passes the slow threshold", () => {
263 const machines = [
264 view("bb-1", "done"),
265 view("zbook", "downloading", { startedAt: 60_000 }),
266 view("alvin", "restarting", { startedAt: 0 }),
267 ];
268 expect(describeUpdateCapsule(run(), machines, null, 60_000)).toEqual({
269 tone: "default",
270 label: "1 of 3 updated",
271 action: null,
272 });
273 expect(describeUpdateCapsule(run(), machines, null, UPDATE_SLOW_AFTER_MS + 6 * 60_000)).toEqual(
274 {
275 tone: "slow",
276 label: "alvin",
277 slow: { status: "restarting", elapsed: "9m" },
278 action: null,
279 },
280 );
281 });
282
283 it("offers a retry only for failed servers it can update again", () => {
284 expect(describeUpdateCapsule(run(), [view("alvin", "failed")], null, 0)).toEqual({
285 tone: "failed",
286 label: "alvin failed",
287 action: "retry",
288 });
289 expect(
290 describeUpdateCapsule(
291 run(),
292 [view("alvin", "failed", { server: null }), view("box", "failed", { server: null })],
293 null,
294 0,
295 ),
296 ).toEqual({ tone: "failed", label: "2 failed", action: "dismiss" });
297 });
298
299 it("ends the run only when every machine is done and this app is not installing", () => {
300 const done = runMachine({ result: "done" });
301 expect(closeFinishedUpdateRun(run({ machines: [done] }))).toBeNull();
302 expect(
303 closeFinishedUpdateRun(run({ machines: [done], localVersion: "0.0.50" })),
304 ).not.toBeNull();
305 expect(
306 closeFinishedUpdateRun(run({ machines: [runMachine({ result: "failed" })] })),
307 ).not.toBeNull();
308 expect(closeFinishedUpdateRun(run({ machines: [done], phase: "providers" }))).not.toBeNull();
309 });
310});
311
312describe("update everything summary", () => {
313 const result = collectUpdateEverythingResult({
314 localVersion: "0.0.50",
315 localFailures: ["Could not download update: Network error."],
316 servers: [
317 { label: "alvin", outcome: { status: "failed", message: "Download failed." } },
318 { label: "box", outcome: { status: "updated" } },
319 { label: "studio", outcome: { status: "updated" } },
320 { label: "busy", outcome: { status: "skipped" } },
321 ],
322 providers: [
323 { status: "updated" },
324 { status: "interrupted" },
325 { status: "failed", line: "box · Codex: npm exited with code 1." },
326 ],
327 });
328
329 it("counts updates and names the machine of each failure", () => {
330 expect(result).toEqual({
331 localVersion: "0.0.50",
332 updatedServers: 2,
333 updatedProviders: 1,
334 restarting: [],
335 failures: [
336 "This app: Could not download update: Network error.",
337 "alvin: Download failed.",
338 "box · Codex: npm exited with code 1.",
339 ],
340 });
341 });
342
343 it("includes this app only when the relaunch landed on its version", () => {
344 expect(getUpdateEverythingToastView(result, "0.0.50")).toEqual({
345 type: "error",
346 title: "Updated this app, 2 servers, and 1 provider",
347 description: [
348 "This app: Could not download update: Network error.",
349 "alvin: Download failed.",
350 "box · Codex: npm exited with code 1.",
351 ].join("\n"),
352 });
353 expect(getUpdateEverythingToastView({ ...result, failures: [] }, "0.0.40")).toEqual({
354 type: "success",
355 title: "Updated 2 servers and 1 provider",
356 });
357 });
358
359 it("reports a failure when nothing updated, and nothing when nothing finished", () => {
360 const empty = { localVersion: null, updatedServers: 0, updatedProviders: 0, restarting: [] };
361 expect(
362 getUpdateEverythingToastView({ ...empty, failures: ["alvin: offline"] }, "0.0.50"),
363 ).toEqual({ type: "error", title: "Update failed", description: "alvin: offline" });
364 expect(getUpdateEverythingToastView({ ...empty, failures: [] }, "0.0.50")).toBeNull();
365 });
366
367 it("names servers still restarting when this app relaunched", () => {
368 expect(
369 getUpdateEverythingToastView(
370 { ...result, failures: [], restarting: ["alvin", "zbook"] },
371 "0.0.50",
372 ),
373 ).toEqual({
374 type: "success",
375 title: "Updated this app, 2 servers, and 1 provider",
376 description: "alvin and zbook are still restarting.",
377 });
378 });
379});
380
381describe("describeUpdateEverything", () => {
382 it("summarizes the run and lists each machine once", () => {
383 const alvin = EnvironmentId.make("alvin");
384 expect(
385 describeUpdateEverything({
386 localVersion: "0.0.50",
387 servers: [
388 {
389 environmentId: alvin,
390 serverLabel: "alvin",
391 selfUpdate: "boot-service",
392 targetVersion: "0.0.50",
393 },
394 {
395 environmentId: EnvironmentId.make("studio"),
396 serverLabel: "studio",
397 selfUpdate: "desktop-managed",
398 targetVersion: "0.0.50",
399 },
400 ],
401 providerMachines: [
402 { environmentId: alvin, label: "alvin", providers: ["Codex", "Claude"] },
403 { environmentId: EnvironmentId.make("box"), label: "box", providers: ["Cursor"] },
404 ],
405 }),
406 ).toEqual({
407 summary: "Update this app, 2 servers, and 3 providers",
408 lines: [
409 "This app: 0.0.50, restarts last",
410 "alvin: server to 0.0.50, Codex, Claude",
411 "studio: desktop app update",
412 "box: Cursor",
413 ],
414 });
415 });
416
417 it("reads naturally with one kind of update", () => {
418 expect(
419 describeUpdateEverything({
420 localVersion: null,
421 servers: [],
422 providerMachines: [
423 { environmentId: EnvironmentId.make("alvin"), label: "alvin", providers: ["Codex"] },
424 ],
425 }).summary,
426 ).toBe("Update 1 provider");
427 });
428});