merge: bring preview/modules-v2 up to date with master (base 0.9.7)

This commit is contained in:
Дмитрий committed 2026-11-03 12:01:47 +05:00
commit 7d062faa1a
327 files changed
+15358 -1098

No files matched your search

+52
View File
@@ -0,0 +1,52 @@
use std::path::Path;
pub fn enabled(dir: &Path) -> coa_core::Result<bool> {
match std::fs::read(dir.join("public-server-browsing.json")) {
Ok(bytes) => Ok(serde_json::from_slice(&bytes)?),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(true),
Err(e) => Err(e.into()),
}
}
pub fn save(dir: &Path, enabled: bool) -> coa_core::Result<()> {
coa_core::fsx::atomic_write_json(&dir.join("public-server-browsing.json"), &enabled)
}
pub fn require_enabled(dir: &Path) -> coa_core::Result<()> {
if enabled(dir)? {
Ok(())
} else {
Err(coa_core::Error::Invalid(
"Public server browsing is disabled in Settings.".into(),
))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn disabled_and_corrupt_preferences_block_browsing() {
let dir = std::env::temp_dir().join(format!(
"coa-browse-prefs-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(&dir).unwrap();
assert!(enabled(&dir).unwrap());
save(&dir, false).unwrap();
assert!(!enabled(&dir).unwrap());
assert!(require_enabled(&dir).is_err());
save(&dir, true).unwrap();
assert!(require_enabled(&dir).is_ok());
let file = dir.join("public-server-browsing.json");
std::fs::write(&file, b"broken").unwrap();
assert!(require_enabled(&dir).is_err());
std::fs::remove_file(file).unwrap();
std::fs::remove_dir(dir).unwrap();
}
}
+72 -8
View File
@@ -72,6 +72,9 @@ pub(crate) fn start(
None
}
};
if let (Some(player), Some(portable)) = (&player, &portable) {
PlayerControl::start_remote_session_sync(player, portable);
}
let host = portable.and_then(|portable| {
let store = match ControlStore::open(&base.join("host")) {
Ok(s) => Arc::new(Mutex::new(s)),
@@ -172,6 +175,7 @@ pub(crate) async fn registry_set_access(
state: State<'_, AppState>,
local_id: String,
existing_only: bool,
allow_portable: bool,
route: Option<String>,
) -> Result<(), ServiceError> {
let rt = state
@@ -179,7 +183,32 @@ pub(crate) async fn registry_set_access(
.clone()
.ok_or_else(|| fail("stopped", "the publishing service did not start"))?;
tauri::async_runtime::spawn_blocking(move || {
rt.set_access(&local_id, existing_only, route.as_deref())
if allow_portable {
if let Some(route) = route.as_deref().filter(|value| !value.trim().is_empty()) {
coa_core::realm_registry::settings::validate_route(route.trim())
.map_err(|e| fail("invalid", e.to_string()))?;
}
let installs = Registry::at(data_dir().join("installs.json"))
.list().map_err(|e| fail("invalid", e.to_string()))?;
let access = coa_core::realm_registry::advert::find_access(
&data_dir().join("portable/realms"), &installs, &local_id,
).ok_or_else(|| fail("invalid", "This realm is no longer installed."))?;
if let Some(root) = &access.root {
coa_core::config::portable::enable(root)
.map_err(|e| fail("invalid", e.to_string()))?;
} else {
let db = access.db().map_err(|e| fail("invalid", e.to_string()))?;
let mut ra = access.ra().map_err(|e| fail("invalid", e.to_string()))?;
let caps = coa_core::portable::realm::profile::probe_capabilities(
&db, Some(&access.data_dir), Some(&mut ra),
&coa_core::portable::extension::ExtensionRegistry::new(),
).map_err(|e| fail("invalid", e.to_string()))?;
if !caps.content.supports(coa_core::portable::capabilities::Feature::RuntimeSessions) {
return Err(fail("invalid", "Enable portable sessions in this external server's core configuration and restart it before allowing portable characters."));
}
}
}
rt.set_access(&local_id, existing_only, allow_portable, route.as_deref())
.map_err(|e| fail("invalid", e.to_string()))
})
.await
@@ -279,12 +308,46 @@ pub(crate) async fn join_realm(
out.status = "incompatible".into();
return Ok(out);
}
let here = pc_bg.claimed_here(&rid_bg).map_err(from_control)?;
if !here.iter().any(|(id, _)| id.to_string() == character) {
// Phase 12.1: Transfer canonical character to remote Host over the encrypted control channel
let owned_realm =
coa_core::realm_registry::settings::load(&data_dir().join("registry"))
.map_err(|e| fail("registry", e.to_string()))?
.realms
.into_iter()
.find(|(_, cfg)| cfg.enabled && cfg.realm_id == Some(rid_bg))
.map(|(local_id, _)| local_id);
if let Some(local_id) = owned_realm {
if let Some(pending) = pc_bg
.pending_remote_sessions()
.map_err(from_control)?
.into_iter()
.find(|pending| pending.character_id.to_string() == character)
{
pc_bg
.leave_idle_remote_session(pending.character_id, &portable)
.map_err(from_control)?;
}
let username = out.username.clone();
portable.call(move |service| {
service.play(&character, &local_id, username.as_deref())
})??;
} else {
if let Some(pending) = pc_bg
.pending_remote_sessions()
.map_err(from_control)?
.into_iter()
.find(|pending| {
pending.character_id.to_string() == character
&& pending.realm_id != rid_bg.to_string()
})
{
pc_bg
.leave_idle_remote_session(pending.character_id, &portable)
.map_err(from_control)?;
}
let char_id_str = character.clone();
let bundle =
portable.call(move |s| s.export_for_remote_transfer(&char_id_str))??;
let remote_realm = rid_bg.to_string();
let (bundle, session, revision) = portable
.call(move |s| s.prepare_remote_transfer(&char_id_str, &remote_realm))??;
if bundle.ruleset.as_str() != detail.ruleset.as_str() {
ch.close();
return Err(fail(
@@ -298,11 +361,12 @@ pub(crate) async fn join_realm(
}
let cuuid = bundle.character_id.as_uuid();
let _outcome = pc_bg
.transfer_character(
.transfer_owned_character(
&mut ch,
session,
cuuid,
bundle.ruleset.as_str(),
1,
revision,
&bundle.payload,
bundle.content_hash,
bundle.collections,
+223 -64
View File
@@ -5,7 +5,9 @@ use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
mod browse_preferences;
mod docker_install;
mod window_preferences;
use coa_core::backup::{self, Kind, RecoveryPoint, Trigger, VerifyReport};
use coa_core::config::{self, Scope, SettingsView};
@@ -28,6 +30,16 @@ use tauri::{AppHandle, Emitter, Manager, State};
mod control_cmds;
/// Informational release notes only; never used to select or authorize an update.
#[tauri::command]
async fn release_history(component: String, target: Option<String>) -> std::result::Result<Value, String> {
tauri::async_runtime::spawn_blocking(move || {
coa_core::release_history::load_for_target(&component, &data_dir().join("release-history"), target.as_deref())
})
.await
.map_err(|e| e.to_string())?
}
struct AppState {
registry: Registry,
/// Installation ids with a start/stop currently running (one action at a time per server).
@@ -291,10 +303,39 @@ fn installation_source(custom: Option<String>) -> Result<Source> {
.ok()
.filter(|value| !value.trim().is_empty())
});
select_installation_source(custom, || update_source(None))
}
fn select_installation_source(
custom: Option<String>,
latest: impl FnOnce() -> Result<Source>,
) -> Result<Source> {
if custom.is_some() {
return Ok(package_source(custom));
}
Ok(Source::Installation(Box::new(update_source(None)?)))
Ok(Source::Installation(Box::new(latest()?)))
}
#[cfg(test)]
mod installation_source_tests {
use super::*;
#[test]
fn fresh_install_uses_the_selected_current_release_full_image() {
let source = select_installation_source(None, || {
Ok(Source::Url("https://example.test/releases/current".into()))
}).unwrap();
assert!(matches!(source, Source::Installation(inner)
if matches!(*inner, Source::Url(ref url) if url.ends_with("/current"))));
}
#[test]
fn unavailable_current_release_does_not_fall_back_to_an_old_base() {
let result = select_installation_source(None, || {
Err(Error::PackageNotPublished("current unavailable".into()))
});
assert!(matches!(result, Err(Error::PackageNotPublished(_))));
}
}
#[derive(Serialize)]
@@ -615,7 +656,22 @@ async fn start_server(
})
.await;
let _ = tauri::async_runtime::spawn_blocking(move || {
meta_dir(&root).and_then(|m| coa_core::friends::reapply(&root, &m))
let meta = meta_dir(&root)?;
coa_core::friends::reapply(&root, &meta)?;
// A world switched on after the server was opened to friends has no firewall rule yet. Rules are only
// added when missing (one Windows confirmation); a refusal must not undo a start that worked.
if platform::flavor() == Flavor::Repack
&& coa_core::friends::load(&meta).mode != coa_core::friends::Mode::Local
{
let extra = coa_core::realms::state(&root)?.extra_world_ports();
if let Err(e) = coa_core::firewall::ensure_rules_with_extra(
&layout::read_ports(&root),
&extra,
) {
tracing::warn!("firewall rules for the running worlds were not added: {e}");
}
}
Ok::<(), Error>(())
})
.await;
}
@@ -623,6 +679,16 @@ async fn start_server(
Ok(out)
}
#[tauri::command]
async fn force_stop_server(
state: State<'_, AppState>,
id: String,
) -> std::result::Result<DriverOutcome, UiError> {
let root = path_of(&state, &id)?;
let _guard = BusyGuard::acquire(&state, &id)?;
blocking(move || driver::force_stop(&root)).await
}
#[tauri::command]
async fn stop_server(
state: State<'_, AppState>,
@@ -1029,14 +1095,10 @@ async fn create_account(
password: String,
administrator: bool,
) -> std::result::Result<(), UiError> {
let _guard = BusyGuard::acquire(&state, &id)?;
let root = path_of(&state, &id)?;
blocking(move || {
coa_core::ra::validate_account(&username, &password)?;
let mut ra = Ra::connect(&root)?;
ra.create_account(&username, &password)?;
if administrator {
ra.make_administrator(&username)?;
}
coa_core::accounts::create(&root, &username, &password, administrator)?;
tracing::info!(%username, administrator, "account created");
Ok(())
})
@@ -1996,6 +2058,34 @@ fn client_of(root: &std::path::Path) -> Result<(PathBuf, InstallMeta, Option<Pat
Ok((dir, meta, Some(client)))
}
#[tauri::command]
fn client_graphics(
state: State<'_, AppState>,
id: String,
) -> std::result::Result<coa_core::client_graphics::Graphics, UiError> {
Ok(coa_core::client_graphics::status(
&client_context(&state, &id)?.require()?,
)?)
}
#[tauri::command]
fn client_set_graphics(
state: State<'_, AppState>,
id: String,
name: String,
disabled: bool,
) -> std::result::Result<coa_core::client_graphics::Graphics, UiError> {
let job = state.client_cancel.lock().unwrap();
if job.is_some() {
return Err(Error::Invalid("Wait for the client operation to finish.".into()).into());
}
Ok(coa_core::client_graphics::set(
&client_context(&state, &id)?.require()?,
&name,
disabled,
)?)
}
#[tauri::command]
fn client_info(
state: State<'_, AppState>,
@@ -2491,7 +2581,7 @@ async fn report_context(
.into_iter()
.flatten()
.collect::<Vec<String>>()
.join(" · ");
.join(" В· ");
Ok(ReportContext {
manager_version: coa_core::MANAGER_VERSION.to_string(),
windows: windows_version(),
@@ -2604,13 +2694,7 @@ async fn friends_enable(
let ports = layout::read_ports(&root);
let mut note = None;
let realms = coa_core::realms::state(&root)?;
let extra: Vec<u16> = [
realms.secondary_world_port.filter(|_| realms.simultaneous),
realms.reborn_world_port.filter(|_| realms.with_reborn),
]
.into_iter()
.flatten()
.collect();
let extra = realms.extra_world_ports();
let host = match mode {
Mode::Local => "127.0.0.1".to_string(),
Mode::Lan => coa_core::net::resolve_lan_host(lan_address_override.as_deref(), coa_core::net::lan_ip())?,
@@ -2639,7 +2723,7 @@ async fn friends_enable(
friends::save(&meta, &settings)?;
let running = coa_core::process::observe(&root, &ports).world.state == coa_core::process::ServiceState::Running;
if running {
friends::apply_realm_address(&root, &host)?;
friends::apply_realm_address(&root, &settings)?;
}
Ok(FriendsResult { host, restart_required: changed && running, note })
})
@@ -3129,49 +3213,68 @@ async fn preview_check_updates(
.await
}
#[tauri::command]
fn manager_installing(enabled: bool) {
QUIT_REQUESTED.store(enabled, std::sync::atomic::Ordering::SeqCst);
}
#[tauri::command]
fn close_manager(app: AppHandle) -> std::result::Result<(), UiError> {
if window_preferences::close_to_tray(&data_dir()).unwrap_or(false) {
QUIT_REQUESTED.store(false, std::sync::atomic::Ordering::SeqCst);
if let Some(window) = app.get_webview_window("main") {
window.hide().map_err(|e| Error::Invalid(e.to_string()))?;
}
} else {
QUIT_REQUESTED.store(true, std::sync::atomic::Ordering::SeqCst);
app.exit(0);
}
Ok(())
}
#[tauri::command]
fn close_to_tray() -> std::result::Result<bool, UiError> {
Ok(window_preferences::close_to_tray(&data_dir())?)
}
#[tauri::command]
fn set_close_to_tray(enabled: bool) -> std::result::Result<(), UiError> {
Ok(window_preferences::save(&data_dir(), enabled)?)
}
fn show_main_window(app: &AppHandle) {
let handle = app.clone();
if let Err(error) = app.run_on_main_thread(move || {
if let Some(window) = handle.get_webview_window("main") {
let result = window
.unminimize()
.and_then(|_| window.show())
.and_then(|_| window.set_focus());
if let Err(error) = result {
tracing::error!(%error, "Could not restore the Manager window");
}
} else {
tracing::error!("The Manager main window is missing");
}
}) {
tracing::error!(%error, "Could not schedule Manager window restoration");
}
}
static QUIT_REQUESTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub fn run() {
let dir = data_dir();
let _ = coa_core::logging::init(&dir.join("logs").join("manager.log"));
// Crash safety: recover any unfinished client realmlist overrides from previous abnormal termination
let _ = coa_core::client::revert_realmlist_override(&dir);
let portable = start_portable(&dir);
let (control, host_control) = control_cmds::start(&dir, portable.clone());
let registry = Registry::at(dir.join("installs.json"));
if registry.list().map(|l| l.is_empty()).unwrap_or(true) {
let test_realm_path = std::env::var("COA_TEST_REALM_DIR")
.map(PathBuf::from)
.unwrap_or_else(|_| PathBuf::from(r"C:\games\CoA Server Preview"));
let target_realm = if test_realm_path.join("worldserver.exe").is_file() {
Some(("preview-realm", test_realm_path))
} else {
let spike_path = PathBuf::from(r"C:\games\coa-work\plugin-spike\server-v03");
if spike_path.join("worldserver.exe").is_file() {
Some(("test-realm-v03", spike_path))
} else {
None
}
};
if let Some((name, path)) = target_realm {
let _ = registry.register(name, &path);
}
}
tauri::Builder::default()
.plugin(tauri_plugin_single_instance::init(|app, _, _| {
show_main_window(app)
}))
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_updater::Builder::new().build())
.plugin(tauri_plugin_process::init())
.manage(AppState {
registry,
busy: Mutex::new(HashSet::new()),
install_cancel: Mutex::new(None),
client_cancel: Mutex::new(None),
portable,
realm_registry: start_realm_registry(&dir),
control,
host_control,
})
.invoke_handler(tauri::generate_handler![
release_history,
preview_toolchain_status,
preview_register_test_realm,
preview_build_module,
@@ -3195,6 +3298,7 @@ pub fn run() {
server_status,
start_server,
stop_server,
force_stop_server,
get_settings,
save_settings,
list_presets,
@@ -3262,6 +3366,8 @@ pub fn run() {
remote_connection,
remote_connect,
client_info,
client_graphics,
client_set_graphics,
set_client,
client_realmlist,
client_install_addon,
@@ -3302,6 +3408,12 @@ pub fn run() {
portable_launch,
registry_status,
portable_preflight_remote,
manager_installing,
close_manager,
close_to_tray,
set_close_to_tray,
browse_enabled,
browse_set_enabled,
browse_list,
browse_detail,
module_catalog,
@@ -3322,18 +3434,62 @@ pub fn run() {
])
.on_window_event(|window, event| {
if let tauri::WindowEvent::CloseRequested { api, .. } = event {
api.prevent_close();
let _ = window.hide();
if window.label() != "main" {
return;
}
if window_preferences::close_to_tray(&data_dir()).unwrap_or(false) {
api.prevent_close();
if let Err(error) = window.hide() {
tracing::warn!(%error, "Could not hide the Manager window");
}
} else {
QUIT_REQUESTED.store(true, std::sync::atomic::Ordering::SeqCst);
}
}
})
.setup(|app| {
let dir = data_dir();
// Crash safety: recover any unfinished client realmlist overrides from previous abnormal termination
let _ = coa_core::client::revert_realmlist_override(&dir);
let portable = start_portable(&dir);
let (control, host_control) = control_cmds::start(&dir, portable.clone());
let registry = Registry::at(dir.join("installs.json"));
if registry.list().map(|l| l.is_empty()).unwrap_or(true) {
let test_realm_path = std::env::var("COA_TEST_REALM_DIR")
.map(PathBuf::from)
.unwrap_or_else(|_| PathBuf::from(r"C:\games\CoA Server Preview"));
let target_realm = if test_realm_path.join("worldserver.exe").is_file() {
Some(("preview-realm", test_realm_path))
} else {
let spike_path = PathBuf::from(r"C:\games\coa-work\plugin-spike\server-v03");
if spike_path.join("worldserver.exe").is_file() {
Some(("test-realm-v03", spike_path))
} else {
None
}
};
if let Some((name, path)) = target_realm {
let _ = registry.register(name, &path);
}
}
app.manage(AppState {
registry,
busy: Mutex::new(HashSet::new()),
install_cancel: Mutex::new(None),
client_cancel: Mutex::new(None),
portable,
realm_registry: start_realm_registry(&dir),
control,
host_control,
});
#[cfg(desktop)]
{
use tauri::menu::{Menu, MenuItem};
use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent};
use tauri::Manager;
let show = MenuItem::with_id(app, "show", "Open CoA Server Manager", true, None::<&str>)?;
let show =
MenuItem::with_id(app, "show", "Open CoA Server Manager", true, None::<&str>)?;
let quit = MenuItem::with_id(app, "quit", "Exit", true, None::<&str>)?;
let menu = Menu::with_items(app, &[&show, &quit])?;
@@ -3343,11 +3499,7 @@ pub fn run() {
.show_menu_on_left_click(false)
.on_menu_event(|app, event| match event.id.as_ref() {
"show" => {
if let Some(window) = app.get_webview_window("main") {
let _ = window.show();
let _ = window.unminimize();
let _ = window.set_focus();
}
show_main_window(app);
}
"quit" => {
QUIT_REQUESTED.store(true, std::sync::atomic::Ordering::SeqCst);
@@ -3363,11 +3515,7 @@ pub fn run() {
} = event
{
let app = tray.app_handle();
if let Some(window) = app.get_webview_window("main") {
let _ = window.show();
let _ = window.unminimize();
let _ = window.set_focus();
}
show_main_window(app);
}
});
@@ -3427,6 +3575,7 @@ async fn portable_preflight_remote(
}
fn browse_client() -> std::result::Result<coa_core::realm_registry::BrowseClient, UiError> {
browse_preferences::require_enabled(&data_dir())?;
let settings = coa_core::realm_registry::settings::load(&data_dir().join("registry"))?;
let url = std::env::var("COA_REGISTRY_URL")
.ok()
@@ -3435,6 +3584,16 @@ fn browse_client() -> std::result::Result<coa_core::realm_registry::BrowseClient
Ok(coa_core::realm_registry::BrowseClient::new(&url)?)
}
#[tauri::command]
fn browse_enabled() -> std::result::Result<bool, UiError> {
Ok(browse_preferences::enabled(&data_dir())?)
}
#[tauri::command]
fn browse_set_enabled(enabled: bool) -> std::result::Result<(), UiError> {
Ok(browse_preferences::save(&data_dir(), enabled)?)
}
fn browse_error(e: coa_core::realm_registry::ClientError) -> UiError {
Error::Invalid(e.to_string()).into()
}
+13
View File
@@ -0,0 +1,13 @@
use std::path::Path;
pub fn close_to_tray(dir: &Path) -> coa_core::Result<bool> {
match std::fs::read(dir.join("close-to-tray.json")) {
Ok(bytes) => Ok(serde_json::from_slice(&bytes)?),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(e) => Err(e.into()),
}
}
pub fn save(dir: &Path, enabled: bool) -> coa_core::Result<()> {
coa_core::fsx::atomic_write_json(&dir.join("close-to-tray.json"), &enabled)
}