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

ComposerPrimaryActions.tsx

545 lines19.0 KB

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