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

main
tsx 509 lines 18.4 KB
Raw
1 import { m } from "../i18n/messages";
2 import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
3 import { ThreadDetailsControl } from "./chat/ThreadDetailsControl";
4 import {
5 AuthSettingsWriteScope,
6 type EnvironmentId,
7 type ProjectScript,
8 type T3ProjectFileScript,
9 } from "@t3tools/contracts";
10 import { useAtomValue } from "@effect/atom-react";
11 import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
12 import {
13 isAtomCommandInterrupted,
14 squashAtomCommandFailure,
15 } from "@t3tools/client-runtime/state/runtime";
16 import { projectScriptMenuLabel } from "@t3tools/shared/projectScriptsCopy";
17 import { ChevronDownIcon, DownloadIcon, PlusIcon, SettingsIcon, WrenchIcon } from "lucide-react";
18 import React, { useState } from "react";
19 import { T, useGT, useMessages, Var } from "gt-react";
20
21 import { commandForProjectScript, primaryProjectScript } from "~/projectScripts";
22 import { shortcutLabelForCommand } from "~/keybindings";
23 import { serverEnvironment } from "~/state/server";
24 import { readEnvironmentScope } from "~/state/session";
25 import {
26 EMPTY_PROJECT_SCRIPT_INPUT,
27 editorRequestForScript,
28 ProjectScriptEditorDialog,
29 ScriptIcon,
30 type NewProjectScriptInput,
31 type ProjectScriptActionResult,
32 type ProjectScriptEditorRequest,
33 } from "./projectScriptEditor";
34 import { Button } from "./ui/button";
35 import { Group, GroupSeparator } from "./ui/group";
36 import {
37 Menu,
38 MenuGroup,
39 MenuGroupLabel,
40 MenuItem,
41 MenuItemLabel,
42 MenuPopup,
43 MenuSeparator,
44 MenuShortcut,
45 MenuTrigger,
46 MenuSub,
47 MenuSubTrigger,
48 MenuSubPopup,
49 } from "./ui/menu";
50 import { stackedThreadToast, toastManager } from "./ui/toast";
51 import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
52 import { cn } from "~/lib/utils";
53 import {
54 THREAD_DETAILS_PANEL_CHEVRON_CLASS,
55 THREAD_DETAILS_PANEL_ICON_CLASS,
56 THREAD_DETAILS_PANEL_LABEL_CLASS,
57 THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS,
58 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
59 } from "./chat/threadDetailsPanelStyles";
60
61 export type { NewProjectScriptInput, ProjectScriptActionResult };
62
63 const NO_FILE_SCRIPTS: ReadonlyArray<T3ProjectFileScript> = [];
64
65 interface ProjectScriptsControlProps {
66 displayMode?: "toolbar" | "panel";
67 presentation?: "toolbar" | "menu";
68 onRequestMenuClose?: () => void;
69 environmentId: EnvironmentId;
70 scripts: ReadonlyArray<ProjectScript>;
71 fileScripts?: ReadonlyArray<T3ProjectFileScript>;
72 preferredScriptId?: string | null;
73 onRunScript?: ((script: ProjectScript) => void) | undefined;
74 onAddScript: (input: NewProjectScriptInput) => Promise<ProjectScriptActionResult>;
75 onUpdateScript: (
76 scriptId: string,
77 input: NewProjectScriptInput,
78 ) => Promise<ProjectScriptActionResult>;
79 onDeleteScript: (scriptId: string) => Promise<ProjectScriptActionResult>;
80 }
81
82 export default function ProjectScriptsControl({
83 displayMode = "toolbar",
84 presentation = "toolbar",
85 onRequestMenuClose,
86 environmentId,
87 scripts,
88 fileScripts = NO_FILE_SCRIPTS,
89 preferredScriptId = null,
90 onRunScript,
91 onAddScript,
92 onUpdateScript,
93 onDeleteScript,
94 }: ProjectScriptsControlProps) {
95 const gt = useGT();
96 const messages = useMessages();
97 const isPanel = displayMode === "panel";
98 const ActionGroup = isPanel ? "div" : Group;
99 const panelAnchorRef = React.useRef<HTMLDivElement | null>(null);
100 const keybindings =
101 useAtomValue(serverEnvironment.configValueAtom(environmentId))?.keybindings ??
102 DEFAULT_RESOLVED_KEYBINDINGS;
103 const [actionsMenuOpen, setActionsMenuOpen] = useState({
104 presentation,
105 scripts: false,
106 imports: false,
107 });
108 if (actionsMenuOpen.presentation !== presentation) {
109 setActionsMenuOpen({ presentation, scripts: false, imports: false });
110 }
111 const [editorRequest, setEditorRequest] = useState<ProjectScriptEditorRequest | null>(null);
112 const editorRequestIdRef = React.useRef(0);
113
114 const primaryScript =
115 (preferredScriptId ? scripts.find((script) => script.id === preferredScriptId) : undefined) ??
116 primaryProjectScript(scripts);
117 const importableScripts = fileScripts.filter(
118 (fileScript) =>
119 !scripts.some(
120 (script) =>
121 script.command === fileScript.command ||
122 script.name.toLowerCase() === fileScript.name.toLowerCase(),
123 ),
124 );
125
126 const openAddDialog = () => {
127 editorRequestIdRef.current += 1;
128 setEditorRequest({ scriptId: null, initial: EMPTY_PROJECT_SCRIPT_INPUT });
129 };
130
131 const openEditDialog = (script: ProjectScript) => {
132 editorRequestIdRef.current += 1;
133 onRequestMenuClose?.();
134 setActionsMenuOpen({ presentation, scripts: false, imports: false });
135 setEditorRequest(editorRequestForScript(script, keybindings));
136 };
137
138 const submitScript = (scriptId: string | null, input: NewProjectScriptInput) =>
139 scriptId === null ? onAddScript(input) : onUpdateScript(scriptId, input);
140
141 const importFileScript = async (fileScript: T3ProjectFileScript) => {
142 const requestId = ++editorRequestIdRef.current;
143 const payload: NewProjectScriptInput = {
144 name: fileScript.name,
145 command: fileScript.command,
146 icon: fileScript.icon ?? "play",
147 runOnWorktreeCreate: fileScript.runOnWorktreeCreate ?? false,
148 waitForSetup: fileScript.runOnWorktreeCreate === true && fileScript.async === false,
149 runOnSettle: fileScript.runOnSettle ?? false,
150 stopOnSettle: fileScript.stopOnSettle ?? false,
151 ...(readEnvironmentScope(environmentId, AuthSettingsWriteScope) ? { keybinding: null } : {}),
152 previewUrl: fileScript.previewUrl ?? null,
153 autoOpenPreview: fileScript.previewUrl ? (fileScript.autoOpenPreview ?? false) : false,
154 };
155 const result = await onAddScript(payload);
156 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
157
158 const message = thrownErrorMessage(squashAtomCommandFailure(result), m);
159 if (requestId !== editorRequestIdRef.current) {
160 toastManager.add(
161 stackedThreadToast({
162 type: "error",
163 title: gt("Failed to import {name}.", { name: fileScript.name }),
164 ...(message ? { description: message } : {}),
165 }),
166 );
167 return;
168 }
169 setEditorRequest({
170 scriptId: null,
171 initial: payload,
172 error: message ?? gt("Failed to import action."),
173 });
174 };
175
176 const importMenuItems = importableScripts.length > 0 && (
177 <>
178 {scripts.length > 0 && <MenuSeparator />}
179 <MenuGroup>
180 <MenuGroupLabel>
181 <T>
182 From <Var>t3.json</Var>
183 </T>
184 </MenuGroupLabel>
185 {importableScripts.map((fileScript) => (
186 <MenuItem
187 density={presentation === "menu" ? "touch" : "default"}
188 key={`${fileScript.name} ${fileScript.command}`}
189 onClick={() => void importFileScript(fileScript)}
190 >
191 <ScriptIcon icon={fileScript.icon ?? "play"} className="size-4" />
192 <MenuItemLabel>{fileScript.name}</MenuItemLabel>
193 <MenuShortcut>
194 <DownloadIcon
195 className="size-3.5"
196 aria-label={gt("Import", { $context: "verb, import an action from t3.json" })}
197 />
198 </MenuShortcut>
199 </MenuItem>
200 ))}
201 </MenuGroup>
202 </>
203 );
204
205 const scriptItems = (
206 <>
207 {scripts.map((script) => {
208 const shortcutLabel = shortcutLabelForCommand(
209 keybindings,
210 commandForProjectScript(script.id),
211 );
212 return (
213 <MenuItem
214 density={presentation === "menu" ? "touch" : "default"}
215 key={script.id}
216 className="group"
217 disabled={!onRunScript}
218 onClick={() => onRunScript?.(script)}
219 >
220 <ScriptIcon icon={script.icon} className="size-4" />
221 <MenuItemLabel>{projectScriptMenuLabel(script, messages)}</MenuItemLabel>
222 <span className="relative ms-auto flex h-6 min-w-6 items-center justify-end">
223 {shortcutLabel &&
224 (presentation === "menu" ? (
225 <MenuShortcut className="ms-0 mr-7">{shortcutLabel}</MenuShortcut>
226 ) : (
227 <span className="transition-opacity group-hover:opacity-0 group-focus-visible:opacity-0">
228 <MenuShortcut className="ms-0">{shortcutLabel}</MenuShortcut>
229 </span>
230 ))}
231 <span
232 className={`absolute right-0 top-1/2 flex -translate-y-1/2 ${presentation === "menu" ? "" : "opacity-0 pointer-events-none transition-opacity group-hover:opacity-100 group-hover:pointer-events-auto group-focus-visible:opacity-100 group-focus-visible:pointer-events-auto"}`}
233 >
234 <Button
235 type="button"
236 variant="ghost"
237 size="icon-xs"
238 className="size-6"
239 aria-label={gt("Edit {name}", { name: script.name })}
240 onPointerDown={(event) => {
241 event.preventDefault();
242 event.stopPropagation();
243 }}
244 onClick={(event) => {
245 event.preventDefault();
246 event.stopPropagation();
247 openEditDialog(script);
248 }}
249 >
250 <SettingsIcon className="size-3.5" />
251 </Button>
252 </span>
253 </span>
254 </MenuItem>
255 );
256 })}
257 {importMenuItems}
258 <MenuItem density={presentation === "menu" ? "touch" : "default"} onClick={openAddDialog}>
259 <PlusIcon className="size-4" />
260 <MenuItemLabel>{isPanel ? gt("Add project script") : gt("Add action")}</MenuItemLabel>
261 </MenuItem>
262 </>
263 );
264
265 return (
266 <>
267 {presentation === "menu" ? (
268 <>
269 {primaryScript && (
270 <MenuItem
271 density={presentation === "menu" ? "touch" : "default"}
272 disabled={!onRunScript}
273 onClick={() => onRunScript?.(primaryScript)}
274 >
275 <ScriptIcon icon={primaryScript.icon} className="size-4" />
276 <MenuItemLabel>
277 <T>
278 Run <Var>{primaryScript.name}</Var>
279 </T>
280 </MenuItemLabel>
281 <MenuShortcut>
282 {shortcutLabelForCommand(keybindings, commandForProjectScript(primaryScript.id))}
283 </MenuShortcut>
284 </MenuItem>
285 )}
286 {scripts.length > 0 || importableScripts.length > 0 ? (
287 <MenuSub
288 open={actionsMenuOpen.scripts}
289 onOpenChange={(open) =>
290 setActionsMenuOpen({ presentation, scripts: open, imports: false })
291 }
292 >
293 <MenuSubTrigger density="touch">
294 <ScriptIcon icon="play" className="size-4" />
295 <MenuItemLabel>
296 <T>Project actions</T>
297 </MenuItemLabel>
298 </MenuSubTrigger>
299 <MenuSubPopup>{scriptItems}</MenuSubPopup>
300 </MenuSub>
301 ) : (
302 <MenuItem
303 density={presentation === "menu" ? "touch" : "default"}
304 onClick={openAddDialog}
305 >
306 <PlusIcon className="size-4" />
307 <MenuItemLabel>
308 <T>Add project action…</T>
309 </MenuItemLabel>
310 </MenuItem>
311 )}
312 </>
313 ) : primaryScript ? (
314 <ActionGroup
315 role="group"
316 aria-label={gt("Project scripts")}
317 {...(isPanel
318 ? { className: THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS, ref: panelAnchorRef }
319 : {})}
320 >
321 <Tooltip>
322 <TooltipTrigger
323 render={
324 <ThreadDetailsControl
325 size="xs"
326 variant={isPanel ? "ghost" : "outline"}
327 part="primary"
328 panel={isPanel}
329 className={isPanel ? undefined : "w-7 sm:w-6 @3xl/header-actions:w-auto!"}
330 aria-label={gt("Run {name}", { name: primaryScript.name })}
331 // Tooltip replaces the button data-slot, so toolbar theming needs a separate hook.
332 data-toolbar-control=""
333 aria-disabled={!onRunScript || undefined}
334 onClick={() => onRunScript?.(primaryScript)}
335 />
336 }
337 >
338 <ScriptIcon
339 icon={primaryScript.icon}
340 {...(isPanel ? { className: THREAD_DETAILS_PANEL_ICON_CLASS } : {})}
341 />
342 <span
343 className={cn(
344 "sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5",
345 isPanel && cn("not-sr-only ml-0 truncate", THREAD_DETAILS_PANEL_LABEL_CLASS),
346 )}
347 >
348 {primaryScript.name}
349 </span>
350 </TooltipTrigger>
351 <TooltipPopup side="top">
352 {onRunScript
353 ? gt("Run {name}", { name: primaryScript.name })
354 : gt("Pair this client again with permission to run terminal commands.")}
355 </TooltipPopup>
356 </Tooltip>
357 {isPanel ? (
358 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
359 ) : (
360 <GroupSeparator className="hidden @3xl/header-actions:block" />
361 )}
362 <Menu
363 open={actionsMenuOpen.scripts}
364 onOpenChange={(open) =>
365 setActionsMenuOpen({ presentation, scripts: open, imports: false })
366 }
367 >
368 <Tooltip>
369 <TooltipTrigger
370 render={
371 <MenuTrigger
372 render={
373 <ThreadDetailsControl
374 size={isPanel ? "sm" : "icon-xs"}
375 variant={isPanel ? "ghost" : "outline"}
376 part="secondary"
377 panel={isPanel}
378 aria-label={gt("Script actions")}
379 data-toolbar-control=""
380 />
381 }
382 />
383 }
384 >
385 <ChevronDownIcon
386 className={isPanel ? THREAD_DETAILS_PANEL_CHEVRON_CLASS : "size-4"}
387 />
388 </TooltipTrigger>
389 <TooltipPopup side="top">
390 <T>Script actions</T>
391 </TooltipPopup>
392 </Tooltip>
393 <MenuPopup
394 align="end"
395 {...(isPanel ? { anchor: panelAnchorRef } : {})}
396 className={isPanel ? "w-(--anchor-width)" : undefined}
397 >
398 {scriptItems}
399 </MenuPopup>
400 </Menu>
401 </ActionGroup>
402 ) : scripts.length > 0 || importableScripts.length > 0 ? (
403 isPanel ? (
404 <div
405 role="group"
406 aria-label={gt("Project actions")}
407 className={THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS}
408 ref={panelAnchorRef}
409 >
410 <ThreadDetailsControl
411 size="sm"
412 variant="ghost"
413 part="primary"
414 aria-label={gt("Project actions")}
415 onClick={() => setActionsMenuOpen({ presentation, scripts: false, imports: true })}
416 >
417 <WrenchIcon className={THREAD_DETAILS_PANEL_ICON_CLASS} />
418 <span className={cn("min-w-0 truncate", THREAD_DETAILS_PANEL_LABEL_CLASS)}>
419 <T context="project actions menu">Actions</T>
420 </span>
421 </ThreadDetailsControl>
422 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
423 <Menu
424 highlightItemOnHover={false}
425 open={actionsMenuOpen.imports}
426 onOpenChange={(open) =>
427 setActionsMenuOpen({ presentation, scripts: false, imports: open })
428 }
429 >
430 <MenuTrigger
431 render={
432 <ThreadDetailsControl
433 size="sm"
434 variant="ghost"
435 part="secondary"
436 aria-label={gt("Choose project action")}
437 />
438 }
439 >
440 <ChevronDownIcon className={THREAD_DETAILS_PANEL_CHEVRON_CLASS} />
441 </MenuTrigger>
442 <MenuPopup align="end" anchor={panelAnchorRef} className="w-(--anchor-width)">
443 {scriptItems}
444 </MenuPopup>
445 </Menu>
446 </div>
447 ) : (
448 <Menu
449 highlightItemOnHover={false}
450 open={actionsMenuOpen.imports}
451 onOpenChange={(open) =>
452 setActionsMenuOpen({ presentation, scripts: false, imports: open })
453 }
454 >
455 <MenuTrigger
456 render={<Button size="xs" variant="outline" aria-label={gt("Project actions")} />}
457 >
458 <WrenchIcon className="size-3.5" />
459 <span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
460 <T context="project actions menu">Actions</T>
461 </span>
462 <ChevronDownIcon className="size-3.5" />
463 </MenuTrigger>
464 <MenuPopup align="end">{scriptItems}</MenuPopup>
465 </Menu>
466 )
467 ) : (
468 <Tooltip>
469 <TooltipTrigger
470 render={
471 <ThreadDetailsControl
472 size="xs"
473 variant={isPanel ? "ghost" : "outline"}
474 part="row"
475 panel={isPanel}
476 className={isPanel ? undefined : "w-7 sm:w-6 @3xl/header-actions:w-auto!"}
477 aria-label={isPanel ? gt("Add project script") : gt("Add action")}
478 data-toolbar-control=""
479 onClick={openAddDialog}
480 />
481 }
482 >
483 <PlusIcon className="size-3.5" />
484 <span
485 className={cn(
486 "sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5",
487 isPanel && cn("not-sr-only ml-0.5", THREAD_DETAILS_PANEL_LABEL_CLASS),
488 )}
489 >
490 {isPanel ? gt("Add project script") : gt("Add action")}
491 </span>
492 </TooltipTrigger>
493 <TooltipPopup side="top">
494 {isPanel ? gt("Add project script") : gt("Add action")}
495 </TooltipPopup>
496 </Tooltip>
497 )}
498
499 <ProjectScriptEditorDialog
500 environmentId={environmentId}
501 request={editorRequest}
502 scripts={scripts}
503 onSubmit={submitScript}
504 onDelete={(scriptId) => void onDeleteScript(scriptId)}
505 onClose={() => setEditorRequest(null)}
506 />
507 </>
508 );
509 }