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 /** Setup scripts only: hold the agent until the script exits. */
94 waitForSetup: boolean;
95 /** Omit to preserve the current shortcut when the form did not edit it. */
96 keybinding?: string | null;
97 /** Optional URL to open in the in-app preview when this script runs. */
98 previewUrl: string | null;
99 /** When true, automatically open the preview panel pointed at `previewUrl`. */
100 autoOpenPreview: boolean;
101}
102
103export type ProjectScriptActionResult = AtomCommandResult<void, unknown>;
104
105export const EMPTY_PROJECT_SCRIPT_INPUT: NewProjectScriptInput = {
106 name: "",
107 command: "",
108 icon: "play",
109 runOnWorktreeCreate: false,
110 waitForSetup: false,
111 keybinding: null,
112 previewUrl: null,
113 autoOpenPreview: false,
114};
115
116/** What the editor dialog should open with. `scriptId: null` means "add". */
117export interface ProjectScriptEditorRequest {
118 scriptId: string | null;
119 initial: NewProjectScriptInput;
120 /** Validation error to show immediately (e.g. a failed t3.json import). */
121 error?: string;
122}
123
124export function editorRequestForScript(
125 script: ProjectScript,
126 keybindings: ResolvedKeybindingsConfig,
127): ProjectScriptEditorRequest {
128 return {
129 scriptId: script.id,
130 initial: {
131 name: script.name,
132 command: script.command,
133 icon: script.icon,
134 runOnWorktreeCreate: script.runOnWorktreeCreate,
135 waitForSetup: script.runOnWorktreeCreate && script.async === false,
136 keybinding: keybindingValueForCommand(keybindings, commandForProjectScript(script.id)),
137 previewUrl: script.previewUrl ?? null,
138 autoOpenPreview: script.autoOpenPreview ?? false,
139 },
140 };
141}
142
143/**
144 * Add/edit dialog for a project script, shared by the chat-header scripts menu
145 * and the project settings page. The parent owns which script (if any) is
146 * being edited via `request`; the dialog owns the form state and validation.
147 */
148export function ProjectScriptEditorDialog({
149 environmentId,
150 editScope = AuthOrchestrationOperateScope,
151 request,
152 scripts,
153 onSubmit,
154 onDelete,
155 onClose,
156}: {
157 environmentId: EnvironmentId;
158 editScope?: typeof AuthOrchestrationOperateScope | typeof AuthSettingsWriteScope;
159 request: ProjectScriptEditorRequest | null;
160 /** Existing scripts, used to derive a unique id for new scripts. */
161 scripts: ReadonlyArray<ProjectScript>;
162 onSubmit: (
163 scriptId: string | null,
164 input: NewProjectScriptInput,
165 ) => Promise<ProjectScriptActionResult>;
166 onDelete: (scriptId: string) => void;
167 onClose: () => void;
168}) {
169 const canEditActions = useEnvironmentScope(environmentId, editScope);
170 const canWriteSettings = useEnvironmentScope(environmentId, AuthSettingsWriteScope);
171 const formId = React.useId();
172 const [name, setName] = useState("");
173 const [command, setCommand] = useState("");
174 const [icon, setIcon] = useState<ProjectScriptIcon>("play");
175 const [iconPickerOpen, setIconPickerOpen] = useComposerMenuState(!canEditActions);
176 const [runOnWorktreeCreate, setRunOnWorktreeCreate] = useState(false);
177 const [waitForSetup, setWaitForSetup] = useState(false);
178 const [keybinding, setKeybinding] = useState("");
179 const [previewUrl, setPreviewUrl] = useState("");
180 const [autoOpenPreview, setAutoOpenPreview] = useState(false);
181 const [validationError, setValidationError] = useState<string | null>(null);
182 const [deleteConfirmOpen, setDeleteConfirmOpen] = useComposerMenuState(!canEditActions);
183 const [savingRequest, setSavingRequest] = useState<ProjectScriptEditorRequest | null>(null);
184 const pendingSubmissionRef = useRef<{ request: ProjectScriptEditorRequest } | null>(null);
185
186 const isOpen = request !== null;
187 const isEditing = request?.scriptId != null;
188 const isSaving = request !== null && savingRequest === request;
189
190 // A save completion must not affect a replacement request or an unmounted editor.
191 useLayoutEffect(
192 () => () => {
193 if (pendingSubmissionRef.current?.request === request) {
194 pendingSubmissionRef.current = null;
195 }
196 },
197 [request],
198 );
199
200 // Hydrate the form whenever a new request opens the dialog.
201 useEffect(() => {
202 if (!request) return;
203 setName(request.initial.name);
204 setCommand(request.initial.command);
205 setIcon(request.initial.icon);
206 setIconPickerOpen(false);
207 setRunOnWorktreeCreate(request.initial.runOnWorktreeCreate);
208 setWaitForSetup(request.initial.waitForSetup);
209 setKeybinding(request.initial.keybinding ?? "");
210 setPreviewUrl(request.initial.previewUrl ?? "");
211 setAutoOpenPreview(request.initial.autoOpenPreview);
212 setValidationError(request.error ?? null);
213 setSavingRequest(null);
214 }, [request, setIconPickerOpen]);
215
216 const close = () => {
217 pendingSubmissionRef.current = null;
218 setSavingRequest(null);
219 setIconPickerOpen(false);
220 onClose();
221 };
222
223 const captureKeybinding = (event: KeyboardEvent<HTMLInputElement>) => {
224 if (!readEnvironmentScope(environmentId, editScope)) return;
225 if (!readEnvironmentScope(environmentId, AuthSettingsWriteScope)) return;
226 if (event.key === "Tab") return;
227 event.preventDefault();
228 if (event.key === "Backspace" || event.key === "Delete") {
229 setKeybinding("");
230 return;
231 }
232 const next = keybindingFromKeyboardEvent(event, navigator.platform);
233 if (!next) return;
234 setKeybinding(next);
235 };
236
237 const submit = async (event: FormEvent) => {
238 event.preventDefault();
239 if (!request || pendingSubmissionRef.current !== null) return;
240 if (!readEnvironmentScope(environmentId, editScope)) {
241 setValidationError("This connection cannot change project actions.");
242 return;
243 }
244 const changesKeybinding =
245 (keybinding.trim() || null) !== (request.initial.keybinding?.trim() || null);
246 const canChangeKeybinding = readEnvironmentScope(environmentId, AuthSettingsWriteScope);
247 if (changesKeybinding && !canChangeKeybinding) {
248 setValidationError("This connection cannot change keyboard shortcuts.");
249 return;
250 }
251 const trimmedName = name.trim();
252 const trimmedCommand = command.trim();
253 if (trimmedName.length === 0) {
254 setValidationError("Name is required.");
255 return;
256 }
257 if (trimmedCommand.length === 0) {
258 setValidationError("Command is required.");
259 return;
260 }
261
262 setValidationError(null);
263 let payload: NewProjectScriptInput;
264 try {
265 const scriptIdForValidation =
266 request.scriptId ??
267 nextProjectScriptId(
268 trimmedName,
269 scripts.map((script) => script.id),
270 );
271 const keybindingRule = decodeProjectScriptKeybindingRule({
272 keybinding,
273 command: commandForProjectScript(scriptIdForValidation),
274 });
275 const trimmedPreviewUrl = previewUrl.trim();
276 payload = {
277 name: trimmedName,
278 command: trimmedCommand,
279 icon,
280 runOnWorktreeCreate,
281 waitForSetup: runOnWorktreeCreate && waitForSetup,
282 ...((request.scriptId === null && canChangeKeybinding) || changesKeybinding
283 ? { keybinding: keybindingRule?.key ?? null }
284 : {}),
285 previewUrl: trimmedPreviewUrl.length > 0 ? trimmedPreviewUrl : null,
286 autoOpenPreview: trimmedPreviewUrl.length > 0 ? autoOpenPreview : false,
287 } satisfies NewProjectScriptInput;
288 } catch (error) {
289 setValidationError(error instanceof Error ? error.message : "Failed to save action.");
290 return;
291 }
292
293 const submission = { request };
294 pendingSubmissionRef.current = submission;
295 setSavingRequest(request);
296 setIconPickerOpen(false);
297 try {
298 const result = await onSubmit(request.scriptId, payload);
299 if (pendingSubmissionRef.current === submission) {
300 if (result._tag === "Failure") {
301 if (!isAtomCommandInterrupted(result)) {
302 const error = squashAtomCommandFailure(result);
303 setValidationError(error instanceof Error ? error.message : "Failed to save action.");
304 }
305 } else {
306 close();
307 }
308 }
309 } catch (error) {
310 if (pendingSubmissionRef.current === submission) {
311 setValidationError(error instanceof Error ? error.message : "Failed to save action.");
312 }
313 }
314 if (pendingSubmissionRef.current === submission) {
315 pendingSubmissionRef.current = null;
316 setSavingRequest(null);
317 }
318 };
319
320 return (
321 <>
322 <Dialog
323 open={isOpen}
324 onOpenChange={(open) => {
325 if (!open) {
326 close();
327 }
328 }}
329 >
330 <DialogPopup>
331 <DialogHeader>
332 <DialogTitle>{isEditing ? "Edit Action" : "Add Action"}</DialogTitle>
333 <DialogDescription>
334 Actions are project-scoped commands you can run from the top bar or keybindings.
335 </DialogDescription>
336 </DialogHeader>
337 <DialogPanel>
338 <form id={formId} onSubmit={submit}>
339 <fieldset className="space-y-4" disabled={isSaving || !canEditActions}>
340 <div className="space-y-1.5">
341 <Label htmlFor="script-name">Name</Label>
342 <div className="flex items-center gap-2">
343 <Popover onOpenChange={setIconPickerOpen} open={iconPickerOpen}>
344 <PopoverTrigger
345 render={
346 <Button
347 type="button"
348 variant="outline"
349 className="size-9 shrink-0"
350 aria-label="Choose icon"
351 />
352 }
353 >
354 <ScriptIcon icon={icon} className="size-4.5" />
355 </PopoverTrigger>
356 <PopoverPopup align="start">
357 <div className="grid grid-cols-3 gap-2">
358 {SCRIPT_ICONS.map((entry) => {
359 const isSelected = entry.id === icon;
360 return (
361 <button
362 key={entry.id}
363 type="button"
364 className={`relative flex flex-col items-center gap-2 rounded-md border px-2 py-2 text-xs dark:border-transparent ${
365 isSelected
366 ? "border-primary/70 bg-primary/10 dark:ring-1 dark:ring-primary/30"
367 : "border-border/70 hover:bg-accent/60 dark:bg-white/[0.035]"
368 }`}
369 onClick={() => {
370 setIcon(entry.id);
371 setIconPickerOpen(false);
372 }}
373 >
374 <ScriptIcon icon={entry.id} className="size-4" />
375 <span>{entry.label}</span>
376 </button>
377 );
378 })}
379 </div>
380 </PopoverPopup>
381 </Popover>
382 <Input
383 id="script-name"
384 autoFocus
385 placeholder="Test"
386 value={name}
387 onChange={(event) => setName(event.target.value)}
388 />
389 </div>
390 </div>
391 <div className="space-y-1.5">
392 <Label htmlFor="script-keybinding">Keybinding</Label>
393 <Input
394 disabled={!canWriteSettings}
395 id="script-keybinding"
396 placeholder="Press shortcut"
397 value={keybinding}
398 readOnly
399 onKeyDown={captureKeybinding}
400 />
401 <p className="text-xs text-muted-foreground">
402 Press a shortcut. Use <code>Backspace</code> to clear. Shortcuts are
403 environment-wide. Projects using the same action share its shortcut.
404 </p>
405 </div>
406 <div className="space-y-1.5">
407 <Label htmlFor="script-command">Command</Label>
408 <Textarea
409 id="script-command"
410 placeholder="bun test"
411 value={command}
412 onChange={(event) => setCommand(event.target.value)}
413 />
414 </div>
415 <div className="space-y-1.5">
416 <Label htmlFor="script-preview-url">Preview URL (optional)</Label>
417 <Input
418 id="script-preview-url"
419 placeholder="http://localhost:5173"
420 value={previewUrl}
421 onChange={(event) => setPreviewUrl(event.target.value)}
422 />
423 <p className="text-xs text-muted-foreground">
424 Open this URL in the in-app preview when this action runs.
425 </p>
426 </div>
427 <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]">
428 <span>Run automatically on worktree creation</span>
429 <Switch
430 checked={runOnWorktreeCreate}
431 onCheckedChange={(checked) => setRunOnWorktreeCreate(Boolean(checked))}
432 />
433 </label>
434 <label
435 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] ${
436 runOnWorktreeCreate ? "" : "opacity-60"
437 }`}
438 >
439 <span>Wait for it to finish before the agent starts</span>
440 <Switch
441 checked={waitForSetup}
442 disabled={!runOnWorktreeCreate}
443 onCheckedChange={(checked) => setWaitForSetup(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}