Skip to content

Commit d520d5b

Browse files
shivamhwpPR Batch Testerclaudemaria-rcks
authored
fix(web): show saved service access with Local environment off (pingdotgg#26464)
Co-authored-by: PR Batch Tester <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: maria-rcks <[email protected]>
1 parent 754e1d1 commit d520d5b

25 files changed

Lines changed: 852 additions & 509 deletions
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import { useAtomValue } from "@effect/atom-react";
2+
import {
3+
AuthRelayReadScope,
4+
type EnvironmentCloudLinkStateResult,
5+
type EnvironmentId,
6+
} from "@t3tools/contracts";
7+
import * as Cause from "effect/Cause";
8+
import { AsyncResult, Atom } from "effect/reactivity";
9+
10+
import { connectionAtomRuntime } from "../connection/runtime";
11+
import { usePrimaryEnvironmentId } from "../state/environments";
12+
import { appAtomRegistry } from "../rpc/atomRegistry";
13+
import { readEnvironmentScope, useEnvironmentScope } from "../state/session";
14+
import { readCloudLinkState, type CloudLinkTarget } from "./linkEnvironment";
15+
import { hasCloudPublicConfig } from "./publicConfig";
16+
17+
const cloudLinkStateAtom = Atom.family((environmentId: EnvironmentId) =>
18+
connectionAtomRuntime
19+
.atom(readCloudLinkState({ target: { environmentId } }))
20+
.pipe(
21+
Atom.swr({ staleTime: 5_000, revalidateOnMount: true }),
22+
Atom.setIdleTTL(5 * 60_000),
23+
Atom.withLabel(`cloud-link:${environmentId}`),
24+
),
25+
);
26+
27+
const EMPTY_CLOUD_LINK_STATE_ATOM = Atom.make(
28+
AsyncResult.success<EnvironmentCloudLinkStateResult | null>(null),
29+
).pipe(Atom.keepAlive, Atom.withLabel("cloud-link:null"));
30+
31+
function refreshCloudLinkState(target: CloudLinkTarget | null): void {
32+
if (target && readEnvironmentScope(target.environmentId, AuthRelayReadScope)) {
33+
appAtomRegistry.refresh(cloudLinkStateAtom(target.environmentId));
34+
}
35+
}
36+
37+
export function readCachedCloudLinkState(target: CloudLinkTarget) {
38+
if (!readEnvironmentScope(target.environmentId, AuthRelayReadScope)) return null;
39+
const result = appAtomRegistry.get(cloudLinkStateAtom(target.environmentId));
40+
return result._tag === "Success" ? result.value : null;
41+
}
42+
43+
export function useCloudLinkState(environmentId: EnvironmentId | null) {
44+
const canReadRelay = useEnvironmentScope(environmentId, AuthRelayReadScope);
45+
const target: CloudLinkTarget | null = environmentId === null ? null : { environmentId };
46+
const atom =
47+
environmentId !== null && hasCloudPublicConfig() && canReadRelay
48+
? cloudLinkStateAtom(environmentId)
49+
: EMPTY_CLOUD_LINK_STATE_ATOM;
50+
const result = useAtomValue(atom);
51+
const refresh = () => {
52+
refreshCloudLinkState(target);
53+
};
54+
let error: string | null = null;
55+
if (result._tag === "Failure") {
56+
const cause = Cause.squash(result.cause);
57+
error = cause instanceof Error ? cause.message : "Could not read T3 Connect link state.";
58+
}
59+
60+
return {
61+
data: result._tag === "Failure" ? null : AsyncResult.getOrElse(result, () => null),
62+
error,
63+
isPending: result.waiting,
64+
refresh,
65+
target,
66+
};
67+
}
68+
69+
export function usePrimaryCloudLinkState() {
70+
return useCloudLinkState(usePrimaryEnvironmentId());
71+
}

‎apps/web/src/cloud/linkEnvironment.test.ts‎

Lines changed: 93 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import { afterEach, beforeEach, vi } from "vite-plus/test";
1616
import {
1717
AVAILABLE_CONNECTION_STATE,
1818
type PreparedConnection,
19+
BearerConnectionTarget,
1920
PrimaryConnectionTarget,
2021
EnvironmentSupervisor,
2122
} from "@t3tools/client-runtime/connection";
@@ -25,15 +26,22 @@ import { ManagedRelay } from "@t3tools/client-runtime/relay";
2526
import { layerRemoteHttpClient } from "@t3tools/client-runtime/rpc";
2627
import { __resetDesktopPrimaryAuthForTests } from "../environments/primary/desktopAuth";
2728

28-
import { readPrimaryCloudLinkState, type CloudLinkTarget } from "./linkEnvironment";
29+
import { readCloudLinkState } from "./linkEnvironment";
2930

30-
const TARGET: CloudLinkTarget = {
31+
const TARGET = {
3132
environmentId: "environment-1",
3233
label: "Desktop",
3334
httpBaseUrl: "http://127.0.0.1:3000",
3435
wsBaseUrl: "ws://127.0.0.1:3000",
3536
};
3637

38+
const SAVED_SERVICE_TARGET = {
39+
environmentId: "saved-service",
40+
label: "Service",
41+
httpBaseUrl: "http://127.0.0.1:3773",
42+
wsBaseUrl: "ws://127.0.0.1:3773",
43+
};
44+
3745
const relayClientInstallDialog = vi.hoisted(() => ({
3846
requestConfirmation: vi.fn(),
3947
reportProgress: vi.fn(),
@@ -88,26 +96,73 @@ function layerRegistry(options?: {
8896
inboundFrames: Effect.succeed(0),
8997
closed: Effect.never,
9098
};
91-
const target = new PrimaryConnectionTarget({
92-
environmentId: EnvironmentId.make(TARGET.environmentId),
93-
label: TARGET.label,
94-
httpBaseUrl: TARGET.httpBaseUrl,
95-
wsBaseUrl: TARGET.wsBaseUrl,
99+
const makeSupervisor = Effect.fn(function* (prepared: Option.Option<PreparedConnection>) {
100+
return EnvironmentSupervisor.EnvironmentSupervisor.of({
101+
target: new PrimaryConnectionTarget({
102+
environmentId: EnvironmentId.make(TARGET.environmentId),
103+
label: TARGET.label,
104+
httpBaseUrl: TARGET.httpBaseUrl,
105+
wsBaseUrl: TARGET.wsBaseUrl,
106+
}),
107+
state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
108+
session: yield* SubscriptionRef.make(Option.some(session)),
109+
prepared: yield* SubscriptionRef.make(prepared),
110+
connect: Effect.void,
111+
disconnect: Effect.void,
112+
retryNow: Effect.void,
113+
} satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
96114
});
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"]);
115+
const supervisors = new Map([
116+
[
117+
TARGET.environmentId,
118+
yield* makeSupervisor(
119+
Option.some({
120+
environmentId: EnvironmentId.make(TARGET.environmentId),
121+
label: TARGET.label,
122+
httpBaseUrl: TARGET.httpBaseUrl,
123+
socketUrl: `${TARGET.wsBaseUrl}/ws`,
124+
httpAuthorization: { _tag: "Bearer", token: "desktop-bearer-token" },
125+
target: new PrimaryConnectionTarget({
126+
environmentId: EnvironmentId.make(TARGET.environmentId),
127+
label: TARGET.label,
128+
httpBaseUrl: TARGET.httpBaseUrl,
129+
wsBaseUrl: TARGET.wsBaseUrl,
130+
}),
131+
}),
132+
),
133+
],
134+
[
135+
SAVED_SERVICE_TARGET.environmentId,
136+
yield* makeSupervisor(
137+
Option.some({
138+
environmentId: EnvironmentId.make(SAVED_SERVICE_TARGET.environmentId),
139+
label: SAVED_SERVICE_TARGET.label,
140+
httpBaseUrl: SAVED_SERVICE_TARGET.httpBaseUrl,
141+
socketUrl: `${SAVED_SERVICE_TARGET.wsBaseUrl}/ws`,
142+
httpAuthorization: { _tag: "Bearer", token: "saved-service-token" },
143+
target: new BearerConnectionTarget({
144+
environmentId: EnvironmentId.make(SAVED_SERVICE_TARGET.environmentId),
145+
label: SAVED_SERVICE_TARGET.label,
146+
connectionId: "saved-service-connection",
147+
}),
148+
}),
149+
),
150+
],
151+
]);
152+
const supervisorFor = (environmentId: EnvironmentId) => supervisors.get(environmentId)!;
106153
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),
154+
run: <A, E, R>(environmentId: EnvironmentId, effect: Effect.Effect<A, E, R>) =>
155+
Effect.provideService(
156+
effect,
157+
EnvironmentSupervisor.EnvironmentSupervisor,
158+
supervisorFor(environmentId),
159+
),
160+
runStream: <A, E, R>(environmentId: EnvironmentId, stream: Stream.Stream<A, E, R>) =>
161+
Stream.provideService(
162+
stream,
163+
EnvironmentSupervisor.EnvironmentSupervisor,
164+
supervisorFor(environmentId),
165+
),
111166
} as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"];
112167
return EnvironmentRegistry.EnvironmentRegistry.of(registry);
113168
}),
@@ -145,9 +200,9 @@ afterEach(() => {
145200
});
146201

147202
describe("web cloud link environment client", () => {
148-
it.effect("uses desktop bearer auth for primary cloud link state", () =>
203+
it.effect("reads link state from the chosen environment with its own credentials", () =>
149204
Effect.gen(function* () {
150-
const fetchMock = vi.fn().mockResolvedValue(
205+
const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) =>
151206
Response.json({
152207
linked: true,
153208
cloudUserId: "user-1",
@@ -165,11 +220,23 @@ describe("web cloud link environment client", () => {
165220
} as unknown as DesktopBridge,
166221
});
167222

168-
yield* withServices(readPrimaryCloudLinkState({ target: TARGET }));
223+
for (const [target, token] of [
224+
[TARGET, "desktop-bearer-token"],
225+
[SAVED_SERVICE_TARGET, "saved-service-token"],
226+
] as const) {
227+
fetchMock.mockClear();
228+
yield* withServices(
229+
readCloudLinkState({
230+
target: { environmentId: EnvironmentId.make(target.environmentId) },
231+
}),
232+
);
169233

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");
234+
const [input, init] = fetchMock.mock.calls[0]!;
235+
const request = new Request(input, init);
236+
expect(new URL(request.url).origin).toBe(target.httpBaseUrl);
237+
expect(request.credentials).not.toBe("include");
238+
expect(request.headers.get("authorization")).toBe(`Bearer ${token}`);
239+
}
173240
}),
174241
);
175242
});

0 commit comments

Comments
 (0)