Repository navigation
Expand file tree
/
Copy pathconnection_settings.py
More file actions
1248 lines (1123 loc) · 46.6 KB
/
Copy pathconnection_settings.py
File metadata and controls
1248 lines (1123 loc) · 46.6 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
"""Adwaita preferences: connection, per-model basics, passive Model Fit.
Phase 3 Model Fit is observational only (show/ps/metrics). It never changes
Phase 2 controls, request options, or loads models.
Controllers share the same ``OllamaClient`` instance; connection changes
update that instance in place so load/chat keep working without rewiring.
"""
from __future__ import annotations
import threading
from collections.abc import Callable
from pathlib import Path
from typing import Any
import gi
gi.require_version("Gtk", "4.0")
gi.require_version("Adw", "1")
gi.require_version("Gio", "2.0")
from gi.repository import Adw, Gio, GLib, Gtk
import app_settings as _app_settings
from model_fit import (
UNAVAILABLE,
capabilities_label,
context_budget,
context_usage_view,
estimate_conversation_tokens,
format_bytes,
format_tokens,
format_tps,
gpu_resident_portion,
last_metrics_if_current,
match_running_model,
merge_descriptor,
)
from model_profile import (
CONTEXT_TIER_IDS,
CONTEXT_TIER_LABELS,
CONTEXT_TIER_NUM_CTX,
KEEP_ALIVE_IDS,
KEEP_ALIVE_LABELS,
KEEP_ALIVE_VALUES,
RESPONSE_STYLE_IDS,
RESPONSE_STYLE_LABELS,
RESPONSE_STYLE_TEMPERATURE,
ModelProfileService,
fit_num_ctx,
keep_alive_id_for_value,
max_context_from_profile,
num_ctx_for_tier,
)
from ollama_client import ModelDescriptor, OllamaClient, OllamaError
def _markup_safe(text: str) -> str:
"""Escape dynamic text destined for an Adw row title/subtitle.
``Adw.PreferencesRow:use-markup`` defaults to TRUE, so these strings are
parsed as Pango markup. Values derived from the server, the model, or the
filesystem are plain text, not markup — an unescaped ``<`` aborts
rendering (e.g. the context-usage label ``... tokens (<1%)`` failed with
"“1%)<” is not a valid name"). Escape at this boundary rather than
special-casing any single value.
"""
return GLib.markup_escape_text(str(text))
def open_folder(path: Path, *, parent: Gtk.Window | None = None) -> None:
"""Reveal *path* in the file manager; create the directory if needed."""
try:
path.mkdir(parents=True, exist_ok=True)
except OSError as exc:
print(f"open folder mkdir: {exc}", flush=True)
try:
launcher = Gtk.FileLauncher.new(Gio.File.new_for_path(str(path)))
launcher.launch(parent, None, None, None)
return
except Exception as exc: # noqa: BLE001
try:
Gio.AppInfo.launch_default_for_uri(path.as_uri(), None)
except Exception as exc2: # noqa: BLE001
print(f"open folder: {exc} / {exc2}", flush=True)
def apply_client_connection(
client: OllamaClient,
*,
base_url: str,
connect_timeout_sec: float,
) -> None:
"""Mutate an existing client so shared controllers pick up new settings."""
client.base_url = _app_settings.normalize_base_url(base_url)
try:
timeout = float(connect_timeout_sec)
except (TypeError, ValueError):
timeout = _app_settings.DEFAULT_CONNECT_TIMEOUT_SEC
if timeout <= 0 or timeout != timeout:
timeout = _app_settings.DEFAULT_CONNECT_TIMEOUT_SEC
client.timeout = timeout
class ConnectionPreferences:
"""Settings UI: connection, per-model basics, Model Fit (embedded main column)."""
def __init__(
self,
*,
parent: Adw.ApplicationWindow,
client: OllamaClient,
profiles: ModelProfileService,
get_selected_model: Callable[[], str | None],
get_conversation_messages: Callable[[], list[dict[str, Any]]] | None = None,
settings_dir: Path | None = None,
settings_path: Path | None = None,
on_connection_applied: Callable[[], None] | None = None,
on_close: Callable[[], None] | None = None,
) -> None:
self._parent = parent
self._client = client
self._profiles = profiles
self._get_selected_model = get_selected_model
self._get_conversation_messages = get_conversation_messages
self._settings_dir = settings_dir
self._settings_path = settings_path
self._on_connection_applied = on_connection_applied
self._on_close = on_close
self._panel: Gtk.Widget | None = None
self._url_row: Adw.EntryRow | None = None
self._timeout_row: Adw.SpinRow | None = None
self._status_row: Adw.ActionRow | None = None
self._version_row: Adw.ActionRow | None = None
self._test_btn: Gtk.Button | None = None
# Model page widgets
self._model_title_row: Adw.ActionRow | None = None
self._context_row: Adw.ComboRow | None = None
self._custom_ctx_row: Adw.SpinRow | None = None
self._style_row: Adw.ComboRow | None = None
self._temp_row: Adw.SpinRow | None = None
self._max_out_row: Adw.SpinRow | None = None
self._keep_alive_row: Adw.ComboRow | None = None
self._think_row: Adw.SwitchRow | None = None
self._reset_btn: Gtk.Button | None = None
self._model_group: Adw.PreferencesGroup | None = None
# Model Fit rows (Phase 3) — ActionRow title → widget
self._fit_rows: dict[str, Adw.ActionRow] = {}
self._fit_warning_row: Adw.ActionRow | None = None
self._applying = False
self._model_loading = False
self._test_generation = 0
self._caps_generation = 0
self._fit_generation = 0
self._think_supported = False
self._bound_model: str | None = None
# (model, context_length) Ollama last reported for a loaded model.
self._allocated_ctx: tuple[str, int] | None = None
def ensure_panel(self) -> Gtk.Widget:
"""Build the settings page once; reuse thereafter."""
if self._panel is None:
self._panel = self._build()
self._load_from_settings()
return self._panel
def present(self) -> None:
"""Refresh live data when the settings page is shown."""
self.ensure_panel()
self.refresh_selected_model()
# Non-blocking status probe with the currently applied client.
self._refresh_status_async(use_form_values=False)
def dismiss(self) -> None:
"""Flush form state when leaving settings (does not destroy the panel)."""
self._apply_form(show_errors=False)
self._save_model_prefs()
self._bound_model = None
def refresh_selected_model(self) -> None:
"""Reload model controls for the window's current model (no cross-leak)."""
if self._panel is None:
return
self._load_model_prefs()
self._probe_thinking_capability()
self._refresh_model_fit_async()
def _request_close(self, *_args) -> None:
if self._on_close is not None:
try:
self._on_close()
except Exception as exc: # noqa: BLE001
print(f"settings close: {exc}", flush=True)
def _build(self) -> Gtk.Widget:
"""Embedded full-column settings page (not a floating dialog)."""
toolbar = Adw.ToolbarView()
toolbar.add_css_class("chickenbutt-settings-panel")
toolbar.set_hexpand(True)
toolbar.set_vexpand(True)
header = Adw.HeaderBar()
header.set_show_end_title_buttons(False)
header.set_show_start_title_buttons(False)
back = Gtk.Button()
back.set_icon_name("go-previous-symbolic")
back.set_tooltip_text("Back to chat")
back.set_valign(Gtk.Align.CENTER)
try:
back.set_cursor_from_name("pointer")
except Exception: # noqa: BLE001
pass
back.connect("clicked", self._request_close)
header.pack_start(back)
stack = Adw.ViewStack()
stack.set_hexpand(True)
stack.set_vexpand(True)
switcher = Adw.ViewSwitcher()
switcher.set_stack(stack)
try:
switcher.set_policy(Adw.ViewSwitcherPolicy.WIDE)
except Exception: # noqa: BLE001
pass
header.set_title_widget(switcher)
toolbar.add_top_bar(header)
def _add_page(
page: Adw.PreferencesPage, name: str, title: str, icon: str
) -> None:
page.set_hexpand(True)
page.set_vexpand(True)
stack_page = stack.add_titled(page, name, title)
try:
stack_page.set_icon_name(icon)
except Exception: # noqa: BLE001
pass
page = Adw.PreferencesPage()
page.set_title("Connection")
page.set_icon_name("network-server-symbolic")
_add_page(page, "connection", "Connection", "network-server-symbolic")
conn = Adw.PreferencesGroup()
conn.set_title("Ollama")
conn.set_description(
"ChickenButt talks to Ollama over HTTP. Connection timeout applies "
"to ordinary requests (list models, version, health). Chat streams "
"are not cut off by this timeout."
)
page.add(conn)
url_row = Adw.EntryRow()
url_row.set_title("Address")
url_row.set_show_apply_button(True)
url_row.set_input_purpose(Gtk.InputPurpose.URL)
url_row.connect("apply", self._on_url_apply)
conn.add(url_row)
self._url_row = url_row
adjustment = Gtk.Adjustment(
value=_app_settings.DEFAULT_CONNECT_TIMEOUT_SEC,
lower=1.0,
upper=600.0,
step_increment=1.0,
page_increment=10.0,
)
timeout_row = Adw.SpinRow(adjustment=adjustment, digits=0)
timeout_row.set_title("Connection timeout")
timeout_row.set_subtitle("Seconds for non-stream requests")
timeout_row.connect("notify::value", self._on_timeout_changed)
conn.add(timeout_row)
self._timeout_row = timeout_row
status_row = Adw.ActionRow()
status_row.set_title("Status")
status_row.set_subtitle("Not checked yet")
conn.add(status_row)
self._status_row = status_row
version_row = Adw.ActionRow()
version_row.set_title("Ollama version")
version_row.set_subtitle("—")
conn.add(version_row)
self._version_row = version_row
test_row = Adw.ActionRow()
test_row.set_title("Test connection")
test_row.set_subtitle("Uses the address and timeout shown above")
test_btn = Gtk.Button(label="Test")
test_btn.set_valign(Gtk.Align.CENTER)
test_btn.add_css_class("suggested-action")
test_btn.connect("clicked", self._on_test_clicked)
test_row.add_suffix(test_btn)
test_row.set_activatable_widget(test_btn)
conn.add(test_row)
self._test_btn = test_btn
data = Adw.PreferencesGroup()
data.set_title("Local data")
data.set_description(
"Chat history and settings stay on this device. They are not "
"uploaded by ChickenButt."
)
page.add(data)
config_dir = _app_settings._SETTINGS_DIR
data_dir = Path(GLib.get_user_data_dir()) / "chickenbutt"
config_row = Adw.ActionRow()
config_row.set_title("Config folder")
config_row.set_subtitle(_markup_safe(config_dir))
config_btn = Gtk.Button(label="Open")
config_btn.set_valign(Gtk.Align.CENTER)
config_btn.connect(
"clicked", lambda *_: open_folder(config_dir, parent=self._parent)
)
config_row.add_suffix(config_btn)
config_row.set_activatable_widget(config_btn)
data.add(config_row)
data_row = Adw.ActionRow()
data_row.set_title("Data folder")
data_row.set_subtitle(_markup_safe(data_dir))
data_btn = Gtk.Button(label="Open")
data_btn.set_valign(Gtk.Align.CENTER)
data_btn.connect(
"clicked", lambda *_: open_folder(data_dir, parent=self._parent)
)
data_row.add_suffix(data_btn)
data_row.set_activatable_widget(data_btn)
data.add(data_row)
# --- Model basics (Phase 2) ---
model_page = Adw.PreferencesPage()
model_page.set_title("Model")
model_page.set_icon_name("emoji-objects-symbolic")
_add_page(model_page, "model", "Model", "emoji-objects-symbolic")
model_group = Adw.PreferencesGroup()
model_group.set_title("Selected model")
model_group.set_description(
"These preferences apply to the model currently selected in the "
"sidebar. Empty or reset profiles use Ollama’s defaults (optional "
"request fields are omitted)."
)
model_page.add(model_group)
self._model_group = model_group
model_title = Adw.ActionRow()
model_title.set_title("Model")
model_title.set_subtitle("No model selected")
model_group.add(model_title)
self._model_title_row = model_title
context_row = Adw.ComboRow()
context_row.set_title("Context")
context_row.set_model(Gtk.StringList.new(list(CONTEXT_TIER_LABELS)))
context_row.connect("notify::selected", self._on_context_tier_changed)
model_group.add(context_row)
self._context_row = context_row
ctx_adj = Gtk.Adjustment(
value=8192, lower=512, upper=262144, step_increment=512, page_increment=4096
)
custom_ctx = Adw.SpinRow(adjustment=ctx_adj, digits=0)
custom_ctx.set_title("Custom context size")
custom_ctx.set_subtitle("Tokens (num_ctx)")
custom_ctx.set_visible(False)
custom_ctx.connect("notify::value", self._on_custom_ctx_changed)
model_group.add(custom_ctx)
self._custom_ctx_row = custom_ctx
style_row = Adw.ComboRow()
style_row.set_title("Response style")
style_row.set_model(Gtk.StringList.new(list(RESPONSE_STYLE_LABELS)))
style_row.connect("notify::selected", self._on_style_changed)
model_group.add(style_row)
self._style_row = style_row
temp_adj = Gtk.Adjustment(
value=0.7, lower=0.0, upper=2.0, step_increment=0.05, page_increment=0.1
)
temp_row = Adw.SpinRow(adjustment=temp_adj, digits=2)
temp_row.set_title("Creativity")
temp_row.set_subtitle("Temperature — editing marks Response style as Custom")
temp_row.connect("notify::value", self._on_temp_changed)
model_group.add(temp_row)
self._temp_row = temp_row
max_adj = Gtk.Adjustment(
value=0, lower=0, upper=128000, step_increment=64, page_increment=256
)
max_out = Adw.SpinRow(adjustment=max_adj, digits=0)
max_out.set_title("Maximum output")
max_out.set_subtitle("0 = Ollama default (omit num_predict)")
max_out.connect("notify::value", self._on_max_out_changed)
model_group.add(max_out)
self._max_out_row = max_out
keep_row = Adw.ComboRow()
keep_row.set_title("Keep model loaded")
keep_row.set_model(Gtk.StringList.new(list(KEEP_ALIVE_LABELS)))
keep_row.connect("notify::selected", self._on_keep_alive_changed)
model_group.add(keep_row)
self._keep_alive_row = keep_row
think_row = Adw.SwitchRow()
think_row.set_title("Show reasoning")
think_row.set_subtitle("Only available for models that support thinking")
think_row.set_sensitive(False)
think_row.connect("notify::active", self._on_think_changed)
model_group.add(think_row)
self._think_row = think_row
reset_row = Adw.ActionRow()
reset_row.set_title("Reset this model")
reset_row.set_subtitle("Clear preferences; keep performance observations")
reset_btn = Gtk.Button(label="Reset to defaults")
reset_btn.set_valign(Gtk.Align.CENTER)
reset_btn.add_css_class("destructive-action")
reset_btn.connect("clicked", self._on_reset_clicked)
reset_row.add_suffix(reset_btn)
reset_row.set_activatable_widget(reset_btn)
model_group.add(reset_row)
self._reset_btn = reset_btn
# --- Model Fit (Phase 3, observational only) ---
fit_page = Adw.PreferencesPage()
fit_page.set_title("Model Fit")
fit_page.set_icon_name("emblem-ok-symbolic")
_add_page(fit_page, "model-fit", "Model Fit", "emblem-ok-symbolic")
fit_intro = Adw.PreferencesGroup()
fit_intro.set_title("Model Fit")
fit_intro.set_description(
"Observational facts about the selected model. This page never "
"changes your Model preferences or chat options."
)
fit_page.add(fit_intro)
def _fit_row(group: Adw.PreferencesGroup, key: str, title: str) -> Adw.ActionRow:
row = Adw.ActionRow()
row.set_title(title)
row.set_subtitle(UNAVAILABLE)
group.add(row)
self._fit_rows[key] = row
return row
model_facts = Adw.PreferencesGroup()
model_facts.set_title("Model")
fit_page.add(model_facts)
_fit_row(model_facts, "parameters", "Parameters")
_fit_row(model_facts, "quantization", "Quantization")
_fit_row(model_facts, "max_context", "Maximum supported context")
_fit_row(model_facts, "capabilities", "Capabilities")
_fit_row(model_facts, "model_size", "Model size")
load_facts = Adw.PreferencesGroup()
load_facts.set_title("Current load")
load_facts.set_description(
"Appears when this model is loaded in Ollama. "
"GPU-resident portion is the share of this model’s memory in GPU "
"memory — not overall GPU utilization."
)
fit_page.add(load_facts)
_fit_row(load_facts, "allocated_ctx", "Allocated context")
_fit_row(load_facts, "loaded_mem", "Loaded memory")
_fit_row(load_facts, "vram_mem", "GPU-resident memory")
_fit_row(load_facts, "gpu_portion", "GPU-resident portion")
last_resp = Adw.PreferencesGroup()
last_resp.set_title("Last response")
last_resp.set_description(
"From the last completed generation for this model’s current "
"installed digest. Empty after a digest change until you chat again."
)
fit_page.add(last_resp)
_fit_row(last_resp, "prompt_tps", "Prompt processing")
_fit_row(last_resp, "gen_tps", "Generation speed")
_fit_row(last_resp, "peak_ctx", "Peak context used")
convo = Adw.PreferencesGroup()
convo.set_title("Conversation")
fit_page.add(convo)
_fit_row(convo, "ctx_usage", "Context usage")
warn = Adw.ActionRow()
warn.set_title("Context warning")
warn.set_subtitle("")
warn.set_visible(False)
convo.add(warn)
self._fit_warning_row = warn
toolbar.set_content(stack)
return toolbar
def _load_from_settings(self) -> None:
cfg = _app_settings.get_ollama_config(self._settings_path)
self._applying = True
try:
if self._url_row is not None:
self._url_row.set_text(str(cfg.get("base_url") or ""))
if self._timeout_row is not None:
self._timeout_row.set_value(
float(
cfg.get("connect_timeout_sec")
or _app_settings.DEFAULT_CONNECT_TIMEOUT_SEC
)
)
finally:
self._applying = False
def _form_url(self) -> str:
if self._url_row is None:
return _app_settings.DEFAULT_BASE_URL
return self._url_row.get_text()
def _form_timeout(self) -> float:
if self._timeout_row is None:
return _app_settings.DEFAULT_CONNECT_TIMEOUT_SEC
return float(self._timeout_row.get_value())
def _set_status(self, status: str, version: str | None = None) -> None:
if self._status_row is not None:
self._status_row.set_subtitle(_markup_safe(status))
if version is not None and self._version_row is not None:
self._version_row.set_subtitle(_markup_safe(version))
def _on_url_apply(self, *_args) -> None:
if self._applying:
return
self._apply_form(show_errors=True)
def _on_timeout_changed(self, *_args) -> None:
if self._applying:
return
self._apply_form(show_errors=False)
# --- Model basics ---
def _selected_model_name(self) -> str | None:
try:
name = self._get_selected_model()
except Exception: # noqa: BLE001
return None
if not name or not str(name).strip():
return None
return str(name)
def _set_combo_by_id(
self, row: Adw.ComboRow | None, ids: tuple[str, ...], selected_id: str
) -> None:
if row is None:
return
try:
idx = ids.index(selected_id)
except ValueError:
idx = 0
row.set_selected(idx)
def _combo_id(self, row: Adw.ComboRow | None, ids: tuple[str, ...]) -> str:
if row is None:
return ids[0]
idx = int(row.get_selected())
if idx < 0 or idx >= len(ids):
return ids[0]
return ids[idx]
def _load_model_prefs(self) -> None:
model = self._selected_model_name()
self._bound_model = model
self._model_loading = True
try:
if self._model_title_row is not None:
self._model_title_row.set_subtitle(
_markup_safe(model or "No model selected")
)
enabled = bool(model)
for w in (
self._context_row,
self._custom_ctx_row,
self._style_row,
self._temp_row,
self._max_out_row,
self._keep_alive_row,
self._reset_btn,
):
if w is not None:
w.set_sensitive(enabled)
profile = self._profiles.get_profile(model) if model else {}
options = profile.get("options") if isinstance(profile.get("options"), dict) else {}
tier = profile.get("context_tier")
if not isinstance(tier, str) or tier not in CONTEXT_TIER_IDS:
# Infer from stored num_ctx when possible.
nctx = options.get("num_ctx")
tier = "auto"
if isinstance(nctx, (int, float)) and int(nctx) > 0:
nctx_i = int(nctx)
for tid, val in CONTEXT_TIER_NUM_CTX.items():
if val == nctx_i:
tier = tid
break
else:
tier = "custom"
self._set_combo_by_id(self._context_row, CONTEXT_TIER_IDS, tier)
self._update_context_row_subtitle()
if self._custom_ctx_row is not None:
nctx = options.get("num_ctx")
if isinstance(nctx, (int, float)) and int(nctx) > 0:
self._custom_ctx_row.set_value(float(int(nctx)))
else:
self._custom_ctx_row.set_value(8192.0)
self._custom_ctx_row.set_visible(tier == "custom")
style = profile.get("response_style")
if not isinstance(style, str) or style not in RESPONSE_STYLE_IDS:
temp = options.get("temperature")
style = "balanced"
if isinstance(temp, (int, float)):
for sid, tval in RESPONSE_STYLE_TEMPERATURE.items():
if tval is not None and abs(float(temp) - tval) < 0.001:
style = sid
break
else:
style = "custom"
elif not options and not profile:
# Empty profile: show Balanced as a neutral label but do not
# persist temperature until the user changes something.
style = "balanced"
self._set_combo_by_id(self._style_row, RESPONSE_STYLE_IDS, style)
if self._temp_row is not None:
temp = options.get("temperature")
if isinstance(temp, (int, float)):
self._temp_row.set_value(float(temp))
else:
preset = RESPONSE_STYLE_TEMPERATURE.get(style)
# Balanced / omit → show a neutral 0.7 in the spinner only.
self._temp_row.set_value(
float(preset if preset is not None else 0.7)
)
if self._max_out_row is not None:
npred = options.get("num_predict")
if isinstance(npred, (int, float)) and int(npred) > 0:
self._max_out_row.set_value(float(int(npred)))
else:
self._max_out_row.set_value(0.0)
ka_id = keep_alive_id_for_value(profile.get("keep_alive"))
self._set_combo_by_id(self._keep_alive_row, KEEP_ALIVE_IDS, ka_id)
if self._think_row is not None:
think = profile.get("think")
self._think_row.set_active(bool(think) is True or think is True)
# Sensitivity updated by capability probe.
self._think_row.set_sensitive(False)
self._think_supported = False
finally:
self._model_loading = False
def _probe_thinking_capability(self) -> None:
model = self._selected_model_name()
self._caps_generation += 1
gen = self._caps_generation
if not model:
if self._think_row is not None:
self._think_row.set_sensitive(False)
self._think_row.set_subtitle(
"Only available for models that support thinking"
)
return
def work() -> None:
supported = False
try:
desc = self._client.show_model(model)
caps = {c.lower() for c in (desc.capabilities or ())}
supported = "thinking" in caps
except Exception: # noqa: BLE001
supported = False
def done() -> bool:
if gen != self._caps_generation:
return False
self._think_supported = supported
if self._think_row is not None:
self._think_row.set_sensitive(bool(model) and supported)
if supported:
self._think_row.set_subtitle(
"Send Ollama’s think flag for this model"
)
else:
self._think_row.set_subtitle(
"This model does not advertise thinking support"
)
# Do not force-clear stored think here — only hide control
# effect on next save when unsupported.
return False
GLib.idle_add(done)
threading.Thread(
target=work, daemon=True, name="cb-settings-think-caps"
).start()
def _fit_set(self, key: str, subtitle: str) -> None:
row = self._fit_rows.get(key)
if row is not None:
row.set_subtitle(_markup_safe(subtitle))
def _fit_clear_all(self) -> None:
for key in self._fit_rows:
self._fit_set(key, UNAVAILABLE)
if self._fit_warning_row is not None:
self._fit_warning_row.set_visible(False)
self._fit_warning_row.set_subtitle("")
def _update_context_row_subtitle(self) -> None:
"""Explain the Auto/Fit tier's resolved size; no subtitle for fixed tiers."""
if self._context_row is None:
return
tier = self._combo_id(self._context_row, CONTEXT_TIER_IDS)
if tier not in ("auto", "fit"):
self._context_row.set_subtitle("")
return
model = self._bound_model
if tier == "auto":
alloc = self._allocated_ctx
if model and alloc is not None and alloc[0] == model:
text = (
f"Sized by Ollama for this machine — currently "
f"{format_tokens(alloc[1])} tokens. Long chats are "
"summarized to fit."
)
else:
text = (
"Sized by Ollama for this machine when the model loads. "
"Long chats are summarized to fit."
)
self._context_row.set_subtitle(_markup_safe(text))
return
max_ctx = self._profiles.max_context(model) if model else None
resolved = fit_num_ctx(max_ctx)
if resolved is None:
self._context_row.set_subtitle(
_markup_safe(
"Model maximum not known yet — Ollama's default applies "
"until it is read"
)
)
elif max_ctx is not None and max_ctx > resolved:
self._context_row.set_subtitle(
_markup_safe(
f"{format_tokens(resolved)} — capped; this model supports "
f"{format_tokens(max_ctx)}"
)
)
else:
self._context_row.set_subtitle(
_markup_safe(f"{format_tokens(resolved)} — this model's maximum")
)
def _profile_num_ctx(self, model: str | None) -> int | None:
if not model:
return None
profile = self._profiles.get_profile(model)
tier = profile.get("context_tier")
options = profile.get("options") if isinstance(profile.get("options"), dict) else {}
return num_ctx_for_tier(
str(tier) if isinstance(tier, str) else None,
options if isinstance(options, dict) else None,
model_max_ctx=max_context_from_profile(profile),
)
def _refresh_model_fit_async(self) -> None:
"""Fetch show/ps on a worker; apply only if generation still matches."""
model = self._selected_model_name()
self._fit_generation += 1
gen = self._fit_generation
self._fit_clear_all()
if not model:
return
# Immediate conversation estimate (local, no network).
self._apply_conversation_usage(
model=model,
allocated_ctx=None,
max_ctx=None,
measured_peak=None,
)
def work() -> None:
show_desc: ModelDescriptor | None = None
tags_desc: ModelDescriptor | None = None
running = None
show_error: str | None = None
try:
show_desc = self._client.show_model(model)
except Exception as exc: # noqa: BLE001
show_error = str(exc) or "show failed"
try:
for d in self._client.list_models_detail():
if d.name == model:
tags_desc = d
break
if d.name.split(":")[0] == model.split(":")[0] and tags_desc is None:
tags_desc = d
except Exception: # noqa: BLE001
pass
try:
running = match_running_model(
model, self._client.list_running_models_detail()
)
except Exception: # noqa: BLE001
running = None
merged = merge_descriptor(show_desc, tags_desc)
profile = self._profiles.get_profile(model)
dig = None
if running is not None and running.digest:
dig = running.digest
elif merged is not None and merged.digest:
dig = merged.digest
elif isinstance(profile.get("last_seen_digest"), str):
dig = profile["last_seen_digest"]
metrics = last_metrics_if_current(profile, current_digest=dig)
def done() -> bool:
if gen != self._fit_generation:
return False
if self._selected_model_name() != model:
return False
self._apply_model_fit_snapshot(
model=model,
merged=merged,
running=running,
metrics=metrics,
show_error=show_error,
)
return False
GLib.idle_add(done)
threading.Thread(
target=work, daemon=True, name="cb-settings-model-fit"
).start()
def _apply_model_fit_snapshot(
self,
*,
model: str,
merged: ModelDescriptor | None,
running: Any,
metrics: dict[str, Any] | None,
show_error: str | None,
) -> None:
if merged is not None:
self._fit_set(
"parameters",
merged.parameter_size or UNAVAILABLE,
)
self._fit_set(
"quantization",
merged.quantization or UNAVAILABLE,
)
self._fit_set(
"max_context",
format_tokens(merged.context_length),
)
self._fit_set(
"capabilities",
capabilities_label(merged.capabilities),
)
self._fit_set("model_size", format_bytes(merged.size))
elif show_error:
# Network/metadata failure: unavailable, do not break chat.
self._fit_set("parameters", UNAVAILABLE)
self._fit_set("quantization", UNAVAILABLE)
self._fit_set("max_context", UNAVAILABLE)
self._fit_set("capabilities", UNAVAILABLE)
self._fit_set("model_size", UNAVAILABLE)
if running is not None:
self._fit_set(
"allocated_ctx",
format_tokens(running.context_length),
)
self._fit_set("loaded_mem", format_bytes(running.size))
self._fit_set("vram_mem", format_bytes(running.size_vram))
self._fit_set(
"gpu_portion",
gpu_resident_portion(running.size, running.size_vram),
)
else:
self._fit_set("allocated_ctx", "Not loaded")
self._fit_set("loaded_mem", "Not loaded")
self._fit_set("vram_mem", "Not loaded")
self._fit_set("gpu_portion", "Not loaded")
if metrics:
self._fit_set(
"prompt_tps",
format_tps(metrics.get("prompt_tokens_per_sec")),
)
self._fit_set(
"gen_tps",
format_tps(metrics.get("generation_tokens_per_sec")),
)
self._fit_set(
"peak_ctx",
format_tokens(metrics.get("peak_context_tokens")),
)
measured_peak = metrics.get("peak_context_tokens")
if not isinstance(measured_peak, (int, float)):
measured_peak = None
else:
measured_peak = int(measured_peak)
else:
self._fit_set("prompt_tps", UNAVAILABLE)
self._fit_set("gen_tps", UNAVAILABLE)
self._fit_set("peak_ctx", UNAVAILABLE)
measured_peak = None
max_ctx = merged.context_length if merged is not None else None
if max_ctx:
# Keep the "Fit to model" tier resolvable even when the chat-side
# probe missed; observational write, no preference is touched.
try:
self._profiles.record_model_limits(model, max_context=max_ctx)
except Exception: # noqa: BLE001
pass
if model == self._bound_model:
self._update_context_row_subtitle()
allocated = running.context_length if running is not None else None
if isinstance(allocated, int) and allocated > 0:
self._allocated_ctx = (model, allocated)
if model == self._bound_model:
self._update_context_row_subtitle()
self._apply_conversation_usage(
model=model,
allocated_ctx=allocated,
max_ctx=max_ctx,
measured_peak=measured_peak,
)
def _apply_conversation_usage(
self,
*,
model: str,
allocated_ctx: int | None,
max_ctx: int | None,
measured_peak: int | None,
) -> None:
budget = context_budget(
allocated_ctx=allocated_ctx,
max_ctx=max_ctx,
profile_num_ctx=self._profile_num_ctx(model),
)
# Prefer Ollama-measured peak from last response when available;
# otherwise estimate from the open conversation (labelled estimated).
estimated = True
used: int | None
if measured_peak is not None and measured_peak > 0:
used = measured_peak
estimated = False
else:
messages: list[dict[str, Any]] = []
if self._get_conversation_messages is not None:
try:
messages = list(self._get_conversation_messages() or [])
except Exception: # noqa: BLE001
messages = []
used = estimate_conversation_tokens(messages) if messages else 0
estimated = True
view = context_usage_view(
used_tokens=used if budget else used,
budget=budget,
estimated=estimated,
)
self._fit_set("ctx_usage", view.label)
if self._fit_warning_row is not None:
if view.warn:
self._fit_warning_row.set_visible(True)
self._fit_warning_row.set_subtitle(
"This conversation is approaching the context limit. "
"ChickenButt will summarize older messages for the model "
"automatically; the full chat stays in your history."
)
else:
self._fit_warning_row.set_visible(False)
self._fit_warning_row.set_subtitle("")
def _save_model_prefs(self) -> None: