Open History to see the last commit
1import {
2 DEFAULT_SERVER_SETTINGS,
3 type EnvironmentId,
4 type EnvironmentTheme,
5 type ServerConfig,
6 type ServerConfigStreamEvent,
7 type ServerLifecycleLegacyThreadMigrationPayload,
8 type ServerLifecycleWelcomePayload,
9 type ServerProvider,
10 type ServerSettings,
11} from "@t3tools/contracts";
12import {
13 AVAILABLE_CONNECTION_STATE,
14 presentConnectionState,
15 type EnvironmentPresentation,
16} from "@t3tools/client-runtime/connection";
17import { createServerEnvironmentAtoms } from "@t3tools/client-runtime/state/server";
18import { createOutdatedServerUpdateCommand } from "@t3tools/client-runtime/state/outdatedServerUpdate";
19import { createEnvironmentServerConfigsAtom } from "@t3tools/client-runtime/state/shell";
20import { mergeWithDefaultKeybindings } from "@t3tools/shared/keybindings";
21import * as Option from "effect/Option";
22import { AsyncResult, Atom } from "effect/reactivity";
23
24import { isConnectedWithConfig } from "../components/settings/scopedSettings";
25import { environmentCatalog } from "../connection/catalog";
26import { connectionAtomRuntime } from "../connection/runtime";
27import { environmentAtomList } from "./environmentAtomList";
28import { primaryEnvironmentIdAtom, localEnvironmentIdAtom } from "./primaryEnvironment";
29import { environmentSession } from "./session";
30import { reuseProvidersIgnoringCheckedAt } from "./serverProviders.logic";
31
32// Subscribe to every environment's themes; primary can change without reconnecting or updating the subscription.
33export const serverEnvironment = createServerEnvironmentAtoms(connectionAtomRuntime, {
34 initialConfigValueAtom: environmentSession.initialConfigValueAtom,
35 environmentThemes: true,
36 usageLimitSources: true,
37 usageLimitsCommand: true,
38});
39export const environmentUpdateStatesAtom = environmentAtomList(
40 "web-environment-update-states",
41 serverEnvironment.updateStateAtom,
42);
43export const updateOutdatedServer = createOutdatedServerUpdateCommand(connectionAtomRuntime);
44export const environmentServerConfigsAtom = createEnvironmentServerConfigsAtom({
45 catalogValueAtom: environmentCatalog.catalogValueAtom,
46 serverConfigValueAtom: serverEnvironment.configValueAtom,
47});
48
49interface PrimaryServerState {
50 readonly config: ServerConfig | null;
51 readonly latestEvent: ServerConfigStreamEvent | null;
52 readonly welcome: ServerLifecycleWelcomePayload | null;
53}
54
55export const EMPTY_SERVER_PROVIDERS: ReadonlyArray<ServerProvider> = [];
56const EMPTY_PRIMARY_SERVER_STATE: PrimaryServerState = {
57 config: null,
58 latestEvent: null,
59 welcome: null,
60};
61
62const primaryServerStateAtom = Atom.make((get): PrimaryServerState => {
63 const environmentId = get(primaryEnvironmentIdAtom);
64 if (environmentId === null) {
65 return EMPTY_PRIMARY_SERVER_STATE;
66 }
67
68 const target = { environmentId, input: {} };
69 const configProjection = AsyncResult.getOrElse(
70 get(serverEnvironment.configProjection(target)),
71 () => null,
72 );
73 const welcome = AsyncResult.getOrElse(get(serverEnvironment.welcome(target)), () => null);
74
75 return {
76 config: get(serverEnvironment.configValueAtom(environmentId)),
77 latestEvent: configProjection?.latestEvent ?? null,
78 welcome,
79 };
80}).pipe(Atom.withLabel("web-primary-server-state"));
81
82export const primaryServerConfigAtom = Atom.make(
83 (get): ServerConfig | null => get(primaryServerStateAtom).config,
84).pipe(Atom.withLabel("web-primary-server-config"));
85
86// The config cache can outlive the session and predate an opt-out.
87export const primaryRelayTracingAllowedAtom = Atom.make((get): boolean | null => {
88 const environmentId = get(primaryEnvironmentIdAtom);
89 const config =
90 environmentId === null ? null : get(environmentSession.initialConfigValueAtom(environmentId));
91 return config === null ? null : config.observability.relayTracingAllowed !== false;
92}).pipe(Atom.withLabel("web-primary-relay-tracing-allowed"));
93
94export const primaryServerConfigEventAtom = Atom.make(
95 (get): ServerConfigStreamEvent | null => get(primaryServerStateAtom).latestEvent,
96).pipe(Atom.withLabel("web-primary-server-config-event"));
97
98export const primaryServerWelcomeAtom = Atom.make(
99 (get): ServerLifecycleWelcomePayload | null => get(primaryServerStateAtom).welcome,
100).pipe(Atom.withLabel("web-primary-server-welcome"));
101
102export const primaryServerLegacyThreadMigrationAtom = Atom.make(
103 (get): ServerLifecycleLegacyThreadMigrationPayload | null => {
104 const environmentId = get(primaryEnvironmentIdAtom);
105 if (environmentId === null) {
106 return null;
107 }
108 return AsyncResult.getOrElse(
109 get(serverEnvironment.legacyThreadMigration({ environmentId, input: {} })),
110 () => null,
111 );
112 },
113).pipe(Atom.withLabel("web-primary-server-legacy-thread-migration"));
114
115export const primaryServerSettingsAtom = Atom.make(
116 (get): ServerSettings => get(primaryServerConfigAtom)?.settings ?? DEFAULT_SERVER_SETTINGS,
117).pipe(Atom.withLabel("web-primary-server-settings"));
118
119export const primaryServerProvidersAtom = Atom.make(
120 (get): ReadonlyArray<ServerProvider> =>
121 get(primaryServerConfigAtom)?.providers ?? EMPTY_SERVER_PROVIDERS,
122).pipe(Atom.withLabel("web-primary-server-providers"));
123
124/** Without a primary, global shortcuts follow unscoped Settings. */
125export function createShortcutKeybindingsAtom(input: {
126 readonly primaryEnvironmentIdAtom: Atom.Atom<EnvironmentId | null>;
127 readonly primaryConfigAtom: Atom.Atom<ServerConfig | null>;
128 readonly environmentsAtom: Atom.Atom<
129 ReadonlyMap<EnvironmentId, Pick<EnvironmentPresentation, "connection" | "serverConfig">>
130 >;
131}) {
132 // Selected before merging, so unrelated config updates keep the merged array.
133 const customAtom = Atom.make((get) => {
134 if (get(input.primaryEnvironmentIdAtom) !== null) {
135 // A primary stays authoritative while its config loads.
136 return get(input.primaryConfigAtom)?.keybindings ?? null;
137 }
138 const environments = [...get(input.environmentsAtom).values()];
139 return environments.find(isConnectedWithConfig)?.serverConfig?.keybindings ?? null;
140 });
141 return Atom.make((get): ServerConfig["keybindings"] =>
142 mergeWithDefaultKeybindings(get(customAtom) ?? []),
143 );
144}
145
146// Settings' presentations import this module; mirror their catalog order and
147// connection presentation here to avoid a cycle.
148const environmentConnectionsAtom = Atom.make((get) => {
149 const environments = new Map<
150 EnvironmentId,
151 Pick<EnvironmentPresentation, "connection" | "serverConfig">
152 >();
153 for (const [environmentId, entry] of get(environmentCatalog.catalogValueAtom).entries) {
154 const state = AsyncResult.getOrElse(
155 get(environmentCatalog.stateAtom(environmentId)),
156 () => AVAILABLE_CONNECTION_STATE,
157 );
158 environments.set(environmentId, {
159 connection:
160 entry.unsupportedReason === undefined
161 ? presentConnectionState(state)
162 : { phase: "unsupported", error: entry.unsupportedReason, traceId: null },
163 serverConfig: get(serverEnvironment.configValueAtom(environmentId)),
164 });
165 }
166 return environments;
167});
168
169export const primaryServerKeybindingsAtom = createShortcutKeybindingsAtom({
170 primaryEnvironmentIdAtom,
171 primaryConfigAtom: primaryServerConfigAtom,
172 environmentsAtom: environmentConnectionsAtom,
173}).pipe(Atom.withLabel("web-primary-server-keybindings"));
174
175const EMPTY_ENVIRONMENT_THEMES: ReadonlyArray<EnvironmentTheme> = [];
176
177const themeServerConfigAtom = Atom.make((get): ServerConfig | null => {
178 const environmentId = get(localEnvironmentIdAtom);
179 return environmentId === null ? null : get(serverEnvironment.configValueAtom(environmentId));
180}).pipe(Atom.withLabel("web-theme-server-config"));
181
182/**
183 * Null until the theme environment says what it publishes. Cached configs and
184 * snapshots never carry themes, so a capable server has none until its theme
185 * event lands.
186 */
187export const themeServerEnvironmentThemesAtom = Atom.make(
188 (get): ReadonlyArray<EnvironmentTheme> | null => {
189 const config = get(themeServerConfigAtom);
190 if (config === null) return null;
191 if (config.environmentThemes !== undefined) return config.environmentThemes;
192 return config.environment.capabilities.environmentThemes === true
193 ? null
194 : EMPTY_ENVIRONMENT_THEMES;
195 },
196).pipe(Atom.withLabel("web-theme-server-environment-themes"));
197
198export const themeServerSettingsAtom = Atom.make(
199 (get): ServerSettings => get(themeServerConfigAtom)?.settings ?? DEFAULT_SERVER_SETTINGS,
200).pipe(Atom.withLabel("web-theme-server-settings"));
201
202export const providersIgnoringCheckedAtAtom = Atom.family((environmentId: EnvironmentId) =>
203 Atom.make((get): ReadonlyArray<ServerProvider> =>
204 reuseProvidersIgnoringCheckedAt(
205 Option.getOrNull(get.self<ReadonlyArray<ServerProvider>>()),
206 get(serverEnvironment.providersValueAtom(environmentId)) ?? EMPTY_SERVER_PROVIDERS,
207 ),
208 ).pipe(Atom.withLabel(`web-providers-ignoring-checked-at:${environmentId}`)),
209);