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

main
tsx 544 lines 18.9 KB
Raw
1 import {
2 memo,
3 useEffect,
4 useState,
5 type MouseEventHandler,
6 type PointerEventHandler,
7 type ReactNode,
8 } from "react";
9 import { msg, useGT, useMessages } from "gt-react";
10 import {
11 CheckIcon,
12 ChevronLeftIcon,
13 Minimize2Icon,
14 PlayIcon,
15 CornerUpRightIcon,
16 ListPlusIcon,
17 } from "lucide-react";
18 import { useEnvironmentIdentificationMode } from "~/hooks/useSettings";
19 import type { MessageResolver } from "~/i18n/messages";
20 import { formatContextWindowTokens } from "~/lib/contextWindow";
21 import { cn, isMacPlatform } from "~/lib/utils";
22 import { useShortcutModifierState } from "../../shortcutModifierState";
23 import { StageBackdropButtonArt, useSidebarStageBackdropVariant } from "../SidebarStageBackdrop";
24 import { Button } from "../ui/button";
25 import { Spinner } from "../ui/spinner";
26 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
27 import {
28 alternateComposerDispatchAction,
29 resolveComposerDispatchMode,
30 } from "@t3tools/client-runtime/state/composer-dispatch";
31
32 interface PendingActionState {
33 questionIndex: number;
34 isLastQuestion: boolean;
35 canAdvance: boolean;
36 isResponding: boolean;
37 isComplete: boolean;
38 }
39
40 interface ComposerPrimaryActionsProps {
41 /** Footer controls (dictation) that always sit right before the primary button. */
42 children?: ReactNode;
43 compact: boolean;
44 canOperateThread: boolean;
45 pendingAction: PendingActionState | null;
46 isRunning: boolean;
47 canInterrupt: boolean;
48 runId?: string | null;
49 followUpBehavior?: "queue" | "steer";
50 canSteer?: boolean;
51 alternateShortcutLabel?: string | null;
52 /** Dictation is running; Send finishes it and submits once the transcript lands. */
53 voiceInputActive?: boolean;
54 isSendBusy: boolean;
55 sendDisabledReason: string | null;
56 isEnvironmentUnavailable: boolean;
57 isPreparingWorktree: boolean;
58 hasSendableContent: boolean;
59 canResume?: boolean;
60 preserveComposerFocusOnPointerDown?: boolean;
61 isEditingQueuedMessage?: boolean;
62 onSubmitMessage?: MouseEventHandler<HTMLButtonElement>;
63 onResume?: () => void;
64 onPreviousPendingQuestion: () => void;
65 onInterrupt: () => void;
66 compactBeforeSendTokens?: number | null;
67 hideCompactToggle?: boolean;
68 keepFullHistory?: boolean;
69 onToggleKeepFullHistory?: () => void;
70 }
71
72 const formatPendingPrimaryActionLabel = (
73 input: {
74 compact: boolean;
75 isLastQuestion: boolean;
76 isResponding: boolean;
77 questionIndex: number;
78 },
79 resolve: MessageResolver,
80 ) => {
81 if (input.isResponding) {
82 return resolve(msg("Submitting..."));
83 }
84 if (input.compact) {
85 return input.isLastQuestion
86 ? resolve(msg("Submit", { $context: "verb, submits answers" }))
87 : resolve(msg("Next", { $context: "button that goes to the next question" }));
88 }
89 if (!input.isLastQuestion) {
90 return resolve(msg("Next question"));
91 }
92 return input.questionIndex > 0 ? resolve(msg("Submit answers")) : resolve(msg("Submit answer"));
93 };
94
95 const STOP_PENDING_MAX_MS = 10_000;
96 // The action that takes Stop's place ignores clicks this long, so repeat Stop clicks can't resume.
97 const STOP_LANDED_CLICK_GUARD_MS = 500;
98
99 const messageActionPillClassName =
100 "inline-flex shrink-0 cursor-pointer items-center justify-center gap-1.5 whitespace-nowrap rounded-full bg-message-action font-medium text-base text-message-action-foreground shadow-xs shadow-message-action/24 outline-none hover:bg-message-action-hover focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-64 disabled:shadow-none sm:text-sm";
101
102 const preventPointerFocus: PointerEventHandler<HTMLElement> = (event) => {
103 event.preventDefault();
104 };
105
106 type StopPhase = "pending" | "timedOut" | "landed" | null;
107
108 function useStopPhase(input: {
109 runId: string | null;
110 canInterrupt: boolean;
111 canOperateThread: boolean;
112 }) {
113 const { runId, canInterrupt, canOperateThread } = input;
114 const [stopPhase, setStopPhase] = useState<StopPhase>(null);
115 const [stopRunId, setStopRunId] = useState(runId);
116 if (runId !== null && stopRunId !== runId) {
117 setStopRunId(runId);
118 setStopPhase(null);
119 } else if (canOperateThread) {
120 // Losing permission also clears canInterrupt; it does not acknowledge the stop.
121 if ((stopPhase === "pending" || stopPhase === "timedOut") && !canInterrupt)
122 setStopPhase("landed");
123 else if (stopPhase === "landed" && canInterrupt) setStopPhase(null);
124 }
125 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- timers that re-enable an unsettled Stop and end the landed click guard
126 useEffect(() => {
127 if (stopPhase === "pending") {
128 const timeout = setTimeout(() => setStopPhase("timedOut"), STOP_PENDING_MAX_MS);
129 return () => clearTimeout(timeout);
130 }
131 if (stopPhase === "landed") {
132 const timeout = setTimeout(() => setStopPhase(null), STOP_LANDED_CLICK_GUARD_MS);
133 return () => clearTimeout(timeout);
134 }
135 }, [stopPhase]);
136 return [stopPhase, setStopPhase] as const;
137 }
138
139 function StopGenerationButton({
140 stopPhase,
141 canOperateThread,
142 insidePendingAction,
143 preserveComposerFocusOnPointerDown,
144 onStopRequested,
145 onInterrupt,
146 }: {
147 stopPhase: StopPhase;
148 canOperateThread: boolean;
149 insidePendingAction: boolean;
150 preserveComposerFocusOnPointerDown: boolean;
151 onStopRequested: () => void;
152 onInterrupt: () => void;
153 }) {
154 const gt = useGT();
155 const isStopDisabled = stopPhase === "pending";
156 return (
157 <Tooltip>
158 <TooltipTrigger
159 render={
160 <button
161 type="button"
162 className={cn(
163 "flex shrink-0 cursor-pointer items-center justify-center rounded-full bg-destructive/90 text-white shadow-xs shadow-destructive/24 inset-shadow-control-highlight transition-colors duration-150 hover:bg-destructive active:inset-shadow-control-pressed active:shadow-none disabled:cursor-default disabled:opacity-64 disabled:hover:bg-destructive/90 [&_svg]:pointer-events-none",
164 insidePendingAction ? "size-8 sm:size-7" : "size-8 sm:h-8 sm:w-8",
165 )}
166 onPointerDown={preserveComposerFocusOnPointerDown ? preventPointerFocus : undefined}
167 disabled={!canOperateThread || isStopDisabled}
168 onClick={() => {
169 if (!canOperateThread || isStopDisabled) return;
170 onStopRequested();
171 onInterrupt();
172 }}
173 aria-label={stopPhase === "pending" ? gt("Stopping") : gt("Stop generation")}
174 />
175 }
176 >
177 <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor" aria-hidden="true">
178 <rect x="2" y="2" width="8" height="8" rx="1.5" />
179 </svg>
180 </TooltipTrigger>
181 <TooltipPopup>
182 {stopPhase === "pending"
183 ? gt("Stopping…")
184 : gt("Interrupt", { $context: "verb, stops the running agent" })}
185 </TooltipPopup>
186 </Tooltip>
187 );
188 }
189
190 /** The collapsed mobile composer's Stop, shown in place of `children` while a turn can be stopped. */
191 export function CollapsedComposerStopAction({
192 children,
193 canOperateThread,
194 canInterrupt,
195 runId,
196 hasSendableContent,
197 isEditingQueuedMessage,
198 onInterrupt,
199 }: {
200 children: ReactNode;
201 canOperateThread: boolean;
202 canInterrupt: boolean;
203 runId: string | null;
204 hasSendableContent: boolean;
205 isEditingQueuedMessage: boolean;
206 onInterrupt: () => void;
207 }) {
208 const [stopPhase, setStopPhase] = useStopPhase({ runId, canInterrupt, canOperateThread });
209 if (
210 !(canInterrupt || stopPhase === "pending" || stopPhase === "timedOut") ||
211 hasSendableContent ||
212 isEditingQueuedMessage
213 ) {
214 return children;
215 }
216 return (
217 <span
218 data-chat-composer-transition-actions="true"
219 data-chat-composer-collapsed-controls="true"
220 className="flex shrink-0"
221 >
222 <StopGenerationButton
223 stopPhase={stopPhase}
224 canOperateThread={canOperateThread}
225 insidePendingAction={false}
226 preserveComposerFocusOnPointerDown
227 onStopRequested={() => setStopPhase("pending")}
228 onInterrupt={onInterrupt}
229 />
230 </span>
231 );
232 }
233
234 export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
235 children,
236 compact,
237 canOperateThread,
238 pendingAction,
239 isRunning,
240 canInterrupt,
241 runId = null,
242 followUpBehavior = "steer",
243 canSteer = true,
244 alternateShortcutLabel = null,
245 voiceInputActive = false,
246 isSendBusy,
247 sendDisabledReason,
248 isEnvironmentUnavailable,
249 isPreparingWorktree,
250 hasSendableContent,
251 canResume = false,
252 preserveComposerFocusOnPointerDown = false,
253 isEditingQueuedMessage = false,
254 onSubmitMessage,
255 onResume,
256 onPreviousPendingQuestion,
257 onInterrupt,
258 compactBeforeSendTokens = null,
259 hideCompactToggle = false,
260 keepFullHistory = false,
261 onToggleKeepFullHistory,
262 }: ComposerPrimaryActionsProps) {
263 const gt = useGT();
264 const m = useMessages();
265 const [stopPhase, setStopPhase] = useStopPhase({ runId, canInterrupt, canOperateThread });
266 const pointerFocusProps = preserveComposerFocusOnPointerDown
267 ? { onPointerDown: preventPointerFocus }
268 : undefined;
269 const environmentIdentificationMode = useEnvironmentIdentificationMode();
270 const shortcutModifiers = useShortcutModifierState();
271 const isQueuing =
272 !isEditingQueuedMessage &&
273 resolveComposerDispatchMode({
274 running: isRunning,
275 activeTurnDefault: followUpBehavior,
276 canSteer,
277 alternateModifier: shortcutModifiers.metaKey || shortcutModifiers.ctrlKey,
278 }) === "queue";
279 const alternateAction = alternateComposerDispatchAction(followUpBehavior);
280 const isSendDisabled = !canOperateThread || sendDisabledReason !== null;
281 const stageBackdropVariant = useSidebarStageBackdropVariant(environmentIdentificationMode);
282
283 const renderStopGenerationButton = (insidePendingAction: boolean) => (
284 <StopGenerationButton
285 key="interrupt"
286 stopPhase={stopPhase}
287 canOperateThread={canOperateThread}
288 insidePendingAction={insidePendingAction}
289 preserveComposerFocusOnPointerDown={preserveComposerFocusOnPointerDown}
290 onStopRequested={() => setStopPhase("pending")}
291 onInterrupt={onInterrupt}
292 />
293 );
294
295 // Keep the clicked target at the right edge even if typing changes the primary action.
296 const withStopButton = (action: ReactNode) => (
297 <>
298 {action}
299 {stopPhase === "pending" || stopPhase === "timedOut"
300 ? renderStopGenerationButton(false)
301 : null}
302 </>
303 );
304
305 if (pendingAction) {
306 return (
307 <div className={cn("flex items-center justify-end", compact ? "gap-1.5" : "gap-2")}>
308 {pendingAction.questionIndex > 0 ? (
309 compact ? (
310 <Button
311 size="icon-sm"
312 variant="outline"
313 {...pointerFocusProps}
314 onClick={onPreviousPendingQuestion}
315 disabled={pendingAction.isResponding}
316 aria-label={gt("Previous question")}
317 >
318 <ChevronLeftIcon className="size-3.5" />
319 </Button>
320 ) : (
321 <Button
322 size="sm"
323 variant="outline"
324 {...pointerFocusProps}
325 onClick={onPreviousPendingQuestion}
326 disabled={pendingAction.isResponding}
327 >
328 {gt("Previous", { $context: "button that goes to the previous question" })}
329 </Button>
330 )
331 ) : null}
332 {children}
333 <button
334 type="submit"
335 className={cn(messageActionPillClassName, "h-8 sm:h-7", compact ? "px-3" : "px-4")}
336 {...pointerFocusProps}
337 onClick={(event) => {
338 if (stopPhase === "landed") event.preventDefault();
339 }}
340 disabled={
341 !canOperateThread ||
342 isEnvironmentUnavailable ||
343 isSendDisabled ||
344 pendingAction.isResponding ||
345 (!voiceInputActive &&
346 (pendingAction.isLastQuestion
347 ? !pendingAction.isComplete
348 : !pendingAction.canAdvance))
349 }
350 >
351 {formatPendingPrimaryActionLabel(
352 {
353 compact,
354 isLastQuestion: pendingAction.isLastQuestion,
355 isResponding: pendingAction.isResponding,
356 questionIndex: pendingAction.questionIndex,
357 },
358 m,
359 )}
360 </button>
361 {canInterrupt || stopPhase === "pending" || stopPhase === "timedOut"
362 ? renderStopGenerationButton(true)
363 : null}
364 </div>
365 );
366 }
367
368 if (
369 (canInterrupt || stopPhase === "pending" || stopPhase === "timedOut") &&
370 !hasSendableContent &&
371 !isEditingQueuedMessage
372 ) {
373 return (
374 <>
375 {children}
376 {renderStopGenerationButton(false)}
377 </>
378 );
379 }
380
381 const showResume = canResume && !hasSendableContent && !isEditingQueuedMessage;
382
383 const compactTokens =
384 compactBeforeSendTokens !== null && !showResume && !isEditingQueuedMessage
385 ? formatContextWindowTokens(compactBeforeSendTokens)
386 : null;
387 const compactsBeforeSend = compactTokens !== null && !keepFullHistory;
388
389 const submitLabel = showResume
390 ? gt("Resume thread")
391 : isEditingQueuedMessage
392 ? gt("Update queued message")
393 : compactsBeforeSend
394 ? gt("Compact and send")
395 : isQueuing
396 ? gt("Queue message")
397 : isRunning
398 ? gt("Steer message")
399 : gt("Submit message");
400 const submitStatus = isEnvironmentUnavailable
401 ? gt("Environment disconnected")
402 : (sendDisabledReason ??
403 (isPreparingWorktree
404 ? gt("Preparing worktree")
405 : isSendBusy
406 ? isEditingQueuedMessage
407 ? gt("Updating queued message")
408 : gt("Submitting message")
409 : null));
410 const modifier = isMacPlatform(navigator.platform) ? "⌘" : "Ctrl";
411 const dispatchTooltip =
412 alternateAction === "queue"
413 ? alternateShortcutLabel
414 ? gt("Click to steer, {modifier}-click or {shortcut} to queue", {
415 modifier,
416 shortcut: alternateShortcutLabel,
417 })
418 : gt("Click to steer, {modifier}-click to queue", { modifier })
419 : alternateShortcutLabel
420 ? gt("Click to queue, {modifier}-click or {shortcut} to steer", {
421 modifier,
422 shortcut: alternateShortcutLabel,
423 })
424 : gt("Click to queue, {modifier}-click to steer", { modifier });
425 const submitTooltip =
426 submitStatus ??
427 (compactsBeforeSend
428 ? gt("Summarize {tokens} tokens of history, then send", { tokens: compactTokens })
429 : isRunning && !isEditingQueuedMessage && canSteer
430 ? dispatchTooltip
431 : submitLabel);
432
433 const sendButton = (
434 <button
435 type={showResume ? "button" : "submit"}
436 className={cn(
437 "relative isolate flex h-9 w-9 items-center justify-center overflow-hidden rounded-full shadow-xs transition-all duration-150 enabled:cursor-pointer enabled:inset-shadow-control-highlight hover:scale-105 active:inset-shadow-control-pressed active:shadow-none disabled:pointer-events-none disabled:shadow-none disabled:hover:scale-100 sm:h-8 sm:w-8 [&_svg]:pointer-events-none",
438 stageBackdropVariant
439 ? "bg-transparent text-white enabled:shadow-black/24 enabled:hover:brightness-110 disabled:opacity-64"
440 : "bg-message-action text-message-action-foreground enabled:shadow-message-action/24 hover:bg-message-action-hover disabled:bg-foreground/12 disabled:text-muted-foreground",
441 )}
442 {...pointerFocusProps}
443 onClick={(event) => {
444 if (stopPhase === "landed") {
445 event.preventDefault();
446 return;
447 }
448 if (showResume) onResume?.();
449 else onSubmitMessage?.(event);
450 }}
451 disabled={
452 isSendBusy ||
453 isSendDisabled ||
454 isEnvironmentUnavailable ||
455 (!hasSendableContent && !showResume)
456 }
457 aria-label={submitStatus ?? submitLabel}
458 >
459 {stageBackdropVariant ? (
460 <span className="pointer-events-none absolute inset-0 -z-10" aria-hidden="true">
461 <StageBackdropButtonArt variant={stageBackdropVariant} />
462 </span>
463 ) : null}
464 {isSendBusy ? (
465 <Spinner size="sm" aria-hidden="true" />
466 ) : showResume ? (
467 <PlayIcon className="size-4 fill-current" aria-hidden="true" />
468 ) : isEditingQueuedMessage ? (
469 <CheckIcon className="size-4" aria-hidden="true" />
470 ) : isRunning && isQueuing ? (
471 <ListPlusIcon className="size-4" aria-hidden="true" />
472 ) : isRunning ? (
473 <CornerUpRightIcon className="size-4" aria-hidden="true" />
474 ) : (
475 <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
476 <path
477 d="M7 11.5V2.5M7 2.5L3 6.5M7 2.5L11 6.5"
478 stroke="currentColor"
479 strokeWidth="1.8"
480 strokeLinecap="round"
481 strokeLinejoin="round"
482 />
483 </svg>
484 )}
485 </button>
486 );
487
488 const submit = (
489 <Tooltip key="submit">
490 <TooltipTrigger render={<span className="inline-flex" />}>{sendButton}</TooltipTrigger>
491 <TooltipPopup>{submitTooltip}</TooltipPopup>
492 </Tooltip>
493 );
494 if (compactTokens === null || hideCompactToggle) {
495 return withStopButton(
496 <>
497 {children}
498 {submit}
499 </>,
500 );
501 }
502
503 return withStopButton(
504 <div data-chat-composer-compact-send="true" className="flex items-center gap-2">
505 <Tooltip>
506 <TooltipTrigger
507 render={
508 <button
509 type="button"
510 className="flex h-7 shrink-0 cursor-pointer items-center gap-1.5 rounded-(--control-radius) px-2 font-medium text-base text-foreground/80 tabular-nums outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-64 sm:text-sm aria-pressed:bg-accent/60 aria-pressed:text-foreground [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:text-muted-foreground"
511 {...pointerFocusProps}
512 aria-pressed={!keepFullHistory}
513 aria-label={gt("Compact {tokens} tokens of history before sending", {
514 tokens: compactTokens,
515 })}
516 disabled={!canOperateThread}
517 onClick={onToggleKeepFullHistory}
518 />
519 }
520 >
521 <Minimize2Icon aria-hidden="true" />
522 <span className="@max-[480px]/composer-surface:hidden">
523 {keepFullHistory
524 ? gt("Keep", { $context: "keep full history instead of compacting" })
525 : gt("Compact", { $context: "verb, compact history before sending" })}
526 </span>
527 <span className="text-muted-foreground">{compactTokens}</span>
528 </TooltipTrigger>
529 <TooltipPopup>
530 <div>
531 {keepFullHistory
532 ? gt("Next send keeps all {tokens} tokens.", { tokens: compactTokens })
533 : gt("Next send compacts {tokens} tokens first.", { tokens: compactTokens })}
534 </div>
535 <div>
536 {keepFullHistory ? gt("Click to compact first") : gt("Click to keep full history")}
537 </div>
538 </TooltipPopup>
539 </Tooltip>
540 {children}
541 {submit}
542 </div>,
543 );
544 });