Replace the three error styles with one Error type and one Result alias in error.rs. The error crosses IPC as the same plain string as before. The message text does not change. Move the shared file mechanics to fsutil.rs. These are the reserved-name check, the link and junction check, the limited reads, and the atomic writes. Each module keeps its own path rules, limits, and messages. The plugin settings writer now flushes its file to disk before the rename. Remove the current_root_path and list_entries wrappers and an unused mime value. Use named windows-sys constants for the process, file, drive, and error codes. Add a test that compares the command lists in lib.rs, build.rs, and the capability files. The settings capability must be a subset of the full list. In Cargo.toml, set the author, keep only the rlib crate type, and remove the unused thiserror dependency. Remove panic = "abort" from the release profile. A panic on a worker thread then stops only that thread. It does not stop the editor with unsaved buffers.
84 lines
4.9 KiB
Rust
84 lines
4.9 KiB
Rust
use std::{collections::HashMap, io::{BufRead, BufReader}, sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}}, time::Duration};
|
|
use reqwest::{blocking::Client, Url};
|
|
use serde::Deserialize;
|
|
use tauri::{ipc::Channel, State, WebviewWindow};
|
|
|
|
use crate::error::Result;
|
|
|
|
#[derive(Default)]
|
|
pub struct CompletionState { requests: Mutex<HashMap<String, Arc<AtomicBool>>> }
|
|
impl CompletionState {
|
|
pub fn close_window(&self, window: &str) {
|
|
if let Ok(mut requests) = self.requests.lock() {
|
|
requests.retain(|key, flag| { if key.starts_with(&format!("{window}:")) { flag.store(true, Ordering::Relaxed); false } else { true } });
|
|
}
|
|
}
|
|
}
|
|
#[derive(Deserialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct CompletionRequest { endpoint: String, route: String, body: Option<String>, timeout_ms: Option<u64> }
|
|
fn target(endpoint: &str, route: &str) -> Result<Url> {
|
|
let mut url = Url::parse(endpoint).map_err(|_| "Enter a local server URL.")?;
|
|
if !matches!(url.scheme(), "http" | "https") || !matches!(url.host_str(), Some("127.0.0.1" | "[::1]" | "localhost"))
|
|
|| !url.username().is_empty() || url.password().is_some() || url.query().is_some() || url.fragment().is_some()
|
|
|| !matches!(url.path(), "" | "/" | "/v1" | "/v1/") {
|
|
return Err("This trial connects only to a loopback model server.".into());
|
|
}
|
|
if !matches!(route, "/v1/models" | "/v1/chat/completions" | "/api/tags" | "/api/generate") { return Err("Unsupported completion route.".into()); }
|
|
if url.host_str() == Some("localhost") { url.set_host(Some("127.0.0.1")).map_err(|_| "Invalid local host.")?; }
|
|
url.set_path(route); Ok(url)
|
|
}
|
|
#[tauri::command]
|
|
pub fn completion_cancel(window: WebviewWindow, state: State<'_, CompletionState>, id: String) {
|
|
if let Ok(requests) = state.requests.lock() { if let Some(flag) = requests.get(&format!("{}:{id}", window.label())) { flag.store(true, Ordering::Relaxed); } }
|
|
}
|
|
#[tauri::command]
|
|
pub async fn completion_request(window: WebviewWindow, state: State<'_, CompletionState>, id: String, request: CompletionRequest, on_line: Channel<String>) -> Result<()> {
|
|
if id.len() > 80 || request.body.as_ref().is_some_and(|v| v.len() > 32768) { return Err("Completion request is too large.".into()); }
|
|
let url = target(&request.endpoint, &request.route)?;
|
|
let flag = Arc::new(AtomicBool::new(false));
|
|
let key = format!("{}:{id}", window.label());
|
|
{
|
|
let mut requests = state.requests.lock().map_err(|_| "Completion state is unavailable.")?;
|
|
if requests.len() >= 16 { return Err("The local server is busy. Wait before retrying.".into()); }
|
|
requests.insert(key.clone(), flag.clone());
|
|
}
|
|
let result = tauri::async_runtime::spawn_blocking(move || -> Result<()> {
|
|
let client = Client::builder().no_proxy().redirect(reqwest::redirect::Policy::none())
|
|
.connect_timeout(Duration::from_secs(2)).timeout(Duration::from_millis(request.timeout_ms.unwrap_or(5000).clamp(100, 15000)))
|
|
.build().map_err(|_| "Could not create a local connection.")?;
|
|
if flag.load(Ordering::Relaxed) { return Ok(()); }
|
|
let call = if let Some(body) = request.body { client.post(url).header("Content-Type", "application/json").body(body) } else { client.get(url) };
|
|
let response = call.send().map_err(|e| if e.is_timeout() { "The local model timed out." } else { "Cannot connect to the local model server." })?;
|
|
if !response.status().is_success() { return Err(format!("Local server returned HTTP {}.", response.status().as_u16()).into()); }
|
|
let mut reader = BufReader::new(response);
|
|
let mut total = 0;
|
|
loop {
|
|
if flag.load(Ordering::Relaxed) { return Ok(()); }
|
|
let mut bytes = Vec::new();
|
|
let count = std::io::Read::take(&mut reader, 65537).read_until(b'\n', &mut bytes).map_err(|_| "The local response ended unexpectedly.")?;
|
|
if count == 0 { break; }
|
|
total += count;
|
|
if count > 65536 || total > 262144 { return Err("Local response exceeded the size limit.".into()); }
|
|
if flag.load(Ordering::Relaxed) { return Ok(()); }
|
|
let line = String::from_utf8(bytes).map_err(|_| "Local response is not UTF-8.")?;
|
|
if on_line.send(line).is_err() { break; }
|
|
}
|
|
Ok(())
|
|
}).await.map_err(|_| "Local completion task stopped.");
|
|
if let Ok(mut requests) = state.requests.lock() { requests.remove(&key); }
|
|
result?
|
|
}
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
#[test]
|
|
fn only_loopback_and_fixed_routes() {
|
|
assert_eq!(target("http://localhost:8080/v1", "/v1/models").unwrap().as_str(), "http://127.0.0.1:8080/v1/models");
|
|
for address in ["https://example.com", "http://127.0.0.1.example.com", "http://user@localhost", "file:///a", "http://localhost/?key=x", "http://localhost/path"] {
|
|
assert!(target(address, "/v1/models").is_err(), "{address}");
|
|
}
|
|
assert!(target("http://127.0.0.1:8080", "/shutdown").is_err());
|
|
}
|
|
}
|