| 1 | use codewhale_engine::conversation_modes::{ |
| 2 | self, CREATOR, ConversationMode, ConversationModeTable, STANDARD, |
| 3 | }; |
| 4 | use codewhale_engine::extension_host::ExtensionHostOptions; |
| 5 | use codewhale_localization::{Locale, MessageId, tr}; |
| 6 | use codewhale_runtime::config::Config; |
| 7 | |
| 8 | const LABEL_CHARS: usize = 40; |
| 9 | |
| 10 | pub(crate) fn options(config: &Config) -> ExtensionHostOptions { |
| 11 | ExtensionHostOptions::from_config(config.extension_host.as_ref()) |
| 12 | } |
| 13 | |
| 14 | pub(crate) async fn current_table(config: &Config) -> ConversationModeTable { |
| 15 | let plugin_creator_enabled = config |
| 16 | .features() |
| 17 | .enabled(codewhale_runtime::features::Feature::PluginCreator); |
| 18 | conversation_modes::current_table(options(config), plugin_creator_enabled).await |
| 19 | } |
| 20 | |
| 21 | pub(crate) fn current_table_blocking(config: Option<&Config>) -> ConversationModeTable { |
| 22 | let options = config.map_or_else(ExtensionHostOptions::default, options); |
| 23 | let plugin_creator_enabled = config.map_or_else( |
| 24 | || { |
| 25 | codewhale_runtime::features::Features::with_defaults() |
| 26 | .enabled(codewhale_runtime::features::Feature::PluginCreator) |
| 27 | }, |
| 28 | |config| { |
| 29 | config |
| 30 | .features() |
| 31 | .enabled(codewhale_runtime::features::Feature::PluginCreator) |
| 32 | }, |
| 33 | ); |
| 34 | let future = conversation_modes::current_table(options, plugin_creator_enabled); |
| 35 | match tokio::runtime::Handle::try_current() { |
| 36 | Ok(handle) if handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread => { |
| 37 | tokio::task::block_in_place(|| handle.block_on(future)) |
| 38 | } |
| 39 | _ => std::thread::scope(|scope| { |
| 40 | scope |
| 41 | .spawn(|| { |
| 42 | tokio::runtime::Builder::new_current_thread() |
| 43 | .enable_all() |
| 44 | .build() |
| 45 | .expect("conversation mode runtime") |
| 46 | .block_on(future) |
| 47 | }) |
| 48 | .join() |
| 49 | .expect("conversation mode probe") |
| 50 | }), |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | pub(crate) fn display_name(locale: Locale, mode: &ConversationMode) -> String { |
| 55 | match mode.id.as_str() { |
| 56 | STANDARD => tr(locale, MessageId::ConversationModeStandardName).into_owned(), |
| 57 | CREATOR => tr(locale, MessageId::ConversationModeCreatorName).into_owned(), |
| 58 | _ => mode.name.clone(), |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | pub(crate) fn display_description(locale: Locale, mode: &ConversationMode) -> String { |
| 63 | match mode.id.as_str() { |
| 64 | STANDARD => tr(locale, MessageId::ConversationModeStandardDescription).into_owned(), |
| 65 | CREATOR => tr(locale, MessageId::ConversationModeCreatorDescription).into_owned(), |
| 66 | _ => mode.description.clone(), |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | pub(crate) fn display_reason(locale: Locale, reason: Option<&str>) -> String { |
| 71 | match reason.map(str::trim).filter(|reason| !reason.is_empty()) { |
| 72 | Some(reason) => reason.to_string(), |
| 73 | None => tr(locale, MessageId::ConversationModeUnavailableDefault).into_owned(), |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | fn clean(text: &str) -> String { |
| 78 | let mut out: String = text |
| 79 | .chars() |
| 80 | .filter(|c| { |
| 81 | !c.is_control() |
| 82 | && !matches!(*c, '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' | '\u{FEFF}') |
| 83 | }) |
| 84 | .take(LABEL_CHARS + 1) |
| 85 | .collect(); |
| 86 | if out.chars().count() > LABEL_CHARS { |
| 87 | out = out.chars().take(LABEL_CHARS).collect::<String>() + "…"; |
| 88 | } |
| 89 | out |
| 90 | } |
| 91 | |
| 92 | pub(crate) fn name_for_stored( |
| 93 | locale: Locale, |
| 94 | stored: Option<&str>, |
| 95 | table: Option<&ConversationModeTable>, |
| 96 | ) -> String { |
| 97 | let id = conversation_modes::effective_id(stored); |
| 98 | match table.and_then(|table| table.modes.iter().find(|mode| mode.id == id)) { |
| 99 | Some(mode) => display_name(locale, mode), |
| 100 | None if id == STANDARD => tr(locale, MessageId::ConversationModeStandardName).into_owned(), |
| 101 | None if id == CREATOR => tr(locale, MessageId::ConversationModeCreatorName).into_owned(), |
| 102 | None => clean(id), |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | pub(crate) fn unavailable_reason( |
| 107 | stored: Option<&str>, |
| 108 | table: &ConversationModeTable, |
| 109 | locale: Locale, |
| 110 | ) -> Option<String> { |
| 111 | let id = conversation_modes::effective_id(stored); |
| 112 | match table.modes.iter().find(|mode| mode.id == id) { |
| 113 | Some(mode) => (!mode.available).then(|| display_reason(locale, mode.reason.as_deref())), |
| 114 | None => Some( |
| 115 | tr(locale, MessageId::ConversationModeUnknown) |
| 116 | .replace("{id}", &clean(id)) |
| 117 | .replace( |
| 118 | "{modes}", |
| 119 | &table |
| 120 | .modes |
| 121 | .iter() |
| 122 | .map(|mode| mode.id.as_str()) |
| 123 | .collect::<Vec<_>>() |
| 124 | .join(", "), |
| 125 | ), |
| 126 | ), |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | pub(crate) fn label( |
| 131 | locale: Locale, |
| 132 | stored: Option<&str>, |
| 133 | unavailable: Option<&str>, |
| 134 | table: Option<&ConversationModeTable>, |
| 135 | ) -> Option<String> { |
| 136 | stored?; |
| 137 | let name = name_for_stored(locale, stored, table); |
| 138 | Some(if unavailable.is_some() { |
| 139 | tr(locale, MessageId::ConversationModeLabelUnavailable).replace("{name}", &name) |
| 140 | } else { |
| 141 | name |
| 142 | }) |
| 143 | } |
| 144 | |
| 145 | pub(crate) fn new_command(id: &str) -> String { |
| 146 | if id == STANDARD { |
| 147 | "/new".to_string() |
| 148 | } else { |
| 149 | format!("/new {id}") |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | pub(crate) fn locked_refusal(locale: Locale, requested_id: &str) -> String { |
| 154 | tr(locale, MessageId::ConversationModeLockedRefusal) |
| 155 | .replace("{command}", &format!("`{}`", new_command(requested_id))) |
| 156 | } |
| 157 | |
| 158 | pub(crate) enum Resolution { |
| 159 | Unknown(String), |
| 160 | Unavailable { |
| 161 | name: String, |
| 162 | reason: String, |
| 163 | }, |
| 164 | Ready { |
| 165 | stored: Option<String>, |
| 166 | name: String, |
| 167 | }, |
| 168 | } |
| 169 | |
| 170 | pub(crate) fn resolve(locale: Locale, table: &ConversationModeTable, id: &str) -> Resolution { |
| 171 | let id = id.trim().to_ascii_lowercase(); |
| 172 | let id = id.as_str(); |
| 173 | match table.modes.iter().find(|mode| mode.id == id) { |
| 174 | None => Resolution::Unknown( |
| 175 | tr(locale, MessageId::ConversationModeUnknown) |
| 176 | .replace("{id}", &clean(id)) |
| 177 | .replace( |
| 178 | "{modes}", |
| 179 | &table |
| 180 | .modes |
| 181 | .iter() |
| 182 | .map(|mode| mode.id.as_str()) |
| 183 | .collect::<Vec<_>>() |
| 184 | .join(", "), |
| 185 | ), |
| 186 | ), |
| 187 | Some(mode) if !mode.available => Resolution::Unavailable { |
| 188 | name: display_name(locale, mode), |
| 189 | reason: display_reason(locale, mode.reason.as_deref()), |
| 190 | }, |
| 191 | Some(mode) => Resolution::Ready { |
| 192 | stored: conversation_modes::stored_form(&mode.id), |
| 193 | name: display_name(locale, mode), |
| 194 | }, |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | pub(crate) fn unavailable_message(locale: Locale, name: &str, reason: &str) -> String { |
| 199 | tr(locale, MessageId::ConversationModeUnavailableRefusal) |
| 200 | .replace("{name}", name) |
| 201 | .replace("{reason}", reason) |
| 202 | } |
| 203 | |
| 204 | pub(crate) fn saved_unavailable_notice(locale: Locale, name: &str, reason: &str) -> String { |
| 205 | tr(locale, MessageId::ConversationModeSavedUnavailableNotice) |
| 206 | .replace("{name}", name) |
| 207 | .replace("{reason}", reason) |
| 208 | } |
| 209 | |
| 210 | pub(crate) async fn set_in_place( |
| 211 | app: &mut crate::tui::app::App, |
| 212 | config: &Config, |
| 213 | engine: &codewhale_engine::core::engine::EngineHandle, |
| 214 | id: &str, |
| 215 | ) -> Result<String, String> { |
| 216 | let locale = app.ui_locale; |
| 217 | let table = current_table(config).await; |
| 218 | match resolve(locale, &table, id) { |
| 219 | Resolution::Unknown(message) => Err(message), |
| 220 | Resolution::Unavailable { name, reason } => { |
| 221 | Err(unavailable_message(locale, &name, &reason)) |
| 222 | } |
| 223 | Resolution::Ready { stored, name } => { |
| 224 | let done = tr(locale, MessageId::ConversationModeSet).replace("{name}", &name); |
| 225 | if stored == app.conversation_mode { |
| 226 | return Ok(done); |
| 227 | } |
| 228 | if app.conversation_mode_locked() { |
| 229 | return Err(locked_refusal(locale, id.trim())); |
| 230 | } |
| 231 | let previous = app.conversation_mode.clone(); |
| 232 | let previous_unavailable = app.conversation_mode_unavailable.clone(); |
| 233 | app.install_conversation_mode(stored, None); |
| 234 | let synced = engine |
| 235 | .send(codewhale_engine::core::ops::Op::SyncSession { |
| 236 | expected: None, |
| 237 | control: app.session_sync_control(), |
| 238 | session_id: app.current_session_id.clone(), |
| 239 | messages: app.api_messages.as_ref().clone(), |
| 240 | system_prompt: app.system_prompt.clone(), |
| 241 | system_prompt_override: false, |
| 242 | model: app.model.clone(), |
| 243 | workspace: app.workspace.clone(), |
| 244 | mode: app.mode, |
| 245 | agent_preset: app.agent_preset(), |
| 246 | }) |
| 247 | .await; |
| 248 | if let Err(error) = synced { |
| 249 | tracing::warn!(%error, "conversation mode session sync failed"); |
| 250 | app.install_conversation_mode(previous, previous_unavailable); |
| 251 | return Err(tr(locale, MessageId::ConversationModeSyncFailed).into_owned()); |
| 252 | } |
| 253 | Ok(done) |
| 254 | } |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | pub(crate) async fn launch_conversation_mode( |
| 259 | config: &Config, |
| 260 | locale: Locale, |
| 261 | flag: Option<&str>, |
| 262 | resumed: Option<&codewhale_engine::session_manager::SavedSession>, |
| 263 | ) -> Result<Option<String>, String> { |
| 264 | let Some(id) = flag.map(str::trim) else { |
| 265 | return Ok(None); |
| 266 | }; |
| 267 | if let Some(saved) = resumed { |
| 268 | let requested = conversation_modes::stored_form(&id.to_ascii_lowercase()); |
| 269 | return if requested == saved.agent_preset { |
| 270 | Ok(requested) |
| 271 | } else { |
| 272 | Err(locked_refusal(locale, id)) |
| 273 | }; |
| 274 | } |
| 275 | let table = current_table(config).await; |
| 276 | match resolve(locale, &table, id) { |
| 277 | Resolution::Unknown(message) => Err(message), |
| 278 | Resolution::Unavailable { name, reason } => { |
| 279 | Err(unavailable_message(locale, &name, &reason)) |
| 280 | } |
| 281 | Resolution::Ready { stored, .. } => Ok(stored), |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | pub(crate) fn load_saved_for_resume( |
| 286 | locale: Locale, |
| 287 | selector: &str, |
| 288 | workspace: &std::path::Path, |
| 289 | ) -> Result<codewhale_engine::session_manager::SavedSession, String> { |
| 290 | codewhale_engine::session_manager::SessionManager::default_location() |
| 291 | .ok() |
| 292 | .and_then(|manager| { |
| 293 | if selector == "latest" { |
| 294 | let id = manager |
| 295 | .get_latest_session_for_workspace(workspace) |
| 296 | .ok() |
| 297 | .flatten()? |
| 298 | .id; |
| 299 | manager.load_session(&id).ok() |
| 300 | } else { |
| 301 | manager.load_session_by_prefix(selector).ok() |
| 302 | } |
| 303 | }) |
| 304 | .ok_or_else(|| tr(locale, MessageId::ConversationModeResumeUnreadable).into_owned()) |
| 305 | } |
| 306 | |
| 307 | #[cfg(test)] |
| 308 | mod tests { |
| 309 | use super::*; |
| 310 | |
| 311 | fn table_with_unavailable(reason: Option<String>) -> ConversationModeTable { |
| 312 | ConversationModeTable { |
| 313 | default: STANDARD, |
| 314 | modes: vec![ConversationMode { |
| 315 | id: "unavailable-id".to_string(), |
| 316 | name: "Unavailable".to_string(), |
| 317 | description: "Unavailable test mode".to_string(), |
| 318 | source: "builtin", |
| 319 | available: false, |
| 320 | reason, |
| 321 | }], |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | #[test] |
| 326 | fn display_reason_localizes_missing_or_blank_reason() { |
| 327 | let expected = tr( |
| 328 | Locale::ZhHans, |
| 329 | MessageId::ConversationModeUnavailableDefault, |
| 330 | ); |
| 331 | for raw in [None, Some(""), Some(" ")] { |
| 332 | let reason = display_reason(Locale::ZhHans, raw); |
| 333 | assert_eq!(reason, expected.as_ref()); |
| 334 | assert!(!reason.contains("This mode is unavailable.")); |
| 335 | assert!(!reason.contains("unavailable")); |
| 336 | } |
| 337 | assert_eq!( |
| 338 | display_reason(Locale::ZhHans, Some("custom extension reason")), |
| 339 | "custom extension reason" |
| 340 | ); |
| 341 | } |
| 342 | |
| 343 | #[test] |
| 344 | fn resolve_and_unavailable_reason_localize_default_reason() { |
| 345 | let table = table_with_unavailable(None); |
| 346 | let expected = tr( |
| 347 | Locale::ZhHans, |
| 348 | MessageId::ConversationModeUnavailableDefault, |
| 349 | ); |
| 350 | |
| 351 | let Resolution::Unavailable { reason, .. } = |
| 352 | resolve(Locale::ZhHans, &table, "unavailable-id") |
| 353 | else { |
| 354 | panic!("expected Resolution::Unavailable"); |
| 355 | }; |
| 356 | assert_eq!(reason, expected.as_ref()); |
| 357 | assert!(!reason.contains("This mode is unavailable.")); |
| 358 | |
| 359 | let fallback = unavailable_reason(Some("unavailable-id"), &table, Locale::ZhHans) |
| 360 | .expect("unavailable reason"); |
| 361 | assert_eq!(fallback, expected.as_ref()); |
| 362 | assert!(!fallback.contains("unavailable")); |
| 363 | } |
| 364 | } |
| 365 |