Файли
openidea/plugins/official/ai-completion/src/lib.rs
T
LU XIANGRUIтаwildcatDownstairs 7fef1e10a8 fix(ai-completion): say why no suggestions appear and let the model be chosen (#6936)
The plugin's optional net:localhost permission is not ticked by default, and a missing Ollama model answers 404; both only reached the IDE log. Failed requests now show one warning that says why and what to do, and a new AI Completion: Set Model command (Set Endpoint URL also asks for its value from the palette). The host answers an empty list instead of "no server supports inline completion" when a plugin offers ghost text, so the editor keeps asking while typing.

Fixes #6930

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 18:03:40 +08:00

355 рядки
16 KiB
Rust
Неформатований Анотація Історія

Цей файл містить неоднозначні символи Юнікоду
Цей файл містить символи Юнікоду, які можна сплутати з іншими символами. Якщо ви вважаєте, що це зроблено навмисно, можете сміливо ігнорувати це попередження. Щоб показати їх, скористайтеся кнопкою Escape.
//! AI Completion for OpenIDEA: inline suggestions from an OpenAI-compatible
//! `/v1/completions` endpoint (fill-in-the-middle with `prompt` + `suffix`).
//! The IDE cancels a request as soon as the user types on (the fetch returns
//! `Cancelled`); the API key is filled in by the IDE (`{{secret:api-key}}`)
//! and never seen here.
use openidea_plugin::host::{self, storage};
use openidea_plugin::providers::{Document, InlineSuggestion, Providers};
use openidea_plugin::text::offset;
use openidea_plugin::{Error, HttpRequest, Invocation, LogLevel, NotificationLevel, Plugin, Position, register_plugin};
use serde_json::{Value, json};
const LOCAL: &str = "http://localhost:11434";
const OPENAI: &str = "https://api.openai.com";
const LOCAL_MODEL: &str = "qwen2.5-coder:1.5b";
const OPENAI_MODEL: &str = "gpt-3.5-turbo-instruct";
/// Context sent around the caret.
const PREFIX_CHARS: usize = 3000;
const SUFFIX_CHARS: usize = 1000;
#[derive(Default)]
pub struct AiCompletion {
/// Why the last request failed, so it is logged once rather than per keystroke.
last_error: Option<String>,
/// The last failure shown to the user, so a notice is not repeated.
last_notice: Option<String>,
}
struct Config {
endpoint: String,
model: String,
openai: bool,
enabled: bool,
}
/// Whether `endpoint` is OpenAI's API host itself, so the key may go to it:
/// `https`, exactly `api.openai.com` (or `:443`), and no `user@` before the host
/// (`https://api.openai.com@localhost` is localhost).
pub fn is_openai(endpoint: &str) -> bool {
let Some(rest) = endpoint.strip_prefix("https://") else { return false };
let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
matches!(authority, "api.openai.com" | "api.openai.com:443")
}
fn config() -> Config {
let get = |k: &str| storage::get(k).ok().flatten();
let endpoint = get("endpoint").unwrap_or_else(|| LOCAL.into());
let openai = is_openai(&endpoint);
let model = get("model").unwrap_or_else(|| (if openai { OPENAI_MODEL } else { LOCAL_MODEL }).into());
Config { endpoint, model, openai, enabled: get("enabled").as_deref() != Some("false") }
}
/// What to tell the user about a failed request: why, and what to do.
pub fn advice(endpoint: &str, model: &str, openai: bool, failure: &Result<String, Error>) -> String {
match failure {
Err(Error::Denied(_)) => format!(
"AI Completion may not connect to {endpoint}. Allow its network access in Settings › Plugins › AI Completion."
),
Ok(text) if !openai && text.starts_with("HTTP 404") => format!(
"The model {model} is not available at {endpoint}. Run `ollama pull {model}`, or choose an installed model with AI Completion: Set Model."
),
Err(Error::Failed(e)) if e.contains("timed out") => format!(
"{endpoint} took too long to answer; the model may still be loading, or be too large for this machine."
),
Err(Error::Failed(e)) if !openai => format!("Could not reach Ollama at {endpoint} ({e}). Is it running?"),
Ok(text) => format!("{endpoint} answered {text}"),
Err(e) => format!("Could not reach {endpoint}: {e}"),
}
}
/// The command's argument, or what the user types (pre-filled with `current`);
/// `None` when dismissed.
fn arg_or_input(arg: Option<&str>, prompt: &str, current: &str) -> Result<Option<String>, Error> {
let value = match arg {
Some(a) => Some(a.to_owned()),
None => host::input(prompt, Some(current))?,
};
Ok(value.map(|v| v.trim().to_owned()).filter(|v| !v.is_empty()))
}
/// The last `max` characters of `s` (on a char boundary).
fn tail(s: &str, max: usize) -> &str {
match s.char_indices().rev().nth(max.saturating_sub(1)) {
Some((i, _)) if s.chars().count() > max => &s[i..],
_ => s,
}
}
fn head(s: &str, max: usize) -> &str {
s.char_indices().nth(max).map_or(s, |(i, _)| &s[..i])
}
/// The request body for the text around `at`, or `None` when there is
/// nothing to complete (in the middle of a word).
pub fn request_body(doc: &Document, at: Position, model: &str) -> Option<String> {
let at = offset(&doc.text, at)?;
let (before, after) = doc.text.split_at(at);
// Only at the end of a line or before closing punctuation.
let rest_of_line = after.split('\n').next().unwrap_or("");
if !rest_of_line.trim().chars().all(|c| ")]}>;,'\"`".contains(c)) {
return None;
}
let body = json!({
"model": model,
"prompt": tail(before, PREFIX_CHARS),
"suffix": head(after, SUFFIX_CHARS),
"max_tokens": 64,
"temperature": 0,
"stop": ["\n\n"],
});
Some(body.to_string())
}
/// The suggestion in a `/v1/completions` response.
pub fn suggestion(response: &str) -> Option<String> {
let v: Value = serde_json::from_str(response).ok()?;
let text = v["choices"][0]["text"].as_str()?.trim_end().to_owned();
(!text.trim().is_empty()).then_some(text)
}
impl Providers for AiCompletion {
fn inline_completion(&mut self, doc: &Document, at: Position) -> Option<InlineSuggestion> {
let c = config();
if !c.enabled {
return None;
}
let body = request_body(doc, at, &c.model)?;
let mut req = HttpRequest::post(&format!("{}/v1/completions", c.endpoint.trim_end_matches('/')), body)
.header("Content-Type", "application/json");
if c.openai {
if !host::secret_is_set("api-key") {
return None;
}
req = req.header("Authorization", "Bearer {{secret:api-key}}");
}
req.timeout_ms = Some(10_000);
match host::fetch(&req) {
Ok(r) if r.status == 200 => {
self.last_error = None;
suggestion(&r.text()).map(|insert_text| InlineSuggestion { insert_text, replace: None })
}
// Superseded by the next keystroke: nothing to report.
Err(Error::Cancelled) => None,
other => {
let failure = other.map(|r| format!("HTTP {}: {}", r.status, head(&r.text(), 200)));
let msg = match &failure {
Ok(m) => m.clone(),
Err(e) => e.to_string(),
};
if self.last_error.as_ref() != Some(&msg) {
host::log(LogLevel::Warn, &format!("{}: {msg}", c.endpoint));
self.last_error = Some(msg);
}
// Otherwise a failure only shows in the IDE log, where nobody looks.
let notice = advice(&c.endpoint, &c.model, c.openai, &failure);
if self.last_notice.as_ref() != Some(&notice) {
host::notify(NotificationLevel::Warning, "AI Completion", &notice);
self.last_notice = Some(notice);
}
None
}
}
}
}
impl Plugin for AiCompletion {
fn run_command(&mut self, id: &str, _ctx: &Invocation, arg: Option<&str>) -> Result<Option<String>, Error> {
let msg = match id {
"use-local" => {
storage::set("endpoint", LOCAL)?;
storage::delete("model")?;
format!("Using the local model {LOCAL_MODEL} (Ollama at {LOCAL}).")
}
"use-openai" => {
storage::set("endpoint", OPENAI)?;
storage::delete("model")?;
if host::secret_is_set("api-key") {
format!("Using OpenAI ({OPENAI_MODEL}).")
} else {
"Using OpenAI: store your API key in Settings › Plugins › AI Completion.".into()
}
}
"set-endpoint" => {
let Some(url) = arg_or_input(arg, "Endpoint URL (e.g. http://localhost:11434)", &config().endpoint)?
else {
return Ok(None);
};
if !(url.starts_with("http://") || url.starts_with("https://")) {
return Err("give the endpoint URL, e.g. http://localhost:11434".into());
}
storage::set("endpoint", &url)?;
format!("Using {url}.")
}
"set-model" => {
let Some(model) = arg_or_input(arg, "Model (as `ollama list` shows it)", &config().model)? else {
return Ok(None);
};
storage::set("model", &model)?;
format!("Using the model {model}.")
}
"toggle" => {
let enabled = !config().enabled;
storage::set("enabled", if enabled { "true" } else { "false" })?;
(if enabled { "AI Completion is on." } else { "AI Completion is off." }).into()
}
_ => return Err(Error::NotFound(format!("command {id}"))),
};
// A new setting may fix (or change) the failure: tell again.
self.last_notice = None;
host::notify(NotificationLevel::Info, "AI Completion", &msg);
Ok(Some(msg))
}
}
register_plugin!(AiCompletion, providers);
#[cfg(test)]
mod tests {
use super::*;
use openidea_plugin::HttpResponse;
use openidea_plugin::mock::MockHost;
fn doc(text: &str) -> Document {
Document { path: "/p/a.rs".into(), language: "rust".into(), version: 1, text: text.into() }
}
#[test]
fn asks_with_prefix_and_suffix_and_returns_the_text() {
let host = MockHost::install().with_capabilities(&["storage", "net:localhost"]);
host.on_fetch(|r| {
let body: Value = serde_json::from_slice(r.body.as_ref().unwrap()).unwrap();
assert_eq!(body["prompt"], "fn add(a: i32, b: i32) -> i32 {\n ");
assert_eq!(body["suffix"], "\n}\n");
Ok(HttpResponse { status: 200, headers: vec![], body: br#"{"choices":[{"text":"a + b\n"}]}"#.to_vec() })
});
let s = AiCompletion::default()
.inline_completion(&doc("fn add(a: i32, b: i32) -> i32 {\n \n}\n"), Position::new(1, 4))
.unwrap();
assert_eq!(s.insert_text, "a + b");
assert_eq!(host.requests()[0].url, "http://localhost:11434/v1/completions");
}
#[test]
fn openai_uses_the_secret_and_only_when_set() {
let host = MockHost::install().with_capabilities(&["storage", "net:api.openai.com", "secrets"]);
host.on_fetch(|_| {
Ok(HttpResponse { status: 200, headers: vec![], body: br#"{"choices":[{"text":"x"}]}"#.to_vec() })
});
let mut p = AiCompletion::default();
p.run_command("use-openai", &host.invocation(), None).unwrap();
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none(), "no key yet");
host.set_secret("api-key", "sk-test");
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_some());
let sent = &host.requests()[0];
assert!(sent.headers.contains(&("Authorization".into(), "Bearer sk-test".into())));
}
#[test]
fn the_key_goes_to_openai_only() {
assert!(is_openai(OPENAI));
assert!(is_openai("https://api.openai.com/"));
assert!(is_openai("https://api.openai.com:443/v1"));
for other in [
"https://api.openai.com@localhost:9999",
"https://api.openai.com:x@localhost",
"https://api.openai.com.example.com",
"https://api.openai.com\\@localhost",
"http://api.openai.com",
"http://localhost:11434",
] {
assert!(!is_openai(other), "{other}");
}
let host = MockHost::install().with_capabilities(&["storage"]);
AiCompletion::default()
.run_command("set-endpoint", &host.invocation(), Some("https://api.openai.com@localhost:9999"))
.unwrap();
assert!(!config().openai, "no key for a look-alike endpoint");
}
#[test]
fn quiet_when_cancelled_or_mid_word() {
let host = MockHost::install().with_capabilities(&["storage"]);
let mut p = AiCompletion::default();
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none(), "net denied");
assert!(request_body(&doc("let abc = d;"), Position::new(0, 5), "m").is_none(), "mid-word");
assert!(request_body(&doc("call(x)"), Position::new(0, 6), "m").is_some(), "before `)`");
let host2 = MockHost::install().with_capabilities(&["storage", "net:localhost"]);
host2.on_fetch(|_| Err(Error::Cancelled));
assert!(p.inline_completion(&doc("x"), Position::new(0, 1)).is_none());
assert!(host2.logs().is_empty(), "a cancelled request is not an error");
drop(host);
p.run_command("toggle", &host2.invocation(), None).unwrap();
assert!(p.inline_completion(&doc("x"), Position::new(0, 1)).is_none());
assert_eq!(host2.requests().len(), 1, "disabled: no request");
}
#[test]
fn tells_the_user_why_once_and_what_to_do() {
// Installed without the optional network permission (the default for it).
let host = MockHost::install().with_capabilities(&["storage"]);
let mut p = AiCompletion::default();
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none());
assert!(p.inline_completion(&doc("let x = 1"), Position::new(0, 9)).is_none());
let notes = host.notifications();
assert_eq!(notes.len(), 1, "once, not per keystroke: {notes:?}");
assert!(notes[0].body.contains("Settings › Plugins › AI Completion"), "{}", notes[0].body);
// A model that is not pulled: Ollama answers 404.
let host = MockHost::install().with_capabilities(&["storage", "net:localhost"]);
host.on_fetch(|_| {
Ok(HttpResponse {
status: 404,
headers: vec![],
body: br#"{"error":{"message":"model \"qwen2.5-coder:1.5b\" not found, try pulling it first"}}"#
.to_vec(),
})
});
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none());
let body = &host.notifications()[0].body;
assert!(body.contains("ollama pull qwen2.5-coder:1.5b") && body.contains("Set Model"), "{body}");
// Ollama not running.
host.on_fetch(|_| Err(Error::Failed("connection refused".into())));
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none());
assert!(host.notifications()[1].body.contains("Is it running?"));
host.on_fetch(|_| Err(Error::Failed("error sending request: operation timed out".into())));
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none());
assert!(host.notifications()[2].body.contains("took too long"));
}
#[test]
fn set_model_takes_an_argument_or_asks() {
let host = MockHost::install().with_capabilities(&["storage", "net:localhost"]);
host.on_fetch(|_| {
Ok(HttpResponse { status: 200, headers: vec![], body: br#"{"choices":[{"text":"x"}]}"#.to_vec() })
});
let mut p = AiCompletion::default();
p.run_command("set-model", &host.invocation(), Some(" qwen2.5-coder:7b ")).unwrap();
assert_eq!(config().model, "qwen2.5-coder:7b");
// From the command palette: no argument, so it asks.
host.answer_next_prompt(Some(&["codellama:7b-code"]));
p.run_command("set-model", &host.invocation(), None).unwrap();
p.inline_completion(&doc("let x = "), Position::new(0, 8)).unwrap();
let body: Value = serde_json::from_slice(host.requests()[0].body.as_ref().unwrap()).unwrap();
assert_eq!(body["model"], "codellama:7b-code");
// Dismissed: nothing changes.
assert_eq!(p.run_command("set-model", &host.invocation(), None).unwrap(), None);
assert_eq!(config().model, "codellama:7b-code");
host.answer_next_prompt(Some(&["http://127.0.0.1:11434"]));
p.run_command("set-endpoint", &host.invocation(), None).unwrap();
assert_eq!(config().endpoint, "http://127.0.0.1:11434");
}
}