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