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/http";
15import { afterEach, beforeEach, vi } from "vite-plus/test";
16import {
17 AVAILABLE_CONNECTION_STATE,
18 type PreparedConnection,
19 PrimaryConnectionTarget,
20 EnvironmentSupervisor,
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 { layerRemoteHttpClient } from "@t3tools/client-runtime/rpc";
26import { __resetDesktopPrimaryAuthForTests } from "../environments/primary/desktopAuth";
27
28import { readPrimaryCloudLinkState, type CloudLinkTarget } from "./linkEnvironment";
29
30const TARGET: CloudLinkTarget = {
31 environmentId: "environment-1",
32 label: "Desktop",
33 httpBaseUrl: "http://127.0.0.1:3000",
34 wsBaseUrl: "ws://127.0.0.1:3000",
35};
36
37const relayClientInstallDialog = vi.hoisted(() => ({
38 requestConfirmation: vi.fn(),
39 reportProgress: vi.fn(),
40 finish: vi.fn(),
41}));
42
43vi.mock("./relayClientInstallDialog", () => ({
44 requestRelayClientInstallConfirmation: relayClientInstallDialog.requestConfirmation,
45 reportRelayClientInstallProgress: relayClientInstallDialog.reportProgress,
46 finishRelayClientInstall: relayClientInstallDialog.finish,
47}));
48
49const createProof = vi.fn(() => Effect.succeed("dpop-proof"));
50const layerDpopSigner = Layer.succeed(
51 ManagedRelay.ManagedRelayDpopSigner,
52 ManagedRelay.ManagedRelayDpopSigner.of({
53 thumbprint: Effect.succeed("thumbprint"),
54 createProof,
55 }),
56);
57
58function layerRelay() {
59 const layerHttp = layerRemoteHttpClient(globalThis.fetch);
60 return Layer.mergeAll(
61 layerHttp,
62 ManagedRelay.layer({
63 relayUrl: "https://relay.example.test",
64 clientId: RelayWebClientId,
65 }).pipe(Layer.provideMerge(layerDpopSigner), Layer.provide(layerHttp)),
66 );
67}
68
69function layerRegistry(options?: {
70 readonly status?: { readonly status: "available"; readonly version: string };
71 readonly installEvents?: ReadonlyArray<RelayClientInstallProgressEvent>;
72}) {
73 return Layer.effect(
74 EnvironmentRegistry.EnvironmentRegistry,
75 Effect.gen(function* () {
76 const client = {
77 [WS_METHODS.cloudGetRelayClientStatus]: () =>
78 Effect.succeed(options?.status ?? { status: "available", version: "2026.6.0" }),
79 [WS_METHODS.cloudInstallRelayClient]: () =>
80 Stream.fromIterable(options?.installEvents ?? []),
81 } as unknown as RpcSession["client"];
82 const session: RpcSession = {
83 client,
84 initialConfig: Effect.never,
85 subscribeServerConfig: (input = {}) => client.subscribeServerConfig(input),
86 ready: Effect.void,
87 probe: Effect.void,
88 inboundFrames: Effect.succeed(0),
89 closed: Effect.never,
90 };
91 const target = new PrimaryConnectionTarget({
92 environmentId: EnvironmentId.make(TARGET.environmentId),
93 label: TARGET.label,
94 httpBaseUrl: TARGET.httpBaseUrl,
95 wsBaseUrl: TARGET.wsBaseUrl,
96 });
97 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
98 target,
99 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
100 session: yield* SubscriptionRef.make(Option.some(session)),
101 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
102 connect: Effect.void,
103 disconnect: Effect.void,
104 retryNow: Effect.void,
105 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
106 const registry = {
107 run: <A, E, R>(_environmentId: EnvironmentId, effect: Effect.Effect<A, E, R>) =>
108 Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
109 runStream: <A, E, R>(_environmentId: EnvironmentId, stream: Stream.Stream<A, E, R>) =>
110 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
111 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"];
112 return EnvironmentRegistry.EnvironmentRegistry.of(registry);
113 }),
114 );
115}
116
117function layerServices(options?: Parameters<typeof layerRegistry>[0]) {
118 return Layer.mergeAll(layerRelay(), layerRegistry(options));
119}
120
121function withServices<A, E>(
122 effect: Effect.Effect<
123 A,
124 E,
125 | HttpClient.HttpClient
126 | ManagedRelay.ManagedRelayClient
127 | EnvironmentRegistry.EnvironmentRegistry
128 >,
129 options?: Parameters<typeof layerRegistry>[0],
130) {
131 return effect.pipe(Effect.provide(layerServices(options)));
132}
133
134beforeEach(() => {
135 vi.clearAllMocks();
136 vi.stubEnv("VITE_T3CODE_RELAY_URL", "https://relay.example.test");
137 relayClientInstallDialog.requestConfirmation.mockResolvedValue(true);
138});
139
140afterEach(() => {
141 __resetDesktopPrimaryAuthForTests();
142 vi.unstubAllGlobals();
143 vi.unstubAllEnvs();
144 vi.restoreAllMocks();
145});
146
147describe("web cloud link environment client", () => {
148 it.effect("uses desktop bearer auth for primary cloud link state", () =>
149 Effect.gen(function* () {
150 const fetchMock = vi.fn().mockResolvedValue(
151 Response.json({
152 linked: true,
153 cloudUserId: "user-1",
154 relayUrl: "https://relay.example.test",
155 relayIssuer: "https://relay.example.test",
156 managedTunnelActive: true,
157 publishAgentActivity: false,
158 }),
159 );
160 vi.stubGlobal("fetch", fetchMock);
161 vi.stubGlobal("window", {
162 location: { origin: "t3code://app" },
163 desktopBridge: {
164 getLocalEnvironmentBearerToken: vi.fn().mockResolvedValue("desktop-bearer-token"),
165 } as unknown as DesktopBridge,
166 });
167
168 yield* withServices(readPrimaryCloudLinkState({ target: TARGET }));
169
170 const request = new Request(fetchMock.mock.calls[0]?.[0], fetchMock.mock.calls[0]?.[1]);
171 expect(request.credentials).not.toBe("include");
172 expect(request.headers.get("authorization")).toBe("Bearer desktop-bearer-token");
173 }),
174 );
175});