Open History to see the last commit
1import {
2 DEFAULT_SERVER_SETTINGS,
3 type EditorId,
4 type EnvironmentId,
5 type EnvironmentTheme,
6 type ServerConfig,
7 type ServerConfigStreamEvent,
8 type ServerLifecycleLegacyThreadMigrationPayload,
9 type ServerLifecycleWelcomePayload,
10 type ServerProvider,
11 type ServerSettings,
12} from "@t3tools/contracts";
13import {
14 AVAILABLE_CONNECTION_STATE,
15 presentEnvironmentConnection,
16 type EnvironmentPresentation,
17} from "@t3tools/client-runtime/connection";
18import { createServerEnvironmentAtoms } from "@t3tools/client-runtime/state/server";
19import { createOutdatedServerUpdateCommand } from "@t3tools/client-runtime/state/outdatedServerUpdate";
20import { createEnvironmentServerConfigsAtom } from "@t3tools/client-runtime/state/shell";
21import { mergeWithDefaultKeybindings } from "@t3tools/shared/keybindings";
22import * as Option from "effect/Option";
23import { AsyncResult, Atom } from "effect/reactivity";
24
25import { isConnectedWithConfig } from "../components/settings/scopedSettings";
26import { environmentCatalog } from "../connection/catalog";
27import { connectionAtomRuntime } from "../connection/runtime";
28import { environmentAtomList } from "./environmentAtomList";
29import { primaryEnvironmentIdAtom } from "./primaryEnvironment";
30import { environmentSession } from "./session";
31import { reuseProvidersIgnoringCheckedAt } from "./serverProviders.logic";
32
33// Only the primary environment's themes are rendered, but which environment is primary changes
34// at runtime and the subscription payload is fixed when it is established -- gating on "primary
35// right now" would leave a newly promoted environment with no themes until it reconnected.
36export const serverEnvironment = createServerEnvironmentAtoms(connectionAtomRuntime, {
37 initialConfigValueAtom: environmentSession.initialConfigValueAtom,
38 environmentThemes: true,
39 usageLimitSources: true,
40 usageLimitsCommand: true,
41});
42export const environmentUpdateStatesAtom = environmentAtomList(
43 "web-environment-update-states",
44 serverEnvironment.updateStateAtom,
45);
46export const updateOutdatedServer = createOutdatedServerUpdateCommand(connectionAtomRuntime);
47export const environmentServerConfigsAtom = createEnvironmentServerConfigsAtom({
48 catalogValueAtom: environmentCatalog.catalogValueAtom,
49 serverConfigValueAtom: serverEnvironment.configValueAtom,
50});
51
52interface PrimaryServerState {
53 readonly config: ServerConfig | null;
54 readonly latestEvent: ServerConfigStreamEvent | null;
55 readonly welcome: ServerLifecycleWelcomePayload | null;
56}
57
58const EMPTY_AVAILABLE_EDITORS: ReadonlyArray<EditorId> = [];
59export const EMPTY_SERVER_PROVIDERS: ReadonlyArray<ServerProvider> = [];
60const EMPTY_PRIMARY_SERVER_STATE: PrimaryServerState = {
61 config: null,
62 latestEvent: null,
63 welcome: null,
64};
65
66const primaryServerStateAtom = Atom.make((get): PrimaryServerState => {
67 const environmentId = get(primaryEnvironmentIdAtom);
68 if (environmentId === null) {
69 return EMPTY_PRIMARY_SERVER_STATE;
70 }
71
72 const target = { environmentId, input: {} };
73 const configProjection = Option.getOrNull(
74 AsyncResult.value(get(serverEnvironment.configProjection(target))),
75 );
76 const welcome = Option.getOrNull(AsyncResult.value(get(serverEnvironment.welcome(target))));
77
78 return {
79 config: get(serverEnvironment.configValueAtom(environmentId)),
80 latestEvent: configProjection?.latestEvent ?? null,
81 welcome,
82 };
83}).pipe(Atom.withLabel("web-primary-server-state"));
84
85export const primaryServerConfigAtom = Atom.make(
86 (get): ServerConfig | null => get(primaryServerStateAtom).config,
87).pipe(Atom.withLabel("web-primary-server-config"));
88
89export const primaryServerConfigEventAtom = Atom.make(
90 (get): ServerConfigStreamEvent | null => get(primaryServerStateAtom).latestEvent,
91).pipe(Atom.withLabel("web-primary-server-config-event"));
92
93export const primaryServerWelcomeAtom = Atom.make(
94 (get): ServerLifecycleWelcomePayload | null => get(primaryServerStateAtom).welcome,
95).pipe(Atom.withLabel("web-primary-server-welcome"));
96
97export const primaryServerLegacyThreadMigrationAtom = Atom.make(
98 (get): ServerLifecycleLegacyThreadMigrationPayload | null => {
99 const environmentId = get(primaryEnvironmentIdAtom);
100 if (environmentId === null) {
101 return null;
102 }
103 return Option.getOrNull(
104 AsyncResult.value(get(serverEnvironment.legacyThreadMigration({ environmentId, input: {} }))),
105 );
106 },
107).pipe(Atom.withLabel("web-primary-server-legacy-thread-migration"));
108
109export const primaryServerSettingsAtom = Atom.make(
110 (get): ServerSettings => get(primaryServerConfigAtom)?.settings ?? DEFAULT_SERVER_SETTINGS,
111).pipe(Atom.withLabel("web-primary-server-settings"));
112
113export const primaryServerProvidersAtom = Atom.make(
114 (get): ReadonlyArray<ServerProvider> =>
115 get(primaryServerConfigAtom)?.providers ?? EMPTY_SERVER_PROVIDERS,
116).pipe(Atom.withLabel("web-primary-server-providers"));
117
118/** Without a primary, global shortcuts follow unscoped Settings. */
119export function createShortcutKeybindingsAtom(input: {
120 readonly primaryEnvironmentIdAtom: Atom.Atom<EnvironmentId | null>;
121 readonly primaryConfigAtom: Atom.Atom<ServerConfig | null>;
122 readonly environmentsAtom: Atom.Atom<
123 ReadonlyMap<EnvironmentId, Pick<EnvironmentPresentation, "connection" | "serverConfig">>
124 >;
125}) {
126 // Selected before merging, so unrelated config updates keep the merged array.
127 const customAtom = Atom.make((get) => {
128 if (get(input.primaryEnvironmentIdAtom) !== null) {
129 // A primary stays authoritative while its config loads.
130 return get(input.primaryConfigAtom)?.keybindings ?? null;
131 }
132 const environments = [...get(input.environmentsAtom).values()];
133 return environments.find(isConnectedWithConfig)?.serverConfig?.keybindings ?? null;
134 });
135 return Atom.make((get): ServerConfig["keybindings"] =>
136 mergeWithDefaultKeybindings(get(customAtom) ?? []),
137 );
138}
139
140// Settings' presentations import this module; mirror their catalog order and
141// connection presentation here to avoid a cycle.
142const environmentConnectionsAtom = Atom.make((get) => {
143 const environments = new Map<
144 EnvironmentId,
145 Pick<EnvironmentPresentation, "connection" | "serverConfig">
146 >();
147 for (const [environmentId, entry] of get(environmentCatalog.catalogValueAtom).entries) {
148 const state = Option.getOrElse(
149 AsyncResult.value(get(environmentCatalog.stateAtom(environmentId))),
150 () => AVAILABLE_CONNECTION_STATE,
151 );
152 environments.set(environmentId, {
153 connection:
154 entry.unsupportedReason === undefined
155 ? presentEnvironmentConnection(state)
156 : { phase: "unsupported", error: entry.unsupportedReason, traceId: null },
157 serverConfig: get(serverEnvironment.configValueAtom(environmentId)),
158 });
159 }
160 return environments;
161});
162
163export const primaryServerKeybindingsAtom = createShortcutKeybindingsAtom({
164 primaryEnvironmentIdAtom,
165 primaryConfigAtom: primaryServerConfigAtom,
166 environmentsAtom: environmentConnectionsAtom,
167}).pipe(Atom.withLabel("web-primary-server-keybindings"));
168
169export const primaryServerAvailableEditorsAtom = Atom.make(
170 (get): ReadonlyArray<EditorId> =>
171 get(primaryServerConfigAtom)?.availableEditors ?? EMPTY_AVAILABLE_EDITORS,
172).pipe(Atom.withLabel("web-primary-server-available-editors"));
173
174const EMPTY_ENVIRONMENT_THEMES: ReadonlyArray<EnvironmentTheme> = [];
175
176export const primaryServerEnvironmentThemesAtom = Atom.make(
177 (get): ReadonlyArray<EnvironmentTheme> =>
178 get(primaryServerConfigAtom)?.environmentThemes ?? EMPTY_ENVIRONMENT_THEMES,
179).pipe(Atom.withLabel("web-primary-server-environment-themes"));
180
181/** Providers for views that do not show `checkedAt`; see {@link reuseProvidersIgnoringCheckedAt}. */
182export const providersIgnoringCheckedAtAtom = Atom.family((environmentId: EnvironmentId) =>
183 Atom.make((get): ReadonlyArray<ServerProvider> =>
184 reuseProvidersIgnoringCheckedAt(
185 Option.getOrNull(get.self<ReadonlyArray<ServerProvider>>()),
186 get(serverEnvironment.providersValueAtom(environmentId)) ?? EMPTY_SERVER_PROVIDERS,
187 ),
188 ).pipe(Atom.withLabel(`web-providers-ignoring-checked-at:${environmentId}`)),
189);