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

scopedSettings.ts

491 lines18.0 KB

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