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