diff --git a/crates/ide-agent/src/catalogs.rs b/crates/ide-agent/src/catalogs.rs index 8fd948c84e..46f6d1c8ea 100644 --- a/crates/ide-agent/src/catalogs.rs +++ b/crates/ide-agent/src/catalogs.rs @@ -256,6 +256,38 @@ impl AgentCatalogs { .cloned() } + pub(super) async fn load_levels( + self: &Arc, + shared: &Arc, + provider: &str, + model: &str, + ) -> Result, String> { + if let Some(levels) = self.levels(shared, provider, model) { + return Ok(levels); + } + let unavailable = || "The agent did not report settings for the selected model".to_owned(); + let spec = shared.spec(provider).ok_or_else(unavailable)?; + let (_, flight) = self.request(shared, spec, false, Some(model)); + if let Some(mut ready) = flight { + while !*ready.borrow_and_update() { + if ready.changed().await.is_err() { + break; + } + } + } + self.levels(shared, provider, model).ok_or_else(|| { + let state = self.state.lock(); + state + .entries + .get(&Self::key(shared, provider)) + .and_then(|entry| { + entry.model_failures.get(model).map(|failure| &failure.error).or(entry.error.as_ref()) + }) + .cloned() + .unwrap_or_else(unavailable) + }) + } + pub(crate) fn evict_if_idle(&self, shared: &Shared, provider: &str) { let key = Self::key(shared, provider); let mut state = self.state.lock(); diff --git a/crates/ide-agent/src/catalogs/tests.rs b/crates/ide-agent/src/catalogs/tests.rs index 703f52e4dc..cdd749b9ea 100644 --- a/crates/ide-agent/src/catalogs/tests.rs +++ b/crates/ide-agent/src/catalogs/tests.rs @@ -323,6 +323,36 @@ async fn discovered_model_can_be_selected_while_the_session_is_not_running() { switch_chat_model(ChatSwitch::Idle).await; } +#[tokio::test] +async fn discovered_model_effort_is_discovered_persisted_and_applied_before_the_first_reply() { + switch_chat_model(ChatSwitch::Uncached).await; +} + +#[tokio::test] +async fn discovered_model_with_no_effort_can_be_selected() { + switch_chat_model(ChatSwitch::NoEffort).await; +} + +#[tokio::test] +async fn discovered_model_settings_failure_leaves_the_chat_unchanged() { + switch_chat_model(ChatSwitch::DiscoveryFails).await; +} + +#[tokio::test] +async fn discovered_model_withdrawn_effort_prevents_sending() { + switch_chat_model(ChatSwitch::EffortUnavailable).await; +} + +#[tokio::test] +async fn discovered_model_rejected_effort_prevents_sending() { + switch_chat_model(ChatSwitch::EffortRejected).await; +} + +#[tokio::test] +async fn discovered_model_lookup_does_not_overwrite_a_newer_selection() { + switch_chat_model(ChatSwitch::Superseded).await; +} + #[derive(Clone, Copy)] enum ChatSwitch { Live, @@ -330,6 +360,12 @@ enum ChatSwitch { ResumeFails, Unavailable, Idle, + Uncached, + NoEffort, + DiscoveryFails, + EffortUnavailable, + EffortRejected, + Superseded, } async fn switch_chat_model(scenario: ChatSwitch) { @@ -376,7 +412,21 @@ async fn switch_chat_model(scenario: ChatSwitch) { } let before_entries = serde_json::to_value(manager.entries(&task.id, None).unwrap()).unwrap(); let before_config = manager.task(&task.id).unwrap().state.lock().task.config.clone(); - if matches!(scenario, ChatSwitch::Idle) { + let offline = matches!(scenario, ChatSwitch::Idle | ChatSwitch::Uncached | ChatSwitch::Superseded); + let missing_settings = matches!( + scenario, + ChatSwitch::Uncached | ChatSwitch::NoEffort | ChatSwitch::DiscoveryFails | ChatSwitch::Superseded + ); + let no_effort = matches!(scenario, ChatSwitch::NoEffort); + let effort_error = match scenario { + ChatSwitch::EffortUnavailable => Some("no longer offers effort value thorough"), + ChatSwitch::EffortRejected => Some("effort rejected by the agent"), + _ => None, + }; + let choose_effort = matches!(scenario, ChatSwitch::Uncached) || effort_error.is_some(); + let (catalog_models, catalog_effort): (&[&str], &[&str]) = + if missing_settings { (&["old", "new"], &["low", "high"]) } else { (&["new", "old"], &["quick", "thorough"]) }; + if offline { manager.shutdown(); manager = make_manager(tmp.path(), Arc::default(), &harness); } @@ -385,41 +435,122 @@ async fn switch_chat_model(scenario: ChatSwitch) { assert!(manager.refresh_models(PROVIDER, false, None).unwrap().refreshing); let next = harness.next().await; assert_eq!((next.launch, next.method.as_str()), (1, "session/new")); - next.reply.send(Ok(response(&["new", "old"], &["catalog-only"]))).unwrap(); - assert_eq!(model_values(&completed(&mut events).await), ["new", "old"]); + next.reply.send(Ok(response(catalog_models, catalog_effort))).unwrap(); + let catalog = completed(&mut events).await; + assert_eq!(model_values(&catalog), catalog_models); + if missing_settings { + assert!(!catalog.thought_levels.contains_key("new")); + } assert_eq!(manager.task(&task.id).unwrap().state.lock().task.config, before_config); let live = matches!(scenario, ChatSwitch::Live); - let offline = matches!(scenario, ChatSwitch::Idle); + let resumed_launch = if missing_settings { 3 } else { 2 }; let load_fails = matches!(scenario, ChatSwitch::ResumeFails); let unavailable = matches!(scenario, ChatSwitch::Unavailable); - let switching = manager.set_config(&task.id, "model", "new".into()); - tokio::pin!(switching); - if !offline { - let next = next_chat_request(&mut harness, switching.as_mut()).await; - assert_eq!((next.launch, next.method.as_str()), (0, "session/set_config_option")); - assert_eq!(next.params, json!({"sessionId": "saved-chat", "configId": "model", "value": "new"})); - if live { - next.reply.send(Ok(response(&["new", "old"], &["session-only"]))).unwrap(); - } else { - next.reply.send(Err("not in this process's model list".into())).unwrap(); + { + let switching = manager.set_config(&task.id, "model", "new".into()); + tokio::pin!(switching); + if !offline { + let next = next_chat_request(&mut harness, switching.as_mut()).await; + assert_eq!((next.launch, next.method.as_str()), (0, "session/set_config_option")); + assert_eq!(next.params, json!({"sessionId": "saved-chat", "configId": "model", "value": "new"})); + if live { + next.reply.send(Ok(response(&["new", "old"], &["session-only"]))).unwrap(); + } else { + next.reply.send(Err("not in this process's model list".into())).unwrap(); + } + } + if missing_settings { + let discovery = next_chat_request(&mut harness, switching.as_mut()).await; + assert_eq!((discovery.launch, discovery.method.as_str()), (2, "session/new")); + discovery.reply.send(Ok(response(catalog_models, catalog_effort))).unwrap(); + let set = next_chat_request(&mut harness, switching.as_mut()).await; + assert_eq!(set.params, json!({"sessionId": "discovery-only", "configId": "model", "value": "new"})); + assert_eq!(set.method, "session/set_config_option"); + assert!( + manager + .prompt(&task.id, AgentPrompt { text: "too early".into(), ..Default::default() }, false) + .await + .is_err() + ); + if matches!(scenario, ChatSwitch::DiscoveryFails) { + set.reply.send(Err("Sign in required".into())).unwrap(); + let error = switching.await.unwrap_err().to_string(); + assert!(error.contains("Sign in required"), "{error}"); + assert_eq!(manager.subscribe(Arc::new(|_| {})).remove(0).config, before_config); + assert!(harness.pending.try_recv().is_err()); + manager.shutdown(); + return; + } + if matches!(scenario, ChatSwitch::Superseded) { + manager.set_config(&task.id, "model", "old".into()).await.unwrap(); + set.reply.send(Ok(response(&["new", "old"], &["quick", "thorough"]))).unwrap(); + switching.await.unwrap(); + let task = manager.subscribe(Arc::new(|_| {})).remove(0); + assert_eq!(task.config.iter().find(|o| o.id == "model").unwrap().current.as_deref(), Some("old")); + assert_eq!(task.config.iter().find(|o| o.id == "effort").unwrap().current.as_deref(), Some("low")); + assert!(harness.pending.try_recv().is_err()); + manager.shutdown(); + return; + } + let levels: &[&str] = if no_effort { &[] } else { &["quick", "thorough"] }; + set.reply.send(Ok(response(&["new", "old"], levels))).unwrap(); + } + tokio::select! { + result = &mut switching => result.unwrap(), + request = harness.next() => panic!("selection must not reopen the chat or send: {request:?}"), } } - // A fallback selection settles without waiting for a new process. - tokio::select! { - result = &mut switching => result.unwrap(), - request = harness.next() => panic!("selection must not open another session: {request:?}"), - } assert_eq!(serde_json::to_value(manager.entries(&task.id, None).unwrap()).unwrap(), before_entries); + if matches!(scenario, ChatSwitch::Uncached) { + let update = tokio::time::timeout(Duration::from_secs(5), async { + loop { + if let AgentEvent::Task { task: update } = events.recv().await.unwrap() + && update.id == task.id + { + break update; + } + } + }) + .await + .unwrap(); + let effort = update.config.iter().find(|o| o.id == "effort").unwrap(); + assert_eq!(effort.values.iter().map(|v| v.value.as_str()).collect::>(), ["quick", "thorough"]); + } let snapshot = |manager: &AgentManager| manager.subscribe(Arc::new(|_| {})).remove(0); let current = snapshot(&manager); assert_eq!(current.config.iter().find(|o| o.id == "model").unwrap().current.as_deref(), Some("new")); assert_eq!(current.model.as_deref(), Some(if live { "new" } else { "old" })); + let effort = + |task: &crate::AgentTask| task.config.iter().find(|o| o.id == "effort").and_then(|o| o.current.clone()); + assert_eq!( + effort(¤t).as_deref(), + if live { + Some("session-only") + } else if no_effort { + None + } else { + Some("quick") + }, + "the new model's effort must be available before sending" + ); + if choose_effort { + assert!(manager.set_config(&task.id, "effort", "high".into()).await.is_err()); + manager.set_config(&task.id, "effort", "thorough".into()).await.unwrap(); + assert_eq!(effort(&snapshot(&manager)).as_deref(), Some("thorough")); + if matches!(scenario, ChatSwitch::Uncached) { + manager.shutdown(); + manager = make_manager(tmp.path(), Arc::default(), &harness); + let restored = snapshot(&manager); + assert_eq!(restored.id, task.id); + assert_eq!(effort(&restored).as_deref(), Some("thorough")); + } + } manager.prompt(&task.id, AgentPrompt { text: "next".into(), ..Default::default() }, false).await.unwrap(); if !live { let load = harness.next().await; - assert_eq!((load.launch, load.method.as_str()), (2, "session/load")); + assert_eq!((load.launch, load.method.as_str()), (resumed_launch, "session/load")); assert_eq!(load.params["sessionId"], "saved-chat"); load.notifications .send(json!({"jsonrpc": "2.0", "method": "session/update", "params": { @@ -447,6 +578,7 @@ async fn switch_chat_model(scenario: ChatSwitch) { let task = snapshot(&manager); assert_eq!(task.model.as_deref(), Some("old")); assert_eq!(task.config.iter().find(|o| o.id == "model").unwrap().current.as_deref(), Some("old")); + assert_eq!(effort(&task).as_deref(), Some("low")); let expected = if load_fails { "cannot resume saved-chat" } else { "does not offer model new" }; assert!(task.error.as_deref().unwrap().contains(expected), "{:?}", task.error); assert!(harness.pending.try_recv().is_err(), "must not send on the previous model or create a session"); @@ -472,24 +604,60 @@ async fn switch_chat_model(scenario: ChatSwitch) { return; } let set = harness.next().await; - assert_eq!((set.launch, set.method.as_str()), (2, "session/set_config_option")); + assert_eq!((set.launch, set.method.as_str()), (resumed_launch, "session/set_config_option")); assert_eq!(set.params, json!({"sessionId": "saved-chat", "configId": "model", "value": "new"})); - set.reply.send(Ok(response(&["new", "old"], &["session-only"]))).unwrap(); + let levels: &[&str] = match scenario { + ChatSwitch::NoEffort => &[], + ChatSwitch::EffortUnavailable => &["session-only", "quick"], + _ if choose_effort => &["session-only", "thorough"], + _ => &["session-only"], + }; + set.reply.send(Ok(response(&["new", "old"], levels))).unwrap(); let set = harness.next().await; - assert_eq!((set.launch, set.method.as_str()), (2, "session/set_mode")); + assert_eq!((set.launch, set.method.as_str()), (resumed_launch, "session/set_mode")); assert_eq!(set.params, json!({"sessionId": "saved-chat", "modeId": "ask"})); set.reply.send(Ok(json!({}))).unwrap(); + if choose_effort && !matches!(scenario, ChatSwitch::EffortUnavailable) { + let set = harness.next().await; + assert_eq!((set.launch, set.method.as_str()), (resumed_launch, "session/set_config_option")); + assert_eq!(set.params, json!({"sessionId": "saved-chat", "configId": "effort", "value": "thorough"})); + let reply = if effort_error.is_some() { + Err("effort rejected by the agent".into()) + } else { + Ok(response(&["new", "old"], &["thorough", "session-only"])) + }; + set.reply.send(reply).unwrap(); + } + if let Some(expected) = effort_error { + wait_for_chat(&manager, &task.id, AgentStatus::Failed).await; + let current = snapshot(&manager); + assert_eq!(current.model.as_deref(), Some("old")); + assert_eq!(effort(¤t).as_deref(), Some("low")); + assert!(current.error.as_deref().unwrap().contains(expected), "{:?}", current.error); + assert!(harness.pending.try_recv().is_err(), "must not send using a fallback effort"); + manager.shutdown(); + return; + } } let next = harness.next().await; assert_eq!( (next.launch, next.method.as_str(), &next.params["sessionId"]), - (if live { 0 } else { 2 }, "session/prompt", &json!("saved-chat")) + (if live { 0 } else { resumed_launch }, "session/prompt", &json!("saved-chat")) ); next.reply.send(Ok(json!({"stopReason": "end_turn"}))).unwrap(); wait_for_chat(&manager, &task.id, AgentStatus::Ready).await; let current = snapshot(&manager); assert_eq!(current.model.as_deref(), Some("new")); - assert_eq!(current.config.iter().find(|o| o.id == "effort").unwrap().current.as_deref(), Some("session-only")); + assert_eq!( + effort(¤t).as_deref(), + if choose_effort { + Some("thorough") + } else if no_effort { + None + } else { + Some("session-only") + } + ); assert_eq!(current.config.iter().find(|o| o.id == "mode").unwrap().current.as_deref(), Some("ask")); manager.shutdown(); } diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs index 0e401130ad..a0eb4e4c8d 100644 --- a/crates/ide-agent/src/lib.rs +++ b/crates/ide-agent/src/lib.rs @@ -357,9 +357,11 @@ struct TaskFile { /// Settings the user chose, re-applied to every new or reloaded session. #[serde(default)] wanted: Vec, - /// Option id of a discovered model in `wanted` that still needs a same-session reload. - #[serde(default, skip_serializing_if = "Option::is_none")] + /// Pending model option id in task files saved before pending settings were stored separately. + #[serde(default, skip_serializing)] pending_model: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pending_switch: Option, /// In the project's own checkout: files already changed when the task started. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] before: BTreeMap, @@ -384,6 +386,26 @@ struct TaskFile { title_renamed: bool, } +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +struct PendingModel { + model: AgentConfigChoice, + candidate: Option, + options: Vec, + choices: Vec, +} + +impl PendingModel { + fn apply(&self, wanted: &mut Vec, confirmed: &[AgentConfigOption]) { + wanted.retain(|choice| { + choice.id != self.model.id + && !self.options.iter().any(|o| o.id == choice.id) + && !confirmed.iter().any(|o| o.id == choice.id && config::is_per_model_option(o)) + }); + wanted.push(self.model.clone()); + wanted.extend(self.choices.iter().cloned()); + } +} + /// The changed files of a checkout, stamped. type Snapshot = BTreeMap; @@ -392,8 +414,9 @@ struct TaskState { session_id: Option, conversation: Conversation, wanted: Vec, - pending_model: Option, + pending_model: Option, model_choice: u64, + discovering_model: Option, before: Arc>, saved: Option, /// See `TaskFile::touched`. @@ -415,23 +438,43 @@ struct TaskState { } impl TaskState { - fn pending_model(&self) -> Option<&AgentConfigChoice> { - let id = self.pending_model.as_deref()?; - self.wanted.iter().find(|c| c.id == id) - } - fn snapshot(&self) -> AgentTask { let mut task = self.task.clone(); - if let Some(choice) = self.pending_model() - && let Some(model) = task.config.iter_mut().find(|o| o.id == choice.id) + if let Some(pending) = &self.pending_model + && let Some(model) = task.config.iter_mut().find(|o| o.id == pending.model.id) { - model.current = Some(choice.value.clone()); + model.current = Some(pending.model.value.clone()); + if let Some(candidate) = &pending.candidate + && !model.values.iter().any(|v| v.value == candidate.value) + { + model.values.push(candidate.clone()); + } task.config.retain(|o| !config::is_per_model_option(o)); + task.config.extend(pending.options.iter().cloned().map(|mut option| { + if let Some(choice) = pending.choices.iter().find(|choice| choice.id == option.id) { + option.current = Some(choice.value.clone()); + } + option + })); } task } } +struct DiscoveringModel<'a> { + state: &'a Mutex, + generation: u64, +} + +impl Drop for DiscoveringModel<'_> { + fn drop(&mut self) { + let mut s = self.state.lock(); + if s.discovering_model == Some(self.generation) { + s.discovering_model = None; + } + } +} + /// A running agent and its session. #[derive(Clone)] struct Live { @@ -796,6 +839,7 @@ impl AgentManager { entries: Vec::new(), wanted: Vec::new(), pending_model: None, + pending_switch: None, before: BTreeMap::new(), saved: None, touched: Some(BTreeSet::new()), @@ -912,6 +956,7 @@ impl AgentManager { entries: Vec::new(), wanted: req.config, pending_model: None, + pending_switch: None, before, saved, touched: (req.isolation == Isolation::Local).then(BTreeSet::new), @@ -949,6 +994,9 @@ impl AgentManager { if s.task.status == AgentStatus::Archived { return Err(IdeError::invalid("the task is archived")); } + if s.discovering_model.is_some() { + return Err(IdeError::unavailable("Model settings are still loading")); + } if s.busy { let item = AgentQueued { id: uuid::Uuid::new_v4().simple().to_string(), prompt }; if now { @@ -1068,6 +1116,24 @@ impl AgentManager { let task = self.task(id)?; let (target, change) = { let mut s = task.state.lock(); + let busy = s.busy; + let archived = s.task.status == AgentStatus::Archived; + if let Some(pending) = &mut s.pending_model + && let Some(target) = pending.options.iter().find(|o| o.id == option) + { + if archived || busy { + return Err(IdeError::invalid("The pending model settings cannot be changed now")); + } + if !target.values.iter().any(|v| v.value == value) { + return Err(IdeError::invalid(format!("{} has no value {value}", target.name))); + } + pending.choices.retain(|c| c.id != option); + pending.choices.push(AgentConfigChoice { id: option.to_owned(), value }); + drop(s); + task.persist(); + task.emit_task(); + return Ok(()); + } let target = s .task .config @@ -1075,6 +1141,9 @@ impl AgentManager { .find(|o| o.id == option) .ok_or_else(|| IdeError::not_found("no such setting"))? .clone(); + if s.pending_model.is_some() && config::is_per_model_option(&target) { + return Err(IdeError::invalid("This setting is not available on the selected model")); + } if !target.values.iter().any(|v| v.value == value) { if target.category.as_deref() != Some("model") { return Err(IdeError::invalid(format!("{} has no value {value}", target.name))); @@ -1083,8 +1152,12 @@ impl AgentManager { } else { let switching_model = target.category.as_deref() == Some("model"); if switching_model { + if s.pending_model.is_some() && s.busy { + return Err(IdeError::invalid("The pending model settings cannot be changed now")); + } s.model_choice += 1; s.pending_model = None; + s.discovering_model = None; } let previous_levels = (switching_model && target.current.as_deref() != Some(value.as_str())) .then(|| s.task.config.extract_if(.., |o| config::is_per_model_option(o)).collect::>()); @@ -1116,33 +1189,19 @@ impl AgentManager { && (previous.as_deref() != Some(value.as_str()) || !model_options) { let provider = task.state.lock().task.provider.clone(); - let mut levels = self.shared.paths.catalogs.levels(&self.shared, &provider, &value); - let mut error = None; - if levels.is_none() - && let Some(spec) = self.shared.spec(&provider) - { - let (catalog, flight) = self.shared.paths.catalogs.request(&self.shared, spec, false, Some(&value)); - error = catalog.error; - if let Some(mut ready) = flight { - while !*ready.borrow_and_update() { - if ready.changed().await.is_err() { - break; - } - } - } - levels = self.shared.paths.catalogs.levels(&self.shared, &provider, &value); - } + let levels = self.shared.paths.catalogs.load_levels(&self.shared, &provider, &value).await; // Another selection may have superseded this discovery while it was waiting. if task.state.lock().model_choice != model_choice { return Ok(()); } - let Some(levels) = levels else { - restore_config_choice(&task, &target, &value, previous.as_deref(), model_choice, previous_levels); - task.persist(); - task.emit_task(); - return Err(IdeError::unavailable( - error.unwrap_or_else(|| "The agent did not report settings for the selected model".into()), - )); + let levels = match levels { + Ok(levels) => levels, + Err(error) => { + restore_config_choice(&task, &target, &value, previous.as_deref(), model_choice, previous_levels); + task.persist(); + task.emit_task(); + return Err(IdeError::unavailable(error)); + } }; let mut s = task.state.lock(); if s.model_choice != model_choice { @@ -1265,6 +1324,7 @@ impl AgentManager { entries, wanted: s.wanted.clone(), pending_model: None, + pending_switch: None, before: (*s.before).clone(), saved: s.saved.clone(), touched: s.touched.as_deref().cloned(), @@ -1310,6 +1370,8 @@ impl AgentManager { }; s.session_id = None; s.pending_model = None; + s.model_choice += 1; + s.discovering_model = None; s.conversation = Conversation::default(); // The fresh session reports its own usage; nothing carries over. s.task.usage = None; @@ -1908,6 +1970,24 @@ impl Task { let mut task = file.task; config::add_client_options(&task.provider, &mut task.config); let conversation = Conversation::restore(file.entries, file.subagents); + let mut wanted = file.wanted; + let pending_model = file.pending_switch.or_else(|| { + let id = file.pending_model?; + let index = wanted.iter().position(|choice| choice.id == id)?; + let model = wanted.remove(index); + if let Some(value) = task.model.clone() { + wanted.push(AgentConfigChoice { id, value }); + } + let catalog = shared.paths.catalogs.cached(&shared, &task.provider); + let candidate = catalog + .config + .iter() + .find(|o| o.category.as_deref() == Some("model")) + .and_then(|o| o.values.iter().find(|v| v.value == model.value)) + .cloned(); + let options = catalog.thought_levels.get(&model.value).cloned().unwrap_or_default(); + Some(PendingModel { model, candidate, options, choices: Vec::new() }) + }); Arc::new(Self { id: task.id.clone(), shared, @@ -1915,9 +1995,10 @@ impl Task { task, session_id: file.session_id, conversation, - wanted: file.wanted, - pending_model: file.pending_model, + wanted, + pending_model, model_choice: 0, + discovering_model: None, before: Arc::new(file.before), saved: file.saved, touched: file.touched.map(Arc::new), @@ -2111,7 +2192,8 @@ impl Task { session_id: s.session_id.clone(), entries: s.conversation.main.entries.clone(), wanted: s.wanted.clone(), - pending_model: s.pending_model.clone(), + pending_model: None, + pending_switch: s.pending_model.clone(), before: (*s.before).clone(), saved: s.saved.clone(), touched: s.touched.as_deref().cloned(), @@ -2264,13 +2346,18 @@ impl Task { let candidate = self.shared.paths.catalogs.fresh_model(&self.shared, &spec, &value).ok_or_else(|| { IdeError::invalid(format!("{} has no value {value} in the current model catalog", target.name)) })?; - let model_choice = { + let selection = { let mut s = self.state.lock(); + if s.task.status == AgentStatus::Archived { + return Err(IdeError::invalid("the task is archived")); + } s.model_choice += 1; - s.model_choice + s.discovering_model = Some(s.model_choice); + DiscoveringModel { state: &self.state, generation: s.model_choice } }; + let model_choice = selection.generation; // A prompt starting during the switch must not grab the peer we're about to recycle. - let _connecting = self.connecting.lock().await; + let connecting = self.connecting.lock().await; { let s = self.state.lock(); if s.model_choice != model_choice { @@ -2293,16 +2380,16 @@ impl Task { Ok(None) }; - let accepted = { - let mut s = self.state.lock(); - if s.model_choice != model_choice { - return Ok(()); - } - if s.task.status == AgentStatus::Archived { - return Err(IdeError::invalid("the task is archived")); - } - let pending = match result { - Ok(Some(reply)) => { + let refused = match result { + Ok(Some(reply)) => { + let (config, model) = { + let mut s = self.state.lock(); + if s.model_choice != model_choice { + return Ok(()); + } + if s.task.status == AgentStatus::Archived { + return Err(IdeError::invalid("the task is archived")); + } if let Some(options) = reply.get("configOptions") { config::merge_update(&mut s.task.config, options); } else if s.task.model.as_deref() != Some(value.as_str()) { @@ -2321,36 +2408,66 @@ impl Task { model.current = Some(value.clone()); s.task.model = Some(value.clone()); sync_usage_context_size(&mut s.task); - false - } - refused => { - if s.session_id.is_none() - || live.as_ref().is_some_and(|l| !l.resumable) - || self.start_fresh.load(Ordering::Acquire) - { - return Err(IdeError::unavailable( - refused.err().unwrap_or_else(|| "The agent does not support resuming this session.".into()), - )); - } - if s.busy || !s.background_tasks.is_empty() || !self.permissions.lock().is_empty() { - return Err(IdeError::invalid("wait until the agent is done")); - } - true - } - }; - s.wanted.retain(|c| c.id != target.id); - s.pending_model = pending.then(|| target.id.clone()); - s.wanted.push(AgentConfigChoice { id: target.id, value }); - (!pending).then(|| { - let model = s.task.model.clone().filter(|_| s.task.config.iter().any(config::is_per_model_option)); - (s.task.config.clone(), model) - }) + s.pending_model = None; + s.wanted.retain(|c| c.id != target.id); + s.wanted.push(AgentConfigChoice { id: target.id, value }); + let model = s.task.model.clone().filter(|_| s.task.config.iter().any(config::is_per_model_option)); + (s.task.config.clone(), model) + }; + self.shared.remember(&provider, Some(&config), None, model.as_deref()); + self.persist(); + self.emit_task(); + return Ok(()); + } + refused => refused, }; - if let Some((config, model)) = accepted { - self.shared.remember(&provider, Some(&config), None, model.as_deref()); - } else { - self.recycle_resumable_session(); + { + let s = self.state.lock(); + if s.model_choice != model_choice { + return Ok(()); + } + if s.session_id.is_none() + || live.as_ref().is_some_and(|l| !l.resumable) + || self.start_fresh.load(Ordering::Acquire) + { + return Err(IdeError::unavailable( + refused.err().unwrap_or_else(|| "The agent does not support resuming this session.".into()), + )); + } + if s.busy || !s.background_tasks.is_empty() || !self.permissions.lock().is_empty() { + return Err(IdeError::invalid("wait until the agent is done")); + } } + // Catalog discovery never owns the chat session. Let a newer model choice supersede it. + drop(connecting); + let options = self.shared.paths.catalogs.load_levels(&self.shared, &provider, &value).await; + let _connecting = self.connecting.lock().await; + { + let mut s = self.state.lock(); + if s.model_choice != model_choice { + return Ok(()); + } + if s.task.status == AgentStatus::Archived { + return Err(IdeError::invalid("the task is archived")); + } + if s.busy || !s.background_tasks.is_empty() || !self.permissions.lock().is_empty() { + return Err(IdeError::invalid("wait until the agent is done")); + } + let options = options.map_err(IdeError::unavailable)?; + let choices = s + .pending_model + .take() + .filter(|pending| pending.model.value == value) + .map(|pending| pending.choices) + .unwrap_or_default(); + s.pending_model = Some(PendingModel { + model: AgentConfigChoice { id: target.id, value }, + candidate: Some(candidate), + options, + choices, + }); + } + self.recycle_resumable_session(); self.persist(); self.emit_task(); Ok(()) @@ -2612,10 +2729,9 @@ impl Task { } let (provider_id, cwd, saved, pending) = { let s = self.state.lock(); - let pending = s.pending_model().map(|choice| (choice.clone(), s.task.model.clone())); - (s.task.provider.clone(), s.task.cwd.0.clone(), s.session_id.clone(), pending) + (s.task.provider.clone(), s.task.cwd.0.clone(), s.session_id.clone(), s.pending_model.clone()) }; - let pending_model = pending.as_ref().map(|(choice, _)| choice); + let pending_model = pending.as_ref(); let raw_spec = self.shared.spec(&provider_id).ok_or_else(|| format!("unknown agent {provider_id}"))?; let can_fallback = raw_spec.driver == provider::Driver::Copilot && !self.shared.uses_copilot_acp_fallback(&raw_spec); @@ -2641,22 +2757,12 @@ impl Task { let live = match opened { Ok(live) => live, Err(err) => { - if let Some((choice, previous)) = pending { - let mut s = self.state.lock(); - if s.pending_model() == Some(&choice) { - s.pending_model = None; - s.wanted.retain(|c| c.id != choice.id); - if let Some(model) = s.task.config.iter_mut().find(|o| o.id == choice.id) { - model.current.clone_from(&previous); - } - s.task.model.clone_from(&previous); - if let Some(value) = previous { - s.wanted.push(AgentConfigChoice { id: choice.id, value }); - } - drop(s); - self.persist(); - self.emit_task(); - } + let mut s = self.state.lock(); + if pending.is_some() && s.pending_model == pending { + s.pending_model = None; + drop(s); + self.persist(); + self.emit_task(); } return Err(err.message); } @@ -2671,7 +2777,7 @@ impl Task { spec: provider::ProviderSpec, cwd: &Path, saved: Option, - pending_model: Option<&AgentConfigChoice>, + pending_model: Option<&PendingModel>, ) -> Result { let launch_cwd = cwd.to_path_buf(); let mut spec = tokio::task::spawn_blocking(move || spec.resolve_for_launch(&launch_cwd)) @@ -2697,14 +2803,15 @@ impl Task { } }); // Speaks ACP v1 or v2, whichever the agent chooses; the task sees v1 either way. - let client = acp::Dialect::wrap(Arc::new(Client { task: Arc::downgrade(self) })); + let client = Client::new(self, saved.as_deref().filter(|_| pending_model.is_some())); + let handler = acp::Dialect::wrap(client.clone()); let raw_peer = - (self.shared.connector)(&spec, cwd, client.clone(), on_stderr).map_err(|e| SessionOpenError { + (self.shared.connector)(&spec, cwd, handler.clone(), on_stderr).map_err(|e| SessionOpenError { message: format!("Couldn't start {} (`{}`): {e}", spec.name, spec.command), allow_acp_fallback: !native::copilot::is_missing_binary_error(&e), })?; let mut stop_on_err = KillOnDrop(Some(raw_peer.clone())); - let peer = acp::Conn::new(raw_peer, client); + let peer = acp::Conn::new(raw_peer, handler); let init = peer.initialize(&client_info()).await.map_err(|e| { let is_auth = matches!(&e, RpcError::Server { code, message, .. } if acp::auth_required(*code, message)); @@ -2803,7 +2910,13 @@ impl Task { // The session's settings, then the user's choices on top. // A session that reports none keeps the last known ones, but what is set is unknown. - let reported = config::options_of(&result); + let mut reported = config::options_of(&result); + if let Some(update) = client.take_opening_config() + && let Some(config) = update.get("configOptions") + && reported.iter().all(|o| o.category.as_deref() != Some("model")) + { + config::merge_update(&mut reported, config); + } let known = !reported.is_empty(); if known { self.shared.remember(provider_id, Some(&reported), None, model_of(&reported).as_deref()); @@ -2811,19 +2924,33 @@ impl Task { let (mut options, mut wanted) = { let s = self.state.lock(); let options = if known { reported } else { s.task.config.clone() }; - let wanted = s.wanted.clone(); + let mut wanted = s.wanted.clone(); + if let Some(pending) = pending_model { + pending.apply(&mut wanted, &s.task.config); + } (options, wanted) }; config::add_client_options(provider_id, &mut options); // Changing model can replace the effort / context-tier choices; validate those only afterwards. - wanted.sort_by_key(|c| match options.iter().find(|o| o.id == c.id) { - Some(o) if o.category.as_deref() == Some("model") => 0, - Some(o) if config::is_per_model_option(o) => 2, - _ => 1, + wanted.sort_by_key(|c| { + if let Some(pending) = pending_model { + if c == &pending.model { + return 0; + } + if pending.choices.contains(c) { + return 2; + } + } + match options.iter().find(|o| o.id == c.id) { + Some(o) if o.category.as_deref() == Some("model") => 0, + Some(o) if config::is_per_model_option(o) => 2, + _ => 1, + } }); let mut model_options = known; for choice in &wanted { - let pending = pending_model == Some(choice); + let pending = pending_model.is_some_and(|p| &p.model == choice); + let explicit = pending_model.is_some_and(|p| p.choices.contains(choice)); if pending && !options.iter().any(|o| { o.id == choice.id @@ -2836,6 +2963,19 @@ impl Task { allow_acp_fallback: false, }); } + if explicit + && (!model_options + || !options.iter().any(|o| { + o.id == choice.id + && config::is_per_model_option(o) + && o.values.iter().any(|v| v.value == choice.value) + })) + { + return Err(SessionOpenError { + message: format!("The selected model no longer offers {} value {}.", choice.id, choice.value), + allow_acp_fallback: false, + }); + } // An option the session doesn't offer yet is set once it does (`apply_late_choices`). let Some(o) = options.iter().find(|o| o.id == choice.id).cloned() else { continue }; if o.id == config::CURSOR_APPROVAL { @@ -2847,7 +2987,7 @@ impl Task { if config::is_per_model_option(&o) && !model_options { continue; } - let already = known && o.current.as_deref() == Some(choice.value.as_str()); + let already = (known || explicit) && o.current.as_deref() == Some(choice.value.as_str()); if already || !o.values.iter().any(|v| v.value == choice.value) { continue; } @@ -2856,14 +2996,30 @@ impl Task { params["sessionId"] = json!(session_id); match peer.request::<_, Value>(method, params, None).await { Ok(reply) => { - if pending && !config::accepts_model(&reply, &o.id, &choice.value) { + let observed = client.take_opening_config(); + let report = + if reply.get("configOptions").is_some() { &reply } else { observed.as_ref().unwrap_or(&reply) }; + if pending && !config::accepts_model(report, &o.id, &choice.value) { return Err(SessionOpenError { message: format!("The reloaded session did not switch to model {}.", choice.value), allow_acp_fallback: false, }); } - if let Some(fresh) = reply.get("configOptions") { + if let Some(fresh) = report.get("configOptions") { config::merge_update(&mut options, fresh); + if explicit + && !options.iter().any(|option| { + option.id == choice.id && option.current.as_deref() == Some(choice.value.as_str()) + }) + { + return Err(SessionOpenError { + message: format!( + "The selected model did not accept {} value {}.", + choice.id, choice.value + ), + allow_acp_fallback: false, + }); + } model_options = true; } else if o.category.as_deref() == Some("model") { if o.current.as_deref() != Some(choice.value.as_str()) { @@ -2875,7 +3031,7 @@ impl Task { o.current = Some(choice.value.clone()); } } - Err(e) if pending => { + Err(e) if pending || explicit => { return Err(SessionOpenError { message: self.describe(e), allow_acp_fallback: false }); } Err(e) => tracing::warn!("agent task {}: setting {} to {} failed: {e}", self.id, o.id, choice.value), @@ -2885,6 +3041,16 @@ impl Task { self.shared.remember(provider_id, Some(&options), None, model.as_deref()); { let mut s = self.state.lock(); + if let Some(pending) = pending_model { + if s.pending_model.as_ref() != Some(pending) { + return Err(SessionOpenError { + message: "The pending model settings changed while reopening the session.".into(), + allow_acp_fallback: false, + }); + } + let TaskState { task, wanted, .. } = &mut *s; + pending.apply(wanted, &task.config); + } s.task.model = model_of(&options).or(s.task.model.take()); s.task.config = options; s.pending_model = None; @@ -2894,6 +3060,7 @@ impl Task { // The (re)started process runs nothing yet: whatever it reports next is all of it. s.background_tasks = Vec::new(); s.task.background.clear(); + *client.opening_config.lock() = None; } self.persist(); self.emit_task(); @@ -3361,6 +3528,28 @@ impl Task { /// Answers the agent's requests on behalf of one task. struct Client { task: Weak, + opening_config: Mutex>, +} + +/// Config replays belong to the candidate connection until its model and settings are confirmed. +struct OpeningConfig { + session: String, + options: Option, +} + +impl Client { + fn new(task: &Arc, opening_session: Option<&str>) -> Arc { + Arc::new(Self { + task: Arc::downgrade(task), + opening_config: Mutex::new( + opening_session.map(|id| OpeningConfig { session: id.to_owned(), options: None }), + ), + }) + } + + fn take_opening_config(&self) -> Option { + self.opening_config.lock().as_mut()?.options.take() + } } impl Handler for Client { @@ -3377,6 +3566,14 @@ impl Handler for Client { if method == "session/update" && let (Some(task), Some(update)) = (self.task.upgrade(), params.get("update")) { + if update.get("sessionUpdate").and_then(Value::as_str) == Some("config_option_update") + && let Some(opening) = self.opening_config.lock().as_mut() + { + if params.get("sessionId").and_then(Value::as_str) == Some(opening.session.as_str()) { + opening.options = Some(update.clone()); + } + return; + } task.on_update(params.get("sessionId").and_then(Value::as_str), update); } } diff --git a/crates/ide-agent/src/tests.rs b/crates/ide-agent/src/tests.rs index c644cf44fb..25d2016c89 100644 --- a/crates/ide-agent/src/tests.rs +++ b/crates/ide-agent/src/tests.rs @@ -1935,7 +1935,7 @@ async fn startup_warnings_survive_replay_and_restart_without_failing_the_task() let handle = mgr.task(&task.id).unwrap(); handle.replaying.store(true, Ordering::Release); handle.turn_started.store(false, Ordering::Release); - let client = Client { task: Arc::downgrade(&handle) }; + let client = Client::new(&handle, None); client.on_notification(WARNING_NOTIFICATION, json!({"message": "Project MCP config is disabled until trusted."})); client.on_notification(WARNING_NOTIFICATION, json!({"message": " "})); client.on_notification(WARNING_NOTIFICATION, json!({})); diff --git a/crates/ide-core/src/workflow_settings.rs b/crates/ide-core/src/workflow_settings.rs index 06c41a2a3a..816a0281a6 100644 --- a/crates/ide-core/src/workflow_settings.rs +++ b/crates/ide-core/src/workflow_settings.rs @@ -170,6 +170,12 @@ pub struct CommitSettings { pub double_click_opens_diff: Option, /// Team conventions for Generate Commit Message with Agent, added to its prompt. pub agent_instructions: String, + /// The coding agent Generate Commit Message with Agent uses; empty follows the latest task's agent. + pub agent: String, + /// That agent's model for commit messages; empty keeps the model the agent would use. + pub agent_model: String, + /// That model's thinking level for commit messages; empty keeps the agent's. + pub agent_effort: String, } impl Default for CommitSettings { @@ -192,6 +198,9 @@ impl Default for CommitSettings { disabled_plugin_checks: Vec::new(), double_click_opens_diff: None, agent_instructions: String::new(), + agent: String::new(), + agent_model: String::new(), + agent_effort: String::new(), } } } diff --git a/crates/ide-host/src/formatter.rs b/crates/ide-host/src/formatter.rs index ca4fd05b6d..d61c23b009 100644 --- a/crates/ide-host/src/formatter.rs +++ b/crates/ide-host/src/formatter.rs @@ -119,6 +119,29 @@ fn php_cs_fixer_edits( .collect()) } +/// Some language servers (Vue's, for one) answer Reformat Code with one edit replacing the +/// whole file; applied as is, it moves the caret and the view to the top of the file. The same +/// result as one edit per changed region keeps them where they were. +fn minimal_edits(text: &str, edits: Vec) -> Vec { + if !edits.iter().any(|e| e.range.end.line > e.range.start.line) { + return edits; + } + let original = ide_text::Document::new(text); + let mut formatted = original.clone(); + if formatted.apply_edits(&edits).is_err() { + return edits; + } + original + .diff(&formatted.text()) + .changes + .into_iter() + .map(|c| TextEdit { + range: Range::new(original.offset_to_pos(c.from), original.offset_to_pos(c.to)), + new_text: c.insert, + }) + .collect() +} + pub async fn format( host: &Host, window: &str, @@ -292,7 +315,11 @@ async fn provider_edits( if options.on_save && !settings.editor.format_on_save { return Ok(None); } - return project.lsp.format(doc, range, options).await.map(Some); + let edits = project.lsp.format(doc, range, options).await?; + let text = snap.text; + return tokio::task::spawn_blocking(move || Some(minimal_edits(&text, edits))) + .await + .map_err(|e| IdeError::internal(e.to_string())); }; let tool_settings = settings.languages.formatter(selected); if options.on_save && !tool_settings.run_on_save { @@ -523,6 +550,25 @@ mod tests { const ALIGN: PhpAlignment = PhpAlignment { key_value_pairs: true, assignments: true }; + #[test] + fn a_whole_file_edit_becomes_one_edit_per_changed_region() { + let text = "a\n b\nc\nd\n e\n"; + let formatted = "a\nb\nc\nd\ne\n"; + let whole = vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(5, 0)), new_text: formatted.into() }]; + let edits = minimal_edits(text, whole); + assert_eq!( + edits, + [ + TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 2)), new_text: String::new() }, + TextEdit { range: Range::new(Pos::new(4, 0), Pos::new(4, 2)), new_text: String::new() }, + ] + ); + assert_eq!(after(text, &edits), formatted); + // Single-line edits are already minimal and pass through. + let small = vec![TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 2)), new_text: String::new() }]; + assert_eq!(minimal_edits(text, small.clone()), small); + } + #[test] fn php_alignment_is_off_unless_the_php_code_style_turns_it_on() { let php = LanguageId::new("php"); diff --git a/crates/ide-sdk/src/tests.rs b/crates/ide-sdk/src/tests.rs index 7bfe85a507..a0f9524060 100644 --- a/crates/ide-sdk/src/tests.rs +++ b/crates/ide-sdk/src/tests.rs @@ -902,9 +902,11 @@ fn always_update_snapshots_adds_dash_u_once() { apply_to_run_configs(&mut own, tmp.path(), &s); assert_eq!(own[0].args, ["--update-snapshots", "package"]); + // Settings apply to the stored configuration at each launch, so turning it off drops -U. s.languages.java.maven.update_snapshots = false; - apply_to_run_configs(&mut configs, tmp.path(), &s); - assert_eq!(configs[0].args, ["package"]); + let mut stored = vec![run("maven", "./mvnw", &["package"])]; + apply_to_run_configs(&mut stored, tmp.path(), &s); + assert_eq!(stored[0].args, ["package"]); } #[test] diff --git a/crates/ide-workspace/src/settings.rs b/crates/ide-workspace/src/settings.rs index d6b1526e35..f2e0132435 100644 --- a/crates/ide-workspace/src/settings.rs +++ b/crates/ide-workspace/src/settings.rs @@ -847,6 +847,9 @@ mod tests { "disabledPluginChecks": [], "doubleClickOpensDiff": null, "agentInstructions": "", + "agent": "", + "agentModel": "", + "agentEffort": "", }) ); } diff --git a/docs/en/contribute/testing/perf.mdx b/docs/en/contribute/testing/perf.mdx index a34c92abe0..bacf8e96ee 100644 --- a/docs/en/contribute/testing/perf.mdx +++ b/docs/en/contribute/testing/perf.mdx @@ -29,7 +29,13 @@ pnpm perf -- --only typing --profile --unminified # CPU profile and top functi Other options: `--warmup ` (default 1), `--headed`, `--no-build` (reuse the last build), `--channel ` (default `chromium`, or `OPENIDEA_PERF_CHANNEL`), `--fail-on-regression`. -Scenarios (`perf/scenarios.ts`): `typing`, `typingLarge`, `typingAngular`, `completion`, `consoleOutput`, `terminalTui`, `keyRepeat`, `scroll`, `gitLog`, `gitLogScrollbar`, `resizePanels`, `startup`, `tabs`, `agentTabs`, `popups`, `toolWindows`, `projectTree`, `leaks`. Bundle size (`bundle.initialJsKb`, `bundle.initialCssKb`) is checked on every run. +`--runs` must be a positive integer, `--warmup` a nonnegative integer, and `--cpu` a finite number of at least 1. Empty or unknown `--only` entries fail before building or launching a browser. Every declared selected scenario must return exactly one result; missing budgeted metrics and nonfinite metrics fail even when CPU throttling disables timing-budget enforcement. Unminified profiling builds intentionally omit bundle-size checks. + +Every attempted repetition, including warmups, is retained in `target/perf/report.json` with status, metrics and failure reason. Markdown shows valid/planned and attempted counts. Missing or nonfinite repetitions are not filtered out of medians; invalid warmups also fail the scenario. Build, browser and cleanup failures replace the previous report with a fresh failure. + +UI builds and individual trials have five-minute wall-clock deadlines independent of renderer animation frames. Browser startup is bounded to 30 seconds; context/HTTP cleanup to five seconds, with bounded forced browser termination. The owned Playwright browser server adds a local WebSocket command hop; in-page timing clocks are unchanged. + +Scenarios (`perf/scenarios.ts`): `typing`, `typingLarge`, `typingAngular`, `completion`, `consoleOutput`, `terminalTui`, `keyRepeat`, `scroll`, `gitLog`, `gitLogScrollbar`, `resizePanels`, `startup`, `tabs`, `agentTabs`, `popups`, `toolWindows`, `projectTree`, `leaks`. Bundle size (`bundle.initialJsKb`, `bundle.initialCssKb`) is checked except with `--unminified`. Latencies are measured from input to the start of the first frame that shows the result, so about 16.7 ms means "next frame". @@ -42,9 +48,17 @@ Latencies are measured from input to the start of the first frame that shows the A scenario in `perf/scenarios.ts` has an `id`, a `title` and a `run(h)` that drives the page through the harness (`perf/lib/harness.ts`: open files, set the cursor, type and measure, read editor state) and returns metrics. Add a budget for each metric you want enforced as `"."` in `budgets.json`. +### Current-operation checks + +An already-visible result is not evidence that the measured action worked. Interaction waits require a current input and the requested state transition; file opening checks the active full path, typing checks the resulting text/caret and key-sample count, and scroll/completion navigation checks its destination. + +Code-intelligence evals also wait for successful action completion. Rename correctness uses the current matching request only: multi-file previews validate proposed edits, while applied local renames validate the edited document. Incomplete answers are degraded results. Clean-file diagnostics require a fresh backend publication for that document, including an explicitly empty publication; a quiet empty UI alone cannot pass. + +Diagnostics acknowledgements match the path, backend source and local opening token. Backend publications carry no document version, so a delayed same-path publication after reopening cannot be distinguished from a newly computed one. + ## Backend: `pnpm perf:rust` -`perf/rust.ts` runs `cargo bench` for `ide-text`, `ide-language`, `ide-index`, `ide-search` and `ide-host`, reads the Criterion results from `target/criterion`, and checks each bench's mean (in µs). +`perf/rust.ts` runs `cargo bench` for `ide-text`, `ide-language`, `ide-index`, `ide-search`, `ide-host` and `ide-heap`, reads the Criterion results, and checks each bench's mean (in µs). ```sh pnpm perf:rust # run the benches, then check @@ -62,6 +76,22 @@ The benches live in `crates//benches/`: | `search_5k/…` | `ide-search` | literal, regex and dense-match search over 5k files | | `plugins/…` | `ide-host` | loading 50 plugins, cold activation, syntax highlights of a 2k-line file | +Expected IDs and package ownership are declared independently of collected artifacts in `perf/lib/rust.ts`. A selected package must produce every expected ID, including observe-only measurements. `--package` scopes both collection and required budgets, also with `--no-run`; unknown packages fail before Cargo starts. + +Six IDs are observe-only (required finite measurements, without an absolute budget): `syntax_2mb/outline_uncached`, `syntax_2mb/folding_uncached`, `index_100k/find_files/zzzz`, `index_100k/find_symbols/renderView`, `startup_20k/reopen_wait_idle`, and `search_excluded_subtrees/5k_dependencies`. New IDs need an explicit budget or observe-only classification. + +Normal runs write isolated `/runs/run-*/criterion` artifacts, a `run.json` manifest and Cargo logs. `CRITERION_HOME` and `CARGO_TARGET_DIR` are passed consistently to Cargo. Both artifact files must fall within the recorded run window; future timestamps fail. `--no-run` inspects the newest recorded run covering the selected packages, retaining original artifact dates and any recorded failure; pre-manifest output is explicitly labelled legacy inspection, not current execution. + +Cargo has a 60-minute deadline including cold compilation (`PERF_RUST_TIMEOUT_MS` overrides milliseconds), followed by bounded process-tree termination. Cargo, artifact and manifest failures write fresh `report-rust.json` and Markdown with partial evidence. + +## Code intelligence: `pnpm eval` + +Use `pnpm eval --list` for scenario IDs and supported conditions. `--only` accepts comma-separated IDs or dot-prefix groups; every entry must match executable work. `--condition` accepts only `warm` or `cold`, and a selection incompatible with that condition is rejected before building or launching. Repetition counts follow the UI runner's integer requirements. + +The selected scenario/condition plan defines the required outcomes independently of collected results. Missing, duplicate or unexpected outcomes fail; an empty workload cannot pass. Required timing and correctness metrics must be present and finite, rather than silently skipped by the judge. + +Raw attempts, warmups, results and partial timeout timings remain in `target/eval/report.json`; invalid trials cannot disappear into an otherwise valid median. Startup/build failures also produce a fresh failing report. Session startup, fixture setup and each trial have five-minute wall-clock bounds; renderer measurements additionally have a Node deadline one second beyond their configured timeout. Server initialization is limited to 30 seconds, individual stdio requests to five minutes, release compilation to 60 minutes. Cleanup errors fail the run. + ## Budgets and baselines [`perf/budgets.json`](https://github.com/l0ng-ai/openidea/blob/main/perf/budgets.json) holds upper bounds (lower is better): @@ -92,4 +122,6 @@ python perf/compare/bench.py ~/src/some-project --runs 5 --wipe-caches # cold Each run launches the app on the project, waits until it is ready (the process tree's CPU stays low after the window and the log markers appear), idles, closes it, and records time to window and to ready, peak and idle memory summed over every process the app started (webview, language servers, JVMs), CPU time, exit time and cache size. Apps run interleaved after warmup runs; output goes to `results/