feat(webui): add session-scoped reasoning effort (#6441)
* feat(webui): add session-scoped model options Extend the composer preset menu with inherited reasoning effort and Codex Fast mode overrides. Persist choices with ordinary inputs, isolate captured runtimes, and restore browser preferences without changing shared presets. Add regression coverage for pending preset ordering, settings initialization, session and host isolation, queue edits, Codex request mapping, and narrow-screen controls. * feat(webui): refine session model options and add Codex Ultrafast Fit the composer options into a compact single row and preview reasoning effort only during a drag. Add Fast/Ultrafast controls for eligible Codex models, preserve explicit session choices across reloads, and document the speed tiers. * fix(webui): add Codex speed control to the component gallery * fix(webui): preserve saved model options after preset rename Use the session options for display when a browser preference no longer matches the preset. Omit model options from the next message unless the browser has a matching choice, so stale preferences cannot overwrite options the gateway already saved.
This commit is contained in:
1 parent
2b232c9133
commit
0f45d74fec
82 files changed
+2289
-113
No files matched your search
@@ -4,6 +4,7 @@ import { useAutomaticModelAPI } from "@/components/settings/models/useAutomaticM
|
||||
import { useModelPresetDrag } from "@/components/settings/models/useModelPresetDrag";
|
||||
import { ReasoningEffortPicker } from "@/components/settings/models/ReasoningEffortPicker";
|
||||
import { RemoveActionButton } from "@/components/settings/shared/RemoveActionButton";
|
||||
import { CodexSpeedControl } from "@/components/ui/codex-speed-control";
|
||||
import { ToggleButton } from "@/components/ui/toggle-button";
|
||||
import type { EditCompletion } from "@/components/settings/shared/useEditCompletion";
|
||||
import { useEffect, useId, useRef, useState, type Dispatch, type SetStateAction } from "react";
|
||||
@@ -47,9 +48,9 @@ import {
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { ModelAPIConfig, SettingsPayload } from "@/lib/types";
|
||||
import type { CodexFastMode, ModelAPIConfig, SettingsPayload } from "@/lib/types";
|
||||
import { ProviderParameterFields, type RequestParameterDraft } from "@/components/settings/models/ProviderParameterFields";
|
||||
import { providerJsonValue } from "@/components/settings/models/providerForm";
|
||||
import { parseProviderObject, providerJsonValue } from "@/components/settings/models/providerForm";
|
||||
|
||||
export interface AgentSettingsDraft {
|
||||
model: string;
|
||||
@@ -59,6 +60,7 @@ export interface AgentSettingsDraft {
|
||||
contextWindowTokens: number;
|
||||
temperature: number;
|
||||
reasoningEffort: string;
|
||||
codexFastMode: CodexFastMode | null;
|
||||
supportsImages: boolean;
|
||||
api: ModelAPIConfig | null;
|
||||
extraHeaders: string;
|
||||
@@ -104,6 +106,7 @@ export const DEFAULT_AGENT_SETTINGS_DRAFT: AgentSettingsDraft = {
|
||||
contextWindowTokens: 200_000,
|
||||
temperature: 0.1,
|
||||
reasoningEffort: "",
|
||||
codexFastMode: null,
|
||||
supportsImages: true,
|
||||
api: null,
|
||||
extraHeaders: "",
|
||||
@@ -132,6 +135,7 @@ export function agentDraftFromPayload(
|
||||
),
|
||||
temperature: activePreset?.temperature ?? payload.agent.temperature,
|
||||
reasoningEffort: activePreset?.reasoning_effort ?? "",
|
||||
codexFastMode: activePreset?.codex_fast_mode ?? null,
|
||||
supportsImages: (activePreset ? activePreset.supports_images : payload.agent.supports_images) ?? true,
|
||||
api: activePreset ? activePreset.api ?? null : payload.agent.api ?? null,
|
||||
extraHeaders: providerJsonValue(activePreset?.extra_headers),
|
||||
@@ -325,6 +329,19 @@ export function ModelsSettings({
|
||||
|
||||
const configuredProviders = settings.providers.filter((provider) => provider.configured);
|
||||
const selectedProvider = settings.providers.find((provider) => provider.name === form.provider);
|
||||
const savedSpeed = form.provider === selectedPreset?.provider && form.model === selectedPreset.model
|
||||
? selectedPreset.model_options?.codex_fast_mode : undefined;
|
||||
const speedProvider = selectedProvider ?? (savedSpeed
|
||||
? settings.providers.find((provider) => provider.name === selectedPreset?.resolved_provider)
|
||||
: undefined);
|
||||
const supportsCodexSpeed = selectedProvider?.codex_fast_mode_supported || !!savedSpeed;
|
||||
const speedTier = supportsCodexSpeed
|
||||
? { ...speedProvider?.extra_body, ...parseProviderObject(form.extraBody) }.service_tier
|
||||
: undefined;
|
||||
const shownSpeed = form.codexFastMode ?? (speedTier === "ultrafast" ? speedTier : speedTier === "priority");
|
||||
const supportsUltrafast = (model: string) => selectedProvider?.codex_ultrafast_models?.includes(
|
||||
model.trim().toLowerCase().replace(/^openai[-_]codex\//, ""),
|
||||
);
|
||||
const selectableProviders = uniqueProviders([
|
||||
...configuredProviders,
|
||||
...(selectedProvider ? [selectedProvider] : []),
|
||||
@@ -352,6 +369,7 @@ export function ModelsSettings({
|
||||
extraHeaders: provider === prev.provider ? prev.extraHeaders : "",
|
||||
extraQuery: provider === prev.provider ? prev.extraQuery : "",
|
||||
extraBody: provider === prev.provider ? prev.extraBody : "",
|
||||
codexFastMode: provider === prev.provider ? prev.codexFastMode : null,
|
||||
modelPreset: clearSuggestedName ? "" : prev.modelPreset,
|
||||
}));
|
||||
};
|
||||
@@ -406,6 +424,7 @@ export function ModelsSettings({
|
||||
contextWindowTokens: normalizeContextWindowTokens(preset.context_window_tokens),
|
||||
temperature: preset.temperature,
|
||||
reasoningEffort: preset.reasoning_effort ?? "",
|
||||
codexFastMode: preset.codex_fast_mode ?? null,
|
||||
supportsImages: preset.supports_images ?? true,
|
||||
api: preset.api ?? null,
|
||||
extraHeaders: providerJsonValue(preset.extra_headers),
|
||||
@@ -541,6 +560,8 @@ export function ModelsSettings({
|
||||
model,
|
||||
contextWindowTokens: initializeContext ? contextWindow : prev.contextWindowTokens,
|
||||
api: model === prev.model ? prev.api : null,
|
||||
codexFastMode: prev.codexFastMode === "ultrafast" && model !== prev.model && !supportsUltrafast(model)
|
||||
? null : prev.codexFastMode,
|
||||
modelPreset: canSuggestName ? suggestion : prev.modelPreset,
|
||||
}));
|
||||
}}
|
||||
@@ -572,6 +593,21 @@ export function ModelsSettings({
|
||||
onChange={(reasoningEffort) => setForm((prev) => ({ ...prev, reasoningEffort }))}
|
||||
/>
|
||||
</SettingsRow>
|
||||
{supportsCodexSpeed && (
|
||||
<SettingsRow
|
||||
title={t("thread.composer.modelOptions.codexFast")}
|
||||
description={t("settings.providers.capabilityFastModeHelp")}
|
||||
>
|
||||
<CodexSpeedControl
|
||||
value={shownSpeed}
|
||||
ultrafastSupported={supportsUltrafast(form.model) || savedSpeed?.ultrafast_supported}
|
||||
onChange={(codexFastMode) => {
|
||||
edits.complete();
|
||||
setForm((prev) => ({ ...prev, codexFastMode }));
|
||||
}}
|
||||
/>
|
||||
</SettingsRow>
|
||||
)}
|
||||
<Dialog open={advancedOpen} onOpenChange={(open) => {
|
||||
if (!open && !creating && edits.needsCompletion()) {
|
||||
void edits.commit().then((saved) => { if (saved) setAdvancedOpen(false); });
|
||||
|
||||
@@ -81,7 +81,7 @@ const PROVIDER_REQUEST_OPTIONS: Partial<Record<string, ProviderRequestOption[]>>
|
||||
openai_codex: [{
|
||||
kind: "priority",
|
||||
titleKey: "settings.providers.capabilityFastMode",
|
||||
title: "Fast mode",
|
||||
title: "Fast",
|
||||
helpKey: "settings.providers.capabilityFastModeHelp",
|
||||
help: "Faster responses, increased usage.",
|
||||
}],
|
||||
|
||||
@@ -6,6 +6,7 @@ import { ComboboxOption, useComboboxNavigation } from "@/components/ui/combobox"
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Popover, PopoverAnchor, PopoverContent } from "@/components/ui/popover";
|
||||
import { useProviderModelCatalog } from "@/hooks/useProviderModelCatalog";
|
||||
import { reasoningEffortValues } from "@/lib/provider-model-catalog";
|
||||
import type { SettingsPayload } from "@/lib/types";
|
||||
|
||||
const NO_PROVIDER = {};
|
||||
@@ -31,8 +32,7 @@ export function ReasoningEffortPicker({ token, provider, model, savedValues, val
|
||||
provider: provider?.name ?? "",
|
||||
enabled: open && !!model && !!provider?.configured && provider.model_catalog !== "unsupported",
|
||||
});
|
||||
const efforts = payload?.models.find((entry) => entry.id === model)?.reasoning_efforts ?? savedValues ?? [];
|
||||
const values = [DEFAULT_VALUE, ...new Set(efforts.filter(Boolean))];
|
||||
const values = [DEFAULT_VALUE, ...reasoningEffortValues(payload, model, savedValues)];
|
||||
const close = () => { restoreFocus.current = true; setOpen(false); };
|
||||
const navigation = useComboboxNavigation({
|
||||
open,
|
||||
|
||||
@@ -209,6 +209,7 @@ export function useModelSettingsActions({
|
||||
contextWindowTokens: form.contextWindowTokens,
|
||||
temperature: form.temperature,
|
||||
reasoningEffort: form.reasoningEffort || null,
|
||||
codexFastMode: form.codexFastMode ?? undefined,
|
||||
supportsImages: form.supportsImages,
|
||||
api: form.api ?? undefined,
|
||||
...(settings.model_request_overrides_supported ? {
|
||||
@@ -273,6 +274,8 @@ export function useModelSettingsActions({
|
||||
form.temperature !== selectedPreset.temperature ? form.temperature : undefined,
|
||||
reasoningEffort:
|
||||
reasoningEffort !== selectedPreset.reasoning_effort ? reasoningEffort : undefined,
|
||||
codexFastMode: form.codexFastMode !== (selectedPreset.codex_fast_mode ?? null)
|
||||
? form.codexFastMode : undefined,
|
||||
supportsImages: form.supportsImages !== (selectedPreset.supports_images ?? true)
|
||||
? form.supportsImages : undefined,
|
||||
api: modelAPISelection(form.api) !== modelAPISelection(selectedPreset.api)
|
||||
@@ -350,6 +353,7 @@ export function useModelSettingsActions({
|
||||
),
|
||||
temperature: primaryPreset?.temperature ?? settings.agent.temperature,
|
||||
reasoningEffort: primaryPreset?.reasoning_effort ?? settings.agent.reasoning_effort ?? "",
|
||||
codexFastMode: null,
|
||||
}));
|
||||
setModelPresetCreating(true);
|
||||
};
|
||||
|
||||
@@ -137,7 +137,7 @@ export function ProviderPicker({
|
||||
showBrandLogos={showProviderLogos}
|
||||
/>
|
||||
) : null}
|
||||
<span className="truncate">{selectedProvider?.label ?? emptyLabel}</span>
|
||||
<span className="relative top-px truncate">{selectedProvider?.label ?? emptyLabel}</span>
|
||||
</span></SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent onCloseAutoFocus={(event) => {
|
||||
|
||||
@@ -268,6 +268,7 @@ export function useSettingsController({
|
||||
form.contextWindowTokens !== normalizeContextWindowTokens(selectedPreset.context_window_tokens) ||
|
||||
form.temperature !== selectedPreset.temperature ||
|
||||
form.reasoningEffort !== (selectedPreset.reasoning_effort ?? "") ||
|
||||
form.codexFastMode !== (selectedPreset.codex_fast_mode ?? null) ||
|
||||
form.supportsImages !== (selectedPreset.supports_images ?? true) ||
|
||||
modelAPISelection(form.api) !== modelAPISelection(selectedPreset.api) ||
|
||||
form.extraHeaders !== providerJsonValue(selectedPreset.extra_headers) ||
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import { useRef, useState, type CSSProperties, type PointerEvent } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { CodexSpeedControl } from "@/components/ui/codex-speed-control";
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip-primitives";
|
||||
import type { ModelOptionsCapability, SessionModelOptions } from "@/lib/types";
|
||||
|
||||
import "./model-options-control.css";
|
||||
|
||||
export interface ModelOptionsControlProps {
|
||||
data: { value: SessionModelOptions; capability: ModelOptionsCapability; efforts: string[] } | null;
|
||||
onChange: (value: SessionModelOptions) => void;
|
||||
}
|
||||
|
||||
function ReasoningEffortControl({ options, selected, ordered, onChange }: {
|
||||
options: (string | null)[];
|
||||
selected: number;
|
||||
ordered: boolean;
|
||||
onChange: (value: string | null) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const label = t("settings.models.reasoningEffort");
|
||||
const auto = t("settings.values.auto");
|
||||
const last = options.length - 1;
|
||||
const axisRef = useRef<HTMLDivElement>(null);
|
||||
const thumbRef = useRef<HTMLSpanElement>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const drag = useRef<{ start: number; span: number; offset: number } | null>(null);
|
||||
const [preview, setPreview] = useState<number | null>(null);
|
||||
const position = preview ?? selected / Math.max(last, 1);
|
||||
const selectedLabel = options[selected] ?? auto;
|
||||
const previewLabel = options[Math.round(position * last)] ?? auto;
|
||||
|
||||
function positionAt(clientX: number) {
|
||||
const { start, span, offset } = drag.current!;
|
||||
return Math.max(0, Math.min(1, (clientX - start) / span - offset));
|
||||
}
|
||||
|
||||
function startDrag(event: PointerEvent<HTMLDivElement>) {
|
||||
if (!event.isPrimary || event.button !== 0) return;
|
||||
const axis = axisRef.current!;
|
||||
const bounds = axis.getBoundingClientRect();
|
||||
const radius = thumbRef.current!.offsetWidth / 2;
|
||||
const rtl = getComputedStyle(axis).direction === "rtl";
|
||||
const start = rtl ? bounds.right : bounds.left;
|
||||
const span = rtl ? -bounds.width : bounds.width;
|
||||
const delta = (event.clientX - start) / span - position;
|
||||
drag.current = { start, span, offset: Math.abs(delta * span) <= radius ? delta : 0 };
|
||||
event.preventDefault();
|
||||
inputRef.current?.focus({ preventScroll: true });
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
setPreview(positionAt(event.clientX));
|
||||
}
|
||||
|
||||
function endDrag() {
|
||||
drag.current = null;
|
||||
setPreview(null);
|
||||
}
|
||||
if (!ordered && last > 0) {
|
||||
return (
|
||||
<label className="reasoning-effort flex-1 justify-between text-xs">
|
||||
<span className="min-w-0 truncate" title={label}>{label}</span>
|
||||
<select className="min-h-7 min-w-0 max-w-[55%] shrink-0 truncate rounded-control border border-input bg-background px-2 text-xs text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring max-sm:min-h-11"
|
||||
value={selected} onChange={(event) => onChange(options[Number(event.currentTarget.value)])}>
|
||||
{options.map((option, index) => <option key={index} value={index}>{option ?? auto}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="reasoning-effort text-xs">
|
||||
<span className="min-w-0 truncate" title={label}>{label}</span>
|
||||
{last > 0 ? (
|
||||
<div className="reasoning-effort-slider" data-dragging={preview !== null || undefined}
|
||||
data-at-start={position === 0 || undefined}
|
||||
style={{ "--effort-progress": position, "--effort-steps": last } as CSSProperties}
|
||||
onPointerDown={startDrag}
|
||||
onPointerMove={(event) => {
|
||||
if (drag.current && event.currentTarget.hasPointerCapture(event.pointerId)) setPreview(positionAt(event.clientX));
|
||||
}}
|
||||
onPointerUp={(event) => {
|
||||
if (!drag.current || !event.currentTarget.hasPointerCapture(event.pointerId)) return;
|
||||
const next = Math.round(positionAt(event.clientX) * last);
|
||||
endDrag();
|
||||
if (next !== selected) onChange(options[next]);
|
||||
}}
|
||||
onLostPointerCapture={endDrag}>
|
||||
<div className="reasoning-effort-track" aria-hidden="true">
|
||||
<div className="reasoning-effort-lane"><span className="reasoning-effort-fill" /></div>
|
||||
<div ref={axisRef} className="reasoning-effort-axis">
|
||||
{options.map((_, index) => (
|
||||
<span key={index} className="reasoning-effort-tick" style={{ insetInlineStart: `${index / last * 100}%` }} />
|
||||
))}
|
||||
<TooltipProvider>
|
||||
<Tooltip open={preview !== null} disableHoverableContent onOpenChange={(open) => { if (!open) endDrag(); }}>
|
||||
<TooltipTrigger asChild>
|
||||
<span ref={thumbRef} className="reasoning-effort-thumb" />
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" sideOffset={6} updatePositionStrategy="always" className="pointer-events-none">
|
||||
{previewLabel}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
</div>
|
||||
<input ref={inputRef} type="range" min={0} max={last} step={1} value={selected} aria-label={label} aria-valuetext={selectedLabel}
|
||||
onChange={(event) => onChange(options[event.currentTarget.valueAsNumber])} />
|
||||
</div>
|
||||
) : (
|
||||
<span className="ms-auto min-w-0 max-w-[50%] truncate font-medium text-foreground" title={selectedLabel}>{selectedLabel}</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ModelOptionsControl({ data, onChange }: ModelOptionsControlProps) {
|
||||
if (!data) return null;
|
||||
const { value, capability, efforts } = data;
|
||||
const defaultEffort = capability.reasoning_effort.default;
|
||||
const effectiveEffort = value.reasoning_effort ?? defaultEffort;
|
||||
// Keep preset and session values selectable even if they aren't in the model catalog.
|
||||
const values = [...new Set([...efforts, defaultEffort, value.reasoning_effort].filter((effort): effort is string => !!effort))];
|
||||
const speed = capability.codex_fast_mode;
|
||||
if (!values.length && !speed) return null;
|
||||
const options = defaultEffort === null ? [null, ...values] : values;
|
||||
return (
|
||||
<div className="model-options-row mt-1 flex items-center gap-1 border-t border-border/55 px-2 py-1">
|
||||
{values.length > 0 ? (
|
||||
<ReasoningEffortControl options={options} selected={options.indexOf(effectiveEffort)}
|
||||
ordered={values.every((effort) => efforts.includes(effort))}
|
||||
onChange={(reasoning_effort) => onChange({ ...value, reasoning_effort })} />
|
||||
) : null}
|
||||
{speed ? (
|
||||
<div className="flex shrink-0">
|
||||
<CodexSpeedControl
|
||||
value={value.codex_fast_mode ?? speed.default}
|
||||
onChange={(codex_fast_mode) => onChange({ ...value, codex_fast_mode })}
|
||||
ultrafastSupported={speed.ultrafast_supported}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ModelOptionsControl, type ModelOptionsControlProps } from "@/components/thread/ModelOptionsControl";
|
||||
import { formatModelContextWindow } from "@/lib/model-context-format";
|
||||
import {
|
||||
ModelsIcon,
|
||||
@@ -25,6 +26,7 @@ import { inferProviderFromModelName, providerBrand } from "@/lib/provider-brand"
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const pickerWidthClassName = "w-[min(18rem,calc(100vw-2rem))]";
|
||||
const speedPickerWidthClassName = "w-max max-w-[min(22rem,calc(100vw-1rem))]";
|
||||
const LONG_PRESS_MS = 400;
|
||||
const PRESS_SLOP_PX = 8;
|
||||
const PILL_GAP_PX = 4;
|
||||
@@ -93,6 +95,8 @@ interface ModelPresetBadgeProps {
|
||||
modelPreset?: string | null;
|
||||
modelPresets?: ModelPresetOption[];
|
||||
onPresetChange?: (name: string) => void;
|
||||
modelOptionsControl?: ModelOptionsControlProps;
|
||||
onMenuOpenChange?: (open: boolean) => void;
|
||||
onManageModels?: () => void;
|
||||
onRequestComposerFocus?: () => void;
|
||||
provider?: string | null;
|
||||
@@ -109,6 +113,8 @@ export function ModelPresetBadge({
|
||||
modelPreset,
|
||||
modelPresets = [],
|
||||
onPresetChange,
|
||||
modelOptionsControl,
|
||||
onMenuOpenChange,
|
||||
onManageModels,
|
||||
onRequestComposerFocus,
|
||||
provider,
|
||||
@@ -121,6 +127,7 @@ export function ModelPresetBadge({
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [tooltipOpen, setTooltipOpen] = useState(false);
|
||||
useEffect(() => { onMenuOpenChange?.(open); }, [onMenuOpenChange, open]);
|
||||
const [motion, setMotion] = useState<PresetMotion | null>(null);
|
||||
const [motionWidth, setMotionWidth] = useState<number | null>(null);
|
||||
const gestureRef = useRef<PresetGesture | null>(null);
|
||||
@@ -151,7 +158,8 @@ export function ModelPresetBadge({
|
||||
: modelPresets.map((preset, index) => index === listedIndex ? activePreset : preset);
|
||||
const opensSetup = Boolean(onClick);
|
||||
const canSwitch = !opensSetup && Boolean(onPresetChange) && activeName !== "" && presets.length > 1;
|
||||
const canOpenPicker = !opensSetup && (canSwitch || Boolean(onManageModels));
|
||||
const canOpenPicker = !opensSetup && (canSwitch || Boolean(onManageModels) || Boolean(modelOptionsControl?.data));
|
||||
const showsSpeedControl = Boolean(modelOptionsControl?.data?.capability.codex_fast_mode);
|
||||
const pickerPresets = activeName && onPresetChange ? presets : [activePreset];
|
||||
const currentIndex = Math.max(0, presets.findIndex((preset) => preset.name === activeName));
|
||||
const pillHeight = isHero ? 32 : 36;
|
||||
@@ -401,7 +409,7 @@ export function ModelPresetBadge({
|
||||
align="end"
|
||||
side="top"
|
||||
sideOffset={10}
|
||||
collisionPadding={12}
|
||||
collisionPadding={showsSpeedControl ? 8 : 12}
|
||||
role="dialog"
|
||||
aria-label={switchModelLabel}
|
||||
onEscapeKeyDown={escapeFocus.contentProps.onEscapeKeyDown}
|
||||
@@ -424,7 +432,8 @@ export function ModelPresetBadge({
|
||||
selected?.focus();
|
||||
}}
|
||||
className={cn(
|
||||
pickerWidthClassName,
|
||||
showsSpeedControl ? speedPickerWidthClassName : pickerWidthClassName,
|
||||
"max-h-[var(--radix-popover-content-available-height)] overflow-y-auto",
|
||||
"origin-[var(--radix-popover-content-transform-origin)] p-1.5 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-bottom-1 data-[state=open]:slide-in-from-bottom-1 duration-200 ease-out motion-reduce:animate-none",
|
||||
)}
|
||||
>
|
||||
@@ -454,6 +463,7 @@ export function ModelPresetBadge({
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{modelOptionsControl ? <ModelOptionsControl {...modelOptionsControl} /> : null}
|
||||
{onManageModels ? (
|
||||
<div className="mt-1 border-t border-border/55 pt-1">
|
||||
<button
|
||||
@@ -462,7 +472,7 @@ export function ModelPresetBadge({
|
||||
className={cn(
|
||||
floatingItemClassName,
|
||||
floatingItemFocusClassName,
|
||||
"flex min-h-9 w-full items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-sm font-medium text-muted-foreground hover:text-foreground",
|
||||
"flex min-h-9 w-full items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-sm font-medium text-muted-foreground hover:text-foreground max-sm:min-h-11",
|
||||
)}
|
||||
>
|
||||
<ModelsIcon className="size-4 shrink-0" strokeWidth={1.75} />
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { ModelOptionsControlProps } from "@/components/thread/ModelOptionsControl";
|
||||
import { pastedFilePath, PastedPathRange, type LocalAttachment } from "../../../../packages/client-events/attachments";
|
||||
import {
|
||||
NewChatIcon,
|
||||
@@ -231,6 +232,8 @@ interface ThreadComposerProps {
|
||||
modelDetail?: string | null;
|
||||
modelPreset?: string | null;
|
||||
modelPresets?: ModelPresetOption[];
|
||||
modelOptionsControl?: ModelOptionsControlProps;
|
||||
onModelMenuOpenChange?: (open: boolean) => void;
|
||||
onModelPresetChange?: (name: string) => void;
|
||||
modelProvider?: string | null;
|
||||
modelProviderLabel?: string | null;
|
||||
@@ -559,6 +562,8 @@ export function ThreadComposer({
|
||||
modelDetail = null,
|
||||
modelPreset = null,
|
||||
modelPresets = [],
|
||||
modelOptionsControl,
|
||||
onModelMenuOpenChange,
|
||||
onModelPresetChange,
|
||||
modelProvider = null,
|
||||
modelProviderLabel = null,
|
||||
@@ -1988,6 +1993,8 @@ export function ThreadComposer({
|
||||
modelDetail={modelDetail}
|
||||
modelPreset={modelPreset}
|
||||
modelPresets={modelPresets}
|
||||
modelOptionsControl={modelOptionsControl}
|
||||
onMenuOpenChange={onModelMenuOpenChange}
|
||||
onPresetChange={onModelPresetChange}
|
||||
onManageModels={onManageModels}
|
||||
onRequestComposerFocus={() => textareaRef.current?.focus()}
|
||||
|
||||
@@ -11,6 +11,7 @@ import { FileActionsProvider } from "@/components/FileActions";
|
||||
import { createFilePreviewResource } from "@/lib/file-preview-resource";
|
||||
import { SessionHandleLabel } from "@/components/SessionHandleLabel";
|
||||
import { PromptNavigator } from "@/components/thread/PromptNavigator";
|
||||
import { useSessionModelOptions } from "@/hooks/useSessionModelOptions";
|
||||
import { usePromptHistory } from "@/hooks/usePromptHistory";
|
||||
import { ModelFallbackNotice } from "@/components/thread/ModelFallbackNotice";
|
||||
import { SandboxNotice } from "@/components/thread/SandboxNotice";
|
||||
@@ -828,12 +829,19 @@ export function ThreadShell({
|
||||
});
|
||||
});
|
||||
}, [activeModelPreset, chatId, client]);
|
||||
const [modelMenuOpen, setModelMenuOpen] = useState(false);
|
||||
const { data: modelOptionsData, select: selectModelOptions, reset: resetModelOptions,
|
||||
sendValue: selectedModelOptions, moveToSession: moveModelOptionsToSession } = useSessionModelOptions({
|
||||
sessionKey: session?.key ?? null, preset: activeModelPreset, settings,
|
||||
open: modelMenuOpen, disabled: temporary, storedValue: session?.modelOptions,
|
||||
});
|
||||
const handleModelPresetChange = useCallback((name: string) => {
|
||||
resetModelOptions(name);
|
||||
setLocalModelPreset(name);
|
||||
if (chatId) {
|
||||
void client.sendSystemCommand(chatId, `/model ${name}`).catch(() => {});
|
||||
}
|
||||
}, [chatId, client]);
|
||||
}, [chatId, client, resetModelOptions]);
|
||||
const modelPresetOptions = useMemo(
|
||||
() => modelPresetOptionsFromSettings(settings),
|
||||
[settings],
|
||||
@@ -853,13 +861,15 @@ export function ThreadShell({
|
||||
: modelBadge.label;
|
||||
const withWorkspaceScope = useCallback(
|
||||
(options?: SendOptions): SendOptions | undefined => {
|
||||
if (!workspaceScope) return options;
|
||||
const modelOptions = selectedModelOptions();
|
||||
if (!workspaceScope && !modelOptions) return options;
|
||||
return {
|
||||
...(options ?? {}),
|
||||
workspaceScope,
|
||||
...(workspaceScope ? { workspaceScope } : {}),
|
||||
...(modelOptions ? { modelOptions } : {}),
|
||||
};
|
||||
},
|
||||
[workspaceScope],
|
||||
[selectedModelOptions, workspaceScope],
|
||||
);
|
||||
|
||||
const refreshModelSettings = useCallback(async () => {
|
||||
@@ -1049,13 +1059,14 @@ export function ThreadShell({
|
||||
setBooting(false);
|
||||
return false;
|
||||
}
|
||||
moveModelOptionsToSession(`websocket:${newId}`, pendingFirstRef.current?.options?.modelOptions);
|
||||
if (localModelPreset) {
|
||||
await client.sendSystemCommand(newId, `/model ${localModelPreset}`).catch(() => {});
|
||||
}
|
||||
setPendingFirstTargetChatId(newId);
|
||||
return delivery;
|
||||
},
|
||||
[booting, client, draftKey, draftStore, localModelPreset, onCreateChat, persistDraft, withWorkspaceScope, workspaceScope],
|
||||
[booting, client, draftKey, draftStore, localModelPreset, moveModelOptionsToSession, onCreateChat, persistDraft, withWorkspaceScope, workspaceScope],
|
||||
);
|
||||
|
||||
const inspectAttachment = useCallback(async (path: string) => {
|
||||
@@ -1321,6 +1332,8 @@ export function ThreadShell({
|
||||
modelDetail={modelBadge.model}
|
||||
modelPreset={activeModelPreset}
|
||||
modelPresets={modelPresetOptions}
|
||||
modelOptionsControl={{ data: modelOptionsData, onChange: selectModelOptions }}
|
||||
onModelMenuOpenChange={setModelMenuOpen}
|
||||
onModelPresetChange={handleModelPresetChange}
|
||||
modelProvider={modelBadge.provider}
|
||||
modelProviderLabel={modelBadge.providerLabel}
|
||||
@@ -1375,6 +1388,8 @@ export function ThreadShell({
|
||||
modelDetail={modelBadge.model}
|
||||
modelPreset={activeModelPreset}
|
||||
modelPresets={modelPresetOptions}
|
||||
modelOptionsControl={{ data: modelOptionsData, onChange: selectModelOptions }}
|
||||
onModelMenuOpenChange={setModelMenuOpen}
|
||||
onModelPresetChange={handleModelPresetChange}
|
||||
modelProvider={modelBadge.provider}
|
||||
modelProviderLabel={modelBadge.providerLabel}
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
.reasoning-effort {
|
||||
--effort-gap: 0.375rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-inline-size: 0;
|
||||
gap: var(--effort-gap);
|
||||
}
|
||||
|
||||
.reasoning-effort-slider {
|
||||
--effort-track-size: 20px;
|
||||
--effort-thumb-size: 24px;
|
||||
--effort-axis-inset: calc(var(--effort-track-size) / 2);
|
||||
position: relative;
|
||||
display: grid;
|
||||
align-items: center;
|
||||
flex: none;
|
||||
inline-size: calc(var(--effort-steps) * var(--effort-thumb-size) + 2 * var(--effort-axis-inset));
|
||||
max-inline-size: calc(100% - var(--effort-gap));
|
||||
block-size: 36px;
|
||||
cursor: grab;
|
||||
touch-action: pan-y pinch-zoom;
|
||||
}
|
||||
|
||||
.reasoning-effort-track {
|
||||
--effort-lane: #e6e5e6;
|
||||
--effort-lane-edge: #dad9da;
|
||||
--effort-fill: #000;
|
||||
position: relative;
|
||||
isolation: isolate;
|
||||
block-size: var(--effort-track-size);
|
||||
border-radius: var(--radius-pill);
|
||||
corner-shape: round;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
:where(.dark) .reasoning-effort-track {
|
||||
--effort-lane: #4b4a4b;
|
||||
--effort-lane-edge: #555455;
|
||||
--effort-fill: #d4d4d4;
|
||||
}
|
||||
|
||||
.reasoning-effort-lane {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
overflow: hidden;
|
||||
border-radius: inherit;
|
||||
corner-shape: round;
|
||||
background: var(--effort-lane);
|
||||
box-shadow: inset 0 0 0 1px var(--effort-lane-edge);
|
||||
}
|
||||
|
||||
.reasoning-effort-axis {
|
||||
position: absolute;
|
||||
inset: 0 var(--effort-axis-inset);
|
||||
}
|
||||
|
||||
.reasoning-effort-fill {
|
||||
display: block;
|
||||
/* The fill stops at the center of the thumb, which covers its edge. */
|
||||
inline-size: calc(var(--effort-axis-inset) + (100% - 2 * var(--effort-axis-inset)) * var(--effort-progress));
|
||||
block-size: 100%;
|
||||
background: var(--effort-fill);
|
||||
transition-property: inline-size, opacity;
|
||||
}
|
||||
|
||||
.reasoning-effort-slider[data-at-start] .reasoning-effort-fill { opacity: 0; }
|
||||
|
||||
.reasoning-effort-tick,
|
||||
.reasoning-effort-thumb {
|
||||
position: absolute;
|
||||
inset-block-start: 50%;
|
||||
translate: 0 -50%;
|
||||
margin-inline-start: calc(var(--marker-size) / -2);
|
||||
inline-size: var(--marker-size);
|
||||
block-size: var(--marker-size);
|
||||
border-radius: 50%;
|
||||
corner-shape: round;
|
||||
}
|
||||
|
||||
.reasoning-effort-tick {
|
||||
--marker-size: 4px;
|
||||
background: white;
|
||||
mix-blend-mode: difference;
|
||||
opacity: 0.24;
|
||||
}
|
||||
|
||||
.reasoning-effort-thumb {
|
||||
--marker-size: var(--effort-thumb-size);
|
||||
inset-inline-start: calc(100% * var(--effort-progress));
|
||||
border: 1px solid #d9d9d9;
|
||||
background: #fff;
|
||||
box-shadow: 0 1px 2px rgb(0 0 0 / 0.08);
|
||||
transition-property: inset-inline-start, scale;
|
||||
}
|
||||
|
||||
.reasoning-effort-fill,
|
||||
.reasoning-effort-thumb {
|
||||
transition-duration: 150ms;
|
||||
transition-timing-function: cubic-bezier(0.2, 0.75, 0.25, 1);
|
||||
}
|
||||
|
||||
.reasoning-effort-slider[data-dragging] .reasoning-effort-fill {
|
||||
transition-property: none;
|
||||
}
|
||||
|
||||
.reasoning-effort-slider[data-dragging] .reasoning-effort-thumb {
|
||||
scale: 1.06;
|
||||
transition-property: scale;
|
||||
}
|
||||
|
||||
/* Keep native keyboard and assistive-technology input; pointer drag previews independently. */
|
||||
.reasoning-effort-slider > input {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
appearance: none;
|
||||
inline-size: 100%;
|
||||
block-size: 100%;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.reasoning-effort-slider[data-dragging] {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
.reasoning-effort-slider:has(input:focus-visible) .reasoning-effort-track {
|
||||
outline: 2px solid hsl(var(--ring));
|
||||
outline-offset: 5px;
|
||||
}
|
||||
|
||||
@media (max-width: 639px) {
|
||||
.reasoning-effort-slider { block-size: 44px; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.reasoning-effort-fill,
|
||||
.reasoning-effort-thumb { transition-duration: 0s; }
|
||||
}
|
||||
|
||||
@media (forced-colors: active) {
|
||||
.reasoning-effort-track { forced-color-adjust: none; }
|
||||
.reasoning-effort-lane { background: GrayText; box-shadow: none; }
|
||||
.reasoning-effort-fill { background: Highlight; }
|
||||
.reasoning-effort-tick { background: Canvas; mix-blend-mode: normal; opacity: 1; }
|
||||
.reasoning-effort-thumb { background: Canvas; border-color: Highlight; box-shadow: inset 0 0 0 1px Highlight; }
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { Zap } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { HoverHint } from "@/components/ui/hover-hint";
|
||||
import type { CodexFastMode } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export function CodexSpeedControl({ value, onChange, ultrafastSupported }: {
|
||||
value: CodexFastMode;
|
||||
onChange: (value: CodexFastMode) => void;
|
||||
ultrafastSupported?: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const title = t("thread.composer.modelOptions.codexFast");
|
||||
const help = t("settings.providers.capabilityFastModeHelp");
|
||||
const modes = ultrafastSupported || value === "ultrafast" ? [true, "ultrafast"] as const : [true] as const;
|
||||
return (
|
||||
<div role="group" aria-label={title} className="inline-flex items-center gap-0.5">
|
||||
{modes.map((mode) => {
|
||||
const ultra = mode === "ultrafast";
|
||||
const label = ultra ? t("thread.composer.modelOptions.ultrafast") : title;
|
||||
const selected = value === mode;
|
||||
return (
|
||||
<HoverHint key={String(mode)} content={<><strong className="block">{label}</strong>{help}</>}>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
aria-label={label}
|
||||
aria-pressed={selected}
|
||||
className="group/speed h-8 w-8 rounded-lg p-0 max-sm:h-11 max-sm:w-11"
|
||||
onClick={() => onChange(selected ? false : mode)}
|
||||
>
|
||||
<span aria-hidden className={cn(
|
||||
"grid size-7 place-items-center rounded-md",
|
||||
selected ? "bg-foreground text-background" : "bg-muted/65 text-muted-foreground group-hover/speed:text-foreground",
|
||||
)}>
|
||||
{ultra ? (
|
||||
<span className="relative size-[18px]">
|
||||
<Zap className="absolute left-0 top-0 size-3.5 opacity-60" />
|
||||
<Zap className="absolute bottom-0 right-0 size-3.5" />
|
||||
</span>
|
||||
) : <Zap className="size-4" />}
|
||||
</span>
|
||||
</Button>
|
||||
</HoverHint>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { SidebarPanel } from "@/components/ui/sidebar-panel";
|
||||
import { Plus } from "lucide-react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CodexSpeedControl } from "@/components/ui/codex-speed-control";
|
||||
import { Input, SearchInput } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { ToggleButton } from "@/components/ui/toggle-button";
|
||||
@@ -21,6 +22,7 @@ import { ExpandableText } from "@/components/ui/expandable-text";
|
||||
import { StreamingLabelSheen } from "@/components/ui/streaming-label-sheen";
|
||||
import { LoadingRing } from "@/components/ui/loading-ring";
|
||||
import { ImageViewport } from "@/components/ui/image-viewport";
|
||||
import type { CodexFastMode } from "@/lib/types";
|
||||
import { Sample, type ComponentExample } from "./example";
|
||||
import { useGalleryTranslation } from "./i18n";
|
||||
|
||||
@@ -79,6 +81,11 @@ function Switches() {
|
||||
</div>;
|
||||
}
|
||||
|
||||
function CodexSpeedPreview() {
|
||||
const [value, setValue] = useState<CodexFastMode>(false);
|
||||
return <CodexSpeedControl value={value} onChange={setValue} ultrafastSupported />;
|
||||
}
|
||||
|
||||
function Selects() {
|
||||
const { t } = useGalleryTranslation();
|
||||
const [value, setValue] = useState("default");
|
||||
@@ -279,6 +286,9 @@ export const foundationExamples: ComponentExample[] = [
|
||||
description: "controls.textarea.description", options: "controls.textarea.options", code: '<Textarea aria-label="Notes" value={notes} onChange={event => setNotes(event.target.value)} />' },
|
||||
{ title: "controls.toggle.title", files: ["toggle-button"], Preview: Switches,
|
||||
description: "controls.toggle.description", options: "controls.toggle.options", code: '<ToggleButton checked={enabled} onChange={setEnabled} label="Enable feature" />' },
|
||||
{ title: "controls.codexSpeed.title", files: ["codex-speed-control"], Preview: CodexSpeedPreview,
|
||||
description: "controls.codexSpeed.description", options: "controls.codexSpeed.options",
|
||||
code: 'const [value, setValue] = useState<CodexFastMode>(false);\n<CodexSpeedControl value={value} onChange={setValue} ultrafastSupported />' },
|
||||
{ title: "controls.select.title", files: ["select"], Preview: Selects,
|
||||
description: "controls.select.description", options: "controls.select.options",
|
||||
code: '<Select value={value} onValueChange={setValue}>\n <SelectTrigger aria-label="Model"><SelectValue /></SelectTrigger>\n <SelectContent><SelectItem value="default">Default</SelectItem></SelectContent>\n</Select>' },
|
||||
|
||||
@@ -54,6 +54,11 @@
|
||||
"model": "Example model",
|
||||
"disabledModel": "Disabled model"
|
||||
},
|
||||
"codexSpeed": {
|
||||
"title": "Codex speed",
|
||||
"description": "Choose Fast or Ultrafast. Select the active speed again to turn it off.",
|
||||
"options": "Show Ultrafast for supported models."
|
||||
},
|
||||
"segmented": {
|
||||
"title": "Segmented choices",
|
||||
"description": "A short, always-visible set of choices.",
|
||||
|
||||
@@ -54,6 +54,11 @@
|
||||
"model": "Modelo de ejemplo",
|
||||
"disabledModel": "Selector de modelo desactivado"
|
||||
},
|
||||
"codexSpeed": {
|
||||
"title": "Velocidad de Codex",
|
||||
"description": "Elige Fast o Ultrarrápido. Vuelve a seleccionar el modo activo para desactivarlo.",
|
||||
"options": "Muestra Ultrarrápido en los modelos compatibles."
|
||||
},
|
||||
"segmented": {
|
||||
"title": "Selección segmentada",
|
||||
"description": "Un pequeño conjunto de opciones siempre visibles.",
|
||||
|
||||
@@ -54,6 +54,11 @@
|
||||
"model": "Modèle d’exemple",
|
||||
"disabledModel": "Sélecteur de modèle désactivé"
|
||||
},
|
||||
"codexSpeed": {
|
||||
"title": "Vitesse de Codex",
|
||||
"description": "Choisissez Fast ou Ultrarapide. Sélectionnez de nouveau le mode actif pour le désactiver.",
|
||||
"options": "Affiche Ultrarapide pour les modèles compatibles."
|
||||
},
|
||||
"segmented": {
|
||||
"title": "Choix segmentés",
|
||||
"description": "Un petit ensemble de choix toujours visibles.",
|
||||
|
||||
@@ -54,6 +54,11 @@
|
||||
"model": "Model contoh",
|
||||
"disabledModel": "Pemilih model yang dinonaktifkan"
|
||||
},
|
||||
"codexSpeed": {
|
||||
"title": "Kecepatan Codex",
|
||||
"description": "Pilih Fast atau Ultracepat. Pilih kembali mode yang aktif untuk menonaktifkannya.",
|
||||
"options": "Tampilkan Ultracepat untuk model yang mendukungnya."
|
||||
},
|
||||
"segmented": {
|
||||
"title": "Pilihan bersegmen",
|
||||
"description": "Sekumpulan kecil pilihan yang selalu terlihat.",
|
||||
|
||||
@@ -54,6 +54,11 @@
|
||||
"model": "サンプルのモデル",
|
||||
"disabledModel": "無効化されたモデル選択"
|
||||
},
|
||||
"codexSpeed": {
|
||||
"title": "Codex の速度",
|
||||
"description": "Fast または超高速を選びます。選択中のモードをもう一度選ぶと解除できます。",
|
||||
"options": "対応モデルでは超高速を表示します。"
|
||||
},
|
||||
"segmented": {
|
||||
"title": "セグメント選択",
|
||||
"description": "少数の選択肢を常に表示します。",
|
||||
|
||||
@@ -54,6 +54,11 @@
|
||||
"model": "예제 모델",
|
||||
"disabledModel": "비활성화된 모델 선택"
|
||||
},
|
||||
"codexSpeed": {
|
||||
"title": "Codex 속도",
|
||||
"description": "Fast 또는 초고속을 선택합니다. 선택된 모드를 다시 누르면 해제됩니다.",
|
||||
"options": "지원 모델에 초고속을 표시합니다."
|
||||
},
|
||||
"segmented": {
|
||||
"title": "분할 선택",
|
||||
"description": "적은 수의 선택지를 항상 표시합니다.",
|
||||
|
||||
@@ -54,6 +54,11 @@
|
||||
"model": "Modelo de exemplo",
|
||||
"disabledModel": "Seletor de modelo desativado"
|
||||
},
|
||||
"codexSpeed": {
|
||||
"title": "Velocidade do Codex",
|
||||
"description": "Escolha Fast ou Ultrarrápido. Selecione o modo ativo novamente para desativá-lo.",
|
||||
"options": "Mostra Ultrarrápido nos modelos compatíveis."
|
||||
},
|
||||
"segmented": {
|
||||
"title": "Escolhas segmentadas",
|
||||
"description": "Um pequeno conjunto de escolhas sempre visíveis.",
|
||||
|
||||
@@ -54,6 +54,11 @@
|
||||
"model": "Mô hình ví dụ",
|
||||
"disabledModel": "Bộ chọn mô hình bị vô hiệu hóa"
|
||||
},
|
||||
"codexSpeed": {
|
||||
"title": "Tốc độ Codex",
|
||||
"description": "Chọn Fast hoặc Siêu nhanh. Chọn lại chế độ đang bật để tắt.",
|
||||
"options": "Hiển thị Siêu nhanh cho các mô hình được hỗ trợ."
|
||||
},
|
||||
"segmented": {
|
||||
"title": "Lựa chọn phân đoạn",
|
||||
"description": "Một nhóm ít lựa chọn luôn hiển thị.",
|
||||
|
||||
@@ -54,6 +54,11 @@
|
||||
"model": "示例模型",
|
||||
"disabledModel": "禁用的模型选择器"
|
||||
},
|
||||
"codexSpeed": {
|
||||
"title": "Codex 加速",
|
||||
"description": "选择 Fast 或极速,再点一次当前档位即可关闭。",
|
||||
"options": "仅为支持的模型显示极速档。"
|
||||
},
|
||||
"segmented": {
|
||||
"title": "分段选择",
|
||||
"description": "始终可见的一组简短选项。",
|
||||
|
||||
@@ -54,6 +54,11 @@
|
||||
"model": "範例模型",
|
||||
"disabledModel": "停用的模型選擇器"
|
||||
},
|
||||
"codexSpeed": {
|
||||
"title": "Codex 加速",
|
||||
"description": "選擇 Fast 或極速,再按一次目前的選項即可關閉。",
|
||||
"options": "只為支援的模型顯示極速選項。"
|
||||
},
|
||||
"segmented": {
|
||||
"title": "分段選擇",
|
||||
"description": "一組簡短且持續顯示的選項。",
|
||||
|
||||
@@ -31,6 +31,7 @@ import type {
|
||||
OutboundMcpPresetMention,
|
||||
OutboundMedia,
|
||||
SessionMention,
|
||||
SessionModelOptions,
|
||||
GoalStateWsPayload,
|
||||
MessageDeliveryStatus,
|
||||
RecoveryState,
|
||||
@@ -63,6 +64,7 @@ export interface SendAttachment {
|
||||
}
|
||||
|
||||
export interface SendOptions {
|
||||
modelOptions?: SessionModelOptions;
|
||||
intent?: "create_automation";
|
||||
cliApps?: OutboundCliAppMention[];
|
||||
mcpPresets?: OutboundMcpPresetMention[];
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { useProviderModelCatalog } from "@/hooks/useProviderModelCatalog";
|
||||
import { reasoningEffortValues } from "@/lib/provider-model-catalog";
|
||||
import type { SessionModelOptions, SettingsPayload } from "@/lib/types";
|
||||
import { useClient } from "@/providers/ClientProvider";
|
||||
|
||||
const NO_PROVIDER = {};
|
||||
const PREFIX = "nanobot.model-options.v1.";
|
||||
const INHERIT: SessionModelOptions = { reasoning_effort: null, codex_fast_mode: null };
|
||||
type Preference = { preset: string; options: SessionModelOptions };
|
||||
const preferenceKey = (host: string, session: string | null) => `${PREFIX}${JSON.stringify([host, session])}`;
|
||||
|
||||
function readPreference(key: string): Preference | null {
|
||||
try {
|
||||
const value = JSON.parse(localStorage.getItem(key) ?? "null");
|
||||
const options = value?.options;
|
||||
return typeof value?.preset === "string" && options
|
||||
&& (options.reasoning_effort === null || typeof options.reasoning_effort === "string")
|
||||
&& (options.codex_fast_mode === null || typeof options.codex_fast_mode === "boolean" || options.codex_fast_mode === "ultrafast")
|
||||
? { preset: value.preset, options: { reasoning_effort: options.reasoning_effort, codex_fast_mode: options.codex_fast_mode } } : null;
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
function storePreference(key: string, value: Preference | null) {
|
||||
try {
|
||||
if (value) localStorage.setItem(key, JSON.stringify(value));
|
||||
else localStorage.removeItem(key);
|
||||
} catch { /* Browser preferences must not block sending. */ }
|
||||
}
|
||||
|
||||
/** Browser-only choices; the ordinary send is the only gateway persistence boundary. */
|
||||
export function useSessionModelOptions({ sessionKey, preset, settings, open, disabled, storedValue }: {
|
||||
sessionKey: string | null;
|
||||
preset: string;
|
||||
settings: SettingsPayload | null;
|
||||
open: boolean;
|
||||
disabled: boolean;
|
||||
storedValue?: SessionModelOptions;
|
||||
}) {
|
||||
const { client, token, webuiCapabilities } = useClient();
|
||||
const enabled = !disabled && settings !== null && webuiCapabilities.includes("webui.model-options.v1");
|
||||
const host = client.preferenceScope;
|
||||
const key = preferenceKey(host, sessionKey);
|
||||
const entries = useRef(new Map<string, Preference | null>());
|
||||
const [, redraw] = useState(0);
|
||||
if (!entries.current.has(key)) entries.current.set(key, readPreference(key));
|
||||
const saved = entries.current.get(key);
|
||||
const localOptions = saved?.preset === preset ? saved.options : undefined;
|
||||
const value = localOptions ?? storedValue ?? INHERIT;
|
||||
const pending = useRef(new Map<string, Preference | null>());
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const flush = useCallback(() => {
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
timer.current = null;
|
||||
pending.current.forEach((entry, entryKey) => storePreference(entryKey, entry));
|
||||
pending.current.clear();
|
||||
}, []);
|
||||
const remember = useCallback((entryKey: string, entry: Preference | null) => {
|
||||
entries.current.set(entryKey, entry);
|
||||
pending.current.set(entryKey, entry);
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
timer.current = setTimeout(flush, 250);
|
||||
redraw((revision) => revision + 1);
|
||||
}, [flush]);
|
||||
useEffect(() => {
|
||||
if (enabled && saved && saved.preset !== preset) remember(key, null);
|
||||
}, [enabled, key, preset, remember, saved]);
|
||||
useEffect(() => {
|
||||
window.addEventListener("pagehide", flush);
|
||||
return () => { window.removeEventListener("pagehide", flush); flush(); };
|
||||
}, [flush]);
|
||||
|
||||
const configuration = settings?.model_presets.find((entry) => entry.name === preset);
|
||||
const capability = configuration?.model_options;
|
||||
const providerName = configuration?.resolved_provider ?? configuration?.provider;
|
||||
const provider = settings?.providers.find((entry) => entry.name === providerName);
|
||||
const model = configuration?.model ?? "";
|
||||
const { payload } = useProviderModelCatalog({
|
||||
revision: provider ?? NO_PROVIDER, token, provider: provider?.name ?? "",
|
||||
enabled: enabled && open && !!capability && !!model && !!provider?.configured && provider.model_catalog !== "unsupported",
|
||||
});
|
||||
const efforts = reasoningEffortValues(payload, model, capability?.reasoning_effort.values);
|
||||
const select = useCallback((options: SessionModelOptions) => {
|
||||
if (enabled) remember(key, { preset, options });
|
||||
}, [enabled, key, preset, remember]);
|
||||
const reset = useCallback((nextPreset: string) => {
|
||||
if (enabled) remember(key, { preset: nextPreset, options: INHERIT });
|
||||
}, [enabled, key, remember]);
|
||||
const moveToSession = useCallback((target: string, sentValue: SessionModelOptions | undefined) => {
|
||||
if (!enabled || sessionKey || !sentValue) return;
|
||||
const targetKey = preferenceKey(host, target);
|
||||
const targetChoice = entries.current.get(targetKey) ?? readPreference(targetKey);
|
||||
if (!targetChoice) remember(targetKey, { preset, options: sentValue });
|
||||
remember(key, null);
|
||||
// A completed draft must not be resurrected by a reload before the debounce fires.
|
||||
flush();
|
||||
}, [enabled, flush, host, key, preset, remember, sessionKey]);
|
||||
|
||||
// The Gateway owns persisted options. Omission preserves them; null fields explicitly clear them.
|
||||
const sendValue = useCallback(() => enabled ? localOptions : undefined, [enabled, localOptions]);
|
||||
return {
|
||||
data: enabled && capability ? { value, capability, efforts } : null,
|
||||
select, reset, moveToSession, sendValue,
|
||||
};
|
||||
}
|
||||
@@ -1399,7 +1399,7 @@
|
||||
"extraHeaders": "Headers",
|
||||
"extraBody": "Body parameters",
|
||||
"extraQuery": "Query parameters",
|
||||
"capabilityFastMode": "Fast mode",
|
||||
"capabilityFastMode": "Fast",
|
||||
"capabilityFastModeHelp": "Faster responses, increased usage.",
|
||||
"capabilityXSearch": "X Search",
|
||||
"capabilityXSearchHelp": "Supported Grok models can search X.\n\nAllow supported Grok models to use xAI-hosted X Search. Search activity appears in chat.",
|
||||
@@ -2147,6 +2147,13 @@
|
||||
"removeContext": "Remove attachments and quoted text before running a command."
|
||||
},
|
||||
"chooseAI": "Choose model",
|
||||
"modelOptions": {
|
||||
"title": "For this chat",
|
||||
"on": "On",
|
||||
"off": "Off",
|
||||
"codexFast": "Fast",
|
||||
"ultrafast": "Ultrafast"
|
||||
},
|
||||
"switchModel": "Switch model",
|
||||
"manageModels": "Manage presets",
|
||||
"fallbackNotice": "This response used a fallback model: {{model}}.",
|
||||
|
||||
@@ -1009,7 +1009,7 @@
|
||||
"extraHeaders": "Cabeceras",
|
||||
"extraBody": "Parámetros del cuerpo",
|
||||
"extraQuery": "Parámetros de consulta",
|
||||
"capabilityFastMode": "Modo rápido",
|
||||
"capabilityFastMode": "Fast",
|
||||
"capabilityFastModeHelp": "Respuestas más rápidas, mayor consumo.",
|
||||
"capabilityXSearch": "Búsqueda en X",
|
||||
"capabilityXSearchHelp": "Los modelos Grok compatibles pueden buscar en X.\n\nPermite que los modelos Grok compatibles usen X Search alojado por xAI. La actividad de búsqueda aparece en el chat.",
|
||||
@@ -1965,6 +1965,13 @@
|
||||
"removeContext": "Elimina los archivos adjuntos y el texto citado antes de ejecutar un comando."
|
||||
},
|
||||
"chooseAI": "Elegir modelo",
|
||||
"modelOptions": {
|
||||
"title": "Para este chat",
|
||||
"on": "Activado",
|
||||
"off": "Desactivado",
|
||||
"codexFast": "Fast",
|
||||
"ultrafast": "Ultrarrápido"
|
||||
},
|
||||
"switchModel": "Cambiar modelo",
|
||||
"manageModels": "Gestionar preajustes",
|
||||
"fallbackNotice": "Esta respuesta usó un modelo alternativo: {{model}}.",
|
||||
|
||||
@@ -1009,7 +1009,7 @@
|
||||
"extraHeaders": "En-têtes",
|
||||
"extraBody": "Paramètres du corps",
|
||||
"extraQuery": "Paramètres de requête",
|
||||
"capabilityFastMode": "Mode rapide",
|
||||
"capabilityFastMode": "Fast",
|
||||
"capabilityFastModeHelp": "Réponses plus rapides, consommation accrue.",
|
||||
"capabilityXSearch": "Recherche sur X",
|
||||
"capabilityXSearchHelp": "Les modèles Grok compatibles peuvent rechercher sur X.\n\nPermet aux modèles Grok compatibles d’utiliser X Search hébergé par xAI. L’activité de recherche apparaît dans le chat.",
|
||||
@@ -1965,6 +1965,13 @@
|
||||
"removeContext": "Retirez les pièces jointes et le texte cité avant d’exécuter une commande."
|
||||
},
|
||||
"chooseAI": "Choisir le modèle",
|
||||
"modelOptions": {
|
||||
"title": "Pour cette discussion",
|
||||
"on": "Activé",
|
||||
"off": "Désactivé",
|
||||
"codexFast": "Fast",
|
||||
"ultrafast": "Ultrarapide"
|
||||
},
|
||||
"switchModel": "Changer de modèle",
|
||||
"manageModels": "Gérer les préréglages",
|
||||
"fallbackNotice": "Cette réponse a utilisé un modèle de secours : {{model}}.",
|
||||
|
||||
@@ -1009,7 +1009,7 @@
|
||||
"extraHeaders": "Header",
|
||||
"extraBody": "Parameter body",
|
||||
"extraQuery": "Parameter kueri",
|
||||
"capabilityFastMode": "Mode cepat",
|
||||
"capabilityFastMode": "Fast",
|
||||
"capabilityFastModeHelp": "Respons lebih cepat, penggunaan meningkat.",
|
||||
"capabilityXSearch": "Pencarian X",
|
||||
"capabilityXSearchHelp": "Model Grok yang didukung dapat mencari di X.\n\nIzinkan model Grok yang didukung menggunakan X Search yang dihosting xAI. Aktivitas pencarian ditampilkan di chat.",
|
||||
@@ -1965,6 +1965,13 @@
|
||||
"removeContext": "Hapus lampiran dan teks kutipan sebelum menjalankan perintah."
|
||||
},
|
||||
"chooseAI": "Pilih model",
|
||||
"modelOptions": {
|
||||
"title": "Untuk chat ini",
|
||||
"on": "Aktif",
|
||||
"off": "Nonaktif",
|
||||
"codexFast": "Fast",
|
||||
"ultrafast": "Ultracepat"
|
||||
},
|
||||
"switchModel": "Ganti model",
|
||||
"manageModels": "Kelola preset",
|
||||
"fallbackNotice": "Respons ini menggunakan model cadangan: {{model}}.",
|
||||
|
||||
@@ -1009,7 +1009,7 @@
|
||||
"extraHeaders": "ヘッダー",
|
||||
"extraBody": "本文のパラメーター",
|
||||
"extraQuery": "クエリパラメーター",
|
||||
"capabilityFastMode": "高速モード",
|
||||
"capabilityFastMode": "Fast",
|
||||
"capabilityFastModeHelp": "応答が速くなり、使用量が増えます。",
|
||||
"capabilityXSearch": "X 検索",
|
||||
"capabilityXSearchHelp": "対応する Grok モデルが X を検索できます。\n\n対応する Grok モデルが xAI ホストの X Search を使用できるようにします。検索状況はチャットに表示されます。",
|
||||
@@ -1965,6 +1965,13 @@
|
||||
"removeContext": "コマンドを実行する前に、添付ファイルと引用テキストを削除してください。"
|
||||
},
|
||||
"chooseAI": "モデルを選択",
|
||||
"modelOptions": {
|
||||
"title": "このチャット",
|
||||
"on": "オン",
|
||||
"off": "オフ",
|
||||
"codexFast": "Fast",
|
||||
"ultrafast": "超高速"
|
||||
},
|
||||
"switchModel": "モデルを切り替え",
|
||||
"manageModels": "プリセット管理",
|
||||
"fallbackNotice": "この応答では代替モデルを使用しました:{{model}}。",
|
||||
|
||||
@@ -1009,7 +1009,7 @@
|
||||
"extraHeaders": "헤더",
|
||||
"extraBody": "본문 매개변수",
|
||||
"extraQuery": "쿼리 매개변수",
|
||||
"capabilityFastMode": "고속 모드",
|
||||
"capabilityFastMode": "Fast",
|
||||
"capabilityFastModeHelp": "응답이 빨라지고 사용량이 늘어납니다.",
|
||||
"capabilityXSearch": "X 검색",
|
||||
"capabilityXSearchHelp": "지원되는 Grok 모델은 X를 검색할 수 있습니다.\n\n지원되는 Grok 모델이 xAI 호스팅 X Search를 사용하도록 허용합니다. 검색 활동은 채팅에 표시됩니다.",
|
||||
@@ -1965,6 +1965,13 @@
|
||||
"removeContext": "명령을 실행하기 전에 첨부 파일과 인용문을 제거하세요."
|
||||
},
|
||||
"chooseAI": "모델 선택",
|
||||
"modelOptions": {
|
||||
"title": "현재 채팅",
|
||||
"on": "켜기",
|
||||
"off": "끄기",
|
||||
"codexFast": "Fast",
|
||||
"ultrafast": "초고속"
|
||||
},
|
||||
"switchModel": "모델 전환",
|
||||
"manageModels": "프리셋 관리",
|
||||
"fallbackNotice": "이 응답은 대체 모델을 사용했습니다: {{model}}.",
|
||||
|
||||
@@ -1219,7 +1219,7 @@
|
||||
"extraHeaders": "Cabeçalhos",
|
||||
"extraBody": "Parâmetros do corpo",
|
||||
"extraQuery": "Parâmetros de consulta",
|
||||
"capabilityFastMode": "Modo rápido",
|
||||
"capabilityFastMode": "Fast",
|
||||
"capabilityFastModeHelp": "Respostas mais rápidas, maior consumo.",
|
||||
"capabilityXSearch": "Pesquisa no X",
|
||||
"capabilityXSearchHelp": "Modelos Grok compatíveis podem pesquisar no X.\n\nPermite que modelos Grok compatíveis usem o X Search hospedado pela xAI. A atividade de pesquisa aparece no chat.",
|
||||
@@ -1967,6 +1967,13 @@
|
||||
"removeContext": "Remova os anexos e o texto citado antes de executar um comando."
|
||||
},
|
||||
"chooseAI": "Escolher modelo",
|
||||
"modelOptions": {
|
||||
"title": "Para esta conversa",
|
||||
"on": "Ativado",
|
||||
"off": "Desativado",
|
||||
"codexFast": "Fast",
|
||||
"ultrafast": "Ultrarrápido"
|
||||
},
|
||||
"switchModel": "Trocar modelo",
|
||||
"manageModels": "Gerenciar presets",
|
||||
"fallbackNotice": "Esta resposta usou um modelo alternativo: {{model}}.",
|
||||
|
||||
@@ -1009,7 +1009,7 @@
|
||||
"extraHeaders": "Header",
|
||||
"extraBody": "Tham số body",
|
||||
"extraQuery": "Tham số truy vấn",
|
||||
"capabilityFastMode": "Chế độ nhanh",
|
||||
"capabilityFastMode": "Fast",
|
||||
"capabilityFastModeHelp": "Phản hồi nhanh hơn, mức sử dụng cao hơn.",
|
||||
"capabilityXSearch": "Tìm kiếm X",
|
||||
"capabilityXSearchHelp": "Mô hình Grok được hỗ trợ có thể tìm kiếm X.\n\nCho phép các mô hình Grok được hỗ trợ dùng X Search do xAI lưu trữ. Hoạt động tìm kiếm được hiển thị trong cuộc trò chuyện.",
|
||||
@@ -1965,6 +1965,13 @@
|
||||
"removeContext": "Xóa tệp đính kèm và văn bản trích dẫn trước khi chạy lệnh."
|
||||
},
|
||||
"chooseAI": "Chọn mô hình",
|
||||
"modelOptions": {
|
||||
"title": "Cho cuộc trò chuyện này",
|
||||
"on": "Bật",
|
||||
"off": "Tắt",
|
||||
"codexFast": "Fast",
|
||||
"ultrafast": "Siêu nhanh"
|
||||
},
|
||||
"switchModel": "Đổi mô hình",
|
||||
"manageModels": "Quản lý bộ thiết lập",
|
||||
"fallbackNotice": "Phản hồi này đã sử dụng mô hình dự phòng: {{model}}.",
|
||||
|
||||
@@ -1399,7 +1399,7 @@
|
||||
"extraHeaders": "请求头",
|
||||
"extraBody": "请求体参数",
|
||||
"extraQuery": "查询参数",
|
||||
"capabilityFastMode": "快速模式",
|
||||
"capabilityFastMode": "Fast",
|
||||
"capabilityFastModeHelp": "更快响应,用量更高",
|
||||
"capabilityXSearch": "X 搜索",
|
||||
"capabilityXSearchHelp": "支持的 Grok 模型可搜索 X\n\n允许受支持的 Grok 模型使用 xAI 托管的 X Search,并在对话中展示搜索过程。",
|
||||
@@ -2147,6 +2147,13 @@
|
||||
"removeContext": "执行命令前,请移除附件和引用文本。"
|
||||
},
|
||||
"chooseAI": "选择模型",
|
||||
"modelOptions": {
|
||||
"title": "当前会话",
|
||||
"on": "开启",
|
||||
"off": "关闭",
|
||||
"codexFast": "Fast",
|
||||
"ultrafast": "极速"
|
||||
},
|
||||
"switchModel": "切换模型",
|
||||
"manageModels": "管理预设",
|
||||
"fallbackNotice": "本次已使用备用模型:{{model}}。",
|
||||
|
||||
@@ -1009,7 +1009,7 @@
|
||||
"extraHeaders": "請求頭",
|
||||
"extraBody": "請求體引數",
|
||||
"extraQuery": "查詢引數",
|
||||
"capabilityFastMode": "快速模式",
|
||||
"capabilityFastMode": "Fast",
|
||||
"capabilityFastModeHelp": "回應更快,用量更高",
|
||||
"capabilityXSearch": "X 搜尋",
|
||||
"capabilityXSearchHelp": "支援的 Grok 模型可搜尋 X\n\n允許受支援的 Grok 模型使用 xAI 託管的 X Search,並在對話中展示搜尋過程。",
|
||||
@@ -1965,6 +1965,13 @@
|
||||
"removeContext": "執行命令前,請移除附件和引用文字。"
|
||||
},
|
||||
"chooseAI": "選擇模型",
|
||||
"modelOptions": {
|
||||
"title": "目前對話",
|
||||
"on": "開啟",
|
||||
"off": "關閉",
|
||||
"codexFast": "Fast",
|
||||
"ultrafast": "極速"
|
||||
},
|
||||
"switchModel": "切換模型",
|
||||
"manageModels": "管理預設",
|
||||
"fallbackNotice": "本次已使用備用模型:{{model}}。",
|
||||
|
||||
@@ -10,6 +10,7 @@ import type {
|
||||
ChannelConnectPayload,
|
||||
ChannelValidationPayload,
|
||||
ChatSummary,
|
||||
SessionModelOptions,
|
||||
ContextGraph,
|
||||
CliAppsPayload,
|
||||
FilePreviewPayload,
|
||||
@@ -204,6 +205,7 @@ export async function listSessions(
|
||||
title?: string;
|
||||
preview?: string;
|
||||
model_preset?: string | null;
|
||||
model_options?: SessionModelOptions;
|
||||
run_started_at?: number | null;
|
||||
recovery_state?: RecoveryState | null;
|
||||
workspace_scope?: WorkspaceScopePayload | null;
|
||||
@@ -226,6 +228,7 @@ export async function listSessions(
|
||||
title: s.title ?? "",
|
||||
preview: s.preview ?? "",
|
||||
modelPreset: s.model_preset ?? null,
|
||||
modelOptions: s.model_options ?? { reasoning_effort: null, codex_fast_mode: null },
|
||||
runStartedAt: s.run_started_at ?? null,
|
||||
recoveryState: s.recovery_state ?? null,
|
||||
workspaceScope: s.workspace_scope ?? null,
|
||||
@@ -1417,7 +1420,7 @@ export async function fetchSidebarState(
|
||||
function modelGenerationSettingsPayload(
|
||||
configuration: Pick<
|
||||
ModelConfigurationCreate,
|
||||
"maxTokens" | "contextWindowTokens" | "temperature" | "reasoningEffort" | "supportsImages" | "api" | "extraHeaders" | "extraQuery" | "extraBody"
|
||||
"maxTokens" | "contextWindowTokens" | "temperature" | "reasoningEffort" | "codexFastMode" | "supportsImages" | "api" | "extraHeaders" | "extraQuery" | "extraBody"
|
||||
>,
|
||||
): Record<string, unknown> {
|
||||
const payload: Record<string, unknown> = {};
|
||||
@@ -1436,6 +1439,9 @@ function modelGenerationSettingsPayload(
|
||||
if (configuration.reasoningEffort !== undefined) {
|
||||
payload.reasoning_effort = configuration.reasoningEffort ?? "";
|
||||
}
|
||||
if (configuration.codexFastMode !== undefined) {
|
||||
payload.codex_fast_mode = configuration.codexFastMode ?? "";
|
||||
}
|
||||
if (configuration.api !== undefined) {
|
||||
payload.api = configuration.api;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import type {
|
||||
OutboundMcpPresetMention,
|
||||
OutboundMedia,
|
||||
SessionMention,
|
||||
SessionModelOptions,
|
||||
SidebarStatePayload,
|
||||
GoalStateWsPayload,
|
||||
WorkspaceScopePayload,
|
||||
@@ -288,6 +289,12 @@ export class NanobotClient {
|
||||
return this.readyChatId;
|
||||
}
|
||||
|
||||
/** Stable browser preference namespace without authentication or query parameters. */
|
||||
get preferenceScope(): string {
|
||||
const url = new URL(this.currentUrl, window.location.href);
|
||||
return `${url.protocol}//${url.host}${url.pathname}`;
|
||||
}
|
||||
|
||||
/** Swap the URL (e.g. after fetching a fresh token) then reconnect. */
|
||||
updateUrl(url: string, socketFactory?: (url: string) => WebSocket): void {
|
||||
this.currentUrl = url;
|
||||
@@ -819,6 +826,7 @@ export class NanobotClient {
|
||||
quotedContext?: string;
|
||||
intent?: "create_automation";
|
||||
userShell?: boolean;
|
||||
modelOptions?: SessionModelOptions;
|
||||
workspaceScope?: WorkspaceScopePayload | null;
|
||||
turnId?: string;
|
||||
/** False for side-channel or injected messages that do not own a lifecycle. */
|
||||
@@ -841,6 +849,8 @@ export class NanobotClient {
|
||||
...(options?.quotedContext?.trim() ? { quoted_context: options.quotedContext.trim() } : {}),
|
||||
...(options?.intent === "create_automation" ? { intent: options.intent } : {}),
|
||||
...(options?.userShell ? { user_shell: true } : {}),
|
||||
...(!temporary && !options?.userShell && options?.modelOptions
|
||||
? { model_options: options.modelOptions } : {}),
|
||||
...(options?.workspaceScope ? { workspace_scope: options.workspaceScope } : {}),
|
||||
...(options?.turnId ? { turn_id: options.turnId } : {}),
|
||||
webui: true,
|
||||
|
||||
@@ -77,3 +77,8 @@ export function getProviderModelCatalog(revision: object, token: string, provide
|
||||
}
|
||||
return catalog;
|
||||
}
|
||||
|
||||
/** Shared recommendations for both the settings picker and current-chat controls. */
|
||||
export function reasoningEffortValues(payload: ProviderModelsPayload | null, model: string, savedValues?: string[]): string[] {
|
||||
return [...new Set((payload?.models.find((entry) => entry.id === model)?.reasoning_efforts ?? savedValues ?? []).filter(Boolean))];
|
||||
}
|
||||
@@ -488,6 +488,19 @@ export interface UIFileEdit {
|
||||
diff?: UIFileDiff;
|
||||
}
|
||||
|
||||
export type CodexFastMode = boolean | "ultrafast";
|
||||
|
||||
export interface SessionModelOptions {
|
||||
/** Null explicitly inherits the preset/provider value. */
|
||||
reasoning_effort: string | null;
|
||||
codex_fast_mode: CodexFastMode | null;
|
||||
}
|
||||
|
||||
export interface ModelOptionsCapability {
|
||||
reasoning_effort: { default: string | null; values: string[] };
|
||||
codex_fast_mode?: { default: CodexFastMode; ultrafast_supported?: boolean };
|
||||
}
|
||||
|
||||
export interface ChatSummary {
|
||||
/** Server-side session key, e.g. ``websocket:abcd-...``. */
|
||||
key: string;
|
||||
@@ -500,6 +513,7 @@ export interface ChatSummary {
|
||||
preview: string;
|
||||
/** Model preset persisted for this session; null means it still follows the global default. */
|
||||
modelPreset?: string | null;
|
||||
modelOptions?: SessionModelOptions;
|
||||
/** Unix epoch seconds when this session currently has a turn in flight. */
|
||||
runStartedAt?: number | null;
|
||||
/** Durable recovery state that needs attention after an interrupted turn. */
|
||||
@@ -773,6 +787,8 @@ export interface SettingsPayload {
|
||||
temperature: number;
|
||||
reasoning_effort: string | null;
|
||||
reasoning_effort_values?: string[];
|
||||
codex_fast_mode?: CodexFastMode | null;
|
||||
model_options?: ModelOptionsCapability;
|
||||
supports_images?: boolean;
|
||||
api?: ModelAPIConfig | null;
|
||||
extra_headers?: Record<string, string> | null;
|
||||
@@ -806,6 +822,8 @@ export interface SettingsPayload {
|
||||
request_apis?: ProviderRequestAPI[];
|
||||
adapter_request_apis?: ProviderRequestAPI[];
|
||||
provider_api_configurable?: boolean;
|
||||
codex_fast_mode_supported?: boolean;
|
||||
codex_ultrafast_models?: string[];
|
||||
api?: ModelAPIConfig | null;
|
||||
oauth_account?: string | null;
|
||||
oauth_expires_at?: number | null;
|
||||
@@ -1410,6 +1428,7 @@ export interface ModelConfigurationCreate {
|
||||
contextWindowTokens?: number;
|
||||
temperature?: number;
|
||||
reasoningEffort?: string | null;
|
||||
codexFastMode?: CodexFastMode | null;
|
||||
supportsImages?: boolean;
|
||||
api?: ModelAPIConfig | null;
|
||||
extraHeaders?: string;
|
||||
@@ -1426,6 +1445,7 @@ export interface ModelConfigurationUpdate {
|
||||
contextWindowTokens?: number;
|
||||
temperature?: number;
|
||||
reasoningEffort?: string | null;
|
||||
codexFastMode?: CodexFastMode | null;
|
||||
supportsImages?: boolean;
|
||||
api?: ModelAPIConfig | null;
|
||||
extraHeaders?: string;
|
||||
@@ -1887,6 +1907,7 @@ export type Outbound =
|
||||
quoted_context?: string;
|
||||
intent?: "create_automation";
|
||||
user_shell?: true;
|
||||
model_options?: SessionModelOptions;
|
||||
workspace_scope?: WorkspaceScopePayload;
|
||||
turn_id?: string;
|
||||
/** Marks messages sent by the embedded WebUI, without changing the
|
||||
|
||||
@@ -1351,6 +1351,7 @@ describe("webui API helpers", () => {
|
||||
title: "优化 WebUI 标题",
|
||||
project_locked: projectLocked,
|
||||
model_preset: "fast",
|
||||
model_options: projectLocked ? { reasoning_effort: "high", codex_fast_mode: false } : undefined,
|
||||
run_started_at: 1_700_000_000,
|
||||
handle: {
|
||||
id: "handle_0123456789abcdef0123456789abcdef",
|
||||
@@ -1368,6 +1369,8 @@ describe("webui API helpers", () => {
|
||||
projectLocked: true,
|
||||
preview: "",
|
||||
modelPreset: "fast",
|
||||
modelOptions: projectLocked ? { reasoning_effort: "high", codex_fast_mode: false }
|
||||
: { reasoning_effort: null, codex_fast_mode: null },
|
||||
runStartedAt: 1_700_000_000,
|
||||
handle: {
|
||||
id: "handle_0123456789abcdef0123456789abcdef",
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { useState } from "react";
|
||||
import { expect, it, vi } from "vitest";
|
||||
|
||||
import { ModelOptionsControl } from "@/components/thread/ModelOptionsControl";
|
||||
import type { SessionModelOptions } from "@/lib/types";
|
||||
|
||||
function Control({ fast = true, defaultEffort = "medium", onChange }: {
|
||||
fast?: boolean;
|
||||
defaultEffort?: string | null;
|
||||
onChange?: (value: SessionModelOptions) => void;
|
||||
}) {
|
||||
const [value, setValue] = useState<SessionModelOptions>({ reasoning_effort: null, codex_fast_mode: null });
|
||||
const efforts = ["low", "medium", "high"];
|
||||
return <ModelOptionsControl data={{ value, efforts, capability: {
|
||||
reasoning_effort: { default: defaultEffort, values: efforts },
|
||||
...(fast ? { codex_fast_mode: { default: true } } : {}),
|
||||
} }} onChange={(next) => { setValue(next); onChange?.(next); }} />;
|
||||
}
|
||||
|
||||
it("preselects the actual preset values without writing them and saves a reselected value explicitly", () => {
|
||||
const onChange = vi.fn();
|
||||
render(<Control onChange={onChange} />);
|
||||
const effort = screen.getByRole("slider", { name: "Reasoning effort" });
|
||||
const fast = screen.getByRole("button", { name: "Fast" });
|
||||
expect(effort).toHaveAttribute("aria-valuetext", "medium");
|
||||
expect(fast).toHaveAttribute("aria-pressed", "true");
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
fireEvent.change(effort, { target: { value: "0" } });
|
||||
expect(effort).toHaveAttribute("aria-valuetext", "low");
|
||||
fireEvent.click(fast);
|
||||
expect(fast).toHaveAttribute("aria-pressed", "false");
|
||||
fireEvent.change(effort, { target: { value: "1" } });
|
||||
expect(onChange).toHaveBeenLastCalledWith({ reasoning_effort: "medium", codex_fast_mode: false });
|
||||
});
|
||||
|
||||
it("lets the model choose the effort when no concrete preset value is known", () => {
|
||||
const onChange = vi.fn();
|
||||
render(<Control defaultEffort={null} onChange={onChange} />);
|
||||
const effort = screen.getByRole("slider", { name: "Reasoning effort" });
|
||||
expect(effort).toHaveAttribute("aria-valuetext", "Auto");
|
||||
fireEvent.change(effort, { target: { value: "3" } });
|
||||
expect(effort).toHaveAttribute("aria-valuetext", "high");
|
||||
fireEvent.change(effort, { target: { value: "0" } });
|
||||
expect(onChange).toHaveBeenLastCalledWith({ reasoning_effort: null, codex_fast_mode: null });
|
||||
});
|
||||
|
||||
it("keeps a custom preset effort selectable without giving it a position on the scale", () => {
|
||||
const onChange = vi.fn();
|
||||
render(<Control defaultEffort="extended" onChange={onChange} />);
|
||||
const effort = screen.getByRole("combobox", { name: "Reasoning effort" });
|
||||
expect(effort).toHaveDisplayValue("extended");
|
||||
fireEvent.change(effort, { target: { value: "1" } });
|
||||
expect(effort).toHaveDisplayValue("medium");
|
||||
fireEvent.change(effort, { target: { value: "3" } });
|
||||
expect(onChange).toHaveBeenLastCalledWith({ reasoning_effort: "extended", codex_fast_mode: null });
|
||||
});
|
||||
|
||||
it("uses the capability description rather than the provider name to expose Fast mode", () => {
|
||||
render(<Control fast={false} />);
|
||||
expect(screen.getByRole("slider", { name: "Reasoning effort" })).toBeVisible();
|
||||
expect(screen.queryByRole("button", { name: "Fast" })).not.toBeInTheDocument();
|
||||
});
|
||||
@@ -70,6 +70,50 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("NanobotClient", () => {
|
||||
it.each([
|
||||
{ reasoning_effort: "high", codex_fast_mode: true },
|
||||
{ reasoning_effort: null, codex_fast_mode: false },
|
||||
{ reasoning_effort: null, codex_fast_mode: null },
|
||||
])("transmits the whole model option selection without dropping false or null: %j", (modelOptions) => {
|
||||
const client = new NanobotClient({ url: "ws://test", reconnect: false,
|
||||
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
|
||||
client.connect();
|
||||
const socket = lastSocket();
|
||||
socket.fakeOpen();
|
||||
client.sendMessage("chat", "normal message", undefined, { modelOptions });
|
||||
expect(JSON.parse(socket.sent.at(-1)!)).toMatchObject({ type: "message", model_options: modelOptions });
|
||||
client.sendMessage("chat", "keep saved options");
|
||||
expect(JSON.parse(socket.sent.at(-1)!)).not.toHaveProperty("model_options");
|
||||
client.close();
|
||||
});
|
||||
|
||||
it("omits model options for Temporary Chats and shell commands", async () => {
|
||||
const client = new NanobotClient({ url: "ws://test", reconnect: false,
|
||||
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
|
||||
client.connect();
|
||||
const socket = lastSocket();
|
||||
socket.fakeOpen();
|
||||
const created = client.newTemporaryChat();
|
||||
socket.fakeMessage({ event: "attached", chat_id: "temporary-options", temporary: true, request_id: lastRequestId(socket) });
|
||||
await created;
|
||||
const modelOptions = { reasoning_effort: "high", codex_fast_mode: true };
|
||||
client.sendMessage("temporary-options", "temporary message", undefined, { modelOptions });
|
||||
expect(JSON.parse(socket.sent.at(-1)!)).not.toHaveProperty("model_options");
|
||||
client.sendMessage("regular", "pwd", undefined, { modelOptions, userShell: true });
|
||||
expect(JSON.parse(socket.sent.at(-1)!)).toMatchObject({ user_shell: true });
|
||||
expect(JSON.parse(socket.sent.at(-1)!)).not.toHaveProperty("model_options");
|
||||
client.close();
|
||||
});
|
||||
|
||||
it("uses a stable host/path preference scope across token refresh, including custom host transports", () => {
|
||||
const client = new NanobotClient({ url: "ws://host/ws?token=secret", reconnect: false });
|
||||
expect(client.preferenceScope).toBe("ws://host/ws");
|
||||
client.updateUrl("ws://host/ws?token=refreshed");
|
||||
expect(client.preferenceScope).toBe("ws://host/ws");
|
||||
client.updateUrl("nanobot-host://other-host/events?token=secret");
|
||||
expect(client.preferenceScope).toBe("nanobot-host://other-host/events");
|
||||
});
|
||||
|
||||
const chatRequests = [
|
||||
{ type: "new_chat", start: (client: NanobotClient, timeout: number) => client.newChat(timeout) },
|
||||
{ type: "new_temporary_chat", start: (client: NanobotClient, timeout: number) => client.newTemporaryChat(timeout) },
|
||||
|
||||
@@ -304,6 +304,31 @@ describe("Settings models", () => {
|
||||
));
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ model: "gpt-5.6-sol", label: "Off", modeValue: false },
|
||||
{ model: "openai-codex/gpt-6.2-sol", label: "Ultrafast", modeValue: "ultrafast" },
|
||||
])("saves $label for the Codex preset without editing its connection", async ({ model, label, modeValue }) => {
|
||||
const payload = settingsPayload();
|
||||
payload.providers = [{ name: "openai_codex", label: "Codex", configured: true, codex_fast_mode_supported: true,
|
||||
codex_ultrafast_models: ["gpt-6.2-sol"], extra_body: { service_tier: "priority" } }];
|
||||
Object.assign(payload.model_presets[0], {
|
||||
provider: "openai_codex", resolved_provider: "openai_codex", model, codex_fast_mode: null,
|
||||
});
|
||||
requestMutationMock.mockResolvedValue(payload);
|
||||
renderSettingsView({ initialSection: "models", initialSettings: payload });
|
||||
fireEvent.click(await screen.findByRole("button", { name: /primary/i }));
|
||||
const mode = within(screen.getByRole("group", { name: "Fast" }));
|
||||
const fast = mode.getByRole("button", { name: /^Fast$/ });
|
||||
expect(fast).toHaveAttribute("aria-pressed", "true");
|
||||
expect(requestMutationMock).not.toHaveBeenCalled();
|
||||
if (modeValue === false) expect(mode.queryByRole("button", { name: "Ultrafast" })).not.toBeInTheDocument();
|
||||
fireEvent.click(modeValue === false ? fast : mode.getByRole("button", { name: label }));
|
||||
fireEvent.click(presetSaveButton());
|
||||
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
|
||||
"settings.model_configuration.update", { include_usage: false, name: "primary", codex_fast_mode: modeValue }, 20_000,
|
||||
));
|
||||
});
|
||||
|
||||
it("shows the host's automatic API and discards an older reasoning resolution", async () => {
|
||||
const payload = settingsPayload();
|
||||
payload.model_api_resolution_supported = true;
|
||||
|
||||
@@ -945,7 +945,7 @@ describe("Settings providers", () => {
|
||||
await waitFor(() => expect(screen.getByRole("dialog", { name: "Manage providers" })).toBeVisible());
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "OpenAI Codex" }));
|
||||
fireEvent.click(screen.getByRole("switch", { name: "Fast mode" }));
|
||||
fireEvent.click(screen.getByRole("switch", { name: "Fast" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Save provider" }));
|
||||
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
|
||||
"settings.provider.update",
|
||||
|
||||
@@ -66,6 +66,7 @@ function makeClient() {
|
||||
return status;
|
||||
},
|
||||
defaultChatId: null as string | null,
|
||||
preferenceScope: lifecycle.preferenceScope,
|
||||
onStatus: (handler: (nextStatus: ConnectionStatus) => void) => {
|
||||
statusHandlers.add(handler);
|
||||
handler(status);
|
||||
@@ -466,6 +467,87 @@ function settingsWithFastPreset(): SettingsPayload {
|
||||
}
|
||||
|
||||
describe("ThreadShell", () => {
|
||||
function optionsSettings() {
|
||||
const settings = settingsWithFastPreset();
|
||||
for (const preset of settings.model_presets) preset.model_options = {
|
||||
reasoning_effort: { default: "low", values: ["low", "high"] }, codex_fast_mode: { default: true },
|
||||
};
|
||||
settings.providers = settings.providers.map((provider) => ({ ...provider, model_catalog: "unsupported" }));
|
||||
return settings;
|
||||
}
|
||||
|
||||
async function changeOptions() {
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Default" }));
|
||||
fireEvent.change(screen.getByRole("slider", { name: "Reasoning effort" }), { target: { value: "1" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Fast" }));
|
||||
fireEvent.keyDown(screen.getByRole("dialog", { name: "Switch model" }), { key: "Escape" });
|
||||
}
|
||||
|
||||
it("keeps model option choices local until sending, includes explicit false, and clears them on preset switch", async () => {
|
||||
localStorage.clear();
|
||||
const client = makeClient();
|
||||
render(wrap(client, <ThreadShell session={session("model-options")} title="Options" onToggleSidebar={() => {}}
|
||||
settingsSnapshot={optionsSettings()} />, null, "tok", ["webui.model-options.v1"]));
|
||||
await changeOptions();
|
||||
expect(client.sendMessage).not.toHaveBeenCalled();
|
||||
expect(client.sendSystemCommand).not.toHaveBeenCalled();
|
||||
fireEvent.change(screen.getByLabelText("Message input"), { target: { value: "selected options" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
|
||||
await waitFor(() => expect(client.sendMessage).toHaveBeenCalledWith("model-options", "selected options", undefined,
|
||||
expect.objectContaining({ modelOptions: { reasoning_effort: "high", codex_fast_mode: false } })));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Default" }));
|
||||
fireEvent.click(await screen.findByRole("option", { name: "fast" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "fast" }));
|
||||
expect(screen.getByRole("slider", { name: "Reasoning effort" })).toHaveAttribute("aria-valuetext", "low");
|
||||
expect(screen.getByRole("button", { name: "Fast" })).toHaveAttribute("aria-pressed", "true");
|
||||
expect(client.sendSystemCommand).toHaveBeenCalledWith("model-options", "/model fast");
|
||||
expect(client.sendMessage).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("sends and migrates the landing selection with the first ordinary message", async () => {
|
||||
localStorage.clear();
|
||||
const client = makeClient();
|
||||
const settings = optionsSettings();
|
||||
const view = (currentSession: ReturnType<typeof session> | null) => wrap(client, <ThreadShell session={currentSession}
|
||||
title="Options" onToggleSidebar={() => {}} settingsSnapshot={settings} onCreateChat={async () => "options-created"} />,
|
||||
null, "tok", ["webui.model-options.v1"]);
|
||||
const rendered = render(view(null));
|
||||
await changeOptions();
|
||||
fireEvent.change(screen.getByLabelText("Message input"), { target: { value: "first selection" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
|
||||
await act(async () => {});
|
||||
rendered.rerender(view(session("options-created")));
|
||||
await waitFor(() => expect(client.sendMessage).toHaveBeenCalledWith("options-created", "first selection", undefined,
|
||||
expect.objectContaining({ modelOptions: { reasoning_effort: "high", codex_fast_mode: false } })));
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Default" }));
|
||||
expect(screen.getByRole("slider", { name: "Reasoning effort" })).toHaveAttribute("aria-valuetext", "high");
|
||||
expect(screen.getByRole("button", { name: "Fast" })).toHaveAttribute("aria-pressed", "false");
|
||||
});
|
||||
|
||||
it("sends edited queued prompts using current options, while cancelling the queue sends nothing", async () => {
|
||||
localStorage.clear();
|
||||
const client = makeClient();
|
||||
const chatId = "options-queue";
|
||||
render(wrap(client, <ThreadShell session={session(chatId)} title="Options" onToggleSidebar={() => {}}
|
||||
settingsSnapshot={optionsSettings()} />, null, "tok", ["webui.model-options.v1"]));
|
||||
await screen.findByLabelText("Message input");
|
||||
act(() => client._emitChat(chatId, { event: "goal_status", chat_id: chatId, turn_id: "owner", status: "running", started_at: 1_000 }));
|
||||
const input = screen.getByLabelText("Message input");
|
||||
fireEvent.change(input, { target: { value: "queued options" } });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Delete message" }));
|
||||
expect(client.sendMessage).not.toHaveBeenCalled();
|
||||
fireEvent.change(input, { target: { value: "queued options again" } });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
await changeOptions();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Edit message" }));
|
||||
fireEvent.change(input, { target: { value: "edited options" } });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send now" }));
|
||||
await waitFor(() => expect(client.sendMessage).toHaveBeenCalledWith(chatId, "edited options", undefined,
|
||||
expect.objectContaining({ modelOptions: { reasoning_effort: "high", codex_fast_mode: false } })));
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
webuiThreadCache.clear();
|
||||
clearStoredComposerDrafts();
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
import { act, renderHook, waitFor } from "@testing-library/react";
|
||||
import type { ReactNode } from "react";
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
|
||||
import { useSessionModelOptions } from "@/hooks/useSessionModelOptions";
|
||||
import * as api from "@/lib/api";
|
||||
import { NanobotClient } from "@/lib/nanobot-client";
|
||||
import { reasoningEffortValues } from "@/lib/provider-model-catalog";
|
||||
import type { ProviderModelsPayload, SessionModelOptions, SettingsPayload } from "@/lib/types";
|
||||
import { ClientProvider } from "@/providers/ClientProvider";
|
||||
import { settingsPayload } from "./settings-test-utils";
|
||||
|
||||
vi.mock("@/lib/api", () => ({ fetchProviderModels: vi.fn() }));
|
||||
const inherit: SessionModelOptions = { reasoning_effort: null, codex_fast_mode: null };
|
||||
const chosen: SessionModelOptions = { reasoning_effort: "max", codex_fast_mode: false };
|
||||
const payload: ProviderModelsPayload = {
|
||||
provider: "custom", label: "Custom", status: "available", catalog_kind: "official", model_count: 1, source: "remote",
|
||||
models: [{ id: "openai/gpt-4o", reasoning_efforts: ["none", "low", "max"] }],
|
||||
};
|
||||
function props() {
|
||||
const settings = settingsPayload();
|
||||
settings.providers = [{ name: "custom", label: "Custom", configured: true }];
|
||||
settings.model_presets[0].resolved_provider = "custom";
|
||||
settings.model_presets[0].model_options = {
|
||||
reasoning_effort: { default: "low", values: ["low", "high"] }, codex_fast_mode: { default: true },
|
||||
};
|
||||
return { sessionKey: "websocket:a" as string | null, preset: "primary", settings, open: false, disabled: false,
|
||||
storedValue: undefined as SessionModelOptions | undefined };
|
||||
}
|
||||
function wrapper(connection = { client: new NanobotClient({ url: "ws://host-a/ws?token=old", reconnect: false }), token: "old" }, enabled = true) {
|
||||
return ({ children }: { children: ReactNode }) => <ClientProvider client={connection.client} token={connection.token}
|
||||
webuiCapabilities={enabled ? ["webui.model-options.v1"] : []}>{children}</ClientProvider>;
|
||||
}
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.mocked(api.fetchProviderModels).mockReset().mockResolvedValue(payload);
|
||||
});
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it("shares lazy settings recommendations and uses backend capability descriptions for custom providers", async () => {
|
||||
const initial = props();
|
||||
const view = renderHook(useSessionModelOptions, { wrapper: wrapper(), initialProps: initial });
|
||||
expect(api.fetchProviderModels).not.toHaveBeenCalled();
|
||||
expect(view.result.current.data?.efforts).toEqual(["low", "high"]);
|
||||
expect(view.result.current.data?.capability.codex_fast_mode?.default).toBe(true);
|
||||
view.rerender({ ...initial, open: true });
|
||||
await waitFor(() => expect(view.result.current.data?.efforts).toEqual(reasoningEffortValues(payload, initial.settings.agent.model)));
|
||||
expect(view.result.current.data?.value).toEqual(inherit);
|
||||
expect(view.result.current.sendValue()).toBeUndefined();
|
||||
});
|
||||
|
||||
it("coalesces browser writes, immediately transmits false/null, and flushes pagehide without gateway mutations", () => {
|
||||
const view = renderHook(useSessionModelOptions, { wrapper: wrapper(), initialProps: props() });
|
||||
const mutation = vi.spyOn(NanobotClient.prototype, "requestMutation");
|
||||
const storage = vi.spyOn(localStorage, "setItem");
|
||||
vi.useFakeTimers();
|
||||
act(() => { view.result.current.select(chosen); view.result.current.select({ ...chosen, reasoning_effort: null }); });
|
||||
expect(view.result.current.sendValue()).toEqual({ reasoning_effort: null, codex_fast_mode: false });
|
||||
expect(storage).not.toHaveBeenCalled();
|
||||
act(() => vi.advanceTimersByTime(250));
|
||||
expect(storage).toHaveBeenCalledTimes(1);
|
||||
expect(JSON.parse(storage.mock.calls[0][1])).toEqual({ preset: "primary", options: { reasoning_effort: null, codex_fast_mode: false } });
|
||||
act(() => view.result.current.select(inherit));
|
||||
act(() => window.dispatchEvent(new Event("pagehide")));
|
||||
expect(storage).toHaveBeenCalledTimes(2);
|
||||
expect(mutation).not.toHaveBeenCalled();
|
||||
storage.mockRestore(); mutation.mockRestore();
|
||||
});
|
||||
|
||||
it("reloads unsent preferences across token renewal and isolates hosts and sessions including rapid switches", () => {
|
||||
const connection = { client: new NanobotClient({ url: "ws://host-a/ws?token=old", reconnect: false }), token: "old" };
|
||||
const initial = props();
|
||||
const view = renderHook(useSessionModelOptions, { wrapper: wrapper(connection), initialProps: initial });
|
||||
act(() => view.result.current.select(chosen));
|
||||
connection.token = "renewed";
|
||||
connection.client.updateUrl("ws://host-a/ws?token=renewed");
|
||||
view.rerender({ ...initial });
|
||||
expect(view.result.current.sendValue()).toEqual(chosen);
|
||||
view.rerender({ ...initial, sessionKey: "websocket:b", storedValue: { reasoning_effort: "low", codex_fast_mode: true } });
|
||||
expect(view.result.current.data?.value).toEqual({ reasoning_effort: "low", codex_fast_mode: true });
|
||||
expect(view.result.current.sendValue()).toBeUndefined();
|
||||
act(() => view.result.current.select(inherit));
|
||||
view.rerender(initial);
|
||||
expect(view.result.current.sendValue()).toEqual(chosen);
|
||||
connection.client.updateUrl("ws://host-b/ws");
|
||||
view.rerender({ ...initial });
|
||||
expect(view.result.current.data?.value).toEqual(inherit);
|
||||
expect(view.result.current.sendValue()).toBeUndefined();
|
||||
connection.client.updateUrl("ws://host-a/ws?token=again");
|
||||
view.unmount();
|
||||
const reloaded = renderHook(useSessionModelOptions, { wrapper: wrapper(connection), initialProps: initial });
|
||||
expect(reloaded.result.current.sendValue()).toEqual(chosen);
|
||||
reloaded.rerender({ ...initial, sessionKey: "websocket:b" });
|
||||
expect(reloaded.result.current.sendValue()).toEqual(inherit);
|
||||
});
|
||||
|
||||
it("waits for settings before reconciling a reloaded browser preference with the active preset", () => {
|
||||
const initial = props();
|
||||
const key = 'nanobot.model-options.v1.["ws://host-a/ws","websocket:a"]';
|
||||
const saved = JSON.stringify({ preset: initial.preset, options: chosen });
|
||||
localStorage.setItem(key, saved);
|
||||
const view = renderHook(useSessionModelOptions, { wrapper: wrapper(), initialProps: {
|
||||
...initial, preset: "default", settings: null as SettingsPayload | null,
|
||||
} });
|
||||
expect(view.result.current.sendValue()).toBeUndefined();
|
||||
act(() => window.dispatchEvent(new Event("pagehide")));
|
||||
expect(localStorage.getItem(key)).toBe(saved);
|
||||
view.rerender(initial);
|
||||
expect(view.result.current.sendValue()).toEqual(chosen);
|
||||
expect(view.result.current.data?.value).toEqual(chosen);
|
||||
view.unmount();
|
||||
expect(localStorage.getItem(key)).toBe(saved);
|
||||
});
|
||||
|
||||
it("shows the Gateway's last-used options after a preset rename without sending a replacement", () => {
|
||||
const initial = props();
|
||||
const wrap = wrapper();
|
||||
const storedValue: SessionModelOptions = { reasoning_effort: "high", codex_fast_mode: "ultrafast" };
|
||||
const previous = renderHook(useSessionModelOptions, { wrapper: wrap, initialProps: initial });
|
||||
act(() => previous.result.current.select(storedValue));
|
||||
previous.unmount();
|
||||
|
||||
initial.settings.model_presets[0].name = "renamed";
|
||||
const renamed = { ...initial, preset: "renamed", storedValue };
|
||||
const reopened = renderHook(useSessionModelOptions, { wrapper: wrap, initialProps: renamed });
|
||||
expect(reopened.result.current.data?.value).toEqual(storedValue);
|
||||
expect(reopened.result.current.sendValue()).toBeUndefined();
|
||||
reopened.unmount();
|
||||
|
||||
const reloaded = renderHook(useSessionModelOptions, { wrapper: wrap, initialProps: renamed });
|
||||
expect(reloaded.result.current.data?.value).toEqual(storedValue);
|
||||
expect(reloaded.result.current.sendValue()).toBeUndefined();
|
||||
});
|
||||
|
||||
it("migrates a draft snapshot to the first session, clears both choices on preset switch, and clears the draft", () => {
|
||||
const initial = { ...props(), sessionKey: null as string | null };
|
||||
const wrap = wrapper();
|
||||
const view = renderHook(useSessionModelOptions, { wrapper: wrap, initialProps: initial });
|
||||
act(() => view.result.current.select(chosen));
|
||||
act(() => view.result.current.moveToSession("websocket:created", chosen));
|
||||
view.rerender({ ...initial, sessionKey: "websocket:created" });
|
||||
expect(view.result.current.sendValue()).toEqual(chosen);
|
||||
// ThreadShell resets options and selects the preset in the same action.
|
||||
act(() => {
|
||||
view.result.current.reset("other");
|
||||
view.rerender({ ...initial, sessionKey: "websocket:created", preset: "other" });
|
||||
});
|
||||
expect(view.result.current.sendValue()).toEqual(inherit);
|
||||
act(() => {
|
||||
view.result.current.reset("primary");
|
||||
view.rerender({ ...initial, sessionKey: "websocket:created" });
|
||||
});
|
||||
expect(view.result.current.sendValue()).toEqual(inherit);
|
||||
view.unmount();
|
||||
const landing = renderHook(useSessionModelOptions, { wrapper: wrap, initialProps: initial });
|
||||
expect(landing.result.current.data?.value).toEqual(inherit);
|
||||
expect(landing.result.current.sendValue()).toBeUndefined();
|
||||
});
|
||||
|
||||
it("preserves newer target choices made while draft creation was pending", () => {
|
||||
const initial = { ...props(), sessionKey: null as string | null };
|
||||
const view = renderHook(useSessionModelOptions, { wrapper: wrapper(), initialProps: initial });
|
||||
act(() => view.result.current.select(chosen));
|
||||
const transfer = view.result.current.moveToSession;
|
||||
view.rerender({ ...initial, sessionKey: "websocket:created" });
|
||||
const newer = { reasoning_effort: "low", codex_fast_mode: true };
|
||||
act(() => view.result.current.select(newer));
|
||||
act(() => transfer("websocket:created", chosen));
|
||||
expect(view.result.current.sendValue()).toEqual(newer);
|
||||
});
|
||||
|
||||
it.each(["temporary", "unsupported"])("hides and omits options for %s chats", (mode) => {
|
||||
const view = renderHook(useSessionModelOptions, { wrapper: wrapper(undefined, mode !== "unsupported"),
|
||||
initialProps: { ...props(), disabled: mode === "temporary" } });
|
||||
act(() => view.result.current.select(chosen));
|
||||
expect(view.result.current.data).toBeNull();
|
||||
expect(view.result.current.sendValue()).toBeUndefined();
|
||||
expect(localStorage.length).toBe(0);
|
||||
expect(api.fetchProviderModels).not.toHaveBeenCalled();
|
||||
});
|
||||
Reference in new issue
Block a user