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