-
-
Notifications
You must be signed in to change notification settings - Fork 6.9k
Expand file tree
/
Copy pathchat-settings-sheet.tsx
More file actions
2231 lines (2165 loc) · 85.2 KB
/
Copy pathchat-settings-sheet.tsx
File metadata and controls
2231 lines (2165 loc) · 85.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import {
Alert,
AlertDescription,
AlertTitle,
} from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
clearRememberedLoadSettings,
loadRememberedLoadSettings,
rememberedLoadSettingsKey,
saveRememberedLoadSettings,
} from "@/components/assistant-ui/model-selector/remembered-load-settings";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import {
InputGroup,
InputGroupAddon,
InputGroupInput,
} from "@/components/ui/input-group";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet";
import { Slider } from "@/components/ui/slider";
import { Spinner } from "@/components/ui/spinner";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { InfoHint } from "@/components/ui/info-hint";
import { Tooltip, TooltipContent } from "@/components/ui/tooltip";
import { useIsMobile } from "@/hooks/use-mobile";
import { useLlamaUpdateCheck } from "@/hooks/use-llama-update-check";
import { cn } from "@/lib/utils";
import {
ArrowTurnBackwardIcon,
Edit03Icon,
LayoutAlignRightIcon,
} from "@hugeicons/core-free-icons";
import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { Braces, ChevronDown, ExternalLink } from "lucide-react";
import { Tooltip as TooltipPrimitive } from "radix-ui";
import { Fragment, type ReactNode } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { toast } from "@/lib/toast";
import { OpenAICodeExecSection } from "./components/openai-code-exec-section";
import { PermissionModeDropdown } from "./permission-mode-select";
import { resyncInferenceStatusAfterServerModelChange } from "./hooks/use-chat-model-runtime";
import {
type ExternalProviderConfig,
getExternalProviderApiKey,
parseExternalModelId,
supportsProviderPromptCaching,
supportsProviderPromptCacheTtl,
} from "./external-providers";
import {
BUILTIN_PRESETS,
BUILTIN_PRESET_NAMES,
applyPresetParams,
getBuiltinVariantName,
getOrderedPresets,
getPresetSaveState,
getPresetSource,
isSamePresetConfig,
toPresetParams,
} from "./presets/preset-policy";
import {
type ProviderCapabilities,
getExternalMaxOutputTokens,
getExternalMinOutputTokens,
providerSupportsBuiltinCodeExecution,
providerSupportsFastMode,
} from "./provider-capabilities";
import {
isPendingGguf,
pendingSelectionMatches,
useChatRuntimeStore,
} from "./stores/chat-runtime-store";
import { RetrievalSettingsSection } from "@/features/rag/components/retrieval-settings-section";
import type { InferenceParams } from "./types/runtime";
export { defaultInferenceParams, type Preset } from "./presets/preset-policy";
export type { InferenceParams } from "./types/runtime";
const PROMPT_VARIABLE_PATTERN = /{{\s*[a-zA-Z_$][a-zA-Z0-9_$.-]*\s*}}/;
function canUseStorage(): boolean {
return typeof window !== "undefined";
}
function getPromptVariablesError(raw: string): string | null {
const trimmed = raw.trim();
if (!trimmed) {
return null;
}
try {
const parsed = JSON.parse(trimmed) as unknown;
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
return null;
}
} catch {
return "Use valid JSON, for example { \"env\": \"staging\" }.";
}
return "Variables must be a JSON object.";
}
function hasPromptVariableSyntax(prompt: string): boolean {
return PROMPT_VARIABLE_PATTERN.test(prompt);
}
/**
* Editable numeric value display, shared by every slider value and the Context
* Length input. An <input> that looks like text (shows `displayValue ?? value`,
* so "Off"/"Max" labels render) until focus, when it swaps to the raw number,
* selects it, and accepts free text. Commits on blur/Enter, reverts on Escape.
* Clamping happens on commit so typing intermediate values isn't fought.
*/
function snapToStep(
value: number,
step: number,
min?: number,
max?: number,
): number {
const lo = min ?? Number.NEGATIVE_INFINITY;
const hi = max ?? Number.POSITIVE_INFINITY;
const clamped = Math.min(Math.max(value, lo), hi);
const stepStr = String(step);
const decimals = stepStr.includes(".") ? stepStr.split(".")[1].length : 0;
const base = Number.isFinite(lo) ? lo : 0;
const snapped = base + Math.round((clamped - base) / step) * step;
const reclamped = Math.min(Math.max(snapped, lo), hi);
return Number(reclamped.toFixed(decimals));
}
function NumericValueInput({
value,
min,
max,
step,
onChange,
displayValue,
className,
ariaLabel,
size: sizeAttr,
disabled = false,
}: {
value: number;
min?: number;
max?: number;
step: number;
onChange: (v: number) => void;
displayValue?: string;
className?: string;
ariaLabel?: string;
size?: number;
disabled?: boolean;
}) {
const [focused, setFocused] = useState(false);
const [draft, setDraft] = useState("");
const cancelBlurCommitRef = useRef(false);
const commit = (raw: string) => {
const parsed = Number.parseFloat(raw);
if (!Number.isFinite(parsed)) {
return;
}
const final = snapToStep(parsed, step, min, max);
if (final !== value) {
onChange(final);
}
};
const displayed = focused ? draft : (displayValue ?? String(value));
return (
<input
type="text"
inputMode="decimal"
disabled={disabled}
size={sizeAttr}
/* Fixed 4ch pill; grows only when a longer value would clip. */
style={{ width: `calc(${Math.max(displayed.length, 4)}ch + 18px)` }}
value={displayed}
aria-label={ariaLabel}
onFocus={(e) => {
cancelBlurCommitRef.current = false;
setDraft(String(value));
setFocused(true);
// Defer select() so it runs after the value swap above.
const target = e.currentTarget;
requestAnimationFrame(() => target.select());
}}
onBlur={() => {
if (cancelBlurCommitRef.current) {
cancelBlurCommitRef.current = false;
} else {
commit(draft);
}
setFocused(false);
}}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.currentTarget.blur();
} else if (e.key === "Escape") {
cancelBlurCommitRef.current = true;
setDraft(String(value));
e.currentTarget.blur();
}
}}
className={cn("panel-number-input", className)}
/>
);
}
function ParamSlider({
label,
value,
min,
max,
step,
onChange,
displayValue,
info,
valueSize,
}: {
label: string;
value: number;
min: number;
max: number;
step: number;
onChange: (v: number) => void;
displayValue?: string;
info?: ReactNode;
valueSize?: number;
}) {
return (
<div className="space-y-3.5">
<div className="flex items-center justify-between gap-3">
<div className="flex min-w-0 items-center gap-1.5">
<span className="min-w-0 text-[13px] font-medium leading-[1.25] tracking-nav text-nav-fg">
{label}
</span>
{info && <InfoHint>{info}</InfoHint>}
</div>
<NumericValueInput
value={value}
min={min}
max={max}
step={step}
onChange={onChange}
displayValue={displayValue}
ariaLabel={label}
size={valueSize ?? 4}
/>
</div>
<Slider
min={min}
max={max}
step={step}
value={[value]}
onValueChange={([v]) => onChange(snapToStep(v, step, min, max))}
className="panel-slider"
/>
</div>
);
}
const COLLAPSIBLE_STATE_KEY = "unsloth_chat_collapsible_state";
function loadCollapsibleState(): Record<string, boolean> {
if (!canUseStorage()) return {};
try {
const raw = localStorage.getItem(COLLAPSIBLE_STATE_KEY);
if (!raw) return {};
const parsed = JSON.parse(raw);
if (
typeof parsed !== "object" ||
parsed === null ||
Array.isArray(parsed)
) {
return {};
}
return Object.fromEntries(
Object.entries(parsed).filter(
(entry): entry is [string, boolean] => typeof entry[1] === "boolean",
),
);
} catch (error) {
console.warn("Failed to load collapsible state from localStorage:", error);
return {};
}
}
function saveCollapsibleOpen(label: string, open: boolean) {
if (!canUseStorage()) return;
try {
const state = loadCollapsibleState();
state[label] = open;
localStorage.setItem(COLLAPSIBLE_STATE_KEY, JSON.stringify(state));
} catch {
// ignore
}
}
function CollapsibleSection({
label,
labelHref,
headerAction,
onLabelClick,
children,
defaultOpen = false,
first = false,
}: {
label: string;
/**
* When set, the label becomes an external link (e.g. the feature's GitHub PR)
* instead of part of the toggle. The chevron still toggles, so link and button
* are siblings rather than an <a> nested in a <button> (invalid HTML).
*/
labelHref?: string;
/**
* Optional control rendered before the chevron (e.g. an edit icon). The
* label and chevron become sibling toggles so the action is not a button
* nested in a button.
*/
headerAction?: ReactNode;
/** When set, clicking the label runs this instead of toggling collapse. */
onLabelClick?: () => void;
children?: ReactNode;
defaultOpen?: boolean;
first?: boolean;
}) {
const [open, setOpen] = useState(() => {
const saved = loadCollapsibleState();
return Object.hasOwn(saved, label) ? saved[label] : defaultOpen;
});
const toggle = () => {
const next = !open;
setOpen(next);
saveCollapsibleOpen(label, next);
};
const headerClasses = cn(
"flex w-full items-center justify-between text-[12px] font-medium normal-case tracking-[0.04em] text-nav-fg-muted transition-colors focus-visible:outline-none focus-visible:ring-0",
first ? "pt-4 pb-5" : "py-5",
);
return (
<div
className={cn(
!first &&
"border-t border-black/[0.13] dark:border-white/[0.09]",
)}
>
{labelHref ? (
<div className={headerClasses}>
<a
href={labelHref}
target="_blank"
rel="noopener noreferrer"
className="inline-flex cursor-pointer items-center gap-1 leading-none transition-colors hover:text-nav-fg"
>
<span>{label}</span>
<ExternalLink className="size-3" />
</a>
<button
type="button"
onClick={toggle}
aria-label={open ? `Collapse ${label}` : `Expand ${label}`}
className="flex shrink-0 cursor-pointer items-center leading-none transition-colors hover:text-nav-fg"
>
<ChevronDown
className={cn("size-3.5", open ? "rotate-0" : "-rotate-90")}
/>
</button>
</div>
) : headerAction ? (
<div className={headerClasses}>
<button
type="button"
onClick={onLabelClick ?? toggle}
className="flex min-w-0 flex-1 cursor-pointer items-center text-left leading-none transition-colors hover:text-nav-fg"
>
<span className="leading-none">{label}</span>
</button>
<span className="flex shrink-0 items-center gap-1">
{headerAction}
<button
type="button"
onClick={toggle}
aria-label={open ? `Collapse ${label}` : `Expand ${label}`}
className="flex shrink-0 cursor-pointer items-center leading-none transition-colors hover:text-nav-fg"
>
<ChevronDown
className={cn("size-3.5", open ? "rotate-0" : "-rotate-90")}
/>
</button>
</span>
</div>
) : (
<button
type="button"
onClick={toggle}
className={cn("cursor-pointer hover:text-nav-fg", headerClasses)}
>
<span className="leading-none">{label}</span>
<span className="flex shrink-0 items-center leading-none">
<ChevronDown
className={cn("size-3.5", open ? "rotate-0" : "-rotate-90")}
/>
</span>
</button>
)}
{open && <div className="pb-7">{children}</div>}
</div>
);
}
interface ChatSettingsPanelProps {
open: boolean;
onOpenChange?: (open: boolean) => void;
params: InferenceParams;
onParamsChange: (params: InferenceParams) => void;
isExternalModel?: boolean;
/**
* Sampling-param capabilities for the active external provider, or `null` for
* local models (every knob rendered). Drives per-param sampling visibility.
*/
providerCapabilities?: ProviderCapabilities | null;
activeExternalProvider?: ExternalProviderConfig | null;
onExternalProviderChange?: (provider: ExternalProviderConfig) => void;
/**
* Backend provider type for the active external model (e.g. "kimi",
* "anthropic", "openai"), or `null` for local models. Drives the per-provider
* Max Tokens floor in the slider.
*/
externalProviderType?: string | null;
onReloadModel?: () => void;
/** The in-flight load (id + GGUF variant + native path token), or null when
* idle. Used to show a loading state for the staged pick only — not for an
* unrelated load or a cancel's background unload. */
loadingModel?: {
id: string;
ggufVariant?: string | null;
nativePathToken?: string | null;
} | null;
/** Loads the staged `pendingSelection` (deferred "Load on selection" flow). */
onLoadPendingModel?: () => void;
/** Download progress (0–1) for a staged GGUF being fetched, or null when idle. */
stagedDownloadFraction?: number | null;
/** Cancels the in-flight staged download (paired with abandoning the stage). */
onCancelStagedDownload?: () => void;
}
export function ChatSettingsPanel({
open,
onOpenChange,
params,
onParamsChange,
isExternalModel = false,
providerCapabilities = null,
activeExternalProvider = null,
onExternalProviderChange,
externalProviderType = null,
onReloadModel,
loadingModel = null,
onLoadPendingModel,
stagedDownloadFraction,
onCancelStagedDownload,
}: ChatSettingsPanelProps) {
// Local models show every knob; providerCapabilities is only consulted when
// isExternalModel. Unknown providers fall back to the OpenAI-compat shape via
// getProviderCapabilities, so these flags never undercount support.
const showTemperature =
!isExternalModel || Boolean(providerCapabilities?.temperature);
const showTopP = !isExternalModel || Boolean(providerCapabilities?.topP);
const showTopK = !isExternalModel || Boolean(providerCapabilities?.topK);
const showMinP = !isExternalModel || Boolean(providerCapabilities?.minP);
const showRepetitionPenalty =
!isExternalModel || Boolean(providerCapabilities?.repetitionPenalty);
const showPresencePenalty =
!isExternalModel || Boolean(providerCapabilities?.presencePenalty);
const isMobile = useIsMobile();
const pendingSelection = useChatRuntimeStore((s) => s.pendingSelection);
// "Loading" only when the in-flight load IS this staged pick (full id + GGUF
// variant + native token match), not an unrelated load or a cancel's
// background unload. The variant matters: a different quant of the same repo
// staged mid-load must not read as this one loading.
const stagedLoading =
loadingModel != null &&
pendingSelectionMatches(pendingSelection, {
id: loadingModel.id,
ggufVariant: loadingModel.ggufVariant,
nativePathToken: loadingModel.nativePathToken,
});
// Load settings are snapshotted at click time; lock them while loading.
const modelControlsDisabled = stagedLoading;
const abandonStagedModel = useChatRuntimeStore((s) => s.abandonStagedModel);
const resetModelSettingsToLoaded = useChatRuntimeStore(
(s) => s.resetModelSettingsToLoaded,
);
// A staged GGUF pick (deferred load) shows the GGUF load knobs so they can be
// set before the single load.
const pendingIsGguf = isPendingGguf(pendingSelection);
// Short, human-readable name for the staged pick (HF ids carry an org prefix;
// native picks are already a display label). Drives the "staged, not loaded"
// callout so it's obvious the selection hasn't loaded yet.
const stagedLabel = (() => {
const id = pendingSelection?.id ?? "";
const slash = id.lastIndexOf("/");
const base = slash >= 0 ? id.slice(slash + 1) : id;
return base || id;
})();
const isLoadedGguf =
useChatRuntimeStore((s) => s.activeGgufVariant) != null;
// While a pick is staged the sheet configures *that* model, so its GGUF-ness
// (not the currently loaded model's) decides whether the GGUF-only controls
// show. Otherwise a staged non-GGUF Hub repo would inherit the loaded GGUF's
// context/KV/speculative controls.
const isGguf = pendingSelection != null ? pendingIsGguf : isLoadedGguf;
// The Model section (and Load button) shows for any staged pick, even when the
// currently active model is external.
const hasModelContent =
pendingSelection != null ||
(!isExternalModel && (isGguf || Boolean(params.checkpoint)));
const speculativeType = useChatRuntimeStore((s) => s.speculativeType);
const setSpeculativeType = useChatRuntimeStore((s) => s.setSpeculativeType);
const loadedSpeculativeType = useChatRuntimeStore(
(s) => s.loadedSpeculativeType,
);
const specFallbackReason = useChatRuntimeStore((s) => s.specFallbackReason);
// Only binary fallback states are solved by a newer prebuilt.
const mtpUpdatable =
specFallbackReason === "binary_no_mtp" ||
specFallbackReason === "binary_outdated";
const {
status: llamaUpdateStatus,
applying: llamaUpdating,
apply: applyLlamaUpdate,
} = useLlamaUpdateCheck({
enabled: mtpUpdatable,
onReloadRequired: resyncInferenceStatusAfterServerModelChange,
});
const handleMtpUpdate = useCallback(async () => {
const result = await applyLlamaUpdate();
if (result.ok) {
const reloadHint = result.reloadRequired
? " Reload your model to enable MTP."
: "";
toast.success(
`llama.cpp updated to ${result.tag ?? "the latest build"}.${reloadHint}`,
);
} else {
toast.error(`llama.cpp update failed: ${result.error ?? "unknown error"}`);
}
}, [applyLlamaUpdate]);
const specDraftNMax = useChatRuntimeStore((s) => s.specDraftNMax);
const setSpecDraftNMax = useChatRuntimeStore((s) => s.setSpecDraftNMax);
const loadedSpecDraftNMax = useChatRuntimeStore(
(s) => s.loadedSpecDraftNMax,
);
const currentCheckpoint = params.checkpoint;
const ggufContextLength = useChatRuntimeStore((s) => s.ggufContextLength);
const ggufMaxContextLength = useChatRuntimeStore(
(s) => s.ggufMaxContextLength,
);
const ggufNativeContextLength = useChatRuntimeStore(
(s) => s.ggufNativeContextLength,
);
const kvCacheDtype = useChatRuntimeStore((s) => s.kvCacheDtype);
const setKvCacheDtype = useChatRuntimeStore((s) => s.setKvCacheDtype);
const applyRememberedLoadSettings = useChatRuntimeStore(
(s) => s.applyRememberedLoadSettings,
);
const loadedKvCacheDtype = useChatRuntimeStore((s) => s.loadedKvCacheDtype);
const tensorParallel = useChatRuntimeStore((s) => s.tensorParallel);
const setTensorParallel = useChatRuntimeStore((s) => s.setTensorParallel);
const loadedTensorParallel = useChatRuntimeStore(
(s) => s.loadedTensorParallel,
);
const chatTemplateOverride = useChatRuntimeStore(
(s) => s.chatTemplateOverride,
);
const loadedChatTemplateOverride = useChatRuntimeStore(
(s) => s.loadedChatTemplateOverride,
);
const customContextLength = useChatRuntimeStore((s) => s.customContextLength);
const setCustomContextLength = useChatRuntimeStore(
(s) => s.setCustomContextLength,
);
const setActivePresetSource = useChatRuntimeStore(
(s) => s.setActivePresetSource,
);
const activePresetSource = useChatRuntimeStore((s) => s.activePresetSource);
const customPresets = useChatRuntimeStore((s) => s.customPresets);
const setCustomPresets = useChatRuntimeStore((s) => s.setCustomPresets);
const activePreset = useChatRuntimeStore((s) => s.activePreset);
const setActivePreset = useChatRuntimeStore((s) => s.setActivePreset);
const settingsHydrated = useChatRuntimeStore((s) => s.settingsHydrated);
// A staged (not-yet-loaded) GGUF carries its own header context length on
// pendingSelection, so the slider can use the staged model's real ceiling
// without reading the loaded model's `ggufContextLength`.
const stagedContextLength = pendingSelection?.contextLength ?? null;
// "Remember settings next time" tick for a staged model. Seeds the store from
// the saved per-model settings on stage, so the sheet opens with what was used
// last time; the tick reflects whether a saved entry exists.
const [remember, setRemember] = useState(false);
// Keyed per quant: a different variant of the same repo has its own settings.
const pendingKey = pendingSelection
? rememberedLoadSettingsKey(pendingSelection)
: null;
useEffect(() => {
if (!pendingKey) return;
const saved = loadRememberedLoadSettings(pendingKey);
setRemember(saved != null);
if (saved) applyRememberedLoadSettings(saved);
}, [pendingKey, applyRememberedLoadSettings]);
// While staging, the sheet reflects the STAGED model, so its header context
// takes precedence over the loaded model's (which may differ or be larger).
const baseContext = pendingIsGguf ? stagedContextLength : ggufContextLength;
const baseNativeContext = pendingIsGguf
? stagedContextLength
: ggufNativeContextLength;
// Context controls render once we actually have a ceiling: for a staged GGUF,
// once its header metadata arrives (post-download); otherwise post-load.
const showContextControl = pendingIsGguf
? stagedContextLength != null
: isLoadedGguf;
const stagedDownloading =
stagedDownloadFraction != null && stagedDownloadFraction < 1;
const ctxDisplayValue = customContextLength ?? baseContext ?? "";
const ctxMaxValue = baseNativeContext ?? baseContext ?? null;
const kvDirty = kvCacheDtype !== loadedKvCacheDtype;
const ctxDirty = customContextLength !== null;
const specDirty = speculativeType !== loadedSpeculativeType;
const specDraftDirty = specDraftNMax !== loadedSpecDraftNMax;
const tpDirty = tensorParallel !== (loadedTensorParallel ?? false);
// A saved chat-template override is a reload-time setting too, so surface
// Apply for a template-only edit (otherwise it could never be applied).
const templateDirty = chatTemplateOverride !== loadedChatTemplateOverride;
const modelSettingsDirty =
kvDirty || ctxDirty || specDirty || specDraftDirty || tpDirty || templateDirty;
const [presetNameInput, setPresetNameInput] = useState(activePreset);
const [systemPromptEditorOpen, setSystemPromptEditorOpen] = useState(false);
const [systemPromptDraft, setSystemPromptDraft] = useState("");
const [systemVariablesDraft, setSystemVariablesDraft] = useState("");
const [systemVariablesOpen, setSystemVariablesOpen] = useState(false);
// When the prompt overflows the inline box, clicking opens the popup editor.
const systemPromptBoxRef = useRef<HTMLTextAreaElement>(null);
const [systemPromptOverflows, setSystemPromptOverflows] = useState(false);
const [activePresetBaseline, setActivePresetBaseline] = useState(params);
const presets = useMemo(() => {
return getOrderedPresets(customPresets);
}, [customPresets]);
const activePresetDefinition = useMemo(
() => presets.find((preset) => preset.name === activePreset) ?? null,
[activePreset, presets],
);
const activeCustomPreset = useMemo(
() => customPresets.find((preset) => preset.name === activePreset) ?? null,
[activePreset, customPresets],
);
const activeBuiltinPreset = useMemo(
() =>
BUILTIN_PRESETS.find((preset) => preset.name === activePreset) ?? null,
[activePreset],
);
const hasUnsavedPresetChanges = useMemo(
() => {
if (activePresetDefinition == null) {
return false;
}
if (activePresetDefinition.name === "Default") {
return activePresetSource === "modified";
}
return !isSamePresetConfig(activePresetDefinition.params, params);
},
[activePresetDefinition, activePresetSource, params],
);
const presetSaveState = useMemo(
() =>
getPresetSaveState({
rawName: presetNameInput,
activePreset,
presets,
hasUnsavedPresetChanges,
}),
[activePreset, hasUnsavedPresetChanges, presetNameInput, presets],
);
const systemVariablesError = getPromptVariablesError(systemVariablesDraft);
const currentSystemPrompt = params.systemPrompt ?? "";
const currentSystemVariables = params.systemVariables ?? "";
const systemPromptEditorDirty =
systemPromptDraft !== currentSystemPrompt ||
systemVariablesDraft !== currentSystemVariables;
const showPromptCacheTtlControl = Boolean(
activeExternalProvider &&
supportsProviderPromptCacheTtl(activeExternalProvider.providerType),
);
const showPromptCachingControl =
activeExternalProvider != null &&
supportsProviderPromptCaching(activeExternalProvider.providerType);
const promptCachingEnabled =
activeExternalProvider?.enablePromptCaching !== false;
const externalSelection = currentCheckpoint
? parseExternalModelId(currentCheckpoint)
: null;
const showOpenAICodeExecSection =
activeExternalProvider != null &&
providerSupportsBuiltinCodeExecution(
activeExternalProvider.providerType,
externalSelection?.modelId,
activeExternalProvider.baseUrl,
) &&
activeExternalProvider.providerType === "openai";
const showFastModeControl =
activeExternalProvider != null &&
providerSupportsFastMode(
activeExternalProvider.providerType,
externalSelection?.modelId,
);
const activeThreadId = useChatRuntimeStore((s) => s.activeThreadId);
const openAiApiKeyForSection = activeExternalProvider
? getExternalProviderApiKey(activeExternalProvider.id) || null
: null;
function set<K extends keyof InferenceParams>(key: K) {
return (v: InferenceParams[K]) => {
const nextParams = { ...params, [key]: v };
const nextSource = isSamePresetConfig(activePresetBaseline, nextParams)
? getPresetSource(activePreset)
: "modified";
setActivePresetSource(nextSource);
onParamsChange(nextParams);
};
}
function applyPreset(name: string) {
if (!settingsHydrated) {
return;
}
const p = presets.find((pr) => pr.name === name);
if (p) {
onParamsChange({
...applyPresetParams(params, p.params),
});
setActivePreset(name);
setActivePresetSource(getPresetSource(name));
}
}
function savePresetWithName(rawName: string) {
if (!settingsHydrated) {
return;
}
const trimmed = rawName.trim();
if (!trimmed) {
toast.error("Enter a preset name");
return;
}
const usedNames = new Set([
...BUILTIN_PRESET_NAMES,
...customPresets.map((preset) => preset.name),
]);
const saveName = BUILTIN_PRESET_NAMES.has(trimmed)
? getBuiltinVariantName(trimmed, usedNames)
: trimmed;
const next = customPresets.filter((p) => p.name !== saveName);
const merged = [
...next,
{ name: saveName, params: toPresetParams(params) },
];
setCustomPresets(merged);
setActivePreset(saveName);
setActivePresetSource("custom");
setPresetNameInput(saveName);
}
function deletePreset(name: string) {
if (!settingsHydrated) {
return;
}
const hasCustomPreset = customPresets.some(
(preset) => preset.name === name,
);
if (!hasCustomPreset) {
return;
}
const fallbackPreset =
BUILTIN_PRESETS.find((preset) => preset.name === "Default") ??
null;
const next = customPresets.filter((preset) => preset.name !== name);
setCustomPresets(next);
if (activePreset === name) {
if (fallbackPreset) {
onParamsChange({
...applyPresetParams(params, fallbackPreset.params),
});
setActivePreset(fallbackPreset.name);
setActivePresetSource("builtin-default");
}
}
}
function openSystemPromptEditor() {
setSystemPromptDraft(currentSystemPrompt);
setSystemVariablesDraft(currentSystemVariables);
setSystemVariablesOpen(
currentSystemVariables.trim().length > 0 ||
hasPromptVariableSyntax(currentSystemPrompt),
);
setSystemPromptEditorOpen(true);
}
function saveSystemPromptEditor() {
if (systemVariablesError) {
toast.error("Fix prompt variables before saving", {
description: systemVariablesError,
});
return;
}
const nextParams = {
...params,
systemPrompt: systemPromptDraft,
systemVariables: systemVariablesDraft.trim(),
};
const nextSource = isSamePresetConfig(activePresetBaseline, nextParams)
? getPresetSource(activePreset)
: "modified";
setActivePresetSource(nextSource);
onParamsChange(nextParams);
setSystemPromptEditorOpen(false);
}
useEffect(() => {
if (activePresetSource !== "modified") {
setActivePresetBaseline(params);
}
}, [activePresetSource, params]);
useEffect(() => {
if (!settingsHydrated) {
return;
}
if (presets.some((preset) => preset.name === activePreset)) {
const expectedSource = getPresetSource(activePreset);
if (
activePresetSource !== "modified" &&
activePresetSource !== expectedSource
) {
setActivePresetSource(expectedSource);
}
return;
}
setActivePreset("Default");
setActivePresetSource("builtin-default");
}, [
activePreset,
activePresetSource,
presets,
setActivePreset,
setActivePresetSource,
settingsHydrated,
]);
useEffect(() => {
setPresetNameInput(activePreset);
}, [activePreset]);
useEffect(() => {
if (!open) {
setSystemPromptEditorOpen(false);
}
}, [open]);
useEffect(() => {
const el = systemPromptBoxRef.current;
setSystemPromptOverflows(
currentSystemPrompt.length > 0 &&
el != null &&
el.clientHeight > 0 &&
el.scrollHeight > el.clientHeight + 1,
);
}, [currentSystemPrompt, open]);
const settingsScrollRef = useRef<HTMLDivElement>(null);
const settingsContent = (
<>
<div className="flex h-full min-h-0 flex-col">
{/* Header is outside the scroll area so the scrollbar never shifts the close button. */}
<div className="flex h-[48px] shrink-0 items-start gap-2 bg-panel-surface pl-[18px] pr-[16px] pt-[11px]">
{isMobile ? (
<span className="flex h-[34px] flex-1 items-center text-[16px] font-semibold tracking-[0em] dark:tracking-[0.015em] text-nav-fg">
Run settings
</span>
) : (
<>
<span className="flex h-[34px] flex-1 items-center text-[16px] font-semibold tracking-[0em] dark:tracking-[0.015em] text-nav-fg">
Run settings
</span>
<Tooltip>
<TooltipPrimitive.Trigger asChild>
<button
type="button"
onClick={() => onOpenChange?.(false)}
className="flex h-[34px] w-[34px] cursor-pointer items-center justify-center rounded-full text-nav-icon-idle dark:text-nav-fg-muted transition-colors hover:bg-nav-surface-hover hover:text-black dark:hover:text-white focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
aria-label="Close run settings"
>
<HugeiconsIcon
icon={LayoutAlignRightIcon}
strokeWidth={1.75}
className="size-icon"
/>
</button>
</TooltipPrimitive.Trigger>
<TooltipContent
side="bottom"
sideOffset={6}
className="tooltip-compact"
>
Close run settings
</TooltipContent>
</Tooltip>
</>
)}
</div>
<div
ref={settingsScrollRef}
className="run-settings-scroll relative min-h-0 flex-1 overflow-y-auto"
>
<div className="px-[18px] pt-3">
{hasModelContent && (
<CollapsibleSection label="Model" defaultOpen={true} first>
<div className="flex flex-col gap-4 pt-1">
{pendingSelection && (
<Alert className="rounded-[14px] border-primary/30 bg-primary/5 px-3 py-2">
<AlertTitle className="text-[12px] font-medium">
{stagedLoading
? `Loading ${stagedLabel}…`
: `${stagedLabel} is staged, not loaded yet`}
</AlertTitle>
<AlertDescription className="text-[11.5px] leading-[1.45] text-muted-foreground">
{stagedLoading
? "Applying your settings."
: "Set the options below, then choose Load model to load it."}
</AlertDescription>
</Alert>
)}
{isGguf && (
<>
{showContextControl && (
<div className="space-y-3.5">
<div className="flex items-center justify-between gap-3">
<span className="min-w-0 text-[13px] font-medium leading-[1.25] tracking-nav text-nav-fg">
Context Length
</span>
<NumericValueInput
value={
typeof ctxDisplayValue === "number"
? ctxDisplayValue
: (baseContext ?? 0)
}
min={128}
max={ctxMaxValue ?? undefined}
step={1}
onChange={(v) => {
setCustomContextLength(
v === (baseContext ?? 0) ? null : v,