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

ComposerPrimaryActions.tsx

506 lines17.5 KB

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