Open History to see the last commit
1import {
2 type ProviderDriverKind,
3 type ProviderInstanceId,
4 type ProviderOptionDescriptor,
5 type ProviderOptionSelection,
6 type ScopedThreadRef,
7 type ServerProviderModel,
8} from "@t3tools/contracts";
9import {
10 applyClaudePromptEffortPrefix,
11 buildProviderOptionSelectionsFromDescriptors,
12 getProviderOptionCurrentLabel,
13 getProviderOptionCurrentValue,
14 getProviderOptionDescriptors,
15 isClaudeUltrathinkPrompt,
16} from "@t3tools/shared/model";
17import { memo, useCallback, useState } from "react";
18import type { VariantProps } from "class-variance-authority";
19import { ZapIcon } from "lucide-react";
20import { buttonVariants } from "../ui/button";
21import {
22 Menu,
23 MenuGroup,
24 MenuPopup,
25 MenuRadioGroup,
26 MenuRadioItem,
27 MenuSeparator as MenuDivider,
28 MenuTrigger,
29} from "../ui/menu";
30import { useComposerDraftStore, DraftId } from "../../composerDraftStore";
31import { getProviderModelCapabilities } from "../../providerModels";
32import { cn } from "~/lib/utils";
33import { Badge } from "../ui/badge";
34import { ComposerControl, ComposerControlChevron, ComposerControlIcon } from "./ComposerControl";
35
36type ProviderOptions = ReadonlyArray<ProviderOptionSelection>;
37
38type TraitsPersistence =
39 | {
40 threadRef?: ScopedThreadRef;
41 draftId?: DraftId;
42 onModelOptionsChange?: never;
43 }
44 | {
45 threadRef?: undefined;
46 onModelOptionsChange: (nextOptions: ProviderOptions | undefined) => void;
47 };
48
49const ULTRATHINK_PROMPT_PREFIX = "Ultrathink:\n";
50
51function DefaultBadge() {
52 return (
53 <Badge
54 variant="outline"
55 className="inline-flex h-4 w-fit min-w-0 items-center justify-center gap-0 border-border/70 bg-muted/60 px-1.5 py-0 font-semibold text-[10px] text-muted-foreground leading-none sm:h-4"
56 >
57 Default
58 </Badge>
59 );
60}
61
62function replaceDescriptorCurrentValue(
63 descriptors: ReadonlyArray<ProviderOptionDescriptor>,
64 descriptorId: string,
65 currentValue: string | boolean | undefined,
66): ReadonlyArray<ProviderOptionDescriptor> {
67 return descriptors.map((descriptor) =>
68 descriptor.id !== descriptorId
69 ? descriptor
70 : descriptor.type === "boolean"
71 ? {
72 ...descriptor,
73 ...(typeof currentValue === "boolean" ? { currentValue } : {}),
74 }
75 : {
76 ...descriptor,
77 ...(typeof currentValue === "string" ? { currentValue } : {}),
78 },
79 );
80}
81
82function getDescriptorStringValue(
83 descriptor: Extract<ProviderOptionDescriptor, { type: "select" }> | null,
84): string | null {
85 if (!descriptor) {
86 return null;
87 }
88 const value = getProviderOptionCurrentValue(descriptor);
89 return typeof value === "string" ? value : null;
90}
91
92function getSelectedTraits(
93 provider: ProviderDriverKind,
94 models: ReadonlyArray<ServerProviderModel>,
95 model: string | null | undefined,
96 prompt: string,
97 modelOptions: ProviderOptions | null | undefined,
98 allowPromptInjectedEffort: boolean,
99) {
100 const caps = getProviderModelCapabilities(models, model, provider);
101 const descriptors = getProviderOptionDescriptors({
102 caps,
103 selections: modelOptions,
104 });
105 const selectDescriptors = descriptors.filter(
106 (descriptor): descriptor is Extract<ProviderOptionDescriptor, { type: "select" }> =>
107 descriptor.type === "select",
108 );
109 const booleanDescriptors = descriptors.filter(
110 (descriptor): descriptor is Extract<ProviderOptionDescriptor, { type: "boolean" }> =>
111 descriptor.type === "boolean",
112 );
113 const primarySelectDescriptor = selectDescriptors[0] ?? null;
114 const contextWindowDescriptor =
115 selectDescriptors.find((descriptor) => descriptor.id === "contextWindow") ?? null;
116 const agentDescriptor = selectDescriptors.find((descriptor) => descriptor.id === "agent") ?? null;
117 const fastModeDescriptor =
118 booleanDescriptors.find((descriptor) => descriptor.id === "fastMode") ?? null;
119 const thinkingDescriptor =
120 booleanDescriptors.find((descriptor) => descriptor.id === "thinking") ?? null;
121
122 // Prompt-controlled effort (e.g. ultrathink in prompt text)
123 const ultrathinkPromptControlled =
124 allowPromptInjectedEffort &&
125 (primarySelectDescriptor?.promptInjectedValues?.length ?? 0) > 0 &&
126 isClaudeUltrathinkPrompt(prompt);
127
128 // Check if "ultrathink" appears in the body text (not just our prefix)
129 const ultrathinkInBodyText =
130 ultrathinkPromptControlled && isClaudeUltrathinkPrompt(prompt.replace(/^Ultrathink:\s*/i, ""));
131 const effort =
132 (ultrathinkPromptControlled
133 ? "ultrathink"
134 : getDescriptorStringValue(primarySelectDescriptor)) ?? null;
135 const thinkingEnabled =
136 typeof thinkingDescriptor?.currentValue === "boolean" ? thinkingDescriptor.currentValue : null;
137 const contextWindow = getDescriptorStringValue(contextWindowDescriptor);
138 const selectedAgent = getDescriptorStringValue(agentDescriptor);
139 const selectedAgentLabel = agentDescriptor
140 ? getProviderOptionCurrentLabel(agentDescriptor)
141 : null;
142
143 return {
144 caps,
145 descriptors,
146 selectDescriptors,
147 booleanDescriptors,
148 primarySelectDescriptor,
149 contextWindowDescriptor,
150 agentDescriptor,
151 fastModeDescriptor,
152 thinkingDescriptor,
153 effort,
154 thinkingEnabled,
155 contextWindow,
156 ultrathinkPromptControlled,
157 ultrathinkInBodyText,
158 selectedAgent,
159 selectedAgentLabel,
160 };
161}
162
163function getTraitsSectionVisibility(input: {
164 provider: ProviderDriverKind;
165 models: ReadonlyArray<ServerProviderModel>;
166 model: string | null | undefined;
167 prompt: string;
168 modelOptions: ProviderOptions | null | undefined;
169 allowPromptInjectedEffort?: boolean;
170}) {
171 const selected = getSelectedTraits(
172 input.provider,
173 input.models,
174 input.model,
175 input.prompt,
176 input.modelOptions,
177 input.allowPromptInjectedEffort ?? true,
178 );
179
180 const showEffort = selected.primarySelectDescriptor !== null;
181 const showThinking = selected.thinkingDescriptor !== null;
182 const showFastMode = selected.fastModeDescriptor !== null;
183 const showContextWindow = selected.contextWindowDescriptor !== null;
184 const showAgent = selected.agentDescriptor !== null;
185
186 return {
187 ...selected,
188 showEffort,
189 showThinking,
190 showFastMode,
191 showContextWindow,
192 showAgent,
193 hasAnyControls: showEffort || showThinking || showFastMode || showContextWindow || showAgent,
194 };
195}
196
197export function shouldRenderTraitsControls(input: {
198 provider: ProviderDriverKind;
199 models: ReadonlyArray<ServerProviderModel>;
200 model: string | null | undefined;
201 prompt: string;
202 modelOptions: ProviderOptions | null | undefined;
203 allowPromptInjectedEffort?: boolean;
204}): boolean {
205 return getTraitsSectionVisibility(input).hasAnyControls;
206}
207
208export interface TraitsMenuContentProps {
209 provider: ProviderDriverKind;
210 instanceId?: ProviderInstanceId;
211 models: ReadonlyArray<ServerProviderModel>;
212 model: string | null | undefined;
213 prompt: string;
214 onPromptChange: (prompt: string) => void;
215 modelOptions?: ProviderOptions | null | undefined;
216 allowPromptInjectedEffort?: boolean;
217 triggerVariant?: VariantProps<typeof buttonVariants>["variant"];
218 triggerClassName?: string;
219}
220
221export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
222 provider,
223 instanceId,
224 models,
225 model,
226 prompt,
227 onPromptChange,
228 modelOptions,
229 allowPromptInjectedEffort = true,
230 ...persistence
231}: TraitsMenuContentProps & TraitsPersistence) {
232 const setProviderModelOptions = useComposerDraftStore((store) => store.setProviderModelOptions);
233 const updateModelOptions = useCallback(
234 (nextOptions: ProviderOptions | undefined) => {
235 if ("onModelOptionsChange" in persistence) {
236 persistence.onModelOptionsChange(nextOptions);
237 return;
238 }
239 const threadTarget = persistence.threadRef ?? persistence.draftId;
240 if (!threadTarget) {
241 return;
242 }
243 setProviderModelOptions(threadTarget, provider, nextOptions, {
244 ...(instanceId ? { instanceId } : {}),
245 model,
246 persistSticky: true,
247 });
248 },
249 [instanceId, model, persistence, provider, setProviderModelOptions],
250 );
251 const {
252 descriptors,
253 selectDescriptors,
254 booleanDescriptors,
255 primarySelectDescriptor,
256 ultrathinkPromptControlled,
257 ultrathinkInBodyText,
258 hasAnyControls,
259 } = getTraitsSectionVisibility({
260 provider,
261 models,
262 model,
263 prompt,
264 modelOptions,
265 allowPromptInjectedEffort,
266 });
267 const updateDescriptors = (nextDescriptors: ReadonlyArray<ProviderOptionDescriptor>) => {
268 updateModelOptions(buildProviderOptionSelectionsFromDescriptors(nextDescriptors));
269 };
270
271 const handleSelectChange = (
272 descriptor: Extract<ProviderOptionDescriptor, { type: "select" }>,
273 value: string,
274 ) => {
275 if (!value) return;
276 if (descriptor.promptInjectedValues?.includes(value)) {
277 const nextPrompt =
278 prompt.trim().length === 0
279 ? ULTRATHINK_PROMPT_PREFIX
280 : applyClaudePromptEffortPrefix(prompt, "ultrathink");
281 onPromptChange(nextPrompt);
282 return;
283 }
284 if (ultrathinkInBodyText && descriptor.id === primarySelectDescriptor?.id) return;
285 if (ultrathinkPromptControlled && descriptor.id === primarySelectDescriptor?.id) {
286 const stripped = prompt.replace(/^Ultrathink:\s*/i, "");
287 onPromptChange(stripped);
288 }
289 updateDescriptors(replaceDescriptorCurrentValue(descriptors, descriptor.id, value));
290 };
291
292 if (!hasAnyControls) {
293 return null;
294 }
295
296 return (
297 <>
298 {selectDescriptors.map((descriptor, index) => {
299 const selectedValue =
300 ultrathinkPromptControlled && descriptor.id === primarySelectDescriptor?.id
301 ? "ultrathink"
302 : (getDescriptorStringValue(descriptor) ?? "");
303
304 return (
305 <div key={descriptor.id}>
306 {index > 0 ? <MenuDivider /> : null}
307 <MenuGroup>
308 <div className="px-2 pt-1.5 pb-1 font-medium text-muted-foreground text-xs">
309 {descriptor.label}
310 </div>
311 {ultrathinkInBodyText && descriptor.id === primarySelectDescriptor?.id ? (
312 <div className="px-2 pb-1.5 text-muted-foreground/80 text-xs">
313 Your prompt contains "ultrathink" in the text. Remove it to change this
314 option.
315 </div>
316 ) : null}
317 <MenuRadioGroup
318 value={selectedValue}
319 onValueChange={(value) => handleSelectChange(descriptor, value)}
320 >
321 {descriptor.options.map((option) => (
322 <MenuRadioItem
323 key={option.id}
324 value={option.id}
325 hideIndicator
326 // Base UI keeps radio menus open by default. Close on pick so
327 // the traits menu behaves like the model picker.
328 closeOnClick
329 disabled={ultrathinkInBodyText && descriptor.id === primarySelectDescriptor?.id}
330 >
331 <span className="flex w-full min-w-0 flex-col">
332 <span className="flex w-full min-w-0 items-center justify-between gap-3">
333 <span className="min-w-0 truncate">
334 {option.label}
335 {option.isDefault ? (
336 <>
337 {" "}
338 <DefaultBadge />
339 </>
340 ) : null}
341 </span>
342 </span>
343 {option.description ? (
344 <span className="max-w-56 text-pretty text-muted-foreground/80 text-xs">
345 {option.description}
346 </span>
347 ) : null}
348 </span>
349 </MenuRadioItem>
350 ))}
351 </MenuRadioGroup>
352 </MenuGroup>
353 </div>
354 );
355 })}
356 {booleanDescriptors.map((descriptor, index) => {
357 const selectedValue = descriptor.currentValue === true ? "on" : "off";
358
359 return (
360 <div key={descriptor.id}>
361 {index > 0 || selectDescriptors.length > 0 ? <MenuDivider /> : null}
362 <MenuGroup>
363 <div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">
364 {descriptor.label}
365 </div>
366 <MenuRadioGroup
367 value={selectedValue}
368 onValueChange={(value) => {
369 updateDescriptors(
370 replaceDescriptorCurrentValue(descriptors, descriptor.id, value === "on"),
371 );
372 }}
373 >
374 {(["on", "off"] as const).map((value) => (
375 <MenuRadioItem key={value} value={value} hideIndicator closeOnClick>
376 <span className="flex w-full min-w-0 items-center justify-between gap-3">
377 <span>{value === "on" ? "On" : "Off"}</span>
378 </span>
379 </MenuRadioItem>
380 ))}
381 </MenuRadioGroup>
382 </MenuGroup>
383 </div>
384 );
385 })}
386 </>
387 );
388});
389
390/**
391 * Build the traits trigger's text label plus whether the fast-mode bolt should
392 * render. Fast mode is a lightning bolt when on and nothing at all when off —
393 * "Normal" is the near-universal case and isn't worth the horizontal space. The
394 * one exception is when fast mode is the only trait, where a bare bolt (or bare
395 * chevron) would leave the trigger unreadable.
396 */
397export function buildTraitsTriggerDisplay(input: {
398 provider: ProviderDriverKind;
399 descriptors: ReadonlyArray<ProviderOptionDescriptor>;
400 primarySelectDescriptorId: string | null;
401 ultrathinkPromptControlled: boolean;
402}): { label: string; showFastModeIcon: boolean } {
403 let hasFastMode = false;
404 let fastModeEnabled = false;
405 const labels: Array<string> = [];
406 for (const descriptor of input.descriptors) {
407 if (descriptor.id === "fastMode" && descriptor.type === "boolean") {
408 hasFastMode = true;
409 fastModeEnabled = descriptor.currentValue === true;
410 continue;
411 }
412 if (
413 input.provider === "codex" &&
414 descriptor.id === "serviceTier" &&
415 descriptor.type === "select"
416 ) {
417 const currentValue = getProviderOptionCurrentValue(descriptor);
418 const fastTier = descriptor.options.find(({ label }) => label === "Fast");
419 if (fastTier && (currentValue === "default" || currentValue === fastTier.id)) {
420 hasFastMode = true;
421 fastModeEnabled = currentValue === fastTier.id;
422 continue;
423 }
424 }
425 const label =
426 input.ultrathinkPromptControlled && descriptor.id === input.primarySelectDescriptorId
427 ? "Ultrathink"
428 : descriptor.type === "boolean"
429 ? `${descriptor.label} ${descriptor.currentValue === true ? "On" : "Off"}`
430 : getProviderOptionCurrentLabel(descriptor);
431 if (typeof label === "string" && label.length > 0) {
432 labels.push(label);
433 }
434 }
435
436 // Only fall back to text when fast mode is genuinely the sole trait. Keying
437 // off an empty label list alone would also catch descriptors that resolved to
438 // no label at all, printing a bogus "Normal" for a model without fast mode.
439 if (labels.length === 0 && hasFastMode) {
440 return { label: fastModeEnabled ? "Fast" : "Normal", showFastModeIcon: false };
441 }
442 return { label: labels.join(" · "), showFastModeIcon: fastModeEnabled };
443}
444
445export const TraitsPicker = memo(function TraitsPicker({
446 provider,
447 instanceId,
448 models,
449 model,
450 prompt,
451 onPromptChange,
452 modelOptions,
453 allowPromptInjectedEffort = true,
454 triggerVariant,
455 triggerClassName,
456 ...persistence
457}: TraitsMenuContentProps & TraitsPersistence) {
458 const [isMenuOpen, setIsMenuOpen] = useState(false);
459 const { descriptors, primarySelectDescriptor, ultrathinkPromptControlled } =
460 getTraitsSectionVisibility({
461 provider,
462 models,
463 model,
464 prompt,
465 modelOptions,
466 allowPromptInjectedEffort,
467 });
468 if (
469 !shouldRenderTraitsControls({
470 provider,
471 models,
472 model,
473 prompt,
474 modelOptions,
475 allowPromptInjectedEffort,
476 })
477 ) {
478 return null;
479 }
480
481 const { label: triggerLabel, showFastModeIcon } = buildTraitsTriggerDisplay({
482 provider,
483 descriptors,
484 primarySelectDescriptorId: primarySelectDescriptor?.id ?? null,
485 ultrathinkPromptControlled,
486 });
487 const fastModeIcon = showFastModeIcon ? (
488 <>
489 <ComposerControlIcon
490 icon={ZapIcon}
491 className={cn(
492 "fill-current opacity-80",
493 provider === "claudeAgent" ? "text-[#d97757]" : "text-foreground",
494 )}
495 />
496 <span className="sr-only">Fast mode on</span>
497 </>
498 ) : null;
499
500 const isCodexStyle = provider === "codex";
501
502 return (
503 <Menu
504 open={isMenuOpen}
505 onOpenChange={(open) => {
506 setIsMenuOpen(open);
507 }}
508 >
509 <MenuTrigger
510 render={
511 <ComposerControl
512 variant={triggerVariant ?? "ghost"}
513 className={cn(
514 isCodexStyle
515 ? "min-w-0 max-w-40 shrink justify-start overflow-hidden whitespace-nowrap sm:max-w-48"
516 : "shrink-0 whitespace-nowrap",
517 triggerClassName,
518 )}
519 />
520 }
521 >
522 {isCodexStyle ? (
523 <span className="flex min-w-0 w-full items-center gap-1.5 overflow-hidden">
524 {fastModeIcon}
525 <span className="min-w-0 truncate">{triggerLabel}</span>
526 <ComposerControlChevron />
527 </span>
528 ) : (
529 <>
530 {fastModeIcon}
531 <span>{triggerLabel}</span>
532 <ComposerControlChevron />
533 </>
534 )}
535 </MenuTrigger>
536 <MenuPopup align="start">
537 <TraitsMenuContent
538 provider={provider}
539 {...(instanceId ? { instanceId } : {})}
540 models={models}
541 model={model}
542 prompt={prompt}
543 onPromptChange={onPromptChange}
544 modelOptions={modelOptions}
545 allowPromptInjectedEffort={allowPromptInjectedEffort}
546 {...persistence}
547 />
548 </MenuPopup>
549 </Menu>
550 );
551});