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

main
ts 162 lines 5.65 KB
Raw
1 import { AVAILABLE_CONNECTION_STATE } from "@t3tools/client-runtime/connection";
2 import { EnvironmentId, type ServerConfig } from "@t3tools/contracts";
3 import * as Effect from "effect/Effect";
4 import { AsyncResult, Atom } from "effect/reactivity";
5 import { afterEach, describe, expect, it, vi } from "vite-plus/test";
6
7 import { environmentCatalog } from "~/connection/catalog";
8 import { appAtomRegistry } from "~/rpc/atomRegistry";
9 import { serverEnvironment } from "~/state/server";
10 import type { ServerUpdateOutcome, ServerUpdateTarget } from "../ServerUpdateAction";
11 import type { UpdateEverythingRun } from "./updateEverything.logic";
12 import {
13 retryFailedUpdateRunServers,
14 setUpdateEverythingRun,
15 startDesktopUpdateLaunchNotice,
16 } from "./updateEverythingRun";
17
18 function relaunchWhileRestarting(environmentId: EnvironmentId) {
19 const now = 1_800_000_000_000;
20 vi.useFakeTimers({ now });
21 const store = new Map([
22 [
23 "t3code:update-everything-result:v1",
24 JSON.stringify({
25 savedAt: now,
26 localVersion: null,
27 updatedServers: 0,
28 updatedProviders: 0,
29 failures: [],
30 handedOff: [{ environmentId, label: "Slow", targetVersion: "9.9.9", startedAt: now }],
31 }),
32 ],
33 ]);
34 vi.stubGlobal("window", {
35 localStorage: {
36 getItem: (key: string) => store.get(key) ?? null,
37 removeItem: (key: string) => store.delete(key),
38 },
39 });
40 return startDesktopUpdateLaunchNotice();
41 }
42
43 describe("startDesktopUpdateLaunchNotice", () => {
44 afterEach(() => {
45 vi.useRealTimers();
46 vi.unstubAllGlobals();
47 });
48
49 it("keeps a server that is still restarting from looking idle after the app relaunches", async () => {
50 const environmentId = EnvironmentId.make("slow-machine");
51 const stop = relaunchWhileRestarting(environmentId);
52 try {
53 // Lets the registry run its cleanup of unobserved atoms before the UI mounts.
54 await vi.advanceTimersByTimeAsync(1_000);
55 expect(appAtomRegistry.get(serverEnvironment.updateStateAtom(environmentId))).toMatchObject({
56 status: "running",
57 stage: "resuming",
58 targetVersion: "9.9.9",
59 });
60 } finally {
61 await vi.advanceTimersByTimeAsync(32 * 60 * 1000);
62 stop();
63 }
64 });
65
66 it("retries the connection to a restarting server instead of waiting out its backoff", async () => {
67 const environmentId = EnvironmentId.make("backing-off-machine");
68 using _connection = vi
69 .spyOn(environmentCatalog, "stateAtom")
70 .mockReturnValue(
71 Atom.make(
72 AsyncResult.success({ ...AVAILABLE_CONNECTION_STATE, phase: "backoff" as const }),
73 ) as unknown as ReturnType<typeof environmentCatalog.stateAtom>,
74 );
75 using retryNow = vi.spyOn(environmentCatalog.retryNow, "run").mockReturnValue(Effect.void);
76 const stop = relaunchWhileRestarting(environmentId);
77 try {
78 await vi.advanceTimersByTimeAsync(1_000);
79 expect(retryNow).toHaveBeenCalledWith(appAtomRegistry, environmentId);
80 } finally {
81 await vi.advanceTimersByTimeAsync(32 * 60 * 1000);
82 stop();
83 }
84 });
85
86 it("clears the restored state when the server never comes back", async () => {
87 const environmentId = EnvironmentId.make("lost-machine");
88 const stateAtom = serverEnvironment.updateStateAtom(environmentId);
89 const stop = relaunchWhileRestarting(environmentId);
90 // Observed like the UI does, so the registry cannot reset it by dropping the atom.
91 const release = appAtomRegistry.mount(stateAtom);
92 try {
93 await vi.advanceTimersByTimeAsync(32 * 60 * 1000);
94 expect(appAtomRegistry.get(stateAtom)).toEqual({ status: "idle" });
95 } finally {
96 release();
97 stop();
98 }
99 });
100 });
101
102 describe("retryFailedUpdateRunServers", () => {
103 it("settles a failed server that already restarted on the target and retries only the others", () => {
104 const targetVersion = "9.9.9";
105 const serverVersions = new Map([
106 [EnvironmentId.make("already-updated"), targetVersion],
107 [EnvironmentId.make("behind"), "9.9.8"],
108 ]);
109 using _config = vi
110 .spyOn(serverEnvironment, "configValueAtom")
111 .mockImplementation((environmentId) =>
112 Atom.make({
113 environment: { serverVersion: serverVersions.get(environmentId!) },
114 } as unknown as ServerConfig),
115 );
116 const rejection = "Remote updates must select a newer server version.";
117 const failedMachine = (environmentId: EnvironmentId) => ({
118 environmentId,
119 label: environmentId,
120 updatesProviders: false,
121 server: {
122 environmentId,
123 serverLabel: environmentId,
124 selfUpdate: "boot-service" as const,
125 targetVersion,
126 },
127 handedOffVersion: null,
128 startedAt: 0,
129 result: "failed" as const,
130 failure: rejection,
131 providerFailure: null,
132 });
133 setUpdateEverythingRun(() => ({
134 localVersion: null,
135 phase: "servers",
136 restartAt: null,
137 machines: [...serverVersions.keys()].map(failedMachine),
138 }));
139 const update = vi.fn(
140 (_target: ServerUpdateTarget) => new Promise<ServerUpdateOutcome>(() => {}),
141 );
142
143 retryFailedUpdateRunServers(update);
144
145 let run: UpdateEverythingRun | null = null;
146 setUpdateEverythingRun((current) => {
147 run = current;
148 return null;
149 });
150 expect(update.mock.calls.map(([target]) => target.environmentId)).toEqual(["behind"]);
151 expect(
152 (run as UpdateEverythingRun | null)?.machines.map(({ environmentId, result, server }) => ({
153 environmentId,
154 result,
155 retryable: server !== null,
156 })),
157 ).toEqual([
158 { environmentId: "already-updated", result: "done", retryable: false },
159 { environmentId: "behind", result: null, retryable: true },
160 ]);
161 });
162 });