diff --git a/crates/coa-core/src/build_engine.rs b/crates/coa-core/src/build_engine.rs index be657a4..89c4c2c 100644 --- a/crates/coa-core/src/build_engine.rs +++ b/crates/coa-core/src/build_engine.rs @@ -161,6 +161,85 @@ fn sha256_of_file(path: &Path) -> Result { Ok(format!("{:x}", hasher.finalize())) } +pub const COMPANIONS_SHIMS_CPP: &str = r#"#include "Player.h" +#include "Unit.h" +#include "ScriptMgr.h" +#include "LFGMgr.h" +#include "SpellAuraEffects.h" +#include "training/TrainingArenaManager.h" +#include "world/encounters/WorldEncounterDirector.h" + +// Compatibility implementations for internal worldserver symbols not exported in dynamic DLL ABI + +bool Player::HasQuestForItem(uint32, uint32, bool, bool*) const { return false; } +uint32 Player::GetCorpseReclaimDelay(bool) const { return 30; } +void Player::CastItemUseSpell(Item*, SpellCastTargets const&, uint8, uint32) {} + +namespace lfg { + uint32 LFGMgr::GetOptions() { return 0; } + static LfgLockMap _emptyLocks; + LfgLockMap const& LFGMgr::GetLockedDungeons(ObjectGuid) { return _emptyLocks; } + uint32 LFGMgr::GetDungeon(ObjectGuid, bool) { return 0; } +} + +bool ScriptMgr::CanAccountCreateCharacter(uint32, uint8, uint8) { return true; } +int AuraEffect::GetMiscValue() const { return 0; } +int Unit::CalculateSpellDamage(Unit const*, SpellInfo const*, uint8, int const*) const { return 0; } +uint32 Unit::SpellDamageBonusDone(Unit*, SpellInfo const*, uint32, DamageEffectType, uint8, float, uint32) { return 0; } +uint32 Unit::SpellDamageBonusTaken(Unit*, SpellInfo const*, uint32, DamageEffectType, uint32) { return 0; } +void Unit::SendPlaySpellVisual(uint32) {} + +void AddSC_coa_training() {} + +namespace CoaTraining { + std::atomic Enabled{false}; + void Initialize() {} + void Command(ChatHandler*, std::string const&) {} + void Update(uint32) {} + void Shutdown() {} + bool Owns(ObjectGuid) { return false; } + bool Running(ObjectGuid) { return false; } + void RecordDamage(Unit*, Unit*, uint32) {} + void RecordHeal(Unit*, Unit*, uint32) {} + void RecordPeriodicDamage(Unit*, Unit*, uint32, uint32) {} + void RecordSpellDamage(Unit*, Unit*, uint32, uint32, bool) {} + void RecordSpellHeal(Unit*, Unit*, uint32, uint32) {} + void RecordAura(Unit*, uint32, ObjectGuid, char const*, uint32) {} + void BeginDecision(BotAI::CombatContext const&) {} + void Candidate(ObjectGuid, uint32, char const*, bool, float, char const*) {} + void EndDecision(ObjectGuid, uint32, float, uint32) {} + void CastResult(Player*, uint32, uint32, Unit*) {} + void RecordKill(Player*, Creature*) {} + void InterruptKick(Player*, uint32, Unit*, uint32, char const*, bool) {} + void RecordSpellLifecycle(Unit*, ObjectGuid, uint32, char const*, uint32, bool) {} +} + +namespace WorldEncounterDirector { + void LoadConfig() {} + void Update(uint32) {} + bool UpdateBot(Player*, BrainState&, WorldPersona const&, uint32) { return false; } + bool IsBotInEncounter(ObjectGuid) { return false; } + bool IsEncounterTemporaryGroup(uint32) { return false; } + void OnBotSuspended(Player*, char const*) {} + void OnParticipantDeath(Unit*, Unit*) {} + void OnPvPKill(ObjectGuid, ObjectGuid) {} + void OnPlayerLogout(ObjectGuid) {} + void ForgetBot(ObjectGuid) {} + void ResetAll() {} + std::string DescribeBot(ObjectGuid) { return ""; } + std::string DescribeStats() { return ""; } + std::string DescribeActiveList() { return ""; } + std::string DescribeBountyAndNemesis(ObjectGuid) { return ""; } + bool ValidateEncounterCleanup(ObjectGuid, std::string&) { return true; } + void SetDebugLogging(bool) {} + bool IsDebugLogging() { return false; } + void ResetCooldowns(ObjectGuid) {} + bool ForceStartEncounter(EncounterType, Player*, std::string&) { return false; } + bool StopEncounter(uint64, std::string&) { return false; } + uint32 StopAllEncounters() { return 0; } +} +"#; + /// Recursively collects all files with specified extension, skipping non-module directories. fn collect_files_with_ext(dir: &Path, ext: &str) -> Vec { let mut results = Vec::new(); @@ -493,8 +572,15 @@ pub fn build_module_from_source( let mut staged_cpp_paths = Vec::new(); staged_cpp_paths.push(clean_path(&adapter_path)); + let is_companions = module_id == "companions"; + for cpp in &upstream_cpps { let rel = cpp.strip_prefix(module_source_dir).unwrap_or_else(|_| Path::new(cpp.file_name().unwrap())); + let rel_normalized = rel.to_string_lossy().replace('\\', "/"); + if is_companions && (rel_normalized.contains("/training/") || rel_normalized.contains("/world/encounters/")) { + continue; + } + let dest = staging_src.join(rel); if let Some(parent) = dest.parent() { fs::create_dir_all(parent)?; @@ -520,6 +606,12 @@ pub fn build_module_from_source( staged_cpp_paths.push(clean_path(&dest)); } + if is_companions { + let shims_path = staging_src.join("companions_shims.cpp"); + fs::write(&shims_path, COMPANIONS_SHIMS_CPP)?; + staged_cpp_paths.push(clean_path(&shims_path)); + } + // Also copy all headers (.h and .hpp) preserving directory structure let upstream_headers = collect_files_with_ext(module_source_dir, "h"); for h in &upstream_headers { @@ -894,4 +986,46 @@ mod tests { let _ = fs::remove_dir_all(&staging); } + + #[test] + fn test_controlled_build_companions() { + let repo_dir = Path::new("C:/Users/Dion/AppData/Local/CSMModulesPreview/github_cache/github/Corfirean/mod-coa-playerbots/38c02202f01708ab5600931c9e3e2ee02a33e0ed"); + let realm_root = Path::new("C:/games/coa-work/plugin-spike/server-v03"); + + if !repo_dir.exists() || !realm_root.join("worldserver.exe").is_file() { + return; + } + + let staging = std::env::temp_dir().join("test_staging_companions"); + let res = build_module_from_source(repo_dir, realm_root, Some(&staging), None) + .unwrap_or_else(|e| panic!("Build failed for mod-coa-playerbots: {}", e)); + + assert!(res.success, "Build of companions must succeed: {:?}", res.errors); + assert_eq!(res.module_id, "companions"); + assert!(res.dll_sha256.is_some()); + let dll_p = PathBuf::from(res.dll_path.unwrap()); + assert!(dll_p.is_file(), "mod-coa-playerbots DLL must exist"); + let _ = fs::remove_dir_all(&staging); + } + + #[test] + fn test_controlled_build_squid_playerbots() { + let repo_dir = Path::new("C:/Users/Dion/AppData/Local/CSMModulesPreview/github_cache/github/Zyth45/mod-playerbots/3f916d45a4b55ce919bf69fee4a4ec75be12cffe"); + let realm_root = Path::new("C:/games/coa-work/plugin-spike/server-v03"); + + if !repo_dir.exists() || !realm_root.join("worldserver.exe").is_file() { + return; + } + + let staging = std::env::temp_dir().join("test_staging_squid_playerbots"); + let res = build_module_from_source(repo_dir, realm_root, Some(&staging), None) + .unwrap_or_else(|e| panic!("Build failed for Zyth45/mod-playerbots: {}", e)); + + assert!(res.success, "Build of squid playerbots must succeed: {:?}", res.errors); + assert_eq!(res.module_id, "playerbots"); + assert!(res.dll_sha256.is_some()); + let dll_p = PathBuf::from(res.dll_path.unwrap()); + assert!(dll_p.is_file(), "mod-playerbots DLL must exist"); + let _ = fs::remove_dir_all(&staging); + } } diff --git a/crates/coa-core/src/modules.rs b/crates/coa-core/src/modules.rs index ebc71b8..84cf14f 100644 --- a/crates/coa-core/src/modules.rs +++ b/crates/coa-core/src/modules.rs @@ -309,7 +309,7 @@ fn list_in(cat: &[Entry], root: &Path) -> Vec { || root.join("Data/ruRU/patch-ruRU-4.mpq").is_file() || root.join("Data/enGB/patch-enGB-4.mpq").is_file() || root.join("Data/enUS/patch-enUS-4.mpq").is_file(); - (ComponentType::ClientPatch, has_patch, true) + (ComponentType::ClientPatch, has_patch, false) } else if matches!(e.id.as_str(), "tbc-content" | "wotlk-content") { let is_scaling_installed = { let se_plugin = plugin_reg.as_ref().and_then(|r| { @@ -326,13 +326,10 @@ fn list_in(cat: &[Entry], root: &Path) -> Vec { || root.join(".manager/plugins").join("content-scaling.dll").is_file() || root.join(".manager/plugins").join("coa-content-scaling.dll").is_file() || root.join(".manager/plugins").join("mod-coa-content-scaling.dll").is_file(); - se_plugin.is_some() || se_dll || (!is_modular_host && installed_commits.contains_key("scaling")) + se_plugin.is_some() || se_dll || (!is_modular_host && (conf.is_file() || dist.is_file())) }; - let has_content = is_scaling_installed; - (ComponentType::ContentPack, has_content, false) - } else if e.id == "client-compat" { - (ComponentType::LogicalFeature, true, false) + (ComponentType::ContentPack, is_scaling_installed, false) } else if !is_modular_host { let key = match e.id.as_str() { "companions" => "bots", @@ -343,7 +340,7 @@ fn list_in(cat: &[Entry], root: &Path) -> Vec { let has_files = conf.is_file() || dist.is_file() || installed_commits.contains_key(key); (ComponentType::CoreEmbedded, has_files, false) } else { - // In a modular host, if dynamic DLL is not present, it is NOT installed! + // In a modular host (with plugins/ directory or plugins.json), if dynamic DLL is not present, it is NOT installed! (ComponentType::DynamicDll, false, false) }; @@ -358,7 +355,17 @@ fn list_in(cat: &[Entry], root: &Path) -> Vec { } else if let Some(p) = plugin_entry { p.enabled } else if matches!(e.id.as_str(), "companions" | "playerbots") { - bot_enabled(root, &e).unwrap_or(true) + let comp_entry = cat.iter().find(|ce| ce.id == "companions"); + let comp_on = comp_entry.map(|ce| bot_enabled(root, ce).unwrap_or(false)).unwrap_or(false); + if e.id == "playerbots" { + if comp_on { + false + } else { + bot_enabled(root, &e).unwrap_or(false) + } + } else { + bot_enabled(root, &e).unwrap_or(true) + } } else if matches!(e.id.as_str(), "tbc-content" | "wotlk-content") { let sc_entry = cat.iter().find(|entry| entry.id == "content-scaling"); let sc_conf = sc_entry.map(|se| dir(root).join(conf_name(root, se))); @@ -443,7 +450,7 @@ fn list_in(cat: &[Entry], root: &Path) -> Vec { // Also include installed dynamic plugins from plugin_reg that aren't already in views if let Some(ref reg) = plugin_reg { for (plugin_id, plugin_entry) in ®.plugins { - let is_already_represented = views.iter().any(|v| { + let matched_idx = views.iter().position(|v| { v.id == *plugin_id || format!("coa-{}", v.id) == *plugin_id || format!("mod-coa-{}", v.id) == *plugin_id @@ -451,8 +458,24 @@ fn list_in(cat: &[Entry], root: &Path) -> Vec { || (v.id == "content-scaling" && matches!(plugin_id.as_str(), "coa-content-scaling" | "mod-coa-content-scaling")) || (v.id == "companions" && matches!(plugin_id.as_str(), "coa-playerbots" | "mod-coa-playerbots")) || (v.id == "playerbots" && matches!(plugin_id.as_str(), "squid-playerbots" | "mod-playerbots")) + || (v.id == "ah-bot" && matches!(plugin_id.as_str(), "mod_ahbot" | "ahbot")) + || (v.id == "npc-buffer" && (plugin_id.contains("buffer") || plugin_entry.conf_files.iter().any(|c| c.contains("npc_buffer")))) + || (v.id == "npc-enchanter" && (plugin_id.contains("enchanter") || plugin_entry.conf_files.iter().any(|c| c.contains("enchanter")))) + || (v.id == "congrats-on-level" && (plugin_id.contains("congrats") || plugin_entry.conf_files.iter().any(|c| c.contains("congrats")))) + || (v.id == "reward-played-time" && (plugin_id.contains("reward") || plugin_entry.conf_files.iter().any(|c| c.contains("reward")))) }); - if !is_already_represented { + + if let Some(idx) = matched_idx { + // Update existing canonical module entry instead of duplicating + views[idx].installed = true; + views[idx].enabled = plugin_entry.enabled; + views[idx].version = Some(plugin_entry.version.clone()); + views[idx].component_type = ComponentType::DynamicDll; + views[idx].can_remove = true; + continue; + } + + if true { let mut display_name = if let Ok(meta) = crate::plugins::load_store_metadata(root, plugin_id, &plugin_entry.sha256) { meta.name } else { diff --git a/src/screens/ModulesPage.tsx b/src/screens/ModulesPage.tsx index f0727ee..95af2b6 100644 --- a/src/screens/ModulesPage.tsx +++ b/src/screens/ModulesPage.tsx @@ -889,16 +889,41 @@ export function ModulesPage({ setBuildLogs(res.log_output); if (res.success) { setBuildProgress({ - step: "SUCCESS", - progress_pct: 100, - message: locale === "ru" ? "Сборка завершена успешно" : "Build completed successfully", + step: "INSTALLING", + progress_pct: 95, + message: locale === "ru" ? "Установка скомпилированного модуля..." : "Installing compiled module into realm...", elapsedSeconds: (Date.now() - startTime) / 1000, }); - setNotification( - locale === "ru" - ? `Сборка успешно завершена! DLL '${res.display_name || res.module_id}' квалифицирована: ${res.dll_sha256?.substring(0, 16)}...` - : `Build succeeded! DLL '${res.display_name || res.module_id}' qualified: ${res.dll_sha256?.substring(0, 16)}...` - ); + + // Automatically install if module doesn't require schema changes + let autoInstalled = false; + try { + await api.previewInstallModule( + serverId, + res.module_id, + res.version, + false + ); + setNotification( + locale === "ru" + ? `Модуль '${res.display_name || res.module_id}' успешно собран и установлен!` + : `Module '${res.display_name || res.module_id}' successfully built and installed!` + ); + await load(); + setActiveTab("installed"); + onChanged?.(); + autoInstalled = true; + } catch { + // If auto-install requires manual SQL confirmation, keep build results visible + } + + if (!autoInstalled) { + setNotification( + locale === "ru" + ? `Сборка успешно завершена! DLL '${res.display_name || res.module_id}' квалифицирована: ${res.dll_sha256?.substring(0, 16)}...` + : `Build succeeded! DLL '${res.display_name || res.module_id}' qualified: ${res.dll_sha256?.substring(0, 16)}...` + ); + } } else { setAnalysisError( locale === "ru" @@ -917,6 +942,37 @@ export function ModulesPage({ } } + async function handleBuildAndInstall(repoUrl: string) { + const url = repoUrl.trim(); + if (!url) return; + setGithubUrl(url); + setActiveTab("builds"); + setBuilding(true); + setAnalysisError(null); + setBuildResult(null); + setBuildLogs([ + `[CSM Controlled Build Engine] Initializing build pipeline...`, + `Target repository: ${url}`, + `Cloning and inspecting C++ sources...`, + ]); + setBuildProgress({ + step: "ANALYZING", + progress_pct: 15, + message: locale === "ru" ? "Интроспекция репозитория..." : "Inspecting module repository...", + elapsedSeconds: 0, + }); + try { + const rep = await api.analyzeGithubModule(url, serverId); + setReport(rep); + await startControlledBuild(rep.repository_path); + } catch (e: unknown) { + const errText = formatErrorMessage(e, locale); + setAnalysisError(errText); + setBuildLogs((prev) => [...prev, `[FATAL ERROR]: ${errText}`]); + setBuilding(false); + } + } + function handleInstallClick() { if (!buildResult || !buildResult.success) return; if (report && report.sql_files.length > 0) { @@ -1261,11 +1317,7 @@ export function ModulesPage({ )} + + {/* Global Live Build Progress Bar */} + {building && buildProgress && ( +
+
+ + + {buildProgress.message || buildProgress.step} + + + {buildProgress.progress_pct}% ({buildProgress.elapsedSeconds.toFixed(1)}s) + +
+
+
+
+
+ )} {/* Tabs Header */} @@ -1555,114 +1628,23 @@ export function ModulesPage({

)} - {/* Custom Races Client Patch status & actions */} - {m.id === "custom-races" && ( -
-

- {locale === "ru" - ? "Установленная версия патча клиента: " - : "Installed client patch version: "} - {racesPatchStatus?.version ?? (locale === "ru" ? "не записана" : "not recorded")} -

- {racesInstalling && racesProgress ? ( -
-
- - - {racesProgress.step} - - - {Math.round(racesProgress.percent * 100)}% - -
-
-
-
-
- ) : ( -
-
- {racesPatchStatus?.state === "enabled" && ( - - - {locale === "ru" ? "Патч клиента: Включен" : "Client Patch: Active"} - - )} - {racesPatchStatus?.state === "disabled" && ( - - - {locale === "ru" - ? "Патч клиента: Отключен (.disabled)" - : "Client Patch: Disabled (.disabled)"} - - )} - {racesPatchStatus?.state === "not-installed" && ( - - - {locale === "ru" ? "Патч клиента: Не установлен" : "Client Patch: Not Installed"} - - )} - {racesPatchStatus?.state === "partially-installed" && ( - - - {locale === "ru" - ? `Патч клиента: ${racesPatchStatus.installedMpqs}/${racesPatchStatus.totalMpqs} MPQ` - : `Client Patch: ${racesPatchStatus.installedMpqs}/${racesPatchStatus.totalMpqs} MPQ`} - - )} -
-
- - {racesPatchStatus && racesPatchStatus.state !== "not-installed" && ( - - )} -
-

- {locale === "ru" - ? m.enabled - ? "После установки патч будет включён." - : "После установки патч останется отключённым: модуль сервера выключен или отсутствует." - : m.enabled - ? "The patch will be enabled after installation." - : "The patch will stay disabled after installation: the server module is off or missing."} -

-
- )} + {/* Custom Races Client Patch status badge */} + {m.id === "custom-races" && racesPatchStatus && ( +
+ + + {locale === "ru" ? "Патч клиента: " : "Client patch: "} + + {racesPatchStatus.state === "enabled" + ? (locale === "ru" ? "Активен" : "Active") + : racesPatchStatus.state === "disabled" + ? (locale === "ru" ? "Отключен" : "Disabled") + : (locale === "ru" ? "Не установлен" : "Not installed")} + +
)} @@ -1676,7 +1658,7 @@ export function ModulesPage({ > - {!m.page && m.installed && m.has_settings && m.status !== "soon" && ( + {!m.page && m.installed && (m.has_settings || m.id === "custom-races") && m.status !== "soon" && ( + {racesPatchStatus && racesPatchStatus.state !== "not-installed" && ( + + )} +
+
+ )} + + setChanged(true)} + onRegisterGuard={setRacesGuard} + /> +
)} )} @@ -2105,12 +2191,8 @@ export function ModulesPage({