| 220 | } |
| 221 | |
| 222 | fn complete_prompt(&self, word: &str) -> Result<Vec<String>, ReadlineError> { |
| 223 | let sender = &self.sender; |
| 224 | let receiver = self.receiver.borrow_mut(); |
| 225 | let query = PromptQuery::Search(if !word.is_empty() { Some(word.to_string()) } else { None }); |
| 226 | |
| 227 | sender |
| 228 | .send(query) |
| 229 | .map_err(|e| ReadlineError::Io(std::io::Error::other(e.to_string())))?; |
| 230 | // We only want stuff from the current tail end onward |
| 231 | let mut new_receiver = receiver.resubscribe(); |
| 232 | |
| 233 | // Here we poll on the receiver for [max_attempts] number of times. |
| 234 | // The reason for this is because we are trying to receive something managed by an async |
| 235 | // channel from a sync context. |
| 236 | // If we ever switch back to a single threaded runtime for whatever reason, this function |
| 237 | // will not panic but nothing will be fetched because the thread that is doing |
| 238 | // try_recv is also the thread that is supposed to be doing the sending. |
| 239 | let mut attempts = 0; |
| 240 | let max_attempts = 5; |
| 241 | let query_res = loop { |
| 242 | match new_receiver.try_recv() { |
| 243 | Ok(result) => break result, |
| 244 | Err(_e) if attempts < max_attempts - 1 => { |
| 245 | attempts += 1; |
| 246 | std::thread::sleep(std::time::Duration::from_millis(100)); |
| 247 | }, |
| 248 | Err(e) => { |
| 249 | return Err(ReadlineError::Io(std::io::Error::other(eyre::eyre!( |
| 250 | "Failed to receive prompt info from complete prompt after {} attempts: {:?}", |
| 251 | max_attempts, |
| 252 | e |
| 253 | )))); |
| 254 | }, |
| 255 | } |
| 256 | }; |
| 257 | let matches = match query_res { |
| 258 | PromptQueryResult::Search(list) => list.into_iter().map(|n| format!("@{n}")).collect::<Vec<_>>(), |
| 259 | PromptQueryResult::List(_) => { |
| 260 | return Err(ReadlineError::Io(std::io::Error::other(eyre::eyre!( |
| 261 | "Wrong query response type received", |
| 262 | )))); |
| 263 | }, |
| 264 | }; |
| 265 | |
| 266 | Ok(matches) |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | pub struct ChatCompleter { |