Open History to see the last commit
1import { useAtomSubscribe, useAtomValue } from "@effect/atom-react";
2import {
3 DEFAULT_SERVER_SETTINGS,
4 type EditorId,
5 type ServerConfig,
6 type ServerConfigStreamEvent,
7 type ServerConfigUpdatedPayload,
8 type ServerLifecycleWelcomePayload,
9 type ServerProvider,
10 type ServerProviderUpdatedPayload,
11 type ServerSettings,
12} from "@t3tools/contracts";
13import { Atom } from "effect/unstable/reactivity";
14
15import type { WsRpcClient } from "../wsRpcClient";
16import { appAtomRegistry, resetAppAtomRegistryForTests } from "./atomRegistry";
17
18export type ServerConfigUpdateSource = ServerConfigStreamEvent["type"];
19
20export interface ServerConfigUpdatedNotification {
21 readonly payload: ServerConfigUpdatedPayload;
22 readonly source: ServerConfigUpdateSource;
23}
24
25type ServerStateClient = Pick<
26 WsRpcClient["server"],
27 "getConfig" | "subscribeConfig" | "subscribeLifecycle"
28>;
29
30function makeStateAtom<A>(label: string, initialValue: A) {
31 return Atom.make(initialValue).pipe(Atom.keepAlive, Atom.withLabel(label));
32}
33
34function toServerConfigUpdatedPayload(config: ServerConfig): ServerConfigUpdatedPayload {
35 return {
36 issues: config.issues,
37 providers: config.providers,
38 settings: config.settings,
39 };
40}
41
42const EMPTY_AVAILABLE_EDITORS: ReadonlyArray<EditorId> = [];
43const EMPTY_KEYBINDINGS: ServerConfig["keybindings"] = [];
44const EMPTY_SERVER_PROVIDERS: ReadonlyArray<ServerProvider> = [];
45
46const selectAvailableEditors = (config: ServerConfig | null): ReadonlyArray<EditorId> =>
47 config?.availableEditors ?? EMPTY_AVAILABLE_EDITORS;
48const selectKeybindings = (config: ServerConfig | null) => config?.keybindings ?? EMPTY_KEYBINDINGS;
49const selectKeybindingsConfigPath = (config: ServerConfig | null) =>
50 config?.keybindingsConfigPath ?? null;
51const selectProviders = (config: ServerConfig | null) =>
52 config?.providers ?? EMPTY_SERVER_PROVIDERS;
53const selectSettings = (config: ServerConfig | null): ServerSettings =>
54 config?.settings ?? DEFAULT_SERVER_SETTINGS;
55
56export const welcomeAtom = makeStateAtom<ServerLifecycleWelcomePayload | null>(
57 "server-welcome",
58 null,
59);
60export const serverConfigAtom = makeStateAtom<ServerConfig | null>("server-config", null);
61export const serverConfigUpdatedAtom = makeStateAtom<ServerConfigUpdatedNotification | null>(
62 "server-config-updated",
63 null,
64);
65export const providersUpdatedAtom = makeStateAtom<ServerProviderUpdatedPayload | null>(
66 "server-providers-updated",
67 null,
68);
69
70export function getServerConfig(): ServerConfig | null {
71 return appAtomRegistry.get(serverConfigAtom);
72}
73
74export function setServerConfigSnapshot(config: ServerConfig): void {
75 resolveServerConfig(config);
76 emitProvidersUpdated({ providers: config.providers });
77 emitServerConfigUpdated(toServerConfigUpdatedPayload(config), "snapshot");
78}
79
80export function applyServerConfigEvent(event: ServerConfigStreamEvent): void {
81 switch (event.type) {
82 case "snapshot": {
83 setServerConfigSnapshot(event.config);
84 return;
85 }
86 case "keybindingsUpdated": {
87 const latestServerConfig = getServerConfig();
88 if (!latestServerConfig) {
89 return;
90 }
91 const nextConfig = {
92 ...latestServerConfig,
93 issues: event.payload.issues,
94 } satisfies ServerConfig;
95 resolveServerConfig(nextConfig);
96 emitServerConfigUpdated(toServerConfigUpdatedPayload(nextConfig), event.type);
97 return;
98 }
99 case "providerStatuses": {
100 applyProvidersUpdated(event.payload);
101 return;
102 }
103 case "settingsUpdated": {
104 applySettingsUpdated(event.payload.settings);
105 return;
106 }
107 }
108}
109
110export function applyProvidersUpdated(payload: ServerProviderUpdatedPayload): void {
111 const latestServerConfig = getServerConfig();
112 emitProvidersUpdated(payload);
113
114 if (!latestServerConfig) {
115 return;
116 }
117
118 const nextConfig = {
119 ...latestServerConfig,
120 providers: payload.providers,
121 } satisfies ServerConfig;
122 resolveServerConfig(nextConfig);
123 emitServerConfigUpdated(toServerConfigUpdatedPayload(nextConfig), "providerStatuses");
124}
125
126export function applySettingsUpdated(settings: ServerSettings): void {
127 const latestServerConfig = getServerConfig();
128 if (!latestServerConfig) {
129 return;
130 }
131
132 const nextConfig = {
133 ...latestServerConfig,
134 settings,
135 } satisfies ServerConfig;
136 resolveServerConfig(nextConfig);
137 emitServerConfigUpdated(toServerConfigUpdatedPayload(nextConfig), "settingsUpdated");
138}
139
140export function emitWelcome(payload: ServerLifecycleWelcomePayload): void {
141 appAtomRegistry.set(welcomeAtom, payload);
142}
143
144export function onWelcome(listener: (payload: ServerLifecycleWelcomePayload) => void): () => void {
145 return subscribeLatest(welcomeAtom, listener);
146}
147
148export function onServerConfigUpdated(
149 listener: (payload: ServerConfigUpdatedPayload, source: ServerConfigUpdateSource) => void,
150): () => void {
151 return subscribeLatest(serverConfigUpdatedAtom, (notification) => {
152 listener(notification.payload, notification.source);
153 });
154}
155
156export function onProvidersUpdated(
157 listener: (payload: ServerProviderUpdatedPayload) => void,
158): () => void {
159 return subscribeLatest(providersUpdatedAtom, listener);
160}
161
162export function startServerStateSync(client: ServerStateClient): () => void {
163 let disposed = false;
164 const cleanups = [
165 client.subscribeLifecycle((event) => {
166 if (event.type === "welcome") {
167 emitWelcome(event.payload);
168 }
169 }),
170 client.subscribeConfig((event) => {
171 applyServerConfigEvent(event);
172 }),
173 ];
174
175 if (getServerConfig() === null) {
176 void client
177 .getConfig()
178 .then((config) => {
179 if (disposed || getServerConfig() !== null) {
180 return;
181 }
182 setServerConfigSnapshot(config);
183 })
184 .catch(() => undefined);
185 }
186
187 return () => {
188 disposed = true;
189 for (const cleanup of cleanups) {
190 cleanup();
191 }
192 };
193}
194
195export function resetServerStateForTests() {
196 resetAppAtomRegistryForTests();
197}
198
199function resolveServerConfig(config: ServerConfig): void {
200 appAtomRegistry.set(serverConfigAtom, config);
201}
202
203function emitProvidersUpdated(payload: ServerProviderUpdatedPayload): void {
204 appAtomRegistry.set(providersUpdatedAtom, payload);
205}
206
207function emitServerConfigUpdated(
208 payload: ServerConfigUpdatedPayload,
209 source: ServerConfigUpdateSource,
210): void {
211 appAtomRegistry.set(serverConfigUpdatedAtom, { payload, source });
212}
213
214function subscribeLatest<A>(
215 atom: Atom.Atom<A | null>,
216 listener: (value: NonNullable<A>) => void,
217): () => void {
218 return appAtomRegistry.subscribe(
219 atom,
220 (value) => {
221 if (value === null) {
222 return;
223 }
224 listener(value as NonNullable<A>);
225 },
226 { immediate: true },
227 );
228}
229
230function useLatestAtomSubscription<A>(
231 atom: Atom.Atom<A | null>,
232 listener: (value: NonNullable<A>) => void,
233) {
234 useAtomSubscribe(
235 atom,
236 (value) => {
237 if (value === null) {
238 return;
239 }
240 listener(value as NonNullable<A>);
241 },
242 { immediate: true },
243 );
244}
245
246export function useServerConfig(): ServerConfig | null {
247 return useAtomValue(serverConfigAtom);
248}
249
250export function useServerSettings(): ServerSettings {
251 return useAtomValue(serverConfigAtom, selectSettings);
252}
253
254export function useServerProviders(): ReadonlyArray<ServerProvider> {
255 return useAtomValue(serverConfigAtom, selectProviders);
256}
257
258export function useServerKeybindings(): ServerConfig["keybindings"] {
259 return useAtomValue(serverConfigAtom, selectKeybindings);
260}
261
262export function useServerAvailableEditors(): ReadonlyArray<EditorId> {
263 return useAtomValue(serverConfigAtom, selectAvailableEditors);
264}
265
266export function useServerKeybindingsConfigPath(): string | null {
267 return useAtomValue(serverConfigAtom, selectKeybindingsConfigPath);
268}
269
270export function useServerWelcomeSubscription(
271 listener: (payload: ServerLifecycleWelcomePayload) => void,
272): void {
273 useLatestAtomSubscription(welcomeAtom, listener);
274}
275
276export function useServerConfigUpdatedSubscription(
277 listener: (notification: ServerConfigUpdatedNotification) => void,
278): void {
279 useLatestAtomSubscription(serverConfigUpdatedAtom, listener);
280}