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

ComposerPrimaryActions.tsx

398 lines14.8 KB

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