Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

projectScriptEditor.tsx

623 lines22.3 KB

1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import {
3 AuthOrchestrationOperateScope,
4 AuthSettingsWriteScope,
5 type EnvironmentId,
6 type ProjectScript,
7 type ProjectScriptIcon,
8 type ResolvedKeybindingsConfig,
9} from "@t3tools/contracts";
10import {
11 isAtomCommandInterrupted,
12 squashAtomCommandFailure,
13 type AtomCommandResult,
14} from "@t3tools/client-runtime/state/runtime";
15import {
16 BugIcon,
17 FlaskConicalIcon,
18 HammerIcon,
19 ListChecksIcon,
20 PlayIcon,
21 WrenchIcon,
22} from "lucide-react";
23import { msg, T, useGT, useMessages, Var } from "gt-react";
24import React, { type FormEvent, type KeyboardEvent, useEffect, useRef, useState } from "react";
25​
26import {
27 keybindingValueForCommand,
28 decodeProjectScriptKeybindingRule,
29} from "~/lib/projectScriptKeybindings";
30import { keybindingFromKeyboardEvent } from "~/components/settings/KeybindingsSettings.logic";
31import { commandForProjectScript, nextProjectScriptId } from "~/projectScripts";
32import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
33import { useComposerMenuState } from "./chat/useComposerMenuState";
34import {
35 AlertDialog,
36 AlertDialogClose,
37 AlertDialogDescription,
38 AlertDialogFooter,
39 AlertDialogHeader,
40 AlertDialogPopup,
41 AlertDialogTitle,
42} from "./ui/alert-dialog";
43import { Button } from "./ui/button";
44import {
45 Dialog,
46 DialogDescription,
47 DialogFooter,
48 DialogHeader,
49 DialogPanel,
50 DialogPopup,
51 DialogTitle,
52} from "./ui/dialog";
53import { Input } from "./ui/input";
54import { Label } from "./ui/label";
55import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover";
56import { Switch } from "./ui/switch";
57import { Textarea } from "./ui/textarea";
58​
59const SCRIPT_ICONS: Array<{ id: ProjectScriptIcon; label: string }> = [
60 { id: "play", label: msg("Play") },
61 { id: "test", label: msg("Test") },
62 { id: "lint", label: msg("Lint") },
63 { id: "configure", label: msg("Configure") },
64 { id: "build", label: msg("Build") },
65 { id: "debug", label: msg("Debug") },
66];
67​
68export function ScriptIcon({
69 icon,
70 className = "size-3.5",
71}: {
72 icon: ProjectScriptIcon;
73 className?: string;
74}) {
75 if (icon === "test") return <FlaskConicalIcon className={className} />;
76 if (icon === "lint") return <ListChecksIcon className={className} />;
77 if (icon === "configure") return <WrenchIcon className={className} />;
78 if (icon === "build") return <HammerIcon className={className} />;
79 if (icon === "debug") return <BugIcon className={className} />;
80 return <PlayIcon className={className} />;
82​
83export interface NewProjectScriptInput {
84 name: string;
85 command: string;
86 icon: ProjectScriptIcon;
87 runOnWorktreeCreate: boolean;
88 waitForSetup: boolean;
89 runOnSettle: boolean;
90 stopOnSettle?: boolean;
91 /** Omit to preserve the current shortcut when the form did not edit it. */
92 keybinding?: string | null;
93 previewUrl: string | null;
94 autoOpenPreview: boolean;
96​
97export type ProjectScriptActionResult = AtomCommandResult<void, unknown>;
98​
99export const EMPTY_PROJECT_SCRIPT_INPUT: NewProjectScriptInput = {
100 name: "",
101 command: "",
102 icon: "play",
103 runOnWorktreeCreate: false,
104 waitForSetup: false,
105 runOnSettle: false,
106 stopOnSettle: false,
107 keybinding: null,
108 previewUrl: null,
109 autoOpenPreview: false,
110};
111​
112export interface ProjectScriptEditorRequest {
113 scriptId: string | null;
114 initial: NewProjectScriptInput;
115 error?: string;
117​
118export function editorRequestForScript(
119 script: ProjectScript,
120 keybindings: ResolvedKeybindingsConfig,
121): ProjectScriptEditorRequest {
122 return {
123 scriptId: script.id,
124 initial: {
125 name: script.name,
126 command: script.command,
127 icon: script.icon,
128 runOnWorktreeCreate: script.runOnWorktreeCreate,
129 waitForSetup: script.runOnWorktreeCreate && script.async === false,
130 runOnSettle: script.runOnSettle ?? false,
131 stopOnSettle: script.stopOnSettle ?? false,
132 keybinding: keybindingValueForCommand(keybindings, commandForProjectScript(script.id)),
133 previewUrl: script.previewUrl ?? null,
134 autoOpenPreview: script.autoOpenPreview ?? false,
135 },
136 };
138​
139export function ProjectScriptEditorDialog({
140 environmentId,
141 editScope = AuthOrchestrationOperateScope,
142 request,
143 scripts,
144 onSubmit,
145 onDelete,
146 onClose,
147}: {
148 environmentId: EnvironmentId;
149 editScope?: typeof AuthOrchestrationOperateScope | typeof AuthSettingsWriteScope;
150 request: ProjectScriptEditorRequest | null;
151 scripts: ReadonlyArray<ProjectScript>;
152 onSubmit: (
153 scriptId: string | null,
154 input: NewProjectScriptInput,
155 ) => Promise<ProjectScriptActionResult>;
156 onDelete: (scriptId: string) => void;
157 onClose: () => void;
158}) {
159 const gt = useGT();
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 // The last opened request stays shown while the dialog animates closed. Each
176 // new request mounts a fresh form, which drops the previous request's save.
177 const [shown, setShown] = useState<{
178 readonly request: ProjectScriptEditorRequest;
179 readonly key: number;
180 } | null>(request === null ? null : { request, key: 0 });
181 if (request !== null && request !== shown?.request) {
182 setShown({ request, key: (shown?.key ?? 0) + 1 });
183 }
184 const [deleteConfirmOpen, setDeleteConfirmOpen] = useComposerMenuState(!canEditActions);
185 const [deleteName, setDeleteName] = useState("");
186​
187 return (
188 <>
189 <Dialog
190 open={request !== null}
191 // A stray click outside would discard the unsaved draft; Escape and Cancel still close it.
192 disablePointerDismissal
193 onOpenChange={(open) => {
194 if (!open) onClose();
195 }}
196 >
197 {/* The form owns its fields so a keystroke re-renders it, not the dialog chrome. */}
198 <DialogPopup>
199 {shown ? (
200 <ProjectScriptEditorForm
201 key={shown.key}
202 environmentId={environmentId}
203 editScope={editScope}
204 request={shown.request}
205 scripts={scripts}
206 validationError={validationError}
207 onValidationError={setValidationError}
208 onSubmit={onSubmit}
209 onRequestDelete={(name) => {
210 setDeleteName(name);
211 setDeleteConfirmOpen(true);
212 }}
213 onClose={onClose}
214 />
215 ) : null}
216 </DialogPopup>
217 </Dialog>
218​
219 <AlertDialog open={deleteConfirmOpen && canEditActions} onOpenChange={setDeleteConfirmOpen}>
220 <AlertDialogPopup>
221 <AlertDialogHeader>
222 <AlertDialogTitle>
223 <T>
224 Delete action "<Var>{deleteName}</Var>"?
225 </T>
226 </AlertDialogTitle>
227 <AlertDialogDescription>
228 <T>This action cannot be undone.</T>
229 </AlertDialogDescription>
230 </AlertDialogHeader>
231 <AlertDialogFooter>
232 <AlertDialogClose render={<Button variant="outline" />}>
233 <T>Cancel</T>
234 </AlertDialogClose>
235 <Button
236 variant="destructive"
237 disabled={!canEditActions}
238 onClick={() => {
239 if (!request?.scriptId) return;
240 if (!readEnvironmentScope(environmentId, editScope)) {
241 setValidationError(gt("This connection cannot change project actions."));
242 return;
243 }
244 setDeleteConfirmOpen(false);
245 onClose();
246 onDelete(request.scriptId);
247 }}
248 >
249 <T>Delete action</T>
250 </Button>
251 </AlertDialogFooter>
252 </AlertDialogPopup>
253 </AlertDialog>
254 </>
255 );
257​
258function ProjectScriptEditorForm({
259 environmentId,
260 editScope,
261 request,
262 scripts,
263 validationError,
264 onValidationError: setValidationError,
265 onSubmit,
266 onRequestDelete,
267 onClose,
268}: {
269 environmentId: EnvironmentId;
270 editScope: typeof AuthOrchestrationOperateScope | typeof AuthSettingsWriteScope;
271 request: ProjectScriptEditorRequest;
272 scripts: ReadonlyArray<ProjectScript>;
273 validationError: string | null;
274 onValidationError: (error: string | null) => void;
275 onSubmit: (
276 scriptId: string | null,
277 input: NewProjectScriptInput,
278 ) => Promise<ProjectScriptActionResult>;
279 onRequestDelete: (name: string) => void;
280 onClose: () => void;
281}) {
282 const gt = useGT();
283 const m = useMessages();
284 const canEditActions = useEnvironmentScope(environmentId, editScope);
285 const canWriteSettings = useEnvironmentScope(environmentId, AuthSettingsWriteScope);
286 const formId = React.useId();
287 const [name, setName] = useState(request.initial.name);
288 const [command, setCommand] = useState(request.initial.command);
289 const [icon, setIcon] = useState<ProjectScriptIcon>(request.initial.icon);
290 const [iconPickerOpen, setIconPickerOpen] = useComposerMenuState(!canEditActions);
291 const [runOnWorktreeCreate, setRunOnWorktreeCreate] = useState(
292 request.initial.runOnWorktreeCreate,
293 );
294 const [waitForSetup, setWaitForSetup] = useState(request.initial.waitForSetup);
295 const [runOnSettle, setRunOnSettle] = useState(request.initial.runOnSettle);
296 const [stopOnSettle, setStopOnSettle] = useState(request.initial.stopOnSettle ?? false);
297 const [keybinding, setKeybinding] = useState(request.initial.keybinding ?? "");
298 const [previewUrl, setPreviewUrl] = useState(request.initial.previewUrl ?? "");
299 const [autoOpenPreview, setAutoOpenPreview] = useState(request.initial.autoOpenPreview);
300 const [isSaving, setIsSaving] = useState(false);
301 const pendingSubmissionRef = useRef<object | null>(null);
302 // A save that settles after this form is replaced must not close or error
303 // the request that replaced it.
304 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- drops the pending save on unmount so a late result cannot close or fail the next request
305 useEffect(
306 () => () => {
307 pendingSubmissionRef.current = null;
308 },
309 [],
310 );
311​
312 const isEditing = request.scriptId != null;
313​
314 const close = () => {
315 pendingSubmissionRef.current = null;
316 setIsSaving(false);
317 setIconPickerOpen(false);
318 onClose();
319 };
320​
321 const captureKeybinding = (event: KeyboardEvent<HTMLInputElement>) => {
322 if (!readEnvironmentScope(environmentId, editScope)) return;
323 if (!readEnvironmentScope(environmentId, AuthSettingsWriteScope)) return;
324 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
325 if (event.key === "Tab") return;
326 // Leave bare Escape unhandled so it keeps dismissing the dialog.
327 if (
328 event.key === "Escape" &&
329 !event.shiftKey &&
330 !event.altKey &&
331 !event.ctrlKey &&
332 !event.metaKey
333 ) {
334 return;
335 }
336 event.preventDefault();
337 event.stopPropagation();
338 if (event.key === "Backspace" || event.key === "Delete") {
339 setKeybinding("");
340 return;
341 }
342 const next = keybindingFromKeyboardEvent(event, navigator.platform);
343 if (!next) return;
344 setKeybinding(next);
345 };
346​
347 const submit = async (event: FormEvent) => {
348 event.preventDefault();
349 if (pendingSubmissionRef.current !== null) return;
350 if (!readEnvironmentScope(environmentId, editScope)) {
351 setValidationError(gt("This connection cannot change project actions."));
352 return;
353 }
354 const changesKeybinding =
355 (keybinding.trim() || null) !== (request.initial.keybinding?.trim() || null);
356 const canChangeKeybinding = readEnvironmentScope(environmentId, AuthSettingsWriteScope);
357 if (changesKeybinding && !canChangeKeybinding) {
358 setValidationError(gt("This connection cannot change keyboard shortcuts."));
359 return;
360 }
361 const trimmedName = name.trim();
362 const trimmedCommand = command.trim();
363 if (trimmedName.length === 0) {
364 setValidationError(gt("Name is required."));
365 return;
366 }
367 if (trimmedCommand.length === 0) {
368 setValidationError(gt("Command is required."));
369 return;
370 }
371​
372 setValidationError(null);
373 let payload: NewProjectScriptInput;
374 try {
375 const scriptIdForValidation =
376 request.scriptId ??
377 nextProjectScriptId(
378 trimmedName,
379 scripts.map((script) => script.id),
380 );
381 const keybindingRule = decodeProjectScriptKeybindingRule({
382 keybinding,
383 command: commandForProjectScript(scriptIdForValidation),
384 });
385 const trimmedPreviewUrl = previewUrl.trim();
386 payload = {
387 name: trimmedName,
388 command: trimmedCommand,
389 icon,
390 runOnWorktreeCreate,
391 waitForSetup: runOnWorktreeCreate && waitForSetup,
392 runOnSettle,
393 stopOnSettle,
394 ...((request.scriptId === null && canChangeKeybinding) || changesKeybinding
395 ? { keybinding: keybindingRule?.key ?? null }
396 : {}),
397 previewUrl: trimmedPreviewUrl.length > 0 ? trimmedPreviewUrl : null,
398 autoOpenPreview: trimmedPreviewUrl.length > 0 ? autoOpenPreview : false,
399 } satisfies NewProjectScriptInput;
400 } catch (error) {
401 setValidationError(thrownErrorMessage(error, m) ?? gt("Failed to save action."));
402 return;
403 }
404​
405 const submission = {};
406 pendingSubmissionRef.current = submission;
407 setIsSaving(true);
408 setIconPickerOpen(false);
409 try {
410 const result = await onSubmit(request.scriptId, payload);
411 if (pendingSubmissionRef.current === submission) {
412 if (result._tag === "Failure") {
413 if (!isAtomCommandInterrupted(result)) {
414 const error = squashAtomCommandFailure(result);
415 setValidationError(thrownErrorMessage(error, m) ?? gt("Failed to save action."));
416 }
417 } else {
418 close();
419 }
420 }
421 } catch (error) {
422 if (pendingSubmissionRef.current === submission) {
423 setValidationError(thrownErrorMessage(error, m) ?? gt("Failed to save action."));
424 }
425 }
426 if (pendingSubmissionRef.current === submission) {
427 pendingSubmissionRef.current = null;
428 setIsSaving(false);
429 }
430 };
431​
432 return (
433 <>
434 <DialogHeader>
435 <DialogTitle>{isEditing ? <T>Edit Action</T> : <T>Add Action</T>}</DialogTitle>
436 <DialogDescription>
437 <T>Actions are project-scoped commands you can run from the top bar or keybindings.</T>
438 </DialogDescription>
439 </DialogHeader>
440 <DialogPanel>
441 <form id={formId} onSubmit={submit}>
442 <fieldset className="space-y-4" disabled={isSaving || !canEditActions}>
443 <div className="space-y-1.5">
444 <Label htmlFor="script-name">
445 <T>Name</T>
446 </Label>
447 <div className="flex items-center gap-2">
448 <Popover onOpenChange={setIconPickerOpen} open={iconPickerOpen}>
449 <PopoverTrigger
450 render={
451 <Button
452 type="button"
453 variant="outline"
454 className="size-9 shrink-0"
455 aria-label={gt("Choose icon")}
456 />
457 }
458 >
459 <ScriptIcon icon={icon} className="size-4.5" />
460 </PopoverTrigger>
461 <PopoverPopup align="start">
462 <div className="grid grid-cols-3 gap-2">
463 {SCRIPT_ICONS.map((entry) => {
464 const isSelected = entry.id === icon;
465 return (
466 <button
467 key={entry.id}
468 type="button"
469 className={`relative flex flex-col items-center gap-2 rounded-md border px-2 py-2 text-xs dark:border-transparent ${
470 isSelected
471 ? "border-primary/70 bg-primary/10 ring-inset dark:ring-1 dark:ring-primary/30"
472 : "border-border/70 hover:bg-accent/60 dark:bg-white/[0.035]"
473 }`}
474 onClick={() => {
475 setIcon(entry.id);
476 setIconPickerOpen(false);
477 }}
478 >
479 <ScriptIcon icon={entry.id} className="size-4" />
480 <span>{m(entry.label)}</span>
481 </button>
482 );
483 })}
484 </div>
485 </PopoverPopup>
486 </Popover>
487 <Input
488 id="script-name"
489 autoFocus
490 placeholder={gt("Test", { $context: "example action name" })}
491 value={name}
492 onChange={(event) => setName(event.target.value)}
493 />
494 </div>
495 </div>
496 <div className="space-y-1.5">
497 <Label htmlFor="script-keybinding">
498 <T>Keybinding</T>
499 </Label>
500 <Input
501 data-keybinding-capture=""
502 disabled={!canWriteSettings}
503 id="script-keybinding"
504 placeholder={gt("Press shortcut")}
505 value={keybinding}
506 readOnly
507 onKeyDown={captureKeybinding}
508 />
509 <p className="text-xs text-muted-foreground">
510 <T>
511 Press a shortcut. Use <code>Backspace</code> to clear. Shortcuts are
512 environment-wide. Projects using the same action share its shortcut.
513 </T>
514 </p>
515 </div>
516 <div className="space-y-1.5">
517 <Label htmlFor="script-command">
518 <T>Command</T>
519 </Label>
520 <Textarea
521 id="script-command"
522 data-script-command-input
523 // oxlint-disable-next-line t3code/no-untranslated-copy -- example shell command
524 placeholder="bun test"
525 value={command}
526 onChange={(event) => setCommand(event.target.value)}
527 />
528 </div>
529 <div className="space-y-1.5">
530 <Label htmlFor="script-preview-url">
531 <T>Preview URL (optional)</T>
532 </Label>
533 <Input
534 id="script-preview-url"
535 placeholder="http://localhost:5173"
536 value={previewUrl}
537 onChange={(event) => setPreviewUrl(event.target.value)}
538 />
539 <p className="text-xs text-muted-foreground">
540 <T>Open this URL in the in-app preview when this action runs.</T>
541 </p>
542 </div>
543 <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]">
544 <span>
545 <T>Run automatically on worktree creation</T>
546 </span>
547 <Switch
548 checked={runOnWorktreeCreate}
549 onCheckedChange={(checked) => setRunOnWorktreeCreate(Boolean(checked))}
550 />
551 </label>
552 <label
553 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] ${
554 runOnWorktreeCreate ? "" : "opacity-60"
555 }`}
556 >
557 <span>
558 <T>Wait for it to finish before the agent starts</T>
559 </span>
560 <Switch
561 checked={waitForSetup}
562 disabled={!runOnWorktreeCreate}
563 onCheckedChange={(checked) => setWaitForSetup(Boolean(checked))}
564 />
565 </label>
566 <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]">
567 <span>
568 <T>Run in the thread's worktree when the thread settles</T>
569 </span>
570 <Switch
571 checked={runOnSettle}
572 onCheckedChange={(checked) => setRunOnSettle(Boolean(checked))}
573 />
574 </label>
575 <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]">
576 <span>
577 <T>Stop this action when the thread settles</T>
578 </span>
579 <Switch
580 checked={stopOnSettle}
581 onCheckedChange={(checked) => setStopOnSettle(Boolean(checked))}
582 />
583 </label>
584 <label
585 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] ${
586 previewUrl.trim().length === 0 ? "opacity-60" : ""
587 }`}
588 >
589 <span>
590 <T>Open preview automatically when this action runs</T>
591 </span>
592 <Switch
593 checked={autoOpenPreview}
594 disabled={previewUrl.trim().length === 0}
595 onCheckedChange={(checked) => setAutoOpenPreview(Boolean(checked))}
596 />
597 </label>
598 {validationError && <p className="text-sm text-destructive">{validationError}</p>}
599 </fieldset>
600 </form>
601 </DialogPanel>
602 <DialogFooter variant="bare">
603 {isEditing && (
604 <Button
605 type="button"
606 variant="destructive-outline"
607 className="mr-auto"
608 disabled={isSaving || !canEditActions}
609 onClick={() => onRequestDelete(name)}
610 >
611 <T context="verb, delete the action">Delete</T>
612 </Button>
613 )}
614 <Button type="button" variant="outline" onClick={close}>
615 <T>Cancel</T>
616 </Button>
617 <Button form={formId} type="submit" disabled={isSaving || !canEditActions}>
618 {isSaving ? <T>Saving…</T> : isEditing ? <T>Save changes</T> : <T>Save action</T>}
619 </Button>
620 </DialogFooter>
621 </>
622 );