@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 342 lines 11.2 KB
Raw
1 import { beforeEach, vi } from "vite-plus/test";
2 import { describe, expect, it } from "@effect/vitest";
3 import * as Effect from "effect/Effect";
4 import * as Option from "effect/Option";
5 import * as SubscriptionRef from "effect/SubscriptionRef";
6 import * as Layer from "effect/Layer";
7 import { EnvironmentId } from "@t3tools/contracts";
8 import { RelayMobileClientId } from "@t3tools/contracts/relay";
9 import {
10 EnvironmentSupervisor,
11 AVAILABLE_CONNECTION_STATE,
12 PrimaryConnectionTarget,
13 type PreparedConnection,
14 } from "@t3tools/client-runtime/connection";
15 import { ManagedRelay } from "@t3tools/client-runtime/relay";
16 import { layerRemoteHttpClient, type RpcSession } from "@t3tools/client-runtime/rpc";
17 import { HttpClient } from "effect/http";
18
19 import * as MobileStorage from "../../persistence/mobile-storage";
20
21 import {
22 linkEnvironmentToCloudWithPreference,
23 updateLinkedEnvironmentLiveActivityPreference,
24 } from "./linkEnvironment";
25
26 vi.mock("expo-constants", () => ({
27 default: {
28 expoConfig: {
29 extra: {
30 relay: {
31 url: "https://relay.example.test",
32 },
33 },
34 },
35 },
36 }));
37
38 vi.mock("expo-device", () => ({
39 deviceType: 1,
40 DeviceType: {
41 UNKNOWN: 0,
42 PHONE: 1,
43 TABLET: 2,
44 DESKTOP: 3,
45 TV: 4,
46 },
47 osVersion: "18.4.1",
48 modelName: "iPhone 15 Pro",
49 }));
50
51 vi.mock("react-native", () => ({
52 Platform: {
53 OS: "ios",
54 },
55 }));
56
57 vi.mock("expo-secure-store", () => ({
58 deleteItemAsync: vi.fn(),
59 getItemAsync: vi.fn(),
60 setItemAsync: vi.fn(),
61 }));
62
63 const savedConnection = {
64 environmentId: EnvironmentId.make("env-1"),
65 environmentLabel: "Desktop",
66 pairingUrl: "https://desktop.example.test/",
67 displayUrl: "https://desktop.example.test/",
68 httpBaseUrl: "https://desktop.example.test/",
69 wsBaseUrl: "wss://desktop.example.test/ws",
70 bearerToken: "local-bearer",
71 };
72
73 const createProofMock = vi.fn(
74 (input: { readonly method: string; readonly url: string; readonly accessToken?: string }) =>
75 Effect.succeed(`dpop:${input.method}:${input.url}`),
76 );
77 const layerTestDpopSigner = Layer.succeed(
78 ManagedRelay.ManagedRelayDpopSigner,
79 ManagedRelay.ManagedRelayDpopSigner.of({
80 thumbprint: Effect.succeed("client-proof-key-thumbprint"),
81 createProof: (input) => createProofMock(input),
82 }),
83 );
84
85 function layerCloudClient() {
86 const layerHttpClient = layerRemoteHttpClient((input, init) => globalThis.fetch(input, init));
87 return Layer.mergeAll(
88 layerHttpClient,
89 Layer.succeed(
90 MobileStorage.MobileStorage,
91 MobileStorage.MobileStorage.of({
92 loadOrCreateAgentAwarenessDeviceId: Effect.succeed("device-1"),
93 loadAgentAwarenessDeviceId: Effect.succeed("device-1"),
94 loadAgentAwarenessRegistrationRecord: Effect.succeed(null),
95 saveAgentAwarenessRegistrationRecord: () => Effect.void,
96 clearAgentAwarenessRegistrationRecord: Effect.void,
97 loadRecentThreadShortcuts: Effect.succeed([]),
98 saveRecentThreadShortcuts: () => Effect.void,
99 }),
100 ),
101 ManagedRelay.layer({
102 relayUrl: "https://relay.example.test",
103 clientId: RelayMobileClientId,
104 }).pipe(Layer.provideMerge(layerTestDpopSigner), Layer.provide(layerHttpClient)),
105 );
106 }
107
108 const withCloudServices = <A, E>(
109 effect: Effect.Effect<
110 A,
111 E,
112 | HttpClient.HttpClient
113 | ManagedRelay.ManagedRelayClient
114 | ManagedRelay.ManagedRelayDpopSigner
115 | MobileStorage.MobileStorage
116 >,
117 ) => effect.pipe(Effect.provide(layerCloudClient()));
118
119 const linkedSupervisor = Effect.gen(function* () {
120 const target = new PrimaryConnectionTarget({
121 environmentId: savedConnection.environmentId,
122 label: savedConnection.environmentLabel,
123 httpBaseUrl: savedConnection.httpBaseUrl,
124 wsBaseUrl: savedConnection.wsBaseUrl,
125 });
126 return EnvironmentSupervisor.EnvironmentSupervisor.of({
127 target,
128 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
129 session: yield* SubscriptionRef.make(Option.none<RpcSession>()),
130 prepared: yield* SubscriptionRef.make(
131 Option.some<PreparedConnection>({
132 environmentId: savedConnection.environmentId,
133 label: savedConnection.environmentLabel,
134 httpBaseUrl: savedConnection.httpBaseUrl,
135 socketUrl: savedConnection.wsBaseUrl,
136 httpAuthorization: { _tag: "Bearer", token: "local-bearer" },
137 target,
138 }),
139 ),
140 connect: Effect.void,
141 disconnect: Effect.void,
142 retryNow: Effect.void,
143 });
144 });
145
146 const linkPreparedEnvironment = (liveActivitiesEnabled: boolean) =>
147 Effect.flatMap(linkedSupervisor, (supervisor) =>
148 withCloudServices(
149 linkEnvironmentToCloudWithPreference({
150 clerkToken: "clerk-token",
151 liveActivitiesEnabled,
152 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor)),
153 ),
154 );
155
156 function validLinkProof() {
157 return "signed-environment-link-jwt";
158 }
159
160 function validLinkResponse(environmentId = "env-1") {
161 return {
162 ok: true,
163 environmentId,
164 endpoint: {
165 httpBaseUrl: "https://desktop.example.test/",
166 wsBaseUrl: "wss://desktop.example.test/ws",
167 providerKind: "manual",
168 },
169 endpointRuntime: null,
170 relayIssuer: "https://relay.example.test",
171 cloudUserId: "user_123",
172 environmentCredential: "environment-credential",
173 cloudMintPublicKey: "cloud-mint-public-key",
174 };
175 }
176
177 function linkStateResponse() {
178 return {
179 linked: false,
180 cloudUserId: null,
181 relayUrl: null,
182 relayIssuer: null,
183 publishAgentActivity: true,
184 };
185 }
186
187 function validLinkChallengeResponse() {
188 return {
189 challenge: "link-challenge",
190 expiresAt: "2026-05-25T00:05:00.000Z",
191 };
192 }
193
194 function requestBodyText(body: BodyInit | null | undefined): string {
195 return body instanceof Uint8Array ? new TextDecoder().decode(body) : String(body ?? "");
196 }
197
198 describe("mobile cloud link environment client", () => {
199 beforeEach(() => {
200 vi.restoreAllMocks();
201 createProofMock.mockClear();
202 });
203
204 it.effect("skips Live Activity updates when the environment has no prepared connection", () =>
205 Effect.gen(function* () {
206 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
207 target: new PrimaryConnectionTarget({
208 environmentId: savedConnection.environmentId,
209 label: savedConnection.environmentLabel,
210 httpBaseUrl: savedConnection.httpBaseUrl,
211 wsBaseUrl: savedConnection.wsBaseUrl,
212 }),
213 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
214 session: yield* SubscriptionRef.make(Option.none<RpcSession>()),
215 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
216 connect: Effect.void,
217 disconnect: Effect.void,
218 retryNow: Effect.void,
219 });
220 const result = yield* updateLinkedEnvironmentLiveActivityPreference(true).pipe(
221 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
222 Effect.provideService(
223 HttpClient.HttpClient,
224 HttpClient.make(() => Effect.die("unexpected HTTP request")),
225 ),
226 );
227 expect(result).toBe("disconnected");
228 }),
229 );
230
231 it.effect(
232 "rejects relay link credentials for a different environment before persisting relay config",
233 () =>
234 Effect.gen(function* () {
235 const fetchMock = vi.fn((url: string | URL) => {
236 if (String(url).endsWith("/api/connect/preferences")) {
237 return Promise.resolve(Response.json(linkStateResponse()));
238 }
239 if (String(url).endsWith("/v1/client/environment-link-challenges")) {
240 return Promise.resolve(Response.json(validLinkChallengeResponse()));
241 }
242 if (String(url).endsWith("/api/connect/link-proof")) {
243 return Promise.resolve(Response.json(validLinkProof()));
244 }
245 return Promise.resolve(Response.json(validLinkResponse("env-other")));
246 });
247 vi.stubGlobal("fetch", fetchMock);
248
249 const error = yield* linkPreparedEnvironment(true).pipe(Effect.flip);
250 expect(error).toMatchObject({
251 _tag: "CloudEnvironmentLinkError",
252 message: "Relay returned credentials for a different environment.",
253 });
254 expect(fetchMock).toHaveBeenCalledTimes(4);
255 }),
256 );
257
258 it.effect("rejects relay link credentials for a different managed endpoint provider", () =>
259 Effect.gen(function* () {
260 const fetchMock = vi.fn((url: string | URL) => {
261 if (String(url).endsWith("/api/connect/preferences")) {
262 return Promise.resolve(Response.json(linkStateResponse()));
263 }
264 if (String(url).endsWith("/v1/client/environment-link-challenges")) {
265 return Promise.resolve(Response.json(validLinkChallengeResponse()));
266 }
267 if (String(url).endsWith("/api/connect/link-proof")) {
268 return Promise.resolve(Response.json(validLinkProof()));
269 }
270 return Promise.resolve(
271 Response.json({
272 ...validLinkResponse(),
273 endpoint: {
274 ...validLinkResponse().endpoint,
275 providerKind: "cloudflare_tunnel",
276 },
277 }),
278 );
279 });
280 vi.stubGlobal("fetch", fetchMock);
281
282 const error = yield* linkPreparedEnvironment(true).pipe(Effect.flip);
283 expect(error).toMatchObject({
284 _tag: "CloudEnvironmentLinkError",
285 message: "Relay returned credentials for a different endpoint provider.",
286 });
287 expect(fetchMock).toHaveBeenCalledTimes(4);
288 }),
289 );
290
291 it.effect("preserves disabled Live Activity preferences when linking an environment", () =>
292 Effect.gen(function* () {
293 const bodies: Array<unknown> = [];
294 const fetchMock = vi.fn((url: string | URL, init?: RequestInit) => {
295 if (init?.body) {
296 bodies.push(JSON.parse(requestBodyText(init.body)));
297 }
298 if (String(url).endsWith("/v1/client/environment-link-challenges")) {
299 return Promise.resolve(Response.json(validLinkChallengeResponse()));
300 }
301 if (String(url).endsWith("/api/connect/link-proof")) {
302 return Promise.resolve(Response.json(validLinkProof()));
303 }
304 if (String(url).endsWith("/v1/client/environment-links")) {
305 return Promise.resolve(Response.json(validLinkResponse()));
306 }
307 if (String(url).endsWith("/api/connect/preferences")) {
308 return Promise.resolve(Response.json(linkStateResponse()));
309 }
310 return Promise.resolve(
311 Response.json({ ok: true, endpointRuntimeStatus: { status: "configured" } }),
312 );
313 });
314 vi.stubGlobal("fetch", fetchMock);
315
316 yield* linkPreparedEnvironment(false);
317
318 expect(bodies[0]).toEqual({ publishAgentActivity: true });
319 expect(bodies[2]).toMatchObject({
320 endpoint: {
321 httpBaseUrl: "https://desktop.example.test/",
322 wsBaseUrl: "wss://desktop.example.test/ws",
323 providerKind: "manual",
324 },
325 origin: {
326 localHttpHost: "127.0.0.1",
327 localHttpPort: 443,
328 },
329 });
330 expect(bodies[3]).toMatchObject({
331 deviceId: "device-1",
332 notificationsEnabled: true,
333 liveActivitiesEnabled: false,
334 managedTunnelsEnabled: false,
335 });
336 expect(bodies[4]).toMatchObject({
337 cloudUserId: "user_123",
338 environmentCredential: "environment-credential",
339 });
340 }),
341 );
342 });