The best way to control Claude Code, Codex and more from any computer or phone

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