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

projectScriptEditor.tsx

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