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 } | null;
38}
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);
46}
47
48function isPlainObject(value: unknown): value is Record<string, unknown> {
49 return typeof value === "object" && value !== null && !Array.isArray(value);
50}
51
52export function isConnectedWithConfig(
53 environment: Pick<ScopedSettingsEnvironment, "connection" | "serverConfig">,
54) {
55 return environment.connection.phase === "connected" && environment.serverConfig !== null;
56}
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 };
74}
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>>;
82}
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 );
126}
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 );
139}
140
141/**
142 * Servers store the idle compaction mode differently by version, so selected
143 * environments are compared by the mode each resolves to, and "Never" is offered
144 * only when every one of them can store it.
145 */
146export function scopedIdleCompaction(targets: readonly Pick<ScopedSettingsTarget, "settings">[]) {
147 const modes = targets.map((candidate) => globalIdleCompaction(candidate.settings));
148 return {
149 mixed: modes.some((mode) => mode !== modes[0]),
150 neverAvailable: targets.every((candidate) => readsIdleCompactionModes(candidate.settings)),
151 };
152}
153
154export type ScopedSettingSource = ProjectSettingSource | "mixed";
155
156export function scopedSettingsSource(
157 targets: readonly Pick<ScopedSettingsTarget, "sources">[],
158 keys: readonly (keyof ServerSettings)[],
159): ScopedSettingSource {
160 const scoped = keys.filter(isProjectScopedSettingKey);
161 if (scoped.length === 0 || targets.length === 0) return "environment";
162 const sources = new Set(targets.flatMap((target) => scoped.map((key) => target.sources[key])));
163 return sources.size > 1
164 ? "mixed"
165 : sources.has("project")
166 ? "project"
167 : sources.has("t3.json")
168 ? "t3.json"
169 : "environment";
170}
171
172interface ScopedServerWrite {
173 readonly environmentId: EnvironmentId;
174 readonly label: string;
175 readonly patch: ServerSettingsPatch;
176 readonly previous: ServerSettings;
177}
178
179function projectOverrideWrites(
180 scope: Extract<ResolvedSettingsScope, { kind: "project" | "checkout" }>,
181 environments: readonly ScopedSettingsEnvironment[],
182 update: (
183 current: ProjectSettingsOverrides,
184 settings: ServerSettings,
185 projectId: ProjectId,
186 ) => ProjectSettingsOverrides | null,
187): ScopedServerWrite[] {
188 const byId = new Map(environments.map((environment) => [environment.environmentId, environment]));
189 const writes = new Map<EnvironmentId, ScopedServerWrite>();
190 for (const member of scope.members) {
191 const environment = byId.get(member.environmentId);
192 if (!environment?.serverConfig || environment.connection.phase !== "connected") {
193 continue;
194 }
195 const settings = environment.serverConfig.settings;
196 const entry = update(settings.projectSettingsOverrides[member.id] ?? {}, settings, member.id);
197 const existing = writes.get(member.environmentId);
198 writes.set(member.environmentId, {
199 environmentId: member.environmentId,
200 label: environment.label,
201 previous: settings,
202 patch: {
203 projectSettingsOverrides: {
204 ...existing?.patch.projectSettingsOverrides,
205 [member.id]: entry,
206 },
207 },
208 });
209 }
210 return [...writes.values()];
211}
212
213/** Puts an idle compaction mode in the form each destination server reads. */
214function forDestination(previous: ServerSettings, patch: ServerSettingsPatch): ServerSettingsPatch {
215 if (patch.idleCompaction === undefined) return patch;
216 const { idleCompaction, compactIdleThreads: _legacy, ...rest } = patch;
217 return { ...rest, ...idleCompactionPatch(previous, idleCompaction) };
218}
219
220export function planScopedSettingsPatch(
221 scope: ResolvedSettingsScope,
222 environments: readonly ScopedSettingsEnvironment[],
223 patch: ScopedSettingsPatch,
224) {
225 const clientPatch = Object.fromEntries(
226 Object.entries(patch).filter(([key]) => CLIENT_KEYS.has(key) && !SERVER_KEYS.has(key)),
227 ) as ClientSettingsPatch;
228 const serverPatch = Object.fromEntries(
229 Object.entries(patch).filter(([key]) => SERVER_KEYS.has(key)),
230 ) as ServerSettingsPatch;
231 const serverKeys = Object.keys(serverPatch);
232 const { connectedEnvironments } = selectScopedSettingsEnvironments(scope, environments, null);
233 const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
234 const unscopableKeys = isProjectScope
235 ? serverKeys.filter((key) => !isProjectScopedSettingKey(key))
236 : [];
237 const serverWrites: ScopedServerWrite[] =
238 serverKeys.length === 0
239 ? []
240 : isProjectScope
241 ? unscopableKeys.length > 0
242 ? []
243 : projectOverrideWrites(scope, environments, (current, settings, projectId) => {
244 // Override entries store whole objects; complete partial patches from each target's effective
245 // value.
246 const effective = resolveProjectSettings(settings, projectId).settings;
247 const next: Record<string, unknown> = { ...current };
248 for (const [key, value] of Object.entries<unknown>(serverPatch)) {
249 if (key === "worktreeCleanup" && serverPatch.worktreeCleanup?.mode === "custom") {
250 next[key] = {
251 mode: "custom",
252 rules: {
253 ...resolveWorktreeCleanup(settings, projectId),
254 ...serverPatch.worktreeCleanup.rules,
255 },
256 };
257 continue;
258 }
259 // Inherit sends null; remove overrides whose keys cannot store null.
260 if (
261 value === null &&
262 !isNullableProjectSettingsOverride(key as ProjectScopedServerSettingKey)
263 ) {
264 delete next[key];
265 continue;
266 }
267 const base: unknown = effective[key as keyof ServerSettings];
268 // A new model must not inherit the previous model's options.
269 if (
270 isPlainObject(value) &&
271 isPlainObject(base) &&
272 (key === "defaultModelSelection" ||
273 key === "sourceControlWriterModelSelection" ||
274 key === "reviewGuideModelSelection" ||
275 key === "textGenerationModelSelection") &&
276 (value.instanceId !== undefined || value.model !== undefined)
277 ) {
278 next[key] = { instanceId: base.instanceId, model: base.model, ...value };
279 continue;
280 }
281 next[key] =
282 isPlainObject(value) && isPlainObject(base) ? { ...base, ...value } : value;
283 }
284 return next as ProjectSettingsOverrides;
285 })
286 : scope.kind === "all" || scope.kind === "environment"
287 ? connectedEnvironments.flatMap((environment) => {
288 const previous = environment.serverConfig?.settings;
289 if (!previous) return [];
290 return [
291 {
292 environmentId: environment.environmentId,
293 label: environment.label,
294 previous,
295 patch: forDestination(
296 previous,
297 previous.worktreeCleanup != null &&
298 serverPatch.storageCleanup &&
299 Object.keys(serverPatch.storageCleanup).some((key) =>
300 key.startsWith("worktree"),
301 )
302 ? {
303 ...serverPatch,
304 worktreeCleanup: {
305 mode: "custom",
306 rules: {
307 ...resolveWorktreeCleanup(previous, null),
308 ...Object.fromEntries(
309 Object.entries(serverPatch.storageCleanup).filter(([key]) =>
310 key.startsWith("worktree"),
311 ),
312 ),
313 },
314 },
315 }
316 : serverPatch,
317 ),
318 },
319 ];
320 })
321 : [];
322 const hasClientWrite = Object.keys(clientPatch).length > 0;
323 const hasWrite = hasClientWrite || serverWrites.length > 0;
324 const unavailableReason =
325 hasWrite || Object.keys(patch).length === 0
326 ? null
327 : scope.kind === "unavailable"
328 ? scope.message
329 : unscopableKeys.length > 0
330 ? "This setting is environment-wide and cannot be overridden by a project."
331 : isProjectScope
332 ? "Connect the selected checkouts, or update their environments, to save a project override."
333 : `Connect ${scope.kind === "environment" ? scope.label : "an environment"} to save this setting.`;
334 return { clientPatch, hasClientWrite, serverWrites, unavailableReason };
335}
336
337export function planScopedSettingsClear(
338 scope: ResolvedSettingsScope,
339 environments: readonly ScopedSettingsEnvironment[],
340 keys: readonly ProjectScopedServerSettingKey[],
341) {
342 const serverWrites =
343 scope.kind === "project" || scope.kind === "checkout"
344 ? projectOverrideWrites(scope, environments, (_current, settings, projectId) =>
345 clearProjectSettingsOverrides(settings, projectId, keys),
346 )
347 : [];
348 return {
349 clientPatch: {} as ClientSettingsPatch,
350 hasClientWrite: false,
351 serverWrites,
352 unavailableReason:
353 serverWrites.length > 0
354 ? null
355 : "Connect the selected checkouts, or update their environments, to reset this override.",
356 };
357}
358
359export interface ProjectOverrideEntry {
360 readonly environmentId: EnvironmentId;
361 readonly projectId: ProjectId;
362}
363
364export function listProjectOverrides(
365 environments: readonly ScopedSettingsEnvironment[],
366 keys: readonly (keyof ServerSettings)[],
367): readonly ProjectOverrideEntry[] {
368 const scoped = keys.filter(isProjectScopedSettingKey);
369 if (scoped.length === 0) return [];
370 return environments.flatMap((environment) => {
371 const overrides = environment.serverConfig?.settings.projectSettingsOverrides;
372 if (!overrides) return [];
373 return Object.entries(overrides).flatMap(([projectId, entry]) =>
374 scoped.some((key) => Object.hasOwn(entry, key))
375 ? [{ environmentId: environment.environmentId, projectId: projectId as ProjectId }]
376 : [],
377 );
378 });
379}
380
381export function planProjectOverridesClear(
382 environments: readonly ScopedSettingsEnvironment[],
383 entries: readonly ProjectOverrideEntry[],
384 keys: readonly ProjectScopedServerSettingKey[],
385) {
386 const byId = new Map(environments.map((environment) => [environment.environmentId, environment]));
387 const writes = new Map<EnvironmentId, ScopedServerWrite>();
388 for (const { environmentId, projectId } of entries) {
389 const environment = byId.get(environmentId);
390 if (!environment?.serverConfig || environment.connection.phase !== "connected") continue;
391 const settings = environment.serverConfig.settings;
392 const existing = writes.get(environmentId);
393 writes.set(environmentId, {
394 environmentId,
395 label: environment.label,
396 previous: settings,
397 patch: {
398 projectSettingsOverrides: {
399 ...existing?.patch.projectSettingsOverrides,
400 [projectId]: clearProjectSettingsOverrides(settings, projectId, keys),
401 },
402 },
403 });
404 }
405 const serverWrites = [...writes.values()];
406 return {
407 clientPatch: {} as ClientSettingsPatch,
408 hasClientWrite: false,
409 serverWrites,
410 unavailableReason:
411 serverWrites.length > 0 ? null : "Connect the environments to reset these overrides.",
412 };
413}
414
415function writeWasDropped(value: unknown, before: unknown, saved: unknown): boolean {
416 if (value === null) return before != null && Equal.equals(saved, before);
417 if (isPlainObject(value) && !Array.isArray(before) && !Array.isArray(saved)) {
418 const field = (source: unknown, key: string) =>
419 isPlainObject(source) ? source[key] : undefined;
420 return Object.entries(value).some(([key, next]) =>
421 writeWasDropped(next, field(before, key), field(saved, key)),
422 );
423 }
424 const unchanged =
425 typeof value === "string" && typeof before === "string"
426 ? value.trim() === before
427 : Equal.equals(value, before);
428 return !unchanged && Equal.equals(saved, before);
429}
430
431/** Older servers silently drop unknown keys; report them so rows cannot stay mixed forever. */
432function droppedSettingKeys(write: ScopedServerWrite, saved: ServerSettings | undefined) {
433 if (saved === undefined) return [];
434 return Object.entries(write.patch).flatMap(([key, value]) =>
435 writeWasDropped(
436 value,
437 write.previous[key as keyof ServerSettings],
438 saved[key as keyof ServerSettings],
439 )
440 ? [key]
441 : [],
442 );
443}
444
445export async function persistScopedSettingsPatch(
446 plan: ReturnType<typeof planScopedSettingsPatch>,
447 persistServer: (input: {
448 environmentId: EnvironmentId;
449 input: { patch: ServerSettingsPatch };
450 }) => Promise<{
451 readonly _tag: "Success" | "Failure";
452 readonly cause?: Cause.Cause<unknown>;
453 readonly value?: ServerSettings;
454 }>,
455 persistClient: (patch: ClientSettingsPatch) => void,
456) {
457 if (plan.hasClientWrite) persistClient(plan.clientPatch);
458 const results = await Promise.allSettled(
459 plan.serverWrites.map(({ environmentId, patch }) =>
460 persistServer({ environmentId, input: { patch } }),
461 ),
462 );
463 const saved = (index: number) => {
464 const result = results[index];
465 return (
466 result?.status === "fulfilled" &&
467 result.value._tag === "Success" &&
468 droppedSettingKeys(plan.serverWrites[index]!, result.value.value).length === 0
469 );
470 };
471 const failedEnvironments = plan.serverWrites.flatMap((environment, index) => {
472 if (saved(index)) return [];
473 const result = results[index];
474 if (result?.status === "fulfilled" && result.value._tag === "Success") {
475 return [
476 {
477 ...environment,
478 message: "This environment does not support this setting. Update T3 Code on it.",
479 },
480 ];
481 }
482 const error: unknown =
483 result?.status === "rejected"
484 ? result.reason
485 : result?.status === "fulfilled" && result.value.cause
486 ? Cause.squash(result.value.cause)
487 : undefined;
488 return [
489 {
490 ...environment,
491 message:
492 error instanceof Error
493 ? error.message
494 : "The save failed. Try reconnecting and saving again.",
495 },
496 ];
497 });
498 const savedEnvironments = plan.serverWrites.filter((_, index) => saved(index));
499 return {
500 failedEnvironments,
501 savedEnvironments,
502 savedEnvironmentCount: savedEnvironments.length,
503 };
504}