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

main
ts 184 lines 6.41 KB
Raw
1 import { AuthSettingsWriteScope } from "@t3tools/contracts";
2 import { useEnvironmentsWithScope } from "../../state/session";
3 import {
4 requiredScopesForServerSettingsPatch,
5 EnvironmentAuthorizationError,
6 } from "@t3tools/contracts";
7 import { readEnvironmentScope } from "../../state/session";
8 import * as Cause from "effect/Cause";
9 import { AsyncResult } from "effect/reactivity";
10 import { msg } from "gt-react";
11 import {
12 DEFAULT_SERVER_SETTINGS,
13 type EnvironmentId,
14 type ProjectScopedServerSettingKey,
15 type ServerSettings,
16 type UnifiedSettings,
17 } from "@t3tools/contracts";
18
19 import { persistClientSettingsPatch, useMergedSettings } from "../../hooks/useSettings";
20 import { m } from "../../i18n/messages";
21 import { appAtomRegistry } from "../../rpc/atomRegistry";
22 import { readEnvironment } from "../../state/environments";
23 import { serverEnvironment } from "../../state/server";
24 import { useAtomCommand } from "../../state/use-atom-command";
25 import { toastManager } from "../ui/toast";
26 import { useOptionalSettingsScope, useSettingsScope } from "./SettingsScopeContext";
27 import {
28 createScopedSettingsWriter,
29 pendingScopedWritesAtom,
30 planProjectOverridesClear,
31 planScopedSettingsClear,
32 planScopedSettingsPatch,
33 scopedSettingsAreMixed,
34 scopedSettingsSource,
35 settlePendingScopedWrites,
36 type ProjectOverrideEntry,
37 type ScopedSettingsPatch,
38 } from "./scopedSettings";
39
40 const readSettings = (environmentId: EnvironmentId) =>
41 readEnvironment(environmentId)?.serverConfig?.settings ?? null;
42 const writeScopedSettings = createScopedSettingsWriter(readSettings);
43
44 export function useScopedSettings<T = UnifiedSettings>(
45 selector?: (settings: UnifiedSettings) => T,
46 ): T {
47 const { target } = useSettingsScope();
48 return useMergedSettings(target?.settings ?? DEFAULT_SERVER_SETTINGS, selector);
49 }
50
51 export function useScopedSettingsMixed(keys: readonly (keyof ServerSettings)[]): boolean {
52 const { targets } = useSettingsScope();
53 return scopedSettingsAreMixed(targets, keys);
54 }
55
56 export function useScopedSettingSource(keys: readonly (keyof ServerSettings)[]) {
57 const { targets } = useSettingsScope();
58 return scopedSettingsSource(targets, keys);
59 }
60
61 function useRunScopedPlan() {
62 const persistServer = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
63 return (
64 environments: Parameters<typeof writeScopedSettings>[0],
65 planner: Parameters<typeof writeScopedSettings>[1],
66 onFailed?: () => void,
67 ) => {
68 const plan = planner(environments);
69 if (plan.unavailableReason) {
70 toastManager.add({
71 type: "warning",
72 title: m(msg("Setting not saved")),
73 description: plan.unavailableReason,
74 });
75 onFailed?.();
76 return;
77 }
78 const save = {};
79 const settle = (environmentId: EnvironmentId, saved?: ServerSettings) =>
80 appAtomRegistry.update(pendingScopedWritesAtom, (writes) =>
81 settlePendingScopedWrites(
82 writes,
83 { save, environmentId },
84 (id) => readSettings(id) ?? undefined,
85 saved,
86 ),
87 );
88 appAtomRegistry.update(pendingScopedWritesAtom, (writes) => [
89 ...writes,
90 ...plan.serverWrites.map(({ environmentId, patch }) => ({ save, environmentId, patch })),
91 ]);
92 void writeScopedSettings(
93 environments,
94 planner,
95 async (request) => {
96 const missing = requiredScopesForServerSettingsPatch(request.input.patch).find(
97 (scope) => !readEnvironmentScope(request.environmentId, scope),
98 );
99 const result = missing
100 ? AsyncResult.failure(
101 Cause.fail(
102 new EnvironmentAuthorizationError({
103 requiredScope: missing,
104 message: m(msg("This connection lacks permission to change these settings.")),
105 }),
106 ),
107 )
108 : await persistServer(request).catch((error: unknown) => {
109 settle(request.environmentId);
110 throw error;
111 });
112 settle(request.environmentId, result._tag === "Success" ? result.value : undefined);
113 return result;
114 },
115 persistClientSettingsPatch,
116 ).then(({ failedEnvironments, savedEnvironments, savedEnvironmentCount }) => {
117 if (failedEnvironments.length === 0) return;
118 onFailed?.();
119 toastManager.add({
120 type: "error",
121 title:
122 savedEnvironmentCount > 0
123 ? m(msg("Setting saved on some environments"))
124 : m(msg("Setting not saved")),
125 description: [
126 ...failedEnvironments.map(({ label, message }) =>
127 m(msg("Could not save on {label}: {message}", { label, message })),
128 ),
129 ...(savedEnvironmentCount > 0
130 ? [
131 m(
132 msg("Saved on {environments}.", {
133 environments: savedEnvironments.map(({ label }) => label).join(", "),
134 }),
135 ),
136 ]
137 : []),
138 ].join("\n"),
139 });
140 });
141 };
142 }
143
144 export function useUpdateScopedSettings() {
145 const { scope, environments, deviceOnly } = useSettingsScope();
146 const run = useRunScopedPlan();
147 /** `onFailed` runs when any target rejects or drops the patch, so a draft can fall back. */
148 return (patch: ScopedSettingsPatch, options?: { readonly onFailed?: () => void }) =>
149 run(
150 environments,
151 (current) => planScopedSettingsPatch(scope, current, patch, { deviceOnly }),
152 options?.onFailed,
153 );
154 }
155
156 export function useClearScopedSettings() {
157 const context = useOptionalSettingsScope();
158 const run = useRunScopedPlan();
159 return (keys: readonly ProjectScopedServerSettingKey[]) => {
160 if (context === null) return;
161 run(context.environments, (current) => planScopedSettingsClear(context.scope, current, keys));
162 };
163 }
164
165 export function useClearProjectOverrides() {
166 const context = useOptionalSettingsScope();
167 const run = useRunScopedPlan();
168 return (
169 entries: readonly ProjectOverrideEntry[],
170 keys: readonly ProjectScopedServerSettingKey[],
171 ) => {
172 if (context === null) return;
173 run(context.environments, (current) => planProjectOverridesClear(current, entries, keys));
174 };
175 }
176
177 export function useScopedSettingsWriteAllowed() {
178 const { connectedEnvironments } = useSettingsScope();
179 const writable = useEnvironmentsWithScope(connectedEnvironments, AuthSettingsWriteScope);
180 return (
181 connectedEnvironments.length > 0 &&
182 connectedEnvironments.every((target) => writable.has(target.environmentId))
183 );
184 }