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

main
ts 274 lines 9.58 KB
Raw
1 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import { expect, it } from "@effect/vitest";
4 import type { DesktopUpdateState, DesktopUpdateStatusReport } from "@t3tools/contracts";
5 import * as Deferred from "effect/Deferred";
6 import * as Effect from "effect/Effect";
7 import * as FileSystem from "effect/FileSystem";
8 import * as Fiber from "effect/Fiber";
9 import * as Layer from "effect/Layer";
10 import * as Option from "effect/Option";
11 import * as Stream from "effect/Stream";
12
13 import * as ServerConfig from "../config.ts";
14 import * as DesktopTelemetryReceiver from "../resourceTelemetry/DesktopTelemetryReceiver.ts";
15 import * as DesktopAppUpdate from "./DesktopAppUpdate.ts";
16
17 function makeState(overrides: Partial<DesktopUpdateState> = {}): DesktopUpdateState {
18 return {
19 enabled: true,
20 status: "idle",
21 channel: "latest",
22 currentVersion: "1.2.3",
23 hostArch: "arm64",
24 appArch: "arm64",
25 runningUnderArm64Translation: false,
26 availableVersion: null,
27 downloadedVersion: null,
28 releaseNotes: [],
29 downloadPercent: null,
30 checkedAt: null,
31 message: null,
32 errorContext: null,
33 canRetry: false,
34 omittedReleaseCount: 0,
35 ...overrides,
36 };
37 }
38
39 function report(
40 requestId: string,
41 state: DesktopUpdateState,
42 terminal?: {
43 readonly outcome: DesktopUpdateStatusReport["outcome"];
44 readonly reason?: string;
45 readonly preparedRequestId?: string;
46 },
47 ): DesktopUpdateStatusReport {
48 return {
49 version: 1,
50 type: "desktopUpdateStatus",
51 requestId,
52 ...(terminal?.outcome === undefined ? {} : { outcome: terminal.outcome }),
53 ...(terminal?.reason === undefined ? {} : { reason: terminal.reason }),
54 ...(terminal?.preparedRequestId === undefined
55 ? {}
56 : { preparedRequestId: terminal.preparedRequestId }),
57 state,
58 };
59 }
60
61 interface HarnessOptions {
62 readonly mode?: "web" | "desktop";
63 readonly controlFd?: number | undefined;
64 readonly reports?: (requestId: string) => readonly DesktopUpdateStatusReport[];
65 readonly keepOpen?: boolean;
66 }
67
68 const makeHarness = Effect.fn("test.make_desktop_app_update_harness")(function* (
69 options: HarnessOptions = {},
70 ) {
71 const fs = yield* FileSystem.FileSystem;
72 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-desktop-app-update-test-" });
73 const requestIdDeferred = yield* Deferred.make<string>();
74 const baseConfig = yield* ServerConfig.ServerConfig.pipe(
75 Effect.provide(ServerConfig.layerTest(process.cwd(), baseDir)),
76 );
77 const config: ServerConfig.ServerConfig["Service"] = {
78 ...baseConfig,
79 mode: options.mode ?? "desktop",
80 ...("controlFd" in options
81 ? { desktopTelemetryControlFd: options.controlFd }
82 : { desktopTelemetryControlFd: 5 }),
83 };
84 const reportsForRun = options.reports ?? (() => []);
85 const changes = Stream.unwrap(
86 Deferred.await(requestIdDeferred).pipe(
87 Effect.map((requestId) => {
88 const emitted = Stream.fromIterable(reportsForRun(requestId));
89 return options.keepOpen ? Stream.concat(emitted, Stream.never) : emitted;
90 }),
91 ),
92 );
93
94 const service = yield* DesktopAppUpdate.make().pipe(
95 Effect.provide(
96 Layer.mergeAll(
97 DesktopTelemetryReceiver.layerTest({
98 requestDesktopUpdate: (requestId) =>
99 Deferred.succeed(requestIdDeferred, requestId).pipe(Effect.asVoid),
100 desktopUpdates: Effect.succeed({
101 latest: Option.none<DesktopUpdateStatusReport>(),
102 changes,
103 }),
104 }),
105 ServerConfig.layer(config),
106 ),
107 ),
108 );
109 return { service };
110 });
111
112 it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("desktop app update", (it) => {
113 it.effect("collapses state reports into progress stages and succeeds on installing", () =>
114 Effect.gen(function* () {
115 const { service } = yield* makeHarness({
116 reports: (requestId) => [
117 report(requestId, makeState({ status: "checking" })),
118 report(requestId, makeState({ status: "available", availableVersion: "1.2.4" })),
119 report(requestId, makeState({ status: "downloading", downloadPercent: 40 })),
120 report("other-run", makeState({ status: "error", message: "unrelated" })),
121 report(requestId, makeState({ status: "downloaded", downloadedVersion: "1.2.4" }), {
122 outcome: "ready-to-install",
123 }),
124 ],
125 });
126 const stages: string[] = [];
127 const result = yield* service.run((stage) => Effect.sync(() => void stages.push(stage)));
128 expect(result).toEqual({
129 targetVersion: "1.2.4",
130 method: "desktop-app",
131 desktopUpdateToken: expect.any(String),
132 });
133 expect(stages).toEqual(["downloading", "installing"]);
134
135 const retry = yield* service.run(() => Effect.void).pipe(Effect.flip);
136 expect(retry.reason).not.toBe("A desktop app update is already in progress.");
137 }),
138 );
139
140 it.effect("commits the original preparation when a retry joins its downloaded update", () =>
141 Effect.gen(function* () {
142 const { service } = yield* makeHarness({
143 reports: (requestId) => [
144 report(requestId, makeState({ status: "downloaded", downloadedVersion: "1.2.4" }), {
145 outcome: "ready-to-install",
146 preparedRequestId: "original-preparation",
147 }),
148 report("original-preparation", makeState({ status: "downloaded" }), {
149 outcome: "failed",
150 reason: "installer refused",
151 }),
152 ],
153 });
154 const prepared = yield* service.run(() => Effect.void);
155 expect(prepared.desktopUpdateToken).toBe("original-preparation");
156 expect(
157 (yield* service.commit(prepared.desktopUpdateToken ?? "missing").pipe(Effect.flip)).reason,
158 ).toBe("installer refused");
159 }),
160 );
161
162 it.effect("succeeds without an install when a track switch finds the host current", () =>
163 Effect.gen(function* () {
164 const { service } = yield* makeHarness({
165 reports: (requestId) => [
166 report(requestId, makeState({ status: "up-to-date", currentVersion: "1.2.3" }), {
167 outcome: "up-to-date",
168 }),
169 ],
170 });
171 const trackSwitch = { channel: "latest" as const, targetVersion: "1.2.3" };
172
173 expect(yield* service.run(() => Effect.void, trackSwitch)).toEqual({
174 targetVersion: "1.2.3",
175 method: "desktop-app",
176 });
177 }),
178 );
179
180 it.effect("replays a retained commit failure for the preparation token", () =>
181 Effect.gen(function* () {
182 const { service } = yield* makeHarness({
183 reports: (requestId) => [
184 report(requestId, makeState({ status: "downloaded", downloadedVersion: "1.2.4" }), {
185 outcome: "ready-to-install",
186 }),
187 report(
188 requestId,
189 makeState({
190 status: "downloaded",
191 downloadedVersion: "1.2.4",
192 errorContext: "install",
193 message: "installer refused",
194 }),
195 { outcome: "failed", reason: "installer refused" },
196 ),
197 ],
198 });
199 const prepared = yield* service.run(() => Effect.void);
200
201 expect(
202 (yield* service.commit(prepared.desktopUpdateToken ?? "missing").pipe(Effect.flip)).reason,
203 ).toBe("installer refused");
204 }),
205 );
206
207 it.effect.each([true, false])(
208 "carries the track mismatch only for its own failure (%s)",
209 (matchingReason) =>
210 Effect.gen(function* () {
211 const mismatch = "This Stable build can't update from the Nightly track on its own.";
212 const reason = matchingReason ? mismatch : "The desktop update was cancelled.";
213 const { service } = yield* makeHarness({
214 reports: (requestId) => [
215 report(
216 requestId,
217 makeState({
218 status: "error",
219 channel: "nightly",
220 message: mismatch,
221 errorContext: "check",
222 trackMismatch: { buildChannel: "latest" },
223 }),
224 { outcome: "failed", reason },
225 ),
226 ],
227 });
228 const error = yield* service.run(() => Effect.void).pipe(Effect.flip);
229 expect(error.reason).toBe(reason);
230 expect(error.trackMismatch).toEqual(
231 matchingReason ? { buildChannel: "latest", savedChannel: "nightly" } : undefined,
232 );
233 }),
234 );
235
236 it.effect("fails when the desktop stops reporting before a terminal outcome", () =>
237 Effect.gen(function* () {
238 const { service } = yield* makeHarness({
239 reports: (requestId) => [report(requestId, makeState({ status: "checking" }))],
240 });
241 expect((yield* service.run(() => Effect.void).pipe(Effect.flip)).reason).toBe(
242 "The desktop app stopped reporting its update.",
243 );
244 }),
245 );
246
247 it.effect("allows only one desktop update at a time", () =>
248 Effect.gen(function* () {
249 const { service } = yield* makeHarness({ reports: () => [], keepOpen: true });
250 const first = yield* Effect.forkChild(
251 service.run(() => Effect.void),
252 {
253 startImmediately: true,
254 },
255 );
256 expect((yield* service.run(() => Effect.void).pipe(Effect.flip)).reason).toBe(
257 "A desktop app update is already in progress.",
258 );
259 yield* Fiber.interrupt(first);
260
261 const retry = yield* Effect.forkChild(
262 service.run(() => Effect.void),
263 {
264 startImmediately: true,
265 },
266 );
267 yield* Effect.yieldNow;
268 expect((yield* service.run(() => Effect.void).pipe(Effect.flip)).reason).toBe(
269 "A desktop app update is already in progress.",
270 );
271 yield* Fiber.interrupt(retry);
272 }),
273 );
274 });