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 {
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;
36}
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;
68}
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
90const messageActionPillClassName =
91 "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";
92
93const preventPointerFocus: PointerEventHandler<HTMLElement> = (event) => {
94 event.preventDefault();
95};
96
97export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
98 children,
99 compact,
100 canOperateThread,
101 pendingAction,
102 isRunning,
103 canInterrupt,
104 runId = null,
105 followUpBehavior = "steer",
106 canSteer = true,
107 alternateShortcutLabel = null,
108 voiceInputActive = false,
109 isSendBusy,
110 sendDisabledReason,
111 isEnvironmentUnavailable,
112 isPreparingWorktree,
113 hasSendableContent,
114 canResume = false,
115 preserveComposerFocusOnPointerDown = false,
116 isEditingQueuedMessage = false,
117 onSubmitMessage,
118 onResume,
119 onPreviousPendingQuestion,
120 onInterrupt,
121 compactBeforeSendTokens = null,
122 hideCompactToggle = false,
123 keepFullHistory = false,
124 onToggleKeepFullHistory,
125}: ComposerPrimaryActionsProps) {
126 const [stopPhase, setStopPhase] = useState<"pending" | "timedOut" | "landed" | null>(null);
127 const [stopRunId, setStopRunId] = useState(runId);
128 if (runId !== null && stopRunId !== runId) {
129 setStopRunId(runId);
130 setStopPhase(null);
131 } else if (canOperateThread) {
132 // Losing permission also clears canInterrupt; it does not acknowledge the stop.
133 if ((stopPhase === "pending" || stopPhase === "timedOut") && !canInterrupt)
134 setStopPhase("landed");
135 else if (stopPhase === "landed" && canInterrupt) setStopPhase(null);
136 }
137 const isStopDisabled = stopPhase === "pending" || stopPhase === "landed";
138 const stopLabel =
139 stopPhase === "landed" ? "Stopped" : stopPhase === "pending" ? "Stopping" : "Stop generation";
140 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- timer that re-enables Stop if the interrupt never settles
141 useEffect(() => {
142 if (stopPhase !== "pending") return;
143 const timeout = setTimeout(() => setStopPhase("timedOut"), STOP_PENDING_MAX_MS);
144 return () => clearTimeout(timeout);
145 }, [stopPhase]);
146 const pointerFocusProps = preserveComposerFocusOnPointerDown
147 ? { onPointerDown: preventPointerFocus }
148 : undefined;
149 const environmentIdentificationMode = useEnvironmentIdentificationMode();
150 const shortcutModifiers = useShortcutModifierState();
151 const isQueuing =
152 !isEditingQueuedMessage &&
153 resolveComposerDispatchMode({
154 running: isRunning,
155 activeTurnDefault: followUpBehavior,
156 canSteer,
157 alternateModifier: shortcutModifiers.metaKey || shortcutModifiers.ctrlKey,
158 }) === "queue";
159 const alternateAction = alternateComposerDispatchAction(followUpBehavior);
160 const isSendDisabled = !canOperateThread || sendDisabledReason !== null;
161 const stageBackdropVariant = useSidebarStageBackdropVariant(environmentIdentificationMode);
162
163 const renderStopGenerationButton = (insidePendingAction: boolean) => (
164 <Tooltip key="interrupt">
165 <TooltipTrigger
166 render={
167 <button
168 type="button"
169 className={cn(
170 "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",
171 insidePendingAction ? "size-8 sm:size-7" : "size-8 sm:h-8 sm:w-8",
172 )}
173 {...pointerFocusProps}
174 disabled={!canOperateThread || isStopDisabled}
175 onClick={() => {
176 if (!canOperateThread || isStopDisabled) return;
177 setStopPhase("pending");
178 onInterrupt();
179 }}
180 aria-label={stopLabel}
181 />
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 </TooltipTrigger>
188 <TooltipPopup>
189 {stopPhase === "pending" ? "Stopping…" : stopPhase === "landed" ? "Stopped" : "Interrupt"}
190 </TooltipPopup>
191 </Tooltip>
192 );
193
194 // Keep the clicked target at the right edge even if typing changes the primary action.
195 const withStopButton = (action: ReactNode) => (
196 <>
197 {action}
198 {stopPhase === null ? null : renderStopGenerationButton(false)}
199 </>
200 );
201
202 if (pendingAction) {
203 return (
204 <div className={cn("flex items-center justify-end", compact ? "gap-1.5" : "gap-2")}>
205 {pendingAction.questionIndex > 0 ? (
206 compact ? (
207 <Button
208 size="icon-sm"
209 variant="outline"
210 {...pointerFocusProps}
211 onClick={onPreviousPendingQuestion}
212 disabled={pendingAction.isResponding}
213 aria-label="Previous question"
214 >
215 <ChevronLeftIcon className="size-3.5" />
216 </Button>
217 ) : (
218 <Button
219 size="sm"
220 variant="outline"
221 {...pointerFocusProps}
222 onClick={onPreviousPendingQuestion}
223 disabled={pendingAction.isResponding}
224 >
225 Previous
226 </Button>
227 )
228 ) : null}
229 {children}
230 <button
231 type="submit"
232 className={cn(messageActionPillClassName, "h-8 sm:h-7", compact ? "px-3" : "px-4")}
233 {...pointerFocusProps}
234 disabled={
235 !canOperateThread ||
236 isEnvironmentUnavailable ||
237 isSendDisabled ||
238 pendingAction.isResponding ||
239 (!voiceInputActive &&
240 (pendingAction.isLastQuestion
241 ? !pendingAction.isComplete
242 : !pendingAction.canAdvance))
243 }
244 >
245 {formatPendingPrimaryActionLabel({
246 compact,
247 isLastQuestion: pendingAction.isLastQuestion,
248 isResponding: pendingAction.isResponding,
249 questionIndex: pendingAction.questionIndex,
250 })}
251 </button>
252 {canInterrupt || stopPhase !== null ? renderStopGenerationButton(true) : null}
253 </div>
254 );
255 }
256
257 if (
258 (canInterrupt || stopPhase === "pending" || stopPhase === "timedOut") &&
259 !hasSendableContent &&
260 !isEditingQueuedMessage
261 ) {
262 return (
263 <>
264 {children}
265 {renderStopGenerationButton(false)}
266 </>
267 );
268 }
269
270 const showResume = canResume && !hasSendableContent && !isEditingQueuedMessage;
271
272 const compactTokens =
273 compactBeforeSendTokens !== null && !showResume && !isEditingQueuedMessage
274 ? formatContextWindowTokens(compactBeforeSendTokens)
275 : null;
276 const compactsBeforeSend = compactTokens !== null && !keepFullHistory;
277
278 const submitLabel = showResume
279 ? "Resume thread"
280 : isEditingQueuedMessage
281 ? "Update queued message"
282 : compactsBeforeSend
283 ? "Compact and send"
284 : isQueuing
285 ? "Queue message"
286 : isRunning
287 ? "Steer message"
288 : "Submit message";
289 const submitStatus = isEnvironmentUnavailable
290 ? "Environment disconnected"
291 : (sendDisabledReason ??
292 (isPreparingWorktree
293 ? "Preparing worktree"
294 : isSendBusy
295 ? isEditingQueuedMessage
296 ? "Updating queued message"
297 : "Submitting message"
298 : null));
299 const submitTooltip =
300 submitStatus ??
301 (compactsBeforeSend
302 ? `Summarize ${compactTokens} tokens of history, then send`
303 : isRunning && !isEditingQueuedMessage && canSteer
304 ? `Click to ${followUpBehavior}, ${isMacPlatform(navigator.platform) ? "⌘" : "Ctrl"}-click${alternateShortcutLabel ? ` or ${alternateShortcutLabel}` : ""} to ${alternateAction}`
305 : submitLabel);
306
307 const sendButton = (
308 <button
309 type={showResume ? "button" : "submit"}
310 className={cn(
311 "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",
312 stageBackdropVariant
313 ? "bg-transparent text-white enabled:shadow-black/24 enabled:hover:brightness-110 disabled:opacity-64"
314 : "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",
315 )}
316 {...pointerFocusProps}
317 onClick={showResume ? onResume : onSubmitMessage}
318 disabled={
319 isSendBusy ||
320 isSendDisabled ||
321 isEnvironmentUnavailable ||
322 (!hasSendableContent && !showResume)
323 }
324 aria-label={submitStatus ?? submitLabel}
325 >
326 {stageBackdropVariant ? (
327 <span className="pointer-events-none absolute inset-0 -z-10" aria-hidden="true">
328 <StageBackdropButtonArt variant={stageBackdropVariant} />
329 </span>
330 ) : null}
331 {isSendBusy ? (
332 <Spinner size="sm" aria-hidden="true" />
333 ) : showResume ? (
334 <PlayIcon className="size-4 fill-current" aria-hidden="true" />
335 ) : isEditingQueuedMessage ? (
336 <CheckIcon className="size-4" aria-hidden="true" />
337 ) : isRunning && isQueuing ? (
338 <ListPlusIcon className="size-4" aria-hidden="true" />
339 ) : isRunning ? (
340 <CornerUpRightIcon className="size-4" aria-hidden="true" />
341 ) : (
342 <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
343 <path
344 d="M7 11.5V2.5M7 2.5L3 6.5M7 2.5L11 6.5"
345 stroke="currentColor"
346 strokeWidth="1.8"
347 strokeLinecap="round"
348 strokeLinejoin="round"
349 />
350 </svg>
351 )}
352 </button>
353 );
354
355 const submit = (
356 <Tooltip key="submit">
357 <TooltipTrigger render={<span className="inline-flex" />}>{sendButton}</TooltipTrigger>
358 <TooltipPopup>{submitTooltip}</TooltipPopup>
359 </Tooltip>
360 );
361 if (compactTokens === null || hideCompactToggle) {
362 return withStopButton(
363 <>
364 {children}
365 {submit}
366 </>,
367 );
368 }
369
370 return withStopButton(
371 <div data-chat-composer-compact-send="true" className="flex items-center gap-2">
372 <Tooltip>
373 <TooltipTrigger
374 render={
375 <button
376 type="button"
377 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"
378 {...pointerFocusProps}
379 aria-pressed={!keepFullHistory}
380 aria-label={`Compact ${compactTokens} tokens of history before sending`}
381 disabled={!canOperateThread}
382 onClick={onToggleKeepFullHistory}
383 />
384 }
385 >
386 <Minimize2Icon aria-hidden="true" />
387 <span className="@max-[480px]/composer-surface:hidden">
388 {keepFullHistory ? "Keep" : "Compact"}
389 </span>
390 <span className="text-muted-foreground">{compactTokens}</span>
391 </TooltipTrigger>
392 <TooltipPopup>
393 <div>
394 {keepFullHistory
395 ? `Next send keeps all ${compactTokens} tokens.`
396 : `Next send compacts ${compactTokens} tokens first.`}
397 </div>
398 <div>{keepFullHistory ? "Click to compact first" : "Click to keep full history"}</div>
399 </TooltipPopup>
400 </Tooltip>
401 {children}
402 {submit}
403 </div>,
404 );
405});