diff --git a/docs/architecture/model-request-cache-reuse.md b/docs/architecture/model-request-cache-reuse.md index bda773658a..bf3fa94aea 100644 --- a/docs/architecture/model-request-cache-reuse.md +++ b/docs/architecture/model-request-cache-reuse.md @@ -123,11 +123,17 @@ persistence first and then captures the context snapshot. The child session is initialized from a captured parent context snapshot: - same parent agent type -- same workspace and model config +- same workspace, with parent model configuration inherited by default - inherited message context - cloned session-level prompt cache - seeded skill/agent listing baselines derived from the parent session +`ai.btw.model_selection` may instead choose a model or pool for new side questions. +The host resolves that default before the first turn, below an explicit child +selection, and existing children retain their own choice. A changed model starts +with its own default reasoning. The context snapshot remains inherited; provider +cache reuse still depends on the selected model's normal cache identity checks. + That gives the side thread an already-built conversational prefix. In other words, `/btw` now reuses both: diff --git a/docs/interactive-capabilities/capabilities.json b/docs/interactive-capabilities/capabilities.json index a74032ccf9..6da747dfe2 100644 --- a/docs/interactive-capabilities/capabilities.json +++ b/docs/interactive-capabilities/capabilities.json @@ -4,7 +4,7 @@ "title": "OpenBitFun Playbook", "origin": "https://playbook.openbitfun.com", "source": "src/shared/interactive-capabilities/catalog.json", - "digest": "3f6c6936d3a543526f6a768b31c8058041ab3704f44be401086eb9174440d5cc", + "digest": "1e9b09293cfab7a47682d9decab4e0626137d6e79cd2405688d7f16e05a8e6b5", "ownerDigest": "6f0746578f3c56479f7c289bb05395dfe6917042f4d419de8c9a2f719d31f815", "searchAcceptance": [ { @@ -31932,8 +31932,8 @@ "control": { "kind": "open", "reasonCode": "unstructuredInteraction", - "reasonZh": "“开启或关闭侧问(/btw)面板关闭前的丢弃确认提示”保存在当前界面的交互偏好中,智能体会为你打开“输入与交互 → 侧问关闭确认”开关位置。", - "reasonEn": "“Enable or disable the confirmation prompt before closing a /btw side conversation” is stored as a client UI interaction preference; the Agent opens Input & Interaction → Side-Question Close Confirmation for you." + "reasonZh": "“开启或关闭侧问(/btw)面板关闭前的丢弃确认提示”保存在当前界面的交互偏好中,智能体会为你打开“会话与记忆 → 侧问”中的确认开关。", + "reasonEn": "“Enable or disable the confirmation prompt before closing a /btw side conversation” is stored as a client UI interaction preference; the Agent opens Session & Memory → Side questions for you." } }, { diff --git a/docs/interactive-capabilities/technical/product-control-open-audit.json b/docs/interactive-capabilities/technical/product-control-open-audit.json index 6894a50655..97a6601ddb 100644 --- a/docs/interactive-capabilities/technical/product-control-open-audit.json +++ b/docs/interactive-capabilities/technical/product-control-open-audit.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "generatedFrom": "src/shared/interactive-capabilities/catalog.json", - "catalogDigest": "3f6c6936d3a543526f6a768b31c8058041ab3704f44be401086eb9174440d5cc", + "catalogDigest": "1e9b09293cfab7a47682d9decab4e0626137d6e79cd2405688d7f16e05a8e6b5", "count": 231, "reasonCounts": { "externalAuth": 4, @@ -2762,15 +2762,15 @@ "titleZh": "开启或关闭侧问(/btw)面板关闭前的丢弃确认提示", "titleEn": "Enable or disable the confirmation prompt before closing a /btw side conversation", "reasonCode": "unstructuredInteraction", - "reasonZh": "“开启或关闭侧问(/btw)面板关闭前的丢弃确认提示”保存在当前界面的交互偏好中,智能体会为你打开“输入与交互 → 侧问关闭确认”开关位置。", - "reasonEn": "“Enable or disable the confirmation prompt before closing a /btw side conversation” is stored as a client UI interaction preference; the Agent opens Input & Interaction → Side-Question Close Confirmation for you.", + "reasonZh": "“开启或关闭侧问(/btw)面板关闭前的丢弃确认提示”保存在当前界面的交互偏好中,智能体会为你打开“会话与记忆 → 侧问”中的确认开关。", + "reasonEn": "“Enable or disable the confirmation prompt before closing a /btw side conversation” is stored as a client UI interaction preference; the Agent opens Session & Memory → Side questions for you.", "presentationTarget": { "kind": "settings", "pageId": "application.voice", "sectionId": "btw-close-confirmation" }, "evidence": [ - "source:src/web-ui/src/app/scenes/settings/pages/application/BtwCloseConfirmationSettingsSection.tsx#BtwCloseConfirmationSettingsSection" + "source:src/web-ui/src/app/scenes/settings/pages/ai/BtwSettingsSection.tsx#BtwSettingsSection" ] }, { diff --git a/docs/interactive-capabilities/technical/tauri-command-map.json b/docs/interactive-capabilities/technical/tauri-command-map.json index 66bffae176..787b826a6f 100644 --- a/docs/interactive-capabilities/technical/tauri-command-map.json +++ b/docs/interactive-capabilities/technical/tauri-command-map.json @@ -1,7 +1,7 @@ { "schemaVersion": 2, "generatedFrom": "src/shared/interactive-capabilities/catalog.json", - "catalogDigest": "3f6c6936d3a543526f6a768b31c8058041ab3704f44be401086eb9174440d5cc", + "catalogDigest": "1e9b09293cfab7a47682d9decab4e0626137d6e79cd2405688d7f16e05a8e6b5", "commandCount": 701, "coverage": { "commandCount": 701, diff --git a/scripts/generate-interactive-capabilities.mjs b/scripts/generate-interactive-capabilities.mjs index 09a5ece14d..c035ce2d24 100644 --- a/scripts/generate-interactive-capabilities.mjs +++ b/scripts/generate-interactive-capabilities.mjs @@ -415,9 +415,10 @@ export function projectSettingsCatalogDestination(capabilityId, destination, ite if (destination.kind !== 'settings') return destination; const capability = SETTINGS_MIGRATIONS.capabilities[capabilityId]; const input = capability?.items?.[itemId] ?? capability?.destination ?? destination; + const migratedSection = SETTINGS_MIGRATIONS.sections?.[input.pageId]?.[input.sectionId]; const migratedView = SETTINGS_MIGRATIONS.views[input.pageId]?.[input.viewId]; - const migrated = migratedView ?? SETTINGS_MIGRATIONS.pages[input.pageId]; - const sectionId = input.sectionId ?? migrated?.sectionId; + const migrated = migratedSection ?? migratedView ?? SETTINGS_MIGRATIONS.pages[input.pageId]; + const sectionId = migratedSection?.sectionId ?? input.sectionId ?? migrated?.sectionId; return { kind: 'settings', pageId: migrated?.pageId ?? input.pageId, diff --git a/scripts/interactive-capabilities.test.mjs b/scripts/interactive-capabilities.test.mjs index f304d37a1e..c7459c5a36 100644 --- a/scripts/interactive-capabilities.test.mjs +++ b/scripts/interactive-capabilities.test.mjs @@ -29,6 +29,15 @@ test('historical settings wire targets resolve through the current presentation assert.deepEqual(projectSettingsCatalogDestination(automation.id, hooks.destination, hooks.id), { kind: 'settings', pageId: 'tools.automation', sectionId: 'hooks', }); + const input = runtimeCatalog.capabilities.find(({ id }) => id === 'setting.application.input'); + const btwClose = input.items.find(({ id }) => id === 'btw-close-confirmation'); + assert.deepEqual(btwClose.destination, { kind: 'settings', pageId: 'application.voice', sectionId: 'btw-close-confirmation' }); + assert.deepEqual(projectSettingsCatalogDestination(input.id, btwClose.destination, btwClose.id), { + kind: 'settings', pageId: 'ai.session-memory', sectionId: 'btw', + }); + assert.deepEqual(projectSettingsCatalogDestination('legacy', { kind: 'settings', pageId: 'application.input', sectionId: 'btw-close-confirmation' }), { + kind: 'settings', pageId: 'ai.session-memory', sectionId: 'btw', + }); const computerUse = runtimeCatalog.capabilities.find(({ id }) => id === 'feature.computer-use'); assert.deepEqual(projectSettingsCatalogDestination(computerUse.id, computerUse.destination), { kind: 'settings', pageId: 'tools.desktop-control', diff --git a/src/apps/cli/src/peer_host/commands/btw.rs b/src/apps/cli/src/peer_host/commands/btw.rs index 757605b0b1..a5510d56b4 100644 --- a/src/apps/cli/src/peer_host/commands/btw.rs +++ b/src/apps/cli/src/peer_host/commands/btw.rs @@ -143,6 +143,10 @@ pub(crate) async fn btw_ask_stream(state: &PeerHostState, args: &Value) -> Resul return Err("Peer event stream lost continuity while starting the side question".into()); } + let model_target = coordinator + .get_session_manager() + .get_session(&child_session_id) + .map(openbitfun_core::agentic::session::session_model_target); let runtime = side_questions().clone(); let request_id = request.request_id; runtime @@ -166,7 +170,7 @@ pub(crate) async fn btw_ask_stream(state: &PeerHostState, args: &Value) -> Resul tokio::time::sleep(BTW_TURN_POLL_INTERVAL).await; } }); - Ok(json!({ "ok": true })) + Ok(json!({ "ok": true, "modelTarget": model_target })) } pub(crate) async fn btw_cancel(args: &Value) -> Result { diff --git a/src/apps/desktop/README.md b/src/apps/desktop/README.md index 79524538be..2b9a71221f 100644 --- a/src/apps/desktop/README.md +++ b/src/apps/desktop/README.md @@ -1081,6 +1081,21 @@ before the first selected-text question. Peer hosts must advertise `btw_model_pool_selection_v1` for these typed initial choices; older hosts retain the inherited path without silently replacing a pool with its current member. +Settings → AI → Session & Memory → Side questions controls the default for new `/btw` +sessions (`ai.btw.model_selection`). The default is `{ "kind": "inherit" }`, which +retains the parent's model, reasoning and pool binding. A fixed model uses +`{ "kind": "model", "model_ref": "" }`; a pool uses +`{ "kind": "pool", "pool_id": "" }`. An explicit choice inside a side +question takes precedence and affects only that conversation. Changing the global +BTW default does not change existing conversations. A different model starts with +its own default reasoning, while inherited sessions retain the parent's reasoning. +Unavailable saved choices remain stored and block new side questions until an +explicit choice repairs or overrides them. Peers expose this setting only when the +execution host advertises `btw_model_defaults_v1`; settings and model IDs belong to +that host. SSH/Docker workspace side questions keep their parent's execution root. +The host returns the committed model target with admission so the selector shows +the actual choice without depending on a second request. + Peer Device Mode routes pool operations to capable Desktop/CLI hosts. Standalone browser clients, detached dispatch, and ACP/external-agent model selection do not expose pool selection in this version. Mobile/IM clients can continue a diff --git a/src/apps/desktop/src/api/btw_api.rs b/src/apps/desktop/src/api/btw_api.rs index 2da8c359eb..54f706075c 100644 --- a/src/apps/desktop/src/api/btw_api.rs +++ b/src/apps/desktop/src/api/btw_api.rs @@ -41,15 +41,17 @@ pub struct BtwAskStreamRequest { pub user_message_metadata: Option, #[serde(default)] pub initial_model_selection: Option, - /// Requires btw_model_pool_selection_v1; omitted means inherit the parent binding. + /// Requires btw_model_pool_selection_v1; omitted uses the host BTW default. #[serde(default)] pub initial_model_target: Option, } -#[derive(Debug, Clone, Serialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BtwAskStreamResponse { pub ok: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model_target: Option, } #[derive(Debug, Clone, Deserialize)] @@ -132,6 +134,10 @@ pub async fn btw_ask_stream( .await .map_err(|e| e.to_string())?; + let model_target = coordinator + .get_session_manager() + .get_session(&child_session_id) + .map(openbitfun_core::agentic::session::session_model_target); state .side_question_runtime .register_btw_turn( @@ -161,13 +167,37 @@ pub async fn btw_ask_stream( } }); - Ok(BtwAskStreamResponse { ok: true }) + Ok(BtwAskStreamResponse { + ok: true, + model_target, + }) } #[cfg(test)] mod tests { use super::*; + #[test] + fn btw_admission_response_reads_legacy_and_keeps_new_target_optional_for_old_readers() { + let legacy: BtwAskStreamResponse = + serde_json::from_value(serde_json::json!({"ok":true})).unwrap(); + assert!(legacy.model_target.is_none()); + assert_eq!( + serde_json::to_value(legacy).unwrap(), + serde_json::json!({"ok":true}) + ); + let current: BtwAskStreamResponse = serde_json::from_value(serde_json::json!({ + "ok":true, "modelTarget": { "sessionId":"child", "selection":{"kind":"model","model_ref":"side-model"}, "reasoningPreset":null }, + })).unwrap(); + #[derive(Deserialize)] + struct LegacyResponse { + ok: bool, + } + let old_reader: LegacyResponse = + serde_json::from_value(serde_json::to_value(current).unwrap()).unwrap(); + assert!(old_reader.ok); + } + #[test] fn btw_request_reads_legacy_payloads_and_round_trips_optional_metadata() { let legacy = serde_json::json!({ diff --git a/src/crates/assembly/core/src/agentic/coordination/coordinator.rs b/src/crates/assembly/core/src/agentic/coordination/coordinator.rs index a93f68512c..541a52ac4a 100644 --- a/src/crates/assembly/core/src/agentic/coordination/coordinator.rs +++ b/src/crates/assembly/core/src/agentic/coordination/coordinator.rs @@ -405,6 +405,7 @@ fn apply_primary_agent_model_default( #[cfg(test)] tokio::task_local! { static TEST_AGENT_MODEL_DEFAULTS: AgentModelSelections; + static TEST_BTW_AI_CONFIG: crate::service::config::types::AIConfig; } async fn normalize_model_selection(model_id: &str) -> OpenBitFunResult { @@ -12133,6 +12134,50 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet Ok(child_session) } + async fn resolve_btw_initial_model_target( + &self, + child_session_id: &str, + model_id: Option<&str>, + legacy_selection: Option<&openbitfun_runtime_ports::AgentSessionModelSelection>, + explicit_target: Option, + ) -> OpenBitFunResult> { + if explicit_target.is_some() + || legacy_selection.is_some() + || model_id.is_some_and(|id| !id.trim().is_empty()) + || self + .session_manager + .get_session(child_session_id) + .is_some_and(|session| !session.dialog_turn_ids.is_empty()) + { + return Ok(explicit_target); + } + #[cfg(test)] + if let Ok(ai) = TEST_BTW_AI_CONFIG.try_with(Clone::clone) { + return Self::btw_default_model_target(&ai); + } + let service = get_global_config_service().await?; + let ai = service.get_config(Some("ai")).await?; + Self::btw_default_model_target(&ai) + } + + fn btw_default_model_target( + ai: &crate::service::config::types::AIConfig, + ) -> OpenBitFunResult> { + let selection = openbitfun_config_contracts::btw::validate_model_selection(ai) + .map_err(OpenBitFunError::validation)?; + let selection = match selection { + AgentModelSelection::Inherit => return Ok(None), + AgentModelSelection::Model { model_ref } => ModelSelection::Model { model_ref }, + AgentModelSelection::Pool { pool_id } => ModelSelection::Pool { pool_id }, + }; + Ok(Some( + openbitfun_runtime_ports::AgentSessionModelTargetSelection { + selection, + reasoning_preset: None, + }, + )) + } + pub async fn start_btw_turn( &self, request_id: &str, @@ -12170,6 +12215,17 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet )); } + // Resolve the host's future-session default only for an unsubmitted + // child. Explicit controller choices and existing children keep ownership. + let initial_model_target = self + .resolve_btw_initial_model_target( + child_session_id, + model_id, + initial_model_selection.as_ref(), + initial_model_target, + ) + .await?; + let child_session = self .ensure_btw_session( parent_session_id, diff --git a/src/crates/assembly/core/src/agentic/coordination/coordinator/tests/btw_models.rs b/src/crates/assembly/core/src/agentic/coordination/coordinator/tests/btw_models.rs new file mode 100644 index 0000000000..f6da556de9 --- /dev/null +++ b/src/crates/assembly/core/src/agentic/coordination/coordinator/tests/btw_models.rs @@ -0,0 +1,171 @@ +use super::super::{test_support::test_coordinator, ConversationCoordinator, TEST_BTW_AI_CONFIG}; +use crate::agentic::core::{SessionConfig, SessionModelBindingPolicy}; +use crate::agentic::session::TEST_MODEL_RESOLUTION_AI_CONFIG; +use crate::service::config::types::{AIConfig, AIModelConfig, ModelCapability}; +use openbitfun_core_types::model_pool::ModelSelection; +use openbitfun_runtime_ports::AgentSessionModelTargetSelection; +use serde_json::json; + +fn ai() -> AIConfig { + AIConfig { + models: vec![AIModelConfig { + id: "side-model".into(), + enabled: true, + capabilities: vec![ModelCapability::TextChat], + ..Default::default() + }], + btw: json!({"model_selection":{"kind":"model","model_ref":"side-model"}}), + ..Default::default() + } +} + +#[test] +fn btw_defaults_preserve_inheritance_and_use_the_selected_models_reasoning_default() { + assert!( + ConversationCoordinator::btw_default_model_target(&AIConfig::default()) + .unwrap() + .is_none() + ); + let target = ConversationCoordinator::btw_default_model_target(&ai()) + .unwrap() + .unwrap(); + assert_eq!( + target.selection, + ModelSelection::Model { + model_ref: "side-model".into() + } + ); + assert!(target.reasoning_preset.is_none()); + + let mut config = ai(); + config.model_pools.pools.push(json!({"id":"side-pool","name":"Side","strategy":"balanced","member_model_ids":["side-model"]})); + config.btw = json!({"model_selection":{"kind":"pool","pool_id":"side-pool"}}); + assert_eq!( + ConversationCoordinator::btw_default_model_target(&config) + .unwrap() + .unwrap() + .selection, + ModelSelection::Pool { + pool_id: "side-pool".into() + } + ); + config.model_pools.pools.clear(); + assert!(ConversationCoordinator::btw_default_model_target(&config).is_err()); +} + +#[tokio::test] +async fn btw_default_overrides_parent_pool_without_replacing_context_or_remote_identity() { + let (coordinator, manager) = test_coordinator(); + let workspace = crate::service::workspace::legacy_compat::register_remote_fixture( + &format!("/srv/btw-model/{}", uuid::Uuid::new_v4()), + "ssh-model-test", + "example.test", + ) + .await; + let parent = manager + .create_session( + "Parent".into(), + "Standard".into(), + SessionConfig { + workspace_id: Some(workspace.id.clone()), + workspace_path: Some(workspace.root_path.to_string_lossy().into_owned()), + model_pool_id: Some("parent-pool".into()), + model_binding_policy: SessionModelBindingPolicy::Pool, + reasoning_preset: Some("high".into()), + ..Default::default() + }, + ) + .await + .unwrap(); + manager + .replace_context_messages( + &parent.session_id, + vec![crate::agentic::core::Message::user("Parent context".into())], + ) + .await; + TEST_BTW_AI_CONFIG + .scope( + ai(), + TEST_MODEL_RESOLUTION_AI_CONFIG.scope(ai(), async { + let target = coordinator + .resolve_btw_initial_model_target("child", None, None, None) + .await + .unwrap() + .unwrap(); + let child = coordinator + .ensure_btw_session(&parent.session_id, "child", None, "question", None, None) + .await + .unwrap(); + let updated = manager + .update_session_model_target_with_reasoning( + &child.session_id, + &target.selection, + target.reasoning_preset.as_deref(), + ) + .await + .unwrap(); + assert_eq!(updated.config.model_id.as_deref(), Some("side-model")); + assert!(updated.config.model_pool_id.is_none()); + assert!(updated.config.reasoning_preset.is_none()); + assert_eq!(updated.config.workspace_id, parent.config.workspace_id); + assert_eq!( + updated.config.remote_connection_id, + parent.config.remote_connection_id + ); + assert_eq!( + manager.get_context_messages("child").await.unwrap().len(), + 1 + ); + manager + .start_dialog_turn( + "child", + "Standard".into(), + "Question".into(), + None, + None, + None, + ) + .await + .unwrap(); + // A changed/invalid global default is irrelevant once a question exists. + let mut invalid = ai(); + invalid.btw = json!({"model_selection":{"kind":"future"}}); + TEST_BTW_AI_CONFIG + .scope(invalid, async { + assert!(coordinator + .resolve_btw_initial_model_target("child", None, None, None) + .await + .unwrap() + .is_none()); + assert!(coordinator + .resolve_btw_initial_model_target("new-child", None, None, None) + .await + .is_err()); + let explicit = AgentSessionModelTargetSelection { + selection: ModelSelection::Model { + model_ref: "primary".into(), + }, + reasoning_preset: Some("high".into()), + }; + let resolved = coordinator + .resolve_btw_initial_model_target( + "new-child", + None, + None, + Some(explicit), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(resolved.reasoning_preset.as_deref(), Some("high")); + assert!(coordinator + .resolve_btw_initial_model_target("new-child", Some("fast"), None, None) + .await + .unwrap() + .is_none()); + }) + .await; + }), + ) + .await; +} diff --git a/src/crates/assembly/core/src/agentic/coordination/coordinator/tests/mod.rs b/src/crates/assembly/core/src/agentic/coordination/coordinator/tests/mod.rs index 5cb7c381cb..7c8b5d5d1b 100644 --- a/src/crates/assembly/core/src/agentic/coordination/coordinator/tests/mod.rs +++ b/src/crates/assembly/core/src/agentic/coordination/coordinator/tests/mod.rs @@ -1,4 +1,5 @@ mod agent_wait; +mod btw_models; mod delegation_policy; mod image_admission; mod listing_baselines; diff --git a/src/crates/assembly/core/src/service/config/manager.rs b/src/crates/assembly/core/src/service/config/manager.rs index a942dea38e..e03728e97a 100644 --- a/src/crates/assembly/core/src/service/config/manager.rs +++ b/src/crates/assembly/core/src/service/config/manager.rs @@ -810,6 +810,10 @@ impl ConfigManager { } let mut candidate = self.config_with_value(path, json_value)?; let config = &mut candidate.config; + if path == "ai.btw" || path.starts_with("ai.btw.") { + openbitfun_config_contracts::btw::validate_model_selection(&config.ai) + .map_err(OpenBitFunError::validation)?; + } // Whole-document/AI replacements are ingestion boundaries, like import. // Ordinary field updates must not perform legacy migration. if path.is_empty() || path == "ai" { @@ -1728,6 +1732,51 @@ mod tests { assert!(disk.ai.effective_model_selections().is_err()); } + #[tokio::test] + async fn btw_defaults_preserve_unavailable_choices_and_allow_explicit_repair() { + let temp = tempfile::tempdir().unwrap(); + let paths = Arc::new(PathManager::with_user_root_for_tests( + temp.path().join("btw-defaults"), + )); + paths.initialize_user_directories().await.unwrap(); + let mut document = serde_json::to_value(GlobalConfig::default()).unwrap(); + let saved = serde_json::json!({"model_selection":{"kind":"future","target":"new"},"extension":true}); + document["ai"]["btw"] = saved.clone(); + tokio::fs::write( + paths.app_config_file(), + serde_json::to_vec(&document).unwrap(), + ) + .await + .unwrap(); + let mut manager = ConfigManager::new(manager_settings(paths.clone())) + .await + .unwrap(); + manager.set("app.language", "en-US").await.unwrap(); + let exported: serde_json::Value = + serde_json::from_slice(&tokio::fs::read(paths.app_config_file()).await.unwrap()) + .unwrap(); + assert_eq!(exported["ai"]["btw"], saved); + let missing = serde_json::json!({"kind":"model","model_ref":"missing"}); + assert!(manager + .set("ai.btw.model_selection", missing) + .await + .is_err()); + assert_eq!(manager.get::("ai.btw").unwrap(), saved); + manager + .set( + "ai.btw.model_selection", + serde_json::json!({"kind":"inherit"}), + ) + .await + .unwrap(); + assert_eq!( + manager + .get::("ai.btw.extension") + .unwrap(), + true + ); + } + #[tokio::test] async fn present_invalid_selections_survive_load_and_unrelated_save() { let temp = tempfile::tempdir().unwrap(); diff --git a/src/crates/contracts/config-contracts/src/btw.rs b/src/crates/contracts/config-contracts/src/btw.rs new file mode 100644 index 0000000000..c5d86a4390 --- /dev/null +++ b/src/crates/contracts/config-contracts/src/btw.rs @@ -0,0 +1,84 @@ +//! Host-owned defaults for newly submitted side-question sessions. +//! +//! Keep the stored object opaque so future selections survive older readers and +//! unrelated configuration writes. Interpret it only at editing/execution time. + +use crate::model_pool::AgentModelSelection; +use crate::types::{AIConfig, ModelCapability}; +use serde_json::Value; + +pub fn default_btw_config() -> Value { + serde_json::json!({ "model_selection": { "kind": "inherit" } }) +} + +pub fn model_selection(config: &Value) -> Result { + let object = config.as_object().ok_or("Invalid ai.btw configuration")?; + let Some(value) = object.get("model_selection") else { + return Ok(AgentModelSelection::Inherit); + }; + serde_json::from_value(value.clone()) + .map_err(|error| format!("Unsupported ai.btw.model_selection: {error}")) +} + +pub fn validate_model_selection(ai: &AIConfig) -> Result { + let selection = model_selection(&ai.btw)?; + match &selection { + AgentModelSelection::Inherit => {} + AgentModelSelection::Model { model_ref } => { + if !ai.resolve_model_selection(model_ref).is_some_and(|id| { + ai.models.iter().any(|model| { + model.id == id + && model.enabled + && model.supports_capability(ModelCapability::TextChat) + }) + }) { + return Err(format!( + "BTW model is missing, disabled or cannot chat: {model_ref}" + )); + } + } + AgentModelSelection::Pool { pool_id } => { + let pool = ai.model_pools.get(pool_id)?; + if pool.member_model_ids.is_empty() { + return Err(format!("BTW model pool is empty: {pool_id}")); + } + } + } + Ok(selection) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn legacy_ai_defaults_to_inherit_and_round_trips() { + let ai: AIConfig = serde_json::from_value(serde_json::json!({})).unwrap(); + assert_eq!( + model_selection(&ai.btw).unwrap(), + AgentModelSelection::Inherit + ); + let round_trip: AIConfig = + serde_json::from_value(serde_json::to_value(ai).unwrap()).unwrap(); + assert_eq!( + model_selection(&round_trip.btw).unwrap(), + AgentModelSelection::Inherit + ); + } + + #[test] + fn future_and_unavailable_choices_are_preserved() { + for value in [ + serde_json::json!({"model_selection":{"kind":"future","target":"new"},"future":true}), + serde_json::json!({"model_selection":{"kind":"model","model_ref":"deleted"}}), + serde_json::json!({"model_selection":{"kind":"pool","pool_id":"deleted"}}), + Value::Null, + ] { + let mut ai: AIConfig = + serde_json::from_value(serde_json::json!({"btw":value})).unwrap(); + ai.allow_subagent_model_override = false; + assert_eq!(serde_json::to_value(&ai).unwrap()["btw"], value); + assert!(validate_model_selection(&ai).is_err()); + } + } +} diff --git a/src/crates/contracts/config-contracts/src/lib.rs b/src/crates/contracts/config-contracts/src/lib.rs index c3ae527d49..56c328bc36 100644 --- a/src/crates/contracts/config-contracts/src/lib.rs +++ b/src/crates/contracts/config-contracts/src/lib.rs @@ -1,6 +1,7 @@ //! Persisted configuration DTOs and pure compatibility validation. pub mod account_pool; pub mod agent_identity_migration; +pub mod btw; pub mod channel_routing; pub mod conversion; pub mod model_pool; diff --git a/src/crates/contracts/config-contracts/src/types.rs b/src/crates/contracts/config-contracts/src/types.rs index a232ee2a1d..4378c59a3a 100644 --- a/src/crates/contracts/config-contracts/src/types.rs +++ b/src/crates/contracts/config-contracts/src/types.rs @@ -1299,6 +1299,10 @@ pub struct AIConfig { #[serde(default, skip_serializing_if = "TaskModelsConfig::is_default")] pub task_models: TaskModelsConfig, + /// Opaque, host-owned defaults for new BTW sessions; unknown choices stay readable. + #[serde(default = "crate::btw::default_btw_config")] + pub btw: serde_json::Value, + /// Default model configuration. #[serde(default)] pub default_models: DefaultModelsConfig, @@ -2363,6 +2367,7 @@ impl Default for AIConfig { models: vec![], tool_presentation_mode: ToolPresentationMode::default(), task_models: TaskModelsConfig::default(), + btw: crate::btw::default_btw_config(), default_models: DefaultModelsConfig::default(), model_routing: ModelRoutingConfig::default(), agent_model_defaults: AgentModelDefaultsConfig::default(), diff --git a/src/crates/contracts/product-domains/src/generated/product-control-catalog.json b/src/crates/contracts/product-domains/src/generated/product-control-catalog.json index 4983e44eea..eeb6df7133 100644 --- a/src/crates/contracts/product-domains/src/generated/product-control-catalog.json +++ b/src/crates/contracts/product-domains/src/generated/product-control-catalog.json @@ -4,7 +4,7 @@ "title": "OpenBitFun Playbook", "origin": "https://playbook.openbitfun.com", "source": "src/shared/interactive-capabilities/catalog.json", - "digest": "3f6c6936d3a543526f6a768b31c8058041ab3704f44be401086eb9174440d5cc", + "digest": "1e9b09293cfab7a47682d9decab4e0626137d6e79cd2405688d7f16e05a8e6b5", "ownerDigest": "6f0746578f3c56479f7c289bb05395dfe6917042f4d419de8c9a2f719d31f815", "searchAcceptance": [ { @@ -30508,8 +30508,8 @@ "control": { "kind": "open", "reasonCode": "unstructuredInteraction", - "reasonZh": "“开启或关闭侧问(/btw)面板关闭前的丢弃确认提示”保存在当前界面的交互偏好中,智能体会为你打开“输入与交互 → 侧问关闭确认”开关位置。", - "reasonEn": "“Enable or disable the confirmation prompt before closing a /btw side conversation” is stored as a client UI interaction preference; the Agent opens Input & Interaction → Side-Question Close Confirmation for you." + "reasonZh": "“开启或关闭侧问(/btw)面板关闭前的丢弃确认提示”保存在当前界面的交互偏好中,智能体会为你打开“会话与记忆 → 侧问”中的确认开关。", + "reasonEn": "“Enable or disable the confirmation prompt before closing a /btw side conversation” is stored as a client UI interaction preference; the Agent opens Session & Memory → Side questions for you." } }, { diff --git a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json index 81b04cc91e..5422bad462 100644 --- a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json +++ b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "digest": "fnv1a64:aaf7320d931d5b35", + "digest": "fnv1a64:0b686be0f5103ef5", "retiredCommandPrefixes": [ { "prefix": "lsp_", @@ -21,6 +21,7 @@ "runtime_attachment_upload_v1", "btw_initial_model_selection_v1", "btw_model_pool_selection_v1", + "btw_model_defaults_v1", "control_conversation_v1", "control_conversation_reset_v1", "targeted_session_rollback", @@ -78,6 +79,7 @@ "runtime_attachment_upload_v1", "btw_initial_model_selection_v1", "btw_model_pool_selection_v1", + "btw_model_defaults_v1", "control_conversation_v1", "control_conversation_reset_v1", "targeted_session_rollback", @@ -136,6 +138,7 @@ "runtime_attachment_upload_v1", "btw_initial_model_selection_v1", "btw_model_pool_selection_v1", + "btw_model_defaults_v1", "targeted_session_rollback", "token_usage_statistics", "model_channel_routing_v1", diff --git a/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs b/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs index e175f4bbeb..ae0d865972 100644 --- a/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs +++ b/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs @@ -44,6 +44,8 @@ pub enum PeerHostCapability { BtwInitialModelSelectionV1, /// BTW accepts typed initial model/pool choices and retains inherited bindings. BtwModelPoolSelectionV1, + /// Host-owned BTW defaults apply only when no initial override was supplied. + BtwModelDefaultsV1, /// Persistent control conversations and idempotent voice history are available. ControlConversationV1, /// A fresh persistent control conversation can be selected without deleting history. @@ -157,6 +159,7 @@ impl PeerHostCapability { Self::RuntimeAttachmentUploadV1, Self::BtwInitialModelSelectionV1, Self::BtwModelPoolSelectionV1, + Self::BtwModelDefaultsV1, Self::ControlConversationV1, Self::ControlConversationResetV1, Self::TargetedSessionRollback, @@ -220,6 +223,7 @@ impl PeerHostCapability { Self::ControlConversationResetV1 => "control_conversation_reset_v1", Self::BtwInitialModelSelectionV1 => "btw_initial_model_selection_v1", Self::BtwModelPoolSelectionV1 => "btw_model_pool_selection_v1", + Self::BtwModelDefaultsV1 => "btw_model_defaults_v1", Self::TargetedSessionRollback => "targeted_session_rollback", Self::TokenUsageStatistics => "token_usage_statistics", Self::SubscriptionAccountsV1 => "subscription_accounts_v1", @@ -285,6 +289,7 @@ const DESKTOP_CAPABILITIES: &[PeerHostCapability] = &[ PeerHostCapability::RuntimeAttachmentUploadV1, PeerHostCapability::BtwInitialModelSelectionV1, PeerHostCapability::BtwModelPoolSelectionV1, + PeerHostCapability::BtwModelDefaultsV1, PeerHostCapability::ControlConversationV1, PeerHostCapability::ControlConversationResetV1, PeerHostCapability::TargetedSessionRollback, @@ -346,6 +351,7 @@ const CLI_CAPABILITIES: &[PeerHostCapability] = &[ PeerHostCapability::RuntimeAttachmentUploadV1, PeerHostCapability::BtwInitialModelSelectionV1, PeerHostCapability::BtwModelPoolSelectionV1, + PeerHostCapability::BtwModelDefaultsV1, PeerHostCapability::TargetedSessionRollback, PeerHostCapability::TokenUsageStatistics, PeerHostCapability::ModelChannelRoutingV1, @@ -459,6 +465,9 @@ mod tests { PeerHostKind::Cli, PeerHostCapability::BtwModelPoolSelectionV1 )); + for host in [PeerHostKind::Desktop, PeerHostKind::Cli] { + assert!(advertises(host, PeerHostCapability::BtwModelDefaultsV1)); + } } #[test] diff --git a/src/shared/interactive-capabilities/catalog.json b/src/shared/interactive-capabilities/catalog.json index 125951b597..178bb4af35 100644 --- a/src/shared/interactive-capabilities/catalog.json +++ b/src/shared/interactive-capabilities/catalog.json @@ -8578,11 +8578,11 @@ "control": { "kind": "open", "reasonCode": "unstructuredInteraction", - "reasonZh": "“开启或关闭侧问(/btw)面板关闭前的丢弃确认提示”保存在当前界面的交互偏好中,智能体会为你打开“输入与交互 → 侧问关闭确认”开关位置。", - "reasonEn": "“Enable or disable the confirmation prompt before closing a /btw side conversation” is stored as a client UI interaction preference; the Agent opens Input & Interaction → Side-Question Close Confirmation for you." + "reasonZh": "“开启或关闭侧问(/btw)面板关闭前的丢弃确认提示”保存在当前界面的交互偏好中,智能体会为你打开“会话与记忆 → 侧问”中的确认开关。", + "reasonEn": "“Enable or disable the confirmation prompt before closing a /btw side conversation” is stored as a client UI interaction preference; the Agent opens Session & Memory → Side questions for you." }, "evidence": [ - "source:src/web-ui/src/app/scenes/settings/pages/application/BtwCloseConfirmationSettingsSection.tsx#BtwCloseConfirmationSettingsSection" + "source:src/web-ui/src/app/scenes/settings/pages/ai/BtwSettingsSection.tsx#BtwSettingsSection" ] }, { diff --git a/src/web-ui/src/app/global-search/generated/interactive-capabilities.json b/src/web-ui/src/app/global-search/generated/interactive-capabilities.json index 101c78caf4..fd428d4e10 100644 --- a/src/web-ui/src/app/global-search/generated/interactive-capabilities.json +++ b/src/web-ui/src/app/global-search/generated/interactive-capabilities.json @@ -4,7 +4,7 @@ "title": "OpenBitFun Playbook", "origin": "https://playbook.openbitfun.com", "source": "src/shared/interactive-capabilities/catalog.json", - "digest": "3f6c6936d3a543526f6a768b31c8058041ab3704f44be401086eb9174440d5cc", + "digest": "1e9b09293cfab7a47682d9decab4e0626137d6e79cd2405688d7f16e05a8e6b5", "ownerDigest": "6f0746578f3c56479f7c289bb05395dfe6917042f4d419de8c9a2f719d31f815", "searchAcceptance": [ { @@ -30346,8 +30346,8 @@ "control": { "kind": "open", "reasonCode": "unstructuredInteraction", - "reasonZh": "“开启或关闭侧问(/btw)面板关闭前的丢弃确认提示”保存在当前界面的交互偏好中,智能体会为你打开“输入与交互 → 侧问关闭确认”开关位置。", - "reasonEn": "“Enable or disable the confirmation prompt before closing a /btw side conversation” is stored as a client UI interaction preference; the Agent opens Input & Interaction → Side-Question Close Confirmation for you." + "reasonZh": "“开启或关闭侧问(/btw)面板关闭前的丢弃确认提示”保存在当前界面的交互偏好中,智能体会为你打开“会话与记忆 → 侧问”中的确认开关。", + "reasonEn": "“Enable or disable the confirmation prompt before closing a /btw side conversation” is stored as a client UI interaction preference; the Agent opens Session & Memory → Side questions for you." } }, { diff --git a/src/web-ui/src/app/scenes/settings/pages/ai/BtwModelSettingsRow.tsx b/src/web-ui/src/app/scenes/settings/pages/ai/BtwModelSettingsRow.tsx new file mode 100644 index 0000000000..02b8aa3ce4 --- /dev/null +++ b/src/web-ui/src/app/scenes/settings/pages/ai/BtwModelSettingsRow.tsx @@ -0,0 +1,103 @@ +import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react'; +import { Combobox } from '@openbitfun/ui'; +import { useI18n } from '@/infrastructure/i18n'; +import { ConfigPageRow, ConfigRetryState } from '@/infrastructure/config/components/common'; +import { useModelSelectPresentation, type ModelSelectOption } from '@/infrastructure/config/components/ModelSelectPresentation'; +import { configManager } from '@/infrastructure/config/services/ConfigManager'; +import { btwModelSelection, supportsBtwModelDefaults } from '@/infrastructure/config/services/btwModelDefaults'; +import { filterSelectableTextChatModels } from '@/infrastructure/config/services/modelCategory'; +import type { AIModelConfig, AgentModelTargetSelection } from '@/infrastructure/config/types'; +import { modelPoolAPI, readableModelPools, supportsBtwModelPools, type ModelPoolDefinition } from '@/infrastructure/api/service-api/ModelPoolAPI'; +import { getActiveSurfaceScope, onSurfaceActivated } from '@/infrastructure/peer-device/deviceSurface'; + +function BtwModelSettings() { + const { t } = useI18n('settings/models'); + const { buildModelOption } = useModelSelectPresentation(); + const [scope] = useState(getActiveSurfaceScope); + const supported = supportsBtwModelDefaults(); + const [value, setValue] = useState(); + const [models, setModels] = useState([]); + const [pools, setPools] = useState([]); + const [ready, setReady] = useState(false); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(false); + const revision = useRef(0); + const load = useCallback(async () => { + const request = ++revision.current; + try { + const [config, loadedModels, document] = await Promise.all([ + configManager.getConfig('ai.btw'), + configManager.getOptionalConfig('ai.models'), + supportsBtwModelPools() ? modelPoolAPI.list() : undefined, + ]); + if (!scope.isCurrent() || request !== revision.current) return; + if (!Array.isArray(loadedModels)) throw new Error('Model configuration is unavailable'); + setModels(loadedModels); + setValue(config); + setPools(document ? readableModelPools(document) : []); + setReady(true); + setError(false); + } catch { + if (scope.isCurrent() && request === revision.current) setError(true); + } + }, [scope]); + useEffect(() => { + if (!supported) return; + void load(); + const unwatch = configManager.watch('ai.btw', () => void load()); + const unwatchPools = configManager.watch('ai.model_pools', () => void load()); + const unwatchModels = configManager.watch('ai.models', () => void load()); + return () => { revision.current += 1; unwatch(); unwatchPools(); unwatchModels(); }; + }, [load, supported]); + + const selection = ready ? btwModelSelection(value) : undefined; + const selected = selection?.kind === 'inherit' ? 'inherit' + : selection?.kind === 'model' ? `model:${selection.model_ref}` + : selection?.kind === 'pool' ? `pool:${selection.pool_id}` : 'unavailable'; + const options: ModelSelectOption[] = [ + { value: 'inherit', label: t('btwModel.inherit') }, + ...filterSelectableTextChatModels(models).filter(model => model.id?.trim()).map(model => ({ ...buildModelOption(model), value: `model:${model.id}` })), + ...pools.map(pool => ({ value: `pool:${pool.id}`, label: t('btwModel.pool', { name: pool.name }), + disabled: pool.member_model_ids.length === 0 || !['ordered', 'balanced'].includes(pool.strategy) })), + ]; + if (ready && !options.some(option => option.value === selected)) { + options.push({ value: selected, label: t('btwModel.unavailable'), disabled: true }); + } + const save = async (next: string) => { + if (!ready || busy || !scope.isCurrent()) return; + const choice: AgentModelTargetSelection = next === 'inherit' ? { kind: 'inherit' } + : next.startsWith('model:') ? { kind: 'model', model_ref: next.slice(6) } + : { kind: 'pool', pool_id: next.slice(5) }; + setBusy(true); + revision.current++; + try { + const updated = await configManager.updateConfig('ai.btw', current => ({ + ...(current && typeof current === 'object' && !Array.isArray(current) ? current : {}), + model_selection: choice, + })); + if (!scope.isCurrent()) return; + setValue(updated); + setError(false); + } catch { + if (scope.isCurrent()) setError(true); + } finally { + if (scope.isCurrent()) setBusy(false); + } + }; + return <> + {!supported ?

{t('btwModel.unsupported')}

: <> + + void save(String(next))} /> + + {error && void load()} />} + } + ; +} + +export function BtwModelSettingsRow() { + const scope = useSyncExternalStore(onSurfaceActivated, getActiveSurfaceScope, getActiveSurfaceScope); + return ; +} diff --git a/src/web-ui/src/app/scenes/settings/pages/ai/BtwSettingsSection.test.tsx b/src/web-ui/src/app/scenes/settings/pages/ai/BtwSettingsSection.test.tsx new file mode 100644 index 0000000000..e8e4429352 --- /dev/null +++ b/src/web-ui/src/app/scenes/settings/pages/ai/BtwSettingsSection.test.tsx @@ -0,0 +1,137 @@ +// @vitest-environment jsdom +import { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { activateSurface } from '@/infrastructure/peer-device/deviceSurface'; +import type { AIModelConfig } from '@/infrastructure/config/types'; +import BtwSettingsSection from './BtwSettingsSection'; +import { BTW_CLOSE_CONFIRMATION_STORAGE_KEY, shouldConfirmBtwClose } from '@/infrastructure/preferences/btwCloseConfirmation'; + +globalThis.IS_REACT_ACT_ENVIRONMENT = true; +const mocks = vi.hoisted(() => ({ supported: true, get: vi.fn(), update: vi.fn(), list: vi.fn() })); +vi.mock('@/infrastructure/config/services/btwModelDefaults', async original => ({ + ...await original(), + supportsBtwModelDefaults: () => mocks.supported, +})); +vi.mock('@/infrastructure/config/services/ConfigManager', () => ({ configManager: { + getConfig: mocks.get, getOptionalConfig: async () => models, updateConfig: mocks.update, watch: () => () => {}, +} })); +vi.mock('@/infrastructure/api/service-api/ModelPoolAPI', async original => ({ + ...await original(), + supportsBtwModelPools: () => true, modelPoolAPI: { list: mocks.list }, +})); +vi.mock('react-i18next', async original => ({ + ...await original(), useTranslation: () => ({ t: (key: string) => key }), +})); +vi.mock('@openbitfun/ui', async original => ({ + ...await original(), + Combobox: ({ value, options, disabled, onValueChange, 'aria-label': label }: { + value: string; disabled: boolean; options: { value: string; label: string; disabled?: boolean }[]; + onValueChange: (value: string) => void; 'aria-label': string; + }) => , +})); + +const models: AIModelConfig[] = [ + { id: 'alpha', name: 'Alpha', model_name: 'alpha', provider: 'openai', base_url: 'https://example.test', enabled: true, capabilities: ['text_chat'] }, + { id: 'disabled', name: 'Disabled', model_name: 'disabled', provider: 'openai', base_url: 'https://example.test', enabled: false, capabilities: ['text_chat'] }, + { id: 'audio', name: 'Audio', model_name: 'audio', provider: 'openai', base_url: 'https://example.test', enabled: true, capabilities: ['speech_recognition'] }, +]; + +describe('BTW settings', () => { + let root: Root; + let host: HTMLDivElement; + let config: unknown; + const select = () => host.querySelector('select')!; + const render = () => act(async () => { root.render(); }); + const choose = (value: string) => act(async () => { + select().value = value; + select().dispatchEvent(new Event('change', { bubbles: true })); + }); + beforeEach(() => { + activateSurface('local'); mocks.supported = true; + localStorage.removeItem(BTW_CLOSE_CONFIRMATION_STORAGE_KEY); + config = { model_selection: { kind: 'inherit' }, extension: 'keep' }; + mocks.get.mockReset().mockImplementation(async () => config); + mocks.update.mockReset().mockImplementation(async (_path, update) => { config = update(config); return config; }); + mocks.list.mockReset().mockResolvedValue({ version: 1, pools: [ + { id: 'pool', name: 'Side pool', strategy: 'balanced', member_model_ids: ['alpha'] }, + ] }); + host = document.createElement('div'); document.body.append(host); root = createRoot(host); + }); + afterEach(() => { act(() => root.unmount()); host.remove(); activateSurface('local'); }); + + it('groups the host model and existing controller close preference under one side-question section', async () => { + localStorage.setItem(BTW_CLOSE_CONFIRMATION_STORAGE_KEY, 'true'); + await render(); + const section = host.querySelector('#settings-section-btw')!; + const toggle = section.querySelector('[role="switch"]')!; + expect(section.contains(select())).toBe(true); + expect(toggle.checked).toBe(false); + await act(async () => toggle.click()); + expect(shouldConfirmBtwClose()).toBe(true); + expect(mocks.update).not.toHaveBeenCalled(); + }); + + it('defaults to inheritance, filters models and saves a concrete model or pool without dropping extensions', async () => { + await render(); + expect(select().value).toBe('inherit'); + expect([...select().options].map(option => option.value)).toEqual(['inherit', 'model:alpha', 'pool:pool']); + await choose('model:alpha'); + expect(config).toEqual({ model_selection: { kind: 'model', model_ref: 'alpha' }, extension: 'keep' }); + await choose('pool:pool'); + expect(config).toEqual({ model_selection: { kind: 'pool', pool_id: 'pool' }, extension: 'keep' }); + await choose('inherit'); + expect(config).toEqual({ model_selection: { kind: 'inherit' }, extension: 'keep' }); + }); + + it.each([ + { model_selection: { kind: 'model', model_ref: 'deleted' } }, + { model_selection: { kind: 'future' } }, + null, + ])('keeps unavailable saved choices visible and allows an explicit repair: %j', async value => { + config = value; + await render(); + expect(select().selectedOptions[0].disabled).toBe(true); + expect(mocks.update).not.toHaveBeenCalled(); + await choose('inherit'); + expect(config).toEqual({ model_selection: { kind: 'inherit' } }); + }); + + it('locks failed reads and retains the saved choice after failed writes', async () => { + mocks.get.mockRejectedValueOnce(new Error('offline')); + await render(); + expect(select().disabled).toBe(true); + expect(host.textContent).toContain('btwModel.failed'); + await act(async () => host.querySelector('button')!.click()); + expect(select().disabled).toBe(false); + mocks.update.mockRejectedValueOnce(new Error('write failed')); + await choose('model:alpha'); + expect(config).toEqual({ model_selection: { kind: 'inherit' }, extension: 'keep' }); + expect(select().value).toBe('inherit'); + }); + + it('does not read or write the new setting on older hosts', async () => { + mocks.supported = false; + await render(); + expect(host.textContent).toContain('btwModel.unsupported'); + expect(mocks.get).not.toHaveBeenCalled(); + expect(mocks.update).not.toHaveBeenCalled(); + const toggle = host.querySelector('[role="switch"]')!; + expect(toggle.disabled).toBe(false); + await act(async () => toggle.click()); + expect(shouldConfirmBtwClose()).toBe(false); + }); + + it('ignores a departed host response after a surface switch', async () => { + let resolve!: (value: unknown) => void; + mocks.get.mockImplementationOnce(() => new Promise(done => { resolve = done; })); + await render(); + config = { model_selection: { kind: 'pool', pool_id: 'pool' } }; + await act(async () => { activateSurface('peer-device'); }); + expect(select().value).toBe('pool:pool'); + await act(async () => { resolve({ model_selection: { kind: 'model', model_ref: 'alpha' } }); }); + expect(select().value).toBe('pool:pool'); + }); +}); diff --git a/src/web-ui/src/app/scenes/settings/pages/application/BtwCloseConfirmationSettingsSection.tsx b/src/web-ui/src/app/scenes/settings/pages/ai/BtwSettingsSection.tsx similarity index 76% rename from src/web-ui/src/app/scenes/settings/pages/application/BtwCloseConfirmationSettingsSection.tsx rename to src/web-ui/src/app/scenes/settings/pages/ai/BtwSettingsSection.tsx index 53349122ef..225705fdb5 100644 --- a/src/web-ui/src/app/scenes/settings/pages/application/BtwCloseConfirmationSettingsSection.tsx +++ b/src/web-ui/src/app/scenes/settings/pages/ai/BtwSettingsSection.tsx @@ -4,15 +4,18 @@ import { useI18n } from '@/infrastructure/i18n'; import { ConfigPageRow, ConfigPageSection } from '@/infrastructure/config/components/common'; import { setConfirmBtwClose, shouldConfirmBtwClose } from '@/infrastructure/preferences/btwCloseConfirmation'; import { useSettingsSectionAnchor } from '../shared/useSettingsSectionAnchor'; +import { BtwModelSettingsRow } from './BtwModelSettingsRow'; -export default function BtwCloseConfirmationSettingsSection() { +export default function BtwSettingsSection() { const { t } = useI18n('settings/application'); + const { t: tModels } = useI18n('settings/models'); const [enabled, setEnabled] = useState(shouldConfirmBtwClose); - const sectionAnchor = useSettingsSectionAnchor('btw-close-confirmation', true); + const sectionAnchor = useSettingsSectionAnchor('btw', true); return (
- + + { }; const inspectModelReferenceCount = async (modelIds: string[]): Promise => { - const [defaultModels, taskModels, agentModelDefaults] = await Promise.all([ + const [defaultModels, taskModels, agentModelDefaults, btwDefaults] = await Promise.all([ configManager.getConfig('ai.default_models'), configManager.getConfig('ai.task_models'), configManager.getConfig(modelSelectionsConfigPath()), + supportsBtwModelDefaults() ? configManager.getConfig('ai.btw') : undefined, ]); const ids = new Set(modelIds); - return [defaultModels, taskModels, agentModelDefaults] + return [defaultModels, taskModels, agentModelDefaults, btwDefaults] .reduce((count, value) => count + countModelConfigReferences(value, ids), 0); }; diff --git a/src/web-ui/src/app/scenes/settings/pages/ai/SessionMemorySettingsPage.tsx b/src/web-ui/src/app/scenes/settings/pages/ai/SessionMemorySettingsPage.tsx index 6e48633623..dacb98847a 100644 --- a/src/web-ui/src/app/scenes/settings/pages/ai/SessionMemorySettingsPage.tsx +++ b/src/web-ui/src/app/scenes/settings/pages/ai/SessionMemorySettingsPage.tsx @@ -5,6 +5,7 @@ import DefaultHarnessSection from './DefaultHarnessSection'; import MemorySettingsSection from './MemorySettingsSection'; import PromptSuggestionSection from './PromptSuggestionSection'; import SessionTitleSection from './SessionTitleSection'; +import BtwSettingsSection from './BtwSettingsSection'; export default function SessionMemorySettingsPage() { const sessionAnchor = useSettingsSectionAnchor('session'); @@ -15,6 +16,7 @@ export default function SessionMemorySettingsPage() { + ); diff --git a/src/web-ui/src/app/scenes/settings/pages/application/InputSettingsPage.tsx b/src/web-ui/src/app/scenes/settings/pages/application/InputSettingsPage.tsx index f08d963509..c98877babd 100644 --- a/src/web-ui/src/app/scenes/settings/pages/application/InputSettingsPage.tsx +++ b/src/web-ui/src/app/scenes/settings/pages/application/InputSettingsPage.tsx @@ -3,14 +3,12 @@ import KeyboardShortcutsSection from './KeyboardShortcutsSection'; import VoiceSettingsSection from './VoiceSettingsSection'; import TextSelectionSettingsSection from './TextSelectionSettingsSection'; import MessageSendingSettingsSection from './MessageSendingSettingsSection'; -import BtwCloseConfirmationSettingsSection from './BtwCloseConfirmationSettingsSection'; export default function InputSettingsPage() { return ( - diff --git a/src/web-ui/src/app/scenes/settings/pages/shared/SettingsPageComposition.test.ts b/src/web-ui/src/app/scenes/settings/pages/shared/SettingsPageComposition.test.ts index 5d6b680aa4..6af3ac74f8 100644 --- a/src/web-ui/src/app/scenes/settings/pages/shared/SettingsPageComposition.test.ts +++ b/src/web-ui/src/app/scenes/settings/pages/shared/SettingsPageComposition.test.ts @@ -7,7 +7,7 @@ describe('merged settings pages', () => { it.each([ ['../application/PetAssistantSettingsPage.tsx', ['../application/PetSettingsSection.tsx', '../application/RealtimeVoiceSettingsSection.tsx']], ['../application/InputSettingsPage.tsx', ['../application/VoiceSettingsSection.tsx', '../application/KeyboardShortcutsSection.tsx']], - ['../ai/SessionMemorySettingsPage.tsx', ['../ai/DefaultHarnessSection.tsx', '../ai/SessionTitleSection.tsx', '../ai/PromptSuggestionSection.tsx', '../ai/MemorySettingsSection.tsx']], + ['../ai/SessionMemorySettingsPage.tsx', ['../ai/DefaultHarnessSection.tsx', '../ai/SessionTitleSection.tsx', '../ai/PromptSuggestionSection.tsx', '../ai/BtwSettingsSection.tsx', '../ai/MemorySettingsSection.tsx']], ['../development/WorkspaceGitSettingsPage.tsx', ['../development/WorkspaceSearchSection.tsx', '../development/GitCommitSettingsSection.tsx', '../development/WorktreeSettingsSection.tsx']], ['../tools/AutomationSettingsPage.tsx', ['../tools/QuickActionsSettingsSection.tsx', '../tools/HooksSettingsSection.tsx']], ])('keeps one page header and scroll owner for %s', (page, sections) => { diff --git a/src/web-ui/src/app/scenes/settings/settingsDataPreload.ts b/src/web-ui/src/app/scenes/settings/settingsDataPreload.ts index 44fce686b1..8ed61ee8a9 100644 --- a/src/web-ui/src/app/scenes/settings/settingsDataPreload.ts +++ b/src/web-ui/src/app/scenes/settings/settingsDataPreload.ts @@ -1,3 +1,4 @@ +import { supportsBtwModelDefaults } from '@/infrastructure/config/services/btwModelDefaults'; import { modelSelectionsConfigPath } from '@/infrastructure/config/services/modelSelections'; import { configManager } from '@/infrastructure/config/services/ConfigManager'; import type { SettingsPageId } from './settingsTypes'; @@ -30,6 +31,7 @@ const OPTIONAL_PATHS = new Set([ export async function preloadSettingsData(pageId: SettingsPageId): Promise { const paths = [...(CONFIG_PATHS[pageId] ?? []), ...(pageId === 'ai.execution' ? [modelSelectionsConfigPath()] : [])]; + if (pageId === 'ai.session-memory' && supportsBtwModelDefaults()) paths.push('ai.btw'); await Promise.allSettled(paths.map(path => { if (configManager.hasCachedConfig(path)) return; return OPTIONAL_PATHS.has(path) diff --git a/src/web-ui/src/app/scenes/settings/settingsDestination.ts b/src/web-ui/src/app/scenes/settings/settingsDestination.ts index adcc242fa0..6156c1c202 100644 --- a/src/web-ui/src/app/scenes/settings/settingsDestination.ts +++ b/src/web-ui/src/app/scenes/settings/settingsDestination.ts @@ -24,6 +24,7 @@ export function isLegacyEcosystemCompatibilityDestination(value: unknown): boole * validator and the frontend share the same compatibility boundary. */ const LEGACY_DESTINATION_MIGRATIONS: Readonly> = migrations.pages; +const LEGACY_SECTION_MIGRATIONS: Readonly>>> = migrations.sections; const LEGACY_VIEW_MIGRATIONS: Readonly>>> = migrations.views; export interface SettingsDestinationInput { @@ -32,17 +33,18 @@ export interface SettingsDestinationInput { sectionId?: string; } -/** Normalize both old page IDs and old tab links before entering the settings store. */ +/** Normalize old page, tab and section links before entering the settings store. */ export function resolveSettingsDestination(value: string | SettingsDestinationInput): SettingsDestination { const input = typeof value === 'string' ? { pageId: value } : value; - const migrated = (input.viewId ? LEGACY_VIEW_MIGRATIONS[input.pageId]?.[input.viewId] : undefined) + const migratedSection = input.sectionId ? LEGACY_SECTION_MIGRATIONS[input.pageId]?.[input.sectionId] : undefined; + const migrated = migratedSection ?? (input.viewId ? LEGACY_VIEW_MIGRATIONS[input.pageId]?.[input.viewId] : undefined) ?? LEGACY_DESTINATION_MIGRATIONS[input.pageId]; const pageId = migrated?.pageId ?? input.pageId; const destination: SettingsDestination = { pageId: isSettingsPageId(pageId) ? pageId : DEFAULT_SETTINGS_PAGE_ID, }; const manifest = getSettingsPageManifest(destination.pageId); - const sectionId = input.sectionId + const sectionId = migratedSection?.sectionId ?? input.sectionId ?? migrated?.sectionId; const section = manifest.sections?.find(section => section.id === sectionId); const view = manifest.views?.find(view => view.id === input.viewId); diff --git a/src/web-ui/src/app/scenes/settings/settingsDestinationMigrations.json b/src/web-ui/src/app/scenes/settings/settingsDestinationMigrations.json index 6ff2563faa..6c18745f01 100644 --- a/src/web-ui/src/app/scenes/settings/settingsDestinationMigrations.json +++ b/src/web-ui/src/app/scenes/settings/settingsDestinationMigrations.json @@ -174,6 +174,10 @@ "auto-show-selection-toolbar": { "pageId": "application.input", "sectionId": "text-selection" + }, + "btw-close-confirmation": { + "pageId": "ai.session-memory", + "sectionId": "btw" } } }, @@ -221,5 +225,19 @@ } } } + }, + "sections": { + "application.input": { + "btw-close-confirmation": { + "pageId": "ai.session-memory", + "sectionId": "btw" + } + }, + "application.voice": { + "btw-close-confirmation": { + "pageId": "ai.session-memory", + "sectionId": "btw" + } + } } } diff --git a/src/web-ui/src/app/scenes/settings/settingsRegistry.test.ts b/src/web-ui/src/app/scenes/settings/settingsRegistry.test.ts index 185a82c240..f773c87b99 100644 --- a/src/web-ui/src/app/scenes/settings/settingsRegistry.test.ts +++ b/src/web-ui/src/app/scenes/settings/settingsRegistry.test.ts @@ -31,7 +31,8 @@ describe('settings information architecture', () => { expect(new Set(SETTINGS_PAGE_MANIFESTS.map(page => page.id)).size).toBe(20); expect(SETTINGS_PAGE_MANIFESTS.filter(page => page.views?.length).map(page => page.id)).toEqual(['tools.external-agents']); expect(getSettingsPageManifest('tools.external-agents').views?.map(view => view.id)).toEqual(['local', 'ssh', 'json']); - expect(getSettingsPageManifest('application.input').sections?.map(section => section.id)).toEqual(['voice', 'message-sending', 'btw-close-confirmation', 'text-selection', 'shortcuts']); + expect(getSettingsPageManifest('application.input').sections?.map(section => section.id)).toEqual(['voice', 'message-sending', 'text-selection', 'shortcuts']); + expect(getSettingsPageManifest('ai.session-memory').sections?.map(section => section.id)).toEqual(['session', 'btw', 'memory']); expect(getSettingsPageManifest('application.pet').sections?.map(section => section.id)).toEqual(['voice-call', 'pet', 'desktop-cards']); expect(resolveSettingsDestination({ pageId: 'application.appearance', sectionId: 'sidebar-navigation' })) .toEqual({ pageId: 'application.appearance', sectionId: 'sidebar-navigation' }); @@ -93,6 +94,16 @@ describe('settings information architecture', () => { expect(useSettingsStore.getState().activeSectionId).toBe(destination.sectionId ?? null); }); + it.each(['application.input', 'application.voice'])('migrates the old BTW section on %s without redirecting the whole input page', pageId => { + const destination = resolveSettingsDestination({ pageId, sectionId: 'btw-close-confirmation' }); + expect(destination).toEqual({ pageId: 'ai.session-memory', sectionId: 'btw' }); + expect(resolveSettingsDestination(destination)).toEqual(destination); + useSettingsStore.getState().openDestination({ pageId, sectionId: 'btw-close-confirmation' }); + expect(useSettingsStore.getState().activePageId).toBe('ai.session-memory'); + expect(useSettingsStore.getState().activeSectionId).toBe('btw'); + expect(resolveSettingsDestination({ pageId: 'application.input' })).toEqual({ pageId: 'application.input' }); + }); + it('migrates old view payloads and drops targets that do not belong to the destination', () => { expect(resolveSettingsDestination({ pageId: 'tools.execution', viewId: 'common' })).toEqual({ pageId: 'ai.permissions' }); expect(resolveSettingsDestination({ pageId: 'tools.execution', viewId: 'advanced' })).toEqual({ pageId: 'ai.execution' }); @@ -105,6 +116,7 @@ describe('settings information architecture', () => { const targets: SettingsDestinationInput[] = [ ...Object.values(migrations.pages), ...Object.values(migrations.views).flatMap(Object.values), + ...Object.values(migrations.sections).flatMap(Object.values), ...Object.values(migrations.capabilities).flatMap((migration) => [ ...('destination' in migration ? [migration.destination] : []), ...('items' in migration ? Object.values(migration.items) : []), diff --git a/src/web-ui/src/app/scenes/settings/settingsRegistry.ts b/src/web-ui/src/app/scenes/settings/settingsRegistry.ts index 5fac8539e0..692931d248 100644 --- a/src/web-ui/src/app/scenes/settings/settingsRegistry.ts +++ b/src/web-ui/src/app/scenes/settings/settingsRegistry.ts @@ -182,12 +182,6 @@ export const SETTINGS_PAGE_MANIFESTS: readonly SettingsPageManifest[] = [ keywords: ['message', 'send', 'queue', 'immediate', 'steering', 'flowchat'], searchPhrases: [phrase('settings/application', 'messageSending.title'), phrase('settings/application', 'messageSending.duringTurn'), phrase('settings/application', 'messageSending.description')], }, - { - id: 'btw-close-confirmation', - labelKey: 'navigation.sections.btw-close-confirmation', - keywords: ['btw', 'side conversation', 'close', 'confirmation', 'prompt'], - searchPhrases: [phrase('settings/application', 'btwCloseConfirmation.title'), phrase('settings/application', 'btwCloseConfirmation.label')], - }, { id: 'text-selection', labelKey: 'navigation.sections.text-selection', @@ -239,8 +233,8 @@ export const SETTINGS_PAGE_MANIFESTS: readonly SettingsPageManifest[] = [ icon: Brain, labelKey: 'navigation.pages.sessionMemory.label', descriptionKey: 'navigation.pages.sessionMemory.description', - keywords: ['session', 'memory', 'harness', 'title', 'remember', 'recall'], - namespaces: ['settings', 'settings/runtime', 'settings/models', 'settings/memory', 'flow-chat'], + keywords: ['session', 'memory', 'harness', 'title', 'remember', 'recall', 'btw', 'side question'], + namespaces: ['settings', 'settings/runtime', 'settings/models', 'settings/memory', 'settings/application', 'flow-chat'], searchPhrases: [], sections: [ { @@ -249,6 +243,12 @@ export const SETTINGS_PAGE_MANIFESTS: readonly SettingsPageManifest[] = [ keywords: ['session', 'harness', 'mode', 'title'], searchPhrases: [phrase('settings/runtime', 'defaultHarness.title'), phrase('settings/models', 'sessionTitle.title')], }, + { + id: 'btw', + labelKey: 'navigation.sections.btw', + keywords: ['btw', 'side question', 'side conversation', 'model', 'pool', 'close', 'confirmation'], + searchPhrases: [phrase('settings/models', 'btwModel.title'), phrase('settings/models', 'btwModel.label'), phrase('settings/application', 'btwCloseConfirmation.label')], + }, { id: 'memory', labelKey: 'navigation.sections.memory', diff --git a/src/web-ui/src/app/scenes/settings/settingsTypes.ts b/src/web-ui/src/app/scenes/settings/settingsTypes.ts index 8877cf69a6..6178d217b0 100644 --- a/src/web-ui/src/app/scenes/settings/settingsTypes.ts +++ b/src/web-ui/src/app/scenes/settings/settingsTypes.ts @@ -36,7 +36,7 @@ export type SettingsViewId = export type SettingsSectionId = | 'sidebar-navigation' | 'message-sending' - | 'btw-close-confirmation' + | 'btw' | 'text-selection' | 'pet' | 'desktop-cards' diff --git a/src/web-ui/src/flow_chat/components/ModelSelector.tsx b/src/web-ui/src/flow_chat/components/ModelSelector.tsx index 8ecfd08ac5..967e771aec 100644 --- a/src/web-ui/src/flow_chat/components/ModelSelector.tsx +++ b/src/web-ui/src/flow_chat/components/ModelSelector.tsx @@ -540,6 +540,7 @@ export const ModelSelector: React.FC = ({ acpClientIdFromAgentType(activeSession?.config.agentType) ?? acpClientIdFromAgentType(activeSession?.mode); const isAcpSession = Boolean(acpClientId && sessionId); + const persistModeDefault = persistSharedModeDefault && activeSession?.sessionKind !== 'btw'; const targetIsSubagent = isSubagentSession || activeSession?.sessionKind === 'subagent'; const sessionPoolId = useSyncExternalStore( @@ -1347,7 +1348,7 @@ export const ModelSelector: React.FC = ({ const modelInformationLoading = availability.status === 'loading' || (isNativeModelSelection && configLoadState === 'ready' && catalogLoadState === 'loading') || (isAcpSession && !externalSelection && acpOptionsLoadState === 'loading'); - const canConfigureNativeDefaults = isNativeModelSelection && persistSharedModeDefault && !targetIsSubagent; + const canConfigureNativeDefaults = isNativeModelSelection && persistModeDefault && !targetIsSubagent; const routing = useModelRouting({ identity: routingIdentity, epoch: deviceSurfaceScope.epoch, request: { sessionId, workspaceId: activeSession?.workspaceId || activeSession?.config.workspaceId, @@ -1567,7 +1568,8 @@ export const ModelSelector: React.FC = ({ } await updateTargetSessionModel(); - if (persistSharedModeDefault) { + if (sessionId && activeSession?.sessionKind === 'btw') store.markBtwModelSelectionExplicit(sessionId); + if (persistModeDefault) { const saveDefault = rememberModeSelection({ kind: 'model', model_ref: modelId }); if (!sessionId) { // A selector without a draft/session has no other owner for the next @@ -1617,6 +1619,7 @@ export const ModelSelector: React.FC = ({ }, [ allModels, loadConfigData, + activeSession?.sessionKind, activeSession?.config.workspacePath, activeSession?.remoteConnectionId, activeSession?.remoteSshHost, @@ -1630,7 +1633,7 @@ export const ModelSelector: React.FC = ({ isAcpSession, loading, modelSelectionScopeKey, - persistSharedModeDefault, + persistModeDefault, routing.pending, reasoningLoading, recentPresetForModel, @@ -1753,7 +1756,10 @@ export const ModelSelector: React.FC = ({ const session = store.getState().sessions.get(sessionId); if (!session) return false; const previousPreset = session.config.reasoningPreset; - if (previousPreset === normalizedPreset) return true; + if (previousPreset === normalizedPreset) { + if (session.sessionKind === 'btw') store.markBtwModelSelectionExplicit(sessionId); + return true; + } const selectionScope = getActiveSurfaceScope(); setReasoningLoading(true); @@ -1772,6 +1778,7 @@ export const ModelSelector: React.FC = ({ }); } selectionScope.assertCurrent('select reasoning preset'); + if (session.sessionKind === 'btw') store.markBtwModelSelectionExplicit(sessionId); if (!targetIsSubagent) { setRecentReasoningPreset(concreteModelId, normalizedPreset); setPreSessionReasoningSelection({ @@ -1951,7 +1958,8 @@ export const ModelSelector: React.FC = ({ store.updateSessionModelPool(sessionId, pool.id, undefined, true); } } - if (!targetIsSubagent && persistSharedModeDefault) { + if (sessionId && activeSession?.sessionKind === 'btw') store.markBtwModelSelectionExplicit(sessionId); + if (!targetIsSubagent && persistModeDefault) { const saved = rememberModeSelection({ kind: 'pool', pool_id: pool.id }); if (!sessionId) await saved; else void saved.catch(error => { diff --git a/src/web-ui/src/flow_chat/components/ModelSelectorAcpMode.test.tsx b/src/web-ui/src/flow_chat/components/ModelSelectorAcpMode.test.tsx index b8df8aaf37..8c5a15c16d 100644 --- a/src/web-ui/src/flow_chat/components/ModelSelectorAcpMode.test.tsx +++ b/src/web-ui/src/flow_chat/components/ModelSelectorAcpMode.test.tsx @@ -34,6 +34,7 @@ const flowChatStoreMocks = vi.hoisted(() => { const store = { getState: () => ({ sessions }), subscribe: vi.fn(() => () => undefined), + markBtwModelSelectionExplicit: vi.fn(), updateSessionModelName: vi.fn(), updateSessionReasoningPreset: vi.fn(), updateSessionMaxContextTokens: vi.fn(), diff --git a/src/web-ui/src/flow_chat/components/ModelSelectorExternal.test.tsx b/src/web-ui/src/flow_chat/components/ModelSelectorExternal.test.tsx index 2bc382f607..774e48f187 100644 --- a/src/web-ui/src/flow_chat/components/ModelSelectorExternal.test.tsx +++ b/src/web-ui/src/flow_chat/components/ModelSelectorExternal.test.tsx @@ -50,6 +50,7 @@ const flowChatStoreMocks = vi.hoisted(() => { subscribers.add(callback); return () => subscribers.delete(callback); }), + markBtwModelSelectionExplicit: vi.fn(), updateSessionModelName: vi.fn((sessionId: string, modelName: string) => { const session = sessions.get(sessionId); if (session) session.config.modelName = modelName; diff --git a/src/web-ui/src/flow_chat/components/ModelSelectorProviderLevels.test.tsx b/src/web-ui/src/flow_chat/components/ModelSelectorProviderLevels.test.tsx index 58075e3e95..e47cd3e4eb 100644 --- a/src/web-ui/src/flow_chat/components/ModelSelectorProviderLevels.test.tsx +++ b/src/web-ui/src/flow_chat/components/ModelSelectorProviderLevels.test.tsx @@ -82,6 +82,7 @@ const flowChatStoreMocks = vi.hoisted(() => { return () => subscribers.delete(callback); }), updateSessionModelPool: vi.fn(), + markBtwModelSelectionExplicit: vi.fn(), updateSessionModelName: vi.fn(), updateSessionReasoningPreset: vi.fn(), updateSessionMaxContextTokens: vi.fn(), @@ -1592,6 +1593,21 @@ describe('ModelSelector provider levels', () => { )?.textContent).toContain('reasoningSelector.levels.high'); }); + it('marks an explicit BTW model choice without changing future main-session defaults', async () => { + flowChatStoreMocks.sessions.set('side', { sessionId: 'side', sessionKind: 'btw', + agentBackedTransient: true, isTransient: true, dialogTurns: [], config: { modelName: 'acme-fast' } }); + await renderSelector(CATALOG_MODELS, 'primary', 'side'); + await openModelList(); + await act(async () => searchTrigger().click()); + await searchFor('deep'); + await act(async () => modelOption('acme-deep')!.click()); + expect(flowChatStoreMocks.store.markBtwModelSelectionExplicit).toHaveBeenCalledWith('side'); + expect(flowChatStoreMocks.sessions.get('side')?.config.modelName).toBe('acme-deep'); + expect(configManager.setConfig).not.toHaveBeenCalled(); + expect(configManager.updateConfig).not.toHaveBeenCalled(); + expect(agentAPI.updateSessionModel).not.toHaveBeenCalled(); + }); + it.each([false, true])('allows Battery mode in BTW and updates the appropriate owner (started=%s)', async started => { poolApiMocks.supported = true; poolApiMocks.list.mockResolvedValue({ version: 1, pools: [ @@ -1614,6 +1630,8 @@ describe('ModelSelector provider levels', () => { expect(flowChatStoreMocks.sessions.get('side')?.config.modelPoolSelectionPending).toBe(true); } expect(agentAPI.updateSessionModel).not.toHaveBeenCalled(); + expect(configManager.setConfig).not.toHaveBeenCalled(); + expect(flowChatStoreMocks.store.markBtwModelSelectionExplicit).toHaveBeenCalledWith('side'); }); it('offers only model pool configuration when battery mode has no pools', async () => { diff --git a/src/web-ui/src/flow_chat/hooks/useMessageSender.test.tsx b/src/web-ui/src/flow_chat/hooks/useMessageSender.test.tsx index 751629eddf..c0e59fd872 100644 --- a/src/web-ui/src/flow_chat/hooks/useMessageSender.test.tsx +++ b/src/web-ui/src/flow_chat/hooks/useMessageSender.test.tsx @@ -32,6 +32,7 @@ const mocks = vi.hoisted(() => { peerActive: false, initialBtwModelSupported: false, initialBtwTargetSupported: false, + btwDefaultsSupported: false, onClearContexts: vi.fn(), getSendPreference: vi.fn(), }; @@ -50,6 +51,9 @@ vi.mock('../services/FlowChatManager', () => ({ vi.mock('@/infrastructure/api/service-api/ModelPoolAPI', () => ({ supportsBtwModelPools: () => !mocks.peerActive || mocks.initialBtwTargetSupported, })); +vi.mock('@/infrastructure/config/services/btwModelDefaults', () => ({ + supportsBtwModelDefaults: () => mocks.btwDefaultsSupported, +})); vi.mock('../services/BtwThreadService', () => ({ sendMessageToBtwSession: mocks.sendBtw })); vi.mock('@/infrastructure/peer-device/peerDeviceContextState', () => ({ usePeerDeviceModeOptional: () => ({ @@ -130,6 +134,7 @@ describe('useMessageSender', () => { mocks.peerActive = false; mocks.initialBtwModelSupported = false; mocks.initialBtwTargetSupported = false; + mocks.btwDefaultsSupported = false; mocks.sessions.set('created-session', { mode: 'Standard' }); mocks.ensureBackendSession.mockResolvedValue(undefined); mocks.sendBtw.mockResolvedValue({ requestId: 'request-1' }); @@ -304,6 +309,29 @@ describe('useMessageSender', () => { expect(mocks.sendBtw).toHaveBeenCalledOnce(); }); + it.each([undefined, 'pool-a'])('lets the host resolve untouched BTW defaults (parent pool=%s)', async modelPoolId => { + mocks.btwDefaultsSupported = true; + mocks.sessions.set('side', { sessionId: 'side', sessionKind: 'btw', parentSessionId: 'parent', + dialogTurns: [], config: { modelName: 'parent-model', modelPoolId, reasoningPreset: 'high' } }); + await act(async () => root.render()); + await act(async () => sendFromProbe?.()); + const request = mocks.sendBtw.mock.calls[0][0]; + expect(request).not.toHaveProperty('modelId'); + expect(request).not.toHaveProperty('initialModelSelection'); + expect(request).not.toHaveProperty('initialModelTarget'); + }); + + it('preserves an explicit first-message model even when BTW defaults are available', async () => { + mocks.btwDefaultsSupported = true; + mocks.sessions.set('side', { sessionId: 'side', sessionKind: 'btw', parentSessionId: 'parent', + dialogTurns: [], config: { modelName: 'chosen', reasoningPreset: 'high', btwModelSelectionExplicit: true } }); + await act(async () => root.render()); + await act(async () => sendFromProbe?.()); + expect(mocks.sendBtw).toHaveBeenCalledWith(expect.objectContaining({ + initialModelTarget: { selection: { kind: 'model', model_ref: 'chosen' }, reasoningPreset: 'high' }, + })); + }); + it.each([false, true])('preserves an inherited pool without a scalar override (peer=%s)', async peer => { mocks.peerActive = peer; mocks.sessions.set('side', { sessionId: 'side', sessionKind: 'btw', parentSessionId: 'parent', diff --git a/src/web-ui/src/flow_chat/hooks/useMessageSender.ts b/src/web-ui/src/flow_chat/hooks/useMessageSender.ts index 763baceea8..a2d5a285af 100644 --- a/src/web-ui/src/flow_chat/hooks/useMessageSender.ts +++ b/src/web-ui/src/flow_chat/hooks/useMessageSender.ts @@ -26,6 +26,7 @@ import { getActiveSurfaceScope } from '@/infrastructure/peer-device/deviceSurfac import { usePeerDeviceModeOptional } from '@/infrastructure/peer-device/peerDeviceContextState'; import { isBtwSessionDraft } from '../utils/modelSelectionTarget'; import { sendMessageToBtwSession } from '../services/BtwThreadService'; +import { supportsBtwModelDefaults } from '@/infrastructure/config/services/btwModelDefaults'; import { supportsBtwModelPools } from '@/infrastructure/api/service-api/ModelPoolAPI'; import type { BtwInitialModelTarget } from '@/infrastructure/api/service-api/BtwAPI'; import { buildImagePayload, stripImageContextTags } from '../utils/imagePayload'; @@ -263,17 +264,20 @@ export function useMessageSender(props: UseMessageSenderProps): UseMessageSender } // An inherited pool must retain the host's parent binding. Only explicit // changes use typed selection; never flatten pool intent to modelName. + const explicitSelection = targetSession.config.btwModelSelectionExplicit + || modelPoolSelectionPending; + const useHostDefault = supportsBtwModelDefaults() && !explicitSelection; let initialModelTarget: BtwInitialModelTarget | undefined; if (modelPoolId && modelPoolSelectionPending) { initialModelTarget = { selection: { kind: 'pool', pool_id: modelPoolId } }; - } else if (!modelPoolId && canSetInitialBtwTarget) { + } else if (!modelPoolId && !useHostDefault && canSetInitialBtwTarget) { initialModelTarget = { selection: { kind: 'model', model_ref: modelName || 'primary' }, reasoningPreset, }; } await sendMessageToBtwSession({ parentSessionId, childSessionId: targetSession.sessionId, question: fullMessage, imagePayload, - ...(!modelPoolId && !initialModelTarget ? { modelId: modelName, + ...(!modelPoolId && !useHostDefault && !initialModelTarget ? { modelId: modelName, ...(canSetInitialBtwModel ? { initialModelSelection: { modelId: modelName || 'primary', reasoningPreset, } } : {}), diff --git a/src/web-ui/src/flow_chat/services/BtwThreadService.test.ts b/src/web-ui/src/flow_chat/services/BtwThreadService.test.ts index 90acfeb725..c5ca89fed1 100644 --- a/src/web-ui/src/flow_chat/services/BtwThreadService.test.ts +++ b/src/web-ui/src/flow_chat/services/BtwThreadService.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; const mockCreateSession = vi.fn(); const mockAskStream = vi.fn(); +const mockNotifyError = vi.fn(); const mockAddExternalSession = vi.fn(); const mockUpdateSessionRelationship = vi.fn(); const mockUpdateSessionBtwOrigin = vi.fn(); @@ -13,6 +14,17 @@ const mockUpdateSessionModelPool = vi.fn(); const mockLoadRelaySessionHistory = vi.fn(); const mockRelayHostHasTurn = vi.fn(); +const defaultsMocks = vi.hoisted(() => ({ supported: false, get: vi.fn(), target: vi.fn() })); +vi.mock('@/infrastructure/config/services/btwModelDefaults', async original => ({ + ...await original(), + supportsBtwModelDefaults: () => defaultsMocks.supported, +})); +vi.mock('@/infrastructure/config/services/ConfigManager', () => ({ configManager: { getConfig: defaultsMocks.get } })); +vi.mock('@/infrastructure/api/service-api/ModelPoolAPI', async original => ({ + ...await original(), + modelPoolAPI: { target: defaultsMocks.target }, +})); + const sessions = new Map(); vi.mock('@/infrastructure/api', () => ({ @@ -59,6 +71,7 @@ vi.mock('./FlowChatManager', () => ({ vi.mock('@/shared/notification-system', () => ({ notificationService: { warning: vi.fn(), + error: (...args: any[]) => mockNotifyError(...args), }, })); @@ -73,6 +86,9 @@ import { activateSurface, surfaceIdForDevice } from '@/infrastructure/peer-devic describe('BtwThreadService', () => { beforeEach(() => { vi.clearAllMocks(); + defaultsMocks.supported = false; + defaultsMocks.get.mockReset(); + defaultsMocks.target.mockReset(); sessions.clear(); sessions.set('parent-1', { sessionId: 'parent-1', @@ -99,6 +115,80 @@ describe('BtwThreadService', () => { }); }); + it('previews a host default without turning it into an explicit first-message choice', async () => { + defaultsMocks.supported = true; + defaultsMocks.get.mockResolvedValue({ model_selection: { kind: 'model', model_ref: 'side-model' } }); + mockAddExternalSession.mockImplementationOnce((id, title, mode, workspacePath, details) => { + sessions.set(id, { sessionId: id, title, mode, workspacePath, ...details, dialogTurns: [], config: {} }); + }); + const { childSessionId } = createBtwSessionPlaceholder({ parentSessionId: 'parent-1', childSessionName: 'Side' }); + await Promise.resolve(); + expect(mockUpdateSessionModelName).toHaveBeenLastCalledWith(childSessionId, 'side-model'); + expect(mockUpdateSessionModelPool).toHaveBeenLastCalledWith(childSessionId, undefined); + expect(mockUpdateSessionReasoningPreset).toHaveBeenLastCalledWith(childSessionId, undefined); + expect(sessions.get(childSessionId).config.btwModelSelectionExplicit).toBeUndefined(); + }); + + it('does not overwrite a user choice with a delayed default preview', async () => { + defaultsMocks.supported = true; + let resolve!: (value: unknown) => void; + defaultsMocks.get.mockImplementationOnce(() => new Promise(done => { resolve = done; })); + mockAddExternalSession.mockImplementationOnce((id, title, mode, workspacePath, details) => { + sessions.set(id, { sessionId: id, title, mode, workspacePath, ...details, dialogTurns: [], config: {} }); + }); + const { childSessionId } = createBtwSessionPlaceholder({ parentSessionId: 'parent-1', childSessionName: 'Side' }); + sessions.get(childSessionId).config.btwModelSelectionExplicit = true; + mockUpdateSessionModelName.mockClear(); + resolve({ model_selection: { kind: 'model', model_ref: 'side-model' } }); + await Promise.resolve(); + expect(mockUpdateSessionModelName).not.toHaveBeenCalled(); + }); + + it('uses the host admission response to display the committed BTW model without a second read', async () => { + defaultsMocks.supported = true; + sessions.set('side', { sessionId: 'side', sessionKind: 'btw', parentSessionId: 'parent-1', + workspaceId: 'workspace-1', workspacePath: '/workspace', config: { modelName: 'parent' } }); + mockAskStream.mockResolvedValueOnce({ ok: true, modelTarget: { + sessionId: 'side', selection: { kind: 'model', model_ref: 'side-model' }, reasoningPreset: null, + } }); + await sendMessageToBtwSession({ parentSessionId: 'parent-1', childSessionId: 'side', question: 'Why?' }); + expect(mockAskStream).toHaveBeenCalledOnce(); + expect(defaultsMocks.target).not.toHaveBeenCalled(); + expect(mockUpdateSessionModelName).toHaveBeenLastCalledWith('side', 'side-model'); + expect(mockUpdateSessionModelPool).toHaveBeenLastCalledWith('side', undefined, undefined); + expect(mockUpdateSessionReasoningPreset).toHaveBeenLastCalledWith('side', null); + }); + + it('keeps a newer user choice when recovering an admitted model target', async () => { + defaultsMocks.supported = true; + const config = { modelName: 'parent', btwModelSelectionExplicit: false }; + sessions.set('side', { sessionId: 'side', sessionKind: 'btw', parentSessionId: 'parent-1', + workspaceId: 'workspace-1', workspacePath: '/workspace', config }); + let resolve!: (value: unknown) => void; + let started!: () => void; + const reading = new Promise(done => { started = done; }); + defaultsMocks.target.mockImplementationOnce(() => { started(); return new Promise(done => { resolve = done; }); }); + const submit = sendMessageToBtwSession({ parentSessionId: 'parent-1', childSessionId: 'side', question: 'Why?' }); + await reading; + config.modelName = 'new-choice'; config.btwModelSelectionExplicit = true; + resolve({ selection: { kind: 'model', model_ref: 'host-default' } }); + await submit; + expect(mockAskStream).toHaveBeenCalledOnce(); + expect(mockUpdateSessionModelName).not.toHaveBeenCalled(); + }); + + it('shows an admission failure instead of silently falling back or replaying the question', async () => { + defaultsMocks.supported = true; + sessions.set('side', { sessionId: 'side', sessionKind: 'btw', parentSessionId: 'parent-1', + workspaceId: 'workspace-1', workspacePath: '/workspace', config: {} }); + mockAskStream.mockRejectedValueOnce(new Error('BTW model is missing: removed-model')); + await expect(sendMessageToBtwSession({ parentSessionId: 'parent-1', childSessionId: 'side', question: 'Why?' })) + .rejects.toThrow('BTW model is missing: removed-model'); + expect(mockAskStream).toHaveBeenCalledOnce(); + expect(mockNotifyError).toHaveBeenCalledOnce(); + expect(sessions.has('side')).toBe(true); + }); + it('passes structured relationship metadata to backend-created review sessions', async () => { const deepReviewRunManifest = { reviewers: [], diff --git a/src/web-ui/src/flow_chat/services/BtwThreadService.ts b/src/web-ui/src/flow_chat/services/BtwThreadService.ts index 594c411c28..528d48a704 100644 --- a/src/web-ui/src/flow_chat/services/BtwThreadService.ts +++ b/src/web-ui/src/flow_chat/services/BtwThreadService.ts @@ -1,5 +1,8 @@ +import { configManager } from '@/infrastructure/config/services/ConfigManager'; +import { btwModelSelection, supportsBtwModelDefaults } from '@/infrastructure/config/services/btwModelDefaults'; +import { modelPoolAPI } from '@/infrastructure/api/service-api/ModelPoolAPI'; import { agentAPI, btwAPI } from '@/infrastructure/api'; -import type { BtwInitialModelTarget } from '@/infrastructure/api/service-api/BtwAPI'; +import type { BtwInitialModelTarget, BtwAskStreamResponse } from '@/infrastructure/api/service-api/BtwAPI'; import { i18nService } from '@/infrastructure/i18n'; import { notificationService } from '@/shared/notification-system'; import { flowChatStore } from '../store/FlowChatStore'; @@ -15,6 +18,7 @@ import type { ImagePayload } from '../utils/imagePayload'; import { absoluteSessionTurnIndexForId } from '../utils/flowChatTurnOrdinal'; import { requireSessionWorkspaceId, sessionWorkspaceId } from '../utils/sessionWorkspace'; import { getActiveSurfaceScope } from '@/infrastructure/peer-device/deviceSurface'; +import { classifyPeerHostRefusal } from '@/infrastructure/peer-device/peerHostRefusal'; import { isPeerReplyLost } from '@/infrastructure/peer-device/peerReplyLost'; import { assertSessionConversationCanSubmit } from '../session-drivers/conversationCapability'; import { trackBtwSessionSubmission } from './btwSessionSubmission'; @@ -236,6 +240,27 @@ export async function createBtwChildSession(params: { }; } +/** Preview only: the host resolves its authoritative default at first submit. */ +async function previewBtwSessionModel(childSessionId: string): Promise { + if (!supportsBtwModelDefaults()) return; + const scope = getActiveSurfaceScope(); + try { + const raw = await configManager.getConfig('ai.btw'); + if (!scope.isCurrent()) return; + const session = flowChatStore.getState().sessions.get(childSessionId); + if (!session || session.dialogTurns.length > 0 || session.btwOrigin?.requestId + || session.config.btwModelSelectionExplicit) return; + const selection = btwModelSelection(raw); + if (!selection) throw new Error('Unsupported ai.btw.model_selection'); + if (selection.kind === 'inherit') return; + flowChatStore.updateSessionModelPool(childSessionId, selection.kind === 'pool' ? selection.pool_id : undefined); + flowChatStore.updateSessionModelName(childSessionId, selection.kind === 'model' ? selection.model_ref : undefined); + flowChatStore.updateSessionReasoningPreset(childSessionId, undefined); + } catch (error) { + if (scope.isCurrent()) log.warn('Could not preview BTW model defaults; host submission will validate them', { error }); + } +} + export function createBtwSessionPlaceholder(params: { parentSessionId: string; workspacePath?: string; @@ -299,6 +324,7 @@ export function createBtwSessionPlaceholder(params: { parentSession.config.modelPoolBinding); } + void previewBtwSessionModel(childSessionId); return { childSessionId, parentDialogTurnId, parentTurnIndex }; } @@ -381,7 +407,8 @@ export async function sendMessageToBtwSession(params: { parentTurnIndex: params.parentTurnIndex ?? childSession.btwOrigin?.parentTurnIndex, }, 'btw'); const modelId = params.modelId?.trim(); - await trackBtwSessionSubmission(params.childSessionId, () => btwAPI.askStream({ + const submittedConfig = { ...childSession.config }; + const response: BtwAskStreamResponse = await trackBtwSessionSubmission(params.childSessionId, () => btwAPI.askStream({ requestId, sessionId: params.parentSessionId, childSessionId: params.childSessionId, @@ -396,13 +423,44 @@ export async function sendMessageToBtwSession(params: { ...(params.initialModelTarget ? { initialModelTarget: params.initialModelTarget } : {}), }).catch(async error => { // Closing waits for this confirmation as part of the submission. - if (!await btwQuestionReachedHost(scope, params.childSessionId, requestId, error)) throw error; + if (!await btwQuestionReachedHost(scope, params.childSessionId, requestId, error)) { + if (scope.isCurrent() && supportsBtwModelDefaults() && !classifyPeerHostRefusal(error)) { + notificationService.error(i18nService.t('flow-chat:btw.submitFailed', { + error: error instanceof Error ? error.message : String(error), + })); + } + throw error; + } log.info('Side question was admitted before its reply was lost', { childSessionId: params.childSessionId, requestId, }); return { ok: true }; })); + // Readback never retries an admitted turn, even if this optional read fails. + // Fence against a subsequent user switch while the read is in flight. + if (supportsBtwModelDefaults() && scope.isCurrent()) { + try { + const target = response.modelTarget ?? await modelPoolAPI.target({ sessionId: params.childSessionId, + workspaceId: sessionWorkspaceId(childSession), workspacePath: childSession.workspacePath, + remoteConnectionId: childSession.remoteConnectionId, remoteSshHost: childSession.remoteSshHost, + includeInternal: true }); + const currentConfig = scope.isCurrent() + ? flowChatStore.getState().sessions.get(params.childSessionId)?.config : undefined; + if (currentConfig && currentConfig.modelName === submittedConfig.modelName + && currentConfig.modelPoolId === submittedConfig.modelPoolId + && currentConfig.reasoningPreset === submittedConfig.reasoningPreset + && currentConfig.btwModelSelectionExplicit === submittedConfig.btwModelSelectionExplicit) { + flowChatStore.updateSessionModelPool(params.childSessionId, + target.selection.kind === 'pool' ? target.selection.pool_id : undefined, target.binding); + flowChatStore.updateSessionModelName(params.childSessionId, + target.selection.kind === 'model' ? target.selection.model_ref : target.binding?.modelId); + flowChatStore.updateSessionReasoningPreset(params.childSessionId, target.reasoningPreset); + } + } catch (error) { + if (scope.isCurrent()) log.warn('Could not read back the admitted BTW model selection', { error }); + } + } followBtwSessionOnPeer(scope, params.childSessionId); if (scope.isCurrent() && params.initialModelTarget?.selection.kind === 'pool') { const current = flowChatStore.getState().sessions.get(params.childSessionId); @@ -413,7 +471,7 @@ export async function sendMessageToBtwSession(params: { current.config.modelPoolBinding); } } - if (modelId && scope.isCurrent()) { + if (modelId && !supportsBtwModelDefaults() && scope.isCurrent()) { flowChatStore.updateSessionModelName(params.childSessionId, modelId); } diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.ts index 46cb01dedf..28511cac61 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.ts @@ -5255,6 +5255,16 @@ export class FlowChatStore { }); } + public markBtwModelSelectionExplicit(sessionId: string): void { + this.setState(state => { + const session = state.sessions.get(sessionId); + if (!session || session.sessionKind !== 'btw' || session.dialogTurns.length > 0) return state; + return { ...state, sessions: new Map(state.sessions).set(sessionId, { + ...session, config: { ...session.config, btwModelSelectionExplicit: true }, + }) }; + }); + } + public updateSessionModelPool( sessionId: string, poolId: string | undefined, binding?: import('@/infrastructure/api/service-api/ModelPoolAPI').ModelPoolBinding, diff --git a/src/web-ui/src/flow_chat/types/flow-chat.ts b/src/web-ui/src/flow_chat/types/flow-chat.ts index c1184c2005..0528f9d965 100644 --- a/src/web-ui/src/flow_chat/types/flow-chat.ts +++ b/src/web-ui/src/flow_chat/types/flow-chat.ts @@ -675,6 +675,8 @@ export interface SessionConfig { modelPoolId?: string; /** Draft-only intent, committed after the runtime session is created. */ modelPoolSelectionPending?: boolean; + /** Draft-only user override; inherited/default previews never set this flag. */ + btwModelSelectionExplicit?: boolean; modelPoolBinding?: import('@/infrastructure/api/service-api/ModelPoolAPI').ModelPoolBinding; /** Explicit reasoning preset for the next turn; omitted means model default. */ reasoningPreset?: string; diff --git a/src/web-ui/src/flow_chat/utils/sessionLineage.test.ts b/src/web-ui/src/flow_chat/utils/sessionLineage.test.ts index 309e2cace0..1a8906b6ef 100644 --- a/src/web-ui/src/flow_chat/utils/sessionLineage.test.ts +++ b/src/web-ui/src/flow_chat/utils/sessionLineage.test.ts @@ -159,4 +159,39 @@ describe('sessionLineage', () => { ]), )).toBe(false); }); + + it.each(['pending', 'image_analyzing', 'processing', 'finishing', 'cancelling'] as const)( + 'does not count a BTW side question as overview activity while %s', + status => { + const side = liveSession('side', 'root'); + side.sessionKind = 'btw'; + side.dialogTurns[0].status = status; + + expect(hasActiveSessionLineageDescendants( + 'root', new Map([[side.sessionId, side]]), + )).toBe(false); + }, + ); + + it('does not count a BTW side question beneath an inactive subagent', () => { + const child = liveSession('child', 'root'); + child.dialogTurns[0].status = 'completed'; + const side = liveSession('side', 'child'); + side.sessionKind = 'btw'; + + expect(hasActiveSessionLineageDescendants( + 'root', new Map([[child.sessionId, child], [side.sessionId, side]]), + )).toBe(false); + }); + + it('still counts an active subagent alongside a BTW side question', () => { + const side = liveSession('side', 'root'); + side.sessionKind = 'btw'; + const child = liveSession('child', 'root'); + const sessions = new Map([[side.sessionId, side], [child.sessionId, child]]); + + expect(hasActiveSessionLineageDescendants('root', sessions)).toBe(true); + child.dialogTurns[0].status = 'completed'; + expect(hasActiveSessionLineageDescendants('root', sessions)).toBe(false); + }); }); diff --git a/src/web-ui/src/flow_chat/utils/sessionLineage.ts b/src/web-ui/src/flow_chat/utils/sessionLineage.ts index 06876bbd88..af2f09da3f 100644 --- a/src/web-ui/src/flow_chat/utils/sessionLineage.ts +++ b/src/web-ui/src/flow_chat/utils/sessionLineage.ts @@ -209,6 +209,8 @@ export function hasActiveSessionLineageDescendants( for (const session of liveSessions.values()) { if ( session.sessionId === rootSessionId || + // Side questions have their own pane and do not light the overview indicator. + session.sessionKind === 'btw' || !isActiveSessionLineageLifecycle(sessionLineageLifecycleForSession(session)) ) { continue; diff --git a/src/web-ui/src/infrastructure/api/generated/productControl.ts b/src/web-ui/src/infrastructure/api/generated/productControl.ts index 36f9eadfac..97385cc696 100644 --- a/src/web-ui/src/infrastructure/api/generated/productControl.ts +++ b/src/web-ui/src/infrastructure/api/generated/productControl.ts @@ -1,5 +1,5 @@ // Generated by scripts/generate-interactive-capabilities.mjs; do not edit. -export const PRODUCT_CONTROL_GRAPH_DIGEST = "3f6c6936d3a543526f6a768b31c8058041ab3704f44be401086eb9174440d5cc" as const; +export const PRODUCT_CONTROL_GRAPH_DIGEST = "1e9b09293cfab7a47682d9decab4e0626137d6e79cd2405688d7f16e05a8e6b5" as const; export type ProductControlCapabilityId = "feature.home-search" | "feature.ai-assistant" | "feature.agents" | "feature.personal-assistants" | "feature.projects" | "feature.files-editor" | "feature.terminal" | "feature.cli-tui" | "feature.git" | "feature.code-review" | "feature.browser" | "feature.computer-use" | "feature.skills" | "feature.miniapps" | "feature.tasks-automation" | "feature.insights" | "feature.ecosystem-compatibility" | "feature.remote-workspaces" | "feature.remote-connect" | "feature.detached-dispatch" | "feature.pages" | "feature.voice-input" | "feature.desktop-pet" | "feature.desktop-cards" | "setting.application.general" | "setting.application.appearance" | "setting.application.pet" | "setting.application.input" | "setting.application.shortcuts" | "setting.application.development" | "setting.ai.models" | "setting.ai.permissions" | "setting.ai.memory" | "setting.workspace.session" | "setting.workspace.worktrees" | "setting.tools.execution" | "setting.application.terminal" | "setting.tools.desktop-control" | "setting.tools.browser-control" | "setting.tools.automation" | "setting.tools.web-search" | "setting.tools.mcp" | "setting.tools.acp" | "setting.data.usage" | "setting.data.archived" | "setting.data.diagnostics" | "feature.generative-ui"; diff --git a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts index 90035eeb4d..bfec5b864c 100644 --- a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts +++ b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate-interactive-capabilities.mjs; do not edit. // Source: openbitfun_product_domains::remote_surface (Product Operation Registry). -export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:aaf7320d931d5b35" as const; +export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:0b686be0f5103ef5" as const; /** * Registered Tauri commands the Peer Device controller keeps on the controller @@ -173,6 +173,7 @@ export const PEER_HOST_CAPABILITY_IDS = [ "runtime_attachment_upload_v1", "btw_initial_model_selection_v1", "btw_model_pool_selection_v1", + "btw_model_defaults_v1", "control_conversation_v1", "control_conversation_reset_v1", "targeted_session_rollback", @@ -237,6 +238,7 @@ export const PEER_HOST_ADVERTISED_CAPABILITIES: Readonly< "runtime_attachment_upload_v1", "btw_initial_model_selection_v1", "btw_model_pool_selection_v1", + "btw_model_defaults_v1", "control_conversation_v1", "control_conversation_reset_v1", "targeted_session_rollback", @@ -295,6 +297,7 @@ export const PEER_HOST_ADVERTISED_CAPABILITIES: Readonly< "runtime_attachment_upload_v1", "btw_initial_model_selection_v1", "btw_model_pool_selection_v1", + "btw_model_defaults_v1", "targeted_session_rollback", "token_usage_statistics", "model_channel_routing_v1", diff --git a/src/web-ui/src/infrastructure/api/service-api/BtwAPI.ts b/src/web-ui/src/infrastructure/api/service-api/BtwAPI.ts index 6389fa522c..05c5a460ec 100644 --- a/src/web-ui/src/infrastructure/api/service-api/BtwAPI.ts +++ b/src/web-ui/src/infrastructure/api/service-api/BtwAPI.ts @@ -1,5 +1,5 @@ import { api } from './ApiClient'; -import { supportsBtwModelPools, type ModelSelection } from './ModelPoolAPI'; +import { supportsBtwModelPools, type ModelSelection, type SessionModelTarget } from './ModelPoolAPI'; import { createTauriCommandError } from '../errors/TauriCommandError'; import type { ImageContextData as ImageInputContextData } from './ImageContextTypes'; @@ -20,14 +20,16 @@ export interface BtwAskStreamRequest { imageContexts?: ImageInputContextData[]; /** Optional UI metadata; question always contains the complete readable fallback. */ userMessageMetadata?: Record; - /** Negotiated on peers; omission retains the parent's model/reasoning policy. */ + /** Negotiated on peers; omission uses the host BTW default (inherit by default). */ initialModelSelection?: { modelId: string; reasoningPreset?: string }; - /** Requires btw_model_pool_selection_v1. Omit to inherit the parent's binding. */ + /** Requires btw_model_pool_selection_v1. Omit to use the host BTW default. */ initialModelTarget?: BtwInitialModelTarget; } export interface BtwAskStreamResponse { ok: boolean; + /** New hosts return the committed choice with admission, including BTW defaults. */ + modelTarget?: SessionModelTarget | null; } export interface BtwCancelRequest { diff --git a/src/web-ui/src/infrastructure/config/services/btwModelDefaults.ts b/src/web-ui/src/infrastructure/config/services/btwModelDefaults.ts new file mode 100644 index 0000000000..504e4f91da --- /dev/null +++ b/src/web-ui/src/infrastructure/config/services/btwModelDefaults.ts @@ -0,0 +1,27 @@ +import { isTauriRuntime } from '@/infrastructure/runtime'; +import { peerConnectionManager } from '@/infrastructure/peer-device/PeerConnectionManager'; +import { getActiveSurfaceScope } from '@/infrastructure/peer-device/deviceSurface'; +import type { AgentModelTargetSelection } from '../types'; + +export function supportsBtwModelDefaults(): boolean { + const scope = getActiveSurfaceScope(); + return scope.surfaceId === 'local' ? isTauriRuntime() : peerConnectionManager.list() + .find(peer => peer.surfaceId === scope.surfaceId)?.capabilities.btwModelDefaultsV1 === true; +} + +/** Only an absent field means inherit; unreadable choices must stay visible. */ +export function btwModelSelection(config: unknown): AgentModelTargetSelection | undefined { + if (!config || typeof config !== 'object' || Array.isArray(config)) return undefined; + const value = (config as Record).model_selection; + if (value === undefined) return { kind: 'inherit' }; + if (!value || typeof value !== 'object') return undefined; + const choice = value as Record; + if (choice.kind === 'inherit') return { kind: 'inherit' }; + if (choice.kind === 'model' && typeof choice.model_ref === 'string' && choice.model_ref.trim()) { + return { kind: 'model', model_ref: choice.model_ref }; + } + if (choice.kind === 'pool' && typeof choice.pool_id === 'string' && choice.pool_id.trim()) { + return { kind: 'pool', pool_id: choice.pool_id }; + } + return undefined; +} diff --git a/src/web-ui/src/infrastructure/config/types/index.ts b/src/web-ui/src/infrastructure/config/types/index.ts index 9d95c5b17e..f43302cbb6 100644 --- a/src/web-ui/src/infrastructure/config/types/index.ts +++ b/src/web-ui/src/infrastructure/config/types/index.ts @@ -520,6 +520,7 @@ export interface AIConfig { agent_model_defaults: AgentModelDefaultsConfig; agent_model_selections?: AgentModelSelections; task_models: TaskModelsConfig; + btw?: { model_selection: AgentModelTargetSelection; [key: string]: unknown }; agent_profiles: Record; proxy: ProxyConfig; request_timeout: number; diff --git a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.test.ts b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.test.ts index 203d2d8e3d..b5d07964d3 100644 --- a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.test.ts +++ b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.test.ts @@ -101,6 +101,7 @@ describe('PeerConnectionManager attach', () => { session_trajectory_v1: true, btw_initial_model_selection_v1: true, btw_model_pool_selection_v1: true, + btw_model_defaults_v1: true, magpie_discovery_v1: true, subagent_model_override_policy_v1: true, }, @@ -122,6 +123,7 @@ describe('PeerConnectionManager attach', () => { expect(caps.sessionTrajectoryV1).toBe(true); expect(caps.btwInitialModelSelectionV1).toBe(true); expect(caps.btwModelPoolSelectionV1).toBe(true); + expect(caps.btwModelDefaultsV1).toBe(true); expect(caps.subagentModelOverridePolicyV1).toBe(true); expect(caps.magpieDiscoveryV1).toBe(true); }); @@ -156,6 +158,7 @@ describe('PeerConnectionManager attach', () => { expect(desktop.getState().capabilities.sessionTrajectoryV1).toBe(false); expect(desktop.getState().capabilities.btwInitialModelSelectionV1).toBe(false); expect(desktop.getState().capabilities.btwModelPoolSelectionV1).toBe(false); + expect(desktop.getState().capabilities.btwModelDefaultsV1).toBe(false); expect(desktop.getState().capabilities.magpieDiscoveryV1).toBe(false); expect(desktop.getState().capabilities.chatMcpCatalogV1).toBe(false); diff --git a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts index 49677425b4..1abcf42851 100644 --- a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts +++ b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts @@ -58,6 +58,7 @@ export interface PeerHostCapabilities { readonly runtimeAttachmentUploadV1?: boolean; readonly btwInitialModelSelectionV1?: boolean; readonly btwModelPoolSelectionV1?: boolean; + readonly btwModelDefaultsV1?: boolean; /** Terminal output arrives as replay pages announced on the host stream. */ readonly terminalCursorReplayV1?: boolean; readonly controlConversationV1?: boolean; @@ -243,6 +244,7 @@ const NO_CAPABILITIES: PeerHostCapabilities = { runtimeAttachmentUploadV1: false, btwInitialModelSelectionV1: false, btwModelPoolSelectionV1: false, + btwModelDefaultsV1: false, terminalCursorReplayV1: false, controlConversationV1: false, controlConversationResetV1: false, @@ -726,6 +728,7 @@ export class PeerConnectionManager { runtimeAttachmentUploadV1: caps?.runtime_attachment_upload_v1 === true, btwInitialModelSelectionV1: caps?.btw_initial_model_selection_v1 === true, btwModelPoolSelectionV1: caps?.btw_model_pool_selection_v1 === true, + btwModelDefaultsV1: caps?.btw_model_defaults_v1 === true, terminalCursorReplayV1: caps?.terminal_cursor_replay_v1 === true, controlConversationV1: caps?.control_conversation_v1 === true, controlConversationResetV1: caps?.control_conversation_reset_v1 === true, diff --git a/src/web-ui/src/locales/en-US/flow-chat.json b/src/web-ui/src/locales/en-US/flow-chat.json index b6a371a5be..67a35629d5 100644 --- a/src/web-ui/src/locales/en-US/flow-chat.json +++ b/src/web-ui/src/locales/en-US/flow-chat.json @@ -1413,7 +1413,8 @@ "nestedDisabled": "A side question cannot start another side question", "error": "Failed", "close": "Close", - "noSession": "No active session for /btw" + "noSession": "No active session for /btw", + "submitFailed": "Could not start the side question: {{error}}" }, "childSession": { "stopReview": "Stop review", diff --git a/src/web-ui/src/locales/en-US/settings.json b/src/web-ui/src/locales/en-US/settings.json index 9aaabea33b..1e0ee4a6cc 100644 --- a/src/web-ui/src/locales/en-US/settings.json +++ b/src/web-ui/src/locales/en-US/settings.json @@ -101,7 +101,6 @@ "sections": { "text-selection": "Text selection", "message-sending": "Message sending", - "btw-close-confirmation": "Side conversation closing", "voice": "Voice", "shortcuts": "Keyboard Shortcuts", "session": "Session Defaults", @@ -114,7 +113,8 @@ "pet": "Pet", "voice-call": "Real-time voice calls", "desktop-cards": "Desktop cards", - "sidebar-navigation": "Left sidebar" + "sidebar-navigation": "Left sidebar", + "btw": "Side questions" } }, "changeGuard": { diff --git a/src/web-ui/src/locales/en-US/settings/models.json b/src/web-ui/src/locales/en-US/settings/models.json index bae74dc437..b0871ede69 100644 --- a/src/web-ui/src/locales/en-US/settings/models.json +++ b/src/web-ui/src/locales/en-US/settings/models.json @@ -1047,5 +1047,15 @@ "noCandidates": "No eligible backup models", "mode": "Routing", "modeHint": "Automatic switching tries the backups in order after a failure; a fixed choice only uses that channel and never switches." + }, + "btwModel": { + "title": "Side questions", + "label": "Default model", + "inherit": "Inherit parent session", + "pool": "Model pool: {{name}}", + "unavailable": "Saved selection is unavailable — choose another model or inherit", + "unsupported": "This host does not support side-question model defaults.", + "failed": "Could not load or save the side-question model setting. Your saved choice is retained.", + "retry": "Retry" } } diff --git a/src/web-ui/src/locales/zh-CN/flow-chat.json b/src/web-ui/src/locales/zh-CN/flow-chat.json index 54a5ec4634..704aa54369 100644 --- a/src/web-ui/src/locales/zh-CN/flow-chat.json +++ b/src/web-ui/src/locales/zh-CN/flow-chat.json @@ -1413,7 +1413,8 @@ "nestedDisabled": "侧问会话中不能继续新建侧问", "error": "失败", "close": "关闭", - "noSession": "当前没有可用于 /btw 的会话" + "noSession": "当前没有可用于 /btw 的会话", + "submitFailed": "无法发起侧问:{{error}}" }, "childSession": { "stopReview": "中止审核", diff --git a/src/web-ui/src/locales/zh-CN/settings.json b/src/web-ui/src/locales/zh-CN/settings.json index af6c298644..fa7ed2cd07 100644 --- a/src/web-ui/src/locales/zh-CN/settings.json +++ b/src/web-ui/src/locales/zh-CN/settings.json @@ -101,7 +101,6 @@ "sections": { "text-selection": "文本选择", "message-sending": "消息发送", - "btw-close-confirmation": "侧问关闭", "voice": "语音", "shortcuts": "快捷键", "session": "会话默认行为", @@ -114,7 +113,8 @@ "pet": "宠物", "voice-call": "实时语音通话", "desktop-cards": "小卡片", - "sidebar-navigation": "左侧导航栏" + "sidebar-navigation": "左侧导航栏", + "btw": "侧问" } }, "changeGuard": { diff --git a/src/web-ui/src/locales/zh-CN/settings/models.json b/src/web-ui/src/locales/zh-CN/settings/models.json index 3d5a48a92a..fcd9a3a790 100644 --- a/src/web-ui/src/locales/zh-CN/settings/models.json +++ b/src/web-ui/src/locales/zh-CN/settings/models.json @@ -1047,5 +1047,15 @@ "noCandidates": "暂无可用的备用模型", "mode": "使用方式", "modeHint": "自动切换会在失败时依次尝试备用渠道;固定使用只走所选渠道,失败时不切换。" + }, + "btwModel": { + "title": "侧问", + "label": "默认模型", + "inherit": "继承父会话", + "pool": "模型池:{{name}}", + "unavailable": "已保存的选择不可用,请另选模型或恢复继承", + "unsupported": "此宿主不支持侧问默认模型设置。", + "failed": "无法读取或保存侧问模型设置,已保留原有选择。", + "retry": "重试" } } diff --git a/src/web-ui/src/locales/zh-TW/flow-chat.json b/src/web-ui/src/locales/zh-TW/flow-chat.json index 24c60e06ee..37887c2ebc 100644 --- a/src/web-ui/src/locales/zh-TW/flow-chat.json +++ b/src/web-ui/src/locales/zh-TW/flow-chat.json @@ -1413,7 +1413,8 @@ "nestedDisabled": "側問會話中不能繼續新增側問", "error": "失敗", "close": "關閉", - "noSession": "目前沒有可用於 /btw 的會話" + "noSession": "目前沒有可用於 /btw 的會話", + "submitFailed": "無法發起側問:{{error}}" }, "childSession": { "stopReview": "中止審核", diff --git a/src/web-ui/src/locales/zh-TW/settings.json b/src/web-ui/src/locales/zh-TW/settings.json index 026e62229b..ed816b8a40 100644 --- a/src/web-ui/src/locales/zh-TW/settings.json +++ b/src/web-ui/src/locales/zh-TW/settings.json @@ -101,7 +101,6 @@ "sections": { "text-selection": "文字選取", "message-sending": "訊息傳送", - "btw-close-confirmation": "側問關閉", "voice": "語音", "shortcuts": "快捷鍵", "session": "工作階段預設行為", @@ -114,7 +113,8 @@ "pet": "寵物", "voice-call": "即時語音通話", "desktop-cards": "小卡片", - "sidebar-navigation": "左側導覽列" + "sidebar-navigation": "左側導覽列", + "btw": "側問" } }, "changeGuard": { diff --git a/src/web-ui/src/locales/zh-TW/settings/models.json b/src/web-ui/src/locales/zh-TW/settings/models.json index aa41dad019..5dbcf903f9 100644 --- a/src/web-ui/src/locales/zh-TW/settings/models.json +++ b/src/web-ui/src/locales/zh-TW/settings/models.json @@ -1047,5 +1047,15 @@ "noCandidates": "暫無可用的備用模型", "mode": "使用方式", "modeHint": "自動切換會在失敗時依序嘗試備用通道;固定使用只走所選通道,失敗時不切換。" + }, + "btwModel": { + "title": "側問", + "label": "預設模型", + "inherit": "繼承父會話", + "pool": "模型池:{{name}}", + "unavailable": "已儲存的選擇無法使用,請另選模型或恢復繼承", + "unsupported": "此主機不支援側問預設模型設定。", + "failed": "無法讀取或儲存側問模型設定,已保留原有選擇。", + "retry": "重試" } }