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
//! Settings screen — the model picker: the provider's own catalogue behind the
//! model row ([docs/research/model-picker.md](../../../docs/research/model-picker.md),
//! stage 4b). Part of the [`super`] module.
//!
//! Deliberately **not** the Choice popup next door. That one reaches an option
//! by cycling to it, one config write per step, which is the wrong shape for a
//! list of 132; and it has no filter, which is the wrong shape for a list of 132
//! for the other reason. What it shares is [`ListScroll`], the one implementation
//! of a list's scroll state (`tools/list_scroll_check.py`).
use crate::shared::api::catalogue::{CatalogModel, CatalogueAnswer, CatalogueError, ModelSlot};
use super::*;
/// What the picker knows about the catalogue right now.
#[derive(Debug, Clone, PartialEq)]
pub(super) enum PickerStatus {
/// The request is out (fork F4: it goes out when the picker opens, never
/// before).
Fetching,
/// The provider answered. An **empty** list is an answer too: Anthropic
/// publishes no embedding model, and a router with nothing loaded lists
/// nothing.
Listed,
/// There is no list, and this is why. The row keeps the text field it has
/// always been — "type a name by hand" is one key away, as always (N5).
Failed(CatalogueError),
}
/// The open picker.
pub(super) struct PickerState {
/// The row that receives the pick.
pub(super) field: FieldId,
/// Which catalogue was asked for, and what it was narrowed to.
pub(super) slot: ModelSlot,
/// What that slot pointed at when the picker opened
/// ([`SettingsScreen::slot_source`]): a late answer about another provider
/// must not land here.
pub(super) source: String,
/// The filter line — a 132-entry list needs one.
pub(super) input: InputBox,
/// Everything the answer carried, in the order the provider published (or
/// newest first, where it publishes a date — `catalogue::parse`).
pub(super) all: Vec<CatalogModel>,
/// Indices into [`Self::all`] that match the filter.
pub(super) results: Vec<usize>,
/// The highlighted row of the rendered list, where **0 is always "type a
/// name by hand"** and the catalogue starts at 1.
pub(super) selected: usize,
pub(super) scroll: ListScroll,
pub(super) status: PickerStatus,
}
impl PickerState {
/// The entry the highlight is on: `None` — the "by hand" row.
fn picked(&self) -> Option<&CatalogModel> {
let idx = self.selected.checked_sub(1)?;
self.all.get(*self.results.get(idx)?)
}
/// How many rows the list draws, the "by hand" row included.
pub(super) fn rows(&self) -> usize {
self.results.len() + 1
}
}
/// Which catalogue a model row is filled from (`None` — not a row a catalogue
/// can fill: a managed GGUF path, or anything else).
pub(super) fn model_slot(id: FieldId) -> Option<ModelSlot> {
match id {
FieldId::XModelName => Some(ModelSlot::Assistant),
FieldId::IxModelName => Some(ModelSlot::Impersonation),
FieldId::EModelName => Some(ModelSlot::Embedder),
_ => None,
}
}
impl SettingsScreen {
/// `Enter` on a model row (fork F1(a)): the catalogue when there is one to
/// show, and today's text editor when there is not.
///
/// Returns `true` when the picker took the key, `false` to let the caller
/// open the editor as it always did.
pub(super) fn open_model_picker(&mut self, id: FieldId) -> Option<SettingsIntent> {
let slot = model_slot(id)?;
let source = self.slot_source(slot);
let mut input = InputBox::new();
input.set_single_line(true);
let cached = self
.catalogues
.iter()
.find(|(s, src, _)| *s == slot && *src == source);
let (all, status, intent) = match cached {
Some((_, _, Ok(models))) => (models.to_vec(), PickerStatus::Listed, None),
Some((_, _, Err(err))) => (Vec::new(), PickerStatus::Failed(*err), None),
// Nothing asked for *this* provider yet — and the asking happens
// here, on the keypress, never when the screen opens (fork F4).
None => {
self.asked.retain(|(s, _)| *s != slot);
self.asked.push((slot, source.clone()));
(
Vec::new(),
PickerStatus::Fetching,
Some(SettingsIntent::ListModels(slot)),
)
}
};
let results = (0..all.len()).collect();
self.picker = Some(PickerState {
field: id,
slot,
source,
input,
all,
results,
// On the first catalogue row when there is one: the list is the
// reason the picker opened.
selected: 1,
scroll: ListScroll::default(),
status,
});
self.picker_clamp();
intent
}
/// What a slot points at right now — its mode, the address and where the key
/// comes from, as one string.
///
/// This is the cache key, and the reason for it: a slot's **provider changes
/// inside one visit** to this screen. Keyed by the slot alone, the first
/// answer was shown under every mode cycled to afterwards — OpenAI's 132
/// models offered for `gemini`, `claude` and `grok` (reported from a live run,
/// 2026-09-18). Where the key comes from is in here too, so correcting a
/// mistyped variable name asks again instead of repeating "no key".
pub(super) fn slot_source(&self, slot: ModelSlot) -> String {
let cfg = &self.config;
let (mode, external, cloud, secret) = match slot {
ModelSlot::Assistant => (
format!("{:?}", cfg.engine.mode),
&cfg.engine.external,
cfg.engine.cloud(),
cfg.engine.secret_key(),
),
ModelSlot::Impersonation => (
format!("{:?}", cfg.impersonation_engine.mode),
&cfg.impersonation_engine.external,
cfg.impersonation_engine.cloud(),
cfg.impersonation_engine.secret_key(),
),
ModelSlot::Embedder => (
format!("{:?}", cfg.embed.mode),
&cfg.embed.external,
cfg.embed.cloud(),
cfg.embed.secret_key(),
),
};
let (url, env) = match cloud {
Some(c) => (c.url.as_deref(), c.api_key_env.as_deref()),
None => (external.url.as_deref(), external.api_key_env.as_deref()),
};
let stored = secret
.as_ref()
.is_some_and(|k| self.secrets_present.contains(k));
format!(
"{mode}|{}|{}|{stored}",
url.unwrap_or_default(),
env.unwrap_or_default()
)
}
/// The answer to [`SettingsIntent::ListModels`], from the orchestrator.
///
/// Kept per slot while the screen is open (N6), so re-opening the picker
/// costs nothing; `Ctrl+R` inside it is what asks again.
pub fn set_model_catalogue(&mut self, slot: ModelSlot, models: CatalogueAnswer) {
// Filed under what was **asked**, not under what the slot points at now:
// the two differ when the mode was cycled while the answer was in flight,
// and filing it under the new provider is the defect this key exists to
// prevent.
let asked = self
.asked
.iter()
.find(|(s, _)| *s == slot)
.map(|(_, src)| src.clone())
.unwrap_or_else(|| self.slot_source(slot));
self.asked.retain(|(s, _)| *s != slot);
self.catalogues
.retain(|(s, src, _)| !(*s == slot && *src == asked));
self.catalogues.push((slot, asked.clone(), models.clone()));
let Some(st) = self
.picker
.as_mut()
.filter(|st| st.slot == slot && st.source == asked)
else {
return;
};
match models {
Ok(list) => {
st.all = list.to_vec();
st.status = PickerStatus::Listed;
}
Err(err) => {
st.all.clear();
st.status = PickerStatus::Failed(err);
}
}
st.selected = 1;
self.picker_filter();
}
/// Recomputes the matching entries (case-insensitive, every word must
/// appear — the search overlay's rule).
pub(super) fn picker_filter(&mut self) {
let Some(st) = &mut self.picker else { return };
let q = st.input.text().to_lowercase();
let terms: Vec<&str> = q.split_whitespace().collect();
st.results = st
.all
.iter()
.enumerate()
.filter(|(_, m)| {
let hay = format!(
"{} {}",
m.id.to_lowercase(),
m.display.as_deref().unwrap_or_default().to_lowercase()
);
terms.iter().all(|t| hay.contains(t))
})
.map(|(i, _)| i)
.collect();
self.picker_clamp();
}
/// Keeps the highlight on a row that exists.
fn picker_clamp(&mut self) {
if let Some(st) = &mut self.picker {
let last = st.rows().saturating_sub(1);
st.selected = st.selected.min(last);
}
}
pub(super) fn handle_picker_key(&mut self, key: KeyEvent) -> Option<SettingsIntent> {
let st = self.picker.as_mut()?;
match (key.code, key.modifiers) {
(KeyCode::Esc, _) => {
self.picker = None;
None
}
(KeyCode::Up, _) => {
st.selected = st.selected.saturating_sub(1);
None
}
(KeyCode::Down, _) => {
if st.selected + 1 < st.rows() {
st.selected += 1;
}
None
}
(KeyCode::Home, _) => {
st.selected = 0;
None
}
(KeyCode::End, _) => {
st.selected = st.rows().saturating_sub(1);
None
}
(KeyCode::Enter, _) => {
let picked = st.picked().map(|m| m.id.clone());
let field = st.field;
self.picker = None;
match picked {
// The catalogue's id, verbatim: on a multi-model endpoint
// this string is what selects the model (N3).
Some(id) => self.apply_text(field, &id),
// "Type a name by hand" — the editor the row has always had.
None => {
let value = self
.fields()
.into_iter()
.find(|f| f.id == field)
.and_then(|f| match f.kind {
FieldKind::Text(v) => Some(v),
_ => None,
})
.unwrap_or_default();
self.open_text_editor(field, &value);
None
}
}
}
// Ask the provider again — the catalogue is otherwise kept for the
// whole visit to the screen (N6).
(KeyCode::Char(_), KeyModifiers::CONTROL) => {
match keys::hotkey_char(&key) {
Some('r') => {
let (slot, source) = (st.slot, st.source.clone());
st.all.clear();
st.results.clear();
st.status = PickerStatus::Fetching;
self.catalogues
.retain(|(s, src, _)| !(*s == slot && *src == source));
self.asked.retain(|(s, _)| *s != slot);
self.asked.push((slot, source));
Some(SettingsIntent::ListModels(slot))
}
// Every other Ctrl combination belongs to the filter's own
// input (Ctrl+K clears it).
_ => {
st.input.on_key(key);
self.picker_filter();
None
}
}
}
_ => {
st.input.on_key(key);
self.picker_filter();
None
}
}
}
/// Whether this row's provider has already been asked and had nothing to
/// give — in which case `Enter` opens the editor directly rather than a
/// picker that could only repeat the refusal (fork F1(a)).
pub(super) fn catalogue_refused(&self, id: FieldId) -> bool {
let Some(slot) = model_slot(id) else {
return false;
};
let source = self.slot_source(slot);
self.catalogues
.iter()
.any(|(s, src, answer)| *s == slot && *src == source && answer.is_err())
}
/// One rendered row of the picker: what the user reads.
///
/// The id first, because the id is what the field takes; then the name the
/// endpoint published for people, and the day it stops serving the model —
/// both only when it published them.
pub(super) fn picker_label(&self, m: &CatalogModel) -> String {
let mut line = m.id.clone();
if let Some(display) = m.display.as_deref().filter(|d| *d != m.id) {
line.push_str(" — ");
line.push_str(display);
}
if let Some(day) = &m.retiring {
line.push_str(&format!(
" · {}",
self.loc()
.tf("ui.settings.models.retiring", &[("date", day)])
));
}
line
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::shared::api::catalogue::ModelRole;
fn model(id: &str, display: Option<&str>) -> CatalogModel {
CatalogModel {
id: id.to_string(),
display: display.map(str::to_string),
role: ModelRole::Unstated,
retiring: None,
}
}
#[test]
fn a_label_carries_the_id_first_and_the_published_extras_after() {
let s = SettingsScreen::new(AppConfig::default(), vec![], vec![]);
assert_eq!(s.picker_label(&model("gpt-5.6-sol", None)), "gpt-5.6-sol");
assert_eq!(
s.picker_label(&model("claude-opus-5", Some("Claude Opus 5"))),
"claude-opus-5 — Claude Opus 5"
);
assert_eq!(
s.picker_label(&CatalogModel {
retiring: Some("2026-10-23".into()),
..model("gpt-4", None)
}),
format!(
"gpt-4 · {}",
s.loc()
.tf("ui.settings.models.retiring", &[("date", "2026-10-23")])
)
);
}
}