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 options?: { readonly deviceOnly?: boolean },
225) {
226 const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
227 const refusesClientKeys = isProjectScope && options?.deviceOnly !== true;
228 const clientKeys = Object.keys(patch).filter(
229 (key) => CLIENT_KEYS.has(key) && !SERVER_KEYS.has(key),
230 );
231 const serverPatch = Object.fromEntries(
232 Object.entries(patch).filter(([key]) => SERVER_KEYS.has(key)),
233 ) as ServerSettingsPatch;
234 const serverKeys = Object.keys(serverPatch);
235 const { connectedEnvironments } = selectScopedSettingsEnvironments(scope, environments, null);
236 // Client settings are stored per device, so a project has nowhere to keep an override.
237 const unscopableKeys = isProjectScope
238 ? [
239 ...(refusesClientKeys ? clientKeys : []),
240 ...serverKeys.filter((key) => !isProjectScopedSettingKey(key)),
241 ]
242 : [];
243 const clientPatch = Object.fromEntries(
244 refusesClientKeys ? [] : Object.entries(patch).filter(([key]) => clientKeys.includes(key)),
245 ) as ClientSettingsPatch;
246 const serverWrites: ScopedServerWrite[] =
247 serverKeys.length === 0
248 ? []
249 : isProjectScope
250 ? unscopableKeys.length > 0
251 ? []
252 : projectOverrideWrites(scope, environments, (current, settings, projectId) => {
253 // Override entries store whole objects; complete partial patches from each target's effective
254 // value.
255 const effective = resolveProjectSettings(settings, projectId).settings;
256 const next: Record<string, unknown> = { ...current };
257 for (const [key, value] of Object.entries<unknown>(serverPatch)) {
258 if (key === "worktreeCleanup" && serverPatch.worktreeCleanup?.mode === "custom") {
259 next[key] = {
260 mode: "custom",
261 rules: {
262 ...resolveWorktreeCleanup(settings, projectId),
263 ...serverPatch.worktreeCleanup.rules,
264 },
265 };
266 continue;
267 }
268 // Inherit sends null; remove overrides whose keys cannot store null.
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/** Older servers silently drop unknown keys; report them so rows cannot stay mixed forever. */
441function droppedSettingKeys(write: ScopedServerWrite, saved: ServerSettings | undefined) {
442 if (saved === undefined) return [];
443 return Object.entries(write.patch).flatMap(([key, value]) =>
444 writeWasDropped(
445 value,
446 write.previous[key as keyof ServerSettings],
447 saved[key as keyof ServerSettings],
448 )
449 ? [key]
450 : [],
451 );
452}
453
454export async function persistScopedSettingsPatch(
455 plan: ReturnType<typeof planScopedSettingsPatch>,
456 persistServer: (input: {
457 environmentId: EnvironmentId;
458 input: { patch: ServerSettingsPatch };
459 }) => Promise<{
460 readonly _tag: "Success" | "Failure";
461 readonly cause?: Cause.Cause<unknown>;
462 readonly value?: ServerSettings;
463 }>,
464 persistClient: (patch: ClientSettingsPatch) => void,
465) {
466 if (plan.hasClientWrite) persistClient(plan.clientPatch);
467 const results = await Promise.allSettled(
468 plan.serverWrites.map(({ environmentId, patch }) =>
469 persistServer({ environmentId, input: { patch } }),
470 ),
471 );
472 const saved = (index: number) => {
473 const result = results[index];
474 return (
475 result?.status === "fulfilled" &&
476 result.value._tag === "Success" &&
477 droppedSettingKeys(plan.serverWrites[index]!, result.value.value).length === 0
478 );
479 };
480 const failedEnvironments = plan.serverWrites.flatMap((environment, index) => {
481 if (saved(index)) return [];
482 const result = results[index];
483 if (result?.status === "fulfilled" && result.value._tag === "Success") {
484 return [
485 {
486 ...environment,
487 message: "This environment does not support this setting. Update T3 Code on it.",
488 },
489 ];
490 }
491 const error: unknown =
492 result?.status === "rejected"
493 ? result.reason
494 : result?.status === "fulfilled" && result.value.cause
495 ? Cause.squash(result.value.cause)
496 : undefined;
497 return [
498 {
499 ...environment,
500 message:
501 error instanceof Error
502 ? error.message
503 : "The save failed. Try reconnecting and saving again.",
504 },
505 ];
506 });
507 const savedEnvironments = plan.serverWrites.filter((_, index) => saved(index));
508 return {
509 failedEnvironments,
510 savedEnvironments,
511 savedEnvironmentCount: savedEnvironments.length,
512 };
513}