Open History to see the last commit
1import { memo, type MouseEventHandler, type PointerEventHandler, type ReactNode } from "react";
2import { CheckIcon, ChevronLeftIcon, Minimize2Icon, PlayIcon } from "lucide-react";
3import { CornerUpRight, ListPlus } from "lucide";
4import { MorphIcon } from "~/components/MorphIcon";
5import { useEnvironmentIdentificationMode } from "~/hooks/useSettings";
6import { formatContextWindowTokens } from "~/lib/contextWindow";
7import { cn, isMacPlatform } from "~/lib/utils";
8import { useShortcutModifierState } from "../../shortcutModifierState";
9import { StageBackdropButtonArt, useSidebarStageBackdropVariant } from "../SidebarStageBackdrop";
10import { Button } from "../ui/button";
11import { Spinner } from "../ui/spinner";
12import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
13import {
14 alternateComposerDispatchAction,
15 resolveComposerDispatchMode,
16} from "@t3tools/client-runtime/state/composer-dispatch";
17
18interface PendingActionState {
19 questionIndex: number;
20 isLastQuestion: boolean;
21 canAdvance: boolean;
22 isResponding: boolean;
23 isComplete: boolean;
24}
25
26interface ComposerPrimaryActionsProps {
27 /** Footer controls (dictation) that always sit right before the primary button. */
28 children?: ReactNode;
29 compact: boolean;
30 canOperateThread: boolean;
31 pendingAction: PendingActionState | null;
32 isRunning: boolean;
33 canInterrupt: boolean;
34 followUpBehavior?: "queue" | "steer";
35 canSteer?: boolean;
36 alternateShortcutLabel?: string | null;
37 /** Dictation is running; Send finishes it and submits once the transcript lands. */
38 voiceInputActive?: boolean;
39 isSendBusy: boolean;
40 sendDisabledReason: string | null;
41 isEnvironmentUnavailable: boolean;
42 isPreparingWorktree: boolean;
43 hasSendableContent: boolean;
44 canResume?: boolean;
45 preserveComposerFocusOnPointerDown?: boolean;
46 isEditingQueuedMessage?: boolean;
47 onSubmitMessage?: MouseEventHandler<HTMLButtonElement>;
48 onResume?: () => void;
49 onPreviousPendingQuestion: () => void;
50 onInterrupt: () => void;
51 compactBeforeSendTokens?: number | null;
52 keepFullHistory?: boolean;
53 onToggleKeepFullHistory?: () => void;
54}
55
56const formatPendingPrimaryActionLabel = (input: {
57 compact: boolean;
58 isLastQuestion: boolean;
59 isResponding: boolean;
60 questionIndex: number;
61}) => {
62 if (input.isResponding) {
63 return "Submitting...";
64 }
65 if (input.compact) {
66 return input.isLastQuestion ? "Submit" : "Next";
67 }
68 if (!input.isLastQuestion) {
69 return "Next question";
70 }
71 return input.questionIndex > 0 ? "Submit answers" : "Submit answer";
72};
73
74const messageActionPillClassName =
75 "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";
76
77const preventPointerFocus: PointerEventHandler<HTMLElement> = (event) => {
78 event.preventDefault();
79};
80
81export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
82 children,
83 compact,
84 canOperateThread,
85 pendingAction,
86 isRunning,
87 canInterrupt,
88 followUpBehavior = "steer",
89 canSteer = true,
90 alternateShortcutLabel = null,
91 voiceInputActive = false,
92 isSendBusy,
93 sendDisabledReason,
94 isEnvironmentUnavailable,
95 isPreparingWorktree,
96 hasSendableContent,
97 canResume = false,
98 preserveComposerFocusOnPointerDown = false,
99 isEditingQueuedMessage = false,
100 onSubmitMessage,
101 onResume,
102 onPreviousPendingQuestion,
103 onInterrupt,
104 compactBeforeSendTokens = null,
105 keepFullHistory = false,
106 onToggleKeepFullHistory,
107}: ComposerPrimaryActionsProps) {
108 const pointerFocusProps = preserveComposerFocusOnPointerDown
109 ? { onPointerDown: preventPointerFocus }
110 : undefined;
111 const environmentIdentificationMode = useEnvironmentIdentificationMode();
112 const shortcutModifiers = useShortcutModifierState();
113 const isQueuing =
114 !isEditingQueuedMessage &&
115 resolveComposerDispatchMode({
116 running: isRunning,
117 activeTurnDefault: followUpBehavior,
118 canSteer,
119 alternateModifier: shortcutModifiers.metaKey || shortcutModifiers.ctrlKey,
120 }) === "queue";
121 const alternateAction = alternateComposerDispatchAction(followUpBehavior);
122 const isSendDisabled = !canOperateThread || sendDisabledReason !== null;
123 const stageBackdropVariant = useSidebarStageBackdropVariant(environmentIdentificationMode);
124
125 const renderStopGenerationButton = (insidePendingAction: boolean) => (
126 <Tooltip key="interrupt">
127 <TooltipTrigger
128 render={
129 <button
130 type="button"
131 className={cn(
132 "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 [&_svg]:pointer-events-none",
133 insidePendingAction ? "size-8 sm:size-7" : "size-8 sm:h-8 sm:w-8",
134 )}
135 {...pointerFocusProps}
136 disabled={!canOperateThread}
137 onClick={() => {
138 if (canOperateThread) onInterrupt();
139 }}
140 aria-label="Stop generation"
141 />
142 }
143 >
144 <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor" aria-hidden="true">
145 <rect x="2" y="2" width="8" height="8" rx="1.5" />
146 </svg>
147 </TooltipTrigger>
148 <TooltipPopup>Interrupt</TooltipPopup>
149 </Tooltip>
150 );
151
152 if (pendingAction) {
153 return (
154 <div className={cn("flex items-center justify-end", compact ? "gap-1.5" : "gap-2")}>
155 {canInterrupt ? renderStopGenerationButton(true) : null}
156 {pendingAction.questionIndex > 0 ? (
157 compact ? (
158 <Button
159 size="icon-sm"
160 variant="outline"
161 {...pointerFocusProps}
162 onClick={onPreviousPendingQuestion}
163 disabled={pendingAction.isResponding}
164 aria-label="Previous question"
165 >
166 <ChevronLeftIcon className="size-3.5" />
167 </Button>
168 ) : (
169 <Button
170 size="sm"
171 variant="outline"
172 {...pointerFocusProps}
173 onClick={onPreviousPendingQuestion}
174 disabled={pendingAction.isResponding}
175 >
176 Previous
177 </Button>
178 )
179 ) : null}
180 {children}
181 <button
182 type="submit"
183 className={cn(messageActionPillClassName, "h-8 sm:h-7", compact ? "px-3" : "px-4")}
184 {...pointerFocusProps}
185 disabled={
186 !canOperateThread ||
187 isEnvironmentUnavailable ||
188 isSendDisabled ||
189 pendingAction.isResponding ||
190 (!voiceInputActive &&
191 (pendingAction.isLastQuestion
192 ? !pendingAction.isComplete
193 : !pendingAction.canAdvance))
194 }
195 >
196 {formatPendingPrimaryActionLabel({
197 compact,
198 isLastQuestion: pendingAction.isLastQuestion,
199 isResponding: pendingAction.isResponding,
200 questionIndex: pendingAction.questionIndex,
201 })}
202 </button>
203 </div>
204 );
205 }
206
207 if (canInterrupt && !hasSendableContent && !isEditingQueuedMessage) {
208 return (
209 <>
210 {children}
211 {renderStopGenerationButton(false)}
212 </>
213 );
214 }
215
216 const showResume = canResume && !hasSendableContent && !isEditingQueuedMessage;
217
218 const compactTokens =
219 compactBeforeSendTokens !== null && !showResume && !isEditingQueuedMessage
220 ? formatContextWindowTokens(compactBeforeSendTokens)
221 : null;
222 const compactsBeforeSend = compactTokens !== null && !keepFullHistory;
223
224 const submitLabel = showResume
225 ? "Resume thread"
226 : isEditingQueuedMessage
227 ? "Update queued message"
228 : compactsBeforeSend
229 ? "Compact and send"
230 : isQueuing
231 ? "Queue message"
232 : isRunning
233 ? "Steer message"
234 : "Submit message";
235 const submitStatus = isEnvironmentUnavailable
236 ? "Environment disconnected"
237 : (sendDisabledReason ??
238 (isPreparingWorktree
239 ? "Preparing worktree"
240 : isSendBusy
241 ? isEditingQueuedMessage
242 ? "Updating queued message"
243 : "Submitting message"
244 : null));
245 const submitTooltip =
246 submitStatus ??
247 (compactsBeforeSend
248 ? `Summarize ${compactTokens} tokens of history, then send`
249 : isRunning && !isEditingQueuedMessage && canSteer
250 ? `Click to ${followUpBehavior}, ${isMacPlatform(navigator.platform) ? "⌘" : "Ctrl"}-click${alternateShortcutLabel ? ` or ${alternateShortcutLabel}` : ""} to ${alternateAction}`
251 : submitLabel);
252
253 const sendButton = (
254 <button
255 type={showResume ? "button" : "submit"}
256 className={cn(
257 "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",
258 stageBackdropVariant
259 ? "bg-transparent text-white enabled:shadow-black/24 enabled:hover:brightness-110 disabled:opacity-64"
260 : "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",
261 )}
262 {...pointerFocusProps}
263 onClick={showResume ? onResume : onSubmitMessage}
264 disabled={
265 isSendBusy ||
266 isSendDisabled ||
267 isEnvironmentUnavailable ||
268 (!hasSendableContent && !showResume)
269 }
270 aria-label={submitStatus ?? submitLabel}
271 >
272 {stageBackdropVariant ? (
273 <span className="pointer-events-none absolute inset-0 -z-10" aria-hidden="true">
274 <StageBackdropButtonArt variant={stageBackdropVariant} />
275 </span>
276 ) : null}
277 {isSendBusy ? (
278 <Spinner size="sm" aria-hidden="true" />
279 ) : showResume ? (
280 <PlayIcon className="size-4 fill-current" aria-hidden="true" />
281 ) : isEditingQueuedMessage ? (
282 <CheckIcon className="size-4" aria-hidden="true" />
283 ) : isRunning ? (
284 <MorphIcon className="size-4" icon={isQueuing ? ListPlus : CornerUpRight} />
285 ) : (
286 <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
287 <path
288 d="M7 11.5V2.5M7 2.5L3 6.5M7 2.5L11 6.5"
289 stroke="currentColor"
290 strokeWidth="1.8"
291 strokeLinecap="round"
292 strokeLinejoin="round"
293 />
294 </svg>
295 )}
296 </button>
297 );
298
299 const submit = (
300 <Tooltip key="submit">
301 <TooltipTrigger render={<span className="inline-flex" />}>{sendButton}</TooltipTrigger>
302 <TooltipPopup>{submitTooltip}</TooltipPopup>
303 </Tooltip>
304 );
305 if (compactTokens === null) {
306 return (
307 <>
308 {children}
309 {submit}
310 </>
311 );
312 }
313
314 return (
315 <div data-chat-composer-compact-send="true" className="flex items-center gap-2">
316 <Tooltip>
317 <TooltipTrigger
318 render={
319 <button
320 type="button"
321 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"
322 {...pointerFocusProps}
323 aria-pressed={!keepFullHistory}
324 aria-label={`Compact ${compactTokens} tokens of history before sending`}
325 disabled={!canOperateThread}
326 onClick={onToggleKeepFullHistory}
327 />
328 }
329 >
330 <Minimize2Icon aria-hidden="true" />
331 <span className="@max-[480px]/composer-surface:hidden">
332 {keepFullHistory ? "Keep" : "Compact"}
333 </span>
334 <span className="text-muted-foreground">{compactTokens}</span>
335 </TooltipTrigger>
336 <TooltipPopup>
337 <div>
338 {keepFullHistory
339 ? `Next send keeps all ${compactTokens} tokens.`
340 : `Next send compacts ${compactTokens} tokens first.`}
341 </div>
342 <div>{keepFullHistory ? "Click to compact first" : "Click to keep full history"}</div>
343 </TooltipPopup>
344 </Tooltip>
345 {children}
346 {submit}
347 </div>
348 );
349});