Open History to see the last commit
1import { RegistryContext } from "@effect/atom-react";
2import {
3 AuthSettingsWriteScope,
4 DEFAULT_SERVER_SETTINGS,
5 EnvironmentId,
6 type AuthEnvironmentScope,
7 type AuthSessionState,
8 type ServerSettingsPatch,
9} from "@t3tools/contracts";
10import * as Cause from "effect/Cause";
11import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
12import { act } from "react";
13import { create, type ReactTestRenderer } from "react-test-renderer";
14import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
15
16type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;
17const state = vi.hoisted(() => ({
18 registry: null as AtomRegistry.AtomRegistry | null,
19 sessions: new Map<EnvironmentId, Atom.Writable<SessionResult>>(),
20 environments: [] as Array<{
21 environmentId: EnvironmentId;
22 label: string;
23 connection: { phase: "connected" | "disconnected" };
24 serverConfig: {
25 environment: { capabilities: { threadAutoSettlement: boolean } };
26 settings: typeof DEFAULT_SERVER_SETTINGS;
27 };
28 }>,
29 persist: vi.fn(),
30 toast: vi.fn(),
31}));
32
33vi.mock("~/connection/runtime", () => ({ connectionAtomRuntime: undefined }));
34vi.mock("@t3tools/client-runtime/state/session", () => ({
35 createEnvironmentSessionAtoms: () => ({
36 sessionStateAtom: (id: EnvironmentId) => state.sessions.get(id)!,
37 }),
38}));
39vi.mock("~/rpc/atomRegistry", () => ({
40 get appAtomRegistry() {
41 return state.registry;
42 },
43}));
44vi.mock("~/state/environments", () => ({
45 useEnvironments: () => ({ environments: state.environments }),
46 usePrimaryEnvironment: () =>
47 state.environments.find((environment) => environment.environmentId === primaryId) ?? null,
48}));
49vi.mock("~/state/server", () => ({
50 serverEnvironment: { updateSettings: Symbol("updateSettings") },
51 primaryServerSettingsAtom: undefined,
52}));
53vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => state.persist }));
54vi.mock("~/components/ui/toast", () => ({ toastManager: { add: state.toast } }));
55vi.mock("~/themePalette", () => ({}));
56vi.mock("./useTheme", () => ({}));
57
58import { useUpdatePrimarySettings } from "./useSettings";
59
60const primaryId = EnvironmentId.make("primary");
61const remoteId = EnvironmentId.make("remote");
62const patch = { sidebarAutoSettleOnMerge: false } satisfies ServerSettingsPatch;
63const session = (scopes: ReadonlyArray<AuthEnvironmentScope>): AuthSessionState => ({
64 authenticated: true,
65 scopes,
66 auth: {
67 policy: "remote-reachable",
68 bootstrapMethods: ["one-time-token"],
69 sessionMethods: ["bearer-access-token"],
70 sessionCookieName: "t3_session",
71 },
72});
73let renderer: ReactTestRenderer | undefined;
74
75function SettingsEditor() {
76 const updateSettings = useUpdatePrimarySettings();
77 return <button onClick={() => updateSettings(patch)}>Save shared setting</button>;
78}
79
80function saveSharedSettings() {
81 renderer!.root.findByType("button").props.onClick();
82}
83
84async function mountEditor() {
85 await act(() => {
86 renderer = create(
87 <RegistryContext.Provider value={state.registry!}>
88 <SettingsEditor />
89 </RegistryContext.Provider>,
90 );
91 });
92}
93
94beforeEach(() => {
95 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
96 state.registry = AtomRegistry.make();
97 state.sessions.clear();
98 state.sessions.set(
99 primaryId,
100 Atom.make<SessionResult>(AsyncResult.success(session([AuthSettingsWriteScope]))),
101 );
102 state.sessions.set(remoteId, Atom.make<SessionResult>(AsyncResult.initial()));
103 state.environments = [primaryId, remoteId].map((environmentId) => ({
104 environmentId,
105 label: environmentId,
106 connection: { phase: "connected" },
107 serverConfig: {
108 environment: { capabilities: { threadAutoSettlement: true } },
109 settings: DEFAULT_SERVER_SETTINGS,
110 },
111 }));
112 state.persist.mockReset();
113 state.persist.mockResolvedValue(AsyncResult.success(DEFAULT_SERVER_SETTINGS));
114 state.toast.mockReset();
115});
116
117afterEach(async () => {
118 await act(() => renderer?.unmount());
119 renderer = undefined;
120 state.registry?.dispose();
121 vi.unstubAllGlobals();
122});
123
124describe("shared settings writes", () => {
125 it("dispatches to the primary and connected remote before the remote grant finishes loading", async () => {
126 await mountEditor();
127 saveSharedSettings();
128
129 expect(state.persist.mock.calls).toEqual([
130 [{ environmentId: primaryId, input: { patch } }],
131 [{ environmentId: remoteId, input: { patch } }],
132 ]);
133 expect(state.registry!.get(state.sessions.get(remoteId)!)).toMatchObject({ _tag: "Initial" });
134 });
135
136 it.each([
137 ["denied", () => AsyncResult.success(session([]))],
138 ["denied while refreshing", () => AsyncResult.waiting(AsyncResult.success(session([])))],
139 [
140 "failed",
141 () => AsyncResult.failure<AuthSessionState, Error>(Cause.fail(new Error("session rejected"))),
142 ],
143 ] as const)("skips a remote whose grant is %s", async (_label, result) => {
144 state.registry!.set(state.sessions.get(remoteId)!, result());
145 await mountEditor();
146 saveSharedSettings();
147
148 expect(state.persist).toHaveBeenCalledExactlyOnceWith({
149 environmentId: primaryId,
150 input: { patch },
151 });
152 });
153
154 it.each(["disconnected", "unsupported"] as const)(
155 "skips a %s remote even with a cold grant",
156 async (condition) => {
157 const remote = state.environments[1]!;
158 if (condition === "disconnected") remote.connection.phase = "disconnected";
159 else remote.serverConfig.environment.capabilities.threadAutoSettlement = false;
160 await mountEditor();
161 saveSharedSettings();
162
163 expect(state.persist).toHaveBeenCalledExactlyOnceWith({
164 environmentId: primaryId,
165 input: { patch },
166 });
167 },
168 );
169
170 it.each(["primary", "hosted"] as const)(
171 "rechecks a cold remote grant that resolves to denied after the %s handler renders",
172 async (mode) => {
173 if (mode === "hosted") {
174 state.environments = state.environments.filter(
175 (environment) => environment.environmentId !== primaryId,
176 );
177 }
178 await mountEditor();
179 const previousUpdate = renderer!.root.findByType("button").props.onClick as () => void;
180 await act(() => {
181 state.registry!.set(state.sessions.get(remoteId)!, AsyncResult.success(session([])));
182 });
183 previousUpdate();
184
185 if (mode === "primary") {
186 expect(state.persist).toHaveBeenCalledExactlyOnceWith({
187 environmentId: primaryId,
188 input: { patch },
189 });
190 expect(state.toast).not.toHaveBeenCalled();
191 } else {
192 expect(state.persist).not.toHaveBeenCalled();
193 expect(state.toast).toHaveBeenCalledExactlyOnceWith({
194 type: "warning",
195 title: "Setting not saved",
196 description: "This connection does not have permission to change these settings.",
197 });
198 }
199 },
200 );
201});