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