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

projectScriptEditor.tsx

560 lines20.0 KB

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