From 5eb56ecbaa9e7802a2a4906efc47d5f0b7d6c79a Mon Sep 17 00:00:00 2001 From: zjywill Date: Tue, 24 Nov 2026 11:43:52 +0800 Subject: [PATCH 1/2] Scroll model picker results across catalog batches Exclude stale managed catalog rows before pagination when the account cannot use them. Keep the unreadable-provider diagnostic if its descriptor is missing. Append model batches as the user scrolls, keeping selection and skipping batches with no selectable model. Keep cursor navigation out of the picker. Amp-Thread-ID: https://ampcode.com/threads/T-01a20b77-de7e-761c-ac5a-7cb00ce255e9 --- crates/dim-app-server/src/provider/query.rs | 18 +- crates/dim-app-server/tests/provider_flow.rs | 70 ++++++ crates/dim-cli/src/model/session.rs | 6 +- crates/dim-cli/src/session_host.rs | 30 +-- crates/dim-cli/src/ui/i18n/de/chrome.rs | 2 - crates/dim-cli/src/ui/i18n/es/chrome.rs | 2 - crates/dim-cli/src/ui/i18n/fr/chrome.rs | 2 - crates/dim-cli/src/ui/i18n/id/chrome.rs | 2 - crates/dim-cli/src/ui/i18n/ja/chrome.rs | 2 - crates/dim-cli/src/ui/i18n/ko/chrome.rs | 2 - crates/dim-cli/src/ui/i18n/pt_br/chrome.rs | 2 - crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs | 2 - crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs | 2 - crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs | 2 - crates/dim-cli/src/ui/models_panel.rs | 239 ++++++++++++++----- crates/dim-cli/src/ui/tui.rs | 17 +- crates/dimcode/tests/cli_tui_flow.rs | 32 ++- docs/design/appserver/provider-management.md | 11 +- docs/design/cli-commands.md | 29 ++- docs/zh/design/cli-commands.md | 10 +- 20 files changed, 342 insertions(+), 140 deletions(-) diff --git a/crates/dim-app-server/src/provider/query.rs b/crates/dim-app-server/src/provider/query.rs index 9b308f4663..20bb47787c 100644 --- a/crates/dim-app-server/src/provider/query.rs +++ b/crates/dim-app-server/src/provider/query.rs @@ -144,6 +144,17 @@ impl ProviderService { let provider_matches = query .as_ref() .is_none_or(|q| display.to_lowercase().contains(q)); + let scan_models = match &header { + Ok(Some(PersistedProviderRecord::Managed(record))) => { + match accounts.get(&id) { + Some(account) if account.account.is_some() + && same_account(&record.account, account) => true, + Some(_) => continue, + None => false, + } + } + _ => true, + }; let mut after = input .after .as_ref() @@ -152,6 +163,7 @@ impl ProviderService { .unwrap_or_default(); let mut saw_model = false; loop { + if !scan_models { break; } let batch = persistence::model_keys( &tx, &bundled, @@ -280,11 +292,7 @@ impl ProviderService { .unwrap_or_default(); (catalog, preferences) } - Ok(Some(PersistedProviderRecord::Managed(record))) - if accounts.get(&provider_id).is_some_and(|a| { - a.account.is_some() && same_account(&record.account, a) - }) => - { + Ok(Some(PersistedProviderRecord::Managed(record))) => { let catalog = record.catalog(&bundled); let preferences = record .model_preferences diff --git a/crates/dim-app-server/tests/provider_flow.rs b/crates/dim-app-server/tests/provider_flow.rs index 872c9407f6..e5622a32eb 100644 --- a/crates/dim-app-server/tests/provider_flow.rs +++ b/crates/dim-app-server/tests/provider_flow.rs @@ -10955,6 +10955,76 @@ async fn model_pages_follow_committed_edits_and_selection_uses_exact_targets() { std::fs::remove_dir_all(home).unwrap(); } +#[tokio::test] +async fn model_page_keeps_magpie_visible_without_the_dim_account_plugin() { + use dim_app_server::provider::ModelQuery; + + let home = temp_home("provider-model-page-without-oauth"); + let (root, provider) = provider_root(&home).await; + let cancel = CancellationToken::new(); + let (base, server) = listing_server(json!({"data":[{"id":"magpie-model", + "context_window":64000,"max_output_tokens":512}]})) + .await; + let magpie = provider + .management("magpie".into(), None, &cancel) + .await + .unwrap(); + provider + .update( + "magpie".into(), + magpie.providers[0].info.version.unwrap(), + serde_json::from_value(json!({"baseUrl":format!("{base}/v1"),"enabled":true, + "credential":{"action":"set","value":"fixture-key"}})) + .unwrap(), + &cancel, + ) + .await + .unwrap(); + let models: Vec<_> = (0..40) + .map(|index| { + json!({"entry":model(&format!("old-{index:02}"), 512), + "protocol":"openai-compatible","unavailableReason":null,"zdr":false}) + }) + .collect(); + let record = json!({"kind":"managed","version":1,"models":models, + "account":{"credentialEpoch":"fixture","generation":1, + "account":{"issuer":"fixture","subject":"fixture","grantedScopes":[]}}, + "modelConfigOverrides":[],"disabledModelIds":[],"modelAliases":{}}); + let database = rusqlite::Connection::open(home.join("native.sqlite")).unwrap(); + dim_app_server::provider::testing::replace_provider( + &database, + "dimcode-api-oauth", + 1, + &record.to_string(), + ) + .unwrap(); + drop(database); + + let page = provider + .query_models(ModelQuery::default(), &cancel) + .await + .unwrap(); + let selectable: Vec<_> = page + .models + .iter() + .filter(|row| !row.disabled && row.model.unavailable_reason.is_none()) + .map(|row| (row.provider_id.as_str(), row.model.id.as_str())) + .collect(); + assert_eq!(selectable, [("magpie", "magpie-model")]); + let page = serde_json::to_value(page).unwrap(); + assert!(page["next"].is_null(), "{page}"); + assert!( + page["empty"].as_array().unwrap().iter().any(|row| { + row["providerId"] == "dimcode-api-oauth" && row["reason"]["kind"] == "unreadable" + }), + "{page}" + ); + + root.shutdown().await.unwrap(); + server.abort(); + std::fs::remove_dir_all(home).unwrap(); +} + #[tokio::test] #[ignore = "records warm provider-read measurements against a disposable store"] async fn measure_on_demand_provider_reads() { diff --git a/crates/dim-cli/src/model/session.rs b/crates/dim-cli/src/model/session.rs index ef8356684f..c10551bab4 100644 --- a/crates/dim-cli/src/model/session.rs +++ b/crates/dim-cli/src/model/session.rs @@ -1442,7 +1442,11 @@ pub enum Update { /// What `/update` found: a newer version, `None` when this build is the /// newest, or why nothing can be offered. UpgradeChecked(Result, String>), - Models(Result), + Models { + query: String, + after: Option, + result: Result, + }, EffortChoices(Result), /// Sent only by a daemon that advertises the policy methods. ModelPolicy(ModelPolicyUpdate), diff --git a/crates/dim-cli/src/session_host.rs b/crates/dim-cli/src/session_host.rs index 3521fdcc5e..b0fcf50db3 100644 --- a/crates/dim-cli/src/session_host.rs +++ b/crates/dim-cli/src/session_host.rs @@ -1989,19 +1989,11 @@ impl Worker { } } Command::ListModels => { - let models = self - .models(String::new(), None) - .await - .map_err(|error| error.to_string()); - self.send(Update::Models(models)); + self.send_models(String::new(), None).await; self.read_model_policy(false).await; } Command::QueryModels { query, after } => { - let models = self - .models(query, after) - .await - .map_err(|error| error.to_string()); - self.send(Update::Models(models)); + self.send_models(query, after).await; } Command::ReadIsolation => { if !self.client.supports(&["settings.read", "settings.update"]) { @@ -2236,11 +2228,7 @@ impl Worker { // The reread lands before the notice: a conflict tells the // user to reread and retry, so the row a retry presses must // already carry the record's current version. - let models = self - .models(query, after) - .await - .map_err(|error| error.to_string()); - self.send(Update::Models(models)); + self.send_models(query, after).await; self.send(Update::Notice(match result { Ok(()) => { "Saved model preferences cleared; select the model to adopt its defaults" @@ -3957,6 +3945,18 @@ impl Worker { result.map_err(|error| error.to_string()) } + async fn send_models(&mut self, query: String, after: Option) { + let result = self + .models(query.clone(), after.clone()) + .await + .map_err(|error| error.to_string()); + self.send(Update::Models { + query, + after, + result, + }); + } + async fn models( &mut self, query: String, diff --git a/crates/dim-cli/src/ui/i18n/de/chrome.rs b/crates/dim-cli/src/ui/i18n/de/chrome.rs index 62d6911b55..e5e8df9abb 100644 --- a/crates/dim-cli/src/ui/i18n/de/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/de/chrome.rs @@ -485,8 +485,6 @@ pub fn lookup(english: &str) -> Option<&'static str> { // models_panel.rs "Select a model" => "Modell wählen", "Loading models..." => "Lade Modelle…", - "Previous page" => "Vorherige Seite", - "Next page" => "Nächste Seite", "No models available. Connect a provider first." => { "Keine Modelle. Erst Provider verbinden." } diff --git a/crates/dim-cli/src/ui/i18n/es/chrome.rs b/crates/dim-cli/src/ui/i18n/es/chrome.rs index 3d6e807825..b4ceda7854 100644 --- a/crates/dim-cli/src/ui/i18n/es/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/es/chrome.rs @@ -491,8 +491,6 @@ pub fn lookup(english: &str) -> Option<&'static str> { // models_panel.rs "Select a model" => "Elige un modelo", "Loading models..." => "Cargando modelos…", - "Previous page" => "Página anterior", - "Next page" => "Página siguiente", "No models available. Connect a provider first." => { "Sin modelos. Conecta un proveedor primero." } diff --git a/crates/dim-cli/src/ui/i18n/fr/chrome.rs b/crates/dim-cli/src/ui/i18n/fr/chrome.rs index 26a9e511c0..6a94c257f1 100644 --- a/crates/dim-cli/src/ui/i18n/fr/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/fr/chrome.rs @@ -477,8 +477,6 @@ pub fn lookup(english: &str) -> Option<&'static str> { // models_panel.rs "Select a model" => "Choisir un modèle", "Loading models..." => "Chargement…", - "Previous page" => "Page précédente", - "Next page" => "Page suivante", "No models available. Connect a provider first." => { "Aucun modèle. Connecter d'abord un fournisseur." } diff --git a/crates/dim-cli/src/ui/i18n/id/chrome.rs b/crates/dim-cli/src/ui/i18n/id/chrome.rs index ebf71e35c6..19b455aa0c 100644 --- a/crates/dim-cli/src/ui/i18n/id/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/id/chrome.rs @@ -471,8 +471,6 @@ pub fn lookup(english: &str) -> Option<&'static str> { // models_panel.rs "Select a model" => "Pilih model", "Loading models..." => "Memuat model…", - "Previous page" => "Halaman sebelumnya", - "Next page" => "Halaman berikutnya", "No models available. Connect a provider first." => { "Tak ada model. Hubungkan provider dulu." } diff --git a/crates/dim-cli/src/ui/i18n/ja/chrome.rs b/crates/dim-cli/src/ui/i18n/ja/chrome.rs index cdc02ea050..674b577d3a 100644 --- a/crates/dim-cli/src/ui/i18n/ja/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/ja/chrome.rs @@ -453,8 +453,6 @@ pub fn lookup(english: &str) -> Option<&'static str> { // models_panel.rs "Select a model" => "モデルを選択", "Loading models..." => "モデルを読込中…", - "Previous page" => "前のページ", - "Next page" => "次のページ", "No models available. Connect a provider first." => { "利用可能なモデルなし。先にプロバイダーに接続" } diff --git a/crates/dim-cli/src/ui/i18n/ko/chrome.rs b/crates/dim-cli/src/ui/i18n/ko/chrome.rs index a85de65140..bd2f160088 100644 --- a/crates/dim-cli/src/ui/i18n/ko/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/ko/chrome.rs @@ -435,8 +435,6 @@ pub fn lookup(english: &str) -> Option<&'static str> { // models_panel.rs "Select a model" => "모델 선택", "Loading models..." => "모델 불러오는 중…", - "Previous page" => "이전 페이지", - "Next page" => "다음 페이지", "No models available. Connect a provider first." => { "사용 가능한 모델 없음. 먼저 프로바이더 연결" } diff --git a/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs b/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs index 6e30b65e3f..3cf390a549 100644 --- a/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs @@ -481,8 +481,6 @@ pub fn lookup(english: &str) -> Option<&'static str> { // models_panel.rs "Select a model" => "Selecione um modelo", "Loading models..." => "Carregando modelos…", - "Previous page" => "Página anterior", - "Next page" => "Próxima página", "No models available. Connect a provider first." => { "Nenhum modelo disponível. Conecte um provedor." } diff --git a/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs b/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs index dd795c7129..24b373f078 100644 --- a/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs @@ -489,8 +489,6 @@ pub fn lookup(english: &str) -> Option<&'static str> { // models_panel.rs "Select a model" => "Selecionar modelo", "Loading models..." => "A carregar modelos…", - "Previous page" => "Página anterior", - "Next page" => "Página seguinte", "No models available. Connect a provider first." => { "Sem modelos disponíveis. Ligue primeiro um fornecedor." } diff --git a/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs b/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs index dd4732d527..978b8472fd 100644 --- a/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs @@ -488,8 +488,6 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Select a model" => "选择模型", "Loading models..." => "正在加载模型...", - "Previous page" => "上一页", - "Next page" => "下一页", "No models available. Connect a provider first." => "无可用模型。请先连接 Provider。", "No matching models." => "无匹配的模型。", "current" => "当前", diff --git a/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs b/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs index e926f2ba7b..2a891140df 100644 --- a/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs @@ -429,8 +429,6 @@ pub fn lookup(english: &str) -> Option<&'static str> { // models_panel.rs "Select a model" => "選擇模型", "Loading models..." => "正在載入模型…", - "Previous page" => "上一頁", - "Next page" => "下一頁", "No models available. Connect a provider first." => "沒有可用的模型。請先連線供應商。", "No matching models." => "沒有相符的模型。", "current" => "目前", diff --git a/crates/dim-cli/src/ui/models_panel.rs b/crates/dim-cli/src/ui/models_panel.rs index 522bd16bce..c5035334f5 100644 --- a/crates/dim-cli/src/ui/models_panel.rs +++ b/crates/dim-cli/src/ui/models_panel.rs @@ -9,7 +9,7 @@ //! > Search models //! › Dim OAuth / deepseek-v4.1-flash ‹ high › current //! Dim OAuth / gpt-6-astra medium -//! Previous page / Next page +//! … more models as the list scrolls … //! Selected: Dim OAuth / deepseek-v4.1-flash unidentified //! Subagent models //! › Agent choice Enter @@ -35,8 +35,8 @@ //! //! Tab/Shift+Tab moves between the three sections and Up/Down stays inside //! the focused one. The search filters the candidates only; the sections -//! stay where they are. The daemon answers the search and the Previous page / -//! Next page rows with bounded pages, one request at a time. Escape from a +//! stay where they are. Searches and forward scrolling read bounded batches; +//! empty batches are traversed without exposing a navigation row. Escape from a //! child page returns one level and restores the query, selection and list //! position; at the root it clears the search first, then closes. //! @@ -78,8 +78,6 @@ const HINT: &str = "Enter select + default · ←/→ effort · Tab section · E const POLICY_SECTION_HINT: &str = "Enter change · Tab section · Esc clear/close"; const MANAGEMENT_SECTION_HINT: &str = "Enter manage · Tab section · Esc clear/close"; const POLICY_HINT: &str = "Enter select · Esc back"; -const PREVIOUS_MODELS: &str = "__previous_models__"; -const NEXT_MODELS: &str = "__next_models__"; const MANAGE_HINT: &str = "Enter manage · Esc back"; const CONVERSATION: &str = "Conversation model"; const AGENT: &str = "agent"; @@ -123,7 +121,8 @@ pub struct ModelsPanel { /// Effort ←/→ chose for `provider::model`, kept across list replacements /// while the row is listed and advertises it. chosen: BTreeMap, - pages: Vec>, + pages: Vec, + refill: usize, requesting: bool, } @@ -137,16 +136,97 @@ impl ModelsPanel { listed: None, policy: None, chosen: BTreeMap::new(), - pages: vec![None], + pages: Vec::new(), + refill: 0, requesting: false, } } - pub fn set_models(&mut self, models: Result) { - if models - .as_ref() - .is_ok_and(|page| page.query != self.list.query()) + fn query(&self) -> &str { + match self.view { + View::Models | View::Fixed => self.list.query(), + View::Policy | View::Manage => self.root.query(), + } + } + + pub fn refresh(&mut self) -> Effect { + self.refill = self.pages.len(); + self.pages.clear(); + self.request(None) + } + + pub fn page( + &mut self, + query: &str, + after: Option, + result: Result, + ) -> Effect { + if query != self.query() { + return Effect::None; + } + let index = match after.as_ref() { + Some(after) => { + let Some(before) = self + .pages + .iter() + .position(|page| page.next.as_ref() == Some(after)) + else { + return Effect::None; + }; + before + 1 + } + None => 0, + }; + let page = match result { + Ok(page) => page, + Err(error) => { + self.refill = 0; + if after.is_none() || self.models().is_empty() { + self.set_models(Err(error.clone())); + } + self.requesting = false; + return Effect::Notice(error); + } + }; + let empty = page.models.is_empty(); + if let Some(previous) = self.pages.get_mut(index) { + let same_end = previous.next == page.next; + *previous = page; + if !same_end { + self.pages.truncate(index + 1); + } + } else { + self.pages.push(page); + } + if self.pages.len() < self.refill + && let Some(next) = self.pages.last().and_then(|page| page.next.clone()) { + return self.request(Some(next)); + } + self.refill = 0; + let mut combined = self.pages[0].clone(); + for page in &self.pages[1..] { + combined.models.extend(page.models.iter().cloned()); + combined.empty.extend(page.empty.iter().cloned()); + combined.limits.extend(page.limits.iter().cloned()); + combined.next.clone_from(&page.next); + } + let next = combined.next.clone(); + self.set_models(Ok(combined)); + if let Some(next) = next + && empty + && index + 1 == self.pages.len() + { + if self.models().is_empty() && matches!(self.view, View::Models | View::Fixed) { + self.list.loading(); + } + return self.request(Some(next)); + } + Effect::None + } + + fn set_models(&mut self, models: Result) { + if models.as_ref().is_ok_and(|page| page.query != self.query()) { return; } if !self.requesting && models.is_err() && self.listed.as_ref().is_some_and(Result::is_ok) { @@ -273,26 +353,19 @@ impl ModelsPanel { let items = match self.view { View::Policy => Some(Ok(self.policy_rows(mode))), View::Models | View::Fixed => self.listed.as_ref().map(|listed| { - listed.clone().map(|list| { - let mut items = model_rows( + listed.as_ref().map_err(Clone::clone).map(|list| { + model_rows( &list.models, marked.as_deref(), if effort { focus.as_deref() } else { None }, if effort { Some(&self.chosen) } else { None }, - ); - if self.pages.len() > 1 { - items.push(Item::new(PREVIOUS_MODELS, t("Previous page"), "")); - } - if list.next.is_some() { - items.push(Item::new(NEXT_MODELS, t("Next page"), "")); - } - items + ) }) }), View::Manage => self .listed .as_ref() - .map(|listed| listed.clone().map(|list| provider_rows(&list))), + .map(|listed| listed.as_ref().map_err(Clone::clone).map(provider_rows)), }; if let Some(items) = items { let preselect = preselect.or(selected.as_deref()).or(marked.as_deref()); @@ -605,6 +678,21 @@ impl ModelsPanel { } } + fn request(&mut self, after: Option) -> Effect { + self.requesting = true; + Effect::QueryModels { + query: self.query().to_owned(), + after, + } + } + + fn search(&mut self) -> Effect { + self.pages.clear(); + self.refill = 0; + self.list.loading(); + self.request(None) + } + /// A paste goes into the filter. pub fn paste(&mut self, text: &str) -> Effect { if self.view == View::Models { @@ -615,13 +703,7 @@ impl ModelsPanel { if !matches!(self.view, View::Models | View::Fixed) { return Effect::None; } - self.pages = vec![None]; - self.list.loading(); - self.requesting = true; - Effect::QueryModels { - query: self.list.query().to_owned(), - after: None, - } + self.search() } pub fn handle_key(&mut self, key: KeyEvent) -> Effect { @@ -663,13 +745,7 @@ impl ModelsPanel { let query = self.list.query().to_owned(); let event = self.list.handle_key(key); if matches!(self.view, View::Models | View::Fixed) && query != self.list.query() { - self.pages = vec![None]; - self.list.loading(); - self.requesting = true; - return Effect::QueryModels { - query: self.list.query().to_owned(), - after: None, - }; + return self.search(); } if self.view == View::Models && self.section == Section::Model @@ -678,43 +754,38 @@ impl ModelsPanel { { self.rebuild(None); } + if matches!(self.view, View::Models | View::Fixed) + && matches!( + key.code, + KeyCode::Down | KeyCode::PageDown | KeyCode::End | KeyCode::Tab + ) + && !self.requesting + && self.list.near_end() + && let Some(next) = self.pages.last().and_then(|page| page.next.clone()) + { + return self.request(Some(next)); + } self.dispatch(event) } fn dispatch(&mut self, event: Event) -> Effect { match (self.view, event) { (_, Event::None | Event::Refresh) => Effect::None, - (_, Event::Pick { id, .. }) if id == NEXT_MODELS => { - let after = self - .listed - .as_ref() - .and_then(|v| v.as_ref().ok()) - .and_then(|v| v.next.clone()); - self.pages.push(after.clone()); - self.list.loading(); - self.requesting = true; - Effect::QueryModels { - query: self.list.query().to_owned(), - after, - } - } - (_, Event::Pick { id, .. }) if id == PREVIOUS_MODELS => { - self.pages.pop(); - self.list.loading(); - self.requesting = true; - Effect::QueryModels { - query: self.list.query().to_owned(), - after: self.pages.last().cloned().flatten(), - } - } (View::Models, Event::Close) => Effect::Close, (View::Policy, Event::Close) => { self.back_to_root(Section::Policy); Effect::None } (View::Fixed, Event::Close) => { + let changed = self.list.query() != self.root.query(); self.open_child(View::Policy, Some(FIXED)); - Effect::None + if changed { + self.pages.clear(); + self.refill = 0; + self.request(None) + } else { + Effect::None + } } (View::Manage, Event::Close) => { self.back_to_root(Section::Management); @@ -766,12 +837,22 @@ impl ModelsPanel { }; self.chosen.remove(&id); self.rebuild(None); + let after = self + .pages + .iter() + .position(|page| { + page.models + .iter() + .any(|m| key(&m.provider_id, &m.model_id) == id) + }) + .and_then(|index| index.checked_sub(1)) + .and_then(|index| self.pages[index].next.clone()); self.models() .iter() .find(|model| id == self::key(&model.provider_id, &model.model_id)) .map(|model| Effect::ClearModelPreferences { query: self.list.query().to_owned(), - after: self.pages.last().cloned().flatten(), + after, provider_id: model.provider_id.clone(), model_id: model.model_id.clone(), expected_version: model.provider_version, @@ -1043,11 +1124,43 @@ fn providers(list: &ModelList) -> Vec { } for limits in &list.limits { let at = slot(&limits.provider_id, &limits.provider_name, &mut providers); - providers[at].limits = Some(limits.clone()); + if let Some(total) = &mut providers[at].limits { + total.count += limits.count; + for candidate in &limits.candidates { + if !total.candidates.contains(candidate) { + total.candidates.push(candidate.clone()); + } + } + } else { + providers[at].limits = Some(limits.clone()); + } } + let counts = |reason| match reason { + EmptyReason::Unavailable { count } => (count, 0), + EmptyReason::Disabled { count } => (0, count), + EmptyReason::Mixed { + unavailable, + disabled, + } => (unavailable, disabled), + EmptyReason::NoModels { .. } | EmptyReason::Unreadable => (0, 0), + }; for empty in &list.empty { let at = slot(&empty.provider_id, &empty.provider_name, &mut providers); - providers[at].empty = Some(empty.clone()); + if let Some(total) = &mut providers[at].empty { + let (u1, d1) = counts(total.reason); + let (u2, d2) = counts(empty.reason); + total.reason = match (u1 + u2, d1 + d2) { + (0, 0) => empty.reason, + (0, count) => EmptyReason::Disabled { count }, + (count, 0) => EmptyReason::Unavailable { count }, + (unavailable, disabled) => EmptyReason::Mixed { + unavailable, + disabled, + }, + }; + } else { + providers[at].empty = Some(empty.clone()); + } } providers } diff --git a/crates/dim-cli/src/ui/tui.rs b/crates/dim-cli/src/ui/tui.rs index b56943edf1..2a5fc64264 100644 --- a/crates/dim-cli/src/ui/tui.rs +++ b/crates/dim-cli/src/ui/tui.rs @@ -3148,12 +3148,14 @@ impl App { panel.set_providers(providers); } } - Update::Models(models) => { - if let Err(error) = &models { - self.set_notice(error.clone()); - } + Update::Models { + query, + after, + result, + } => { if let Some(Prompt::Models(panel)) = &mut self.prompt { - panel.set_models(models); + let effect = panel.page(&query, after, result); + self.apply_effect(effect); } } Update::EffortChoices(result) => { @@ -4306,10 +4308,11 @@ impl App { self.host.send(Command::CloseSessions); } if matches!(self.prompt, Some(Prompt::Management(_))) - && let Some(panel) = self.models_return.take() + && let Some(mut panel) = self.models_return.take() { + let effect = panel.refresh(); self.prompt = Some(Prompt::Models(Box::new(panel))); - self.host.send(Command::ListModels); + self.apply_effect(effect); return Outcome::Continue; } self.prompt = match self.prompt.take() { diff --git a/crates/dimcode/tests/cli_tui_flow.rs b/crates/dimcode/tests/cli_tui_flow.rs index 15efe28205..4308d673b2 100644 --- a/crates/dimcode/tests/cli_tui_flow.rs +++ b/crates/dimcode/tests/cli_tui_flow.rs @@ -7752,7 +7752,7 @@ fn tui_models_picker_draws_its_hint_in_the_interface_language() { } #[test] -fn tui_models_picker_reads_pages_on_demand_and_reopens_without_a_cache() { +fn tui_models_picker_scrolls_across_batches_and_reopens_without_a_cache() { let home = Home::new(); let daemon = home.daemon(|wire| { wire.hello(&[]); @@ -7768,20 +7768,38 @@ fn tui_models_picker_reads_pages_on_demand_and_reopens_without_a_cache() { wire.reply(&first, json!({"models":[],"empty":[{"providerId":"empty","providerName":"Empty","reason":{"kind":"no_models","listable":true}}],"next":{"providerId":"empty","modelId":""}})); let next = wire.read("provider.models.query"); assert_eq!(next["params"]["after"], json!({"providerId":"empty","modelId":""})); - let snapshot = json!({"catalog":{"version":1,"disabledModelIds":[],"models":[{"id":"second","name":"Second","capabilities":dim_agent_types::CatalogCapabilities::with_limits(128_000,16_384)}]}}); - wire.reply(&next, picker_page("test", "Test", snapshot.clone())); + let snapshot = |id| json!({"catalog":{"version":1,"disabledModelIds":[],"models":[{"id":id,"name":id,"capabilities":dim_agent_types::CatalogCapabilities::with_limits(128_000,16_384)}]}}); + let mut second = picker_page("test", "Test", snapshot("second")); + second["next"] = json!({"providerId":"test","modelId":"second"}); + wire.reply(&next, second); + let filtered = wire.read("provider.models.query"); + assert_eq!(filtered["params"]["after"], json!({"providerId":"test","modelId":"second"})); + let mut skipped = picker_page("test", "Test", snapshot("second-disabled")); + skipped["models"][0]["disabled"] = json!(true); + skipped["next"] = json!({"providerId":"test","modelId":"second-disabled"}); + wire.reply(&filtered, skipped); + let third = wire.read("provider.models.query"); + assert_eq!(third["params"]["after"], json!({"providerId":"test","modelId":"second-disabled"})); + wire.reply(&third, picker_page("test", "Test", snapshot("third"))); let reopened = wire.read("provider.models.query"); assert!(reopened["params"]["after"].is_null()); - wire.reply(&reopened, picker_page("test", "Changed", snapshot)); + wire.reply(&reopened, picker_page("test", "Changed", snapshot("second"))); wire.hold(); }); let mut terminal = Terminal::resume_tui(home.command()); terminal.until("test / model"); terminal.write(b"/models\r"); - terminal.until("Empty: no models"); - terminal.until_anywhere("Next page"); - terminal.write(b"\r"); terminal.until("Test / second"); + terminal.until_anywhere("Empty: no models"); + terminal.raw(b"\x1b[B"); + terminal.until("Test / third"); + terminal.raw(b"\x1b[B"); + terminal.until("Selected: Test / third"); + terminal.raw(b"\x1b[A"); + terminal.until("Selected: Test / second"); + let shown = strip_ansi(&terminal.transcript); + assert!(!shown.contains("Next page") && !shown.contains("Previous page")); + assert!(!shown.contains("Test / second-disabled")); terminal.raw(b"\x1b"); terminal.until("Ask anything..."); terminal.write(b"/models\r"); diff --git a/docs/design/appserver/provider-management.md b/docs/design/appserver/provider-management.md index 68b8449ca2..c29f7610a2 100644 --- a/docs/design/appserver/provider-management.md +++ b/docs/design/appserver/provider-management.md @@ -340,11 +340,12 @@ and `disabled`. Disabled and unavailable models remain visible for diagnostics. `{kind:"no_models", listable}` or `{kind:"unreadable"}`. Each page admits at most `limit` model or empty-provider candidates, so a page containing errors can have fewer models. `next:null` ends traversal. A candidate deleted before its target read -is skipped; a later unreadable row is reported in `empty`. A stored empty managed provider -without an account descriptor is reported as unreadable. Invalid limits fail with -`provider_invalid_config`; cancellation and storage errors follow the Provider -operation contract. Reads perform no remote catalog refresh. Refresh is an -explicit management operation. +is skipped; a later unreadable row is reported in `empty`. A stored managed catalog +without a matching signed-in account does not contribute model candidates. If its +account descriptor is absent, it contributes one unreadable provider entry instead. +Invalid limits fail with `provider_invalid_config`; cancellation and storage +errors follow the Provider operation contract. Reads perform no remote catalog +refresh. Refresh is an explicit management operation. `provider.catalog` accepts an optional `modelId` for the adopted model's capability read. It returns the same catalog envelope with only that model and preserves the diff --git a/docs/design/cli-commands.md b/docs/design/cli-commands.md index a899a0db5d..51379b9e8b 100644 --- a/docs/design/cli-commands.md +++ b/docs/design/cli-commands.md @@ -1355,19 +1355,24 @@ the panel's confirmation. ### Model picker reads -Opening `/models` requests one page from +Opening `/models` starts a bounded read from [`provider.models.query`](appserver/provider-management.md#model-display-queries). -Typing searches on the server and resets the page cursor. Next/Previous replace -the displayed page; closing the picker releases its results. Capability reads for -the adopted model pass its provider and model ID. Catalog refresh is the explicit -management action in the provider/account panel. Counts in picker diagnostics -refer to the displayed page. - -```text -/models -> first page -> Next page -> next page - ^ | - +------ Previous page ----+ -Type query -> first matching page +The conversation and fixed subagent model lists scroll continuously. Near the +end, moving down requests the next batch and appends any selectable models +without moving the selection. A batch with no selectable models is traversed +automatically while it has a continuation cursor. Cursor navigation is never +shown as a row. Until the first selectable models arrive the picker shows +loading; an empty result is shown only once traversal ends. Diagnostics describe +the batches loaded so far. Typing searches on the server and starts a new list; +closing the picker releases its results. Capability reads for the adopted model +pass its provider and model ID. Catalog refresh is the explicit management action +in the provider/account panel. + +```text +/models -> first selectable rows (or an empty result) +Scroll ↓ -> append more rows near the bottom +Scroll ↑ -> earlier rows remain in the same list +Type query -> new matching list Esc -> clear query; when empty, close and release results ``` diff --git a/docs/zh/design/cli-commands.md b/docs/zh/design/cli-commands.md index 2901ddc641..9439fcb89d 100644 --- a/docs/zh/design/cli-commands.md +++ b/docs/zh/design/cli-commands.md @@ -783,13 +783,13 @@ Ctrl+T 立即运行所选任务,并报告所有者为手动窗口记录的投 ### 模型选择读取 -打开 `/models` 时向 [`provider.models.query`](appserver/provider-management.md#模型显示查询) 请求一页。输入在服务器上搜索并重置页游标;Next/Previous 替换显示的页;关闭选择面板释放其结果。已采用模型的能力读取带上它的提供方与模型 ID。目录刷新是提供方/账号面板里显式的管理操作。选择面板诊断中的计数针对当前显示的页。 +打开 `/models` 时开始向 [`provider.models.query`](appserver/provider-management.md#模型显示查询) 分批读取。对话模型与固定子代理模型都用连续滚动列表;向下接近末尾时读取下一批并追加可选模型,不移动当前选中项。没有可选模型的批次若还有游标就自动跳过,不显示翻页条目。首批可选模型到达前显示正在加载,读完仍无结果才显示空状态。诊断计数覆盖已读的批次。输入在服务器上搜索并重置列表;关闭选择面板释放结果。已采用模型的能力读取带上它的提供方与模型 ID。目录刷新是提供方/账号面板里显式的管理操作。 ```text -/models -> 第一页 -> Next page -> 下一页 - ^ | - +------ Previous page ----+ -输入查询 -> 第一个匹配页 +/models -> 首批可选模型(或空状态) +向下滚动 -> 接近末尾时追加模型 +向上滚动 -> 同一列表中保留前面的模型 +输入查询 -> 开始新的匹配列表 Esc -> 清除查询;查询为空时关闭并释放结果 ``` From 0ece5709c755c45201a1cbb9e0bb249efe077640 Mon Sep 17 00:00:00 2001 From: zjywill Date: Tue, 24 Nov 2026 13:16:11 +0800 Subject: [PATCH 2/2] Refresh loaded model batches after clearing preferences Provider versions are shared by every model from the same provider. Reread the loaded prefix as one update before reporting the clear result, and do not queue another clear while the picker is waiting for fresh rows. Amp-Thread-ID: https://ampcode.com/threads/T-01a20b77-de7e-761c-ac5a-7cb00ce255e9 --- crates/dim-cli/src/model/session.rs | 4 +- crates/dim-cli/src/session_host.rs | 37 +++++++---- crates/dim-cli/src/ui/models_panel.rs | 88 +++++++++++---------------- crates/dim-cli/src/ui/prompts.rs | 2 +- crates/dim-cli/src/ui/tui.rs | 4 +- crates/dimcode/tests/cli_tui_flow.rs | 58 ++++++++++++++++++ docs/design/cli-commands.md | 8 ++- docs/zh/design/cli-commands.md | 2 + 8 files changed, 131 insertions(+), 72 deletions(-) diff --git a/crates/dim-cli/src/model/session.rs b/crates/dim-cli/src/model/session.rs index c10551bab4..4a53825781 100644 --- a/crates/dim-cli/src/model/session.rs +++ b/crates/dim-cli/src/model/session.rs @@ -389,7 +389,7 @@ pub enum Command { }, ClearModelPreferences { query: String, - after: Option, + batches: usize, provider_id: String, model_id: String, expected_version: u32, @@ -1445,7 +1445,7 @@ pub enum Update { Models { query: String, after: Option, - result: Result, + result: Result, String>, }, EffortChoices(Result), /// Sent only by a daemon that advertises the policy methods. diff --git a/crates/dim-cli/src/session_host.rs b/crates/dim-cli/src/session_host.rs index b0fcf50db3..ec96b150f3 100644 --- a/crates/dim-cli/src/session_host.rs +++ b/crates/dim-cli/src/session_host.rs @@ -1989,11 +1989,11 @@ impl Worker { } } Command::ListModels => { - self.send_models(String::new(), None).await; + self.send_models(String::new(), None, 1).await; self.read_model_policy(false).await; } Command::QueryModels { query, after } => { - self.send_models(query, after).await; + self.send_models(query, after, 1).await; } Command::ReadIsolation => { if !self.client.supports(&["settings.read", "settings.update"]) { @@ -2213,7 +2213,7 @@ impl Worker { } Command::ClearModelPreferences { query, - after, + batches, provider_id, model_id, expected_version, @@ -2225,10 +2225,7 @@ impl Worker { expected_version, ) .await; - // The reread lands before the notice: a conflict tells the - // user to reread and retry, so the row a retry presses must - // already carry the record's current version. - self.send_models(query, after).await; + self.send_models(query, None, batches).await; self.send(Update::Notice(match result { Ok(()) => { "Saved model preferences cleared; select the model to adopt its defaults" @@ -3945,11 +3942,27 @@ impl Worker { result.map_err(|error| error.to_string()) } - async fn send_models(&mut self, query: String, after: Option) { - let result = self - .models(query.clone(), after.clone()) - .await - .map_err(|error| error.to_string()); + async fn send_models( + &mut self, + query: String, + after: Option, + batches: usize, + ) { + let result = async { + let mut pages = Vec::new(); + let mut cursor = after.clone(); + for _ in 0..batches { + let page = self.models(query.clone(), cursor).await?; + cursor = page.next.clone(); + pages.push(page); + if cursor.is_none() { + break; + } + } + Ok::<_, crate::Error>(pages) + } + .await + .map_err(|error| error.to_string()); self.send(Update::Models { query, after, diff --git a/crates/dim-cli/src/ui/models_panel.rs b/crates/dim-cli/src/ui/models_panel.rs index c5035334f5..d816b54e1e 100644 --- a/crates/dim-cli/src/ui/models_panel.rs +++ b/crates/dim-cli/src/ui/models_panel.rs @@ -159,47 +159,35 @@ impl ModelsPanel { &mut self, query: &str, after: Option, - result: Result, + result: Result, String>, ) -> Effect { - if query != self.query() { + if query != self.query() + || (after.is_some() + && after.as_ref() != self.pages.last().and_then(|page| page.next.as_ref())) + { return Effect::None; } - let index = match after.as_ref() { - Some(after) => { - let Some(before) = self - .pages - .iter() - .position(|page| page.next.as_ref() == Some(after)) - else { - return Effect::None; - }; - before + 1 - } - None => 0, - }; - let page = match result { - Ok(page) => page, + let pages = match result { + Ok(pages) => pages, Err(error) => { - self.refill = 0; - if after.is_none() || self.models().is_empty() { + if after.is_none() || self.refill != 0 || self.models().is_empty() { + self.pages.clear(); self.set_models(Err(error.clone())); } + self.refill = 0; self.requesting = false; return Effect::Notice(error); } }; - let empty = page.models.is_empty(); - if let Some(previous) = self.pages.get_mut(index) { - let same_end = previous.next == page.next; - *previous = page; - if !same_end { - self.pages.truncate(index + 1); - } - } else { - self.pages.push(page); + if after.is_none() { + self.pages.clear(); } + self.pages.extend(pages); + let last = self.pages.last().unwrap(); + let empty = last.models.is_empty(); + let next = last.next.clone(); if self.pages.len() < self.refill - && let Some(next) = self.pages.last().and_then(|page| page.next.clone()) + && let Some(next) = next { return self.request(Some(next)); } @@ -211,11 +199,9 @@ impl ModelsPanel { combined.limits.extend(page.limits.iter().cloned()); combined.next.clone_from(&page.next); } - let next = combined.next.clone(); self.set_models(Ok(combined)); if let Some(next) = next && empty - && index + 1 == self.pages.len() { if self.models().is_empty() && matches!(self.view, View::Models | View::Fixed) { self.list.loading(); @@ -832,32 +818,30 @@ impl ModelsPanel { // Clearing the saved preferences drops the row's cycled effort // too: the notice asks for the model to be selected again so it // adopts its defaults, and that only holds if the cycle is gone. + if self.requesting { + return Effect::None; + } let Some(id) = self.list.selected_id() else { return Effect::None; }; + let Some(model) = self + .models() + .iter() + .find(|model| key(&model.provider_id, &model.model_id) == id) + else { + return Effect::None; + }; + let effect = Effect::ClearModelPreferences { + query: self.query().to_owned(), + batches: self.pages.len().max(1), + provider_id: model.provider_id.clone(), + model_id: model.model_id.clone(), + expected_version: model.provider_version, + }; + self.requesting = true; self.chosen.remove(&id); self.rebuild(None); - let after = self - .pages - .iter() - .position(|page| { - page.models - .iter() - .any(|m| key(&m.provider_id, &m.model_id) == id) - }) - .and_then(|index| index.checked_sub(1)) - .and_then(|index| self.pages[index].next.clone()); - self.models() - .iter() - .find(|model| id == self::key(&model.provider_id, &model.model_id)) - .map(|model| Effect::ClearModelPreferences { - query: self.list.query().to_owned(), - after, - provider_id: model.provider_id.clone(), - model_id: model.model_id.clone(), - expected_version: model.provider_version, - }) - .unwrap_or(Effect::None) + effect } fn cycle(&mut self, forward: bool) -> Effect { diff --git a/crates/dim-cli/src/ui/prompts.rs b/crates/dim-cli/src/ui/prompts.rs index f591828143..3e745db9a6 100644 --- a/crates/dim-cli/src/ui/prompts.rs +++ b/crates/dim-cli/src/ui/prompts.rs @@ -265,7 +265,7 @@ pub enum Effect { }, ClearModelPreferences { query: String, - after: Option, + batches: usize, provider_id: String, model_id: String, expected_version: u32, diff --git a/crates/dim-cli/src/ui/tui.rs b/crates/dim-cli/src/ui/tui.rs index 2a5fc64264..2742d190e4 100644 --- a/crates/dim-cli/src/ui/tui.rs +++ b/crates/dim-cli/src/ui/tui.rs @@ -4699,14 +4699,14 @@ impl App { } Effect::ClearModelPreferences { query, - after, + batches, provider_id, model_id, expected_version, } => { self.host.send(Command::ClearModelPreferences { query, - after, + batches, provider_id, model_id, expected_version, diff --git a/crates/dimcode/tests/cli_tui_flow.rs b/crates/dimcode/tests/cli_tui_flow.rs index 4308d673b2..48f56d9e1b 100644 --- a/crates/dimcode/tests/cli_tui_flow.rs +++ b/crates/dimcode/tests/cli_tui_flow.rs @@ -7809,6 +7809,64 @@ fn tui_models_picker_scrolls_across_batches_and_reopens_without_a_cache() { daemon.join().unwrap(); } +#[test] +fn tui_models_picker_rereads_loaded_batches_after_clearing_preferences() { + let home = Home::new(); + let daemon = home.daemon(|wire| { + wire.hello(&[]); + let attach = wire.read("session.attach"); + wire.reply(&attach, attach_record(&attach)); + let history = wire.read("session.history"); + wire.reply(&history, json!({"events":[],"through":8,"nextAfter":8,"done":true})); + wire.no_context(); + let accounts = wire.read("account.providers"); + wire.reply(&accounts, json!([])); + + let cursor = json!({"providerId":"test","modelId":"first"}); + let page = |id, version| picker_page("test", "Test", json!({"catalog":{ + "version":version,"disabledModelIds":[],"models":[{"id":id,"name":id, + "capabilities":dim_agent_types::CatalogCapabilities::with_limits(128_000,16_384)}] + }})); + for (version, target) in [(7, "second"), (8, "first"), (9, "second"), (10, "")] { + let first = wire.read("provider.models.query"); + assert!(first["params"]["after"].is_null()); + let mut first_page = page("first", version); + first_page["next"] = cursor.clone(); + wire.reply(&first, first_page); + let second = wire.read("provider.models.query"); + assert_eq!(second["params"]["after"], cursor); + wire.reply(&second, page("second", version)); + if !target.is_empty() { + let clear = wire.read("provider.preferences.update"); + assert_eq!(clear["params"]["modelId"], target); + assert_eq!(clear["params"]["expectedVersion"], version); + wire.reply(&clear, json!({})); + } + } + wire.hold(); + }); + let mut terminal = Terminal::resume_tui(home.command()); + terminal.until("test / model"); + terminal.write(b"/models\r"); + terminal.until("Selected: Test / first"); + terminal.raw(b"\x1b[B"); + terminal.until("Test / second"); + + for (arrow, target) in [ + (b"\x1b[B", "second"), + (b"\x1b[A", "first"), + (b"\x1b[B", "second"), + ] { + terminal.raw(arrow); + terminal.until(&format!("Selected: Test / {target}")); + terminal.write(b"\x18"); + terminal.until("Saved model preferences cleared"); + } + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); +} + #[test] fn tui_models_picker_names_every_provider_with_no_selectable_model() { let home = Home::new(); diff --git a/docs/design/cli-commands.md b/docs/design/cli-commands.md index 51379b9e8b..98c5f267a5 100644 --- a/docs/design/cli-commands.md +++ b/docs/design/cli-commands.md @@ -1364,9 +1364,11 @@ automatically while it has a continuation cursor. Cursor navigation is never shown as a row. Until the first selectable models arrive the picker shows loading; an empty result is shown only once traversal ends. Diagnostics describe the batches loaded so far. Typing searches on the server and starts a new list; -closing the picker releases its results. Capability reads for the adopted model -pass its provider and model ID. Catalog refresh is the explicit management action -in the provider/account panel. +closing the picker releases its results. Clearing saved preferences rereads the +loaded batches before allowing another clear: a write changes the provider +version shared by all its model rows. Capability reads for the adopted model pass +its provider and model ID. Catalog refresh is the explicit management action in +the provider/account panel. ```text /models -> first selectable rows (or an empty result) diff --git a/docs/zh/design/cli-commands.md b/docs/zh/design/cli-commands.md index 9439fcb89d..2858bb163a 100644 --- a/docs/zh/design/cli-commands.md +++ b/docs/zh/design/cli-commands.md @@ -785,6 +785,8 @@ Ctrl+T 立即运行所选任务,并报告所有者为手动窗口记录的投 打开 `/models` 时开始向 [`provider.models.query`](appserver/provider-management.md#模型显示查询) 分批读取。对话模型与固定子代理模型都用连续滚动列表;向下接近末尾时读取下一批并追加可选模型,不移动当前选中项。没有可选模型的批次若还有游标就自动跳过,不显示翻页条目。首批可选模型到达前显示正在加载,读完仍无结果才显示空状态。诊断计数覆盖已读的批次。输入在服务器上搜索并重置列表;关闭选择面板释放结果。已采用模型的能力读取带上它的提供方与模型 ID。目录刷新是提供方/账号面板里显式的管理操作。 +清除已保存偏好后,选择面板会重新读取已加载的批次,再允许下一次清除:同一提供方的所有模型行共享被这次写入更新的版本号。 + ```text /models -> 首批可选模型(或空状态) 向下滚动 -> 接近末尾时追加模型