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

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