Open History to see the last commit
1import { msg } from "gt-react";
2import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
3import { m } from "~/i18n/messages";
4import type {
5 KeybindingCommand,
6 ProjectId,
7 ProjectScript,
8 EnvironmentId,
9 ServerSettings,
10} from "@t3tools/contracts";
11import { AuthSettingsWriteScope, EnvironmentAuthorizationError } from "@t3tools/contracts";
12import type { UnifiedSettings } from "@t3tools/contracts/settings";
13import {
14 isAtomCommandInterrupted,
15 mapAtomCommandResult,
16 squashAtomCommandFailure,
17 type AtomCommandResult,
18} from "@t3tools/client-runtime/state/runtime";
19import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
20import { resolveProjectScripts } from "@t3tools/shared/projectScripts";
21import * as Cause from "effect/Cause";
22import { AsyncResult } from "effect/reactivity";
23import { useRef } from "react";
24import { useStableCallback } from "../../hooks/useStableCallback";
25import {
26 decodeProjectScriptKeybindingRule,
27 keybindingValueForCommand,
28} from "../../lib/projectScriptKeybindings";
29import {
30 buildProjectScript,
31 commandForProjectScript,
32 nextProjectScriptId,
33 projectScriptIdFromCommand,
34 projectScriptIdsInEnvironment,
35 releaseClaimedRoles,
36} from "../../projectScripts";
37import { appAtomRegistry } from "../../rpc/atomRegistry";
38import { serverEnvironment } from "../../state/server";
39import { readEnvironmentScope } from "../../state/session";
40import { useAtomCommand } from "../../state/use-atom-command";
41import { useProjects } from "../../state/entities";
42import { type NewProjectScriptInput } from "../ProjectScriptsControl";
43import { stackedThreadToast, toastManager } from "../ui/toast";
44
45/** Write script settings before reconciling shortcuts in environment keybindings. */
46export function useProjectScriptEditing(input: {
47 readonly environmentId: EnvironmentId;
48 readonly project: EnvironmentProject | null;
49 readonly settings: UnifiedSettings;
50}) {
51 const { environmentId, project } = input;
52 const allProjects = useProjects();
53 const queue = useRef<Promise<unknown>>(Promise.resolve());
54 const acknowledged = useRef<{
55 environmentId: EnvironmentId;
56 streamed: ServerSettings | null;
57 settings: ServerSettings;
58 } | null>(null);
59 // Each change starts from the last one's saved list, so quick imports do not overwrite each other.
60 const enqueue = <A>(run: () => Promise<A>): Promise<A> => {
61 const next = queue.current.then(run);
62 queue.current = next.catch(() => undefined);
63 return next;
64 };
65 const latestSettings = () => {
66 const streamed = appAtomRegistry.get(serverEnvironment.settingsValueAtom(environmentId));
67 const saved = acknowledged.current;
68 // Keep the acknowledged write until the config stream catches up with the RPC reply.
69 if (saved?.environmentId === environmentId && saved.streamed === streamed) {
70 return saved.settings;
71 }
72 return streamed ?? input.settings;
73 };
74 const updateProjectScriptSettings = useAtomCommand(serverEnvironment.updateSettings, {
75 reportFailure: false,
76 });
77 const upsertKeybinding = useAtomCommand(serverEnvironment.upsertKeybinding, {
78 reportFailure: false,
79 });
80 const removeKeybinding = useAtomCommand(serverEnvironment.removeKeybinding, {
81 reportFailure: false,
82 });
83 const persistProjectScripts = async (input: {
84 settings: ServerSettings;
85 projectId: ProjectId;
86 projectCwd: string;
87 previousScripts: ReadonlyArray<ProjectScript>;
88 nextScripts: ReadonlyArray<ProjectScript>;
89 keybinding: NewProjectScriptInput["keybinding"];
90 keybindingCommand: KeybindingCommand | null;
91 onSettingsSaved?: () => void;
92 }): Promise<AtomCommandResult<void, unknown>> => {
93 const { settings } = input;
94 const serverConfig = appAtomRegistry.get(serverEnvironment.configValueAtom(environmentId));
95 const previousKeybinding = keybindingValueForCommand(
96 serverConfig?.keybindings ?? [],
97 input.keybindingCommand,
98 );
99 const isDeletingScript = !input.nextScripts.some(
100 (script) => commandForProjectScript(script.id) === input.keybindingCommand,
101 );
102 const changesKeybinding =
103 input.keybinding !== undefined &&
104 (input.keybinding?.trim() || null) !== previousKeybinding &&
105 (!isDeletingScript || readEnvironmentScope(environmentId, AuthSettingsWriteScope));
106 if (changesKeybinding && !readEnvironmentScope(environmentId, AuthSettingsWriteScope)) {
107 return AsyncResult.failure(
108 Cause.fail(
109 new EnvironmentAuthorizationError({
110 requiredScope: AuthSettingsWriteScope,
111 message: m(msg("This connection cannot change keyboard shortcuts.")),
112 }),
113 ),
114 );
115 }
116 const keybindingRule = changesKeybinding
117 ? decodeProjectScriptKeybindingRule({
118 keybinding: input.keybinding,
119 command: input.keybindingCommand,
120 })
121 : null;
122 const settingsResult = await updateProjectScriptSettings({
123 environmentId,
124 input: {
125 patch:
126 serverConfig?.environment.capabilities.projectSettingsOverrides === true
127 ? {
128 projectSettingsOverrides: {
129 [input.projectId]: {
130 ...settings.projectSettingsOverrides[input.projectId],
131 defaultProjectScripts: input.nextScripts,
132 },
133 },
134 }
135 : {
136 projectScriptOverrides: {
137 [input.projectId]: input.nextScripts,
138 },
139 },
140 },
141 });
142 if (settingsResult._tag === "Success") {
143 acknowledged.current = {
144 environmentId,
145 streamed: appAtomRegistry.get(serverEnvironment.settingsValueAtom(environmentId)),
146 settings: settingsResult.value,
147 };
148 }
149 const updateResult = mapAtomCommandResult(settingsResult, () => undefined);
150 if (updateResult._tag === "Failure") {
151 return updateResult;
152 }
153
154 input.onSettingsSaved?.();
155 if (!changesKeybinding) return updateResult;
156 if (!readEnvironmentScope(environmentId, AuthSettingsWriteScope)) {
157 return AsyncResult.failure(
158 Cause.fail(
159 new EnvironmentAuthorizationError({
160 requiredScope: AuthSettingsWriteScope,
161 message: isDeletingScript
162 ? m(
163 msg(
164 "The script was deleted, but its keyboard shortcut could not be removed because permission changed.",
165 ),
166 )
167 : m(
168 msg(
169 "The script was saved, but this connection can no longer change keyboard shortcuts.",
170 ),
171 ),
172 }),
173 ),
174 );
175 }
176
177 const scriptId = input.keybindingCommand
178 ? projectScriptIdFromCommand(input.keybindingCommand)
179 : null;
180 if (!keybindingRule && !input.previousScripts.some((script) => script.id === scriptId)) {
181 return updateResult;
182 }
183 const retainedElsewhere =
184 !input.nextScripts.some((script) => script.id === scriptId) &&
185 (settings.defaultProjectScripts.some((script) => script.id === scriptId) ||
186 Object.entries(settings.projectSettingsOverrides).some(
187 ([projectId, entry]) =>
188 projectId !== input.projectId &&
189 entry.defaultProjectScripts?.some((script) => script.id === scriptId),
190 ) ||
191 allProjects.some(
192 (other) =>
193 other.environmentId === environmentId &&
194 other.id !== input.projectId &&
195 resolveProjectScripts(settings, other).some((script) => script.id === scriptId),
196 ));
197 if (!keybindingRule && retainedElsewhere) return updateResult;
198
199 const previousRules = (serverConfig?.keybindings ?? []).flatMap((binding) => {
200 if (binding.command !== input.keybindingCommand || binding.whenAst) return [];
201 const previous = decodeProjectScriptKeybindingRule({
202 keybinding: keybindingValueForCommand([binding], input.keybindingCommand),
203 command: input.keybindingCommand,
204 });
205 return previous ? [previous] : [];
206 });
207 const previous = previousRules.at(-1);
208 for (const rule of keybindingRule ? previousRules.slice(0, -1) : previousRules) {
209 const result = await removeKeybinding({ environmentId, input: rule });
210 if (result._tag === "Failure") return mapAtomCommandResult(result, () => undefined);
211 }
212 return keybindingRule
213 ? mapAtomCommandResult(
214 await upsertKeybinding({
215 environmentId,
216 input:
217 previous && previous.key !== keybindingRule.key
218 ? { ...keybindingRule, replace: previous }
219 : keybindingRule,
220 }),
221 () => undefined,
222 )
223 : updateResult;
224 };
225 const saveProjectScript = async (
226 input: NewProjectScriptInput,
227 onActionCreated?: (scriptId: string) => void,
228 ): Promise<AtomCommandResult<void, unknown>> => {
229 if (!project) {
230 return AsyncResult.success(undefined);
231 }
232 const settings = latestSettings();
233 const scripts = resolveProjectScripts(settings, project);
234 const nextId = nextProjectScriptId(input.name, [
235 ...scripts.map((script) => script.id),
236 ...projectScriptIdsInEnvironment(
237 settings,
238 allProjects.filter((other) => other.environmentId === environmentId),
239 ),
240 ]);
241 const nextScript = buildProjectScript(nextId, input);
242 const nextScripts = [
243 ...scripts.map((script) => releaseClaimedRoles(script, input)),
244 nextScript,
245 ];
246
247 return persistProjectScripts({
248 settings,
249 projectId: project.id,
250 projectCwd: project.workspaceRoot,
251 previousScripts: scripts,
252 nextScripts,
253 keybinding: input.keybinding,
254 keybindingCommand: commandForProjectScript(nextId),
255 // The editor needs the ID even if writing the shortcut fails.
256 onSettingsSaved: () => onActionCreated?.(nextId),
257 });
258 };
259 const updateProjectScript = async (
260 scriptId: string,
261 input: NewProjectScriptInput,
262 retryingCreation = false,
263 ): Promise<AtomCommandResult<void, unknown>> => {
264 if (!project) {
265 return AsyncResult.success(undefined);
266 }
267 const settings = latestSettings();
268 const scripts = resolveProjectScripts(settings, project);
269 const hasScript = scripts.some((script) => script.id === scriptId);
270 if (!hasScript && !retryingCreation) {
271 return AsyncResult.failure(Cause.fail(new Error(m(msg("Script not found.")))));
272 }
273
274 const updatedScript = buildProjectScript(scriptId, input);
275 // A retry has a confirmed ID even if the settings subscription is still behind.
276 const currentScripts = hasScript ? scripts : [...scripts, updatedScript];
277 const nextScripts = currentScripts.map((script) =>
278 script.id === scriptId ? updatedScript : releaseClaimedRoles(script, input),
279 );
280
281 return persistProjectScripts({
282 settings,
283 projectId: project.id,
284 projectCwd: project.workspaceRoot,
285 previousScripts: currentScripts,
286 nextScripts,
287 keybinding: input.keybinding,
288 keybindingCommand: commandForProjectScript(scriptId),
289 });
290 };
291 const deleteProjectScript = async (
292 scriptId: string,
293 ): Promise<AtomCommandResult<void, unknown>> => {
294 if (!project) {
295 return AsyncResult.success(undefined);
296 }
297 const settings = latestSettings();
298 const scripts = resolveProjectScripts(settings, project);
299 const nextScripts = scripts.filter((script) => script.id !== scriptId);
300
301 const deletedName = scripts.find((s) => s.id === scriptId)?.name;
302
303 const result = await persistProjectScripts({
304 settings,
305 projectId: project.id,
306 projectCwd: project.workspaceRoot,
307 previousScripts: scripts,
308 nextScripts,
309 keybinding: null,
310 keybindingCommand: commandForProjectScript(scriptId),
311 });
312 if (result._tag === "Success") {
313 toastManager.add({
314 type: "success",
315 title: m(
316 msg('Deleted action "{name}"', {
317 name:
318 deletedName ?? m(msg("Unknown", { $context: "fallback name of a deleted action" })),
319 }),
320 ),
321 });
322 } else if (!isAtomCommandInterrupted(result)) {
323 const error = squashAtomCommandFailure(result);
324 toastManager.add(
325 stackedThreadToast({
326 type: "error",
327 title: m(msg("Could not delete action")),
328 description: thrownErrorMessage(error, m) ?? m(msg("An unexpected error occurred.")),
329 }),
330 );
331 }
332 return result;
333 };
334 return {
335 saveProjectScript: useStableCallback((...args: Parameters<typeof saveProjectScript>) =>
336 enqueue(() => saveProjectScript(...args)),
337 ),
338 updateProjectScript: useStableCallback((...args: Parameters<typeof updateProjectScript>) =>
339 enqueue(() => updateProjectScript(...args)),
340 ),
341 deleteProjectScript: useStableCallback((...args: Parameters<typeof deleteProjectScript>) =>
342 enqueue(() => deleteProjectScript(...args)),
343 ),
344 };
345}