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