Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

serverConfigProjection.ts

220 lines7.8 KB

1import {
2 worstHostPressureLevel,
3 applyServerProviderDeltas,
4 type ServerConfig,
5 type ServerConfigStreamEvent,
6} from "@t3tools/contracts";
7import * as Equal from "effect/Equal";
8import * as Option from "effect/Option";
9​
10export interface ServerConfigProjection {
11 readonly config: ServerConfig;
12 readonly latestEvent: ServerConfigStreamEvent;
13 readonly source: "cache" | "live";
15​
16/**
17 * Published themes, usage-limit sources and host pressure are current machine
18 * state, so a cache could restore a set the machine no longer reports.
19 */
20export function withoutEnvironmentThemes(config: ServerConfig): ServerConfig {
21 if (
22 config.environmentThemes === undefined &&
23 config.usageLimitSources === undefined &&
24 config.hostPressure === undefined
25 ) {
26 return config;
27 }
28 const {
29 environmentThemes: _themes,
30 usageLimitSources: _sources,
31 hostPressure: _pressure,
32 ...rest
33 } = config;
34 return rest;
36​
37/**
38 * Provider pushes, reconnects, and settings writes resend unchanged data.
39 * Reuse deep-equal objects so memoized UI can skip unchanged providers, models, and skills.
40 */
41export function reuseUnchanged<T>(previous: unknown, next: T): T {
42 if (Object.is(previous, next)) return next;
43 if (
44 typeof previous !== "object" ||
45 typeof next !== "object" ||
46 previous === null ||
47 next === null ||
48 Array.isArray(previous) !== Array.isArray(next)
49 ) {
50 return next;
51 }
52 if (Array.isArray(next)) {
53 const before = previous as ReadonlyArray<unknown>;
54 let same = before.length === next.length;
55 const merged = next.map((item, index) => {
56 const reused = reuseUnchanged(before[index], item);
57 if (reused !== before[index]) same = false;
58 return reused;
59 });
60 return (same ? previous : merged) as T;
61 }
62 // Decoded settings carry Durations, which are fresh instances on every push.
63 if (Equal.isEqual(next)) return (Equal.equals(previous, next) ? previous : next) as T;
64 if (Object.getPrototypeOf(next) !== Object.prototype) return next;
65 const before = previous as Record<string, unknown>;
66 const after = next as Record<string, unknown>;
67 const keys = Object.keys(after);
68 let same = keys.length === Object.keys(before).length;
69 const merged: Record<string, unknown> = {};
70 for (const key of keys) {
71 const reused = reuseUnchanged(before[key], after[key]);
72 if (reused !== before[key] || !(key in before)) same = false;
73 merged[key] = reused;
74 }
75 return (same ? previous : merged) as T;
77​
78type ServerProviders = ServerConfig["providers"];
79​
80/**
81 * A provider sent with a catalog digest comes without its slash commands and skills. Keep the
82 * lists this client holds, stale ones too, until it loads the lists the digest stands for.
83 */
84function withHeldProviderCatalogs(
85 previous: ServerProviders | undefined,
86 next: ServerProviders,
87): ServerProviders {
88 if (previous === undefined) return next;
89 return next.map((provider) => {
90 if (provider.catalogDigest === undefined || provider.loadedCatalogDigest !== undefined) {
91 return provider;
92 }
93 const held = previous.find((candidate) => candidate.instanceId === provider.instanceId);
94 if (held === undefined) return provider;
95 return {
96 ...provider,
97 slashCommands: held.slashCommands,
98 skills: held.skills,
99 ...(held.loadedCatalogDigest === undefined
100 ? {}
101 : { loadedCatalogDigest: held.loadedCatalogDigest }),
102 };
103 });
105​
106export function applyServerConfigProjection(
107 current: Option.Option<ServerConfigProjection>,
108 event: ServerConfigStreamEvent,
109): Option.Option<ServerConfigProjection> {
110 switch (event.type) {
111 case "snapshot": {
112 // Wire snapshots never contain published themes. Keep the previous set
113 // until the server sends its authoritative theme event.
114 const carriedThemes = Option.isSome(current)
115 ? current.value.config.environmentThemes
116 : undefined;
117 const carriedSources = Option.isSome(current)
118 ? current.value.config.usageLimitSources
119 : undefined;
120 // A server without the event would never clear carried pressure.
121 const heldPressure = Option.isSome(current) ? current.value.config.hostPressure : undefined;
122 const carriedPressure =
123 heldPressure !== undefined && event.config.environment.capabilities.hostPressure === true
124 ? heldPressure
125 : undefined;
126 const config: ServerConfig = {
127 ...event.config,
128 providers: withHeldProviderCatalogs(
129 Option.getOrUndefined(current)?.config.providers,
130 event.config.providers,
131 ),
132 ...(carriedThemes === undefined ? {} : { environmentThemes: carriedThemes }),
133 ...(carriedSources === undefined ? {} : { usageLimitSources: carriedSources }),
134 ...(carriedPressure === undefined ? {} : { hostPressure: carriedPressure }),
135 };
136 return Option.some({
137 // Every reconnect re-sends the whole config, usually unchanged apart from timestamps.
138 config: Option.isSome(current) ? reuseUnchanged(current.value.config, config) : config,
139 latestEvent: event,
140 source: "live" as const,
141 });
142 }
143 case "keybindingsUpdated":
144 return Option.map(current, (projection) => ({
145 config: {
146 ...projection.config,
147 keybindings: event.payload.keybindings,
148 issues: event.payload.issues,
149 },
150 latestEvent: event,
151 source: "live",
152 }));
153 case "providerStatuses":
154 case "providerStatusDeltas":
155 return Option.map(current, (projection) => {
156 const previous = projection.config.providers;
157 const providers =
158 event.type === "providerStatuses"
159 ? event.payload.providers
160 : applyServerProviderDeltas(previous, event.payload.providers);
161 return {
162 config: {
163 ...projection.config,
164 providers: reuseUnchanged(previous, withHeldProviderCatalogs(previous, providers)),
165 },
166 latestEvent: event,
167 source: "live",
168 };
169 });
170 case "settingsUpdated":
171 return Option.map(current, (projection) => {
172 const settings = reuseUnchanged(projection.config.settings, event.payload.settings);
173 return {
174 config:
175 settings === projection.config.settings
176 ? projection.config
177 : { ...projection.config, settings },
178 latestEvent: event,
179 source: "live",
180 };
181 });
182 case "environmentThemesUpdated":
183 return Option.map(current, (projection) => ({
184 config: {
185 ...projection.config,
186 // Kept when empty: undefined means the theme event has not arrived yet.
187 environmentThemes: event.payload.themes,
188 },
189 latestEvent: event,
190 source: "live",
191 }));
192 case "hostPressureUpdated":
193 return Option.flatMap(current, (projection) => {
194 // The same projection, so screens do not re-render, but still Some so the
195 // session records this `none` and replays it to subscribers holding a warning.
196 const calm = worstHostPressureLevel(event.payload) === "none";
197 if (calm && projection.config.hostPressure === undefined) return current;
198 const { hostPressure: _previous, ...config } = projection.config;
199 return Option.some({
200 config: calm
201 ? config
202 : {
203 ...config,
204 hostPressure: reuseUnchanged(projection.config.hostPressure, event.payload),
205 },
206 latestEvent: event,
207 source: "live",
208 });
209 });
210 case "usageLimitSourcesUpdated":
211 return Option.map(current, (projection) => ({
212 config: {
213 ...projection.config,
214 usageLimitSources: event.payload.sources.length > 0 ? event.payload.sources : undefined,
215 },
216 latestEvent: event,
217 source: "live",
218 }));
219 }