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

scopedSettings.ts

511 lines18.9 KB

1import {
2 ClientSettingsSchema,
3 type ClientSettingsPatch,
4 type EnvironmentId,
5 globalIdleCompaction,
6 idleCompactionPatch,
7 isNullableProjectSettingsOverride,
8 readsIdleCompactionModes,
9 PROJECT_SCOPED_SERVER_SETTING_KEYS,
10 type ProjectId,
11 type ProjectScopedServerSettingKey,
12 type ProjectSettingsOverrides,
13 ServerSettings,
14 type T3ProjectFile,
15 type ServerSettingsPatch,
16} from "@t3tools/contracts";
17import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
18import {
19 clearProjectSettingsOverrides,
20 resolveProjectSettings,
21 resolveWorktreeCleanup,
22 type ProjectSettingSource,
23} from "@t3tools/shared/projectSettings";
24import * as Equal from "effect/Equal";
25import * as Cause from "effect/Cause";
26​
27import type { ResolvedSettingsScope } from "./settingsScope";
28​
29export type ScopedSettingsPatch = ServerSettingsPatch & ClientSettingsPatch;
30​
31interface ScopedSettingsEnvironment {
32 readonly environmentId: EnvironmentId;
33 readonly label: string;
34 readonly connection: { readonly phase: EnvironmentConnectionPhase };
35 readonly serverConfig: {
36 readonly settings: ServerSettings;
37 readonly environment?: {
38 readonly capabilities: { readonly projectSettingsOverrides?: boolean | undefined };
39 };
40 } | null;
42​
43const SERVER_KEYS = new Set<string>(Object.keys(ServerSettings.fields));
44const CLIENT_KEYS = new Set<string>(Object.keys(ClientSettingsSchema.fields));
45const PROJECT_SCOPED_KEYS = new Set<string>(PROJECT_SCOPED_SERVER_SETTING_KEYS);
46​
47export function isProjectScopedSettingKey(key: string): key is ProjectScopedServerSettingKey {
48 return PROJECT_SCOPED_KEYS.has(key);
50​
51function isPlainObject(value: unknown): value is Record<string, unknown> {
52 return typeof value === "object" && value !== null && !Array.isArray(value);
54​
55export function isConnectedWithConfig(
56 environment: Pick<ScopedSettingsEnvironment, "connection" | "serverConfig">,
57) {
58 return environment.connection.phase === "connected" && environment.serverConfig !== null;
60​
61/** The representative supplies display values, never the set of write targets. */
62export function selectScopedSettingsEnvironments<T extends ScopedSettingsEnvironment>(
63 scope: ResolvedSettingsScope,
64 available: readonly T[],
65 primaryEnvironmentId: EnvironmentId | null,
66) {
67 const selectedIds = new Set(scope.environmentIds);
68 const environments = available.filter((environment) =>
69 selectedIds.has(environment.environmentId),
70 );
71 const connectedEnvironments = environments.filter(isConnectedWithConfig);
72 const environment =
73 connectedEnvironments.find((candidate) => candidate.environmentId === primaryEnvironmentId) ??
74 connectedEnvironments[0] ??
75 null;
76 return { environments, connectedEnvironments, environment };
78​
79export interface ScopedSettingsTarget {
80 readonly environmentId: EnvironmentId;
81 readonly label: string;
82 readonly projectId: ProjectId | null;
83 readonly settings: ServerSettings;
84 readonly sources: Readonly<Record<ProjectScopedServerSettingKey, ProjectSettingSource>>;
86​
87export function resolveScopedSettingsTargets(
88 scope: ResolvedSettingsScope,
89 connectedEnvironments: readonly ScopedSettingsEnvironment[],
90 // A member absent here has no file tier yet; null is a missing or invalid file.
91 projectFiles?: ReadonlyMap<string, T3ProjectFile | null>,
92): readonly ScopedSettingsTarget[] {
93 const byId = new Map(
94 connectedEnvironments.map((environment) => [environment.environmentId, environment]),
95 );
96 if (scope.kind === "project" || scope.kind === "checkout") {
97 return scope.members.flatMap((member) => {
98 const environment = byId.get(member.environmentId);
99 if (!environment?.serverConfig) return [];
100 const projectFile = projectFiles?.get(member.physicalProjectKey);
101 const resolved =
102 projectFile === undefined
103 ? resolveProjectSettings(environment.serverConfig.settings, member.id)
104 : resolveProjectSettings(environment.serverConfig.settings, member.id, null, projectFile);
105 return [
106 {
107 environmentId: member.environmentId,
108 label: environment.label,
109 projectId: member.id,
110 settings: resolved.settings,
111 sources: resolved.sources,
112 },
113 ];
114 });
115 }
116 return connectedEnvironments.flatMap((environment) =>
117 environment.serverConfig
118 ? [
119 {
120 environmentId: environment.environmentId,
121 label: environment.label,
122 projectId: null,
123 settings: environment.serverConfig.settings,
124 sources: resolveProjectSettings(environment.serverConfig.settings, null).sources,
125 },
126 ]
127 : [],
128 );
130​
131export function scopedSettingsAreMixed(
132 targets: readonly Pick<ScopedSettingsTarget, "settings">[],
133 keys: readonly (keyof ServerSettings)[],
134): boolean {
135 const first = targets[0];
136 return (
137 first !== undefined &&
138 targets.some((candidate) =>
139 keys.some((key) => !Equal.equals(first.settings[key], candidate.settings[key])),
140 )
141 );
143​
144/**
145 * Servers store the idle compaction mode differently by version, so selected
146 * environments are compared by the mode each resolves to, and "Never" is offered
147 * only when every one of them can store it.
148 */
149export function scopedIdleCompaction(targets: readonly Pick<ScopedSettingsTarget, "settings">[]) {
150 const modes = targets.map((candidate) => globalIdleCompaction(candidate.settings));
151 return {
152 mixed: modes.some((mode) => mode !== modes[0]),
153 neverAvailable: targets.every((candidate) => readsIdleCompactionModes(candidate.settings)),
154 };
156​
157export type ScopedSettingSource = ProjectSettingSource | "mixed";
158​
159export function scopedSettingsSource(
160 targets: readonly Pick<ScopedSettingsTarget, "sources">[],
161 keys: readonly (keyof ServerSettings)[],
162): ScopedSettingSource {
163 const scoped = keys.filter(isProjectScopedSettingKey);
164 if (scoped.length === 0 || targets.length === 0) return "environment";
165 const sources = new Set(targets.flatMap((target) => scoped.map((key) => target.sources[key])));
166 return sources.size > 1
167 ? "mixed"
168 : sources.has("project")
169 ? "project"
170 : sources.has("t3.json")
171 ? "t3.json"
172 : "environment";
174​
175interface ScopedServerWrite {
176 readonly environmentId: EnvironmentId;
177 readonly label: string;
178 readonly patch: ServerSettingsPatch;
179 readonly previous: ServerSettings;
181​
182function projectOverrideWrites(
183 scope: Extract<ResolvedSettingsScope, { kind: "project" | "checkout" }>,
184 environments: readonly ScopedSettingsEnvironment[],
185 update: (
186 current: ProjectSettingsOverrides,
187 settings: ServerSettings,
188 projectId: ProjectId,
189 ) => ProjectSettingsOverrides | null,
190): ScopedServerWrite[] {
191 const byId = new Map(environments.map((environment) => [environment.environmentId, environment]));
192 const writes = new Map<EnvironmentId, ScopedServerWrite>();
193 for (const member of scope.members) {
194 const environment = byId.get(member.environmentId);
195 if (
196 !environment?.serverConfig ||
197 environment.connection.phase !== "connected" ||
198 environment.serverConfig.environment?.capabilities.projectSettingsOverrides !== true
199 ) {
200 continue;
201 }
202 const settings = environment.serverConfig.settings;
203 const entry = update(settings.projectSettingsOverrides[member.id] ?? {}, settings, member.id);
204 const existing = writes.get(member.environmentId);
205 writes.set(member.environmentId, {
206 environmentId: member.environmentId,
207 label: environment.label,
208 previous: settings,
209 patch: {
210 projectSettingsOverrides: {
211 ...existing?.patch.projectSettingsOverrides,
212 [member.id]: entry,
213 },
214 },
215 });
216 }
217 return [...writes.values()];
219​
220/** Puts an idle compaction mode in the form each destination server reads. */
221function forDestination(previous: ServerSettings, patch: ServerSettingsPatch): ServerSettingsPatch {
222 if (patch.idleCompaction === undefined) return patch;
223 const { idleCompaction, compactIdleThreads: _legacy, ...rest } = patch;
224 return { ...rest, ...idleCompactionPatch(previous, idleCompaction) };
226​
227export function planScopedSettingsPatch(
228 scope: ResolvedSettingsScope,
229 environments: readonly ScopedSettingsEnvironment[],
230 patch: ScopedSettingsPatch,
231) {
232 const clientPatch = Object.fromEntries(
233 Object.entries(patch).filter(([key]) => CLIENT_KEYS.has(key) && !SERVER_KEYS.has(key)),
234 ) as ClientSettingsPatch;
235 const serverPatch = Object.fromEntries(
236 Object.entries(patch).filter(([key]) => SERVER_KEYS.has(key)),
237 ) as ServerSettingsPatch;
238 const serverKeys = Object.keys(serverPatch);
239 const { connectedEnvironments } = selectScopedSettingsEnvironments(scope, environments, null);
240 const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
241 const unscopableKeys = isProjectScope
242 ? serverKeys.filter((key) => !isProjectScopedSettingKey(key))
243 : [];
244 const serverWrites: ScopedServerWrite[] =
245 serverKeys.length === 0
246 ? []
247 : isProjectScope
248 ? unscopableKeys.length > 0
249 ? []
250 : projectOverrideWrites(scope, environments, (current, settings, projectId) => {
251 // Override entries store whole objects; complete partial patches from each target's effective
252 // value.
253 const effective = resolveProjectSettings(settings, projectId).settings;
254 const next: Record<string, unknown> = { ...current };
255 for (const [key, value] of Object.entries<unknown>(serverPatch)) {
256 if (key === "worktreeCleanup" && serverPatch.worktreeCleanup?.mode === "custom") {
257 next[key] = {
258 mode: "custom",
259 rules: {
260 ...resolveWorktreeCleanup(settings, projectId),
261 ...serverPatch.worktreeCleanup.rules,
262 },
263 };
264 continue;
265 }
266 // Inherit sends null; remove overrides whose keys cannot store null.
267 if (
268 value === null &&
269 !isNullableProjectSettingsOverride(key as ProjectScopedServerSettingKey)
270 ) {
271 delete next[key];
272 continue;
273 }
274 const base: unknown = effective[key as keyof ServerSettings];
275 // A new model must not inherit the previous model's options.
276 if (
277 isPlainObject(value) &&
278 isPlainObject(base) &&
279 (key === "defaultModelSelection" ||
280 key === "sourceControlWriterModelSelection" ||
281 key === "reviewGuideModelSelection" ||
282 key === "textGenerationModelSelection") &&
283 (value.instanceId !== undefined || value.model !== undefined)
284 ) {
285 next[key] = { instanceId: base.instanceId, model: base.model, ...value };
286 continue;
287 }
288 next[key] =
289 isPlainObject(value) && isPlainObject(base) ? { ...base, ...value } : value;
290 }
291 return next as ProjectSettingsOverrides;
292 })
293 : scope.kind === "all" || scope.kind === "environment"
294 ? connectedEnvironments.flatMap((environment) => {
295 const previous = environment.serverConfig?.settings;
296 if (!previous) return [];
297 return [
298 {
299 environmentId: environment.environmentId,
300 label: environment.label,
301 previous,
302 patch: forDestination(
303 previous,
304 previous.worktreeCleanup != null &&
305 serverPatch.storageCleanup &&
306 Object.keys(serverPatch.storageCleanup).some((key) =>
307 key.startsWith("worktree"),
308 )
309 ? {
310 ...serverPatch,
311 worktreeCleanup: {
312 mode: "custom",
313 rules: {
314 ...resolveWorktreeCleanup(previous, null),
315 ...Object.fromEntries(
316 Object.entries(serverPatch.storageCleanup).filter(([key]) =>
317 key.startsWith("worktree"),
318 ),
319 ),
320 },
321 },
322 }
323 : serverPatch,
324 ),
325 },
326 ];
327 })
328 : [];
329 const hasClientWrite = Object.keys(clientPatch).length > 0;
330 const hasWrite = hasClientWrite || serverWrites.length > 0;
331 const unavailableReason =
332 hasWrite || Object.keys(patch).length === 0
333 ? null
334 : scope.kind === "unavailable"
335 ? scope.message
336 : unscopableKeys.length > 0
337 ? "This setting is environment-wide and cannot be overridden by a project."
338 : isProjectScope
339 ? "Connect the selected checkouts, or update their environments, to save a project override."
340 : `Connect ${scope.kind === "environment" ? scope.label : "an environment"} to save this setting.`;
341 return { clientPatch, hasClientWrite, serverWrites, unavailableReason };
343​
344export function planScopedSettingsClear(
345 scope: ResolvedSettingsScope,
346 environments: readonly ScopedSettingsEnvironment[],
347 keys: readonly ProjectScopedServerSettingKey[],
348) {
349 const serverWrites =
350 scope.kind === "project" || scope.kind === "checkout"
351 ? projectOverrideWrites(scope, environments, (_current, settings, projectId) =>
352 clearProjectSettingsOverrides(settings, projectId, keys),
353 )
354 : [];
355 return {
356 clientPatch: {} as ClientSettingsPatch,
357 hasClientWrite: false,
358 serverWrites,
359 unavailableReason:
360 serverWrites.length > 0
361 ? null
362 : "Connect the selected checkouts, or update their environments, to reset this override.",
363 };
365​
366export interface ProjectOverrideEntry {
367 readonly environmentId: EnvironmentId;
368 readonly projectId: ProjectId;
370​
371export function listProjectOverrides(
372 environments: readonly ScopedSettingsEnvironment[],
373 keys: readonly (keyof ServerSettings)[],
374): readonly ProjectOverrideEntry[] {
375 const scoped = keys.filter(isProjectScopedSettingKey);
376 if (scoped.length === 0) return [];
377 return environments.flatMap((environment) => {
378 const overrides = environment.serverConfig?.settings.projectSettingsOverrides;
379 if (!overrides) return [];
380 return Object.entries(overrides).flatMap(([projectId, entry]) =>
381 scoped.some((key) => Object.hasOwn(entry, key))
382 ? [{ environmentId: environment.environmentId, projectId: projectId as ProjectId }]
383 : [],
384 );
385 });
387​
388export function planProjectOverridesClear(
389 environments: readonly ScopedSettingsEnvironment[],
390 entries: readonly ProjectOverrideEntry[],
391 keys: readonly ProjectScopedServerSettingKey[],
392) {
393 const byId = new Map(environments.map((environment) => [environment.environmentId, environment]));
394 const writes = new Map<EnvironmentId, ScopedServerWrite>();
395 for (const { environmentId, projectId } of entries) {
396 const environment = byId.get(environmentId);
397 if (!environment?.serverConfig || environment.connection.phase !== "connected") continue;
398 const settings = environment.serverConfig.settings;
399 const existing = writes.get(environmentId);
400 writes.set(environmentId, {
401 environmentId,
402 label: environment.label,
403 previous: settings,
404 patch: {
405 projectSettingsOverrides: {
406 ...existing?.patch.projectSettingsOverrides,
407 [projectId]: clearProjectSettingsOverrides(settings, projectId, keys),
408 },
409 },
410 });
411 }
412 const serverWrites = [...writes.values()];
413 return {
414 clientPatch: {} as ClientSettingsPatch,
415 hasClientWrite: false,
416 serverWrites,
417 unavailableReason:
418 serverWrites.length > 0 ? null : "Connect the environments to reset these overrides.",
419 };
421​
422function writeWasDropped(value: unknown, before: unknown, saved: unknown): boolean {
423 if (value === null) return before != null && Equal.equals(saved, before);
424 if (isPlainObject(value) && !Array.isArray(before) && !Array.isArray(saved)) {
425 const field = (source: unknown, key: string) =>
426 isPlainObject(source) ? source[key] : undefined;
427 return Object.entries(value).some(([key, next]) =>
428 writeWasDropped(next, field(before, key), field(saved, key)),
429 );
430 }
431 const unchanged =
432 typeof value === "string" && typeof before === "string"
433 ? value.trim() === before
434 : Equal.equals(value, before);
435 return !unchanged && Equal.equals(saved, before);
437​
438/** Older servers silently drop unknown keys; report them so rows cannot stay mixed forever. */
439function droppedSettingKeys(write: ScopedServerWrite, saved: ServerSettings | undefined) {
440 if (saved === undefined) return [];
441 return Object.entries(write.patch).flatMap(([key, value]) =>
442 writeWasDropped(
443 value,
444 write.previous[key as keyof ServerSettings],
445 saved[key as keyof ServerSettings],
446 )
447 ? [key]
448 : [],
449 );
451​
452export async function persistScopedSettingsPatch(
453 plan: ReturnType<typeof planScopedSettingsPatch>,
454 persistServer: (input: {
455 environmentId: EnvironmentId;
456 input: { patch: ServerSettingsPatch };
457 }) => Promise<{
458 readonly _tag: "Success" | "Failure";
459 readonly cause?: Cause.Cause<unknown>;
460 readonly value?: ServerSettings;
461 }>,
462 persistClient: (patch: ClientSettingsPatch) => void,
463) {
464 if (plan.hasClientWrite) persistClient(plan.clientPatch);
465 const results = await Promise.allSettled(
466 plan.serverWrites.map(({ environmentId, patch }) =>
467 persistServer({ environmentId, input: { patch } }),
468 ),
469 );
470 const saved = (index: number) => {
471 const result = results[index];
472 return (
473 result?.status === "fulfilled" &&
474 result.value._tag === "Success" &&
475 droppedSettingKeys(plan.serverWrites[index]!, result.value.value).length === 0
476 );
477 };
478 const failedEnvironments = plan.serverWrites.flatMap((environment, index) => {
479 if (saved(index)) return [];
480 const result = results[index];
481 if (result?.status === "fulfilled" && result.value._tag === "Success") {
482 return [
483 {
484 ...environment,
485 message: "This environment does not support this setting. Update T3 Code on it.",
486 },
487 ];
488 }
489 const error: unknown =
490 result?.status === "rejected"
491 ? result.reason
492 : result?.status === "fulfilled" && result.value.cause
493 ? Cause.squash(result.value.cause)
494 : undefined;
495 return [
496 {
497 ...environment,
498 message:
499 error instanceof Error
500 ? error.message
501 : "The save failed. Try reconnecting and saving again.",
502 },
503 ];
504 });
505 const savedEnvironments = plan.serverWrites.filter((_, index) => saved(index));
506 return {
507 failedEnvironments,
508 savedEnvironments,
509 savedEnvironmentCount: savedEnvironments.length,
510 };