mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-25 03:25:56 +00:00
Merge PR #234: Playerbot Characters model setup
This commit is contained in:
commit
1b0adbf94c
21 files changed
+1288
-4
No files matched your search
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: modules
|
||||
type: added
|
||||
audience: admins
|
||||
title: Configure Playerbot Characters from the Modules page
|
||||
---
|
||||
Set up an OpenAI, Ollama, Anthropic or OpenAI-compatible connection from Modules, including its API key. Playerbot Characters gives CoA Companions or SQUID Playerbots dialogue and memories.
|
||||
@@ -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.
|
||||
@@ -665,6 +665,11 @@ fn game_args(
|
||||
a.extend(env("AC_UPDATES_ENABLE_DATABASES", "0"));
|
||||
if kind == GameKind::World {
|
||||
a.extend(["--volume".into(), format!("{}:{DATA}:ro", data.display())]);
|
||||
let pbc = crate::modules::pbc::ASSET_DIR;
|
||||
let assets = host.join(pbc);
|
||||
if assets.is_dir() {
|
||||
a.extend(["--volume".into(), format!("{}:/srv/{pbc}:ro", assets.display())]);
|
||||
}
|
||||
let races = host.join("Data/dbc_races");
|
||||
if races.is_dir() && races != data.join("dbc_races") {
|
||||
a.extend([
|
||||
@@ -1066,6 +1071,8 @@ mod tests {
|
||||
#[test]
|
||||
fn a_first_start_creates_the_network_the_image_and_the_containers_in_order() {
|
||||
let (_d, root) = server("t1");
|
||||
let assets = root.join(crate::modules::pbc::ASSET_DIR);
|
||||
fs::create_dir_all(&assets).unwrap();
|
||||
let sim = Sim::new();
|
||||
let o = start_all(&sim, &root);
|
||||
assert!(o.ok, "{}", o.output);
|
||||
@@ -1091,6 +1098,10 @@ mod tests {
|
||||
["coa-t1-db", "coa-t1-world", "coa-t1-auth"],
|
||||
"database, then world, then auth"
|
||||
);
|
||||
let calls = sim.calls_of("run");
|
||||
let mount = format!("{}:/srv/Extras/PlayerbotCharacters:ro", assets.display());
|
||||
assert!(calls[1].args.windows(2).any(|w| w == ["--volume", mount.as_str()]));
|
||||
assert!(!calls[0].args.contains(&mount) && !calls[2].args.contains(&mount));
|
||||
let exec = sim.calls_of("exec");
|
||||
assert_eq!(
|
||||
exec.len(),
|
||||
|
||||
@@ -154,6 +154,14 @@ pub fn safe_join(root: &Path, rel: &str) -> Result<PathBuf> {
|
||||
|
||||
/// Write `bytes` to `path` so readers see either the old or the new content, never a partial file.
|
||||
pub fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
atomic_write_inner(path, bytes, false)
|
||||
}
|
||||
|
||||
pub(crate) fn atomic_write_private(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
atomic_write_inner(path, bytes, true)
|
||||
}
|
||||
|
||||
fn atomic_write_inner(path: &Path, bytes: &[u8], _private: bool) -> Result<()> {
|
||||
let parent = path
|
||||
.parent()
|
||||
.ok_or_else(|| Error::PathRejected("no parent directory".into()))?;
|
||||
@@ -166,7 +174,14 @@ pub fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
uuid::Uuid::new_v4().simple()
|
||||
));
|
||||
let write = || -> std::io::Result<()> {
|
||||
let mut f = OpenOptions::new().write(true).create_new(true).open(&tmp)?;
|
||||
let mut options = OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
if _private {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode(0o600);
|
||||
}
|
||||
let mut f = options.open(&tmp)?;
|
||||
f.write_all(bytes)?;
|
||||
f.sync_all()?;
|
||||
Ok(())
|
||||
|
||||
@@ -12,6 +12,8 @@ use crate::config::parser::ConfFile;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::fsx;
|
||||
|
||||
pub mod pbc;
|
||||
|
||||
static CATALOG: &str = include_str!("../../../modules/catalog.json");
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
@@ -512,6 +514,12 @@ fn settings_in(cat: &[Entry], root: &Path, id: &str) -> Result<Vec<Setting>> {
|
||||
};
|
||||
Ok(effective
|
||||
.entries()
|
||||
.filter(|(key, _)| {
|
||||
id != "mod-pbc"
|
||||
|| !["PBC.ApiKey", "PBC.AltModelApiKey"]
|
||||
.iter()
|
||||
.any(|secret| key.eq_ignore_ascii_case(secret))
|
||||
})
|
||||
.map(|(k, v)| {
|
||||
let mut val = fields
|
||||
.get(k)
|
||||
@@ -703,6 +711,63 @@ fn save_settings_in(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn playerbot_characters_uses_the_packaged_default_and_keeps_host_settings() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path().join("server");
|
||||
let meta = temp.path().join("metadata");
|
||||
let cat = catalog();
|
||||
let id = "mod-pbc";
|
||||
let card = || list_in(&cat, &root).into_iter().find(|m| m.id == id).unwrap();
|
||||
fs::create_dir_all(dir(&root)).unwrap();
|
||||
fs::create_dir_all(&meta).unwrap();
|
||||
assert!(!card().installed);
|
||||
|
||||
let dist = dir(&root).join("playerbots_characters.conf.dist");
|
||||
let defaults = "[worldserver]\nPBC.Enable = 0\nPBC.DefaultConnection = ../Extras/PlayerbotCharacters/my-connection.jsonc\n";
|
||||
fs::write(&dist, defaults).unwrap();
|
||||
let installed = card();
|
||||
assert!(installed.installed && installed.switchable && installed.has_settings);
|
||||
assert!(!installed.enabled);
|
||||
|
||||
let key = "PBC.DefaultConnection";
|
||||
let path = "C:/Test Server/Model Config/custom.jsonc";
|
||||
save_settings_in(&cat, &root, &meta, id, &BTreeMap::from([(key.into(), path.into())])).unwrap();
|
||||
set_enabled_in(&cat, &root, &meta, id, true).unwrap();
|
||||
assert!(card().enabled);
|
||||
set_enabled_in(&cat, &root, &meta, id, false).unwrap();
|
||||
assert!(!card().enabled);
|
||||
let active = read(&dir(&root).join("playerbots_characters.conf")).unwrap();
|
||||
assert_eq!(active.get(key), Some(path));
|
||||
assert_eq!(fs::read_to_string(dist).unwrap(), defaults);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn playerbot_characters_preserves_legacy_connections_without_exposing_keys() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
fs::create_dir_all(dir(root)).unwrap();
|
||||
let name = "playerbots_characters.conf";
|
||||
fs::write(
|
||||
dir(root).join(name),
|
||||
"[worldserver]\nPBC.Enable = 1\nPBC.BaseUrl = https://example.test/v1\nPBC.Model = legacy\nPBC.ApiKey = fixture-key\nPBC.AltModelApiKey = fixture-alt-key\n",
|
||||
).unwrap();
|
||||
fs::write(
|
||||
dir(root).join(format!("{name}.dist")),
|
||||
"[worldserver]\nPBC.Enable = 0\nPBC.DefaultConnection = \"\"\n",
|
||||
).unwrap();
|
||||
|
||||
crate::config::materialize_module_configs(root).unwrap();
|
||||
let config = read(&dir(root).join(name)).unwrap();
|
||||
assert_eq!(config.get("PBC.Enable"), Some("1"));
|
||||
assert_eq!(config.get("PBC.DefaultConnection"), Some("\"\""));
|
||||
assert_eq!(config.get("PBC.ApiKey"), Some("fixture-key"));
|
||||
assert_eq!(config.get("PBC.AltModelApiKey"), Some("fixture-alt-key"));
|
||||
let visible = serde_json::to_string(&settings(root, "mod-pbc").unwrap()).unwrap();
|
||||
assert!(!visible.contains("fixture-key") && !visible.contains("fixture-alt-key"));
|
||||
assert!(!pbc::load(root).unwrap().active);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_is_time_card_settings_and_backups_match_the_module() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
//! Owns the connection file created by the Manager. Handwritten connection files stay with their owners.
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::io::ErrorKind;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::config::parser::{ConfFile, unquote};
|
||||
use crate::realms::{self, Mode};
|
||||
use crate::{Error, Result, fsx};
|
||||
|
||||
pub mod models;
|
||||
|
||||
const MODULE: &str = "mod-pbc";
|
||||
const PATH_SETTING: &str = "PBC.DefaultConnection";
|
||||
pub(crate) const ASSET_DIR: &str = "Extras/PlayerbotCharacters";
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ApiType {
|
||||
Openai,
|
||||
Ollama,
|
||||
Anthropic,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ConnectionUpdate {
|
||||
pub api_type: ApiType,
|
||||
pub base_url: String,
|
||||
pub model: String,
|
||||
pub api_key: Option<String>,
|
||||
pub remove_key: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Connection {
|
||||
api_type: ApiType,
|
||||
base_url: String,
|
||||
model: String,
|
||||
api_key: String,
|
||||
request_timeout_sec: u32,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ConnectionView {
|
||||
pub api_type: ApiType,
|
||||
pub base_url: String,
|
||||
pub model: String,
|
||||
pub has_key: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Setup {
|
||||
pub active: bool,
|
||||
pub connection: Option<ConnectionView>,
|
||||
}
|
||||
|
||||
fn managed_connection(root: &Path) -> Result<(PathBuf, String)> {
|
||||
let file = match realms::state(root)?.active {
|
||||
Mode::Coa => "manager-connection.jsonc",
|
||||
Mode::Wildcard => "manager-connection-wildcard.jsonc",
|
||||
Mode::Reborn => "manager-connection-reborn.jsonc",
|
||||
};
|
||||
let relative = format!("{ASSET_DIR}/{file}");
|
||||
let path = fsx::ensure_within(root, &root.join(&relative))?;
|
||||
Ok((path, format!("../{relative}")))
|
||||
}
|
||||
|
||||
/// Secondary worlds use their own Core directory. Point their packaged paths back to the shared assets.
|
||||
pub(crate) fn rebase_packaged_paths(config: &str, root: &Path) -> Result<String> {
|
||||
let mut conf = ConfFile::parse_bytes(config.as_bytes())?;
|
||||
let assets = root.join(ASSET_DIR);
|
||||
for key in [
|
||||
PATH_SETTING, "PBC.UtilityConnection", "PBC.CondensationConnection",
|
||||
"PBC.RelationshipUpdateConnection", "PBC.PromptsPath", "PBC.CharacterCardsPath",
|
||||
"PBC.HttpServerFrontendPath",
|
||||
] {
|
||||
let Some(relative) = conf.get(key).map(unquote)
|
||||
.and_then(|path| path.strip_prefix("../Extras/PlayerbotCharacters/"))
|
||||
else { continue };
|
||||
let Ok(path) = fsx::safe_join(&assets, relative) else { continue };
|
||||
let path = path.to_string_lossy().replace('\\', "/");
|
||||
conf.set(key, &format!("\"{path}\""), &[]);
|
||||
}
|
||||
Ok(conf.to_text())
|
||||
}
|
||||
|
||||
fn read_connection(path: &Path) -> Result<Option<Vec<u8>>> {
|
||||
match fs::read(path) {
|
||||
Ok(bytes) => Ok(Some(bytes)),
|
||||
Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
|
||||
Err(error) => Err(error.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse(bytes: &[u8]) -> Result<Connection> {
|
||||
serde_json::from_slice(bytes).map_err(|_| Error::Invalid("The Manager model connection file is invalid.".into()))
|
||||
}
|
||||
|
||||
fn view(connection: Connection) -> ConnectionView {
|
||||
ConnectionView {
|
||||
api_type: connection.api_type,
|
||||
base_url: connection.base_url,
|
||||
model: connection.model,
|
||||
has_key: !connection.api_key.is_empty(),
|
||||
}
|
||||
}
|
||||
|
||||
fn module_setting(root: &Path) -> Result<String> {
|
||||
super::settings(root, MODULE)?
|
||||
.into_iter()
|
||||
.find(|setting| setting.key == PATH_SETTING)
|
||||
.map(|setting| setting.value)
|
||||
.ok_or_else(|| Error::Invalid("This server package does not provide a model connection setting.".into()))
|
||||
}
|
||||
|
||||
pub fn load(root: &Path) -> Result<Setup> {
|
||||
let (path, setting) = managed_connection(root)?;
|
||||
let active = unquote(&module_setting(root)?) == setting;
|
||||
let connection = read_connection(&path)?
|
||||
.as_deref()
|
||||
.map(parse)
|
||||
.transpose()?
|
||||
.map(view);
|
||||
Ok(Setup { active, connection })
|
||||
}
|
||||
|
||||
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 (path, setting) = managed_connection(root)?;
|
||||
let active = unquote(&module_setting(root)?) == 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 previous = read_connection(&path)?;
|
||||
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(),
|
||||
model: model.into(),
|
||||
api_key: key,
|
||||
request_timeout_sec: if matches!(update.api_type, ApiType::Ollama) { 60 } else { 30 },
|
||||
};
|
||||
fsx::atomic_write_private(&path, &serde_json::to_vec_pretty(&connection)?)?;
|
||||
if !active {
|
||||
let changes = BTreeMap::from([(PATH_SETTING.into(), setting)]);
|
||||
if let Err(error) = super::save_settings(root, meta, MODULE, &changes) {
|
||||
if let Some(bytes) = previous {
|
||||
fsx::atomic_write_private(&path, &bytes)?;
|
||||
} else {
|
||||
fs::remove_file(&path)?;
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
Ok(Setup { active: true, connection: Some(view(connection)) })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn update(api_type: ApiType, base_url: &str, api_key: Option<&str>) -> ConnectionUpdate {
|
||||
ConnectionUpdate { api_type, base_url: base_url.into(), model: "example-model".into(),
|
||||
api_key: api_key.map(str::to_owned), remove_key: false }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_setup_preserves_manual_files_and_only_reuses_keys_for_the_same_endpoint() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
let meta = root.join("metadata");
|
||||
let configs = root.join("Core/configs/modules");
|
||||
fs::create_dir_all(&meta).unwrap();
|
||||
fs::create_dir_all(&configs).unwrap();
|
||||
fs::write(configs.join("playerbots_characters.conf.dist"),
|
||||
"[worldserver]\nPBC.Enable = 0\nPBC.DefaultConnection = ../my-custom.jsonc\n").unwrap();
|
||||
fs::write(root.join("my-custom.jsonc"), b"// manual connection").unwrap();
|
||||
assert!(!load(root).unwrap().active);
|
||||
|
||||
let base_url = "https://api.example.com/v1";
|
||||
let saved = save(root, &meta, update(ApiType::Openai, base_url, Some("fixture-key"))).unwrap();
|
||||
assert!(saved.active && saved.connection.as_ref().unwrap().has_key);
|
||||
assert!(!serde_json::to_string(&saved).unwrap().contains("fixture-key"));
|
||||
assert!(save(root, &meta, update(ApiType::Openai, base_url, None)).unwrap().connection.unwrap().has_key);
|
||||
let mut clear = update(ApiType::Openai, base_url, None);
|
||||
clear.remove_key = true;
|
||||
assert!(!save(root, &meta, clear).unwrap().connection.unwrap().has_key);
|
||||
save(root, &meta, update(ApiType::Openai, base_url, Some("replacement-key"))).unwrap();
|
||||
let changed = save(root, &meta, update(ApiType::Ollama, "http://127.0.0.1:11434", None)).unwrap();
|
||||
assert!(!changed.connection.unwrap().has_key);
|
||||
assert!(save(root, &meta, update(ApiType::Openai, "https://user:secret@example.com", None)).is_err());
|
||||
assert_eq!(fs::read(root.join("my-custom.jsonc")).unwrap(), b"// manual connection");
|
||||
let config = fs::read_to_string(configs.join("playerbots_characters.conf")).unwrap();
|
||||
assert!(config.contains("PBC.Enable = 0"));
|
||||
assert!(!config.contains("replacement-key"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secondary_world_uses_the_shared_pbc_assets_and_keeps_custom_paths() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let config = "[worldserver]\nPBC.DefaultConnection = \"../Extras/PlayerbotCharacters/manager-connection.jsonc\"\nPBC.PromptsPath = \"../Extras/PlayerbotCharacters/prompts\"\nPBC.UtilityConnection = \"custom.jsonc\"\n";
|
||||
let result = rebase_packaged_paths(config, temp.path()).unwrap();
|
||||
let result = ConfFile::parse_bytes(result.as_bytes()).unwrap();
|
||||
let expected = temp.path().join(ASSET_DIR).to_string_lossy().replace('\\', "/");
|
||||
assert_eq!(result.get(PATH_SETTING).map(unquote), Some(format!("{expected}/manager-connection.jsonc").as_str()));
|
||||
assert_eq!(result.get("PBC.PromptsPath").map(unquote), Some(format!("{expected}/prompts").as_str()));
|
||||
assert_eq!(result.get("PBC.UtilityConnection").map(unquote), Some("custom.jsonc"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_realm_saves_its_own_model_connection() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
let config = root.join("Core/configs/modules/playerbots_characters.conf");
|
||||
let meta = root.join("metadata");
|
||||
fsx::atomic_write(&config, b"[worldserver]\nPBC.Enable = 0\nPBC.DefaultConnection = \"\"\n").unwrap();
|
||||
let (coa_path, _) = managed_connection(root).unwrap();
|
||||
let endpoint = "https://example.test/v1";
|
||||
save(root, &meta, update(ApiType::Openai, endpoint, Some("coa-key"))).unwrap();
|
||||
let coa_config = fs::read(&config).unwrap();
|
||||
let coa_connection = fs::read(&coa_path).unwrap();
|
||||
|
||||
let state = root.join("Settings/realm-profile.json");
|
||||
let mut realm_state = realms::RealmState {
|
||||
active: Mode::Wildcard,
|
||||
wildcard_created: true,
|
||||
..Default::default()
|
||||
};
|
||||
fsx::atomic_write_json(&state, &realm_state).unwrap();
|
||||
let (wildcard_path, _) = managed_connection(root).unwrap();
|
||||
assert_ne!(coa_path, wildcard_path);
|
||||
assert!(load(root).unwrap().connection.is_none());
|
||||
let mut wildcard = update(ApiType::Openai, endpoint, None);
|
||||
wildcard.model = "wildcard-model".into();
|
||||
let saved = save(root, &meta, wildcard).unwrap().connection.unwrap();
|
||||
assert!(!saved.has_key);
|
||||
assert_eq!(saved.model, "wildcard-model");
|
||||
assert_eq!(fs::read(&coa_path).unwrap(), coa_connection);
|
||||
|
||||
realm_state.active = Mode::Coa;
|
||||
fsx::atomic_write_json(&state, &realm_state).unwrap();
|
||||
fsx::atomic_write(&config, &coa_config).unwrap();
|
||||
let restored = load(root).unwrap();
|
||||
assert!(restored.active && restored.connection.unwrap().has_key);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
//! 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_url, managed_connection, 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 (path, _) = managed_connection(root)?;
|
||||
let previous = read_connection(&path)?;
|
||||
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, _) = managed_connection(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, _) = managed_connection(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);
|
||||
}
|
||||
}
|
||||
@@ -376,6 +376,8 @@ fn prepare(main: &Path, tree: Tree) -> Result<PathBuf> {
|
||||
conf.set("CoA.AllowRemoteClients", "1", &[]);
|
||||
}
|
||||
conf.to_text()
|
||||
} else if path == "Core/configs/modules/playerbots_characters.conf" {
|
||||
crate::modules::pbc::rebase_packaged_paths(&text, main)?
|
||||
} else {
|
||||
text
|
||||
};
|
||||
|
||||
@@ -2362,6 +2362,38 @@ mod tests {
|
||||
w
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn playerbot_characters_release_files_leave_host_connections_and_cards_in_place() {
|
||||
const DIST: &str = "Core/configs/modules/playerbots_characters.conf.dist";
|
||||
const CONFIG: &str = "Core/configs/modules/playerbots_characters.conf";
|
||||
const CONNECTION: &str = "Extras/PlayerbotCharacters/manager-connection.jsonc";
|
||||
const CARD: &str = "Extras/PlayerbotCharacters/cards/Companion.card.txt";
|
||||
const PROMPT: &str = "Extras/PlayerbotCharacters/prompts/enUS/CharacterContext.custom.txt";
|
||||
let defaults = b"[worldserver]\nPBC.Enable = 0\nPBC.DefaultConnection = \"\"\n";
|
||||
for configured in [false, true] {
|
||||
let w = world(&[(DIST, defaults), ("Extras/PlayerbotCharacters/cards/README.txt", b"Cards")], false);
|
||||
let host_config = b"[worldserver]\nPBC.Enable = 1\nPBC.DefaultConnection = ../Extras/PlayerbotCharacters/manager-connection.jsonc\n";
|
||||
if configured {
|
||||
write(&w.root, CONFIG, host_config);
|
||||
write(&w.root, CONNECTION, b"{\"apiKey\":\"fixture-only\"}");
|
||||
write(&w.root, CARD, b"My character card");
|
||||
write(&w.root, PROMPT, b"My custom prompt");
|
||||
}
|
||||
assert_eq!(run(&w, &Fake::ok(), BTreeMap::new(), None).unwrap().txn.state, State::Committed);
|
||||
assert_eq!(fs::read(w.root.join(DIST)).unwrap(), defaults);
|
||||
let module = crate::modules::list(&w.root).into_iter().find(|m| m.id == "mod-pbc").unwrap();
|
||||
assert!(module.installed && module.enabled == configured);
|
||||
if configured {
|
||||
assert_eq!(fs::read(w.root.join(CONFIG)).unwrap(), host_config);
|
||||
assert_eq!(fs::read(w.root.join(CONNECTION)).unwrap(), b"{\"apiKey\":\"fixture-only\"}");
|
||||
assert_eq!(fs::read(w.root.join(CARD)).unwrap(), b"My character card");
|
||||
assert_eq!(fs::read(w.root.join(PROMPT)).unwrap(), b"My custom prompt");
|
||||
} else {
|
||||
assert!(!w.root.join(CONNECTION).exists());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_waits_for_an_update_check_but_not_for_active_maintenance() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -1,6 +1,24 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"modules": [
|
||||
{
|
||||
"id": "mod-pbc",
|
||||
"name": "Playerbot Characters",
|
||||
"description": {
|
||||
"en": "Gives CoA Companions or SQUID Playerbots dialogue, personalities and memories. Requires a model connection you configure.",
|
||||
"ru": "Добавляет диалоги, характеры и воспоминания ботам CoA Companions или SQUID Playerbots. Нужно настроить подключение к модели.",
|
||||
"de": "Gibt CoA Companions oder SQUID Playerbots Dialoge, Persönlichkeiten und Erinnerungen. Die Verbindung zu einem KI-Modell muss eingerichtet werden.",
|
||||
"fr": "Ajoute des dialogues, des personnalités et des souvenirs aux bots CoA Companions ou SQUID Playerbots. Une connexion à un modèle doit être configurée.",
|
||||
"es": "Añade diálogos, personalidades y recuerdos a los bots de CoA Companions o SQUID Playerbots. Requiere configurar una conexión con un modelo.",
|
||||
"zh": "为 CoA Companions 或 SQUID Playerbots 添加对话、个性和记忆。需要自行配置模型连接。"
|
||||
},
|
||||
"repo": "https://github.com/deseven/mod-pbc#model-connection-setup",
|
||||
"conf": "playerbots_characters.conf",
|
||||
"enable_key": "PBC.Enable",
|
||||
"default_on": false,
|
||||
"status": "early",
|
||||
"icon": "bot"
|
||||
},
|
||||
{
|
||||
"id": "dungeon-clear",
|
||||
"name": "Dungeon Clear",
|
||||
|
||||
@@ -1710,6 +1710,40 @@ async fn module_save_settings(
|
||||
.await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn pbc_connection(
|
||||
state: State<'_, AppState>,
|
||||
id: String,
|
||||
) -> std::result::Result<coa_core::modules::pbc::Setup, UiError> {
|
||||
let root = path_of(&state, &id)?;
|
||||
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>,
|
||||
id: String,
|
||||
update: coa_core::modules::pbc::ConnectionUpdate,
|
||||
) -> std::result::Result<coa_core::modules::pbc::Setup, UiError> {
|
||||
let root = path_of(&state, &id)?;
|
||||
let _guard = BusyGuard::acquire(&state, &id)?;
|
||||
blocking(move || {
|
||||
let (dir, _) = install_meta(&root)?;
|
||||
coa_core::modules::pbc::save(&root, &dir, update)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn all_settings(
|
||||
state: State<'_, AppState>,
|
||||
@@ -3217,6 +3251,9 @@ pub fn run() {
|
||||
repair_server,
|
||||
module_set_enabled,
|
||||
module_settings,
|
||||
pbc_connection,
|
||||
pbc_list_models,
|
||||
pbc_save_connection,
|
||||
module_save_settings,
|
||||
all_settings,
|
||||
all_settings_save,
|
||||
|
||||
@@ -844,7 +844,29 @@ 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",
|
||||
"mod.pbc.compatible": "OpenAI-kompatibler Endpunkt",
|
||||
"mod.pbc.model": "Modellname",
|
||||
"mod.pbc.endpoint": "API-Basis-URL",
|
||||
"mod.pbc.key": "API-Schlüssel",
|
||||
"mod.pbc.savedKey": "Schlüssel gespeichert",
|
||||
"mod.pbc.removeKey": "Gespeicherten Schlüssel löschen",
|
||||
"mod.pbc.keyHint": "Lass das Feld leer, um den Schlüssel für denselben Endpunkt zu behalten. Lokales Ollama braucht meist keinen Schlüssel.",
|
||||
"mod.pbc.save": "Modellverbindung speichern",
|
||||
"mod.pbc.saved": "Modellverbindung gespeichert.",
|
||||
"mod.pbc.useConnection": "Beim Speichern wird diese Verbindung als Standard für mod-pbc auf dem Server festgelegt.",
|
||||
"mod.settings": "Einstellungen",
|
||||
"mod.default": "Zurück zum Standard ({v})",
|
||||
"mod.saved": "Gespeichert ({n} geändert).",
|
||||
|
||||
@@ -890,7 +890,29 @@ 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",
|
||||
"mod.pbc.compatible": "OpenAI-compatible endpoint",
|
||||
"mod.pbc.model": "Model name",
|
||||
"mod.pbc.endpoint": "API base URL",
|
||||
"mod.pbc.key": "API key",
|
||||
"mod.pbc.savedKey": "Saved key",
|
||||
"mod.pbc.removeKey": "Remove saved key",
|
||||
"mod.pbc.keyHint": "Leave the key blank to keep it for the same endpoint. Local Ollama usually needs no key.",
|
||||
"mod.pbc.save": "Save model connection",
|
||||
"mod.pbc.saved": "Model connection saved.",
|
||||
"mod.pbc.useConnection": "Saving makes this the server’s default mod-pbc connection.",
|
||||
"mod.settings": "Settings",
|
||||
"mod.default": "Back to the default ({v})",
|
||||
"mod.saved": "Saved ({n} changed).",
|
||||
|
||||
@@ -844,7 +844,29 @@ 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",
|
||||
"mod.pbc.compatible": "Endpoint compatible con OpenAI",
|
||||
"mod.pbc.model": "Nombre del modelo",
|
||||
"mod.pbc.endpoint": "URL base de la API",
|
||||
"mod.pbc.key": "Clave de API",
|
||||
"mod.pbc.savedKey": "Clave guardada",
|
||||
"mod.pbc.removeKey": "Eliminar la clave guardada",
|
||||
"mod.pbc.keyHint": "Deja el campo vacío para conservar la clave del mismo endpoint. Ollama en local normalmente no necesita clave.",
|
||||
"mod.pbc.save": "Guardar la conexión",
|
||||
"mod.pbc.saved": "Conexión con el modelo guardada.",
|
||||
"mod.pbc.useConnection": "Al guardar, esta será la conexión predeterminada de mod-pbc en el servidor.",
|
||||
"mod.settings": "Ajustes",
|
||||
"mod.default": "Volver al valor por defecto ({v})",
|
||||
"mod.saved": "Guardado ({n} cambiado(s)).",
|
||||
|
||||
@@ -844,7 +844,29 @@ 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",
|
||||
"mod.pbc.compatible": "Point d’accès compatible OpenAI",
|
||||
"mod.pbc.model": "Nom du modèle",
|
||||
"mod.pbc.endpoint": "URL de base de l’API",
|
||||
"mod.pbc.key": "Clé API",
|
||||
"mod.pbc.savedKey": "Clé enregistrée",
|
||||
"mod.pbc.removeKey": "Supprimer la clé enregistrée",
|
||||
"mod.pbc.keyHint": "Laissez le champ vide pour conserver la clé du même point d’accès. Ollama en local ne demande généralement pas de clé.",
|
||||
"mod.pbc.save": "Enregistrer la connexion",
|
||||
"mod.pbc.saved": "Connexion au modèle enregistrée.",
|
||||
"mod.pbc.useConnection": "Cette connexion deviendra la connexion par défaut de mod-pbc sur le serveur.",
|
||||
"mod.settings": "Réglages",
|
||||
"mod.default": "Revenir à la valeur par défaut ({v})",
|
||||
"mod.saved": "Enregistré ({n} modifié(s)).",
|
||||
|
||||
@@ -873,7 +873,29 @@ 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": "Провайдер модели",
|
||||
"mod.pbc.compatible": "Эндпоинт, совместимый с OpenAI",
|
||||
"mod.pbc.model": "Имя модели",
|
||||
"mod.pbc.endpoint": "Базовый URL API",
|
||||
"mod.pbc.key": "Ключ API",
|
||||
"mod.pbc.savedKey": "Ключ сохранён",
|
||||
"mod.pbc.removeKey": "Удалить сохранённый ключ",
|
||||
"mod.pbc.keyHint": "Оставьте поле пустым, чтобы сохранить ключ для того же адреса. Локальной Ollama обычно ключ не нужен.",
|
||||
"mod.pbc.save": "Сохранить подключение",
|
||||
"mod.pbc.saved": "Подключение к модели сохранено.",
|
||||
"mod.pbc.useConnection": "После сохранения это подключение станет основным для mod-pbc на сервере.",
|
||||
"mod.settings": "Настройки",
|
||||
"mod.default": "Вернуть по умолчанию ({v})",
|
||||
"mod.saved": "Сохранено (изменено: {n}).",
|
||||
|
||||
@@ -844,7 +844,29 @@ 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": "模型服务商",
|
||||
"mod.pbc.compatible": "兼容 OpenAI 的端点",
|
||||
"mod.pbc.model": "模型名称",
|
||||
"mod.pbc.endpoint": "API 基础网址",
|
||||
"mod.pbc.key": "API 密钥",
|
||||
"mod.pbc.savedKey": "已保存密钥",
|
||||
"mod.pbc.removeKey": "删除已保存的密钥",
|
||||
"mod.pbc.keyHint": "留空会保留同一端点的密钥。本地 Ollama 通常不需要密钥。",
|
||||
"mod.pbc.save": "保存模型连接",
|
||||
"mod.pbc.saved": "模型连接已保存。",
|
||||
"mod.pbc.useConnection": "保存后,此连接将成为该服务器上 mod-pbc 的默认连接。",
|
||||
"mod.settings": "模块设置",
|
||||
"mod.default": "恢复为默认值 ({v})",
|
||||
"mod.saved": "已保存(修改了 {n} 项)。",
|
||||
|
||||
@@ -229,6 +229,26 @@ export interface RealmProfile {
|
||||
data: string;
|
||||
}
|
||||
|
||||
export type PbcApiType = "openai" | "ollama" | "anthropic";
|
||||
export interface PbcConnection {
|
||||
apiType: PbcApiType;
|
||||
baseUrl: string;
|
||||
model: string;
|
||||
}
|
||||
export interface PbcConnectionSetup {
|
||||
active: boolean;
|
||||
connection: (PbcConnection & { hasKey: boolean }) | null;
|
||||
}
|
||||
export interface PbcConnectionUpdate extends PbcConnection {
|
||||
apiKey?: string;
|
||||
removeKey: boolean;
|
||||
}
|
||||
|
||||
export interface PbcModel {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface ModuleView {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -545,6 +565,9 @@ export const api = {
|
||||
realmlistDelete: (id: string, profileId: string) => invoke<void>("realmlist_delete", { id, profileId }),
|
||||
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 }),
|
||||
moduleSaveSettings: (id: string, module: string, changes: Record<string, string>) => invoke<string[]>("module_save_settings", { id, module, changes }),
|
||||
|
||||
@@ -9,6 +9,7 @@ import { useHuman, useI18n, useSchemaText, type Key } from "@/i18n";
|
||||
import { auctionWeightKey, canonicalModuleValue, moduleEnableKey, moduleField, retiredModuleKeys } from "@/lib/moduleSettings";
|
||||
import { AuctionTypes } from "@/screens/AuctionTypes";
|
||||
import { RaceAvailabilitySettings } from "@/screens/RaceAvailabilitySettings";
|
||||
import { PbcConnectionSettings } from "@/screens/PbcConnectionSettings";
|
||||
import type { UnsavedChangesGuard } from "@/lib/unsavedGuard";
|
||||
|
||||
/** The GitHub mark (lucide dropped its brand icons). */
|
||||
@@ -111,16 +112,18 @@ export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId
|
||||
}, [serverId]);
|
||||
const [guard, setGuard] = useState<UnsavedChangesGuard | null>(null);
|
||||
const [racesGuard, setRacesGuard] = useState<UnsavedChangesGuard | null>(null);
|
||||
const [pbcGuard, setPbcGuard] = useState<UnsavedChangesGuard | null>(null);
|
||||
const markChanged = useCallback(() => setChanged(true), []);
|
||||
|
||||
useEffect(() => {
|
||||
const guards = [guard, racesGuard].filter((item): item is UnsavedChangesGuard => item !== null);
|
||||
const guards = [guard, racesGuard, pbcGuard].filter((item): item is UnsavedChangesGuard => item !== null);
|
||||
onRegisterGuard?.(guards.length ? {
|
||||
isDirty: () => guards.some(item => item.isDirty()),
|
||||
save: async () => { for (const item of guards) if (item.isDirty() && !await item.save()) return false; return true; },
|
||||
discard: () => guards.forEach(item => item.discard()),
|
||||
} : null);
|
||||
return () => onRegisterGuard?.(null);
|
||||
}, [guard, racesGuard, onRegisterGuard]);
|
||||
}, [guard, racesGuard, pbcGuard, onRegisterGuard]);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
@@ -343,6 +346,7 @@ export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId
|
||||
{selected?.has_settings && !selected.page && selectedAt >= 0 && Math.floor(selectedAt / 2) === Math.floor(i / 2) && (i % 2 === 1 || i === modules.length - 1) && (
|
||||
<SettingsPanel key={selected.id} className="sm:col-span-2">
|
||||
<h2 className="font-semibold">{t("mod.settingsOf", { name: selected.name })}</h2>
|
||||
{selected.id === "mod-pbc" && <PbcConnectionSettings serverId={serverId} onSaved={markChanged} onRegisterGuard={setPbcGuard} />}
|
||||
<ModuleSettings serverId={serverId} module={selected} onSaved={() => setChanged(true)} onRegisterGuard={setGuard} />
|
||||
{selected.id === "custom-races" && <RaceAvailabilitySettings serverId={serverId}
|
||||
blocked={racesInstalling || toggling !== null} onSaved={() => setChanged(true)}
|
||||
@@ -461,7 +465,7 @@ function ModuleSettings({ serverId, module, onSaved, onRegisterGuard }: { server
|
||||
else next[key] = value;
|
||||
return next;
|
||||
});
|
||||
const available = items?.filter(s => s.key !== moduleEnableKey(module.id) && !["CoACustomRaces.DisabledRaceIds", "CoACustomRaces.DisabledRaceCatalogSha256"].includes(s.key) && !retiredModuleKeys.has(s.key)) ?? [];
|
||||
const available = items?.filter(s => s.key !== moduleEnableKey(module.id) && !["CoACustomRaces.DisabledRaceIds", "CoACustomRaces.DisabledRaceCatalogSha256", "PBC.DefaultConnection"].includes(s.key) && !retiredModuleKeys.has(s.key)) ?? [];
|
||||
const advancedCount = available.filter(s => !auctionWeightKey(s.key) && (!moduleField(s.key, locale, s.field) || moduleField(s.key, locale, s.field)?.advanced)).length;
|
||||
const visible = available.filter(s => {
|
||||
if (module.id === "ah-bot" && auctionWeightKey(s.key)) return false;
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
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: "" },
|
||||
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: "" },
|
||||
};
|
||||
const providerOf = (connection: PbcConnection): Provider => connection.apiType !== "openai" ? connection.apiType
|
||||
: connection.baseUrl === presets.openai.baseUrl ? "openai" : "compatible";
|
||||
const inputClass = "selectable w-full rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none focus:border-gold";
|
||||
|
||||
export function PbcConnectionSettings({ serverId, onSaved, onRegisterGuard }: {
|
||||
serverId: string;
|
||||
onSaved: () => void;
|
||||
onRegisterGuard: (guard: UnsavedChangesGuard | null) => void;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const human = useHuman();
|
||||
const [setup, setSetup] = useState<PbcConnectionSetup | null>(null);
|
||||
const [connection, setConnection] = useState<PbcConnection>(presets.openai);
|
||||
const [provider, setProvider] = useState<Provider>("openai");
|
||||
const [apiKey, setApiKey] = useState("");
|
||||
const [removeKey, setRemoveKey] = useState(false);
|
||||
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;
|
||||
setConnection(current);
|
||||
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; requestId.current++; };
|
||||
}, [serverId, reset, clearCatalog]);
|
||||
|
||||
const previous = setup?.connection ?? presets.openai;
|
||||
const dirty = !!setup && (connection.apiType !== previous.apiType || connection.baseUrl !== previous.baseUrl
|
||||
|| connection.model !== previous.model || !!apiKey || removeKey);
|
||||
const sameEndpoint = connection.apiType === previous.apiType
|
||||
&& 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;
|
||||
setBusy(true);
|
||||
setSaved(false);
|
||||
setError(null);
|
||||
try {
|
||||
const next = await api.pbcSaveConnection(serverId, { ...connection, apiKey: apiKey || undefined, removeKey });
|
||||
setSetup(next);
|
||||
reset(next);
|
||||
setSaved(true);
|
||||
onSaved();
|
||||
return true;
|
||||
} catch (e) {
|
||||
setError(asUiError(e));
|
||||
return false;
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}, [setup, valid, busy, serverId, connection, apiKey, removeKey, reset, onSaved]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!setup || !dirty) return;
|
||||
onRegisterGuard({ isDirty: () => true, save, discard: () => reset(setup) });
|
||||
return () => onRegisterGuard(null);
|
||||
}, [setup, dirty, save, reset, onRegisterGuard]);
|
||||
|
||||
function changeProvider(value: Provider) {
|
||||
setProvider(value);
|
||||
setConnection(presets[value]);
|
||||
setApiKey("");
|
||||
setRemoveKey(false);
|
||||
setSaved(false);
|
||||
clearCatalog();
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="mt-4 space-y-3 border-t border-line pt-4" aria-labelledby="pbc-connection-heading">
|
||||
<h3 id="pbc-connection-heading" className="font-semibold">{t("mod.pbc.connection")}</h3>
|
||||
{error && <p className="text-sm text-warn" role="alert">{error.human.code === "unknown" ? error.technical : human(error.human).message}</p>}
|
||||
{setup && (
|
||||
<form className="space-y-3" onSubmit={event => { event.preventDefault(); void save(); }}>
|
||||
{!setup.active && <p className="text-sm text-muted">{t("mod.pbc.useConnection")}</p>}
|
||||
<fieldset disabled={busy} className="grid gap-3 sm:grid-cols-2">
|
||||
<label className="space-y-1 text-sm">
|
||||
<span>{t("mod.pbc.provider")}</span>
|
||||
<select className={inputClass} value={provider} onChange={event => changeProvider(event.target.value as Provider)}>
|
||||
<option value="openai">OpenAI</option>
|
||||
<option value="ollama">Ollama</option>
|
||||
<option value="anthropic">Anthropic</option>
|
||||
<option value="compatible">{t("mod.pbc.compatible")}</option>
|
||||
</select>
|
||||
</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); 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); 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); 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>
|
||||
{saved && <p className="text-sm text-ok" role="status">{t("mod.pbc.saved")}</p>}
|
||||
</form>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -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