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

ComposerPrimaryActions.tsx

551 lines19.1 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("Submit", { $context: "verb, submits answers" }))
90 : resolve(msg("Next", { $context: "button that goes to the next question" }));
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("Interrupt", { $context: "verb, stops the running agent" })
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: shortcutModifiers.metaKey || shortcutModifiers.ctrlKey,
280 }) === "queue";
281 const alternateAction = alternateComposerDispatchAction(followUpBehavior);
282 const isSendDisabled = !canOperateThread || sendDisabledReason !== null;
283 const stageBackdropVariant = useSidebarStageBackdropVariant(environmentIdentificationMode);
284​
285 const renderStopGenerationButton = (insidePendingAction: boolean) => (
286 <StopGenerationButton
287 key="interrupt"
288 stopPhase={stopPhase}
289 canOperateThread={canOperateThread}
290 insidePendingAction={insidePendingAction}
291 preserveComposerFocusOnPointerDown={preserveComposerFocusOnPointerDown}
292 onStopRequested={() => setStopPhase("pending")}
293 onInterrupt={onInterrupt}
294 />
295 );
296​
297 // Keep the clicked target at the right edge even if typing changes the primary action.
298 const withStopButton = (action: ReactNode) => (
299 <>
300 {action}
301 {stopPhase === "pending" || stopPhase === "timedOut"
302 ? renderStopGenerationButton(false)
303 : null}
304 </>
305 );
306​
307 if (pendingAction) {
308 return (
309 <div className={cn("flex items-center justify-end", compact ? "gap-1.5" : "gap-2")}>
310 {pendingAction.questionIndex > 0 ? (
311 compact ? (
312 <Button
313 size="icon-sm"
314 variant="outline"
315 {...pointerFocusProps}
316 onClick={onPreviousPendingQuestion}
317 disabled={pendingAction.isResponding}
318 aria-label={gt("Previous question")}
319 >
320 <ChevronLeftIcon className="size-3.5" />
321 </Button>
322 ) : (
323 <Button
324 size="sm"
325 variant="outline"
326 {...pointerFocusProps}
327 onClick={onPreviousPendingQuestion}
328 disabled={pendingAction.isResponding}
329 >
330 {gt("Previous", { $context: "button that goes to the previous question" })}
331 </Button>
332 )
333 ) : null}
334 {children}
335 <button
336 type="submit"
337 className={cn(messageActionPillClassName, "h-8 sm:h-7", compact ? "px-3" : "px-4")}
338 {...pointerFocusProps}
339 onClick={(event) => {
340 if (stopPhase === "landed") event.preventDefault();
341 }}
342 disabled={
343 !canOperateThread ||
344 isEnvironmentUnavailable ||
345 isSendDisabled ||
346 pendingAction.isResponding ||
347 (!voiceInputActive &&
348 (pendingAction.isLastQuestion
349 ? !pendingAction.isComplete
350 : !pendingAction.canAdvance))
351 }
352 >
353 {formatPendingPrimaryActionLabel(
354 {
355 compact,
356 isLastQuestion: pendingAction.isLastQuestion,
357 isResponding: pendingAction.isResponding,
358 questionIndex: pendingAction.questionIndex,
359 },
360 m,
361 )}
362 </button>
363 {canInterrupt || stopPhase === "pending" || stopPhase === "timedOut"
364 ? renderStopGenerationButton(true)
365 : null}
366 </div>
367 );
368 }
369​
370 if (
371 (canInterrupt || stopPhase === "pending" || stopPhase === "timedOut") &&
372 !hasSendableContent &&
373 !isEditingQueuedMessage &&
374 !isSendHeld
375 ) {
376 return (
377 <>
378 {children}
379 {renderStopGenerationButton(false)}
380 </>
381 );
382 }
383​
384 const showResume = canResume && !hasSendableContent && !isEditingQueuedMessage;
385​
386 const compactTokens =
387 compactBeforeSendTokens !== null && !showResume && !isEditingQueuedMessage
388 ? formatContextWindowTokens(compactBeforeSendTokens)
389 : null;
390 const compactsBeforeSend = compactTokens !== null && !keepFullHistory;
391​
392 const submitLabel = showResume
393 ? gt("Resume thread")
394 : isEditingQueuedMessage
395 ? gt("Update queued message")
396 : compactsBeforeSend
397 ? gt("Compact and send")
398 : isQueuing
399 ? gt("Queue message")
400 : isRunning
401 ? gt("Steer message")
402 : gt("Submit message");
403 const submitStatus = isEnvironmentUnavailable
404 ? gt("Environment disconnected")
405 : isSendHeld
406 ? gt("Sending when ready")
407 : (sendDisabledReason ??
408 (isPreparingWorktree
409 ? gt("Preparing worktree")
410 : isSendBusy
411 ? isEditingQueuedMessage
412 ? gt("Updating queued message")
413 : gt("Submitting message")
414 : null));
415 const modifier = isMacPlatform(navigator.platform) ? "⌘" : "Ctrl";
416 const dispatchTooltip =
417 alternateAction === "queue"
418 ? alternateShortcutLabel
419 ? gt("Click to steer, {modifier}-click or {shortcut} to queue", {
420 modifier,
421 shortcut: alternateShortcutLabel,
422 })
423 : gt("Click to steer, {modifier}-click to queue", { modifier })
424 : alternateShortcutLabel
425 ? gt("Click to queue, {modifier}-click or {shortcut} to steer", {
426 modifier,
427 shortcut: alternateShortcutLabel,
428 })
429 : gt("Click to queue, {modifier}-click to steer", { modifier });
430 const submitTooltip =
431 submitStatus ??
432 (compactsBeforeSend
433 ? gt("Summarize {tokens} tokens of history, then send", { tokens: compactTokens })
434 : isRunning && !isEditingQueuedMessage && canSteer
435 ? dispatchTooltip
436 : submitLabel);
437​
438 const isBusyOrHeld = isSendBusy || isSendHeld;
439 const sendButton = (
440 <button
441 type={showResume ? "button" : "submit"}
442 className={cn(
443 "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",
444 stageBackdropVariant
445 ? "bg-transparent text-white enabled:shadow-black/24 enabled:hover:brightness-110 disabled:opacity-64"
446 : "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",
447 )}
448 {...pointerFocusProps}
449 onClick={(event) => {
450 if (stopPhase === "landed") {
451 event.preventDefault();
452 return;
453 }
454 if (showResume) onResume?.();
455 else onSubmitMessage?.(event);
456 }}
457 disabled={
458 isBusyOrHeld ||
459 isSendDisabled ||
460 isEnvironmentUnavailable ||
461 (!hasSendableContent && !showResume)
462 }
463 aria-label={submitStatus ?? submitLabel}
464 aria-busy={isBusyOrHeld || undefined}
465 >
466 {stageBackdropVariant ? (
467 <span className="pointer-events-none absolute inset-0 -z-10" aria-hidden="true">
468 <StageBackdropButtonArt variant={stageBackdropVariant} />
469 </span>
470 ) : null}
471 {isBusyOrHeld ? (
472 <Spinner size="sm" aria-hidden="true" />
473 ) : showResume ? (
474 <PlayIcon className="size-4 fill-current" aria-hidden="true" />
475 ) : isEditingQueuedMessage ? (
476 <CheckIcon className="size-4" aria-hidden="true" />
477 ) : isRunning && isQueuing ? (
478 <ListPlusIcon className="size-4" aria-hidden="true" />
479 ) : isRunning ? (
480 <CornerUpRightIcon className="size-4" aria-hidden="true" />
481 ) : (
482 <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
483 <path
484 d="M7 11.5V2.5M7 2.5L3 6.5M7 2.5L11 6.5"
485 stroke="currentColor"
486 strokeWidth="1.8"
487 strokeLinecap="round"
488 strokeLinejoin="round"
489 />
490 </svg>
491 )}
492 </button>
493 );
494​
495 const submit = (
496 <Tooltip key="submit">
497 <TooltipTrigger render={<span className="inline-flex" />}>{sendButton}</TooltipTrigger>
498 <TooltipPopup>{submitTooltip}</TooltipPopup>
499 </Tooltip>
500 );
501 if (compactTokens === null || hideCompactToggle) {
502 return withStopButton(
503 <>
504 {children}
505 {submit}
506 </>,
507 );
508 }
509​
510 return withStopButton(
511 <div data-chat-composer-compact-send="true" className="flex items-center gap-2">
512 <SharedTooltipTrigger
513 render={
514 <button
515 type="button"
516 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"
517 {...pointerFocusProps}
518 aria-pressed={!keepFullHistory}
519 aria-label={gt("Compact {tokens} tokens of history before sending", {
520 tokens: compactTokens,
521 })}
522 disabled={!canOperateThread}
523 onClick={onToggleKeepFullHistory}
524 />
525 }
526 label={
527 <>
528 <div>
529 {keepFullHistory
530 ? gt("Next send keeps all {tokens} tokens.", { tokens: compactTokens })
531 : gt("Next send compacts {tokens} tokens first.", { tokens: compactTokens })}
532 </div>
533 <div>
534 {keepFullHistory ? gt("Click to compact first") : gt("Click to keep full history")}
535 </div>
536 </>
537 }
538 >
539 <Minimize2Icon aria-hidden="true" />
540 <span className="@max-[480px]/composer-surface:hidden">
541 {keepFullHistory
542 ? gt("Keep", { $context: "keep full history instead of compacting" })
543 : gt("Compact", { $context: "verb, compact history before sending" })}
544 </span>
545 <span className="text-muted-foreground">{compactTokens}</span>
546 </SharedTooltipTrigger>
547 {children}
548 {submit}
549 </div>,
550 );
551});