Open History to see the last commit
1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import {
3 AuthOrchestrationOperateScope,
4 AuthSettingsWriteScope,
5 type EnvironmentId,
6 type ProjectScript,
7 type ProjectScriptIcon,
8 type ResolvedKeybindingsConfig,
9} from "@t3tools/contracts";
10import {
11 isAtomCommandInterrupted,
12 squashAtomCommandFailure,
13 type AtomCommandResult,
14} from "@t3tools/client-runtime/state/runtime";
15import {
16 BugIcon,
17 FlaskConicalIcon,
18 HammerIcon,
19 ListChecksIcon,
20 PlayIcon,
21 WrenchIcon,
22} from "lucide-react";
23import { msg, T, useGT, useMessages, Var } from "gt-react";
24import React, { type FormEvent, type KeyboardEvent, useEffect, useRef, useState } from "react";
25
26import {
27 keybindingValueForCommand,
28 decodeProjectScriptKeybindingRule,
29} from "~/lib/projectScriptKeybindings";
30import { keybindingFromKeyboardEvent } from "~/components/settings/KeybindingsSettings.logic";
31import { commandForProjectScript, nextProjectScriptId } from "~/projectScripts";
32import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
33import { useComposerMenuState } from "./chat/useComposerMenuState";
34import {
35 AlertDialog,
36 AlertDialogClose,
37 AlertDialogDescription,
38 AlertDialogFooter,
39 AlertDialogHeader,
40 AlertDialogPopup,
41 AlertDialogTitle,
42} from "./ui/alert-dialog";
43import { Button } from "./ui/button";
44import {
45 Dialog,
46 DialogDescription,
47 DialogFooter,
48 DialogHeader,
49 DialogPanel,
50 DialogPopup,
51 DialogTitle,
52} from "./ui/dialog";
53import { Input } from "./ui/input";
54import { Label } from "./ui/label";
55import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover";
56import { Switch } from "./ui/switch";
57import { Textarea } from "./ui/textarea";
58
59const SCRIPT_ICONS: Array<{ id: ProjectScriptIcon; label: string }> = [
60 { id: "play", label: msg("Play") },
61 { id: "test", label: msg("Test") },
62 { id: "lint", label: msg("Lint") },
63 { id: "configure", label: msg("Configure") },
64 { id: "build", label: msg("Build") },
65 { id: "debug", label: msg("Debug") },
66];
67
68export function ScriptIcon({
69 icon,
70 className = "size-3.5",
71}: {
72 icon: ProjectScriptIcon;
73 className?: string;
74}) {
75 if (icon === "test") return <FlaskConicalIcon className={className} />;
76 if (icon === "lint") return <ListChecksIcon className={className} />;
77 if (icon === "configure") return <WrenchIcon className={className} />;
78 if (icon === "build") return <HammerIcon className={className} />;
79 if (icon === "debug") return <BugIcon className={className} />;
80 return <PlayIcon className={className} />;
81}
82
83export interface NewProjectScriptInput {
84 name: string;
85 command: string;
86 icon: ProjectScriptIcon;
87 runOnWorktreeCreate: boolean;
88 waitForSetup: boolean;
89 runOnSettle: boolean;
90 stopOnSettle?: boolean;
91 /** Omit to preserve the current shortcut when the form did not edit it. */
92 keybinding?: string | null;
93 previewUrl: string | null;
94 autoOpenPreview: boolean;
95}
96
97export type ProjectScriptActionResult = AtomCommandResult<void, unknown>;
98
99export const EMPTY_PROJECT_SCRIPT_INPUT: NewProjectScriptInput = {
100 name: "",
101 command: "",
102 icon: "play",
103 runOnWorktreeCreate: false,
104 waitForSetup: false,
105 runOnSettle: false,
106 stopOnSettle: false,
107 keybinding: null,
108 previewUrl: null,
109 autoOpenPreview: false,
110};
111
112export interface ProjectScriptEditorRequest {
113 scriptId: string | null;
114 initial: NewProjectScriptInput;
115 error?: string;
116}
117
118export function editorRequestForScript(
119 script: ProjectScript,
120 keybindings: ResolvedKeybindingsConfig,
121): ProjectScriptEditorRequest {
122 return {
123 scriptId: script.id,
124 initial: {
125 name: script.name,
126 command: script.command,
127 icon: script.icon,
128 runOnWorktreeCreate: script.runOnWorktreeCreate,
129 waitForSetup: script.runOnWorktreeCreate && script.async === false,
130 runOnSettle: script.runOnSettle ?? false,
131 stopOnSettle: script.stopOnSettle ?? false,
132 keybinding: keybindingValueForCommand(keybindings, commandForProjectScript(script.id)),
133 previewUrl: script.previewUrl ?? null,
134 autoOpenPreview: script.autoOpenPreview ?? false,
135 },
136 };
137}
138
139export function ProjectScriptEditorDialog({
140 environmentId,
141 editScope = AuthOrchestrationOperateScope,
142 request,
143 scripts,
144 onSubmit,
145 onDelete,
146 onClose,
147}: {
148 environmentId: EnvironmentId;
149 editScope?: typeof AuthOrchestrationOperateScope | typeof AuthSettingsWriteScope;
150 request: ProjectScriptEditorRequest | null;
151 scripts: ReadonlyArray<ProjectScript>;
152 onSubmit: (
153 scriptId: string | null,
154 input: NewProjectScriptInput,
155 ) => Promise<ProjectScriptActionResult>;
156 onDelete: (scriptId: string) => void;
157 onClose: () => void;
158}) {
159 const gt = useGT();
160 const canEditActions = useEnvironmentScope(environmentId, editScope);
161 // Scope errors by request so late saves cannot overwrite a newer request's error.
162 const [errorState, setErrorState] = useState<{
163 readonly request: ProjectScriptEditorRequest;
164 readonly message: string | null;
165 } | null>(null);
166 const validationError =
167 request === null
168 ? null
169 : errorState?.request === request
170 ? errorState.message
171 : (request.error ?? null);
172 const setValidationError = (message: string | null) => {
173 if (request !== null) setErrorState({ request, message });
174 };
175 // The last opened request stays shown while the dialog animates closed. Each
176 // new request mounts a fresh form, which drops the previous request's save.
177 const [shown, setShown] = useState<{
178 readonly request: ProjectScriptEditorRequest;
179 readonly key: number;
180 } | null>(request === null ? null : { request, key: 0 });
181 if (request !== null && request !== shown?.request) {
182 setShown({ request, key: (shown?.key ?? 0) + 1 });
183 }
184 const [deleteConfirmOpen, setDeleteConfirmOpen] = useComposerMenuState(!canEditActions);
185 const [deleteName, setDeleteName] = useState("");
186
187 return (
188 <>
189 <Dialog
190 open={request !== null}
191 // A stray click outside would discard the unsaved draft; Escape and Cancel still close it.
192 disablePointerDismissal
193 onOpenChange={(open) => {
194 if (!open) onClose();
195 }}
196 >
197 {/* The form owns its fields so a keystroke re-renders it, not the dialog chrome. */}
198 <DialogPopup>
199 {shown ? (
200 <ProjectScriptEditorForm
201 key={shown.key}
202 environmentId={environmentId}
203 editScope={editScope}
204 request={shown.request}
205 scripts={scripts}
206 validationError={validationError}
207 onValidationError={setValidationError}
208 onSubmit={onSubmit}
209 onRequestDelete={(name) => {
210 setDeleteName(name);
211 setDeleteConfirmOpen(true);
212 }}
213 onClose={onClose}
214 />
215 ) : null}
216 </DialogPopup>
217 </Dialog>
218
219 <AlertDialog open={deleteConfirmOpen && canEditActions} onOpenChange={setDeleteConfirmOpen}>
220 <AlertDialogPopup>
221 <AlertDialogHeader>
222 <AlertDialogTitle>
223 <T>
224 Delete action "<Var>{deleteName}</Var>"?
225 </T>
226 </AlertDialogTitle>
227 <AlertDialogDescription>
228 <T>This action cannot be undone.</T>
229 </AlertDialogDescription>
230 </AlertDialogHeader>
231 <AlertDialogFooter>
232 <AlertDialogClose render={<Button variant="outline" />}>
233 <T>Cancel</T>
234 </AlertDialogClose>
235 <Button
236 variant="destructive"
237 disabled={!canEditActions}
238 onClick={() => {
239 if (!request?.scriptId) return;
240 if (!readEnvironmentScope(environmentId, editScope)) {
241 setValidationError(gt("This connection cannot change project actions."));
242 return;
243 }
244 setDeleteConfirmOpen(false);
245 onClose();
246 onDelete(request.scriptId);
247 }}
248 >
249 <T>Delete action</T>
250 </Button>
251 </AlertDialogFooter>
252 </AlertDialogPopup>
253 </AlertDialog>
254 </>
255 );
256}
257
258function ProjectScriptEditorForm({
259 environmentId,
260 editScope,
261 request,
262 scripts,
263 validationError,
264 onValidationError: setValidationError,
265 onSubmit,
266 onRequestDelete,
267 onClose,
268}: {
269 environmentId: EnvironmentId;
270 editScope: typeof AuthOrchestrationOperateScope | typeof AuthSettingsWriteScope;
271 request: ProjectScriptEditorRequest;
272 scripts: ReadonlyArray<ProjectScript>;
273 validationError: string | null;
274 onValidationError: (error: string | null) => void;
275 onSubmit: (
276 scriptId: string | null,
277 input: NewProjectScriptInput,
278 ) => Promise<ProjectScriptActionResult>;
279 onRequestDelete: (name: string) => void;
280 onClose: () => void;
281}) {
282 const gt = useGT();
283 const m = useMessages();
284 const canEditActions = useEnvironmentScope(environmentId, editScope);
285 const canWriteSettings = useEnvironmentScope(environmentId, AuthSettingsWriteScope);
286 const formId = React.useId();
287 const [name, setName] = useState(request.initial.name);
288 const [command, setCommand] = useState(request.initial.command);
289 const [icon, setIcon] = useState<ProjectScriptIcon>(request.initial.icon);
290 const [iconPickerOpen, setIconPickerOpen] = useComposerMenuState(!canEditActions);
291 const [runOnWorktreeCreate, setRunOnWorktreeCreate] = useState(
292 request.initial.runOnWorktreeCreate,
293 );
294 const [waitForSetup, setWaitForSetup] = useState(request.initial.waitForSetup);
295 const [runOnSettle, setRunOnSettle] = useState(request.initial.runOnSettle);
296 const [stopOnSettle, setStopOnSettle] = useState(request.initial.stopOnSettle ?? false);
297 const [keybinding, setKeybinding] = useState(request.initial.keybinding ?? "");
298 const [previewUrl, setPreviewUrl] = useState(request.initial.previewUrl ?? "");
299 const [autoOpenPreview, setAutoOpenPreview] = useState(request.initial.autoOpenPreview);
300 const [isSaving, setIsSaving] = useState(false);
301 const pendingSubmissionRef = useRef<object | null>(null);
302 // A save that settles after this form is replaced must not close or error
303 // the request that replaced it.
304 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- drops the pending save on unmount so a late result cannot close or fail the next request
305 useEffect(
306 () => () => {
307 pendingSubmissionRef.current = null;
308 },
309 [],
310 );
311
312 const isEditing = request.scriptId != null;
313
314 const close = () => {
315 pendingSubmissionRef.current = null;
316 setIsSaving(false);
317 setIconPickerOpen(false);
318 onClose();
319 };
320
321 const captureKeybinding = (event: KeyboardEvent<HTMLInputElement>) => {
322 if (!readEnvironmentScope(environmentId, editScope)) return;
323 if (!readEnvironmentScope(environmentId, AuthSettingsWriteScope)) return;
324 if (event.key === "Tab") return;
325 event.preventDefault();
326 if (event.key === "Backspace" || event.key === "Delete") {
327 setKeybinding("");
328 return;
329 }
330 const next = keybindingFromKeyboardEvent(event, navigator.platform);
331 if (!next) return;
332 setKeybinding(next);
333 };
334
335 const submit = async (event: FormEvent) => {
336 event.preventDefault();
337 if (pendingSubmissionRef.current !== null) return;
338 if (!readEnvironmentScope(environmentId, editScope)) {
339 setValidationError(gt("This connection cannot change project actions."));
340 return;
341 }
342 const changesKeybinding =
343 (keybinding.trim() || null) !== (request.initial.keybinding?.trim() || null);
344 const canChangeKeybinding = readEnvironmentScope(environmentId, AuthSettingsWriteScope);
345 if (changesKeybinding && !canChangeKeybinding) {
346 setValidationError(gt("This connection cannot change keyboard shortcuts."));
347 return;
348 }
349 const trimmedName = name.trim();
350 const trimmedCommand = command.trim();
351 if (trimmedName.length === 0) {
352 setValidationError(gt("Name is required."));
353 return;
354 }
355 if (trimmedCommand.length === 0) {
356 setValidationError(gt("Command is required."));
357 return;
358 }
359
360 setValidationError(null);
361 let payload: NewProjectScriptInput;
362 try {
363 const scriptIdForValidation =
364 request.scriptId ??
365 nextProjectScriptId(
366 trimmedName,
367 scripts.map((script) => script.id),
368 );
369 const keybindingRule = decodeProjectScriptKeybindingRule({
370 keybinding,
371 command: commandForProjectScript(scriptIdForValidation),
372 });
373 const trimmedPreviewUrl = previewUrl.trim();
374 payload = {
375 name: trimmedName,
376 command: trimmedCommand,
377 icon,
378 runOnWorktreeCreate,
379 waitForSetup: runOnWorktreeCreate && waitForSetup,
380 runOnSettle,
381 stopOnSettle,
382 ...((request.scriptId === null && canChangeKeybinding) || changesKeybinding
383 ? { keybinding: keybindingRule?.key ?? null }
384 : {}),
385 previewUrl: trimmedPreviewUrl.length > 0 ? trimmedPreviewUrl : null,
386 autoOpenPreview: trimmedPreviewUrl.length > 0 ? autoOpenPreview : false,
387 } satisfies NewProjectScriptInput;
388 } catch (error) {
389 setValidationError(thrownErrorMessage(error, m) ?? gt("Failed to save action."));
390 return;
391 }
392
393 const submission = {};
394 pendingSubmissionRef.current = submission;
395 setIsSaving(true);
396 setIconPickerOpen(false);
397 try {
398 const result = await onSubmit(request.scriptId, payload);
399 if (pendingSubmissionRef.current === submission) {
400 if (result._tag === "Failure") {
401 if (!isAtomCommandInterrupted(result)) {
402 const error = squashAtomCommandFailure(result);
403 setValidationError(thrownErrorMessage(error, m) ?? gt("Failed to save action."));
404 }
405 } else {
406 close();
407 }
408 }
409 } catch (error) {
410 if (pendingSubmissionRef.current === submission) {
411 setValidationError(thrownErrorMessage(error, m) ?? gt("Failed to save action."));
412 }
413 }
414 if (pendingSubmissionRef.current === submission) {
415 pendingSubmissionRef.current = null;
416 setIsSaving(false);
417 }
418 };
419
420 return (
421 <>
422 <DialogHeader>
423 <DialogTitle>{isEditing ? <T>Edit Action</T> : <T>Add Action</T>}</DialogTitle>
424 <DialogDescription>
425 <T>Actions are project-scoped commands you can run from the top bar or keybindings.</T>
426 </DialogDescription>
427 </DialogHeader>
428 <DialogPanel>
429 <form id={formId} onSubmit={submit}>
430 <fieldset className="space-y-4" disabled={isSaving || !canEditActions}>
431 <div className="space-y-1.5">
432 <Label htmlFor="script-name">
433 <T>Name</T>
434 </Label>
435 <div className="flex items-center gap-2">
436 <Popover onOpenChange={setIconPickerOpen} open={iconPickerOpen}>
437 <PopoverTrigger
438 render={
439 <Button
440 type="button"
441 variant="outline"
442 className="size-9 shrink-0"
443 aria-label={gt("Choose icon")}
444 />
445 }
446 >
447 <ScriptIcon icon={icon} className="size-4.5" />
448 </PopoverTrigger>
449 <PopoverPopup align="start">
450 <div className="grid grid-cols-3 gap-2">
451 {SCRIPT_ICONS.map((entry) => {
452 const isSelected = entry.id === icon;
453 return (
454 <button
455 key={entry.id}
456 type="button"
457 className={`relative flex flex-col items-center gap-2 rounded-md border px-2 py-2 text-xs dark:border-transparent ${
458 isSelected
459 ? "border-primary/70 bg-primary/10 ring-inset dark:ring-1 dark:ring-primary/30"
460 : "border-border/70 hover:bg-accent/60 dark:bg-white/[0.035]"
461 }`}
462 onClick={() => {
463 setIcon(entry.id);
464 setIconPickerOpen(false);
465 }}
466 >
467 <ScriptIcon icon={entry.id} className="size-4" />
468 <span>{m(entry.label)}</span>
469 </button>
470 );
471 })}
472 </div>
473 </PopoverPopup>
474 </Popover>
475 <Input
476 id="script-name"
477 autoFocus
478 placeholder={gt("Test", { $context: "example action name" })}
479 value={name}
480 onChange={(event) => setName(event.target.value)}
481 />
482 </div>
483 </div>
484 <div className="space-y-1.5">
485 <Label htmlFor="script-keybinding">
486 <T>Keybinding</T>
487 </Label>
488 <Input
489 disabled={!canWriteSettings}
490 id="script-keybinding"
491 placeholder={gt("Press shortcut")}
492 value={keybinding}
493 readOnly
494 onKeyDown={captureKeybinding}
495 />
496 <p className="text-xs text-muted-foreground">
497 <T>
498 Press a shortcut. Use <code>Backspace</code> to clear. Shortcuts are
499 environment-wide. Projects using the same action share its shortcut.
500 </T>
501 </p>
502 </div>
503 <div className="space-y-1.5">
504 <Label htmlFor="script-command">
505 <T>Command</T>
506 </Label>
507 <Textarea
508 id="script-command"
509 // oxlint-disable-next-line t3code/no-untranslated-copy -- example shell command
510 placeholder="bun test"
511 value={command}
512 onChange={(event) => setCommand(event.target.value)}
513 />
514 </div>
515 <div className="space-y-1.5">
516 <Label htmlFor="script-preview-url">
517 <T>Preview URL (optional)</T>
518 </Label>
519 <Input
520 id="script-preview-url"
521 placeholder="http://localhost:5173"
522 value={previewUrl}
523 onChange={(event) => setPreviewUrl(event.target.value)}
524 />
525 <p className="text-xs text-muted-foreground">
526 <T>Open this URL in the in-app preview when this action runs.</T>
527 </p>
528 </div>
529 <label className="flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm dark:border-transparent dark:bg-white/[0.035]">
530 <span>
531 <T>Run automatically on worktree creation</T>
532 </span>
533 <Switch
534 checked={runOnWorktreeCreate}
535 onCheckedChange={(checked) => setRunOnWorktreeCreate(Boolean(checked))}
536 />
537 </label>
538 <label
539 className={`flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm dark:border-transparent dark:bg-white/[0.035] ${
540 runOnWorktreeCreate ? "" : "opacity-60"
541 }`}
542 >
543 <span>
544 <T>Wait for it to finish before the agent starts</T>
545 </span>
546 <Switch
547 checked={waitForSetup}
548 disabled={!runOnWorktreeCreate}
549 onCheckedChange={(checked) => setWaitForSetup(Boolean(checked))}
550 />
551 </label>
552 <label className="flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm dark:border-transparent dark:bg-white/[0.035]">
553 <span>
554 <T>Run in the thread's worktree when the thread settles</T>
555 </span>
556 <Switch
557 checked={runOnSettle}
558 onCheckedChange={(checked) => setRunOnSettle(Boolean(checked))}
559 />
560 </label>
561 <label className="flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm dark:border-transparent dark:bg-white/[0.035]">
562 <span>
563 <T>Stop this action when the thread settles</T>
564 </span>
565 <Switch
566 checked={stopOnSettle}
567 onCheckedChange={(checked) => setStopOnSettle(Boolean(checked))}
568 />
569 </label>
570 <label
571 className={`flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm dark:border-transparent dark:bg-white/[0.035] ${
572 previewUrl.trim().length === 0 ? "opacity-60" : ""
573 }`}
574 >
575 <span>
576 <T>Open preview automatically when this action runs</T>
577 </span>
578 <Switch
579 checked={autoOpenPreview}
580 disabled={previewUrl.trim().length === 0}
581 onCheckedChange={(checked) => setAutoOpenPreview(Boolean(checked))}
582 />
583 </label>
584 {validationError && <p className="text-sm text-destructive">{validationError}</p>}
585 </fieldset>
586 </form>
587 </DialogPanel>
588 <DialogFooter variant="bare">
589 {isEditing && (
590 <Button
591 type="button"
592 variant="destructive-outline"
593 className="mr-auto"
594 disabled={isSaving || !canEditActions}
595 onClick={() => onRequestDelete(name)}
596 >
597 <T context="verb, delete the action">Delete</T>
598 </Button>
599 )}
600 <Button type="button" variant="outline" onClick={close}>
601 <T>Cancel</T>
602 </Button>
603 <Button form={formId} type="submit" disabled={isSaving || !canEditActions}>
604 {isSaving ? <T>Saving…</T> : isEditing ? <T>Save changes</T> : <T>Save action</T>}
605 </Button>
606 </DialogFooter>
607 </>
608 );
609}