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