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