Open History to see the last commit
1import type {
2 ProjectScript,
3 ProjectScriptIcon,
4 ResolvedKeybindingsConfig,
5} from "@t3tools/contracts";
6import {
7 isAtomCommandInterrupted,
8 squashAtomCommandFailure,
9 type AtomCommandResult,
10} from "@t3tools/client-runtime/state/runtime";
11import {
12 BugIcon,
13 FlaskConicalIcon,
14 HammerIcon,
15 ListChecksIcon,
16 PlayIcon,
17 WrenchIcon,
18} from "lucide-react";
19import React, {
20 type FormEvent,
21 type KeyboardEvent,
22 useEffect,
23 useLayoutEffect,
24 useRef,
25 useState,
26} from "react";
27
28import {
29 keybindingValueForCommand,
30 decodeProjectScriptKeybindingRule,
31} from "~/lib/projectScriptKeybindings";
32import { keybindingFromKeyboardEvent } from "~/components/settings/KeybindingsSettings.logic";
33import { commandForProjectScript, nextProjectScriptId } from "~/projectScripts";
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: "Play" },
61 { id: "test", label: "Test" },
62 { id: "lint", label: "Lint" },
63 { id: "configure", label: "Configure" },
64 { id: "build", label: "Build" },
65 { id: "debug", label: "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 /** Setup scripts only: hold the agent until the script exits. */
89 waitForSetup: boolean;
90 keybinding: string | null;
91 /** Optional URL to open in the in-app preview when this script runs. */
92 previewUrl: string | null;
93 /** When true, automatically open the preview panel pointed at `previewUrl`. */
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 keybinding: null,
106 previewUrl: null,
107 autoOpenPreview: false,
108};
109
110/** What the editor dialog should open with. `scriptId: null` means "add". */
111export interface ProjectScriptEditorRequest {
112 scriptId: string | null;
113 initial: NewProjectScriptInput;
114 /** Validation error to show immediately (e.g. a failed t3.json import). */
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 keybinding: keybindingValueForCommand(keybindings, commandForProjectScript(script.id)),
131 previewUrl: script.previewUrl ?? null,
132 autoOpenPreview: script.autoOpenPreview ?? false,
133 },
134 };
135}
136
137/**
138 * Add/edit dialog for a project script, shared by the chat-header scripts menu
139 * and the project settings page. The parent owns which script (if any) is
140 * being edited via `request`; the dialog owns the form state and validation.
141 */
142export function ProjectScriptEditorDialog({
143 request,
144 scripts,
145 onSubmit,
146 onDelete,
147 onClose,
148}: {
149 request: ProjectScriptEditorRequest | null;
150 /** Existing scripts, used to derive a unique id for new scripts. */
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 formId = React.useId();
160 const [name, setName] = useState("");
161 const [command, setCommand] = useState("");
162 const [icon, setIcon] = useState<ProjectScriptIcon>("play");
163 const [iconPickerOpen, setIconPickerOpen] = useState(false);
164 const [runOnWorktreeCreate, setRunOnWorktreeCreate] = useState(false);
165 const [waitForSetup, setWaitForSetup] = useState(false);
166 const [keybinding, setKeybinding] = useState("");
167 const [previewUrl, setPreviewUrl] = useState("");
168 const [autoOpenPreview, setAutoOpenPreview] = useState(false);
169 const [validationError, setValidationError] = useState<string | null>(null);
170 const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
171 const [savingRequest, setSavingRequest] = useState<ProjectScriptEditorRequest | null>(null);
172 const pendingSubmissionRef = useRef<{ request: ProjectScriptEditorRequest } | null>(null);
173
174 const isOpen = request !== null;
175 const isEditing = request?.scriptId != null;
176 const isSaving = request !== null && savingRequest === request;
177
178 // A save completion must not affect a replacement request or an unmounted editor.
179 useLayoutEffect(
180 () => () => {
181 if (pendingSubmissionRef.current?.request === request) {
182 pendingSubmissionRef.current = null;
183 }
184 },
185 [request],
186 );
187
188 // Hydrate the form whenever a new request opens the dialog.
189 useEffect(() => {
190 if (!request) return;
191 setName(request.initial.name);
192 setCommand(request.initial.command);
193 setIcon(request.initial.icon);
194 setIconPickerOpen(false);
195 setRunOnWorktreeCreate(request.initial.runOnWorktreeCreate);
196 setWaitForSetup(request.initial.waitForSetup);
197 setKeybinding(request.initial.keybinding ?? "");
198 setPreviewUrl(request.initial.previewUrl ?? "");
199 setAutoOpenPreview(request.initial.autoOpenPreview);
200 setValidationError(request.error ?? null);
201 setSavingRequest(null);
202 }, [request]);
203
204 const close = () => {
205 pendingSubmissionRef.current = null;
206 setSavingRequest(null);
207 setIconPickerOpen(false);
208 onClose();
209 };
210
211 const captureKeybinding = (event: KeyboardEvent<HTMLInputElement>) => {
212 if (event.key === "Tab") return;
213 event.preventDefault();
214 if (event.key === "Backspace" || event.key === "Delete") {
215 setKeybinding("");
216 return;
217 }
218 const next = keybindingFromKeyboardEvent(event, navigator.platform);
219 if (!next) return;
220 setKeybinding(next);
221 };
222
223 const submit = async (event: FormEvent) => {
224 event.preventDefault();
225 if (!request || pendingSubmissionRef.current !== null) return;
226 const trimmedName = name.trim();
227 const trimmedCommand = command.trim();
228 if (trimmedName.length === 0) {
229 setValidationError("Name is required.");
230 return;
231 }
232 if (trimmedCommand.length === 0) {
233 setValidationError("Command is required.");
234 return;
235 }
236
237 setValidationError(null);
238 let payload: NewProjectScriptInput;
239 try {
240 const scriptIdForValidation =
241 request.scriptId ??
242 nextProjectScriptId(
243 trimmedName,
244 scripts.map((script) => script.id),
245 );
246 const keybindingRule = decodeProjectScriptKeybindingRule({
247 keybinding,
248 command: commandForProjectScript(scriptIdForValidation),
249 });
250 const trimmedPreviewUrl = previewUrl.trim();
251 payload = {
252 name: trimmedName,
253 command: trimmedCommand,
254 icon,
255 runOnWorktreeCreate,
256 waitForSetup: runOnWorktreeCreate && waitForSetup,
257 keybinding: keybindingRule?.key ?? null,
258 previewUrl: trimmedPreviewUrl.length > 0 ? trimmedPreviewUrl : null,
259 autoOpenPreview: trimmedPreviewUrl.length > 0 ? autoOpenPreview : false,
260 } satisfies NewProjectScriptInput;
261 } catch (error) {
262 setValidationError(error instanceof Error ? error.message : "Failed to save action.");
263 return;
264 }
265
266 const submission = { request };
267 pendingSubmissionRef.current = submission;
268 setSavingRequest(request);
269 setIconPickerOpen(false);
270 try {
271 const result = await onSubmit(request.scriptId, payload);
272 if (pendingSubmissionRef.current === submission) {
273 if (result._tag === "Failure") {
274 if (!isAtomCommandInterrupted(result)) {
275 const error = squashAtomCommandFailure(result);
276 setValidationError(error instanceof Error ? error.message : "Failed to save action.");
277 }
278 } else {
279 close();
280 }
281 }
282 } catch (error) {
283 if (pendingSubmissionRef.current === submission) {
284 setValidationError(error instanceof Error ? error.message : "Failed to save action.");
285 }
286 }
287 if (pendingSubmissionRef.current === submission) {
288 pendingSubmissionRef.current = null;
289 setSavingRequest(null);
290 }
291 };
292
293 return (
294 <>
295 <Dialog
296 open={isOpen}
297 onOpenChange={(open) => {
298 if (!open) {
299 close();
300 }
301 }}
302 >
303 <DialogPopup>
304 <DialogHeader>
305 <DialogTitle>{isEditing ? "Edit Action" : "Add Action"}</DialogTitle>
306 <DialogDescription>
307 Actions are project-scoped commands you can run from the top bar or keybindings.
308 </DialogDescription>
309 </DialogHeader>
310 <DialogPanel>
311 <form id={formId} onSubmit={submit}>
312 <fieldset className="space-y-4" disabled={isSaving}>
313 <div className="space-y-1.5">
314 <Label htmlFor="script-name">Name</Label>
315 <div className="flex items-center gap-2">
316 <Popover onOpenChange={setIconPickerOpen} open={iconPickerOpen}>
317 <PopoverTrigger
318 render={
319 <Button
320 type="button"
321 variant="outline"
322 className="size-9 shrink-0"
323 aria-label="Choose icon"
324 />
325 }
326 >
327 <ScriptIcon icon={icon} className="size-4.5" />
328 </PopoverTrigger>
329 <PopoverPopup align="start">
330 <div className="grid grid-cols-3 gap-2">
331 {SCRIPT_ICONS.map((entry) => {
332 const isSelected = entry.id === icon;
333 return (
334 <button
335 key={entry.id}
336 type="button"
337 className={`relative flex flex-col items-center gap-2 rounded-md border px-2 py-2 text-xs dark:border-transparent ${
338 isSelected
339 ? "border-primary/70 bg-primary/10 dark:ring-1 dark:ring-primary/30"
340 : "border-border/70 hover:bg-accent/60 dark:bg-white/[0.035]"
341 }`}
342 onClick={() => {
343 setIcon(entry.id);
344 setIconPickerOpen(false);
345 }}
346 >
347 <ScriptIcon icon={entry.id} className="size-4" />
348 <span>{entry.label}</span>
349 </button>
350 );
351 })}
352 </div>
353 </PopoverPopup>
354 </Popover>
355 <Input
356 id="script-name"
357 autoFocus
358 placeholder="Test"
359 value={name}
360 onChange={(event) => setName(event.target.value)}
361 />
362 </div>
363 </div>
364 <div className="space-y-1.5">
365 <Label htmlFor="script-keybinding">Keybinding</Label>
366 <Input
367 id="script-keybinding"
368 placeholder="Press shortcut"
369 value={keybinding}
370 readOnly
371 onKeyDown={captureKeybinding}
372 />
373 <p className="text-xs text-muted-foreground">
374 Press a shortcut. Use <code>Backspace</code> to clear. Shortcuts are
375 environment-wide. Projects using the same action share its shortcut.
376 </p>
377 </div>
378 <div className="space-y-1.5">
379 <Label htmlFor="script-command">Command</Label>
380 <Textarea
381 id="script-command"
382 placeholder="bun test"
383 value={command}
384 onChange={(event) => setCommand(event.target.value)}
385 />
386 </div>
387 <div className="space-y-1.5">
388 <Label htmlFor="script-preview-url">Preview URL (optional)</Label>
389 <Input
390 id="script-preview-url"
391 placeholder="http://localhost:5173"
392 value={previewUrl}
393 onChange={(event) => setPreviewUrl(event.target.value)}
394 />
395 <p className="text-xs text-muted-foreground">
396 Open this URL in the in-app preview when this action runs.
397 </p>
398 </div>
399 <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]">
400 <span>Run automatically on worktree creation</span>
401 <Switch
402 checked={runOnWorktreeCreate}
403 onCheckedChange={(checked) => setRunOnWorktreeCreate(Boolean(checked))}
404 />
405 </label>
406 <label
407 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] ${
408 runOnWorktreeCreate ? "" : "opacity-60"
409 }`}
410 >
411 <span>Wait for it to finish before the agent starts</span>
412 <Switch
413 checked={waitForSetup}
414 disabled={!runOnWorktreeCreate}
415 onCheckedChange={(checked) => setWaitForSetup(Boolean(checked))}
416 />
417 </label>
418 <label
419 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] ${
420 previewUrl.trim().length === 0 ? "opacity-60" : ""
421 }`}
422 >
423 <span>Open preview automatically when this action runs</span>
424 <Switch
425 checked={autoOpenPreview}
426 disabled={previewUrl.trim().length === 0}
427 onCheckedChange={(checked) => setAutoOpenPreview(Boolean(checked))}
428 />
429 </label>
430 {validationError && <p className="text-sm text-destructive">{validationError}</p>}
431 </fieldset>
432 </form>
433 </DialogPanel>
434 <DialogFooter variant="bare">
435 {isEditing && (
436 <Button
437 type="button"
438 variant="destructive-outline"
439 className="mr-auto"
440 disabled={isSaving}
441 onClick={() => setDeleteConfirmOpen(true)}
442 >
443 Delete
444 </Button>
445 )}
446 <Button type="button" variant="outline" onClick={close}>
447 Cancel
448 </Button>
449 <Button form={formId} type="submit" disabled={isSaving}>
450 {isSaving ? "Saving…" : isEditing ? "Save changes" : "Save action"}
451 </Button>
452 </DialogFooter>
453 </DialogPopup>
454 </Dialog>
455
456 <AlertDialog open={deleteConfirmOpen} onOpenChange={setDeleteConfirmOpen}>
457 <AlertDialogPopup>
458 <AlertDialogHeader>
459 <AlertDialogTitle>Delete action "{name}"?</AlertDialogTitle>
460 <AlertDialogDescription>This action cannot be undone.</AlertDialogDescription>
461 </AlertDialogHeader>
462 <AlertDialogFooter>
463 <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
464 <Button
465 variant="destructive"
466 disabled={isSaving}
467 onClick={() => {
468 if (!request?.scriptId) return;
469 setDeleteConfirmOpen(false);
470 close();
471 onDelete(request.scriptId);
472 }}
473 >
474 Delete action
475 </Button>
476 </AlertDialogFooter>
477 </AlertDialogPopup>
478 </AlertDialog>
479 </>
480 );
481}