Open History to see the last commit
1import {
2 type DesktopBridge,
3 EnvironmentId,
4 type RelayClientInstallProgressEvent,
5 WS_METHODS,
6} from "@t3tools/contracts";
7import { RelayWebClientId } from "@t3tools/contracts/relay";
8import { describe, expect, it } from "@effect/vitest";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as Stream from "effect/Stream";
13import * as SubscriptionRef from "effect/SubscriptionRef";
14import { HttpClient } from "effect/unstable/http";
15import { afterEach, beforeEach, vi } from "vite-plus/test";
16import {
17 AVAILABLE_CONNECTION_STATE,
18 EnvironmentSupervisor,
19 type PreparedConnection,
20 PrimaryConnectionTarget,
21} from "@t3tools/client-runtime/connection";
22import { type RpcSession } from "@t3tools/client-runtime/rpc";
23import { EnvironmentRegistry } from "@t3tools/client-runtime/connection";
24import { ManagedRelay } from "@t3tools/client-runtime/relay";
25import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";
26import { __resetDesktopPrimaryAuthForTests } from "../environments/primary/desktopAuth";
27
28import {
29 collectCloudLinkTargets,
30 linkPrimaryEnvironmentToCloud,
31 listManagedCloudEnvironments,
32 normalizeRelayBaseUrl,
33 readPrimaryCloudLinkState,
34 type CloudLinkTarget,
35 unlinkPrimaryEnvironmentFromCloud,
36 updatePrimaryCloudPreferences,
37} from "./linkEnvironment";
38
39const TARGET: CloudLinkTarget = {
40 environmentId: "environment-1",
41 label: "Desktop",
42 httpBaseUrl: "http://127.0.0.1:3000",
43 wsBaseUrl: "ws://127.0.0.1:3000",
44};
45
46const relayClientInstallDialog = vi.hoisted(() => ({
47 requestConfirmation: vi.fn(),
48 reportProgress: vi.fn(),
49 finish: vi.fn(),
50}));
51
52vi.mock("./relayClientInstallDialog", () => ({
53 requestRelayClientInstallConfirmation: relayClientInstallDialog.requestConfirmation,
54 reportRelayClientInstallProgress: relayClientInstallDialog.reportProgress,
55 finishRelayClientInstall: relayClientInstallDialog.finish,
56}));
57
58const createProof = vi.fn(() => Effect.succeed("dpop-proof"));
59const dpopSignerLayer = Layer.succeed(
60 ManagedRelay.ManagedRelayDpopSigner,
61 ManagedRelay.ManagedRelayDpopSigner.of({
62 thumbprint: Effect.succeed("thumbprint"),
63 createProof,
64 }),
65);
66
67function relayLayer() {
68 const http = remoteHttpClientLayer(globalThis.fetch);
69 return Layer.mergeAll(
70 http,
71 ManagedRelay.layer({
72 relayUrl: "https://relay.example.test",
73 clientId: RelayWebClientId,
74 }).pipe(Layer.provideMerge(dpopSignerLayer), Layer.provide(http)),
75 );
76}
77
78function registryLayer(options?: {
79 readonly status?: { readonly status: "available"; readonly version: string };
80 readonly installEvents?: ReadonlyArray<RelayClientInstallProgressEvent>;
81}) {
82 return Layer.effect(
83 EnvironmentRegistry,
84 Effect.gen(function* () {
85 const client = {
86 [WS_METHODS.cloudGetRelayClientStatus]: () =>
87 Effect.succeed(options?.status ?? { status: "available", version: "2026.6.0" }),
88 [WS_METHODS.cloudInstallRelayClient]: () =>
89 Stream.fromIterable(options?.installEvents ?? []),
90 } as unknown as RpcSession["client"];
91 const session: RpcSession = {
92 client,
93 initialConfig: Effect.never,
94 ready: Effect.void,
95 probe: Effect.void,
96 closed: Effect.never,
97 };
98 const target = new PrimaryConnectionTarget({
99 environmentId: EnvironmentId.make(TARGET.environmentId),
100 label: TARGET.label,
101 httpBaseUrl: TARGET.httpBaseUrl,
102 wsBaseUrl: TARGET.wsBaseUrl,
103 });
104 const supervisor = EnvironmentSupervisor.of({
105 target,
106 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
107 session: yield* SubscriptionRef.make(Option.some(session)),
108 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
109 connect: Effect.void,
110 disconnect: Effect.void,
111 retryNow: Effect.void,
112 } satisfies EnvironmentSupervisor["Service"]);
113 const registry = {
114 run: <A, E, R>(_environmentId: EnvironmentId, effect: Effect.Effect<A, E, R>) =>
115 Effect.provideService(effect, EnvironmentSupervisor, supervisor),
116 runStream: <A, E, R>(_environmentId: EnvironmentId, stream: Stream.Stream<A, E, R>) =>
117 Stream.provideService(stream, EnvironmentSupervisor, supervisor),
118 } as unknown as EnvironmentRegistry["Service"];
119 return EnvironmentRegistry.of(registry);
120 }),
121 );
122}
123
124function services(options?: Parameters<typeof registryLayer>[0]) {
125 return Layer.mergeAll(relayLayer(), registryLayer(options));
126}
127
128function withServices<A, E>(
129 effect: Effect.Effect<
130 A,
131 E,
132 HttpClient.HttpClient | ManagedRelay.ManagedRelayClient | EnvironmentRegistry
133 >,
134 options?: Parameters<typeof registryLayer>[0],
135) {
136 return effect.pipe(Effect.provide(services(options)));
137}
138
139function bodyText(body: BodyInit | null | undefined): string {
140 return body instanceof Uint8Array ? new TextDecoder().decode(body) : String(body ?? "");
141}
142
143beforeEach(() => {
144 vi.clearAllMocks();
145 vi.stubEnv("VITE_T3CODE_RELAY_URL", "https://relay.example.test");
146 relayClientInstallDialog.requestConfirmation.mockResolvedValue(true);
147});
148
149afterEach(() => {
150 __resetDesktopPrimaryAuthForTests();
151 vi.unstubAllGlobals();
152 vi.unstubAllEnvs();
153 vi.restoreAllMocks();
154});
155
156describe("web cloud link environment client", () => {
157 it("normalizes relay URLs and de-duplicates cloud link targets", () => {
158 expect(normalizeRelayBaseUrl(" https://relay.example.test/// ")).toBe(
159 "https://relay.example.test",
160 );
161 expect(normalizeRelayBaseUrl(" ")).toBeNull();
162 expect(
163 collectCloudLinkTargets({
164 primary: TARGET,
165 saved: [TARGET, { ...TARGET, environmentId: "environment-2" }],
166 }).map((target) => target.environmentId),
167 ).toEqual(["environment-1", "environment-2"]);
168 });
169
170 it.effect("lists relay-managed environments through the typed relay client", () =>
171 Effect.gen(function* () {
172 const fetchMock = vi.fn().mockResolvedValue(
173 Response.json({
174 environments: [
175 {
176 environmentId: "environment-1",
177 label: "Desktop",
178 endpoint: {
179 httpBaseUrl: "https://desktop.example.test",
180 wsBaseUrl: "wss://desktop.example.test",
181 providerKind: "cloudflare_tunnel",
182 },
183 linkedAt: "2026-06-06T00:00:00.000Z",
184 },
185 ],
186 }),
187 );
188 vi.stubGlobal("fetch", fetchMock);
189
190 const environments = yield* withServices(
191 listManagedCloudEnvironments({ clerkToken: "clerk-token" }),
192 );
193
194 expect(environments).toHaveLength(1);
195 expect(fetchMock.mock.calls[0]?.[1]?.headers.authorization).toBe("Bearer clerk-token");
196 }),
197 );
198
199 it.effect("reads primary cloud link state from the explicit target", () =>
200 Effect.gen(function* () {
201 const fetchMock = vi.fn().mockResolvedValue(
202 Response.json({
203 linked: true,
204 cloudUserId: "user-1",
205 relayUrl: "https://relay.example.test",
206 relayIssuer: "https://relay.example.test",
207 publishAgentActivity: false,
208 }),
209 );
210 vi.stubGlobal("fetch", fetchMock);
211
212 const state = yield* withServices(readPrimaryCloudLinkState({ target: TARGET }));
213
214 expect(Option.fromNullishOr(state)).toEqual(
215 Option.some({
216 linked: true,
217 cloudUserId: "user-1",
218 relayUrl: "https://relay.example.test",
219 relayIssuer: "https://relay.example.test",
220 publishAgentActivity: false,
221 }),
222 );
223 expect(String(fetchMock.mock.calls[0]?.[0])).toBe(
224 "http://127.0.0.1:3000/api/connect/link-state",
225 );
226 }),
227 );
228
229 it.effect("uses desktop bearer auth for primary cloud link state", () =>
230 Effect.gen(function* () {
231 const fetchMock = vi.fn().mockResolvedValue(
232 Response.json({
233 linked: true,
234 cloudUserId: "user-1",
235 relayUrl: "https://relay.example.test",
236 relayIssuer: "https://relay.example.test",
237 publishAgentActivity: false,
238 }),
239 );
240 vi.stubGlobal("fetch", fetchMock);
241 vi.stubGlobal("window", {
242 location: { origin: "t3code://app" },
243 desktopBridge: {
244 getLocalEnvironmentBearerToken: vi.fn().mockResolvedValue("desktop-bearer-token"),
245 } as unknown as DesktopBridge,
246 });
247
248 yield* withServices(readPrimaryCloudLinkState({ target: TARGET }));
249
250 const request = new Request(fetchMock.mock.calls[0]?.[0], fetchMock.mock.calls[0]?.[1]);
251 expect(request.credentials).not.toBe("include");
252 expect(request.headers.get("authorization")).toBe("Bearer desktop-bearer-token");
253 }),
254 );
255
256 it.effect("updates agent activity publishing for the explicit primary target", () =>
257 Effect.gen(function* () {
258 const fetchMock = vi.fn().mockResolvedValue(
259 Response.json({
260 linked: true,
261 cloudUserId: "user-1",
262 relayUrl: "https://relay.example.test",
263 relayIssuer: "https://relay.example.test",
264 publishAgentActivity: true,
265 }),
266 );
267 vi.stubGlobal("fetch", fetchMock);
268
269 const state = yield* withServices(
270 updatePrimaryCloudPreferences({
271 target: TARGET,
272 publishAgentActivity: true,
273 }),
274 );
275
276 expect(state.publishAgentActivity).toBe(true);
277 expect(String(fetchMock.mock.calls[0]?.[0])).toBe(
278 "http://127.0.0.1:3000/api/connect/preferences",
279 );
280 expect(fetchMock.mock.calls[0]?.[1]?.method).toBe("POST");
281 // @effect-diagnostics-next-line preferSchemaOverJson:off
282 expect(JSON.parse(bodyText(fetchMock.mock.calls[0]?.[1]?.body))).toEqual({
283 publishAgentActivity: true,
284 });
285 }),
286 );
287
288 it.effect("links an available primary environment without invoking installation", () =>
289 Effect.gen(function* () {
290 const fetchMock = vi
291 .fn()
292 .mockResolvedValueOnce(
293 Response.json({
294 challenge: "challenge",
295 expiresAt: "2026-06-06T00:05:00.000Z",
296 }),
297 )
298 .mockResolvedValueOnce(Response.json("signed-proof"))
299 .mockResolvedValueOnce(
300 Response.json({
301 ok: true,
302 environmentId: TARGET.environmentId,
303 endpoint: {
304 httpBaseUrl: "https://desktop.example.test",
305 wsBaseUrl: "wss://desktop.example.test",
306 providerKind: "cloudflare_tunnel",
307 },
308 endpointRuntime: null,
309 relayIssuer: "https://relay.example.test",
310 cloudUserId: "user-1",
311 environmentCredential: "environment-credential",
312 cloudMintPublicKey: "public-key",
313 }),
314 )
315 .mockResolvedValueOnce(
316 Response.json({ ok: true, endpointRuntimeStatus: { status: "configured" } }),
317 );
318 vi.stubGlobal("fetch", fetchMock);
319
320 yield* withServices(
321 linkPrimaryEnvironmentToCloud({
322 target: TARGET,
323 clerkToken: "clerk-token",
324 }),
325 );
326
327 expect(relayClientInstallDialog.requestConfirmation).not.toHaveBeenCalled();
328 expect(String(fetchMock.mock.calls[1]?.[0])).toBe(
329 "http://127.0.0.1:3000/api/connect/link-proof",
330 );
331 // @effect-diagnostics-next-line preferSchemaOverJson:off
332 expect(JSON.parse(bodyText(fetchMock.mock.calls[1]?.[1]?.body))).toMatchObject({
333 challenge: "challenge",
334 endpoint: {
335 httpBaseUrl: TARGET.httpBaseUrl,
336 wsBaseUrl: TARGET.wsBaseUrl,
337 },
338 });
339 }),
340 );
341
342 it.effect("installs a missing relay client before linking", () =>
343 Effect.gen(function* () {
344 vi.stubGlobal("fetch", vi.fn().mockResolvedValue(Response.json({ malformed: true })));
345
346 yield* withServices(
347 linkPrimaryEnvironmentToCloud({
348 target: TARGET,
349 clerkToken: "clerk-token",
350 }),
351 {
352 status: { status: "available", version: "2026.6.0" },
353 installEvents: [],
354 },
355 ).pipe(Effect.flip);
356
357 expect(relayClientInstallDialog.requestConfirmation).not.toHaveBeenCalled();
358 }),
359 );
360
361 it.effect("unlinks locally before revoking the relay record", () =>
362 Effect.gen(function* () {
363 const fetchMock = vi
364 .fn()
365 .mockResolvedValueOnce(
366 Response.json({ ok: true, endpointRuntimeStatus: { status: "disabled" } }),
367 )
368 .mockResolvedValueOnce(Response.json({ ok: true }));
369 vi.stubGlobal("fetch", fetchMock);
370
371 yield* withServices(
372 unlinkPrimaryEnvironmentFromCloud({
373 target: TARGET,
374 clerkToken: "clerk-token",
375 }),
376 );
377
378 expect(String(fetchMock.mock.calls[0]?.[0])).toBe("http://127.0.0.1:3000/api/connect/unlink");
379 expect(String(fetchMock.mock.calls[1]?.[0])).toContain(
380 `/v1/client/environment-links/${TARGET.environmentId}`,
381 );
382 }),
383 );
384});