@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 703 lines 26.4 KB
Raw
1 import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
2 import {
3 ClientSettingsSchema,
4 type ClientSettingsPatch,
5 type EnvironmentId,
6 globalIdleCompaction,
7 idleCompactionPatch,
8 isNullableProjectSettingsOverride,
9 readsIdleCompactionModes,
10 PROJECT_SCOPED_SERVER_SETTING_KEYS,
11 type ProjectId,
12 type ProjectScopedServerSettingKey,
13 type ProjectSettingsOverrides,
14 ServerSettings,
15 type T3ProjectFile,
16 type ServerSettingsPatch,
17 } from "@t3tools/contracts";
18 import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
19 import {
20 clearProjectSettingsOverrides,
21 resolveProjectSettings,
22 resolveWorktreeCleanup,
23 type ProjectSettingSource,
24 } from "@t3tools/shared/projectSettings";
25 import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
26 import * as Equal from "effect/Equal";
27 import * as Cause from "effect/Cause";
28 import { Atom } from "effect/reactivity";
29 import { msg } from "gt-react";
30
31 import { m } from "../../i18n/messages";
32
33 import type { ResolvedSettingsScope } from "./settingsScope";
34
35 export type ScopedSettingsPatch = ServerSettingsPatch & ClientSettingsPatch;
36
37 interface ScopedSettingsEnvironment {
38 readonly environmentId: EnvironmentId;
39 readonly label: string;
40 readonly connection: { readonly phase: EnvironmentConnectionPhase };
41 readonly serverConfig: {
42 readonly settings: ServerSettings;
43 } | null;
44 }
45
46 const SERVER_KEYS = new Set<string>(Object.keys(ServerSettings.fields));
47 const CLIENT_KEYS = new Set<string>(Object.keys(ClientSettingsSchema.fields));
48 const PROJECT_SCOPED_KEYS = new Set<string>(PROJECT_SCOPED_SERVER_SETTING_KEYS);
49
50 export function isProjectScopedSettingKey(key: string): key is ProjectScopedServerSettingKey {
51 return PROJECT_SCOPED_KEYS.has(key);
52 }
53
54 function isPlainObject(value: unknown): value is Record<string, unknown> {
55 return typeof value === "object" && value !== null && !Array.isArray(value);
56 }
57
58 export function isConnectedWithConfig(
59 environment: Pick<ScopedSettingsEnvironment, "connection" | "serverConfig">,
60 ) {
61 return environment.connection.phase === "connected" && environment.serverConfig !== null;
62 }
63
64 /**
65 * A server save shown before its environment pushes the new settings back. It applies while in
66 * flight, and after success only until that environment's settings change from `settledOver`.
67 */
68 export interface PendingScopedWrite {
69 readonly save: object;
70 readonly environmentId: EnvironmentId;
71 readonly patch: ServerSettingsPatch;
72 readonly settledOver?: ServerSettings;
73 }
74
75 export const pendingScopedWritesAtom = Atom.make<readonly PendingScopedWrite[]>([]).pipe(
76 Atom.keepAlive,
77 Atom.withLabel("web-settings:pending-scoped-writes"),
78 );
79
80 const pendingWriteApplies = (write: PendingScopedWrite, settings: ServerSettings | undefined) =>
81 settings !== undefined && (write.settledOver === undefined || write.settledOver === settings);
82
83 /** Settles one environment's write: a failure or an already-pushed result drops it. */
84 export function settlePendingScopedWrites(
85 writes: readonly PendingScopedWrite[],
86 target: Pick<PendingScopedWrite, "save" | "environmentId">,
87 readSettings: (environmentId: EnvironmentId) => ServerSettings | undefined,
88 saved?: ServerSettings,
89 ): readonly PendingScopedWrite[] {
90 return writes.flatMap((write) => {
91 const current = readSettings(write.environmentId);
92 if (write.save !== target.save || write.environmentId !== target.environmentId) {
93 return pendingWriteApplies(write, current) ? [write] : [];
94 }
95 if (saved === undefined || current === undefined || Equal.equals(current, saved)) return [];
96 return [{ ...write, settledOver: current }];
97 });
98 }
99
100 export function applyPendingScopedWrites<T extends ScopedSettingsEnvironment>(
101 environments: readonly T[],
102 writes: readonly PendingScopedWrite[],
103 ): readonly T[] {
104 if (writes.length === 0) return environments;
105 return environments.map((environment) => {
106 const config = environment.serverConfig;
107 if (config === null) return environment;
108 const settings = writes.reduce(
109 (current, write) =>
110 write.environmentId === environment.environmentId &&
111 pendingWriteApplies(write, config.settings)
112 ? applyServerSettingsPatch(current, write.patch)
113 : current,
114 config.settings,
115 );
116 if (settings === config.settings) return environment;
117 // Legacy servers read `compactIdleThreads`, so project the mode back onto it.
118 const { idleCompaction: _mode, ...legacy } = settings;
119 const projected =
120 config.settings.idleCompaction === undefined
121 ? { ...legacy, ...idleCompactionPatch(config.settings, globalIdleCompaction(settings)) }
122 : settings;
123 return { ...environment, serverConfig: { ...config, settings: projected } };
124 });
125 }
126
127 /** The representative supplies display values, never the set of write targets. */
128 export function selectScopedSettingsEnvironments<T extends ScopedSettingsEnvironment>(
129 scope: ResolvedSettingsScope,
130 available: readonly T[],
131 primaryEnvironmentId: EnvironmentId | null,
132 ) {
133 const selectedIds = new Set(scope.environmentIds);
134 const environments = available.filter((environment) =>
135 selectedIds.has(environment.environmentId),
136 );
137 const connectedEnvironments = environments.filter(isConnectedWithConfig);
138 const environment =
139 connectedEnvironments.find((candidate) => candidate.environmentId === primaryEnvironmentId) ??
140 connectedEnvironments[0] ??
141 null;
142 return { environments, connectedEnvironments, environment };
143 }
144
145 export interface ScopedSettingsTarget {
146 readonly environmentId: EnvironmentId;
147 readonly label: string;
148 readonly projectId: ProjectId | null;
149 readonly settings: ServerSettings;
150 readonly sources: Readonly<Record<ProjectScopedServerSettingKey, ProjectSettingSource>>;
151 }
152
153 export function resolveScopedSettingsTargets(
154 scope: ResolvedSettingsScope,
155 connectedEnvironments: readonly ScopedSettingsEnvironment[],
156 // A member absent here has no file tier yet; null is a missing or invalid file.
157 projectFiles?: ReadonlyMap<string, T3ProjectFile | null>,
158 ): readonly ScopedSettingsTarget[] {
159 const byId = new Map(
160 connectedEnvironments.map((environment) => [environment.environmentId, environment]),
161 );
162 if (scope.kind === "project" || scope.kind === "checkout") {
163 return scope.members.flatMap((member) => {
164 const environment = byId.get(member.environmentId);
165 if (!environment?.serverConfig) return [];
166 const projectFile = projectFiles?.get(member.physicalProjectKey);
167 const resolved =
168 projectFile === undefined
169 ? resolveProjectSettings(environment.serverConfig.settings, member.id)
170 : resolveProjectSettings(environment.serverConfig.settings, member.id, null, projectFile);
171 return [
172 {
173 environmentId: member.environmentId,
174 label: environment.label,
175 projectId: member.id,
176 settings: resolved.settings,
177 sources: resolved.sources,
178 },
179 ];
180 });
181 }
182 return connectedEnvironments.flatMap((environment) =>
183 environment.serverConfig
184 ? [
185 {
186 environmentId: environment.environmentId,
187 label: environment.label,
188 projectId: null,
189 settings: environment.serverConfig.settings,
190 sources: resolveProjectSettings(environment.serverConfig.settings, null).sources,
191 },
192 ]
193 : [],
194 );
195 }
196
197 export function scopedSettingsAreMixed(
198 targets: readonly Pick<ScopedSettingsTarget, "settings">[],
199 keys: readonly (keyof ServerSettings)[],
200 ): boolean {
201 const first = targets[0];
202 return (
203 first !== undefined &&
204 targets.some((candidate) =>
205 keys.some((key) => !Equal.equals(first.settings[key], candidate.settings[key])),
206 )
207 );
208 }
209
210 /**
211 * Servers store the idle compaction mode differently by version, so selected
212 * environments are compared by the mode each resolves to, and "Never" is offered
213 * only when every one of them can store it.
214 */
215 export function scopedIdleCompaction(targets: readonly Pick<ScopedSettingsTarget, "settings">[]) {
216 const modes = targets.map((candidate) => globalIdleCompaction(candidate.settings));
217 return {
218 mixed: modes.some((mode) => mode !== modes[0]),
219 neverAvailable: targets.every((candidate) => readsIdleCompactionModes(candidate.settings)),
220 };
221 }
222
223 export type ScopedSettingSource = ProjectSettingSource | "mixed";
224
225 export function scopedSettingsSource(
226 targets: readonly Pick<ScopedSettingsTarget, "sources">[],
227 keys: readonly (keyof ServerSettings)[],
228 ): ScopedSettingSource {
229 const scoped = keys.filter(isProjectScopedSettingKey);
230 if (scoped.length === 0 || targets.length === 0) return "environment";
231 const sources = new Set(targets.flatMap((target) => scoped.map((key) => target.sources[key])));
232 return sources.size > 1
233 ? "mixed"
234 : sources.has("project")
235 ? "project"
236 : sources.has("t3.json")
237 ? "t3.json"
238 : "environment";
239 }
240
241 interface ScopedServerWrite {
242 readonly environmentId: EnvironmentId;
243 readonly label: string;
244 readonly patch: ServerSettingsPatch;
245 readonly previous: ServerSettings;
246 }
247
248 function projectOverrideWrites(
249 scope: Extract<ResolvedSettingsScope, { kind: "project" | "checkout" }>,
250 environments: readonly ScopedSettingsEnvironment[],
251 update: (
252 current: ProjectSettingsOverrides,
253 settings: ServerSettings,
254 projectId: ProjectId,
255 ) => ProjectSettingsOverrides | null,
256 ): ScopedServerWrite[] {
257 const byId = new Map(environments.map((environment) => [environment.environmentId, environment]));
258 const writes = new Map<EnvironmentId, ScopedServerWrite>();
259 for (const member of scope.members) {
260 const environment = byId.get(member.environmentId);
261 if (!environment?.serverConfig || environment.connection.phase !== "connected") {
262 continue;
263 }
264 const settings = environment.serverConfig.settings;
265 const entry = update(settings.projectSettingsOverrides[member.id] ?? {}, settings, member.id);
266 const existing = writes.get(member.environmentId);
267 writes.set(member.environmentId, {
268 environmentId: member.environmentId,
269 label: environment.label,
270 previous: settings,
271 patch: {
272 projectSettingsOverrides: {
273 ...existing?.patch.projectSettingsOverrides,
274 [member.id]: entry,
275 },
276 },
277 });
278 }
279 return [...writes.values()];
280 }
281
282 /** Puts an idle compaction mode in the form each destination server reads. */
283 function forDestination(previous: ServerSettings, patch: ServerSettingsPatch): ServerSettingsPatch {
284 if (patch.idleCompaction === undefined) return patch;
285 const { idleCompaction, compactIdleThreads: _legacy, ...rest } = patch;
286 return { ...rest, ...idleCompactionPatch(previous, idleCompaction) };
287 }
288
289 export function planScopedSettingsPatch(
290 scope: ResolvedSettingsScope,
291 environments: readonly ScopedSettingsEnvironment[],
292 patch: ScopedSettingsPatch,
293 options?: { readonly deviceOnly?: boolean },
294 ) {
295 const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
296 const refusesClientKeys = isProjectScope && options?.deviceOnly !== true;
297 const clientKeys = Object.keys(patch).filter(
298 (key) => CLIENT_KEYS.has(key) && !SERVER_KEYS.has(key),
299 );
300 const serverPatch = Object.fromEntries(
301 Object.entries(patch).filter(([key]) => SERVER_KEYS.has(key)),
302 ) as ServerSettingsPatch;
303 const serverKeys = Object.keys(serverPatch);
304 const { connectedEnvironments } = selectScopedSettingsEnvironments(scope, environments, null);
305 // Client settings are stored per device, so a project has nowhere to keep an override.
306 const unscopableKeys = isProjectScope
307 ? [
308 ...(refusesClientKeys ? clientKeys : []),
309 ...serverKeys.filter((key) => !isProjectScopedSettingKey(key)),
310 ]
311 : [];
312 const clientPatch = Object.fromEntries(
313 refusesClientKeys ? [] : Object.entries(patch).filter(([key]) => clientKeys.includes(key)),
314 ) as ClientSettingsPatch;
315 const serverWrites: ScopedServerWrite[] =
316 serverKeys.length === 0
317 ? []
318 : isProjectScope
319 ? unscopableKeys.length > 0
320 ? []
321 : projectOverrideWrites(scope, environments, (current, settings, projectId) => {
322 // Override entries store whole objects; complete partial patches from each target's effective
323 // value.
324 const effective = resolveProjectSettings(settings, projectId).settings;
325 const next: Record<string, unknown> = { ...current };
326 for (const [key, value] of Object.entries<unknown>(serverPatch)) {
327 if (key === "worktreeCleanup" && serverPatch.worktreeCleanup?.mode === "custom") {
328 next[key] = {
329 mode: "custom",
330 rules: {
331 ...resolveWorktreeCleanup(settings, projectId),
332 ...serverPatch.worktreeCleanup.rules,
333 },
334 };
335 continue;
336 }
337 // Inherit sends null; remove overrides whose keys cannot store null.
338 if (
339 value === null &&
340 !isNullableProjectSettingsOverride(key as ProjectScopedServerSettingKey)
341 ) {
342 delete next[key];
343 continue;
344 }
345 const base: unknown = effective[key as keyof ServerSettings];
346 // A new model must not inherit the previous model's options.
347 if (
348 isPlainObject(value) &&
349 isPlainObject(base) &&
350 (key === "defaultModelSelection" ||
351 key === "sourceControlWriterModelSelection" ||
352 key === "reviewGuideModelSelection" ||
353 key === "textGenerationModelSelection") &&
354 (value.instanceId !== undefined || value.model !== undefined)
355 ) {
356 next[key] = { instanceId: base.instanceId, model: base.model, ...value };
357 continue;
358 }
359 next[key] =
360 isPlainObject(value) && isPlainObject(base) ? { ...base, ...value } : value;
361 }
362 return next as ProjectSettingsOverrides;
363 })
364 : scope.kind === "all" || scope.kind === "environment"
365 ? connectedEnvironments.flatMap((environment) => {
366 const previous = environment.serverConfig?.settings;
367 if (!previous) return [];
368 return [
369 {
370 environmentId: environment.environmentId,
371 label: environment.label,
372 previous,
373 patch: forDestination(
374 previous,
375 previous.worktreeCleanup != null &&
376 serverPatch.storageCleanup &&
377 Object.keys(serverPatch.storageCleanup).some((key) =>
378 key.startsWith("worktree"),
379 )
380 ? {
381 ...serverPatch,
382 worktreeCleanup: {
383 mode: "custom",
384 rules: {
385 ...resolveWorktreeCleanup(previous, null),
386 ...Object.fromEntries(
387 Object.entries(serverPatch.storageCleanup).filter(([key]) =>
388 key.startsWith("worktree"),
389 ),
390 ),
391 },
392 },
393 }
394 : serverPatch,
395 ),
396 },
397 ];
398 })
399 : [];
400 const hasClientWrite = Object.keys(clientPatch).length > 0;
401 const hasWrite = hasClientWrite || serverWrites.length > 0;
402 const unavailableReason =
403 hasWrite || Object.keys(patch).length === 0
404 ? null
405 : scope.kind === "unavailable"
406 ? scope.message
407 : unscopableKeys.length > 0
408 ? m(msg("This setting is environment-wide and cannot be overridden by a project."))
409 : isProjectScope
410 ? m(
411 msg(
412 "Connect the selected checkouts, or update their environments, to save a project override.",
413 ),
414 )
415 : scope.kind === "environment"
416 ? m(msg("Connect {environment} to save this setting.", { environment: scope.label }))
417 : m(msg("Connect an environment to save this setting."));
418 return { clientPatch, hasClientWrite, serverWrites, unavailableReason };
419 }
420
421 export function planScopedSettingsClear(
422 scope: ResolvedSettingsScope,
423 environments: readonly ScopedSettingsEnvironment[],
424 keys: readonly ProjectScopedServerSettingKey[],
425 ) {
426 const serverWrites =
427 scope.kind === "project" || scope.kind === "checkout"
428 ? projectOverrideWrites(scope, environments, (_current, settings, projectId) =>
429 clearProjectSettingsOverrides(settings, projectId, keys),
430 )
431 : [];
432 return {
433 clientPatch: {} as ClientSettingsPatch,
434 hasClientWrite: false,
435 serverWrites,
436 unavailableReason:
437 serverWrites.length > 0
438 ? null
439 : m(
440 msg(
441 "Connect the selected checkouts, or update their environments, to reset this override.",
442 ),
443 ),
444 };
445 }
446
447 export interface ProjectOverrideEntry {
448 readonly environmentId: EnvironmentId;
449 readonly projectId: ProjectId;
450 }
451
452 export function listProjectOverrides(
453 environments: readonly ScopedSettingsEnvironment[],
454 keys: readonly (keyof ServerSettings)[],
455 ): readonly ProjectOverrideEntry[] {
456 const scoped = keys.filter(isProjectScopedSettingKey);
457 if (scoped.length === 0) return [];
458 return environments.flatMap((environment) => {
459 const overrides = environment.serverConfig?.settings.projectSettingsOverrides;
460 if (!overrides) return [];
461 return Object.entries(overrides).flatMap(([projectId, entry]) =>
462 scoped.some((key) => Object.hasOwn(entry, key))
463 ? [{ environmentId: environment.environmentId, projectId: projectId as ProjectId }]
464 : [],
465 );
466 });
467 }
468
469 export function planProjectOverridesClear(
470 environments: readonly ScopedSettingsEnvironment[],
471 entries: readonly ProjectOverrideEntry[],
472 keys: readonly ProjectScopedServerSettingKey[],
473 ) {
474 const byId = new Map(environments.map((environment) => [environment.environmentId, environment]));
475 const writes = new Map<EnvironmentId, ScopedServerWrite>();
476 for (const { environmentId, projectId } of entries) {
477 const environment = byId.get(environmentId);
478 if (!environment?.serverConfig || environment.connection.phase !== "connected") continue;
479 const settings = environment.serverConfig.settings;
480 const existing = writes.get(environmentId);
481 writes.set(environmentId, {
482 environmentId,
483 label: environment.label,
484 previous: settings,
485 patch: {
486 projectSettingsOverrides: {
487 ...existing?.patch.projectSettingsOverrides,
488 [projectId]: clearProjectSettingsOverrides(settings, projectId, keys),
489 },
490 },
491 });
492 }
493 const serverWrites = [...writes.values()];
494 return {
495 clientPatch: {} as ClientSettingsPatch,
496 hasClientWrite: false,
497 serverWrites,
498 unavailableReason:
499 serverWrites.length > 0 ? null : m(msg("Connect the environments to reset these overrides.")),
500 };
501 }
502
503 function writeWasDropped(value: unknown, before: unknown, saved: unknown): boolean {
504 if (value === null) return before != null && Equal.equals(saved, before);
505 if (isPlainObject(value) && !Array.isArray(before) && !Array.isArray(saved)) {
506 const field = (source: unknown, key: string) =>
507 isPlainObject(source) ? source[key] : undefined;
508 return Object.entries(value).some(([key, next]) =>
509 writeWasDropped(next, field(before, key), field(saved, key)),
510 );
511 }
512 const unchanged =
513 typeof value === "string" && typeof before === "string"
514 ? value.trim() === before
515 : Equal.equals(value, before);
516 return !unchanged && Equal.equals(saved, before);
517 }
518
519 /** Older servers silently drop unknown keys; report them so rows cannot stay mixed forever. */
520 function droppedSettingKeys(write: ScopedServerWrite, saved: ServerSettings | undefined) {
521 if (saved === undefined) return [];
522 return Object.entries(write.patch).flatMap(([key, value]) =>
523 writeWasDropped(
524 value,
525 write.previous[key as keyof ServerSettings],
526 saved[key as keyof ServerSettings],
527 )
528 ? [key]
529 : [],
530 );
531 }
532
533 type ScopedSettingsPlan = ReturnType<typeof planScopedSettingsPatch>;
534
535 type ScopedSettingsPersistServer = (input: {
536 environmentId: EnvironmentId;
537 input: { patch: ServerSettingsPatch };
538 }) => Promise<{
539 readonly _tag: "Success" | "Failure";
540 readonly cause?: Cause.Cause<unknown>;
541 readonly value?: ServerSettings;
542 }>;
543
544 export async function persistScopedSettingsPatch(
545 plan: ScopedSettingsPlan,
546 persistServer: ScopedSettingsPersistServer,
547 persistClient: (patch: ClientSettingsPatch) => void,
548 ) {
549 return persistScopedSettingsPlan(
550 plan,
551 async (write) => ({
552 write,
553 result: await persistServer({
554 environmentId: write.environmentId,
555 input: { patch: write.patch },
556 }),
557 }),
558 persistClient,
559 );
560 }
561
562 const OWN_ECHO_LIMIT = 8;
563
564 /**
565 * Project overrides are whole entries built from this client's copy of the settings, and that
566 * copy hears about a save only when the server pushes it back. So saves to one environment run
567 * one at a time, each planned as it starts from the newest settings this client holds: the
568 * previous save's response, unless an independently changed copy has arrived.
569 */
570 export function createScopedSettingsWriter(
571 readSettings: (environmentId: EnvironmentId) => ServerSettings | null,
572 ) {
573 const queues = new Map<EnvironmentId, Promise<unknown>>();
574 const responses = new Map<
575 EnvironmentId,
576 {
577 readonly settings: ServerSettings;
578 readonly copy: ServerSettings;
579 readonly saved: readonly ServerSettings[];
580 }
581 >();
582 return (
583 environments: readonly ScopedSettingsEnvironment[],
584 plan: (environments: readonly ScopedSettingsEnvironment[]) => ScopedSettingsPlan,
585 persistServer: ScopedSettingsPersistServer,
586 persistClient: (patch: ClientSettingsPatch) => void,
587 ) =>
588 persistScopedSettingsPlan(
589 plan(environments),
590 (planned) => {
591 const { environmentId } = planned;
592 const save = (queues.get(environmentId) ?? Promise.resolve()).then(async () => {
593 const copy = readSettings(environmentId);
594 const response = responses.get(environmentId);
595 // A copy equal to one of our earlier responses is a delayed echo, older than the latest.
596 const isOwnEcho = (settings: ServerSettings) =>
597 response?.saved.some((saved) => Equal.equals(saved, settings)) === true;
598 const continues =
599 copy !== null && response !== undefined && (response.copy === copy || isOwnEcho(copy));
600 const settings = continues ? response.settings : copy;
601 const replanned =
602 settings === null ? null : plan(withSettings(environments, environmentId, settings));
603 const write =
604 replanned?.serverWrites.find((next) => next.environmentId === environmentId) ?? planned;
605 const result = await persistServer({ environmentId, input: { patch: write.patch } });
606 const savedCopy = readSettings(environmentId);
607 if (result._tag === "Success" && result.value !== undefined && savedCopy !== null) {
608 // A changed copy may be a newer remote push or the delayed echo of our previous save.
609 if (
610 savedCopy === copy ||
611 Equal.equals(savedCopy, settings) ||
612 Equal.equals(savedCopy, result.value) ||
613 isOwnEcho(savedCopy)
614 ) {
615 responses.set(environmentId, {
616 settings: result.value,
617 copy: savedCopy,
618 saved: [...(continues ? response.saved : []), result.value].slice(-OWN_ECHO_LIMIT),
619 });
620 } else {
621 responses.delete(environmentId);
622 }
623 }
624 return { write, result };
625 });
626 queues.set(
627 environmentId,
628 save.catch(() => undefined),
629 );
630 return save;
631 },
632 persistClient,
633 );
634 }
635
636 function withSettings(
637 environments: readonly ScopedSettingsEnvironment[],
638 environmentId: EnvironmentId,
639 settings: ServerSettings,
640 ) {
641 return environments.map((environment) =>
642 environment.environmentId === environmentId && environment.serverConfig
643 ? { ...environment, serverConfig: { ...environment.serverConfig, settings } }
644 : environment,
645 );
646 }
647
648 async function persistScopedSettingsPlan(
649 plan: ScopedSettingsPlan,
650 persistWrite: (write: ScopedServerWrite) => Promise<{
651 readonly write: ScopedServerWrite;
652 readonly result: Awaited<ReturnType<ScopedSettingsPersistServer>>;
653 }>,
654 persistClient: (patch: ClientSettingsPatch) => void,
655 ) {
656 if (plan.hasClientWrite) persistClient(plan.clientPatch);
657 const results = await Promise.allSettled(plan.serverWrites.map(persistWrite));
658 // A queued write is replanned before it is sent, so judge the write that was sent.
659 const writes = results.map((result, index) =>
660 result.status === "fulfilled" ? result.value.write : plan.serverWrites[index]!,
661 );
662 const saved = (index: number) => {
663 const result = results[index];
664 return (
665 result?.status === "fulfilled" &&
666 result.value.result._tag === "Success" &&
667 droppedSettingKeys(writes[index]!, result.value.result.value).length === 0
668 );
669 };
670 const failedEnvironments = writes.flatMap((environment, index) => {
671 if (saved(index)) return [];
672 const result = results[index];
673 if (result?.status === "fulfilled" && result.value.result._tag === "Success") {
674 return [
675 {
676 ...environment,
677 message: m(msg("This environment does not support this setting. Update T3 Code on it.")),
678 },
679 ];
680 }
681 const error: unknown =
682 result?.status === "rejected"
683 ? result.reason
684 : result?.status === "fulfilled" && result.value.result.cause
685 ? Cause.squash(result.value.result.cause)
686 : undefined;
687 return [
688 {
689 ...environment,
690 message:
691 error instanceof Error
692 ? (errorDisplayMessage(error, m) ?? error.message)
693 : m(msg("The save failed. Try reconnecting and saving again.")),
694 },
695 ];
696 });
697 const savedEnvironments = writes.filter((_, index) => saved(index));
698 return {
699 failedEnvironments,
700 savedEnvironments,
701 savedEnvironmentCount: savedEnvironments.length,
702 };
703 }