Compare commits

...
Author SHA1 Message Date
ДмитрийandClaude Sonnet 5.5 bff5248591 feat(companions): the startup limit is a fleet size, so missing companions are created
CoaBots.AutoLogin.MaxCount only makes the server log in companions that already exist: with 50
companions and a limit of 300, 50 came online. The Manager now creates the difference.

- coa-core: fleet_shortfall / queue_fleet_top_up queue one durable pending job per realm for
  limit - existing (at most 2000 per job, the most one server command takes). Nothing is queued
  when the fleet is complete or an unfinished job exists for the realm.
- start_server: after the world is up, each realm whose auto-login is on is topped up before its
  pending job runs (shared reconcile_realm_companions helper). If the existing count cannot be
  read, nothing is created.
- Saving the startup settings of a running server tops up right away (new top_up_startup_fleet
  command); a shortfall above 200 asks for confirmation.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 21:31:32 +05:00
12 changed files with 221 additions and 34 deletions

No files matched your search

@@ -0,0 +1,7 @@
---
area: manager
type: changed
audience: players
title: The startup limit for companions now creates the ones that are missing
---
With 50 companions and a startup limit of 300, the Manager now creates the missing 250 instead of logging in only 50. Companions that exist are never created again. Up to 2000 are created at a time.
+101
View File
@@ -583,6 +583,45 @@ pub fn cancel_pending_job(meta_dir: &Path, realm: &str) -> Result<Option<Compani
Ok(None)
}
/// The most companions a startup fleet can hold (the limit the settings accept).
pub const STARTUP_FLEET_MAX: u32 = 5000;
/// The most companions one creation job asks the server for (a single server command takes at most this many).
pub const FLEET_JOB_MAX: u32 = 2000;
/// Companions still missing so that `limit` of them exist. The startup limit is a fleet size, not an addition: with
/// 50 companions and a limit of 300 only 250 are missing, and with 300 or more nothing is.
pub fn fleet_shortfall(limit: u32, existing: u32) -> u32 {
limit.min(STARTUP_FLEET_MAX).saturating_sub(existing)
}
/// Queue the durable job that creates the companions a realm's startup fleet is missing (at most `FLEET_JOB_MAX`
/// at a time; the rest follows at the next start or save). Returns the new job, or `None` when the fleet is complete
/// or an unfinished job already exists for the realm: that one is carried out instead, because a second job would
/// create the same bots twice.
pub fn queue_fleet_top_up(
meta_dir: &Path,
instance_id: &str,
mode: crate::realms::Mode,
limit: u32,
existing: u32,
) -> Result<Option<CompanionsPendingJob>> {
let missing = fleet_shortfall(limit, existing).min(FLEET_JOB_MAX);
if missing == 0 {
return Ok(None);
}
let realm = mode.name();
if let Some(job) = load_pending_job(meta_dir, realm)? {
if !job.state.is_terminal() {
return Ok(None);
}
}
validate_spawn_request(mode, missing, None, None, None, None)?;
let job = CompanionsPendingJob::new(instance_id, realm, missing, None, None, None, None);
save_pending_job(meta_dir, realm, &job)?;
Ok(Some(job))
}
/// One-time idempotent migration of legacy `companions.pending.json` into `companions.pending.coa.json`.
/// Never creates a duplicate job if `companions.pending.coa.json` already exists.
pub fn migrate_legacy_pending_job(
@@ -1630,3 +1669,65 @@ mod tests {
assert!(validate_spawn_request(Mode::Reborn, 5, Some(60), Some(7), Some(4), None).is_ok());
}
}
#[cfg(test)]
mod fleet_tests {
use super::*;
use crate::realms::Mode;
#[test]
fn the_limit_is_a_fleet_size_not_an_addition() {
assert_eq!(fleet_shortfall(300, 50), 250);
assert_eq!(fleet_shortfall(300, 300), 0);
assert_eq!(fleet_shortfall(300, 450), 0);
assert_eq!(fleet_shortfall(0, 0), 0);
assert_eq!(fleet_shortfall(9000, 0), STARTUP_FLEET_MAX);
}
#[test]
fn only_the_missing_companions_are_queued() {
let dir = tempfile::tempdir().unwrap();
let job = queue_fleet_top_up(dir.path(), "srv", Mode::Coa, 300, 50).unwrap().unwrap();
assert_eq!(job.count, 250);
assert_eq!(job.effective_requested_count(), 250);
assert_eq!(job.realm, "coa");
let saved = load_pending_job(dir.path(), "coa").unwrap().unwrap();
assert_eq!(saved.job_id, job.job_id);
}
#[test]
fn a_complete_fleet_creates_nothing() {
let dir = tempfile::tempdir().unwrap();
assert!(queue_fleet_top_up(dir.path(), "srv", Mode::Coa, 300, 300).unwrap().is_none());
assert!(queue_fleet_top_up(dir.path(), "srv", Mode::Coa, 300, 1000).unwrap().is_none());
assert!(load_pending_job(dir.path(), "coa").unwrap().is_none());
}
#[test]
fn an_unfinished_job_is_not_doubled_but_a_finished_one_is_replaced() {
let dir = tempfile::tempdir().unwrap();
let first = queue_fleet_top_up(dir.path(), "srv", Mode::Coa, 300, 50).unwrap().unwrap();
assert!(queue_fleet_top_up(dir.path(), "srv", Mode::Coa, 400, 50).unwrap().is_none());
assert_eq!(load_pending_job(dir.path(), "coa").unwrap().unwrap().job_id, first.job_id);
cancel_pending_job(dir.path(), "coa").unwrap();
let second = queue_fleet_top_up(dir.path(), "srv", Mode::Coa, 400, 50).unwrap().unwrap();
assert_ne!(second.job_id, first.job_id);
assert_eq!(second.count, 350);
}
#[test]
fn one_job_never_asks_for_more_than_a_server_command_takes() {
let dir = tempfile::tempdir().unwrap();
let job = queue_fleet_top_up(dir.path(), "srv", Mode::Coa, 5000, 0).unwrap().unwrap();
assert_eq!(job.count, FLEET_JOB_MAX);
}
#[test]
fn realms_keep_separate_jobs() {
let dir = tempfile::tempdir().unwrap();
queue_fleet_top_up(dir.path(), "srv", Mode::Coa, 100, 0).unwrap().unwrap();
let reborn = queue_fleet_top_up(dir.path(), "srv", Mode::Reborn, 40, 10).unwrap().unwrap();
assert_eq!(reborn.count, 30);
assert_eq!(load_pending_job(dir.path(), "coa").unwrap().unwrap().count, 100);
}
}
+89 -32
View File
@@ -2,7 +2,7 @@
//! registry; the frontend can never ask the backend to touch an arbitrary path (scan is read-only).
use std::collections::HashSet;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
mod browse_preferences;
@@ -597,6 +597,91 @@ async fn run_verb(
.map_err(Into::into)
}
/// Creates the companions a realm's startup fleet is missing (when its auto-login is on and its world runs) and
/// carries out the realm's pending companion job. Returns how many companions were queued to top the fleet up.
fn reconcile_realm_companions(
root: &Path,
meta: &Path,
instance_id: &str,
mode: coa_core::realms::Mode,
top_up: bool,
) -> Result<u32> {
let target = coa_core::multiworld::resolve_bot_operation_target(root, mode)?;
let mut queued = 0;
if top_up && target.running {
match queue_startup_fleet(root, meta, instance_id, mode, &target.world_root) {
Ok(n) => queued = n,
Err(e) => tracing::warn!("startup fleet of realm {} was not topped up: {e}", mode.name()),
}
}
let r_snap = root.to_path_buf();
let chars_db = target.chars_db;
let r_ra = root.to_path_buf();
coa_core::companions::process_pending_job_with(
meta,
mode,
instance_id,
target.running,
|since_guid| {
let admin_db = coa_core::db::Db::from_repack(&r_snap, coa_core::db::Account::Admin)?;
let _ = coa_core::companions::ensure_templates_for_schema(&admin_db, chars_db);
coa_core::companions::query_bot_db_snapshot(&r_snap, &admin_db, chars_db, since_guid)
},
|delta, job| {
let mut ra = Ra::connect_target(&r_ra, Some(mode))?;
if let Some(lvl) = job.level {
ra.spawn_custom(delta, lvl, job.class_id, job.spec_id, job.build_id.as_deref())
} else {
ra.spawn_bots(delta)
}
},
)?;
Ok(queued)
}
/// Queues the job that creates the companions missing from a realm's startup fleet. The realm's auto-login limit is
/// the fleet size: companions that exist already count, so only the difference is created. Nothing is created when
/// the number of existing companions cannot be read.
fn queue_startup_fleet(
root: &Path,
meta: &Path,
instance_id: &str,
mode: coa_core::realms::Mode,
world_root: &Path,
) -> Result<u32> {
let cfg = config::load(world_root, Scope::Bots)?;
let value = |key: &str| cfg.settings.iter().find(|s| s.meta.key == key).map(|s| s.value.clone());
let on = value("CoaBots.AutoLoginOnStartup").and_then(|v| v.as_bool()).unwrap_or(false);
let limit = value("CoaBots.AutoLogin.MaxCount").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
if !on || limit == 0 {
return Ok(0);
}
let existing = coa_core::population::query_for_realm(root, mode)?.bots_total;
let job = coa_core::companions::queue_fleet_top_up(meta, instance_id, mode, limit, existing)?;
Ok(job.map_or(0, |j| j.count))
}
/// After the startup fleet settings are saved: create the companions the fleet is missing right away when the realm's
/// world is running (otherwise it happens at the next start). Returns how many were queued.
#[tauri::command]
async fn top_up_startup_fleet(
state: State<'_, AppState>,
id: String,
realm: Option<coa_core::realms::Mode>,
) -> std::result::Result<u32, UiError> {
let root = path_of(&state, &id)?;
let _guard = BusyGuard::acquire(&state, &id)?;
blocking(move || {
if coa_core::realms::guard_module(&root, "companions").is_err() {
return Ok(0);
}
let meta = meta_dir(&root)?;
let mode = realm.unwrap_or_else(|| coa_core::realms::view(&root).map(|v| v.active).unwrap_or_default());
reconcile_realm_companions(&root, &meta, &id, mode, true)
})
.await
}
#[tauri::command]
async fn start_server(
state: State<'_, AppState>,
@@ -643,37 +728,8 @@ async fn start_server(
coa_core::realms::Mode::Wildcard,
coa_core::realms::Mode::Reborn,
] {
let target = match coa_core::multiworld::resolve_bot_operation_target(&r, mode) {
Ok(t) => t,
Err(e) => {
tracing::warn!("cannot resolve target for realm {}: {e}", mode.name());
continue;
}
};
let r_snap = r.clone();
let chars_db = target.chars_db;
let r_ra = r.clone();
let res = coa_core::companions::process_pending_job_with(
&meta,
mode,
&instance_id,
target.running,
|since_guid| {
let admin_db = coa_core::db::Db::from_repack(&r_snap, coa_core::db::Account::Admin)?;
let _ = coa_core::companions::ensure_templates_for_schema(&admin_db, chars_db);
coa_core::companions::query_bot_db_snapshot(&r_snap, &admin_db, chars_db, since_guid)
},
|delta, job| {
let mut ra = Ra::connect_target(&r_ra, Some(mode))?;
if let Some(lvl) = job.level {
ra.spawn_custom(delta, lvl, job.class_id, job.spec_id, job.build_id.as_deref())
} else {
ra.spawn_bots(delta)
}
},
);
if let Err(e) = res {
tracing::warn!("pending companions for realm {} failed during reconciliation: {e}", mode.name());
if let Err(e) = reconcile_realm_companions(&r, &meta, &instance_id, mode, true) {
tracing::warn!("companions for realm {} failed during start-up: {e}", mode.name());
}
}
Ok(())
@@ -3337,6 +3393,7 @@ pub fn run() {
report_targets,
companion_sizes,
add_companions,
top_up_startup_fleet,
get_wildcard_archetypes,
remote_connection,
remote_connect,
+1
View File
@@ -69,6 +69,7 @@ export {};
if(cmd==="list_presets"){const pr=args?.scope==="server"?serverPresets:botsPresets;return (pr.presets as any[]).map(p=>({id:p.id,title:p.title,description:p.description}));}
if(cmd==="preview_preset"){const a=args;const sc=a.scope==="server"?serverSchema:botsSchema;const pr=(a.scope==="server"?serverPresets:botsPresets).presets as any[];const p=pr.find(x=>x.id===a.preset)??{id:a.preset??"defaults",title:"Recommended defaults",description:"Every setting returns to its default value."};const st=(sc.settings as any[]).filter(x=>x.type==="int"||x.type==="float"||x.type==="enum").slice(0,3);return {id:p.id,title:p.title,description:p.description,changes:st.map(x=>({key:x.key,title:x.title,from:x.default,to:x.type==="enum"?(x.options?.[1]?.value??x.default):(Number(x.default)||1)*2,dangerous:false}))};}
if(cmd==="companion_sizes") return {hardware:{cores:16,ram_gb:31,free_ram_gb:12},sizes:[{id:"small",title:"Small",bots:50,warning:null},{id:"medium",title:"Medium",bots:250,warning:null},{id:"large",title:"Large",bots:500,warning:"500 companions may need more CPU and memory than this computer has (8 cores, 16 GB)."}]};
if(cmd==="top_up_startup_fleet") return 0;
if(cmd==="add_companions"){const base=(window as any).__bots??85;(window as any).__target=base+args.count;return {spawned:"queued",created:null,baseline:base};}
if(cmd==="check_update") return {from_version:(window as any).__updated?"0.261028.83":"0.261026.81",to_version:"0.261028.83",items:[],conflicts:[],migrations:5,pending_migrations:(window as any).__updated?0:5,download_bytes:6000000};
if(cmd==="apply_update"){const w=window as any;for(let i=1;i<=8;i++){await new Promise((r: any)=>setTimeout(r,700));(w.__handlers?.["update-progress"]??[]).forEach((h: any)=>h({event:"update-progress",id:1,payload:{step:i<4?"Downloading the update":i<7?"Applying the update":"Finishing",percent:i*12}}));}(window as any).__updated=true;return {txn:{state:"committed",to_version:"0.261028.83"},migrations:null};}
+2
View File
@@ -597,6 +597,8 @@ const de: Partial<Record<keyof typeof en, string>> = {
"comp.startCount": "Wie viele sich anmelden",
"comp.startSave": "Speichern",
"comp.startSaved": "Gespeichert. Gilt ab dem nächsten Serverstart.",
"comp.startTopUp": "Gespeichert. {n} weitere Begleiter werden erstellt, damit {max} existieren; die übrigen gibt es schon.",
"comp.startTopUpConfirm": "{n} weitere Begleiter erstellen, damit {max} existieren? Vorhandene werden nicht erneut erstellt.",
"comp.startHint": "Bots, die sich nicht anmelden, bleiben gespeichert und können später online gebracht werden.",
"comp.startInvalid": "Gib eine ganze Zahl von 0 bis 5000 ein.",
+2
View File
@@ -696,6 +696,8 @@ const en = {
"comp.startCount": "How many log in",
"comp.startSave": "Save",
"comp.startSaved": "Saved. It applies the next time the server starts.",
"comp.startTopUp": "Saved. Creating {n} more companions so that {max} exist; the others already exist.",
"comp.startTopUpConfirm": "Create {n} more companions so that {max} exist? Companions that already exist are not created again.",
"comp.startHint": "Bots that do not log in stay saved and can be brought online later.",
"comp.startInvalid": "Enter a whole number from 0 to 5000.",
+2
View File
@@ -597,6 +597,8 @@ const es: Partial<Record<keyof typeof en, string>> = {
"comp.startCount": "Cuántos inician sesión",
"comp.startSave": "Guardar",
"comp.startSaved": "Guardado. Se aplica la próxima vez que se inicie el servidor.",
"comp.startTopUp": "Guardado. Se crean {n} compañeros más para que existan {max}; los demás ya existen.",
"comp.startTopUpConfirm": "¿Crear {n} compañeros más para que existan {max}? Los que ya existen no se crean de nuevo.",
"comp.startHint": "Los bots que no inician sesión quedan guardados y se pueden conectar más tarde.",
"comp.startInvalid": "Introduce un número entero de 0 a 5000.",
+2
View File
@@ -597,6 +597,8 @@ const fr: Partial<Record<keyof typeof en, string>> = {
"comp.startCount": "Combien se connectent",
"comp.startSave": "Enregistrer",
"comp.startSaved": "Enregistré. S’applique au prochain démarrage du serveur.",
"comp.startTopUp": "Enregistré. {n} compagnons de plus sont créés pour qu’il y en ait {max} ; les autres existent déjà.",
"comp.startTopUpConfirm": "Créer {n} compagnons de plus pour qu’il y en ait {max} ? Ceux qui existent déjà ne sont pas recréés.",
"comp.startHint": "Les bots qui ne se connectent pas restent enregistrés et peuvent être mis en ligne plus tard.",
"comp.startInvalid": "Saisissez un nombre entier de 0 à 5000.",
+2
View File
@@ -679,6 +679,8 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"comp.startCount": "Сколько входит",
"comp.startSave": "Сохранить",
"comp.startSaved": "Сохранено. Вступит в силу при следующем запуске сервера.",
"comp.startTopUp": "Сохранено. Создаётся ещё {n} компаньонов, чтобы их стало {max}; остальные уже есть.",
"comp.startTopUpConfirm": "Создать ещё {n} компаньонов, чтобы их стало {max}? Уже существующие заново не создаются.",
"comp.startHint": "Боты, которые не входят, остаются сохранёнными, их можно вывести в сеть позже.",
"comp.startInvalid": "Введите целое число от 0 до 5000.",
+2
View File
@@ -650,6 +650,8 @@ const zh = {
"comp.startCount": "自动登录随从数量",
"comp.startSave": "保存",
"comp.startSaved": "已保存。将在下次服务器启动时生效。",
"comp.startTopUp": "已保存。正在再创建 {n} 个同伴,使总数达到 {max};其余已存在。",
"comp.startTopUpConfirm": "再创建 {n} 个同伴,使总数达到 {max}?已存在的不会重复创建。",
"comp.startHint": "未登录的随从仍保留在数据库中,随时可在需要时手动调出上线。",
"comp.startInvalid": "请输入 0 到 5000 之间的整数。",
+2
View File
@@ -584,6 +584,8 @@ export const api = {
invoke<{ txn: UpdateTxn; preexisting_character_count?: number }>("apply_update", { id, source: source ?? null, resolutions }),
rollbackUpdate: (id: string, txn: string) => invoke<UpdateTxn>("rollback_update", { id, txn }),
retryUpdateValidation: (id: string, txn: string) => invoke<UpdateTxn>("retry_update_validation", { id, txn }),
/** Creates the companions the startup fleet is missing (the limit is a fleet size). Returns how many were queued. */
topUpStartupFleet: (id: string, realm?: RealmMode) => invoke<number>("top_up_startup_fleet", { id, realm: realm ?? null }),
population: (id: string, realm?: RealmMode) => invoke<Population | null>("get_population", { id, realm: realm ?? null }),
stopSpawning: (id: string, realm?: RealmMode) => invoke<{ count: number }>("companions_stop_spawning", { id, realm: realm ?? null }),
takeOffline: (id: string, realm?: RealmMode) => invoke<{ count: number }>("companions_take_offline", { id, realm: realm ?? null }),
+9 -2
View File
@@ -305,11 +305,18 @@ export function CompanionsCard({ serverId }: { serverId: string }) {
setError(null);
setStartNote(null);
try {
// The limit is a fleet size: companions that exist count, only the missing ones are created.
const missing = autoOn && running && isViewingActiveRealm && pop ? Math.max(0, maxNum - pop.bots_total) : 0;
if (missing > 200 && !window.confirm(t("comp.startTopUpConfirm", { n: Math.min(missing, 2000), max: maxNum }))) {
setStartBusy(false);
return;
}
await api.save(serverId, "bots", {
"CoaBots.AutoLoginOnStartup": autoOn,
"CoaBots.AutoLogin.MaxCount": maxNum,
});
setStartNote(t("comp.startSaved"));
const queued = autoOn && running ? await api.topUpStartupFleet(serverId, activeServerRealm) : 0;
setStartNote(queued > 0 ? t("comp.startTopUp", { n: queued, max: maxNum }) : t("comp.startSaved"));
} catch (e) {
setError(asUiError(e));
} finally {
@@ -781,7 +788,7 @@ export function CompanionsCard({ serverId }: { serverId: string }) {
Persistent Startup Fleet
</h3>
<p className="text-xs text-muted">
Configure how many bots automatically log into the world whenever the server launches.
The server keeps this many companions. At every start the ones that exist log in, and only the missing ones are created.
</p>
<div className="flex flex-wrap items-center gap-4 text-sm">