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