The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; |
| 2 | import { AuthSettingsWriteScope, EnvironmentAuthorizationError } from "@t3tools/contracts"; |
| 3 | import { readEnvironmentScope } from "../../state/session"; |
| 4 | import { |
| 5 | isAtomCommandInterrupted, |
| 6 | mapAtomCommandResult, |
| 7 | squashAtomCommandFailure, |
| 8 | type AtomCommandResult, |
| 9 | } from "@t3tools/client-runtime/state/runtime"; |
| 10 | import { |
| 11 | type EnvironmentId, |
| 12 | type ProjectId, |
| 13 | type ProjectScript, |
| 14 | type ResolvedKeybindingsConfig, |
| 15 | type ServerSettings, |
| 16 | } from "@t3tools/contracts"; |
| 17 | import { resolveProjectScripts } from "@t3tools/shared/projectScripts"; |
| 18 | import { clearProjectSettingsOverrides } from "@t3tools/shared/projectSettings"; |
| 19 | import * as Cause from "effect/Cause"; |
| 20 | import { AsyncResult } from "effect/reactivity"; |
| 21 | import { msg } from "gt-react"; |
| 22 | import { useRef, useState } from "react"; |
| 23 | |
| 24 | import { |
| 25 | decodeProjectScriptKeybindingRule, |
| 26 | keybindingValueForCommand, |
| 27 | } from "../../lib/projectScriptKeybindings"; |
| 28 | import { |
| 29 | buildProjectScript, |
| 30 | commandForProjectScript, |
| 31 | nextProjectScriptId, |
| 32 | releaseClaimedRoles, |
| 33 | } from "../../projectScripts"; |
| 34 | import { useProjects } from "../../state/entities"; |
| 35 | import { serverEnvironment } from "../../state/server"; |
| 36 | import { useAtomCommand } from "../../state/use-atom-command"; |
| 37 | import type { NewProjectScriptInput } from "../projectScriptEditor"; |
| 38 | import { m } from "../../i18n/messages"; |
| 39 | import { toastManager } from "../ui/toast"; |
| 40 | |
| 41 | function reportScriptFailure(result: AtomCommandResult<unknown, unknown>) { |
| 42 | if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { |
| 43 | const error = squashAtomCommandFailure(result); |
| 44 | toastManager.add({ |
| 45 | type: "error", |
| 46 | title: m(msg("Failed to save project actions")), |
| 47 | description: |
| 48 | error instanceof Error |
| 49 | ? (thrownErrorMessage(error, m) ?? error.message) |
| 50 | : m(msg("An error occurred.")), |
| 51 | }); |
| 52 | } |
| 53 | return mapAtomCommandResult(result, () => undefined); |
| 54 | } |
| 55 | |
| 56 | export function useProjectScriptSettings( |
| 57 | targets: readonly { |
| 58 | environmentId: EnvironmentId; |
| 59 | settings: ServerSettings; |
| 60 | keybindings: ResolvedKeybindingsConfig; |
| 61 | project?: { id: ProjectId; scripts: readonly ProjectScript[] }; |
| 62 | }[], |
| 63 | ) { |
| 64 | const projects = useProjects(); |
| 65 | const [saving, setSaving] = useState(false); |
| 66 | const savingRef = useRef(false); |
| 67 | const updateSettings = useAtomCommand(serverEnvironment.updateSettings, "project actions update"); |
| 68 | const upsertKeybinding = useAtomCommand( |
| 69 | serverEnvironment.upsertKeybinding, |
| 70 | "action shortcut update", |
| 71 | ); |
| 72 | const removeKeybinding = useAtomCommand( |
| 73 | serverEnvironment.removeKeybinding, |
| 74 | "action shortcut removal", |
| 75 | ); |
| 76 | |
| 77 | async function persist( |
| 78 | transform: (current: readonly ProjectScript[]) => readonly ProjectScript[] | null, |
| 79 | scriptId?: string, |
| 80 | keybinding?: string | null, |
| 81 | ): Promise<AtomCommandResult<void, unknown>> { |
| 82 | if (savingRef.current || targets.length === 0) { |
| 83 | const message = m(msg("No available machine, or another action change is saving.")); |
| 84 | toastManager.add({ |
| 85 | type: "error", |
| 86 | title: m(msg("Actions not saved")), |
| 87 | description: message, |
| 88 | }); |
| 89 | return AsyncResult.failure(Cause.fail(new Error(message))); |
| 90 | } |
| 91 | if ( |
| 92 | targets.some( |
| 93 | ({ environmentId }) => !readEnvironmentScope(environmentId, AuthSettingsWriteScope), |
| 94 | ) |
| 95 | ) { |
| 96 | return reportScriptFailure( |
| 97 | AsyncResult.failure( |
| 98 | Cause.fail( |
| 99 | new EnvironmentAuthorizationError({ |
| 100 | requiredScope: AuthSettingsWriteScope, |
| 101 | message: m(msg("This connection cannot change environment settings.")), |
| 102 | }), |
| 103 | ), |
| 104 | ), |
| 105 | ); |
| 106 | } |
| 107 | savingRef.current = true; |
| 108 | setSaving(true); |
| 109 | return writeTargets(transform, scriptId, keybinding).finally(() => { |
| 110 | savingRef.current = false; |
| 111 | setSaving(false); |
| 112 | }); |
| 113 | } |
| 114 | |
| 115 | async function writeTargets( |
| 116 | transform: (current: readonly ProjectScript[]) => readonly ProjectScript[] | null, |
| 117 | scriptId: string | undefined, |
| 118 | keybinding: string | null | undefined, |
| 119 | ): Promise<AtomCommandResult<void, unknown>> { |
| 120 | for (const { environmentId, settings, keybindings, project } of targets) { |
| 121 | const current = project |
| 122 | ? resolveProjectScripts(settings, project) |
| 123 | : settings.defaultProjectScripts; |
| 124 | const nextScripts = transform(current); |
| 125 | const effectiveScripts = nextScripts ?? settings.defaultProjectScripts; |
| 126 | const result = await updateSettings({ |
| 127 | environmentId, |
| 128 | input: { |
| 129 | patch: project |
| 130 | ? { |
| 131 | projectSettingsOverrides: { |
| 132 | [project.id]: |
| 133 | nextScripts === null |
| 134 | ? clearProjectSettingsOverrides(settings, project.id, [ |
| 135 | "defaultProjectScripts", |
| 136 | ]) |
| 137 | : { |
| 138 | ...settings.projectSettingsOverrides[project.id], |
| 139 | defaultProjectScripts: nextScripts, |
| 140 | }, |
| 141 | }, |
| 142 | } |
| 143 | : { defaultProjectScripts: nextScripts ?? [] }, |
| 144 | }, |
| 145 | }); |
| 146 | if (result._tag === "Failure") return reportScriptFailure(result); |
| 147 | const changedIds = scriptId |
| 148 | ? [scriptId] |
| 149 | : current |
| 150 | .filter((script) => !effectiveScripts.some((next) => next.id === script.id)) |
| 151 | .map((script) => script.id); |
| 152 | for (const id of changedIds) { |
| 153 | if (keybinding === undefined && effectiveScripts.some((script) => script.id === id)) { |
| 154 | continue; |
| 155 | } |
| 156 | const command = commandForProjectScript(id); |
| 157 | const previousValue = keybindingValueForCommand(keybindings, command); |
| 158 | const previous = previousValue |
| 159 | ? decodeProjectScriptKeybindingRule({ keybinding: previousValue, command }) |
| 160 | : null; |
| 161 | const next = decodeProjectScriptKeybindingRule({ keybinding, command }); |
| 162 | const retainedElsewhere = |
| 163 | !nextScripts?.some((script) => script.id === id) && |
| 164 | ((project && settings.defaultProjectScripts.some((script) => script.id === id)) || |
| 165 | Object.entries(settings.projectSettingsOverrides).some( |
| 166 | ([projectId, entry]) => |
| 167 | projectId !== project?.id && |
| 168 | entry.defaultProjectScripts?.some((script) => script.id === id), |
| 169 | ) || |
| 170 | projects.some( |
| 171 | (other) => |
| 172 | other.environmentId === environmentId && |
| 173 | other.id !== project?.id && |
| 174 | (project ? resolveProjectScripts(settings, other) : other.scripts).some( |
| 175 | (script) => script.id === id, |
| 176 | ), |
| 177 | )); |
| 178 | const bindingResult = next |
| 179 | ? await upsertKeybinding({ |
| 180 | environmentId, |
| 181 | input: previous && previous.key !== next.key ? { ...next, replace: previous } : next, |
| 182 | }) |
| 183 | : previous && !retainedElsewhere |
| 184 | ? await removeKeybinding({ environmentId, input: previous }) |
| 185 | : null; |
| 186 | if (bindingResult?._tag === "Failure") return reportScriptFailure(bindingResult); |
| 187 | } |
| 188 | } |
| 189 | return AsyncResult.success(undefined); |
| 190 | } |
| 191 | |
| 192 | function submit(scriptId: string | null, input: NewProjectScriptInput) { |
| 193 | const existingIds = [ |
| 194 | ...projects.flatMap((project) => project.scripts.map((script) => script.id)), |
| 195 | ...targets.flatMap(({ settings, project }) => |
| 196 | [ |
| 197 | ...settings.defaultProjectScripts, |
| 198 | ...Object.values(settings.projectSettingsOverrides).flatMap( |
| 199 | (entry) => entry.defaultProjectScripts ?? [], |
| 200 | ), |
| 201 | ...(project?.scripts ?? []), |
| 202 | ].map((script) => script.id), |
| 203 | ), |
| 204 | ]; |
| 205 | const id = scriptId ?? nextProjectScriptId(input.name, existingIds); |
| 206 | const next = buildProjectScript(id, input); |
| 207 | return persist( |
| 208 | (current) => { |
| 209 | const updated = current.map((script) => |
| 210 | script.id === id ? next : releaseClaimedRoles(script, input), |
| 211 | ); |
| 212 | return scriptId === null ? [...updated, next] : updated; |
| 213 | }, |
| 214 | id, |
| 215 | input.keybinding, |
| 216 | ); |
| 217 | } |
| 218 | |
| 219 | return { saving, persist, submit }; |
| 220 | } |