Open History to see the last commit
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;
41}
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);
49}
50
51function isPlainObject(value: unknown): value is Record<string, unknown> {
52 return typeof value === "object" && value !== null && !Array.isArray(value);
53}
54
55export function isConnectedWithConfig(
56 environment: Pick<ScopedSettingsEnvironment, "connection" | "serverConfig">,
57) {
58 return environment.connection.phase === "connected" && environment.serverConfig !== null;
59}
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 };
77}
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>>;
85}
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 );
129}
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 );
142}
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 };
155}
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";
173}
174
175interface ScopedServerWrite {
176 readonly environmentId: EnvironmentId;
177 readonly label: string;
178 readonly patch: ServerSettingsPatch;
179 readonly previous: ServerSettings;
180}
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()];
218}
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) };
225}
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 // Object-valued keys arrive as partial patches (the writing style
252 // rows send one field); an override entry stores the whole value,
253 // so complete the patch from the target's effective value.
254 const effective = resolveProjectSettings(settings, projectId).settings;
255 const next: Record<string, unknown> = { ...current };
256 for (const [key, value] of Object.entries<unknown>(serverPatch)) {
257 if (key === "worktreeCleanup" && serverPatch.worktreeCleanup?.mode === "custom") {
258 next[key] = {
259 mode: "custom",
260 rules: {
261 ...resolveWorktreeCleanup(settings, projectId),
262 ...serverPatch.worktreeCleanup.rules,
263 },
264 };
265 continue;
266 }
267 // A picker's "Inherit" sends null; for keys whose override
268 // cannot store null that means remove the override.
269 if (
270 value === null &&
271 !isNullableProjectSettingsOverride(key as ProjectScopedServerSettingKey)
272 ) {
273 delete next[key];
274 continue;
275 }
276 const base: unknown = effective[key as keyof ServerSettings];
277 // A new model must not inherit the previous model's options.
278 if (
279 isPlainObject(value) &&
280 isPlainObject(base) &&
281 (key === "defaultModelSelection" ||
282 key === "sourceControlWriterModelSelection" ||
283 key === "reviewGuideModelSelection" ||
284 key === "textGenerationModelSelection") &&
285 (value.instanceId !== undefined || value.model !== undefined)
286 ) {
287 next[key] = { instanceId: base.instanceId, model: base.model, ...value };
288 continue;
289 }
290 next[key] =
291 isPlainObject(value) && isPlainObject(base) ? { ...base, ...value } : value;
292 }
293 return next as ProjectSettingsOverrides;
294 })
295 : scope.kind === "all" || scope.kind === "environment"
296 ? connectedEnvironments.flatMap((environment) => {
297 const previous = environment.serverConfig?.settings;
298 if (!previous) return [];
299 return [
300 {
301 environmentId: environment.environmentId,
302 label: environment.label,
303 previous,
304 patch: forDestination(
305 previous,
306 previous.worktreeCleanup != null &&
307 serverPatch.storageCleanup &&
308 Object.keys(serverPatch.storageCleanup).some((key) =>
309 key.startsWith("worktree"),
310 )
311 ? {
312 ...serverPatch,
313 worktreeCleanup: {
314 mode: "custom",
315 rules: {
316 ...resolveWorktreeCleanup(previous, null),
317 ...Object.fromEntries(
318 Object.entries(serverPatch.storageCleanup).filter(([key]) =>
319 key.startsWith("worktree"),
320 ),
321 ),
322 },
323 },
324 }
325 : serverPatch,
326 ),
327 },
328 ];
329 })
330 : [];
331 const hasClientWrite = Object.keys(clientPatch).length > 0;
332 const hasWrite = hasClientWrite || serverWrites.length > 0;
333 const unavailableReason =
334 hasWrite || Object.keys(patch).length === 0
335 ? null
336 : scope.kind === "unavailable"
337 ? scope.message
338 : unscopableKeys.length > 0
339 ? "This setting is environment-wide and cannot be overridden by a project."
340 : isProjectScope
341 ? "Connect the selected checkouts, or update their environments, to save a project override."
342 : `Connect ${scope.kind === "environment" ? scope.label : "an environment"} to save this setting.`;
343 return { clientPatch, hasClientWrite, serverWrites, unavailableReason };
344}
345
346export function planScopedSettingsClear(
347 scope: ResolvedSettingsScope,
348 environments: readonly ScopedSettingsEnvironment[],
349 keys: readonly ProjectScopedServerSettingKey[],
350) {
351 const serverWrites =
352 scope.kind === "project" || scope.kind === "checkout"
353 ? projectOverrideWrites(scope, environments, (_current, settings, projectId) =>
354 clearProjectSettingsOverrides(settings, projectId, keys),
355 )
356 : [];
357 return {
358 clientPatch: {} as ClientSettingsPatch,
359 hasClientWrite: false,
360 serverWrites,
361 unavailableReason:
362 serverWrites.length > 0
363 ? null
364 : "Connect the selected checkouts, or update their environments, to reset this override.",
365 };
366}
367
368export interface ProjectOverrideEntry {
369 readonly environmentId: EnvironmentId;
370 readonly projectId: ProjectId;
371}
372
373export function listProjectOverrides(
374 environments: readonly ScopedSettingsEnvironment[],
375 keys: readonly (keyof ServerSettings)[],
376): readonly ProjectOverrideEntry[] {
377 const scoped = keys.filter(isProjectScopedSettingKey);
378 if (scoped.length === 0) return [];
379 return environments.flatMap((environment) => {
380 const overrides = environment.serverConfig?.settings.projectSettingsOverrides;
381 if (!overrides) return [];
382 return Object.entries(overrides).flatMap(([projectId, entry]) =>
383 scoped.some((key) => Object.hasOwn(entry, key))
384 ? [{ environmentId: environment.environmentId, projectId: projectId as ProjectId }]
385 : [],
386 );
387 });
388}
389
390export function planProjectOverridesClear(
391 environments: readonly ScopedSettingsEnvironment[],
392 entries: readonly ProjectOverrideEntry[],
393 keys: readonly ProjectScopedServerSettingKey[],
394) {
395 const byId = new Map(environments.map((environment) => [environment.environmentId, environment]));
396 const writes = new Map<EnvironmentId, ScopedServerWrite>();
397 for (const { environmentId, projectId } of entries) {
398 const environment = byId.get(environmentId);
399 if (!environment?.serverConfig || environment.connection.phase !== "connected") continue;
400 const settings = environment.serverConfig.settings;
401 const existing = writes.get(environmentId);
402 writes.set(environmentId, {
403 environmentId,
404 label: environment.label,
405 previous: settings,
406 patch: {
407 projectSettingsOverrides: {
408 ...existing?.patch.projectSettingsOverrides,
409 [projectId]: clearProjectSettingsOverrides(settings, projectId, keys),
410 },
411 },
412 });
413 }
414 const serverWrites = [...writes.values()];
415 return {
416 clientPatch: {} as ClientSettingsPatch,
417 hasClientWrite: false,
418 serverWrites,
419 unavailableReason:
420 serverWrites.length > 0 ? null : "Connect the environments to reset these overrides.",
421 };
422}
423
424function writeWasDropped(value: unknown, before: unknown, saved: unknown): boolean {
425 if (value === null) return before != null && Equal.equals(saved, before);
426 if (isPlainObject(value) && !Array.isArray(before) && !Array.isArray(saved)) {
427 const field = (source: unknown, key: string) =>
428 isPlainObject(source) ? source[key] : undefined;
429 return Object.entries(value).some(([key, next]) =>
430 writeWasDropped(next, field(before, key), field(saved, key)),
431 );
432 }
433 const unchanged =
434 typeof value === "string" && typeof before === "string"
435 ? value.trim() === before
436 : Equal.equals(value, before);
437 return !unchanged && Equal.equals(saved, before);
438}
439
440/**
441 * An older server drops keys it does not know, top-level or nested, and still
442 * succeeds. Left unreported, the row stays mixed forever.
443 */
444function droppedSettingKeys(write: ScopedServerWrite, saved: ServerSettings | undefined) {
445 if (saved === undefined) return [];
446 return Object.entries(write.patch).flatMap(([key, value]) =>
447 writeWasDropped(
448 value,
449 write.previous[key as keyof ServerSettings],
450 saved[key as keyof ServerSettings],
451 )
452 ? [key]
453 : [],
454 );
455}
456
457export async function persistScopedSettingsPatch(
458 plan: ReturnType<typeof planScopedSettingsPatch>,
459 persistServer: (input: {
460 environmentId: EnvironmentId;
461 input: { patch: ServerSettingsPatch };
462 }) => Promise<{
463 readonly _tag: "Success" | "Failure";
464 readonly cause?: Cause.Cause<unknown>;
465 readonly value?: ServerSettings;
466 }>,
467 persistClient: (patch: ClientSettingsPatch) => void,
468) {
469 if (plan.hasClientWrite) persistClient(plan.clientPatch);
470 const results = await Promise.allSettled(
471 plan.serverWrites.map(({ environmentId, patch }) =>
472 persistServer({ environmentId, input: { patch } }),
473 ),
474 );
475 const saved = (index: number) => {
476 const result = results[index];
477 return (
478 result?.status === "fulfilled" &&
479 result.value._tag === "Success" &&
480 droppedSettingKeys(plan.serverWrites[index]!, result.value.value).length === 0
481 );
482 };
483 const failedEnvironments = plan.serverWrites.flatMap((environment, index) => {
484 if (saved(index)) return [];
485 const result = results[index];
486 if (result?.status === "fulfilled" && result.value._tag === "Success") {
487 return [
488 {
489 ...environment,
490 message: "This environment does not support this setting. Update T3 Code on it.",
491 },
492 ];
493 }
494 const error: unknown =
495 result?.status === "rejected"
496 ? result.reason
497 : result?.status === "fulfilled" && result.value.cause
498 ? Cause.squash(result.value.cause)
499 : undefined;
500 return [
501 {
502 ...environment,
503 message:
504 error instanceof Error
505 ? error.message
506 : "The save failed. Try reconnecting and saving again.",
507 },
508 ];
509 });
510 const savedEnvironments = plan.serverWrites.filter((_, index) => saved(index));
511 return {
512 failedEnvironments,
513 savedEnvironments,
514 savedEnvironmentCount: savedEnvironments.length,
515 };
516}