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