Open History to see the last commit
1import {
2 buildTraitsTriggerDisplay,
3 getDescriptorStringValue,
4 isReasoningControl,
5 selectableProviderOptionChoices,
6} from "@t3tools/client-runtime/model-traits";
7import type { ProviderOptionDescriptor, RuntimeMode } from "@t3tools/contracts";
8import type { EffortDisplay } from "@t3tools/contracts/settings";
9import { getProviderOptionCurrentLabel } from "@t3tools/shared/model";
10import { msg, T, useGT, useMessages } from "gt-react";
11import { CheckIcon, ChevronRightIcon, ChevronUpIcon, WorkflowIcon } from "lucide-react";
12import { type KeyboardEvent, type ReactNode, use, useRef, useState } from "react";
13
14import { m, type MessageResolver } from "~/i18n/messages";
15import { cn } from "~/lib/utils";
16import {
17 Menu,
18 MenuPopup,
19 MenuRadioGroup,
20 MenuRadioItem,
21 MenuRadioItemIndicator,
22 MenuTrigger,
23} from "../ui/menu";
24import { Switch } from "../ui/switch";
25import type { ComposerControlSize } from "./ComposerControl";
26import { ComposerPermissionsSection, type RuntimeModeOption } from "./ComposerFooterControls";
27import { composerFloatingLayerProps, focusCheckedPermission } from "./composerEventScope";
28import { EffortGlyph, FastBolt, resolveEffortGlyph } from "./EffortGlyph";
29import { DockedPickerContext } from "./ProviderModelPicker";
30import {
31 getTraitsSectionVisibility,
32 type TraitsSelectionInput,
33 ULTRATHINK_IN_BODY_NOTE,
34 useTraitsSelection,
35} from "./TraitsPicker";
36import { SharedTooltipTrigger } from "../ui/shared-tooltip";
37
38type SelectDescriptor = Extract<ProviderOptionDescriptor, { type: "select" }>;
39type BooleanDescriptor = Extract<ProviderOptionDescriptor, { type: "boolean" }>;
40
41/** Service tiers, Claude's Fast mode, and Ultracode sit in the footer, not the column. */
42function splitSpeed(
43 selects: ReadonlyArray<SelectDescriptor>,
44 toggles: ReadonlyArray<BooleanDescriptor>,
45) {
46 const speedSelect = selects.find((descriptor) => descriptor.id === "serviceTier") ?? null;
47 const fastToggle = toggles.find((descriptor) => descriptor.id === "fastMode") ?? null;
48 const ultracodeToggle = toggles.find((descriptor) => descriptor.id === "ultracode") ?? null;
49 return {
50 speedSelect,
51 fastToggle,
52 ultracodeToggle,
53 columnSelects: selects.filter((descriptor) => descriptor !== speedSelect),
54 columnToggles: toggles.filter(
55 (descriptor) => descriptor !== fastToggle && descriptor !== ultracodeToggle,
56 ),
57 };
58}
59
60type ColumnControl =
61 | { kind: "select"; descriptor: SelectDescriptor }
62 | { kind: "boolean"; descriptor: BooleanDescriptor };
63
64/**
65 * The column lists the model's reasoning levels under the header that names it. Other options,
66 * such as an agent's session mode, sit below as one row each.
67 */
68function columnControls(
69 selects: ReadonlyArray<SelectDescriptor>,
70 toggles: ReadonlyArray<BooleanDescriptor>,
71) {
72 const { columnSelects, columnToggles } = splitSpeed(selects, toggles);
73 const controls: ReadonlyArray<ColumnControl> = [
74 ...columnSelects.map((descriptor) => ({ kind: "select" as const, descriptor })),
75 ...columnToggles.map((descriptor) => ({ kind: "boolean" as const, descriptor })),
76 ];
77 const effort = controls.find((control) => isReasoningControl(control.descriptor)) ?? null;
78 return { effort, others: controls.filter((control) => control !== effort) };
79}
80
81/**
82 * What the model trigger shows after the model name: the effort word (or bars, per the
83 * Appearance setting), a bolt for Fast, a workflow icon for Ultracode, and other traits such as a
84 * context window.
85 */
86export function describeComposerEffort(
87 traits: TraitsSelectionInput | null,
88 effortDisplay: EffortDisplay,
89 size: ComposerControlSize,
90 resolve: MessageResolver = m,
91): { suffix: ReactNode; detail: string | null } {
92 if (!traits) return { suffix: null, detail: null };
93 const visibility = getTraitsSectionVisibility({ ...traits, resolve });
94 if (!visibility.hasAnyControls) return { suffix: null, detail: null };
95 const modelSelection =
96 traits.instanceId && traits.model
97 ? { instanceId: traits.instanceId, model: traits.model, options: traits.modelOptions ?? [] }
98 : null;
99 const primary = visibility.primarySelectDescriptor;
100 const display = buildTraitsTriggerDisplay(
101 {
102 descriptors: visibility.descriptors,
103 primarySelectDescriptorId: primary?.id ?? null,
104 ultrathinkPromptControlled: visibility.ultrathinkPromptControlled,
105 modelSelection,
106 reportedModelSelection: traits.reportedModelSelection,
107 },
108 resolve,
109 );
110 // The same reasoning control the column lists, wherever the agent put it among its options.
111 const reasoning =
112 columnControls(visibility.selectDescriptors, visibility.booleanDescriptors).effort
113 ?.descriptor ?? null;
114 const ultrathink = visibility.ultrathinkPromptControlled && reasoning === primary;
115 const glyph =
116 reasoning?.type === "select"
117 ? resolveEffortGlyph(
118 reasoning,
119 ultrathink
120 ? "ultrathink"
121 : getDescriptorStringValue(reasoning, modelSelection, traits.reportedModelSelection),
122 )
123 : null;
124 // Workflow levels such as Ultracode always show their name; the setting names every level.
125 const word = glyph
126 ? (glyph.special ?? (effortDisplay === "label" ? glyph.label : null))
127 : !reasoning
128 ? null
129 : reasoning.type === "boolean"
130 ? reasoning.currentValue === true
131 ? resolve(msg`${{ option: reasoning.label }} On`)
132 : resolve(msg`${{ option: reasoning.label }} Off`)
133 : ultrathink
134 ? "Ultrathink"
135 : (getProviderOptionCurrentLabel(
136 reasoning,
137 modelSelection,
138 traits.reportedModelSelection,
139 ) ?? (reasoning.id === "thinking" ? reasoning.label : null));
140 const fast = display.speedLabel === "Fast" || display.speedLabel === "Ultrafast";
141 // Agent options such as modes live in the picker; the trigger adds only the context window.
142 const contextWindow =
143 visibility.contextWindowDescriptor &&
144 getProviderOptionCurrentLabel(
145 visibility.contextWindowDescriptor,
146 modelSelection,
147 traits.reportedModelSelection,
148 );
149 if (!word && !glyph && !fast && !display.ultracode && !contextWindow)
150 return { suffix: null, detail: display.label };
151 return {
152 detail: display.label,
153 suffix: (
154 <span
155 className={cn(
156 "flex shrink-0 items-center gap-1.5 text-muted-foreground group-hover/model-trigger:text-foreground group-data-pressed/model-trigger:text-foreground group-data-popup-open/model-trigger:text-foreground",
157 // A word space after the model name: the regular trigger's gap is wider than one.
158 size === "sm" && "-ms-0.5",
159 )}
160 >
161 {word ? (
162 <span data-composer-control-label className="max-w-24 truncate">
163 {word}
164 </span>
165 ) : glyph ? (
166 <EffortGlyph count={glyph.count} filled={glyph.filled} size={size} />
167 ) : null}
168 {fast ? <FastBolt ultra={display.speedLabel === "Ultrafast"} /> : null}
169 {display.ultracode ? (
170 <WorkflowIcon aria-hidden="true" data-composer-control-icon className="size-3" />
171 ) : null}
172 {contextWindow ? (
173 <span
174 // A label, so icon-only footers drop it; compacted rows drop it before the model.
175 data-composer-control-label
176 data-composer-secondary-trait
177 className="max-w-24 truncate text-xs"
178 >
179 {contextWindow}
180 </span>
181 ) : null}
182 </span>
183 ),
184 };
185}
186
187const COLUMN_ROW =
188 "flex h-8 w-full shrink-0 cursor-pointer items-center gap-2 rounded-sm px-2 text-left text-sm text-foreground outline-none hover:bg-foreground/[0.09] focus-visible:bg-foreground/[0.09] disabled:cursor-not-allowed disabled:opacity-64";
189const COLUMN_LABEL = "px-2 pt-1.5 pb-1 font-medium text-muted-foreground text-xs";
190
191function ColumnRow(props: {
192 label: string;
193 /** Shown on hover; the column is too narrow to print it under the label. */
194 description?: string | undefined;
195 selected: boolean;
196 /** The column's one tab stop: the selected level, else the first when none shows as selected. */
197 tabStop: boolean;
198 isDefault?: boolean | undefined;
199 disabled?: boolean;
200 onPick: () => void;
201}) {
202 const gt = useGT();
203 const rowProps = {
204 type: "button",
205 role: "radio",
206 "aria-checked": props.selected,
207 disabled: props.disabled,
208 "data-effort-row": true,
209 // Focus lands on a level after a model pick, and a typed letter finds one by its label.
210 "data-effort-level": props.label,
211 // Up and Down move between rows.
212 tabIndex: props.tabStop ? 0 : -1,
213 className: COLUMN_ROW,
214 onClick: props.onPick,
215 } as const;
216 const content = (
217 <>
218 <span className="min-w-0 flex-1 truncate">{props.label}</span>
219 {props.selected ? (
220 <>
221 {props.isDefault ? (
222 <span className="sr-only">{gt({ context: "marks the default option" })`Default`}</span>
223 ) : null}
224 <CheckIcon aria-hidden="true" className="size-3.5" />
225 </>
226 ) : props.isDefault ? (
227 <span className="text-muted-foreground/70 text-xs">
228 {gt({ context: "marks the default option" })`Default`}
229 </span>
230 ) : null}
231 </>
232 );
233 if (!props.description) return <button {...rowProps}>{content}</button>;
234 return (
235 <SharedTooltipTrigger
236 render={<button {...rowProps} />}
237 label={props.description}
238 side="right"
239 className="max-w-56"
240 >
241 {content}
242 </SharedTooltipTrigger>
243 );
244}
245
246function moveBetweenRows(event: KeyboardEvent<HTMLElement>) {
247 const arrow = event.key === "ArrowDown" || event.key === "ArrowUp";
248 if (
249 !arrow &&
250 (event.key.length !== 1 ||
251 event.key.trim() === "" ||
252 event.ctrlKey ||
253 event.altKey ||
254 event.metaKey ||
255 event.nativeEvent.isComposing)
256 )
257 return;
258 // An option's side menu is a React child here, but it moves through its own items.
259 if (!event.currentTarget.contains(event.target as Node)) return;
260 const rows = Array.from(
261 event.currentTarget.querySelectorAll<HTMLButtonElement>("[data-effort-row]:not(:disabled)"),
262 );
263 const index = rows.findIndex((row) => row === document.activeElement);
264 const next = arrow
265 ? rows[Math.min(rows.length - 1, Math.max(0, index + (event.key === "ArrowDown" ? 1 : -1)))]
266 : [...rows.slice(index + 1), ...rows.slice(0, index + 1)].find((row) =>
267 row.dataset.effortLevel?.toLowerCase().startsWith(event.key.toLowerCase()),
268 );
269 if (!next) return;
270 event.preventDefault();
271 event.stopPropagation();
272 next.focus();
273 next.scrollIntoView({ block: "nearest" });
274}
275
276function EffortLevels(props: { traits: TraitsSelectionInput }) {
277 const traits = useTraitsSelection(props.traits);
278 const { effort, others } = columnControls(traits.selectDescriptors, traits.booleanDescriptors);
279 if (traits.modelIsUnavailable) {
280 return (
281 <>
282 {traits.descriptors.map((descriptor) => {
283 const value = traits.currentLabel(descriptor);
284 return value ? (
285 <div key={descriptor.id}>
286 <div className={COLUMN_LABEL}>{descriptor.label}</div>
287 <div className="px-2 pb-1.5 text-muted-foreground/80 text-xs">{value}</div>
288 </div>
289 ) : null;
290 })}
291 </>
292 );
293 }
294 if (!effort && others.length === 0) return <NoEffortRow />;
295 // Ultrathink in the prompt locks the levels; the first option then holds the tab stop.
296 const locked =
297 effort?.descriptor.id === traits.primarySelectDescriptor?.id && traits.ultrathinkInBodyText;
298 return (
299 <>
300 {effort ? <EffortRows control={effort} traits={traits} locked={locked} /> : null}
301 {others.length > 0 ? (
302 <div
303 className={cn("flex flex-col gap-0.5", effort && "mt-1 border-t border-border/70 pt-1")}
304 >
305 {others.map((control, index) =>
306 control.kind === "boolean" ? (
307 <OptionSwitchRow
308 key={control.descriptor.id}
309 descriptor={control.descriptor}
310 traits={traits}
311 tabStop={(!effort || locked) && index === 0}
312 />
313 ) : (
314 <OptionMenuRow
315 key={control.descriptor.id}
316 descriptor={control.descriptor}
317 traits={traits}
318 tabStop={(!effort || locked) && index === 0}
319 />
320 ),
321 )}
322 </div>
323 ) : null}
324 </>
325 );
326}
327
328type TraitsSelection = ReturnType<typeof useTraitsSelection>;
329
330function EffortRows(props: { control: ColumnControl; traits: TraitsSelection; locked: boolean }) {
331 const gt = useGT();
332 const messages = useMessages();
333 const { control, traits } = props;
334 const { descriptor } = control;
335 if (control.kind === "boolean") {
336 return (
337 <div role="radiogroup" aria-label={descriptor.label} className="flex flex-col gap-0.5">
338 {([true, false] as const).map((value) => (
339 <ColumnRow
340 key={String(value)}
341 label={
342 value ? gt({ context: "option state" })`On` : gt({ context: "option state" })`Off`
343 }
344 selected={(control.descriptor.currentValue === true) === value}
345 tabStop={(control.descriptor.currentValue === true) === value}
346 onPick={() => traits.changeBoolean(descriptor.id, value)}
347 />
348 ))}
349 </div>
350 );
351 }
352 const { locked } = props;
353 const value = traits.selectValue(control.descriptor);
354 const choices = selectableProviderOptionChoices(control.descriptor);
355 // An "Ultrathink:" prefix selects a level the column does not offer.
356 const shown = choices.some((option) => option.id === value);
357 return (
358 <div role="radiogroup" aria-label={descriptor.label} className="flex flex-col gap-0.5">
359 {locked ? (
360 <div className="px-2 pb-1.5 text-muted-foreground/80 text-xs">
361 {messages(ULTRATHINK_IN_BODY_NOTE)}
362 </div>
363 ) : null}
364 {choices.map((option, index) => (
365 <ColumnRow
366 key={option.id}
367 label={option.label}
368 selected={option.id === value}
369 tabStop={shown ? option.id === value : index === 0}
370 description={option.description}
371 isDefault={option.isDefault}
372 disabled={locked}
373 onPick={() => traits.changeSelect(control.descriptor, option.id)}
374 />
375 ))}
376 </div>
377 );
378}
379
380const OPTION_ROW = cn(COLUMN_ROW, "h-auto py-1");
381
382/** An option's name over its current value. */
383function OptionRowText(props: { label: string; value: string }) {
384 return (
385 <span className="flex min-w-0 flex-1 flex-col">
386 <span className="truncate text-muted-foreground text-xs">{props.label}</span>
387 <span className="truncate">{props.value}</span>
388 </span>
389 );
390}
391
392/**
393 * One select besides reasoning, such as an agent's session mode. It names the current choice and
394 * opens the rest beside the column, so any number of options leaves the levels in place.
395 */
396function OptionMenuRow(props: {
397 descriptor: SelectDescriptor;
398 traits: TraitsSelection;
399 /** Holds the column's tab stop when the model has no levels. */
400 tabStop: boolean;
401}) {
402 const gt = useGT();
403 const { descriptor, traits } = props;
404 const [open, setOpen] = useState(false);
405 const popupRef = useRef<HTMLDivElement>(null);
406 const choices = selectableProviderOptionChoices(descriptor);
407 const value = traits.selectValue(descriptor);
408 const current = choices.find((choice) => choice.id === value)?.label ?? "";
409 return (
410 <Menu
411 open={open}
412 // A modal menu would cover the picker, so the next click there would only close it.
413 modal={false}
414 onOpenChange={setOpen}
415 onOpenChangeComplete={(isOpen) => {
416 if (!isOpen) return;
417 const checked = popupRef.current?.querySelector<HTMLElement>(
418 '[role="menuitemradio"][aria-checked="true"]',
419 );
420 checked?.focus({ preventScroll: true });
421 checked?.scrollIntoView({ block: "nearest" });
422 }}
423 >
424 {/* No hover opening: an opened menu takes focus, which would steal typing from search. */}
425 <MenuTrigger
426 render={
427 <button
428 type="button"
429 data-effort-row
430 tabIndex={props.tabStop ? 0 : -1}
431 aria-label={`${descriptor.label}: ${current}`}
432 className={cn(OPTION_ROW, "data-popup-open:bg-foreground/[0.09]")}
433 onKeyDown={(event) => {
434 if (event.key !== "ArrowRight") return;
435 event.preventDefault();
436 event.stopPropagation();
437 setOpen(true);
438 }}
439 />
440 }
441 >
442 <OptionRowText label={descriptor.label} value={current} />
443 <ChevronRightIcon
444 aria-hidden="true"
445 className="-me-1 size-3.5 shrink-0 text-muted-foreground"
446 />
447 </MenuTrigger>
448 <MenuPopup
449 ref={popupRef}
450 side="right"
451 align="start"
452 sideOffset={6}
453 // A full-width column on phones leaves no room beside it, so fall below or above.
454 collisionAvoidance={{ fallbackAxisSide: "end" }}
455 className="max-w-72"
456 data-model-picker-option-menu
457 {...composerFloatingLayerProps}
458 onKeyDown={(event) => {
459 if (event.key !== "ArrowLeft") return;
460 event.preventDefault();
461 event.stopPropagation();
462 setOpen(false);
463 }}
464 >
465 <MenuRadioGroup
466 aria-label={descriptor.label}
467 value={value}
468 onValueChange={(next: string) => {
469 if (next !== value) traits.changeSelect(descriptor, next);
470 }}
471 >
472 {choices.map((choice) => (
473 <MenuRadioItem key={choice.id} value={choice.id} closeOnClick>
474 <span className="flex items-center gap-3">
475 <span className="flex min-w-0 flex-1 flex-col">
476 <span className="truncate">{choice.label}</span>
477 {choice.description ? (
478 <span className="line-clamp-2 text-muted-foreground text-xs">
479 {choice.description}
480 </span>
481 ) : null}
482 </span>
483 {choice.isDefault ? (
484 <span className="text-muted-foreground/70 text-xs">
485 {gt({ context: "marks the default option" })`Default`}
486 </span>
487 ) : null}
488 <MenuRadioItemIndicator />
489 </span>
490 </MenuRadioItem>
491 ))}
492 </MenuRadioGroup>
493 </MenuPopup>
494 </Menu>
495 );
496}
497
498/** A two-state option toggles in place; a menu would add a click for nothing. */
499function OptionSwitchRow(props: {
500 descriptor: BooleanDescriptor;
501 traits: TraitsSelection;
502 tabStop: boolean;
503}) {
504 const gt = useGT();
505 const { descriptor, traits } = props;
506 const checked = descriptor.currentValue === true;
507 return (
508 <label className={cn(OPTION_ROW, "has-focus-visible:bg-foreground/[0.09]")}>
509 <OptionRowText
510 label={descriptor.label}
511 value={checked ? gt({ context: "option state" })`On` : gt({ context: "option state" })`Off`}
512 />
513 <Switch
514 size="sm"
515 checked={checked}
516 onCheckedChange={(next) => traits.changeBoolean(descriptor.id, next)}
517 aria-label={descriptor.label}
518 data-effort-row
519 tabIndex={props.tabStop ? 0 : -1}
520 />
521 </label>
522 );
523}
524
525function NoEffortRow() {
526 return (
527 <div className="flex h-8 items-center px-2 text-muted-foreground text-sm">
528 <T>No effort levels</T>
529 </div>
530 );
531}
532
533/** The model picker's effort column: the selected model's levels and its other options. */
534export function ComposerEffortColumn(props: { traits: TraitsSelectionInput | null }) {
535 const gt = useGT();
536 const messages = useMessages();
537 const picker = use(DockedPickerContext);
538 const visibility = props.traits
539 ? getTraitsSectionVisibility({ ...props.traits, resolve: messages })
540 : null;
541 const controls =
542 props.traits && visibility
543 ? columnControls(visibility.selectDescriptors, visibility.booleanDescriptors)
544 : null;
545 return (
546 <>
547 {/* Matches the search row's box, so one rule runs across the top of the popup. */}
548 <div className="shrink-0 px-3 pt-2.5">
549 <div className="flex h-8.25 -translate-y-px items-center gap-2 border-b border-border/70 pb-1.5 text-sm">
550 <span className="text-muted-foreground">
551 {controls?.effort?.descriptor.label ??
552 (controls?.others.length
553 ? gt({ context: "heading for model options" })`Options`
554 : gt({ context: "heading for reasoning effort levels" })`Effort`)}
555 </span>
556 <span className="ms-auto min-w-0 truncate text-muted-foreground text-xs">
557 {picker.modelLabel}
558 </span>
559 </div>
560 </div>
561 {/* pt-2.5 puts the first level on the same line as the first model. */}
562 <div
563 className="flex min-h-0 flex-1 flex-col gap-0.5 overflow-y-auto overscroll-contain px-2 pt-2.5 pb-1.5"
564 // Capture, so Up and Down on an option row move rows instead of opening its menu.
565 onKeyDownCapture={moveBetweenRows}
566 >
567 {props.traits ? <EffortLevels traits={props.traits} /> : <NoEffortRow />}
568 </div>
569 </>
570 );
571}
572
573const FOOTER_SEGMENT =
574 "flex h-6 cursor-pointer items-center justify-center gap-1 px-2 text-muted-foreground text-xs outline-none first:rounded-l-md last:rounded-r-md hover:text-foreground data-checked:bg-input/72 data-checked:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset";
575
576function SpeedSegment(props: {
577 checked: boolean;
578 label: string;
579 /** The untranslated speed name that picks the bolt, when `label` is translated. */
580 speed?: string;
581 description?: string | undefined;
582 onPick: () => void;
583}) {
584 const speed = props.speed ?? props.label;
585 const buttonProps = {
586 type: "button",
587 role: "radio",
588 "aria-checked": props.checked,
589 "data-checked": props.checked || undefined,
590 className: FOOTER_SEGMENT,
591 onClick: props.onPick,
592 } as const;
593 const content = (
594 <>
595 {speed === "Fast" || speed === "Ultrafast" ? (
596 <FastBolt ultra={speed === "Ultrafast"} />
597 ) : null}
598 {props.label}
599 </>
600 );
601 if (!props.description) return <button {...buttonProps}>{content}</button>;
602 return (
603 <SharedTooltipTrigger render={<button {...buttonProps} />} label={props.description}>
604 {content}
605 </SharedTooltipTrigger>
606 );
607}
608
609function SpeedControl(props: { traits: TraitsSelectionInput }) {
610 const gt = useGT();
611 const traits = useTraitsSelection(props.traits);
612 const { speedSelect, fastToggle } = splitSpeed(
613 traits.selectDescriptors,
614 traits.booleanDescriptors,
615 );
616 if (traits.modelIsUnavailable || (!speedSelect && !fastToggle)) return null;
617 return (
618 <div
619 role="radiogroup"
620 aria-label={speedSelect?.label ?? fastToggle?.label}
621 className="flex rounded-lg bg-input/40 p-0.5"
622 >
623 {speedSelect
624 ? selectableProviderOptionChoices(speedSelect).map((option) => (
625 <SpeedSegment
626 key={option.id}
627 checked={option.id === traits.selectValue(speedSelect)}
628 label={option.label}
629 description={option.description}
630 onPick={() => traits.changeSelect(speedSelect, option.id)}
631 />
632 ))
633 : fastToggle
634 ? ([false, true] as const).map((value) => (
635 <SpeedSegment
636 key={String(value)}
637 checked={(fastToggle.currentValue === true) === value}
638 speed={value ? "Fast" : "Standard"}
639 label={
640 value
641 ? gt({ context: "response speed" })`Fast`
642 : gt({ context: "response speed" })`Standard`
643 }
644 onPick={() => traits.changeBoolean(fastToggle.id, value)}
645 />
646 ))
647 : null}
648 </div>
649 );
650}
651
652function UltracodeControl(props: { traits: TraitsSelectionInput }) {
653 const traits = useTraitsSelection(props.traits);
654 const { ultracodeToggle } = splitSpeed(traits.selectDescriptors, traits.booleanDescriptors);
655 if (traits.modelIsUnavailable || !ultracodeToggle) return null;
656 const on = ultracodeToggle.currentValue === true;
657 return (
658 <div className="flex rounded-lg bg-input/40 p-0.5">
659 <button
660 type="button"
661 aria-pressed={on}
662 data-checked={on || undefined}
663 className={FOOTER_SEGMENT}
664 onClick={() => traits.changeBoolean(ultracodeToggle.id, !on)}
665 >
666 <WorkflowIcon aria-hidden="true" className="size-3" />
667 {ultracodeToggle.label}
668 </button>
669 </div>
670 );
671}
672
673/** Permissions change rarely, so the footer names the mode and nests the choice in a menu. */
674function PermissionsMenu(props: {
675 runtimeMode: RuntimeMode;
676 options: ReadonlyArray<RuntimeModeOption>;
677 onChange: (mode: RuntimeMode) => void;
678}) {
679 const gt = useGT();
680 const triggerRef = useRef<HTMLButtonElement>(null);
681 const [menuOpen, setMenuOpen] = useState(false);
682 const current = props.options.find((option) => option.mode === props.runtimeMode);
683 if (!current) return null;
684 const CurrentIcon = current.icon;
685 return (
686 <Menu
687 open={menuOpen}
688 onOpenChange={setMenuOpen}
689 onOpenChangeComplete={(open) => {
690 if (open) focusCheckedPermission(triggerRef.current);
691 }}
692 >
693 <MenuTrigger
694 render={
695 <button
696 ref={triggerRef}
697 type="button"
698 data-composer-permissions-trigger
699 aria-label={gt`Permissions: ${{ mode: current.label }}`}
700 className="ms-auto flex h-7 cursor-pointer items-center gap-1.5 rounded-md px-2 text-muted-foreground text-xs outline-none hover:bg-foreground/[0.09] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset data-popup-open:bg-foreground/[0.09] data-popup-open:text-foreground"
701 />
702 }
703 >
704 <CurrentIcon aria-hidden="true" className="size-3.5" />
705 {current.label}
706 <ChevronUpIcon aria-hidden="true" className="size-3" />
707 </MenuTrigger>
708 <MenuPopup
709 side="top"
710 align="end"
711 {...composerFloatingLayerProps}
712 onBlur={(event) => {
713 // Base UI skips focus-out dismissal when focus returns to the pre-open trigger.
714 if (
715 event.relatedTarget instanceof Node &&
716 !event.currentTarget.contains(event.relatedTarget) &&
717 !triggerRef.current?.contains(event.relatedTarget)
718 ) {
719 setMenuOpen(false);
720 }
721 }}
722 onKeyDown={(event) => {
723 const modified = event.shiftKey || event.altKey || event.ctrlKey || event.metaKey;
724 if (event.key !== "Tab" || modified) return;
725 // Tab past the last footer item hits the popover's guard and focuses its trigger.
726 event.preventDefault();
727 setMenuOpen(false);
728 triggerRef.current?.focus();
729 }}
730 >
731 <ComposerPermissionsSection
732 runtimeMode={props.runtimeMode}
733 runtimeModeOptions={props.options}
734 onRuntimeModeChange={props.onChange}
735 />
736 </MenuPopup>
737 </Menu>
738 );
739}
740
741/** The model picker's footer: speed stays one click away, permissions sit one menu deeper. */
742export function ComposerPickerFooter(props: {
743 traits: TraitsSelectionInput | null;
744 runtimeMode: RuntimeMode;
745 runtimeModeOptions: ReadonlyArray<RuntimeModeOption>;
746 onRuntimeModeChange: (mode: RuntimeMode) => void;
747}) {
748 return (
749 <div className="flex flex-wrap items-center gap-2 border-t border-border/70 bg-muted/40 px-3 py-2">
750 {props.traits ? <SpeedControl traits={props.traits} /> : null}
751 {props.traits ? <UltracodeControl traits={props.traits} /> : null}
752 <PermissionsMenu
753 runtimeMode={props.runtimeMode}
754 options={props.runtimeModeOptions}
755 onChange={props.onRuntimeModeChange}
756 />
757 </div>
758 );
759}