mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-25 03:25:56 +00:00
Discover Playerbot Characters models from the provider
This commit is contained in:
1 parent
206d4844c9
commit
6f1eaac719
13 files changed
+633
-32
No files matched your search
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: modules
|
||||
type: added
|
||||
audience: admins
|
||||
title: Choose Playerbot Characters models from a live provider list
|
||||
---
|
||||
Search the models available from your configured provider and refresh the list when models change. Custom endpoints can still use a model ID entered manually.
|
||||
@@ -7,6 +7,8 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::{Error, Result, fsx};
|
||||
|
||||
pub mod models;
|
||||
|
||||
const MODULE: &str = "mod-pbc";
|
||||
const PATH_SETTING: &str = "PBC.DefaultConnection";
|
||||
const CONNECTION_FILE: &str = "Extras/PlayerbotCharacters/manager-connection.jsonc";
|
||||
@@ -99,38 +101,56 @@ pub fn load(root: &Path) -> Result<Setup> {
|
||||
Ok(Setup { active, connection })
|
||||
}
|
||||
|
||||
pub fn save(root: &Path, meta: &Path, update: ConnectionUpdate) -> Result<Setup> {
|
||||
let active = module_setting(root)?.trim_matches('"') == CONNECTION_SETTING;
|
||||
let base_url = update.base_url.trim().trim_end_matches('/');
|
||||
let url = reqwest::Url::parse(base_url).map_err(|_| Error::Invalid("Enter a valid model API base URL.".into()))?;
|
||||
fn connection_url(base_url: &str) -> Result<reqwest::Url> {
|
||||
let url = reqwest::Url::parse(base_url.trim().trim_end_matches('/'))
|
||||
.map_err(|_| Error::Invalid("Enter a valid model API base URL.".into()))?;
|
||||
if !matches!(url.scheme(), "http" | "https") || url.host().is_none()
|
||||
|| !url.username().is_empty() || url.password().is_some() || url.query().is_some() || url.fragment().is_some()
|
||||
{
|
||||
return Err(Error::Invalid("Use an HTTP or HTTPS base URL without credentials, a query, or a fragment.".into()));
|
||||
}
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
fn connection_key(
|
||||
api_type: ApiType,
|
||||
base_url: &str,
|
||||
submitted_key: Option<&str>,
|
||||
remove_key: bool,
|
||||
previous: Option<Connection>,
|
||||
) -> Result<String> {
|
||||
let submitted_key = submitted_key.map(str::trim).filter(|value| !value.is_empty());
|
||||
if submitted_key.is_some_and(|value| value.chars().any(char::is_control)) {
|
||||
return Err(Error::Invalid("Enter the API key on a single line.".into()));
|
||||
}
|
||||
|
||||
let key = if remove_key {
|
||||
String::new()
|
||||
} else if let Some(key) = submitted_key {
|
||||
key.to_owned()
|
||||
} else {
|
||||
previous
|
||||
.filter(|old| old.api_type == api_type && old.base_url == base_url)
|
||||
.map(|old| old.api_key)
|
||||
.unwrap_or_default()
|
||||
};
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
pub fn save(root: &Path, meta: &Path, update: ConnectionUpdate) -> Result<Setup> {
|
||||
let active = module_setting(root)?.trim_matches('"') == CONNECTION_SETTING;
|
||||
let url = connection_url(&update.base_url)?;
|
||||
let base_url = url.as_str().trim_end_matches('/');
|
||||
let model = update.model.trim();
|
||||
if model.is_empty() || model.chars().any(char::is_control) {
|
||||
return Err(Error::Invalid("Enter a model name on a single line.".into()));
|
||||
}
|
||||
let submitted_key = update.api_key.as_deref().map(str::trim).filter(|value| !value.is_empty());
|
||||
if submitted_key.is_some_and(|value| value.chars().any(char::is_control)) {
|
||||
return Err(Error::Invalid("Enter the API key on a single line.".into()));
|
||||
}
|
||||
|
||||
let path = connection_path(root)?;
|
||||
let previous = read_connection(&path)?;
|
||||
let previous_connection = previous.as_deref().map(parse).transpose()?;
|
||||
let key = if update.remove_key {
|
||||
String::new()
|
||||
} else if let Some(key) = submitted_key {
|
||||
key.to_owned()
|
||||
} else {
|
||||
previous_connection
|
||||
.filter(|old| old.api_type == update.api_type && old.base_url == base_url)
|
||||
.map(|old| old.api_key)
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let key = connection_key(
|
||||
update.api_type, base_url, update.api_key.as_deref(), update.remove_key,
|
||||
previous.as_deref().map(parse).transpose()?,
|
||||
)?;
|
||||
let connection = Connection {
|
||||
api_type: update.api_type,
|
||||
base_url: base_url.into(),
|
||||
|
||||
@@ -0,0 +1,313 @@
|
||||
//! Read-only model discovery for the endpoint being edited in the Manager.
|
||||
use reqwest::blocking::Client;
|
||||
use reqwest::header::{self, HeaderMap, HeaderValue};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
use super::{connection_key, connection_path, connection_url, module_setting, parse, read_connection, ApiType};
|
||||
|
||||
const TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const MAX_PAGE_BYTES: u64 = 4 * 1024 * 1024;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Request {
|
||||
pub api_type: ApiType,
|
||||
pub base_url: String,
|
||||
pub api_key: Option<String>,
|
||||
pub remove_key: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct Model {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct CatalogPage {
|
||||
data: Vec<ApiModel>,
|
||||
#[serde(default)]
|
||||
has_more: bool,
|
||||
last_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ApiModel {
|
||||
id: String,
|
||||
display_name: Option<String>,
|
||||
name: Option<String>,
|
||||
lifecycle: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct OllamaList {
|
||||
models: Vec<OllamaModel>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct OllamaModel {
|
||||
model: Option<String>,
|
||||
name: Option<String>,
|
||||
}
|
||||
|
||||
fn request_headers(api_type: ApiType, key: &str) -> Result<HeaderMap> {
|
||||
let mut headers = HeaderMap::new();
|
||||
if api_type == ApiType::Anthropic {
|
||||
// Match the Claude API version and credential format used for dialogue in mod-pbc.
|
||||
headers.insert("anthropic-version", HeaderValue::from_static("2023-06-01"));
|
||||
headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json"));
|
||||
}
|
||||
if !key.is_empty() {
|
||||
let (name, value) = if api_type == ApiType::Anthropic {
|
||||
(header::HeaderName::from_static("x-api-key"), key.to_owned())
|
||||
} else {
|
||||
(header::AUTHORIZATION, format!("Bearer {key}"))
|
||||
};
|
||||
let mut value = HeaderValue::from_str(&value)
|
||||
.map_err(|_| Error::Invalid("The API key contains unsupported characters.".into()))?;
|
||||
value.set_sensitive(true);
|
||||
headers.insert(name, value);
|
||||
}
|
||||
Ok(headers)
|
||||
}
|
||||
|
||||
pub fn list(root: &Path, request: Request) -> Result<Vec<Model>> {
|
||||
module_setting(root)?;
|
||||
let mut url = connection_url(&request.base_url)?;
|
||||
let previous = read_connection(&connection_path(root)?)?;
|
||||
let key = connection_key(
|
||||
request.api_type, url.as_str().trim_end_matches('/'), request.api_key.as_deref(),
|
||||
request.remove_key, previous.as_deref().map(parse).transpose()?,
|
||||
)?;
|
||||
let mut path = url.path_segments_mut()
|
||||
.map_err(|_| Error::Invalid("Enter a valid model API base URL.".into()))?;
|
||||
path.pop_if_empty();
|
||||
if request.api_type == ApiType::Ollama {
|
||||
path.extend(["api", "tags"]);
|
||||
} else {
|
||||
path.push("models");
|
||||
}
|
||||
drop(path);
|
||||
let headers = request_headers(request.api_type, &key)?;
|
||||
let client = Client::builder()
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.build()
|
||||
.map_err(|_| Error::Invalid("Could not start the model list request.".into()))?;
|
||||
|
||||
let deadline = Instant::now() + TIMEOUT;
|
||||
let mut models = BTreeMap::new();
|
||||
let mut cursor = None::<String>;
|
||||
let mut seen_cursors = HashSet::new();
|
||||
loop {
|
||||
let mut page_url = url.clone();
|
||||
if let Some(cursor) = &cursor {
|
||||
page_url.query_pairs_mut().append_pair("after_id", cursor);
|
||||
}
|
||||
let remaining = deadline.saturating_duration_since(Instant::now());
|
||||
if remaining.is_zero() {
|
||||
return Err(Error::Invalid("The model list request timed out.".into()));
|
||||
}
|
||||
let response = client.get(page_url).headers(headers.clone()).timeout(remaining).send()
|
||||
.map_err(|error| Error::Invalid(if error.is_timeout() {
|
||||
"The model list request timed out."
|
||||
} else {
|
||||
"Could not reach the model endpoint."
|
||||
}.into()))?;
|
||||
let status = response.status();
|
||||
if !status.is_success() {
|
||||
return Err(Error::Invalid(format!("The provider returned HTTP {status} for its model list.")));
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
response.take(MAX_PAGE_BYTES + 1).read_to_end(&mut body)
|
||||
.map_err(|_| Error::Invalid("Could not read the provider's model list.".into()))?;
|
||||
if body.len() as u64 > MAX_PAGE_BYTES {
|
||||
return Err(Error::Invalid("The provider returned an oversized model list.".into()));
|
||||
}
|
||||
let invalid_list = |_| Error::Invalid("The endpoint did not return a model list.".into());
|
||||
if request.api_type == ApiType::Ollama {
|
||||
let list: OllamaList = serde_json::from_slice(&body).map_err(invalid_list)?;
|
||||
for model in list.models {
|
||||
if let Some(id) = present(model.model).or_else(|| present(model.name)) {
|
||||
models.insert(id.clone(), id);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
let page: CatalogPage = serde_json::from_slice(&body).map_err(invalid_list)?;
|
||||
for model in page.data {
|
||||
if model.lifecycle.as_deref() == Some("retired") || model.id.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let name = present(model.display_name).or_else(|| present(model.name))
|
||||
.unwrap_or_else(|| model.id.clone());
|
||||
models.insert(model.id, name);
|
||||
}
|
||||
if !page.has_more {
|
||||
break;
|
||||
}
|
||||
cursor = page.last_id.filter(|value| !value.is_empty() && seen_cursors.insert(value.clone()));
|
||||
if cursor.is_none() {
|
||||
return Err(Error::Invalid("The provider returned an invalid model list cursor.".into()));
|
||||
}
|
||||
}
|
||||
|
||||
let mut choices: Vec<_> = models.into_iter().map(|(id, name)| Model { id, name }).collect();
|
||||
choices.sort_by_cached_key(|model| model.name.to_lowercase());
|
||||
Ok(choices)
|
||||
}
|
||||
|
||||
fn present(value: Option<String>) -> Option<String> {
|
||||
value.filter(|text| !text.trim().is_empty())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::modules::pbc::{self, ConnectionUpdate};
|
||||
use std::fs;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::TcpListener;
|
||||
use std::thread::{self, JoinHandle};
|
||||
|
||||
fn server(pages: Vec<(&'static str, &'static str, &'static str)>) -> (String, JoinHandle<Vec<String>>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
let worker = thread::spawn(move || {
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
pages.into_iter().map(|(status, headers, body)| {
|
||||
let mut socket = loop {
|
||||
match listener.accept() {
|
||||
Ok((socket, _)) => break socket,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock && Instant::now() < deadline => {
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
Err(error) => panic!("Mock model endpoint did not receive its request: {error}"),
|
||||
}
|
||||
};
|
||||
socket.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
|
||||
let mut request = String::new();
|
||||
let mut reader = BufReader::new(&socket);
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
if reader.read_line(&mut line).unwrap() == 0 || line == "\r\n" {
|
||||
break;
|
||||
}
|
||||
request.push_str(&line.to_ascii_lowercase());
|
||||
}
|
||||
write!(socket, "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n{headers}\r\n{body}", body.len()).unwrap();
|
||||
request
|
||||
}).collect()
|
||||
});
|
||||
(format!("http://127.0.0.1:{port}"), worker)
|
||||
}
|
||||
|
||||
fn install() -> tempfile::TempDir {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let configs = root.path().join("Core/configs/modules");
|
||||
fs::create_dir_all(&configs).unwrap();
|
||||
fs::write(configs.join("playerbots_characters.conf.dist"),
|
||||
"[worldserver]\nPBC.Enable = 0\nPBC.DefaultConnection = ../connection.jsonc\n").unwrap();
|
||||
root
|
||||
}
|
||||
|
||||
fn request(api_type: ApiType, base_url: &str, api_key: Option<&str>) -> Request {
|
||||
Request { api_type, base_url: base_url.into(), api_key: api_key.map(str::to_owned), remove_key: false }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openai_compatible_lists_current_models_and_reuses_the_matching_saved_key() {
|
||||
let root = install();
|
||||
let (endpoint, requests) = server(vec![
|
||||
("200 OK", "", r#"{"data":[{"id":"model-a"}]}"#),
|
||||
("200 OK", "", r#"{"data":[{"id":"model-b","name":"New Model"},{"id":"model-b","name":"New Model"}]}"#),
|
||||
]);
|
||||
let base = format!("{endpoint}/proxy/v1");
|
||||
pbc::save(root.path(), &root.path().join("metadata"), ConnectionUpdate {
|
||||
api_type: ApiType::Openai, base_url: base.clone(), model: "saved-model".into(),
|
||||
api_key: Some("fixture-secret".into()), remove_key: false,
|
||||
}).unwrap();
|
||||
let path = connection_path(root.path()).unwrap();
|
||||
let saved = fs::read(&path).unwrap();
|
||||
|
||||
let models = list(root.path(), request(ApiType::Openai, &base, None)).unwrap();
|
||||
assert_eq!(models.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["model-a"]);
|
||||
let refreshed = list(root.path(), request(ApiType::Openai, &base, Some("new-draft-key"))).unwrap();
|
||||
assert_eq!(refreshed.len(), 1);
|
||||
assert_eq!((&*refreshed[0].id, &*refreshed[0].name), ("model-b", "New Model"));
|
||||
assert_eq!(fs::read(path).unwrap(), saved);
|
||||
let requests = requests.join().unwrap();
|
||||
assert!(requests.iter().all(|r| r.starts_with("get /proxy/v1/models ")));
|
||||
assert!(requests[0].contains("authorization: bearer fixture-secret\r\n"));
|
||||
assert!(requests[1].contains("authorization: bearer new-draft-key\r\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ollama_lists_installed_models_without_reusing_a_key_for_another_endpoint() {
|
||||
let root = install();
|
||||
pbc::save(root.path(), &root.path().join("metadata"), ConnectionUpdate {
|
||||
api_type: ApiType::Ollama, base_url: "http://127.0.0.1:11434".into(), model: "saved-model".into(),
|
||||
api_key: Some("fixture-secret".into()), remove_key: false,
|
||||
}).unwrap();
|
||||
let (endpoint, requests) = server(vec![
|
||||
("200 OK", "", r#"{"models":[{"model":"qwen:7b","name":"alternate"},{"name":"gemma:4b"}]}"#),
|
||||
]);
|
||||
let models = list(root.path(), request(ApiType::Ollama, &endpoint, None)).unwrap();
|
||||
assert_eq!(models.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["gemma:4b", "qwen:7b"]);
|
||||
let requests = requests.join().unwrap();
|
||||
assert!(requests[0].starts_with("get /api/tags "));
|
||||
assert!(!requests[0].contains("authorization:"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anthropic_follows_cursors_and_keeps_display_names_and_exact_ids() {
|
||||
let root = install();
|
||||
let (endpoint, requests) = server(vec![
|
||||
("200 OK", "", r#"{"data":[{"id":"claude-sonnet-test","display_name":"Claude Sonnet Test"}],"has_more":true,"last_id":"opaque/page+1"}"#),
|
||||
("200 OK", "", r#"{"data":[{"id":"claude-haiku-test","display_name":"Claude Haiku Test"},{"id":"retired-test","lifecycle":"retired"}],"has_more":false}"#),
|
||||
]);
|
||||
let models = list(root.path(), request(ApiType::Anthropic, &format!("{endpoint}/v1"), Some("fixture-key"))).unwrap();
|
||||
assert_eq!(models.iter().map(|m| (&*m.id, &*m.name)).collect::<Vec<_>>(), [
|
||||
("claude-haiku-test", "Claude Haiku Test"), ("claude-sonnet-test", "Claude Sonnet Test"),
|
||||
]);
|
||||
let requests = requests.join().unwrap();
|
||||
assert!(requests[0].starts_with("get /v1/models "));
|
||||
assert!(requests[1].starts_with("get /v1/models?after_id=opaque%2fpage%2b1 "));
|
||||
for request in requests {
|
||||
assert!(request.contains("anthropic-version: 2023-06-01\r\n"));
|
||||
assert!(request.contains("x-api-key: fixture-key\r\n"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redirects_and_http_errors_keep_the_connection_file_and_do_not_expose_the_key() {
|
||||
let root = install();
|
||||
let (endpoint, requests) = server(vec![
|
||||
("302 Found", "Location: http://127.0.0.1:1/models\r\n", ""),
|
||||
("401 Unauthorized", "", "fixture-secret"),
|
||||
]);
|
||||
pbc::save(root.path(), &root.path().join("metadata"), ConnectionUpdate {
|
||||
api_type: ApiType::Openai, base_url: endpoint.clone(), model: "saved-model".into(),
|
||||
api_key: Some("fixture-secret".into()), remove_key: false,
|
||||
}).unwrap();
|
||||
let path = connection_path(root.path()).unwrap();
|
||||
let saved = fs::read(&path).unwrap();
|
||||
let redirect = list(root.path(), request(ApiType::Openai, &endpoint, None)).err().unwrap();
|
||||
assert!(redirect.to_string().contains("302"));
|
||||
let mut no_auth = request(ApiType::Openai, &endpoint, None);
|
||||
no_auth.remove_key = true;
|
||||
let unauthorized = list(root.path(), no_auth).err().unwrap();
|
||||
assert!(unauthorized.to_string().contains("401"));
|
||||
assert!(!unauthorized.to_string().contains("fixture-secret"));
|
||||
let requests = requests.join().unwrap();
|
||||
assert!(requests[0].contains("authorization: bearer fixture-secret"));
|
||||
assert!(!requests[1].contains("authorization:"));
|
||||
assert_eq!(fs::read(path).unwrap(), saved);
|
||||
}
|
||||
}
|
||||
@@ -1719,6 +1719,16 @@ async fn pbc_connection(
|
||||
blocking(move || coa_core::modules::pbc::load(&root)).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn pbc_list_models(
|
||||
state: State<'_, AppState>,
|
||||
id: String,
|
||||
request: coa_core::modules::pbc::models::Request,
|
||||
) -> std::result::Result<Vec<coa_core::modules::pbc::models::Model>, UiError> {
|
||||
let root = path_of(&state, &id)?;
|
||||
blocking(move || coa_core::modules::pbc::models::list(&root, request)).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn pbc_save_connection(
|
||||
state: State<'_, AppState>,
|
||||
@@ -3242,6 +3252,7 @@ pub fn run() {
|
||||
module_set_enabled,
|
||||
module_settings,
|
||||
pbc_connection,
|
||||
pbc_list_models,
|
||||
pbc_save_connection,
|
||||
module_save_settings,
|
||||
all_settings,
|
||||
|
||||
@@ -844,6 +844,16 @@ const de: Partial<Record<keyof typeof en, string>> = {
|
||||
"mod.restart": "Änderungen werden nach einem Neustart des Weltservers wirksam.",
|
||||
"mod.switch": "{name} ein- oder ausschalten",
|
||||
"mod.notHere": "Nicht Teil dieses Servers",
|
||||
"mod.pbc.chooseModel": "Modell auswählen",
|
||||
"mod.pbc.searchModels": "Modelle suchen",
|
||||
"mod.pbc.manualModel": "Modell-ID manuell eingeben",
|
||||
"mod.pbc.browseModels": "Modelle durchsuchen",
|
||||
"mod.pbc.refreshModels": "Modelle aktualisieren",
|
||||
"mod.pbc.loadingModels": "Modelle werden geladen…",
|
||||
"mod.pbc.modelListFailed": "Modelle konnten nicht geladen werden. Prüfe den Endpunkt und den API-Schlüssel oder gib eine Modell-ID ein.",
|
||||
"mod.pbc.noModels": "Keine Modelle gefunden.",
|
||||
"mod.pbc.modelListNeedsUrl": "Gib die API-Basis-URL ein, um Modelle zu laden.",
|
||||
"mod.pbc.modelListNeedsKey": "Gib einen API-Schlüssel ein, um Modelle zu laden.",
|
||||
"mod.github": "GitHub",
|
||||
"mod.pbc.connection": "Modellverbindung",
|
||||
"mod.pbc.provider": "Modellanbieter",
|
||||
|
||||
@@ -890,6 +890,16 @@ const en = {
|
||||
"mod.restart": "Changes apply after the world server restarts.",
|
||||
"mod.switch": "Turn {name} on or off",
|
||||
"mod.notHere": "Not part of this server",
|
||||
"mod.pbc.chooseModel": "Choose a model",
|
||||
"mod.pbc.searchModels": "Search models",
|
||||
"mod.pbc.manualModel": "Enter model ID manually",
|
||||
"mod.pbc.browseModels": "Browse models",
|
||||
"mod.pbc.refreshModels": "Refresh models",
|
||||
"mod.pbc.loadingModels": "Loading models…",
|
||||
"mod.pbc.modelListFailed": "Couldn’t load models. Check the endpoint and API key, or enter a model ID manually.",
|
||||
"mod.pbc.noModels": "No models found.",
|
||||
"mod.pbc.modelListNeedsUrl": "Enter the API base URL to load models.",
|
||||
"mod.pbc.modelListNeedsKey": "Enter an API key to load models.",
|
||||
"mod.github": "GitHub",
|
||||
"mod.pbc.connection": "Model connection",
|
||||
"mod.pbc.provider": "Model provider",
|
||||
|
||||
@@ -844,6 +844,16 @@ const es: Partial<Record<keyof typeof en, string>> = {
|
||||
"mod.restart": "Los cambios se aplican al reiniciar el servidor del mundo.",
|
||||
"mod.switch": "Activar o desactivar {name}",
|
||||
"mod.notHere": "No forma parte de este servidor",
|
||||
"mod.pbc.chooseModel": "Elegir un modelo",
|
||||
"mod.pbc.searchModels": "Buscar modelos",
|
||||
"mod.pbc.manualModel": "Introducir el ID del modelo manualmente",
|
||||
"mod.pbc.browseModels": "Explorar modelos",
|
||||
"mod.pbc.refreshModels": "Actualizar modelos",
|
||||
"mod.pbc.loadingModels": "Cargando modelos…",
|
||||
"mod.pbc.modelListFailed": "No se pudieron cargar los modelos. Revisa el endpoint y la clave de API o introduce el ID del modelo manualmente.",
|
||||
"mod.pbc.noModels": "No se encontraron modelos.",
|
||||
"mod.pbc.modelListNeedsUrl": "Introduce la URL base de la API para cargar los modelos.",
|
||||
"mod.pbc.modelListNeedsKey": "Introduce una clave de API para cargar los modelos.",
|
||||
"mod.github": "GitHub",
|
||||
"mod.pbc.connection": "Conexión con el modelo",
|
||||
"mod.pbc.provider": "Proveedor del modelo",
|
||||
|
||||
@@ -844,6 +844,16 @@ const fr: Partial<Record<keyof typeof en, string>> = {
|
||||
"mod.restart": "Les changements s’appliquent après le redémarrage du serveur de monde.",
|
||||
"mod.switch": "Activer ou désactiver {name}",
|
||||
"mod.notHere": "Ne fait pas partie de ce serveur",
|
||||
"mod.pbc.chooseModel": "Choisir un modèle",
|
||||
"mod.pbc.searchModels": "Rechercher des modèles",
|
||||
"mod.pbc.manualModel": "Saisir l’identifiant du modèle",
|
||||
"mod.pbc.browseModels": "Parcourir les modèles",
|
||||
"mod.pbc.refreshModels": "Actualiser les modèles",
|
||||
"mod.pbc.loadingModels": "Chargement des modèles…",
|
||||
"mod.pbc.modelListFailed": "Impossible de charger les modèles. Vérifiez le point d’accès et la clé API, ou saisissez l’identifiant du modèle.",
|
||||
"mod.pbc.noModels": "Aucun modèle trouvé.",
|
||||
"mod.pbc.modelListNeedsUrl": "Saisissez l’URL de base de l’API pour charger les modèles.",
|
||||
"mod.pbc.modelListNeedsKey": "Saisissez une clé API pour charger les modèles.",
|
||||
"mod.github": "GitHub",
|
||||
"mod.pbc.connection": "Connexion au modèle",
|
||||
"mod.pbc.provider": "Fournisseur du modèle",
|
||||
|
||||
@@ -873,6 +873,16 @@ const ru: Partial<Record<keyof typeof en, string>> = {
|
||||
"mod.restart": "Изменения применятся после перезапуска игрового сервера.",
|
||||
"mod.switch": "Включить или выключить {name}",
|
||||
"mod.notHere": "Нет в этом сервере",
|
||||
"mod.pbc.chooseModel": "Выбрать модель",
|
||||
"mod.pbc.searchModels": "Поиск моделей",
|
||||
"mod.pbc.manualModel": "Ввести ID модели вручную",
|
||||
"mod.pbc.browseModels": "Список моделей",
|
||||
"mod.pbc.refreshModels": "Обновить список моделей",
|
||||
"mod.pbc.loadingModels": "Загрузка моделей…",
|
||||
"mod.pbc.modelListFailed": "Не удалось загрузить модели. Проверьте адрес и ключ API или введите ID модели вручную.",
|
||||
"mod.pbc.noModels": "Модели не найдены.",
|
||||
"mod.pbc.modelListNeedsUrl": "Введите базовый URL API для загрузки моделей.",
|
||||
"mod.pbc.modelListNeedsKey": "Введите ключ API для загрузки моделей.",
|
||||
"mod.github": "GitHub",
|
||||
"mod.pbc.connection": "Подключение к модели",
|
||||
"mod.pbc.provider": "Провайдер модели",
|
||||
|
||||
@@ -844,6 +844,16 @@ const zh = {
|
||||
"mod.restart": "更改将在世界服务器重启后生效。",
|
||||
"mod.switch": "开启或关闭 {name}",
|
||||
"mod.notHere": "未包含在当前服务器中",
|
||||
"mod.pbc.chooseModel": "选择模型",
|
||||
"mod.pbc.searchModels": "搜索模型",
|
||||
"mod.pbc.manualModel": "手动输入模型 ID",
|
||||
"mod.pbc.browseModels": "浏览模型",
|
||||
"mod.pbc.refreshModels": "刷新模型列表",
|
||||
"mod.pbc.loadingModels": "正在加载模型…",
|
||||
"mod.pbc.modelListFailed": "无法加载模型。请检查端点和 API 密钥,或手动输入模型 ID。",
|
||||
"mod.pbc.noModels": "未找到模型。",
|
||||
"mod.pbc.modelListNeedsUrl": "请输入 API 基础网址以加载模型。",
|
||||
"mod.pbc.modelListNeedsKey": "请输入 API 密钥以加载模型。",
|
||||
"mod.github": "GitHub 页面",
|
||||
"mod.pbc.connection": "模型连接",
|
||||
"mod.pbc.provider": "模型服务商",
|
||||
|
||||
@@ -244,6 +244,11 @@ export interface PbcConnectionUpdate extends PbcConnection {
|
||||
removeKey: boolean;
|
||||
}
|
||||
|
||||
export interface PbcModel {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface ModuleView {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -561,6 +566,7 @@ export const api = {
|
||||
realmlistActivate: (id: string, profileId: string) => invoke<string[]>("realmlist_activate", { id, profileId }),
|
||||
modulesList: (id: string) => invoke<ModuleView[]>("modules_list", { id }),
|
||||
pbcConnection: (id: string) => invoke<PbcConnectionSetup>("pbc_connection", { id }),
|
||||
pbcListModels: (id: string, request: Omit<PbcConnectionUpdate, "model">) => invoke<PbcModel[]>("pbc_list_models", { id, request }),
|
||||
pbcSaveConnection: (id: string, update: PbcConnectionUpdate) => invoke<PbcConnectionSetup>("pbc_save_connection", { id, update }),
|
||||
moduleSetEnabled: (id: string, module: string, enabled: boolean) => invoke<void>("module_set_enabled", { id, module, enabled }),
|
||||
moduleSettings: (id: string, module: string) => invoke<ModuleSetting[]>("module_settings", { id, module }),
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useHuman, useI18n } from "@/i18n";
|
||||
import { api, asUiError, type PbcConnection, type PbcConnectionSetup, type UiError } from "@/lib/api";
|
||||
import type { UnsavedChangesGuard } from "@/lib/unsavedGuard";
|
||||
import { PbcModelPicker, type ModelCatalog } from "@/screens/PbcModelPicker";
|
||||
|
||||
type Provider = "openai" | "ollama" | "anthropic" | "compatible";
|
||||
const presets: Record<Provider, PbcConnection> = {
|
||||
openai: { apiType: "openai", baseUrl: "https://api.openai.com/v1", model: "gpt-5.4-mini" },
|
||||
openai: { apiType: "openai", baseUrl: "https://api.openai.com/v1", model: "" },
|
||||
ollama: { apiType: "ollama", baseUrl: "http://127.0.0.1:11434", model: "" },
|
||||
anthropic: { apiType: "anthropic", baseUrl: "https://api.anthropic.com/v1", model: "" },
|
||||
compatible: { apiType: "openai", baseUrl: "", model: "" },
|
||||
@@ -30,6 +31,13 @@ export function PbcConnectionSettings({ serverId, onSaved, onRegisterGuard }: {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<UiError | null>(null);
|
||||
const [saved, setSaved] = useState(false);
|
||||
const [catalog, setCatalog] = useState<ModelCatalog>({ status: "idle", models: [] });
|
||||
const requestId = useRef(0);
|
||||
|
||||
const clearCatalog = useCallback(() => {
|
||||
requestId.current++;
|
||||
setCatalog({ status: "idle", models: [] });
|
||||
}, []);
|
||||
|
||||
const reset = useCallback((value: PbcConnectionSetup) => {
|
||||
const current = value.connection ?? presets.openai;
|
||||
@@ -37,20 +45,22 @@ export function PbcConnectionSettings({ serverId, onSaved, onRegisterGuard }: {
|
||||
setProvider(providerOf(current));
|
||||
setApiKey("");
|
||||
setRemoveKey(false);
|
||||
}, []);
|
||||
clearCatalog();
|
||||
}, [clearCatalog]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
setSetup(null);
|
||||
setSaved(false);
|
||||
setError(null);
|
||||
clearCatalog();
|
||||
void api.pbcConnection(serverId).then(value => {
|
||||
if (cancelled) return;
|
||||
setSetup(value);
|
||||
reset(value);
|
||||
}).catch(e => { if (!cancelled) setError(asUiError(e)); });
|
||||
return () => { cancelled = true; };
|
||||
}, [serverId, reset]);
|
||||
return () => { cancelled = true; requestId.current++; };
|
||||
}, [serverId, reset, clearCatalog]);
|
||||
|
||||
const previous = setup?.connection ?? presets.openai;
|
||||
const dirty = !!setup && (connection.apiType !== previous.apiType || connection.baseUrl !== previous.baseUrl
|
||||
@@ -59,6 +69,25 @@ export function PbcConnectionSettings({ serverId, onSaved, onRegisterGuard }: {
|
||||
&& connection.baseUrl.trim().replace(/\/+$/, "") === previous.baseUrl;
|
||||
const hasKey = !!setup?.connection?.hasKey && sameEndpoint;
|
||||
const valid = !!connection.baseUrl.trim() && !!connection.model.trim();
|
||||
const needsKey = provider === "openai"
|
||||
|| (provider === "anthropic" && connection.baseUrl.trim().replace(/\/+$/, "") === presets.anthropic.baseUrl);
|
||||
const discoveryBlocked = !connection.baseUrl.trim() ? t("mod.pbc.modelListNeedsUrl")
|
||||
: needsKey && !apiKey.trim() && !(hasKey && !removeKey) ? t("mod.pbc.modelListNeedsKey")
|
||||
: undefined;
|
||||
|
||||
async function loadModels(refresh: boolean) {
|
||||
if (discoveryBlocked || catalog.status === "loading" || (!refresh && catalog.status !== "idle")) return;
|
||||
const current = ++requestId.current;
|
||||
setCatalog(previous => ({ ...previous, status: "loading" }));
|
||||
try {
|
||||
const models = await api.pbcListModels(serverId, {
|
||||
apiType: connection.apiType, baseUrl: connection.baseUrl, apiKey: apiKey || undefined, removeKey,
|
||||
});
|
||||
if (current === requestId.current) setCatalog({ status: "ready", models });
|
||||
} catch {
|
||||
if (current === requestId.current) setCatalog(previous => ({ ...previous, status: "error" }));
|
||||
}
|
||||
}
|
||||
|
||||
const save = useCallback(async () => {
|
||||
if (!setup || !valid || busy) return false;
|
||||
@@ -92,6 +121,7 @@ export function PbcConnectionSettings({ serverId, onSaved, onRegisterGuard }: {
|
||||
setApiKey("");
|
||||
setRemoveKey(false);
|
||||
setSaved(false);
|
||||
clearCatalog();
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -111,25 +141,23 @@ export function PbcConnectionSettings({ serverId, onSaved, onRegisterGuard }: {
|
||||
<option value="compatible">{t("mod.pbc.compatible")}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="space-y-1 text-sm">
|
||||
<span>{t("mod.pbc.model")}</span>
|
||||
<input className={inputClass} value={connection.model} required onChange={event => { setConnection({ ...connection, model: event.target.value }); setSaved(false); }} />
|
||||
</label>
|
||||
<label className="space-y-1 text-sm sm:col-span-2">
|
||||
<span>{t("mod.pbc.endpoint")}</span>
|
||||
<input className={inputClass} value={connection.baseUrl} type="url" required readOnly={provider === "openai"}
|
||||
onChange={event => { setConnection({ ...connection, baseUrl: event.target.value }); setApiKey(""); setRemoveKey(false); setSaved(false); }} />
|
||||
onChange={event => { setConnection({ ...connection, baseUrl: event.target.value }); setApiKey(""); setRemoveKey(false); setSaved(false); clearCatalog(); }} />
|
||||
</label>
|
||||
<label className="space-y-1 text-sm sm:col-span-2">
|
||||
<span>{t("mod.pbc.key")}</span>
|
||||
<input className={inputClass} value={apiKey} type="password" autoComplete="off" disabled={removeKey}
|
||||
placeholder={hasKey ? t("mod.pbc.savedKey") : undefined}
|
||||
onChange={event => { setApiKey(event.target.value); setSaved(false); }} />
|
||||
onChange={event => { setApiKey(event.target.value); setSaved(false); clearCatalog(); }} />
|
||||
</label>
|
||||
{hasKey && <label className="flex items-center gap-2 text-sm sm:col-span-2">
|
||||
<input type="checkbox" checked={removeKey} onChange={event => { setRemoveKey(event.target.checked); setApiKey(""); setSaved(false); }} />
|
||||
<input type="checkbox" checked={removeKey} onChange={event => { setRemoveKey(event.target.checked); setApiKey(""); setSaved(false); clearCatalog(); }} />
|
||||
{t("mod.pbc.removeKey")}
|
||||
</label>}
|
||||
<PbcModelPicker key={provider} value={connection.model} catalog={catalog} discoveryBlocked={discoveryBlocked}
|
||||
loadModels={loadModels} onChange={model => { setConnection({ ...connection, model }); setSaved(false); }} />
|
||||
</fieldset>
|
||||
<p className="text-sm text-muted">{t("mod.pbc.keyHint")}</p>
|
||||
<Button size="sm" type="submit" disabled={busy || !valid || (setup.active && !dirty)}>{t("mod.pbc.save")}</Button>
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
import { useEffect, useId, useRef, useState, type KeyboardEvent } from "react";
|
||||
import { ChevronDown } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useI18n } from "@/i18n";
|
||||
import type { PbcModel } from "@/lib/api";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type ModelCatalog = {
|
||||
status: "idle" | "loading" | "ready" | "error";
|
||||
models: PbcModel[];
|
||||
};
|
||||
|
||||
const fieldClass = "selectable w-full rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none focus:border-gold";
|
||||
|
||||
export function PbcModelPicker({ value, onChange, catalog, discoveryBlocked, loadModels }: {
|
||||
value: string;
|
||||
onChange: (id: string) => void;
|
||||
catalog: ModelCatalog;
|
||||
discoveryBlocked?: string;
|
||||
loadModels: (refresh: boolean) => void;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const id = useId();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [manual, setManual] = useState(false);
|
||||
const [query, setQuery] = useState("");
|
||||
const [highlight, setHighlight] = useState(-1);
|
||||
const trigger = useRef<HTMLButtonElement>(null);
|
||||
const search = useRef<HTMLInputElement>(null);
|
||||
const manualInput = useRef<HTMLInputElement>(null);
|
||||
const list = useRef<HTMLUListElement>(null);
|
||||
const term = query.trim().toLocaleLowerCase();
|
||||
const models = catalog.models.filter(model => `${model.name} ${model.id}`.toLocaleLowerCase().includes(term));
|
||||
const selected = catalog.models.find(model => model.id === value);
|
||||
const active = Math.min(highlight, models.length);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) search.current?.focus();
|
||||
else if (manual) manualInput.current?.focus();
|
||||
}, [open, manual]);
|
||||
|
||||
useEffect(() => {
|
||||
if (open && active >= 0) list.current?.children.item(active)?.scrollIntoView({ block: "nearest" });
|
||||
}, [open, active]);
|
||||
|
||||
function browse(refresh = false) {
|
||||
setManual(false);
|
||||
if (!open) {
|
||||
setQuery("");
|
||||
setHighlight(-1);
|
||||
setOpen(true);
|
||||
} else {
|
||||
search.current?.focus();
|
||||
}
|
||||
loadModels(refresh);
|
||||
}
|
||||
|
||||
function choose(index: number) {
|
||||
setOpen(false);
|
||||
if (index === models.length) {
|
||||
setManual(true);
|
||||
} else {
|
||||
onChange(models[index].id);
|
||||
trigger.current?.focus();
|
||||
}
|
||||
}
|
||||
|
||||
function navigate(event: KeyboardEvent<HTMLInputElement>) {
|
||||
switch (event.key) {
|
||||
case "ArrowDown":
|
||||
case "ArrowUp":
|
||||
event.preventDefault();
|
||||
setHighlight(event.key === "ArrowDown"
|
||||
? Math.min(active + 1, models.length)
|
||||
: active <= 0 ? models.length : active - 1);
|
||||
break;
|
||||
case "Enter":
|
||||
event.preventDefault();
|
||||
choose(Math.max(0, active));
|
||||
break;
|
||||
case "Escape":
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
setOpen(false);
|
||||
trigger.current?.focus();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const status = discoveryBlocked
|
||||
?? (catalog.status === "loading" ? t("mod.pbc.loadingModels")
|
||||
: catalog.status === "error" ? t("mod.pbc.modelListFailed")
|
||||
: !models.length && catalog.status === "ready" ? t("mod.pbc.noModels")
|
||||
: "");
|
||||
|
||||
return (
|
||||
<div className="space-y-1.5 sm:col-span-2" onBlur={event => {
|
||||
if (!event.currentTarget.contains(event.relatedTarget)) setOpen(false);
|
||||
}}>
|
||||
<label htmlFor={id} className="block text-sm">{t("mod.pbc.model")}</label>
|
||||
<div className="flex flex-wrap items-start gap-2">
|
||||
<div className="relative min-w-56 flex-1">
|
||||
{manual ? (
|
||||
<input ref={manualInput} id={id} className={fieldClass} value={value} required
|
||||
placeholder={t("mod.pbc.manualModel")} onChange={event => onChange(event.target.value)} />
|
||||
) : (
|
||||
<button ref={trigger} id={id} type="button" className={cn(fieldClass, "flex items-center justify-between gap-2 text-left")}
|
||||
aria-expanded={open} aria-controls={open ? `${id}-picker` : undefined}
|
||||
onClick={() => open ? setOpen(false) : browse()}
|
||||
onKeyDown={event => {
|
||||
if (!open && (event.key === "ArrowDown" || event.key === "ArrowUp")) {
|
||||
event.preventDefault();
|
||||
browse();
|
||||
}
|
||||
}}>
|
||||
<span className={cn("truncate", !value && "text-muted")}>
|
||||
{selected?.name ?? (value || t("mod.pbc.chooseModel"))}
|
||||
</span>
|
||||
<ChevronDown className="h-4 w-4 shrink-0 text-muted" aria-hidden />
|
||||
</button>
|
||||
)}
|
||||
{open && (
|
||||
<div id={`${id}-picker`} className="absolute z-20 mt-1 w-full rounded-md border border-line bg-bg p-2 shadow-lg">
|
||||
<input ref={search} type="text" role="combobox" aria-expanded="true" aria-autocomplete="list"
|
||||
aria-controls={`${id}-options`} aria-activedescendant={active >= 0 ? `${id}-option-${active}` : undefined}
|
||||
aria-label={t("mod.pbc.searchModels")} placeholder={t("mod.pbc.searchModels")}
|
||||
className={fieldClass} value={query} autoComplete="off"
|
||||
onChange={event => { setQuery(event.target.value); setHighlight(-1); }} onKeyDown={navigate} />
|
||||
{status && <p className="px-2 py-2 text-sm text-muted" role="status">{status}</p>}
|
||||
<ul ref={list} id={`${id}-options`} role="listbox" aria-label={t("mod.pbc.model")} className="mt-1 max-h-56 overflow-auto">
|
||||
{models.map((model, index) => (
|
||||
<li key={model.id} id={`${id}-option-${index}`} role="option" aria-selected={model.id === value}
|
||||
className={cn("cursor-pointer rounded px-2 py-1.5 text-sm hover:bg-gold/10", active === index && "bg-gold/15")}
|
||||
onMouseDown={event => event.preventDefault()} onClick={() => choose(index)}>
|
||||
<span className="block break-all">{model.name}</span>
|
||||
{model.id !== model.name && <span className="block break-all text-xs text-muted">{model.id}</span>}
|
||||
</li>
|
||||
))}
|
||||
<li id={`${id}-option-${models.length}`} role="option" aria-selected={false}
|
||||
className={cn("cursor-pointer rounded border-t border-line px-2 py-1.5 text-sm text-gold hover:bg-gold/10",
|
||||
active === models.length && "bg-gold/15")}
|
||||
onMouseDown={event => event.preventDefault()} onClick={() => choose(models.length)}>
|
||||
{t("mod.pbc.manualModel")}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Button size="sm" variant="secondary" type="button" disabled={!manual && (!!discoveryBlocked || catalog.status === "loading")}
|
||||
onClick={() => manual ? browse() : browse(true)}>
|
||||
{t(manual ? "mod.pbc.browseModels" : "mod.pbc.refreshModels")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user