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 items-center justify-between gap-3">
332 <span className="min-w-0 truncate">
333 {option.label}
334 {option.isDefault ? (
335 <>
336 {" "}
337 <DefaultBadge />
338 </>
339 ) : null}
340 </span>
341 </span>
342 </MenuRadioItem>
343 ))}
344 </MenuRadioGroup>
345 </MenuGroup>
346 </div>
347 );
348 })}
349 {booleanDescriptors.map((descriptor, index) => {
350 const selectedValue = descriptor.currentValue === true ? "on" : "off";
351
352 return (
353 <div key={descriptor.id}>
354 {index > 0 || selectDescriptors.length > 0 ? <MenuDivider /> : null}
355 <MenuGroup>
356 <div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">
357 {descriptor.label}
358 </div>
359 <MenuRadioGroup
360 value={selectedValue}
361 onValueChange={(value) => {
362 updateDescriptors(
363 replaceDescriptorCurrentValue(descriptors, descriptor.id, value === "on"),
364 );
365 }}
366 >
367 {(["on", "off"] as const).map((value) => (
368 <MenuRadioItem key={value} value={value} hideIndicator closeOnClick>
369 <span className="flex w-full min-w-0 items-center justify-between gap-3">
370 <span>{value === "on" ? "On" : "Off"}</span>
371 </span>
372 </MenuRadioItem>
373 ))}
374 </MenuRadioGroup>
375 </MenuGroup>
376 </div>
377 );
378 })}
379 </>
380 );
381});
382
383/**
384 * Build the traits trigger's text label plus whether the fast-mode bolt should
385 * render. Fast mode is a lightning bolt when on and nothing at all when off —
386 * "Normal" is the near-universal case and isn't worth the horizontal space. The
387 * one exception is when fast mode is the only trait, where a bare bolt (or bare
388 * chevron) would leave the trigger unreadable.
389 */
390export function buildTraitsTriggerDisplay(input: {
391 provider: ProviderDriverKind;
392 descriptors: ReadonlyArray<ProviderOptionDescriptor>;
393 primarySelectDescriptorId: string | null;
394 ultrathinkPromptControlled: boolean;
395}): { label: string; showFastModeIcon: boolean } {
396 let hasFastMode = false;
397 let fastModeEnabled = false;
398 const labels: Array<string> = [];
399 for (const descriptor of input.descriptors) {
400 if (descriptor.id === "fastMode" && descriptor.type === "boolean") {
401 hasFastMode = true;
402 fastModeEnabled = descriptor.currentValue === true;
403 continue;
404 }
405 if (
406 input.provider === "codex" &&
407 descriptor.id === "serviceTier" &&
408 descriptor.type === "select"
409 ) {
410 const currentValue = getProviderOptionCurrentValue(descriptor);
411 const fastTier = descriptor.options.find(({ label }) => label === "Fast");
412 if (fastTier && (currentValue === "default" || currentValue === fastTier.id)) {
413 hasFastMode = true;
414 fastModeEnabled = currentValue === fastTier.id;
415 continue;
416 }
417 }
418 const label =
419 input.ultrathinkPromptControlled && descriptor.id === input.primarySelectDescriptorId
420 ? "Ultrathink"
421 : descriptor.type === "boolean"
422 ? `${descriptor.label} ${descriptor.currentValue === true ? "On" : "Off"}`
423 : getProviderOptionCurrentLabel(descriptor);
424 if (typeof label === "string" && label.length > 0) {
425 labels.push(label);
426 }
427 }
428
429 // Only fall back to text when fast mode is genuinely the sole trait. Keying
430 // off an empty label list alone would also catch descriptors that resolved to
431 // no label at all, printing a bogus "Normal" for a model without fast mode.
432 if (labels.length === 0 && hasFastMode) {
433 return { label: fastModeEnabled ? "Fast" : "Normal", showFastModeIcon: false };
434 }
435 return { label: labels.join(" · "), showFastModeIcon: fastModeEnabled };
436}
437
438export const TraitsPicker = memo(function TraitsPicker({
439 provider,
440 instanceId,
441 models,
442 model,
443 prompt,
444 onPromptChange,
445 modelOptions,
446 allowPromptInjectedEffort = true,
447 triggerVariant,
448 triggerClassName,
449 ...persistence
450}: TraitsMenuContentProps & TraitsPersistence) {
451 const [isMenuOpen, setIsMenuOpen] = useState(false);
452 const { descriptors, primarySelectDescriptor, ultrathinkPromptControlled } =
453 getTraitsSectionVisibility({
454 provider,
455 models,
456 model,
457 prompt,
458 modelOptions,
459 allowPromptInjectedEffort,
460 });
461 if (
462 !shouldRenderTraitsControls({
463 provider,
464 models,
465 model,
466 prompt,
467 modelOptions,
468 allowPromptInjectedEffort,
469 })
470 ) {
471 return null;
472 }
473
474 const { label: triggerLabel, showFastModeIcon } = buildTraitsTriggerDisplay({
475 provider,
476 descriptors,
477 primarySelectDescriptorId: primarySelectDescriptor?.id ?? null,
478 ultrathinkPromptControlled,
479 });
480 const fastModeIcon = showFastModeIcon ? (
481 <>
482 <ComposerControlIcon
483 icon={ZapIcon}
484 className={cn(
485 "fill-current opacity-80",
486 provider === "claudeAgent" ? "text-[#d97757]" : "text-foreground",
487 )}
488 />
489 <span className="sr-only">Fast mode on</span>
490 </>
491 ) : null;
492
493 const isCodexStyle = provider === "codex";
494
495 return (
496 <Menu
497 open={isMenuOpen}
498 onOpenChange={(open) => {
499 setIsMenuOpen(open);
500 }}
501 >
502 <MenuTrigger
503 render={
504 <ComposerControl
505 variant={triggerVariant ?? "ghost"}
506 className={cn(
507 isCodexStyle
508 ? "min-w-0 max-w-40 shrink justify-start overflow-hidden whitespace-nowrap sm:max-w-48"
509 : "shrink-0 whitespace-nowrap",
510 triggerClassName,
511 )}
512 />
513 }
514 >
515 {isCodexStyle ? (
516 <span className="flex min-w-0 w-full items-center gap-1.5 overflow-hidden">
517 {fastModeIcon}
518 <span className="min-w-0 truncate">{triggerLabel}</span>
519 <ComposerControlChevron />
520 </span>
521 ) : (
522 <>
523 {fastModeIcon}
524 <span>{triggerLabel}</span>
525 <ComposerControlChevron />
526 </>
527 )}
528 </MenuTrigger>
529 <MenuPopup align="start">
530 <TraitsMenuContent
531 provider={provider}
532 {...(instanceId ? { instanceId } : {})}
533 models={models}
534 model={model}
535 prompt={prompt}
536 onPromptChange={onPromptChange}
537 modelOptions={modelOptions}
538 allowPromptInjectedEffort={allowPromptInjectedEffort}
539 {...persistence}
540 />
541 </MenuPopup>
542 </Menu>
543 );
544});