Compare commits

...
Author SHA1 Message Date
Дмитрий dad10d8a5d Integrate settings and release history for Manager 0.9.4 2026-10-29 16:10:43 +05:00
Corfirean b33821e7eb Record reviewed Manager 0.9.3 release notes 2026-10-29 10:33:27 +05:00
Corfirean 1288a84da2 Merge pull request #184 from Corfirean/fix/world-startup-deadline
Release Manager 0.9.3 with slow world startup recovery
2026-10-29 10:15:48 +05:00
Дмитрий e7b76137d1 Prepare Manager 0.9.3 and verify platform-specific realm restriction 2026-10-29 10:07:33 +05:00
Дмитрий 7bb0ea9472 Wait for slow CoA worlds before update rollback 2026-10-29 08:33:11 +05:00
Дмитрий 1dab6154c7 Record reviewed 0.9.2 notes and experimental notice 2026-10-28 23:22:07 +05:00
github-actions[bot] 06a6302732 Update published Manager changelog 2026-10-28 18:20:57 +00:00
Corfirean 65631450ff Merge pull request #181 from Corfirean/fix/manager-092-issues
Manager 0.9.2: database startup, recovery and CoA settings
2026-10-28 23:20:11 +05:00
Дмитрий 2d9c6a65bb Recover safely when rollback restores a legacy world launcher 2026-10-28 22:57:00 +05:00
Дмитрий ce83f04d9d Prepare Manager 0.9.2 with database startup and configuration fixes 2026-10-28 22:17:26 +05:00
Corfirean 81f031b30f Keep experimental notice in Manager 0.9.1 hotfix notes 2026-10-28 18:21:36 +05:00
github-actions[bot] ee3ca2c517 Update published Manager changelog 2026-10-28 13:20:54 +00:00
Corfirean 50e858dcd5 Merge pull request #179 from Corfirean/fix/update-preexisting-character-starts
Manager 0.9.1 hotfix: preserve existing character gaps during server updates
2026-10-28 18:19:47 +05:00
Дмитрий 8bbf16ed4f Prepare Manager 0.9.1 hotfix without settings redesign 2026-10-28 17:46:38 +05:00
Дмитрий 324e9810cc Compare character start gaps against a saved pre-update baseline 2026-10-28 17:40:42 +05:00
Дмитрий a8ab201d7d Document required changelog translation preparation 2026-10-28 16:39:16 +05:00
Дмитрий 733d73ef76 Keep window density stable and group update and launch actions 2026-10-28 15:42:47 +05:00
Дмитрий 5525325160 Group Manager settings and add translated release history 2026-10-28 15:26:01 +05:00
Дмитрий 1aade1dcf9 Keep experimental portable character notice in Manager 0.9.0 notes 2026-10-28 12:38:12 +05:00
Corfirean 787549237f Merge pull request #173 from Corfirean/prepare/manager-20261028
Prepare Manager 0.9.0 with integrated realm, race and scaling controls
2026-10-28 12:37:13 +05:00
github-actions[bot] 088cd05e4f Update published Manager changelog 2026-10-28 07:36:47 +00:00
Дмитрий dc97095bd6 Prepare Manager 0.9.0 candidate and translate integrated realm controls 2026-10-28 08:25:41 +05:00
Дмитрий c6d8e5554d Integrate Manager features and preserve portable controls in the realm dialog 2026-10-28 08:23:35 +05:00
Дмитрий 0900a4a143 Merge remote-tracking branch 'origin/feat/publish-realms-dialog' into prepare/manager-20261028 2026-10-28 08:22:09 +05:00
Дмитрий eeb102e260 Merge remote-tracking branch 'origin/feat/realms-start-together' into prepare/manager-20261028 2026-10-28 08:22:09 +05:00
Дмитрий ea376a66d3 Merge remote-tracking branch 'origin/feat/progression-modes-setting' into prepare/manager-20261028 2026-10-28 08:22:09 +05:00
Дмитрий 88747c8da1 feat: portable play settings, improved offline messaging, and system tray support 2026-10-28 08:14:36 +05:00
ДмитрийandClaude Sonnet 5.5 8e1eb825df fix: clearer listing states, joining options chosen before publishing
Portable characters are on by default in a new listing; account creation and
portable characters are shown in the publish form (and in publish all) and
saved right after the realm is published.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 18:22:51 +05:00
ДмитрийandClaude Sonnet 5.5 4fcf0dde3f fix: changelog fragment without a byte order mark
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 18:02:54 +05:00
ДмитрийandClaude Sonnet 5.5 e4791fc45c feat: public listing as a realm list with a window, a publish-all button and a chip on each realm card
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 18:02:35 +05:00
Дмитрий f55a9fb42b docs: record new-race availability maintenance requirements 2026-10-27 17:35:14 +05:00
Дмитрий 8ad06fd78a feat(manager): configure per-race character creation 2026-10-27 17:24:50 +05:00
ДмитрийandClaude Sonnet 5.5 55b0087455 feat(modules): choose Parallel or Global scaling progression in module settings
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 15:59:29 +05:00
94 changed files with 6366 additions and 626 deletions

No files matched your search

+2
View File
@@ -25,4 +25,6 @@ jobs:
- run: npm ci
- run: node tools/check-i18n.mjs
- run: npm run build
- run: node --experimental-strip-types --test tools/*.test.mjs
- run: python -B -m unittest discover -s tools -p test_launcher_bridge.py
- run: cargo test --workspace --locked
+3 -1
View File
@@ -70,7 +70,9 @@ jobs:
node-version: 22
- run: npm ci
- name: Tests
run: cargo test --workspace -- --test-threads=1
run: cargo test --workspace --locked -- --test-threads=1
- run: node --experimental-strip-types --test tools/*.test.mjs
- run: python -B -m unittest discover -s tools -p test_launcher_bridge.py
- name: Build and sign (publish only when requested)
id: tauri
uses: tauri-apps/tauri-action@v0
+10
View File
@@ -35,6 +35,16 @@ Every published Manager version, including a clearly marked Pre-release, belongs
CHANGELOG.md and changelog/history.json. Its GitHub release notes use the same reviewed record.
Promotion updates that entry without duplicating it; Manager and server histories remain separate.
Translated release notes are a required preparation step before freezing a new Manager source. Follow the
runbook's "Mandatory translated release notes during preparation" checklist: translate every new reviewed
Manager/server note into Russian, German, French, Spanish and Simplified Chinese in
`src/data/latest-note-translations.json`, keyed by exact canonical English text. Preserve existing translations
and released fragments. Refresh the bundled server-history snapshot from a pinned canonical commit and record
its provenance. Run `node --test tools/release-history.test.mjs`, `node tools/check-i18n.mjs` and `npm run build`;
verify each new record, all six viewer languages, English fallback and offline use. Save source/version and checks
in the handoff. Translations ship with Manager: a server-only release must record the carrying Manager version or
pending translation delivery, without forcing another Manager release or changing already signed installers.
Before preparing or publishing a Manager/server release, read the maintained
[release runbook](https://github.com/Corfirean/coa-server-build/blob/main/docs/server-release.md)
and [build agent instructions](https://github.com/Corfirean/coa-server-build/blob/main/AGENTS.md).
+45
View File
@@ -8,6 +8,51 @@ Published releases and previews. Pre-release entries do not change the stable up
Dates follow GitHub publication (UTC); legacy records retain their archived dates. Newest releases first.
## 0.9.3 — 2026-10-29
**Portable Characters are experimental and may contain bugs.**
- Slow server startup no longer triggers an early update rollback.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.3) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.2...v0.9.3)
## 0.9.2 — 2026-10-28
**Portable Characters are experimental and may contain bugs.**
- New server installation waits for slower database startup.
- Find and edit CoA options in the existing server settings.
- Simultaneous update checks share results or wait their turn.
- Recovery can stop an unfinished world startup after restoring an older launcher.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.2) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.1...v0.9.2)
## 0.9.1 — 2026-10-28
**Portable Characters are experimental and may contain bugs.**
- Existing unsupported character records no longer block unrelated server updates.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.1) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.0...v0.9.1)
## 0.9.0 — 2026-10-28
**Portable Characters are experimental and may contain bugs.**
- Choose Parallel or Global level scaling in module settings.
- Report Content Scaling problems directly to its repository.
- Send custom race problem reports directly to their maintainer.
- Internet sharing restores the LAN address after server restarts.
- Configure custom race availability for new characters.
- Public listing offers every realm that starts together, not just the main one.
- Public listing is a short list of realms with a window for the details.
- Configure profession and defense skill gains in server settings.
- Starting a server sets the character classes of the realm chosen on Overview.
- Start Wildcard and Warcraft Reborn together with Conquest of Azeroth.
- Control portable characters and keep Manager running in the system tray.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.0) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.8.2...v0.9.0)
## 0.8.2 — 2026-10-27
**Portable Characters are experimental and may contain bugs.**
Generated
+3 -3
View File
@@ -586,7 +586,7 @@ dependencies = [
[[package]]
name = "coa-core"
version = "0.8.2"
version = "0.9.4"
dependencies = [
"base64 0.22.1",
"chrono",
@@ -634,7 +634,7 @@ dependencies = [
[[package]]
name = "coa-release"
version = "0.8.2"
version = "0.9.4"
dependencies = [
"chrono",
"coa-core",
@@ -643,7 +643,7 @@ dependencies = [
[[package]]
name = "coa-server-manager"
version = "0.8.2"
version = "0.9.4"
dependencies = [
"coa-control-proto",
"coa-core",
+1 -1
View File
@@ -4,7 +4,7 @@ members = ["crates/coa-core", "crates/coa-release", "crates/coa-registry-proto",
exclude = ["services/coa-registry", "services/coa-registry-e2e", "services/coa-coordinator", "services/coa-relay"]
[workspace.package]
version = "0.8.2"
version = "0.9.4"
edition = "2021"
license = "AGPL-3.0-only"
+228
View File
@@ -0,0 +1,228 @@
# Per-race availability audit
Date: 2026-10-27. This is an internal implementation audit, not a supported-feature guide.
## Frozen sources
Separate `feat/per-race-toggles` branches and checkouts:
| Component | Checkout | Fetched base |
| --- | --- | --- |
| Manager | `C:/games/source/per-race-manager` | `origin/master`, `925a81f` |
| Core | `C:/games/source/per-race-core` | `origin/coa-bots`, `1c658cab46d5057a8972cebd84c840aa6fbc4a91` |
| CoA Companions | `C:/games/source/per-race-companions` | `origin/master`, `6a289fc2230ce9425924ca86dee02d0bb8d3d344` |
| Build | `C:/games/source/per-race-build` | `origin/main`, `89795b6` |
The build runbook explicitly selects `Corfirean/azerothcore-wotlk-coa:coa-bots`, not its `main`.
The old `C:/games/source/server/azerothcore-wotlk-coa` checkout instead tracks jealous-sound upstream
and has local modifications. It must not be used as the feature's release base.
The primary Manager and Companions checkouts also contain unrelated work and remain untouched.
SQUID is a separate repository, `Zyth45/mod-playerbots`, not `Corfirean/mod-coa-playerbots`.
Existing research checkout: `C:/games/source/squid-playerbots`. Its current local branch is
`fix/custom-races-existing-bots`, one commit ahead of `origin/coa`. Build policy selects the highest
stable numeric tag, so that local branch must not silently become the shipped dependency.
## Manager integration points
- `crates/coa-core/src/custom_races.rs`: package version `1.9.2`, release URLs, MPQ/root/addon lists,
hash manifests, client status, install, enable/disable and uninstall.
- `PatchTransaction`, `SavedFile`, `recover_patch_transaction`: shared client-relative journal in
`.coa-races-transaction/journal.json`, saved files and `committed` marker. Uncommitted changes roll back.
Paths use `fsx::safe_join`; file moves handle cross-volume addon locations.
- `patch_lock`: exclusive OS file lock on `.coa-races.lock`. The empty file's existence is normal and
does not prove another operation is active. Do not delete it as a stale-lock workaround.
- Client mutations reject `client::is_running`; reuse this gate and lock for availability changes.
- `patch_files`, `matches_patch`, `preserve_original`: ownership and preservation depend on manifests
and hashes, not just a filename. Availability overlay ownership needs its own verified record.
- `modules/catalog.json`: `custom-races` uses `coa_custom_races.conf` and `CoACustomRaces.Enable`.
Companions use `mod_coa_playerbots.conf` / `CoaBots.Enable`; SQUID uses
`playerbots.conf` / `AiPlayerbot.Enabled`.
- `crates/coa-core/src/modules.rs`: `toggle`, `settings_in`, `save_settings_in` write current module
configuration. Bot switches enforce stopped servers and the existing control lock.
- `src/screens/ModulesPage.tsx`: Custom Races card, master toggle, install/progress/status UI.
- `src/lib/api.ts` and `src-tauri/src/lib.rs`: existing `custom_races_status`,
`custom_races_install`, `custom_races_uninstall`, `custom_races_toggle_client` commands.
There is no per-race command or verified availability status yet.
- `src-tauri/src/lib.rs::play`: local launch reads `realms::state`, calls `client::sync_realm`, then
launches. Remote launch has a separate realmlist override path; it cannot infer a remote race policy.
- `crates/coa-core/src/realms.rs`: modes CoA, Wildcard and Warcraft Reborn; current configs are captured
under `Settings/realm-profiles/<mode>.json`. Use this mechanism rather than a parallel realm store.
Existing bot restrictions for non-CoA modes must remain effective.
- `crates/coa-core/src/clientdl.rs::apply`: manifest-based client updates, `keep_modified`, staging,
preservation of replaced files. No availability-overlay invalidation or rebuild exists today.
### Confirmed reconciliation risk
`custom_races.rs::sync_bot_races_config` writes a replacement `AiPlayerbot.ExcludedBotRaces` value:
recommended full exclusions or experimental `65,72,77,80,81`. It does not preserve arbitrary user
exclusions. `modules.rs` calls it from the master switch and BotsEnable saving; some callers discard
errors. Per-race integration cannot rely on this overwrite behavior.
`playerbots_conf_paths` can also copy a `.dist` file when no active config exists; it is not a purely
read-only discovery API. Status inspection should avoid adding more implicit writes.
## Core gates and bypasses
- `modules/mod-coa-custom-races/src/mod_coa_custom_races.cpp`: `WorldScript` loads the master switch;
`AccountScript::CanAccountCreateCharacter` accepts stock IDs 1–8, 10, 11 or an enabled master switch.
No disabled-ID list is implemented. Stock ID 9 is deliberately not included.
- `modules/mod-coa-custom-races/conf/coa_custom_races.conf.dist`: Enable and BotsEnable exist;
DisabledRaceIds does not.
- `src/server/game/Handlers/CharacterHandler.cpp`: normal character creation invokes
`sScriptMgr->CanAccountCreateCharacter` inside its finalization callback and rejects with
`CHAR_CREATE_DISABLED`. A packet from an unpatched client reaches that gate too.
- `src/server/game/Scripting/ScriptDefines/AccountScript.cpp`: hook aggregation must be preserved.
- `src/server/game/DataStores/DBCStores.cpp::LoadDBCStores`: chooses `DataDir/dbc_races/<file>` if
the master switch is enabled and that file exists, otherwise `DataDir/dbc/<file>`.
Per-race creation policy must not remove DBC rows or change login data.
- `.agents/docs/systems/ascension-character-creation.md`: native client compatibility depends on
`CharBaseInfo.dbc`; race button indices are not RaceIDs. Existing race/class checks must stay intact.
## Both bot systems
### CoA Companions
`module/src/BotSpawnRandom.cpp::GetValidBotRaces` reads the global and bot custom-race switches,
`CoaBots.CustomRaces.Enable`, and both AiPlayerbot/CoaBots exclusion lists. It checks DBC presence.
Its experimental defaults apply only when the combined exclusion set is empty: adding an owner list
to that set would silently remove those defaults. Keep those policies independent.
`CreateBotClone`, `CreateOneRandomBot`, and leveled spawning clone SQL character data directly;
they bypass the account creation hook. Enforce new-character policy at the common clone creation
entry as well as random selection. Preserve existing bots and faction selection via
`Player::TeamIdForRace`.
Additional confirmed callers: `module/src/BotBattlegroundFill.cpp::QueueBotForSide` and
`module/src/BotLfgFill.cpp` call `CreateOneRandomBot` after trying to reuse an existing bot.
The existing-bot reuse path must remain separate from creation restrictions.
`tools/offline_bot_factory.py` is another direct-SQL creation path. Its main loop chooses a
template by class and faction, then copies `template.race` into the new character overrides.
It currently does not read the custom-race creation policy. Reject or filter prohibited
templates before generating new accounts, GUIDs or SQL; do not rewrite their races.
### SQUID Playerbots
`src/PlayerbotAIConfig.cpp` loads `AiPlayerbot.ExcludedBotRaces` and adds
`AiPlayerbot.CrashingBotRaces`; it reads BotsEnable. `src/CoaBotRacePolicy.h` implements
`IsCoaBotRaceAllowed`. `src/Bot/Factory/RandomPlayerbotFactory.cpp::CreateRandomBot` applies
that policy before faction and race/class selection.
The same predicate also appears in `src/Bot/RandomPlayerbotMgr.cpp` and
`src/Bot/PlayerbotMgr.cpp`, including existing-character admission. Do not append owner creation
restrictions globally to this shared exclusion vector: that would also affect existing bots.
The predicate currently does not itself require `CoACustomRaces.Enable`.
`RandomPlayerbotFactory.cpp` calls `Player::Create` directly without the account hook.
Use a creation-only check in this factory, leaving existing-character admission unchanged.
## Portable Characters
Manager import code is under `crates/coa-core/src/portable/realm/`.
`import.rs` validates identity namespaces and race/class start data (`UnknownRaceClass`).
Availability policy must not become an import rejection or an identity rewrite. The inspected
creation hook is in the normal packet handler, not this importer. In the core,
`src/server/coa/CoAPortableImport.cpp` checks `GetPlayerInfo(model.Race, model.Class)` and writes
`model.Race` to the imported character and character cache. It does not invoke the account
creation hook. Preserve this separation. Live compatibility is still untested.
## Client experiment, actual observations
The owner updated `C:/games/Ascension` from 1.9.1 to 1.9.2 during this audit; its manifest now says
`# CoA Custom 1.9.2`. A separate physical client copy is being prepared under
`C:/games/source/per-race-evidence/client`; game assets are outside Git. The copy completed:
25646 files copied, zero failures. The separate server file copy also completed, but has not
been configured or started. No database service has been started for this task.
Read-only MPQ membership probing found ChrRaces in patch-ZZZF, ZZZE, ZZZC, ZZZ, ZZW, ZZV, ZZU,
ZZS, T, M and several locale archives. CharacterCreate.lua has multiple owners too.
The old `mpqprobe.py` precedence model explicitly admits an inference for Ascension multi-letter
archives. Therefore `patch-ZZZF.MPQ` is a candidate source, not runtime-confirmed effective data.
`patch-ZZZZ.MPQ` exists already; no overlay filename has been qualified.
Extracted from `patch-ZZZF.MPQ`:
- WDBC, 95 records, 69 fields, record size 276, string block 2428, total bytes 28668.
- SHA-256 `b78635b08bf0bd63d2898fce97c1fb162c8a9c41632703172eefa88bae79061f`.
- Actual rows: Sethrak 82, Gnoll 83, Saberon 97. Their Flags are 12.
- String block starts with `Hu`, not NUL; imposing an initial empty-string invariant incorrectly
rejects this real table. String boundaries and referenced offsets still need validation.
- Sethrak experiment changes only Flags 12 → 13. All other bytes compare equal.
- One generated MPQ was read back through StormLib; its DBC equals the expected patched bytes.
- The installed `pympq` Python extension crashed during interpreter finalization. The experimental
tool instead uses the installed Unicode StormLib DLL directly. It is not a runtime dependency
proposal for Manager or its users.
`tools/race_availability_poc.py` requires an explicit source archive and creates output only in a new
directory. It does not select an archive order, install an overlay or assert in-game success.
`tools/test_race_availability_poc.py` uses synthetic bytes only.
### Background verification after interactive testing was deferred
The owner requested no screen capture/input and no client/server/MySQL launches while other bot
tests run. These restrictions remain active. The owner reported that the copied client launches;
this does not confirm creation behavior or effective DBC loading.
- 17 DBC/fingerprint tests and 8 synthetic MPQ integration tests pass (25 total, none skipped).
- Native tests use the explicitly selected existing Unicode StormLib DLL, with no new install.
- Output is built and verified in a temporary directory before publishing the offline result folder.
Failures leave no published result; this is not the future client transaction implementation.
- One and fifty disabled races both produce one MPQ. StormLib adds an internal `(listfile)`;
the sole game payload is `DBFilesClient/ChrRaces.dbc`.
- Every referenced localized race-name offset is bounds-checked; invalid UTF-8 is rejected.
- The experimental fingerprint includes original DBC SHA-256, normalized IDs, algorithm version
and explicitly recorded profile. A profile label does not prove client compatibility.
- The real three-race offline experiment is in
`C:/games/source/per-race-evidence/multiple-races-offline/report.json`.
Source MPQ SHA-256: `40eac695cfcafb598b8376f3b9a61ecc037e4d445b87279cfe387a91edad32c3`.
Generated DBC SHA-256: `243fb36837b76ebd6943da574cc095be548b4530be7f06487debea6703db10d3`.
The first copy launch showed a missing-critical-files message and subsequently crashed on exit.
The crash report identifies `AMDXN32.DLL` in the AMD graphics driver at the fault address; this
does not establish the root cause. EXE, Extensions, dinput8, d3d9, dxgi, EsteriaAppearance and
patch-ZZZF hashes matched the primary client during comparison. The experimental overlay was
not installed. No graphics-driver or client-runtime changes were made to work around the crash.
## Reference implementations and update preservation
Inspected read-only reference clones:
- `aspollon/AFK-Realm` at `ea9c5bf691c98cace8cc03c06183c161022946de`.
- `aspollon/mod-custom-races` at `5a8f2ff8a0d494ffadf64e677a438aa7f5a6671b`.
`mod-custom-races/afk-realm.json` declares client patch generation and GlueXML Lua insertion.
`client/CustomRaces.lua` extends and lays out buttons, using race names/files and configured IDs.
This is a reference, not evidence of compatibility with the current CoA/Esteria UI or a reason
to replace CSM's prebuilt-server distribution.
`crates/coa-core/src/config/merge.rs` performs additive `.dist` merging: missing keys are added,
existing user values and unknown keys are retained. A new DisabledRaceIds key should use this
path. Existing realm snapshots already capture module `.conf` files. Neither mechanism currently
coordinates an availability overlay with client update/repair; that remains implementation work.
## Open gates
Update after the owner found the existing Hide Races panel: see
[existing-filter research](docs/PER_RACE_EXISTING_FILTER_RESEARCH.md). The inspected Lua already
supports personal name/index-based hiding, but it is not a realm-scoped RaceID policy. Nine
offline Lua 5.1 probes confirmed key behavior and limitations. Reusing its layout/UI is now a
candidate to investigate before choosing a production DBC implementation. This is not evidence
that the DBC approach failed, and it does not qualify client support.
The owner subsequently confirmed the GlueXML probe: restricted races disappeared from selection
and were grey, unchecked and disabled in Hide Races. The production client integration should
reuse this filter; changing DBC flags is no longer the selected implementation path.
Server controls, strict catalog-bound configuration, the core creation hook and both bot factory
guards are implemented and have passed offline checks and native builds. Existing-bot admission
and user/crashing exclusions remain separate from the new creation policy.
Remaining gates:
1. Integrate automatic client reconciliation, ownership and recovery with realm settings.
2. Qualify client update/repair and shared-client PLAY behavior.
3. Verify live creation rejection/re-enable, existing-character login, imports and both bot systems
when the owner's database test environment becomes available.
Status: **PARTIAL** — server implementation and builds pass; live server acceptance and production
client synchronization remain pending. See docs/PER_RACE_TOGGLES_TESTS.md for exact scope.
No existing character data, production service, release channel, or primary client archive was changed.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Choose Parallel or Global level scaling in module settings
---
Content Scaling progression can now be set to Parallel (Classic over 1 to the level cap, TBC and WotLK over 45 to the cap) or Global (all expansions over 1 to the cap) without editing the config file by hand.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Configure custom race availability for new characters
---
Choose individual races in a compact table inside module settings using the installed server catalog. Saving requires a compatible server build and a stopped server. Client synchronization is not yet automatic.
@@ -0,0 +1,7 @@
---
area: manager
type: changed
audience: admins
title: Public listing is a short list of realms with a window for the details
---
Settings shows one line per realm with its state, and publishing opens a window. Publish all realms at once. Account creation and portable characters are chosen before publishing; portable characters are on by default.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Find and edit CoA options in the existing server settings
---
Search includes the separate CoA configuration, including legacy mount flight. Changes go to the correct file; realm profile controls stay managed by the Manager.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Existing unsupported character records no longer block unrelated server updates
---
Updates compare each affected character with its saved pre-update state. Unchanged older problems are reported as warnings without changing characters. Newly missing race/class data still blocks the update and triggers recovery; schema and identity checks remain enforced.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Recovery can stop an unfinished world startup after restoring an older launcher
---
If the world console is unavailable, stop only the verified recorded world process. Keep MySQL running if ownership or shutdown cannot be confirmed.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: New server installation waits for slower database startup
---
Allow up to five minutes for MySQL to become ready. Failed installations stop their temporary database before cleaning up its files.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Control portable characters and keep Manager running in the system tray
---
Realm access settings can enable portable characters. Closing the window keeps Manager in the tray, with commands to reopen or exit. Offline realm messages explain why players cannot connect.
@@ -0,0 +1,7 @@
---
area: manager
type: changed
audience: admins
title: Settings group updates, startup and maintenance with translated release history
---
Server and Manager keep separate update controls. Read their published changes in one place, including translations of the latest releases in all six interface languages. Saved notes remain available offline. Find public realm controls under Play with friends.
@@ -0,0 +1,7 @@
---
area: manager
type: changed
audience: admins
title: Update and launch without updating share a divided button
---
Server and game client actions each use two adjacent segments of equal height. Both actions remain visible and keep their own availability checks.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Simultaneous update checks share results or wait their turn
---
Repeated checks no longer compete with another foreground or background check in the same Manager window. Maintenance and recovery locks remain enforced.
+7
View File
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Maximizing the window keeps text and controls at a comfortable size
---
The interface no longer enlarges with window width. System display scaling and browser zoom still work, and large action buttons use more compact spacing.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Slow server startup no longer triggers an early update rollback
---
World startup now allows up to 25 minutes with either bot system and waits for both game and console ports within one deadline. Servers that stop during startup still fail immediately.
+87 -1
View File
@@ -123,6 +123,7 @@
"Corfirean/coa-server-manager:20261021-scaling-health-settings.md",
"Corfirean/coa-server-manager:20261021-warcraft-reborn-realm.md",
"Corfirean/coa-server-manager:20261022-custom-races-client.md",
"Corfirean/coa-server-manager:20261022-scaling-progression-modes.md",
"Corfirean/coa-server-manager:20261023-ah-bot-single-switch.md",
"Corfirean/coa-server-manager:20261023-interface-language-coverage.md",
"Corfirean/coa-server-manager:20261023-online-players-exclude-squid-bots.md",
@@ -138,7 +139,23 @@
"Corfirean/coa-server-manager:20261024-remote-refresh.md",
"Corfirean/coa-server-manager:20261025-custom-races-191.md",
"Corfirean/coa-server-manager:20261026-custom-races-192.md",
"Corfirean/coa-server-manager:20261027-merged-database-migration-order.md"
"Corfirean/coa-server-manager:20261027-content-scaling-reports.md",
"Corfirean/coa-server-manager:20261027-custom-races-reports.md",
"Corfirean/coa-server-manager:20261027-internet-lan-address.md",
"Corfirean/coa-server-manager:20261027-merged-database-migration-order.md",
"Corfirean/coa-server-manager:20261027-per-race-server-settings.md",
"Corfirean/coa-server-manager:20261027-public-list-shows-every-running-realm.md",
"Corfirean/coa-server-manager:20261027-public-listing-window.md",
"Corfirean/coa-server-manager:20261027-skill-gain-controls.md",
"Corfirean/coa-server-manager:20261027-start-checks-the-realm-class-setting.md",
"Corfirean/coa-server-manager:20261027-start-wildcard-and-reborn-with-coa.md",
"Corfirean/coa-server-manager:20261028-coa-config-search.md",
"Corfirean/coa-server-manager:20261028-existing-character-update-validation.md",
"Corfirean/coa-server-manager:20261028-legacy-world-shutdown.md",
"Corfirean/coa-server-manager:20261028-mysql-install-startup.md",
"Corfirean/coa-server-manager:20261028-portable-settings-and-tray.md",
"Corfirean/coa-server-manager:20261028-update-check-queue.md",
"Corfirean/coa-server-manager:20261029-slow-world-startup.md"
],
"releases": [
{
@@ -721,6 +738,75 @@
"experimentalFeatures": [
"portable-characters"
]
},
{
"tag": "v0.9.0",
"version": "0.9.0",
"date": "2026-10-28",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.0",
"notes": [
"Choose Parallel or Global level scaling in module settings",
"Report Content Scaling problems directly to its repository",
"Send custom race problem reports directly to their maintainer",
"Internet sharing restores the LAN address after server restarts",
"Configure custom race availability for new characters",
"Public listing offers every realm that starts together, not just the main one",
"Public listing is a short list of realms with a window for the details",
"Configure profession and defense skill gains in server settings",
"Starting a server sets the character classes of the realm chosen on Overview",
"Start Wildcard and Warcraft Reborn together with Conquest of Azeroth",
"Control portable characters and keep Manager running in the system tray"
],
"commit": "dc97095bd6b36d9b5111f04f0cfd88e1fb2ab1f1",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.8.2...v0.9.0",
"experimentalFeatures": [
"portable-characters"
]
},
{
"version": "0.9.1",
"tag": "v0.9.1",
"date": "2026-10-28",
"notes": [
"Existing unsupported character records no longer block unrelated server updates"
],
"experimentalFeatures": [
"portable-characters"
],
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.1",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.0...v0.9.1",
"commit": "8bbf16ed4f14e9b78c680783e4be5d8c580cc06b"
},
{
"tag": "v0.9.2",
"version": "0.9.2",
"date": "2026-10-28",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.2",
"notes": [
"New server installation waits for slower database startup",
"Find and edit CoA options in the existing server settings",
"Simultaneous update checks share results or wait their turn",
"Recovery can stop an unfinished world startup after restoring an older launcher"
],
"commit": "2d9c6a65bbb1e296dc919e4c9e5785ed9d4a070b",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.1...v0.9.2",
"experimentalFeatures": [
"portable-characters"
]
},
{
"tag": "v0.9.3",
"version": "0.9.3",
"date": "2026-10-29",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.3",
"notes": [
"Slow server startup no longer triggers an early update rollback"
],
"commit": "e7b76137d1b22a7596c2b1fa05ca9d12403b99d3",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.2...v0.9.3",
"experimentalFeatures": [
"portable-characters"
]
}
]
}
+220 -48
View File
@@ -1,5 +1,5 @@
//! Every setting of the world server's configuration, for people who want more than the curated list: the documented
//! settings come from `worldserver.conf.dist` (the file that ships with the server and explains each one), the current
//! settings come from `worldserver.conf.dist` and `modules/coa.conf.dist`, the current
//! values from the configuration the next start will use. Anything that holds a password, a port, an address, a folder or
//! the database connection is left out; the Manager owns those.
@@ -10,7 +10,7 @@ use std::path::Path;
use serde::Serialize;
use crate::config::parser::ConfFile;
use crate::config::{take_snapshot, targets, Scope};
use crate::config::{take_snapshot, targets, Scope, Targets};
use crate::error::{Error, Result};
use crate::fsx;
@@ -39,6 +39,14 @@ fn hidden(key: &str) -> bool {
|| k.starts_with("logindatabase.")
|| k.starts_with("worlddatabase.")
|| k.starts_with("characterdatabase.")
|| [
"coa.classmodel",
"coa.realmtype",
"coa.gamemodemask",
"coa.mapclass10towarrior",
"coa.clientbooleanconfigs",
]
.contains(&k.as_str())
|| [
"bindip",
"realmid",
@@ -121,52 +129,85 @@ fn dist_path(root: &Path) -> std::path::PathBuf {
root.join("Core/configs/worldserver.conf.dist")
}
fn sources(root: &Path) -> Result<Vec<(std::path::PathBuf, Targets)>> {
let mut result = vec![(dist_path(root), targets(root, Scope::Server)?)];
let dist = root.join("Core/configs/modules/coa.conf.dist");
if dist.is_file() {
let active = root.join("Core/configs/modules/coa.conf");
result.push((
dist,
Targets {
read: active.clone(),
writes: vec![active],
generated: None,
},
));
}
Ok(result)
}
pub fn list(root: &Path) -> Result<Vec<Item>> {
let dist = fs::read_to_string(dist_path(root)).map_err(|_| {
Error::Invalid(
"The documented settings file (worldserver.conf.dist) was not found on this server."
.into(),
)
})?;
let t = targets(root, Scope::Server)?;
let active = ConfFile::parse_bytes(&fs::read(&t.read)?)?;
Ok(parse_dist(&dist)
.into_iter()
.filter(|(k, _, _)| !hidden(k))
.map(|(key, default, doc)| {
let value = active
.get(&key)
.map(|v| v.trim().to_string())
.unwrap_or_else(|| default.clone());
let changed = value != default;
Item {
key,
value,
default,
doc,
changed,
}
})
.collect())
let mut items = Vec::new();
for (dist_path, t) in sources(root)? {
let dist = fs::read_to_string(&dist_path)?;
let active = ConfFile::parse_bytes(&if t.read.exists() {
fs::read(&t.read)?
} else {
dist.as_bytes().to_vec()
})?;
items.extend(
parse_dist(&dist)
.into_iter()
.filter(|(k, _, _)| !hidden(k))
.map(|(key, default, doc)| {
let value = active
.get(&key)
.map(|v| v.trim().to_string())
.unwrap_or_else(|| default.clone());
let changed = value != default;
Item {
key,
value,
default,
doc,
changed,
}
})
.collect::<Vec<_>>(),
);
}
Ok(items)
}
/// Change settings that exist in the documented file. A value is one line of at most 500 characters. Returns the keys
/// that actually changed; the previous files are snapshotted first (and can be restored from Settings).
pub fn save(root: &Path, meta: &Path, changes: &BTreeMap<String, String>) -> Result<Vec<String>> {
let known: BTreeMap<String, String> =
parse_dist(&fs::read_to_string(dist_path(root)).map_err(|_| {
Error::Invalid("worldserver.conf.dist was not found on this server.".into())
})?)
.into_iter()
.map(|(k, d, _)| (k, d))
.collect();
let t = targets(root, Scope::Server)?;
let _lock = crate::update::operation_lock(meta)?;
crate::update::ensure_recovered(meta)?;
let sources = sources(root)?;
let mut known = BTreeMap::new();
let mut originals: Vec<(std::path::PathBuf, Vec<u8>)> = Vec::new();
let mut confs: Vec<ConfFile> = Vec::new();
for p in &t.writes {
let bytes = fs::read(p)?;
confs.push(ConfFile::parse_bytes(&bytes)?);
originals.push((p.clone(), bytes));
let mut owners = Vec::new();
for (index, (dist, t)) in sources.iter().enumerate() {
let defaults = fs::read(dist)?;
for (key, default, _) in parse_dist(&String::from_utf8_lossy(&defaults)) {
if known.insert(key.clone(), (default, index)).is_some() {
return Err(Error::Invalid(format!(
"{key} is documented in more than one configuration file."
)));
}
}
for p in &t.writes {
let bytes = if p.exists() {
fs::read(p)?
} else {
defaults.clone()
};
confs.push(ConfFile::parse_bytes(&bytes)?);
originals.push((p.clone(), bytes));
owners.push(index);
}
}
let mut changed = Vec::new();
for (key, value) in changes {
@@ -181,10 +222,22 @@ pub fn save(root: &Path, meta: &Path, changes: &BTreeMap<String, String>) -> Res
"The value of {key} must be one line of text."
)));
}
let same = confs.iter().all(|c| match c.get(key) {
Some(v) => v.trim() == value,
None => known[key] == value,
});
let (default, owner) = &known[key];
if default.parse::<f64>().is_ok() && !value.parse::<f64>().is_ok_and(f64::is_finite)
|| key == "CoA.LegacyMountFlight" && !matches!(value, "0" | "1")
{
return Err(Error::Invalid(format!(
"The value of {key} must be a number matching its documented default."
)));
}
let same = confs
.iter()
.zip(&owners)
.filter(|(_, index)| *index == owner)
.all(|(c, _)| match c.get(key) {
Some(v) => v.trim() == value,
None => default == value,
});
if !same {
changed.push((key.clone(), value.to_string()));
}
@@ -192,20 +245,31 @@ pub fn save(root: &Path, meta: &Path, changes: &BTreeMap<String, String>) -> Res
if changed.is_empty() {
return Ok(Vec::new());
}
for c in &mut confs {
for (c, owner) in confs.iter_mut().zip(&owners) {
for (k, v) in &changed {
c.set(k, v, &["Added by CoA Server Manager"]);
if known[k].1 == *owner {
c.set(k, v, &["Added by CoA Server Manager"]);
}
}
}
let texts: Vec<String> = confs.iter().map(ConfFile::to_text).collect();
for text in &texts {
for (text, owner) in texts.iter().zip(&owners) {
let reread = ConfFile::parse(text);
for (k, v) in &changed {
if reread.get(k).map(str::trim) != Some(v.as_str()) {
if known[k].1 == *owner && reread.get(k).map(str::trim) != Some(v.as_str()) {
return Err(Error::Invalid(format!("internal check failed for {k}")));
}
}
}
let affected: std::collections::BTreeSet<_> =
changed.iter().map(|(key, _)| known[key].1).collect();
let (originals, texts): (Vec<_>, Vec<_>) = originals
.into_iter()
.zip(texts)
.zip(owners)
.filter(|(_, owner)| affected.contains(owner))
.map(|(pair, _)| pair)
.unzip();
take_snapshot(
meta,
Scope::Server,
@@ -232,6 +296,114 @@ pub fn save(root: &Path, meta: &Path, changes: &BTreeMap<String, String>) -> Res
mod tests {
use super::*;
#[test]
fn unrelated_saves_do_not_create_coa_files_and_existing_realm_values_are_preserved() {
let d = tempfile::tempdir().unwrap();
let (root, meta) = server(d.path());
let module = root.join("Core/configs/modules");
fs::create_dir_all(&module).unwrap();
fs::write(
module.join("coa.conf.dist"),
"CoA.LegacyMountFlight = 0\nCoA.ClassModel = \"coa\"\n",
)
.unwrap();
save(
&root,
&meta,
&BTreeMap::from([("Rate.Drop.Item.Rare".into(), "1.5".into())]),
)
.unwrap();
assert!(!module.join("coa.conf").exists());
fs::write(
module.join("coa.conf"),
"# Reborn realm\nCoA.ClassModel = \"wcr\"\nCustom.Preserved = 42\n",
)
.unwrap();
assert!(save(
&root,
&meta,
&BTreeMap::from([("CoA.ClassModel".into(), "\"coa\"".into())])
)
.is_err());
save(
&root,
&meta,
&BTreeMap::from([("CoA.LegacyMountFlight".into(), "1".into())]),
)
.unwrap();
let actual = fs::read_to_string(module.join("coa.conf")).unwrap();
assert!(
actual.contains("CoA.ClassModel = \"wcr\"") && actual.contains("Custom.Preserved = 42")
);
assert!(actual.contains("# Reborn realm"));
}
#[test]
fn coa_settings_are_found_saved_to_the_module_and_snapshotted_without_profile_overrides() {
let d = tempfile::tempdir().unwrap();
let (root, meta) = server(d.path());
let module = root.join("Core/configs/modules");
fs::create_dir_all(&module).unwrap();
let defaults = "[worldserver]\n# Mount flight rules\nCoA.LegacyMountFlight = 0\nCoA.ClassModel = \"coa\"\nCoA.RealmType = \"live\"\n";
fs::write(module.join("coa.conf.dist"), defaults).unwrap();
let original_world = fs::read(root.join("Core/configs/worldserver.conf")).unwrap();
let items = list(&root).unwrap();
assert!(items
.iter()
.any(|i| i.key == "CoA.LegacyMountFlight" && i.value == "0"));
assert!(!items
.iter()
.any(|i| i.key == "CoA.ClassModel" || i.key == "CoA.RealmType"));
for value in ["2", "invalid", "1\nInjected = 1"] {
assert!(save(
&root,
&meta,
&BTreeMap::from([("CoA.LegacyMountFlight".into(), value.into())])
)
.is_err());
}
assert!(!module.join("coa.conf").exists());
save(
&root,
&meta,
&BTreeMap::from([
("CoA.LegacyMountFlight".into(), "1".into()),
("Rate.Drop.Item.Rare".into(), "1.5".into()),
]),
)
.unwrap();
assert!(fs::read_to_string(module.join("coa.conf"))
.unwrap()
.contains("CoA.LegacyMountFlight = 1"));
let world = fs::read_to_string(root.join("Core/configs/worldserver.conf")).unwrap();
assert!(!world.contains("CoA.LegacyMountFlight"));
assert!(world.contains("Rate.Drop.Item.Rare = 1.5"));
assert!(!String::from_utf8(original_world)
.unwrap()
.contains("CoA.LegacyMountFlight"));
assert_eq!(
list(&root)
.unwrap()
.iter()
.find(|i| i.key == "CoA.LegacyMountFlight")
.unwrap()
.value,
"1"
);
assert!(!crate::config::list_snapshots(&meta).is_empty());
let saved = crate::config::list_snapshots(&meta).remove(0);
crate::config::restore_snapshot(&meta, &saved.id).unwrap();
assert_eq!(
list(&root)
.unwrap()
.iter()
.find(|i| i.key == "CoA.LegacyMountFlight")
.unwrap()
.value,
"0"
);
}
const DIST: &str = "[worldserver]\r\n\r\n###################\r\n# SECTION\r\n###################\r\n\r\n#\r\n# Rate.Drop.Item.Epic\r\n# Rate.Drop.Item.Rare\r\n# Description: Drop rates by quality.\r\n# Default: 1\r\n#\r\n\r\nRate.Drop.Item.Rare = 1\r\nRate.Drop.Item.Epic = 1\r\n\r\n#\r\n# LoginDatabaseInfo\r\n# Description: secret\r\n#\r\n\r\nLoginDatabaseInfo = \"127.0.0.1;3306;a;b;c\"\r\n\r\n#\r\n# Instance.ResetTimeHour\r\n# Description: Hour of the reset.\r\n# Important: Use 0-23.\r\n# Default: 4\r\n#\r\n\r\nInstance.ResetTimeHour = 4\r\n";
fn server(d: &Path) -> (std::path::PathBuf, std::path::PathBuf) {
@@ -0,0 +1,124 @@
//! Update-only comparison of existing unsupported character starts. Never repairs or deletes rows.
use crate::{db::Db, Error, Result};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct MissingStart {
pub guid: u32,
pub race: u32,
pub class: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Baseline {
pub schema: u32,
pub realms: BTreeMap<String, BTreeSet<MissingStart>>,
}
pub fn parse_missing(text: &str) -> Result<BTreeSet<MissingStart>> {
text.lines()
.map(|line| {
let values = line
.split('\t')
.map(str::parse::<u32>)
.collect::<std::result::Result<Vec<_>, _>>()
.map_err(|_| {
Error::Invalid("Cannot read existing character start identities.".into())
})?;
if values.len() != 3 {
return Err(Error::Invalid(
"Incomplete character start identity.".into(),
));
}
Ok(MissingStart {
guid: values[0],
race: values[1],
class: values[2],
})
})
.collect()
}
pub fn missing(db: &Db) -> Result<BTreeSet<MissingStart>> {
parse_missing(&db.query("SELECT c.guid,c.race,c.class FROM acore_characters.characters c LEFT JOIN acore_world.playercreateinfo p ON p.race=c.race AND p.class=c.class WHERE p.race IS NULL;")?)
}
pub fn capture(db: &Db, root: &Path) -> Result<Baseline> {
let mut realms = BTreeMap::new();
for mode in crate::realms::state(root)?.modes() {
realms.insert(
mode.name().to_owned(),
missing(&db.clone().for_realm(mode))?,
);
}
Ok(Baseline { schema: 1, realms })
}
/// Match identity and race/class, never just totals: one new failure cannot replace an old one.
pub fn introduced(
current: &BTreeSet<MissingStart>,
before: &BTreeSet<MissingStart>,
) -> BTreeSet<MissingStart> {
current.difference(before).copied().collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn old_gaps_are_not_new_character_loss() {
let before = parse_missing("1\t44\t14\n2\t44\t14\n3\t44\t14").unwrap();
assert!(introduced(&before, &before).is_empty());
assert!(introduced(&BTreeSet::new(), &before).is_empty());
let replaced = parse_missing("1\t44\t14\n2\t44\t14\n4\t44\t14").unwrap();
assert_eq!(
introduced(&replaced, &before),
parse_missing("4\t44\t14").unwrap()
);
let changed = parse_missing("1\t44\t15").unwrap();
assert_eq!(introduced(&changed, &before), changed);
assert_eq!(introduced(&before, &BTreeSet::new()), before);
}
#[test]
fn malformed_identity_is_not_silently_ignored() {
for text in ["1\t44", "bad\t44\t14", "1\t44\t14\t0", "1\t44\t-1"] {
assert!(parse_missing(text).is_err());
}
assert!(parse_missing("").unwrap().is_empty());
}
#[test]
fn reported_174_old_records_cannot_mask_one_newly_hidden_character() {
// Reproduce the report's scale without shipping another person's diagnostics or identities.
let before: BTreeSet<_> = (1..=174)
.map(|guid| MissingStart {
guid,
race: 44,
class: 14,
})
.collect();
assert!(introduced(&before, &before).is_empty());
let mut after = before.clone();
after.remove(&MissingStart {
guid: 1,
race: 44,
class: 14,
});
after.insert(MissingStart {
guid: 175,
race: 44,
class: 14,
});
assert_eq!(after.len(), before.len());
assert_eq!(
introduced(&after, &before),
BTreeSet::from([MissingStart {
guid: 175,
race: 44,
class: 14
}])
);
}
}
+32 -1
View File
@@ -111,6 +111,13 @@ pub fn playerbots_conf_paths(root: &Path) -> Vec<PathBuf> {
/// Checks whether playerbots are configured to allow custom races.
/// Returns true if AiPlayerbot.ExcludedBotRaces exists and does not exclude general custom races.
pub fn is_bot_custom_races_allowed(root: &Path) -> Option<bool> {
if let Ok(bytes) = fs::read(root.join("Core/configs/modules/coa_custom_races.conf")) {
if let Ok(conf) = crate::config::parser::ConfFile::parse_bytes(&bytes) {
if let Some(value) = conf.get("CoACustomRaces.BotsEnable") {
return Some(matches!(value.trim().trim_matches('"'), "1" | "true"));
}
}
}
for path in playerbots_conf_paths(root) {
if let Ok(bytes) = fs::read(&path) {
if let Ok(conf) = crate::config::parser::ConfFile::parse_bytes(&bytes) {
@@ -142,6 +149,15 @@ pub fn sync_bot_races_config(root: &Path, allow_custom_races: bool) -> Result<()
for path in playerbots_conf_paths(root) {
if let Ok(bytes) = fs::read(&path) {
if let Ok(mut conf) = crate::config::parser::ConfFile::parse_bytes(&bytes) {
if let Some(value) = conf.get("AiPlayerbot.ExcludedBotRaces") {
let clean = value.trim().trim_matches(['"', '\'']);
let owned = String::from_utf8_lossy(&bytes)
.contains("CoA Custom: races new random bots never get")
&& matches!(clean, EXCLUDED_BOT_RACES_RECOMMENDED | EXCLUDED_BOT_RACES_EXPERIMENTAL);
if !owned {
continue;
}
}
conf.set(
"AiPlayerbot.ExcludedBotRaces",
&format!("\"{excluded}\""),
@@ -1621,7 +1637,7 @@ mod tests {
let temp = tempfile::tempdir().unwrap();
let conf = temp.path().join("Core/configs/modules/playerbots.conf");
fs::create_dir_all(conf.parent().unwrap()).unwrap();
fs::write(&conf, "AiPlayerbot.ExcludedBotRaces = \"\"\n").unwrap();
fs::write(&conf, "AiPlayerbot.Enabled = 1\n").unwrap();
sync_bot_races_config(temp.path(), false).unwrap();
assert_eq!(is_bot_custom_races_allowed(temp.path()), Some(false));
let parsed =
@@ -1639,4 +1655,19 @@ mod tests {
);
}
}
#[test]
fn bot_race_sync_preserves_user_and_crashing_exclusions() {
let temp = tempfile::tempdir().unwrap();
let conf = temp.path().join("Core/configs/modules/playerbots.conf");
fs::create_dir_all(conf.parent().unwrap()).unwrap();
for value in ["", "1,82,97", EXCLUDED_BOT_RACES_RECOMMENDED] {
let original = format!("AiPlayerbot.ExcludedBotRaces = \"{value}\"\nAiPlayerbot.CrashingBotRaces = \"72,77,97\"\n");
fs::write(&conf, &original).unwrap();
sync_bot_races_config(temp.path(), true).unwrap();
assert_eq!(fs::read_to_string(&conf).unwrap(), original);
sync_bot_races_config(temp.path(), false).unwrap();
assert_eq!(fs::read_to_string(&conf).unwrap(), original);
}
}
}
+20 -28
View File
@@ -31,36 +31,17 @@ impl Verb {
}
}
fn timeout(self, root: &Path) -> Duration {
fn timeout(self, _root: &Path) -> Duration {
match self {
Verb::StartAll | Verb::StartWorld if squid_enabled(root) => Duration::from_secs(2700),
Verb::StartAll | Verb::StartWorld => Duration::from_secs(420),
Verb::StartMysql => Duration::from_secs(120),
// Includes database startup, optional bot provisioning and the shared 25-minute
// world/console wait in launcher_bridge.py, even for older installed scripts.
Verb::StartAll | Verb::StartWorld => Duration::from_secs(3600),
Verb::StartMysql => Duration::from_secs(360),
Verb::StopAll => Duration::from_secs(240),
}
}
}
fn squid_enabled(root: &Path) -> bool {
let active = root.join("Core/configs/modules/playerbots.conf");
let path = if active.exists() {
active
} else {
root.join("Core/configs/modules/playerbots.conf.dist")
};
std::fs::read(path)
.ok()
.and_then(|bytes| crate::config::parser::ConfFile::parse_bytes(&bytes).ok())
.is_some_and(|config| {
config.get("AiPlayerbot.Enabled").is_none_or(|value| {
!matches!(
value.trim().trim_matches('"').to_ascii_lowercase().as_str(),
"0" | "false" | "no" | "off"
)
})
})
}
#[derive(Debug, Clone, Serialize)]
pub struct DriverOutcome {
pub ok: bool,
@@ -230,6 +211,13 @@ fn run_inner(root: &Path, verb: Verb, validating_update: bool) -> Result<DriverO
let mut output = out_t.join().unwrap_or_default();
output.push_str(&err_t.join().unwrap_or_default());
let mut output = output.trim().to_string();
if status.is_none() {
output.push_str(&format!(
"\nLauncher {} exceeded its {} second deadline; check the server logs.",
verb.arg(),
verb.timeout(&root).as_secs()
));
}
let (ok, exit_code) = match status {
Some(st) => (st.success(), st.code()),
None => (false, None),
@@ -393,7 +381,7 @@ fn recover_mysql_launcher_state(root: &Path, prefer_listener: bool) -> Result<()
Ok(())
}
const LAUNCH_SCRIPT: &str = "import runpy,sys\nfrom pathlib import Path\nscript=sys.argv[1]\nsys.path.insert(0,str(Path(script).resolve().parent))\nsys.argv=sys.argv[1:]\nif sys.argv[1]=='stop-all':\n launcher=runpy.run_path(script,run_name='coa_manager_shutdown')\n config=launcher['settings']()\n with launcher['control_lock']():\n launcher['stop_all'](config)\nelse:\n runpy.run_path(script,run_name='__main__')";
const LAUNCH_SCRIPT: &str = include_str!("launcher_bridge.py");
pub(crate) fn patch_launcher_imports(text: &str) -> Result<String> {
let line = "sys.path.insert(0, str(Path(__file__).resolve().parent))";
@@ -604,7 +592,7 @@ mod tests {
}
#[test]
fn large_squid_provisioning_has_time_to_finish_without_extending_shutdown() {
fn slow_world_startup_has_time_with_either_bot_system_without_extending_shutdown() {
let folder = tempfile::tempdir().unwrap();
let modules = folder.path().join("Core/configs/modules");
std::fs::create_dir_all(&modules).unwrap();
@@ -615,7 +603,7 @@ mod tests {
.unwrap();
assert_eq!(
Verb::StartAll.timeout(folder.path()),
Duration::from_secs(2700)
Duration::from_secs(3600)
);
assert_eq!(
Verb::StopAll.timeout(folder.path()),
@@ -624,7 +612,11 @@ mod tests {
std::fs::write(modules.join("playerbots.conf"), "AiPlayerbot.Enabled = 0\n").unwrap();
assert_eq!(
Verb::StartWorld.timeout(folder.path()),
Duration::from_secs(420)
Duration::from_secs(3600)
);
assert_eq!(
Verb::StartMysql.timeout(folder.path()),
Duration::from_secs(360)
);
}
+52 -15
View File
@@ -239,14 +239,14 @@ fn bootstrap_database_inner(root: &Path) -> Result<()> {
}
fs::copy(&boot, &target)?; // launcher needs database.json to render its files at first start
let started = driver::run(root, Verb::StartMysql)?;
if !started.ok {
return Err(Error::Invalid(format!(
"The database could not be started. {}",
driver::startup_failure(root, &started)
)));
}
let result = (|| -> Result<()> {
let started = driver::run(root, Verb::StartMysql)?;
if !started.ok {
return Err(Error::Invalid(format!(
"The database could not be started. {}",
driver::startup_failure(root, &started)
)));
}
let db = Db::from_repack(root, Account::Admin)?;
let (root_pw, app_pw) = (random_hex(48), random_hex(48));
let accounts = db.query(
@@ -362,6 +362,7 @@ pub fn install_base(p: &Params, report: &dyn Fn(Step)) -> Result<Installed> {
// 3. Extract into our own staging folder.
if staging_root.exists() {
if staging_root.join(MARKER).is_file() {
stop_installation(&staging_root)?;
fs::remove_dir_all(&staging_root)?; // leftover of an earlier failed attempt that we created
} else {
return Err(Error::Invalid(format!("{} is left over from an earlier installation that did not finish, and the Manager cannot tell whether it may be deleted. Delete that folder yourself, then try again.", staging_root.display())));
@@ -426,24 +427,60 @@ pub fn install_base(p: &Params, report: &dyn Fn(Step)) -> Result<Installed> {
})();
if result.is_err() {
if staging_root.join(MARKER).exists() {
// Unfinished work of ours; the destination was never touched.
let _ = driver::run(&staging_root, Verb::StopAll);
let _ = fs::remove_dir_all(&staging_root);
let unfinished = if staging_root.join(MARKER).is_file() {
Some(&staging_root)
} else if dest.join(MARKER).is_file() {
// Failed after the folder was moved into place. The destination was empty or absent before (preflight),
// so what carries our marker is only our unfinished install.
let _ = driver::run(&dest, Verb::StopAll);
let _ = fs::remove_dir_all(&dest);
Some(&dest)
} else {
None
};
if let Some(unfinished) = unfinished {
if let Err(cleanup) = stop_installation(unfinished) {
return Err(Error::Invalid(format!(
"{} {cleanup}",
result.as_ref().unwrap_err()
)));
}
let _ = fs::remove_dir_all(unfinished);
}
}
result
}
fn stop_installation(root: &Path) -> Result<()> {
if !root.join("Scripts/manage.py").is_file() {
return Ok(());
}
let stopped = driver::run(root, Verb::StopAll)?;
if !stopped.ok {
return Err(Error::Invalid(format!(
"The unfinished installation could not be stopped; its files were kept. {}",
driver::startup_failure(root, &stopped)
)));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_unstoppable_partial_installation_keeps_its_files_for_recovery() {
let folder = tempfile::tempdir().unwrap();
let root = folder.path();
fs::create_dir_all(root.join("Scripts")).unwrap();
fs::write(root.join("Scripts/manage.py"), "# incomplete launcher").unwrap();
fs::write(root.join(MARKER), "").unwrap();
fs::write(root.join("database-preserved"), "unchanged").unwrap();
assert!(stop_installation(root).is_err());
assert_eq!(
fs::read_to_string(root.join("database-preserved")).unwrap(),
"unchanged"
);
assert!(root.join(MARKER).is_file());
}
fn reg(d: &Path) -> Registry {
Registry::at(d.join("reg/installs.json"))
}
+61
View File
@@ -0,0 +1,61 @@
import runpy
import sys
import time
from pathlib import Path
script = sys.argv[1]
sys.path.insert(0, str(Path(script).resolve().parent))
sys.argv = sys.argv[1:]
launcher = runpy.run_path(script, run_name="coa_manager_launcher")
original_wait = launcher["wait_ready"]
world_deadline = None
def wait_ready(name, port, seconds=180):
global world_deadline
if name == "mysql":
seconds = max(seconds, 300)
elif name == "world":
# Both game and console listeners belong to one startup, including on old repacks.
# Ordinary CoA worlds can load slowly too; this must not depend on SQUID.
if world_deadline is None:
world_deadline = time.monotonic() + max(seconds, 1500)
seconds = max(0, world_deadline - time.monotonic())
return original_wait(name, port, seconds)
launcher["start_mysql"].__globals__["wait_ready"] = wait_ready
if sys.argv[1] == "stop-all":
shutdown = launcher["stop_all"].__globals__
if "ra" in shutdown:
original_ra = shutdown["ra"]
class UnsafeShutdown(Exception):
pass
def shutdown_command(command, config):
try:
return original_ra(command, config)
except (OSError, RuntimeError):
if not command.startswith("server shutdown "):
raise
world = shutdown["process"]("world")
if not world:
return "Worldserver has already stopped."
expected = Path(script).resolve().parents[1] / "Core" / "worldserver.exe"
if Path(world.get("exe", "")) != expected or not shutdown["same_process"](world):
raise UnsafeShutdown("World process ownership could not be verified; the database was left running.")
try:
shutdown["terminate"](world)
except (OSError, RuntimeError) as error:
raise UnsafeShutdown("Worldserver could not be stopped safely; its database was left running.") from error
if not shutdown["wait_stopped"](world, 90):
raise UnsafeShutdown("Worldserver is still stopping; its database was left running.")
return "Stopped this server's recorded world process without its unavailable console."
shutdown["ra"] = shutdown_command
config = launcher["settings"]()
with launcher["control_lock"]():
launcher["stop_all"](config)
else:
launcher["main"]()
+3
View File
@@ -11,6 +11,7 @@ pub mod accounts;
pub mod allsettings;
pub mod backup;
pub mod channels;
pub mod character_start_check;
pub mod cleanbase;
pub mod client;
pub mod clientdl;
@@ -48,11 +49,13 @@ pub mod population;
pub mod portable;
pub mod process;
pub mod ra;
pub mod race_availability;
pub mod realm_registry;
pub mod realmlist;
pub mod realms;
pub mod registry;
pub mod release;
pub mod release_history;
pub mod release_schema;
pub mod remote_client;
pub mod repair;
+14
View File
@@ -516,6 +516,20 @@ fn save_settings_in(
let mut changed = Vec::new();
for (key, value) in changes {
let value = value.trim();
if id == "custom-races" && key == crate::race_availability::KEY {
require_bot_server_stopped(root)?;
let catalog = crate::race_availability::status(root)?;
if !catalog.server_config_supported {
return Err(Error::Invalid("Update the server before configuring individual race restrictions.".into()));
}
crate::race_availability::parse_disabled(value, &catalog.races)?;
}
if id == "custom-races" && key == crate::race_availability::CATALOG_KEY {
let hash = value.trim_matches('"');
if !hash.is_empty() && (hash.len() != 64 || !hash.bytes().all(|byte| byte.is_ascii_hexdigit())) {
return Err(Error::Invalid("Invalid race catalog fingerprint.".into()));
}
}
if let Some(field) = fields.get(key) {
crate::squid::validate(field, value)?;
}
+6 -1
View File
@@ -497,7 +497,12 @@ mod tests {
)
.unwrap();
let err = set_reborn_enabled(t.path(), true).unwrap_err().to_string();
assert!(err.contains("Select Conquest of Azeroth first"), "{err}");
let expected = if cfg!(windows) {
"Select Conquest of Azeroth first"
} else {
"Simultaneous realms currently require Windows"
};
assert!(err.contains(expected), "{err}");
assert!(!realms::state(t.path()).unwrap().with_reborn);
}
+83
View File
@@ -1004,6 +1004,89 @@ mod tests {
};
let mut server = start();
db.query("CREATE DATABASE acore_characters; CREATE DATABASE acore_world; CREATE DATABASE acore_auth; CREATE TABLE acore_characters.probe(id INT PRIMARY KEY, note VARCHAR(40)); CREATE TABLE acore_world.probe(id INT NOT NULL DEFAULT 0); INSERT INTO acore_world.probe VALUES(43); CREATE TABLE acore_auth.probe(id INT); INSERT INTO acore_auth.probe VALUES(44); CREATE USER 'fixture_user'@'localhost' IDENTIFIED BY 'fixture'; CREATE TRIGGER acore_characters.probe_insert BEFORE INSERT ON acore_characters.probe FOR EACH ROW SET NEW.note='triggered'; INSERT INTO acore_characters.probe VALUES(42,'original'); CREATE VIEW acore_characters.probe_view AS SELECT c.id,w.id AS world_id FROM acore_characters.probe c CROSS JOIN acore_world.probe w; CREATE PROCEDURE acore_characters.probe_proc() SELECT id FROM acore_characters.probe; CREATE FUNCTION acore_characters.probe_func() RETURNS INT DETERMINISTIC RETURN 73;").unwrap();
// Regression: an upgrade must distinguish pre-existing unsupported character starts
// from a newly lost start, without weakening any structural schema check.
db.query("CREATE TABLE acore_characters.characters(guid INT UNSIGNED PRIMARY KEY,race INT UNSIGNED NOT NULL,class INT UNSIGNED NOT NULL); CREATE TABLE acore_world.playercreateinfo(race INT UNSIGNED,class INT UNSIGNED,PRIMARY KEY(race,class)); INSERT INTO acore_characters.characters VALUES(100,44,14),(101,44,14),(102,7,14);").unwrap();
let starts = [1, 2, 3, 4, 5, 6, 7, 8, 10, 11]
.into_iter()
.flat_map(|race| (12..=32).map(move |class| format!("({race},{class})")))
.collect::<Vec<_>>()
.join(",");
db.query(&format!(
"INSERT INTO acore_world.playercreateinfo VALUES {starts};"
))
.unwrap();
crate::schema_check::capture(&db, &root).unwrap();
let baseline = crate::character_start_check::capture(&db, &root).unwrap();
assert_eq!(baseline.realms[crate::realms::Mode::Coa.name()].len(), 2);
assert!(
!crate::schema_check::check(&db, &root).unwrap().is_empty(),
"ordinary diagnostics stay strict"
);
assert!(
crate::schema_check::check_update_with_report(&db, &root, Some(&baseline))
.unwrap()
.is_empty(),
"unchanged old gaps must not block an unrelated upgrade"
);
assert_eq!(
db.query("SELECT COUNT(*) FROM acore_characters.characters;")
.unwrap()
.trim(),
"3"
);
let report_dir = crate::registry::metadata_dir_for(&root)
.unwrap()
.join("diagnostics");
let report_path = fs::read_dir(report_dir)
.unwrap()
.flatten()
.map(|e| e.path())
.find(|p| {
p.file_name()
.unwrap()
.to_string_lossy()
.starts_with("schema-validation-")
})
.unwrap();
let report: serde_json::Value = fsx::read_json(&report_path).unwrap();
assert_eq!(report["preexistingUnsupportedCharacters"], 2);
assert_eq!(
report["preexistingCharacterStarts"],
serde_json::json!([{"race":44,"class":14,"count":2}])
);
assert_eq!(report["problems"], serde_json::json!([]));
// Same count and race/class but a different GUID must still block.
db.query("UPDATE acore_characters.characters SET guid=103 WHERE guid=101;")
.unwrap();
assert!(
!crate::schema_check::check_update_with_report(&db, &root, Some(&baseline))
.unwrap()
.is_empty()
);
db.query("UPDATE acore_characters.characters SET guid=101 WHERE guid=103;")
.unwrap();
// Loss of a formerly valid start is never grandfathered.
db.query("DELETE FROM acore_world.playercreateinfo WHERE race=7 AND class=14;")
.unwrap();
assert!(
!crate::schema_check::check_update_with_report(&db, &root, Some(&baseline))
.unwrap()
.is_empty()
);
db.query("INSERT INTO acore_world.playercreateinfo VALUES(7,14);")
.unwrap();
db.query("ALTER TABLE acore_world.probe MODIFY id VARCHAR(30) NOT NULL DEFAULT '0';")
.unwrap();
assert!(
!crate::schema_check::check_update_with_report(&db, &root, Some(&baseline))
.unwrap()
.is_empty(),
"existing character warnings cannot hide a structural failure"
);
db.query("ALTER TABLE acore_world.probe MODIFY id INT NOT NULL DEFAULT 0; DROP TABLE acore_characters.characters; DROP TABLE acore_world.playercreateinfo;").unwrap();
fs::remove_file(root.join(crate::schema_check::CONTRACT)).unwrap();
// Shared auth must not run again when the active realm changes.
use crate::migrations::Store;
db.query("CREATE DATABASE acore_world_wildcard;").unwrap();
+515
View File
@@ -0,0 +1,515 @@
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};
use serde::Serialize;
use sha2::{Digest, Sha256};
use crate::config::parser::ConfFile;
use crate::error::{Error, Result};
pub const KEY: &str = "CoACustomRaces.DisabledRaceIds";
pub const CATALOG_KEY: &str = "CoACustomRaces.DisabledRaceCatalogSha256";
const CONF: &str = "Core/configs/modules/coa_custom_races.conf";
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Race {
pub id: u32,
pub name: String,
pub faction: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Availability {
pub realm: crate::realms::Mode,
pub races: Vec<Race>,
pub disabled_race_ids: BTreeSet<u32>,
pub catalog_sha256: String,
pub server_config_supported: bool,
pub catalog_needs_review: bool,
pub unrecognized_race_ids: BTreeSet<u32>,
}
fn invalid(message: &str) -> Error {
Error::Invalid(message.into())
}
fn stock(id: u32) -> bool {
(1..=11).contains(&id) && id != 9
}
pub fn catalog(bytes: &[u8]) -> Result<Vec<Race>> {
let word = |offset: usize| -> Result<u32> {
let data = bytes
.get(offset..offset + 4)
.ok_or_else(|| invalid("Truncated race catalog."))?;
Ok(u32::from_le_bytes(data.try_into().unwrap()))
};
if bytes.get(..4) != Some(b"WDBC") || word(8)? != 69 || word(12)? != 276 {
return Err(invalid("Unsupported race catalog format."));
}
let count = word(4)? as usize;
let string_size = word(16)? as usize;
if count == 0 || count > 255 {
return Err(invalid("Invalid race catalog record count."));
}
let strings_start = 20 + count * 276;
if strings_start.checked_add(string_size) != Some(bytes.len()) || string_size == 0 {
return Err(invalid("Invalid race catalog bounds."));
}
let strings = &bytes[strings_start..];
if strings.last() != Some(&0) {
return Err(invalid("Invalid race catalog strings."));
}
let mut ids = BTreeSet::new();
let mut races = Vec::new();
for row in 0..count {
let offset = 20 + row * 276;
let id = word(offset)?;
if id == 0 || id > 255 || !ids.insert(id) {
return Err(invalid("Invalid or duplicate RaceID in the catalog."));
}
let mut name = String::new();
for field in 14..30 {
let index = word(offset + field * 4)? as usize;
let remaining = strings
.get(index..)
.ok_or_else(|| invalid("Invalid race name offset."))?;
let end = remaining
.iter()
.position(|byte| *byte == 0)
.ok_or_else(|| invalid("Unterminated race name."))?;
let value = std::str::from_utf8(&remaining[..end])
.map_err(|_| invalid("Invalid race name encoding."))?;
if name.is_empty() && !value.is_empty() {
name = value.into();
}
}
if stock(id) || word(offset + 4)? & 1 != 0 {
continue;
}
if name.trim().is_empty() {
return Err(invalid("A playable custom race has no name."));
}
let faction = match word(offset + 13 * 4)? {
0 => Some("alliance".into()),
1 => Some("horde".into()),
_ => None,
};
races.push(Race { id, name, faction });
}
races.sort_by_key(|race| race.id);
Ok(races)
}
fn parse_ids(value: &str) -> Result<BTreeSet<u32>> {
let value = value.trim();
let value = if value.starts_with('"') && value.ends_with('"') && value.len() >= 2 {
&value[1..value.len() - 1]
} else {
value
};
if value.trim().is_empty() {
return Ok(BTreeSet::new());
}
let mut disabled = BTreeSet::new();
for token in value.split(',') {
let token = token.trim();
if token.is_empty() || !token.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(invalid(
"Disabled RaceIDs must be a comma-separated list of whole numbers.",
));
}
let id = token
.parse::<u32>()
.map_err(|_| invalid("Invalid disabled RaceID."))?;
if id == 0 || id > 255 || stock(id) || !disabled.insert(id) {
return Err(invalid(
"Disabled RaceIDs contain a stock, unknown or duplicate race.",
));
}
}
Ok(disabled)
}
pub fn parse_disabled(value: &str, races: &[Race]) -> Result<BTreeSet<u32>> {
let disabled = parse_ids(value)?;
let known: BTreeSet<u32> = races.iter().map(|race| race.id).collect();
if !disabled.is_subset(&known) {
return Err(invalid("Disabled RaceIDs contain an unknown race."));
}
Ok(disabled)
}
fn dbc_path(root: &Path) -> Result<PathBuf> {
let config_path = root.join("Core/configs/worldserver.conf");
if config_path.is_file() {
let conf = ConfFile::parse_bytes(&fs::read(config_path)?)?;
let value = conf.get("DataDir").unwrap_or(".");
let data = PathBuf::from(value.trim().trim_matches('"'));
return Ok(if data.is_absolute() {
data
} else {
root.join("Core").join(data)
}
.join("dbc_races/ChrRaces.dbc"));
}
Ok(root.join("Data/dbc_races/ChrRaces.dbc"))
}
pub fn status(root: &Path) -> Result<Availability> {
let bytes = fs::read(dbc_path(root)?)?;
let races = catalog(&bytes)?;
let conf = ConfFile::parse_bytes(&fs::read(root.join(CONF))?)?;
let configured = parse_ids(conf.get(KEY).unwrap_or(""))?;
let known: BTreeSet<u32> = races.iter().map(|race| race.id).collect();
let unrecognized_race_ids: BTreeSet<u32> = configured.difference(&known).copied().collect();
let disabled_race_ids = configured.intersection(&known).copied().collect();
let dist = fs::read(root.join(format!("{CONF}.dist")))
.ok()
.map(|bytes| ConfFile::parse_bytes(&bytes))
.transpose()?;
let catalog_sha256 = hex::encode(Sha256::digest(&bytes));
let saved_hash = conf
.get(CATALOG_KEY)
.unwrap_or("")
.trim()
.trim_matches('"')
.to_ascii_lowercase();
let catalog_needs_review = !configured.is_empty()
&& (saved_hash != catalog_sha256 || !unrecognized_race_ids.is_empty());
Ok(Availability {
realm: crate::realms::state(root)?.active,
races,
disabled_race_ids,
catalog_sha256,
catalog_needs_review,
unrecognized_race_ids,
server_config_supported: dist
.is_some_and(|file| file.get(KEY).is_some() && file.get(CATALOG_KEY).is_some())
&& fs::read(crate::layout::executables(root).0).is_ok_and(|binary| {
[KEY, CATALOG_KEY]
.iter()
.all(|key| binary.windows(key.len()).any(|part| part == key.as_bytes()))
}),
})
}
pub fn save(
root: &Path,
meta: &Path,
expected_catalog: &str,
expected_realm: crate::realms::Mode,
disabled: &[u32],
) -> Result<Availability> {
crate::update::ensure_recovered(meta)?;
fs::create_dir_all(root.join(".state"))?;
let lock = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(root.join(".state/control.lock"))?;
if !fs4::fs_std::FileExt::try_lock_exclusive(&lock)? {
return Err(invalid("Another server operation is in progress."));
}
let observed = crate::process::observe(root, &crate::layout::read_ports(root));
if observed.world.state != crate::process::ServiceState::Stopped
|| crate::multiworld::is_running(root)
{
return Err(invalid(
"Stop the server before changing race availability.",
));
}
let current = status(root)?;
if current.realm != expected_realm {
return Err(invalid(
"The selected realm changed. Reload race availability before saving.",
));
}
if !current.server_config_supported {
return Err(invalid(
"Update the server to a build supporting individual race restrictions first.",
));
}
if current.catalog_sha256 != expected_catalog {
return Err(invalid(
"The race catalog changed. Reload the race list before saving.",
));
}
let value = disabled
.iter()
.map(u32::to_string)
.collect::<Vec<_>>()
.join(",");
let normalized = parse_disabled(&value, &current.races)?;
let value = normalized
.iter()
.map(u32::to_string)
.collect::<Vec<_>>()
.join(",");
crate::modules::save_settings(
root,
meta,
"custom-races",
&BTreeMap::from([
(KEY.into(), format!("\"{value}\"")),
(
CATALOG_KEY.into(),
format!(
"\"{}\"",
if normalized.is_empty() {
""
} else {
&current.catalog_sha256
}
),
),
]),
)?;
status(root)
}
#[cfg(test)]
mod tests {
use super::*;
fn dbc() -> Vec<u8> {
let mut bytes = b"WDBC".to_vec();
for value in [4u32, 69, 276, 11] {
bytes.extend(value.to_le_bytes());
}
for id in [1u32, 82, 83, 97] {
let mut row = vec![0; 276];
row[..4].copy_from_slice(&id.to_le_bytes());
row[4..8].copy_from_slice(&12u32.to_le_bytes());
row[56..60].copy_from_slice(&1u32.to_le_bytes());
bytes.extend(row);
}
bytes.extend(b"\0Synthetic\0");
bytes
}
#[test]
fn catalog_preserves_ids_and_excludes_stock_and_nonplayable() {
let mut bytes = dbc();
bytes[20 + 276 + 4] |= 1;
let races = catalog(&bytes).unwrap();
assert_eq!(
races.iter().map(|race| race.id).collect::<Vec<_>>(),
[83, 97]
);
assert_eq!(races[0].name, "Synthetic");
}
#[test]
fn rejects_corrupt_layout_bounds_ids_and_names() {
for (offset, value) in [
(4, 0),
(8, 68),
(12, 272),
(16, 100),
(20, 0),
(20 + 276, 1),
(20 + 56, 999),
] {
let mut bytes = dbc();
bytes[offset..offset + 4].copy_from_slice(&(value as u32).to_le_bytes());
assert!(catalog(&bytes).is_err(), "offset {offset}");
}
assert!(catalog(&dbc()[..19]).is_err());
assert!(catalog(&dbc()[..100]).is_err());
}
#[test]
fn disabled_set_is_strict_and_atomic() {
let races = catalog(&dbc()).unwrap();
assert_eq!(
parse_disabled("\"97,82\"", &races).unwrap(),
BTreeSet::from([82, 97])
);
assert!(parse_disabled("\"\"", &races).unwrap().is_empty());
for value in [
"82,1", "82,82", "82,250", "82,", "-82", "+82", "82,1-97", "82x", "0",
] {
assert!(parse_disabled(value, &races).is_err(), "{value}");
}
}
#[test]
fn status_uses_current_config_and_requires_server_capability() {
let temporary = tempfile::tempdir().unwrap();
let root = temporary.path();
fs::create_dir_all(root.join("Data/dbc_races")).unwrap();
fs::create_dir_all(root.join("Core/configs/modules")).unwrap();
fs::write(root.join("Data/dbc_races/ChrRaces.dbc"), dbc()).unwrap();
fs::write(root.join(CONF), format!("{KEY} = \"82\"\n")).unwrap();
let before = status(root).unwrap();
assert!(!before.server_config_supported);
assert_eq!(before.disabled_race_ids, BTreeSet::from([82]));
fs::write(
root.join(format!("{CONF}.dist")),
format!("{KEY} = \"\"\n{CATALOG_KEY} = \"\"\n"),
)
.unwrap();
assert!(!status(root).unwrap().server_config_supported);
fs::write(
root.join("Core/worldserver.exe"),
format!("{KEY} {CATALOG_KEY}"),
)
.unwrap();
let after = status(root).unwrap();
assert!(after.server_config_supported);
assert_eq!(before.catalog_sha256, after.catalog_sha256);
}
fn server(root: &Path) {
fs::create_dir_all(root.join("Data/dbc_races")).unwrap();
fs::create_dir_all(root.join("Core/configs/modules")).unwrap();
fs::write(
root.join("Core/worldserver.exe"),
format!("{KEY} {CATALOG_KEY}"),
)
.unwrap();
fs::create_dir_all(root.join("Settings")).unwrap();
fs::write(
root.join("Settings/repack.json"),
r#"{"worldPort":0,"authPort":0,"mysqlPort":0,"raPort":0}"#,
)
.unwrap();
fs::write(root.join("Data/dbc_races/ChrRaces.dbc"), dbc()).unwrap();
fs::write(
root.join(CONF),
format!("CoACustomRaces.Enable = 1\n{KEY} = \"82\"\nUser.Custom = 42\n"),
)
.unwrap();
fs::write(
root.join(format!("{CONF}.dist")),
format!("CoACustomRaces.Enable = 0\n{KEY} = \"\"\n{CATALOG_KEY} = \"\"\n"),
)
.unwrap();
fs::write(
root.join("Core/configs/modules/playerbots.conf"),
"AiPlayerbot.ExcludedBotRaces = \"1,83\"\nAiPlayerbot.CrashingBotRaces = \"97\"\n",
)
.unwrap();
}
#[test]
fn saving_and_allow_all_preserve_user_settings_and_bot_exclusions() {
let temporary = tempfile::tempdir().unwrap();
let root = temporary.path().join("server");
let meta = temporary.path().join("metadata");
server(&root);
let hash = status(&root).unwrap().catalog_sha256;
let bot_path = root.join("Core/configs/modules/playerbots.conf");
let bot_before = fs::read(&bot_path).unwrap();
let saved = save(&root, &meta, &hash, crate::realms::Mode::Coa, &[97, 83]).unwrap();
assert_eq!(saved.disabled_race_ids, BTreeSet::from([83, 97]));
assert!(!saved.catalog_needs_review);
assert!(fs::read_to_string(root.join(CONF)).unwrap().contains(&hash));
assert!(fs::read_to_string(root.join(CONF))
.unwrap()
.contains("User.Custom = 42"));
assert_eq!(fs::read(&bot_path).unwrap(), bot_before);
assert!(save(&root, &meta, &hash, crate::realms::Mode::Coa, &[])
.unwrap()
.disabled_race_ids
.is_empty());
}
#[test]
fn stale_catalog_and_invalid_lists_cannot_change_configuration() {
let temporary = tempfile::tempdir().unwrap();
let root = temporary.path().join("server");
let meta = temporary.path().join("metadata");
server(&root);
let hash = status(&root).unwrap().catalog_sha256;
let before = fs::read(root.join(CONF)).unwrap();
assert!(save(&root, &meta, "stale", crate::realms::Mode::Coa, &[83]).is_err());
for ids in [&[82, 1][..], &[82, 82][..], &[250][..]] {
assert!(save(&root, &meta, &hash, crate::realms::Mode::Coa, ids).is_err());
assert_eq!(fs::read(root.join(CONF)).unwrap(), before);
}
}
#[test]
fn switching_realms_cannot_apply_a_draft_from_another_profile() {
let temporary = tempfile::tempdir().unwrap();
let root = temporary.path().join("server");
let meta = temporary.path().join("metadata");
server(&root);
let loaded = status(&root).unwrap();
let before = fs::read(root.join(CONF)).unwrap();
let realm = crate::realms::RealmState {
active: crate::realms::Mode::Wildcard,
..Default::default()
};
fs::write(
root.join("Settings/realm-profile.json"),
serde_json::to_vec(&realm).unwrap(),
)
.unwrap();
assert!(save(&root, &meta, &loaded.catalog_sha256, loaded.realm, &[83]).is_err());
assert_eq!(fs::read(root.join(CONF)).unwrap(), before);
}
#[test]
fn concurrent_server_operations_cannot_change_policy() {
let temporary = tempfile::tempdir().unwrap();
let root = temporary.path().join("server");
let meta = temporary.path().join("metadata");
server(&root);
fs::create_dir_all(root.join(".state")).unwrap();
let lock = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(root.join(".state/control.lock"))
.unwrap();
assert!(fs4::fs_std::FileExt::try_lock_exclusive(&lock).unwrap());
let loaded = status(&root).unwrap();
let before = fs::read(root.join(CONF)).unwrap();
assert!(save(&root, &meta, &loaded.catalog_sha256, loaded.realm, &[83]).is_err());
assert_eq!(fs::read(root.join(CONF)).unwrap(), before);
}
#[test]
fn relative_data_dir_uses_the_worldserver_working_directory() {
let temporary = tempfile::tempdir().unwrap();
let root = temporary.path().join("server");
server(&root);
fs::write(
root.join("Core/configs/worldserver.conf"),
"DataDir = \"../Data\"\n",
)
.unwrap();
assert_eq!(status(&root).unwrap().races.len(), 3);
}
#[test]
fn changed_catalog_requires_explicit_review_and_unknown_ids_are_not_valid_races() {
let temporary = tempfile::tempdir().unwrap();
let root = temporary.path().join("server");
let meta = temporary.path().join("metadata");
server(&root);
let loaded = status(&root).unwrap();
assert!(loaded.catalog_needs_review);
save(&root, &meta, &loaded.catalog_sha256, loaded.realm, &[82]).unwrap();
assert!(!status(&root).unwrap().catalog_needs_review);
let mut changed = dbc();
changed[20 + 276..24 + 276].copy_from_slice(&84u32.to_le_bytes());
fs::write(root.join("Data/dbc_races/ChrRaces.dbc"), changed).unwrap();
let updated = status(&root).unwrap();
assert!(updated.catalog_needs_review);
assert_eq!(updated.unrecognized_race_ids, BTreeSet::from([82]));
assert!(!updated.races.iter().any(|race| race.id == 82));
assert!(updated.disabled_race_ids.is_empty());
let reviewed = save(&root, &meta, &updated.catalog_sha256, updated.realm, &[]).unwrap();
assert!(!reviewed.catalog_needs_review);
assert!(reviewed.unrecognized_race_ids.is_empty());
}
}
+170
View File
@@ -0,0 +1,170 @@
//! Read-only, bounded canonical histories. Offline fallback is also bundled in the UI.
use serde_json::Value;
use std::{io::Read, path::Path, time::Duration};
const LIMIT: u64 = 2 * 1024 * 1024;
fn repository(component: &str) -> Result<(&'static str, &'static str), String> {
match component {
"server" => Ok(("Corfirean/coa-server-build", "main")),
"manager" => Ok(("Corfirean/coa-server-manager", "master")),
_ => Err("Unknown release component".into()),
}
}
fn validate(bytes: &[u8], component: &str) -> Result<Value, String> {
let (repo, _) = repository(component)?;
if bytes.len() as u64 > LIMIT {
return Err("Release history is too large".into());
}
let value: Value = serde_json::from_slice(bytes).map_err(|e| e.to_string())?;
if value["schema"] != 1 || value["component"] != component || value["repository"] != repo {
return Err("Release history identity mismatch".into());
}
let releases = value["releases"].as_array().ok_or("Missing releases")?;
if releases.len() > 2000 {
return Err("Too many releases".into());
}
for release in releases {
if release.get("prerelease").is_some_and(|v| !v.is_boolean())
|| release.get("experimentalFeatures").is_some_and(|v| {
v.as_array()
.is_none_or(|items| items.iter().any(|item| !item.is_string()))
})
{
return Err("Invalid release flags".into());
}
for field in ["tag", "date"] {
if release[field]
.as_str()
.is_none_or(|s| s.is_empty() || s.len() > 100)
{
return Err("Invalid release metadata".into());
}
}
let version = release["version"].as_str().ok_or("Missing version")?;
if version.len() > 80
|| !version
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b".-+".contains(&b))
{
return Err("Invalid version".into());
}
let notes = release["notes"].as_array().ok_or("Missing notes")?;
if notes.len() > 500
|| notes
.iter()
.any(|n| n.as_str().is_none_or(|s| s.len() > 10000))
{
return Err("Invalid release notes".into());
}
}
Ok(value)
}
pub fn load(component: &str, cache_dir: &Path) -> Result<Value, String> {
let (repo, branch) = repository(component)?;
let cache = cache_dir.join(format!("{component}.json"));
let cached = || {
let mut bytes = Vec::new();
std::fs::File::open(&cache)
.ok()?
.take(LIMIT + 1)
.read_to_end(&mut bytes)
.ok()?;
validate(&bytes, component).ok()
};
if cache
.metadata()
.and_then(|m| m.modified())
.ok()
.and_then(|t| t.elapsed().ok())
.is_some_and(|age| age < Duration::from_secs(3600))
{
if let Some(mut v) = cached() {
v["source"] = "cache".into();
return Ok(v);
}
}
let remote = || -> Result<Value, String> {
let client = reqwest::blocking::Client::builder()
.timeout(Duration::from_secs(8))
.redirect(reqwest::redirect::Policy::none())
.build()
.map_err(|e| e.to_string())?;
let response = client
.get(format!(
"https://raw.githubusercontent.com/{repo}/{branch}/changelog/history.json"
))
.send()
.and_then(|r| r.error_for_status())
.map_err(|e| e.to_string())?;
let mut bytes = Vec::new();
response
.take(LIMIT + 1)
.read_to_end(&mut bytes)
.map_err(|e| e.to_string())?;
let mut value = validate(&bytes, component)?;
if std::fs::create_dir_all(cache_dir).is_ok() {
let _ = std::fs::write(&cache, &bytes);
}
value["source"] = "remote".into();
Ok(value)
};
remote().or_else(|error| {
cached()
.map(|mut v| {
v["source"] = "cache".into();
v
})
.ok_or(error)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_both_complete_bundled_canonical_histories() {
assert!(validate(include_bytes!("../../../changelog/history.json"), "manager").is_ok());
assert!(validate(
include_bytes!("../../../src/data/server-history.json"),
"server"
)
.is_ok());
}
#[test]
fn rejects_cross_component_and_untrusted_components() {
let bytes = br#"{"schema":1,"component":"manager","repository":"Corfirean/coa-server-manager","releases":[]}"#;
assert!(validate(bytes, "manager").is_ok());
assert!(validate(bytes, "server").is_err());
assert!(repository("../../other").is_err());
assert!(validate(&vec![b' '; LIMIT as usize + 1], "manager").is_err());
}
#[test]
fn rejects_malformed_records_before_the_ui_can_use_them() {
let mut value = serde_json::json!({"schema": 1, "component": "server",
"repository": "Corfirean/coa-server-build", "releases": [{
"version": "0.261028.83", "tag": "0.261028.83", "date": "2026-10-28",
"notes": ["Reviewed note"]
}]});
assert!(validate(&serde_json::to_vec(&value).unwrap(), "server").is_ok());
value["releases"][0]["date"] = Value::Null;
assert!(validate(&serde_json::to_vec(&value).unwrap(), "server").is_err());
value["releases"][0]["date"] = "2026-10-28".into();
value["releases"][0]["notes"] = serde_json::json!([{"html": "not a text note"}]);
assert!(validate(&serde_json::to_vec(&value).unwrap(), "server").is_err());
}
#[test]
fn fresh_valid_cache_is_available_without_network() {
let dir = std::env::temp_dir().join(format!("coa-history-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("manager.json"), br#"{"schema":1,"component":"manager","repository":"Corfirean/coa-server-manager","releases":[]}"#).unwrap();
let result = load("manager", &dir).unwrap();
assert_eq!(result["source"], "cache");
std::fs::remove_file(dir.join("manager.json")).unwrap();
std::fs::remove_dir(dir).unwrap();
}
}
+57 -7
View File
@@ -95,13 +95,42 @@ pub struct Problem {
/// Keep all differences for support; never change a database to match a contract automatically.
pub fn check_with_report(db: &Db, root: &Path) -> Result<Vec<Problem>> {
let problems = check(db, root)?;
if problems.is_empty() {
check_update_with_report(db, root, None)
}
/// Only a hash-verified pre-update baseline may downgrade unchanged missing starts to warnings.
pub fn check_update_with_report(
db: &Db,
root: &Path,
baseline: Option<&crate::character_start_check::Baseline>,
) -> Result<Vec<Problem>> {
let mut preexisting = BTreeMap::new();
let before = match baseline {
Some(b) if b.schema == 1 => Some(b.realms.get(db.realm().name()).ok_or_else(|| {
crate::Error::Invalid("The character baseline does not contain this realm.".into())
})?),
Some(_) => {
return Err(crate::Error::Invalid(
"Unsupported character start baseline.".into(),
))
}
None => None,
};
let problems = check_inner(db, root, before, &mut preexisting)?;
let existing: usize = preexisting.values().sum();
let preexisting_details: Vec<_> = preexisting.into_iter().map(|((race, class), count)| serde_json::json!({"race": race, "class": class, "count": count})).collect();
if existing > 0 {
tracing::warn!(realm = db.realm().name(), characters = existing, "Unchanged pre-update characters with missing starting data retained; no character records were repaired or deleted");
}
if problems.is_empty() && existing == 0 {
return Ok(problems);
}
let report = serde_json::json!({
"schema": 1, "checkedAt": chrono::Utc::now().to_rfc3339(),
"realm": db.realm().name(), "problems": problems,
"preexistingUnsupportedCharacters": existing,
"preexistingCharacterStarts": preexisting_details,
"note": "Unchanged pre-update missing starts are reported separately. New missing character starts and all schema errors still block the update.",
});
let path = crate::registry::metadata_dir_for(root)?
.join("diagnostics")
@@ -245,6 +274,15 @@ pub(crate) fn repair_missing_defaults(
}
pub fn check(db: &Db, root: &Path) -> Result<Vec<Problem>> {
check_inner(db, root, None, &mut BTreeMap::new())
}
fn check_inner(
db: &Db,
root: &Path,
before: Option<&BTreeSet<crate::character_start_check::MissingStart>>,
existing: &mut BTreeMap<(u32, u32), usize>,
) -> Result<Vec<Problem>> {
let contract = if root.join(CONTRACT).is_file() {
let contract: Contract = fsx::read_json(&root.join(CONTRACT))?;
if contract.schema != 1 {
@@ -367,12 +405,24 @@ pub fn check(db: &Db, root: &Path) -> Result<Vec<Problem>> {
}
// Check owned characters too, including legacy classes and Wildcard characters. Their rows
// must not silently disappear from character selection after an otherwise healthy update.
let missing = db.query("SELECT c.race,c.class,COUNT(*) FROM acore_characters.characters c LEFT JOIN acore_world.playercreateinfo p ON p.race=c.race AND p.class=c.class WHERE p.race IS NULL GROUP BY c.race,c.class;")?;
for row in missing.lines() {
let fields: Vec<_> = row.split('\t').collect();
if fields.len() == 3 {
problems.push(Problem { database: "world".into(), table: "playercreateinfo".into(), column: String::new(), detail: format!("{} existing characters have no starting data for race {} / class {} and would be hidden from character selection", fields[2], fields[0], fields[1]) });
let current = crate::character_start_check::missing(db)?;
let blocking = if let Some(before) = before {
let introduced = crate::character_start_check::introduced(&current, before);
for character in current.intersection(before) {
*existing
.entry((character.race, character.class))
.or_default() += 1;
}
introduced
} else {
current
};
let mut counts = BTreeMap::<(u32, u32), usize>::new();
for character in blocking {
*counts.entry((character.race, character.class)).or_default() += 1;
}
for ((race, class), count) in counts {
problems.push(Problem { database: "world".into(), table: "playercreateinfo".into(), column: String::new(), detail: format!("{count} existing characters have no starting data for race {race} / class {class} and would be hidden from character selection") });
}
Ok(problems)
}
+248 -17
View File
@@ -22,6 +22,8 @@ use crate::pkgsource::{fetch_manifest, fetch_parts, Source};
use crate::registry::{InstallMeta, MetaDir};
const STAGED_PREFIX: &str = "_migrations/";
const CHARACTER_BASELINE: &str = "character-start-baseline.json";
const CHARACTER_BASELINE_HASH: &str = "@character-starts";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
@@ -106,6 +108,9 @@ pub trait Env {
fn verify_snapshot(&self, _id: &str) -> Result<()> {
Ok(())
}
fn character_start_baseline(&self) -> Result<Option<crate::character_start_check::Baseline>> {
Ok(None)
}
fn snapshot(&self) -> Result<String>;
fn restore_snapshot(&self, id: &str) -> Result<()>;
fn migrate(&self, manifest: &Manifest, staged_migrations: &Path) -> Result<ApplyReport>;
@@ -223,11 +228,12 @@ fn read_journal(path: &Path) -> Result<Txn> {
"Update journal contains invalid recovery hashes.".into(),
));
}
for key in txn
.recovery_hashes
.keys()
.filter(|key| !matches!(key.as_str(), "@install" | "@point"))
{
for key in txn.recovery_hashes.keys().filter(|key| {
!matches!(
key.as_str(),
"@install" | "@point" | CHARACTER_BASELINE_HASH
)
}) {
fsx::safe_join(path.parent().unwrap(), key)?;
}
if completed_legacy_repair {
@@ -684,6 +690,7 @@ pub struct Params<'a> {
#[derive(Debug, Serialize)]
pub struct Outcome {
pub txn: Txn,
pub preexisting_character_count: usize,
pub migrations: Option<ApplyReport>,
}
@@ -816,6 +823,26 @@ pub fn apply(p: &Params, report: &dyn Fn(&str, u8)) -> Result<Outcome> {
.insert("@point".into(), fsx::sha256_file(&point_meta)?);
}
save(meta_dir, &txn)?;
// Capture before any new files or SQL are applied; retry must reuse these exact bytes.
let baseline = match p.env.character_start_baseline() {
Ok(baseline) => baseline,
Err(error) => {
txn.state = State::Failed;
txn.message = Some(format!("The update was not applied because the character baseline could not be captured: {error}"));
save(meta_dir, &txn)?;
return Err(error);
}
};
let preexisting_character_count = baseline
.as_ref()
.map_or(0, |b| b.realms.values().map(|r| r.len()).sum());
if let Some(baseline) = &baseline {
let path = tdir.join(CHARACTER_BASELINE);
fsx::atomic_write_json(&path, baseline)?;
txn.recovery_hashes
.insert(CHARACTER_BASELINE_HASH.into(), fsx::sha256_file(&path)?);
save(meta_dir, &txn)?;
}
txn.ops = items
.iter()
.filter(|i| i.action != Action::Skip)
@@ -909,6 +936,7 @@ pub fn apply(p: &Params, report: &dyn Fn(&str, u8)) -> Result<Outcome> {
save(meta_dir, &txn)?;
return Ok(Outcome {
txn,
preexisting_character_count,
migrations: migrated,
});
}
@@ -919,6 +947,7 @@ pub fn apply(p: &Params, report: &dyn Fn(&str, u8)) -> Result<Outcome> {
let _ = archive;
Ok(Outcome {
txn,
preexisting_character_count,
migrations: migrated,
})
}
@@ -1039,6 +1068,7 @@ pub fn retry_validation(
)));
}
}
read_character_baseline(meta_dir, &txn)?;
env.ensure_stopped()?;
if let Err(error) = env.validate() {
txn.message = Some(format!(
@@ -1115,7 +1145,13 @@ fn restore_transaction(
txn: &mut Txn,
env: &dyn Env,
) -> Result<()> {
for (rel, expected) in &txn.recovery_hashes {
// This baseline is a validation input, not a recovery copy: corruption must block
// retry/commit, but must never prevent restoration of the verified safety backup.
for (rel, expected) in txn
.recovery_hashes
.iter()
.filter(|(key, _)| key.as_str() != CHARACTER_BASELINE_HASH)
{
let saved = match rel.as_str() {
"@install" => before.join("manager-install.json"),
"@point" => crate::backup::point_json(
@@ -1504,6 +1540,33 @@ fn prune(meta_dir: &Path, keep: usize) {
}
}
fn read_character_baseline(
meta: &Path,
txn: &Txn,
) -> Result<Option<crate::character_start_check::Baseline>> {
let path = txn_dir(meta, &txn.id)?.join(CHARACTER_BASELINE);
let Some(expected) = txn.recovery_hashes.get(CHARACTER_BASELINE_HASH) else {
if path.exists() {
return Err(Error::Invalid(
"An unverified character start baseline was found.".into(),
));
}
return Ok(None); // Older transactions remain strict; never learn a baseline after applying SQL.
};
if fsx::sha256_file(&path)? != *expected {
return Err(Error::Invalid(
"The saved character start baseline failed verification.".into(),
));
}
let baseline: crate::character_start_check::Baseline = fsx::read_json(&path)?;
if baseline.schema != 1 {
return Err(Error::Invalid(
"Unsupported character start baseline.".into(),
));
}
Ok(Some(baseline))
}
/// The real environment: a repack-shaped installation driven through its launcher.
pub struct RepackEnv<'a> {
pub root: &'a Path,
@@ -1511,6 +1574,12 @@ pub struct RepackEnv<'a> {
}
impl RepackEnv<'_> {
fn saved_character_baseline(&self) -> Result<Option<crate::character_start_check::Baseline>> {
match unfinished(self.meta_dir) {
Some(txn) => read_character_baseline(self.meta_dir, &txn),
None => Ok(None),
}
}
pub fn pending_migrations(&self, manifest: &Manifest) -> Result<usize> {
Ok(self
.pending_migrations_with(manifest, DatabaseAccess::Start)?
@@ -1527,9 +1596,9 @@ impl RepackEnv<'_> {
return Ok(Some(0));
}
let count = |db: &crate::db::Db| -> Result<usize> {
let db = db.clone().with_read_deadline(
std::time::Instant::now() + std::time::Duration::from_secs(15),
);
let db = db
.clone()
.with_read_deadline(std::time::Instant::now() + std::time::Duration::from_secs(15));
let realms = crate::realms::state(self.root)?;
let modes = realms.modes();
let mut count = 0;
@@ -1772,12 +1841,25 @@ impl Env for RepackEnv<'_> {
Ok(())
}
fn character_start_baseline(&self) -> Result<Option<crate::character_start_check::Baseline>> {
crate::backup::with_database(self.root, |db| {
crate::character_start_check::capture(db, self.root)
})
.map(Some)
}
fn migrate(&self, manifest: &Manifest, staged: &Path) -> Result<ApplyReport> {
crate::backup::with_database(self.root, |db| {
let identities = database_identities(db)?;
let result = migrate_databases(db, self.root, manifest, staged, &|| {
self.migration_snapshot()
})?;
let baseline = self.saved_character_baseline()?;
let result = migrate_databases(
db,
self.root,
manifest,
staged,
&|| self.migration_snapshot(),
baseline.as_ref(),
)?;
if result.failed.is_none() {
verify_database_identities(db, &identities)?;
}
@@ -1799,6 +1881,11 @@ impl RepackEnv<'_> {
crate::mysql_snapshot::stop(self.root)?;
self.ensure_stopped()?;
self.recover_validation()?;
let baseline = if check_schema {
self.saved_character_baseline()?
} else {
None
};
let result = (|| -> Result<()> {
crate::update_isolation::begin(self.root, self.meta_dir)?;
use crate::process::{observe, ServiceState};
@@ -1806,9 +1893,10 @@ impl RepackEnv<'_> {
if check_schema {
let modes = crate::realms::state(self.root)?.modes();
for mode in modes {
if let Some(p) = crate::schema_check::check_with_report(
if let Some(p) = crate::schema_check::check_update_with_report(
&db.clone().for_realm(mode),
self.root,
baseline.as_ref(),
)?
.first()
{
@@ -1851,8 +1939,7 @@ impl RepackEnv<'_> {
if o.mysql.state == ServiceState::Running
&& o.auth.state == ServiceState::Running
&& o.world.state == ServiceState::Running
&& o.extra_worlds()
.all(|s| s.state == ServiceState::Running)
&& o.extra_worlds().all(|s| s.state == ServiceState::Running)
{
let since = ready_since.get_or_insert_with(std::time::Instant::now);
if since.elapsed() >= std::time::Duration::from_secs(10) {
@@ -1869,7 +1956,26 @@ impl RepackEnv<'_> {
};
if healthy {
crate::backup::with_database(self.root, |db| {
verify_database_identities(db, &identities)
verify_database_identities(db, &identities)?;
if check_schema {
for mode in crate::realms::state(self.root)?.modes() {
if let Some(problem) = crate::schema_check::check_update_with_report(
&db.clone().for_realm(mode),
self.root,
baseline.as_ref(),
)?
.first()
{
return Err(Error::Invalid(format!(
"Database validation failed after startup on {}: {}: {}",
mode.name(),
problem.table,
problem.detail
)));
}
}
}
Ok(())
})?;
return Ok(());
}
@@ -1892,6 +1998,7 @@ fn migrate_databases(
manifest: &Manifest,
staged: &Path,
snapshot: &dyn Fn() -> Result<String>,
baseline: Option<&crate::character_start_check::Baseline>,
) -> Result<ApplyReport> {
let realms = crate::realms::state(root)?;
let modes = realms.modes();
@@ -1943,7 +2050,8 @@ fn migrate_databases(
return Ok(result);
}
crate::schema_check::repair_missing_defaults(&db, root, contract)?;
if let Some(p) = crate::schema_check::check_with_report(&db, root)?.first() {
if let Some(p) = crate::schema_check::check_update_with_report(&db, root, baseline)?.first()
{
return Err(Error::Invalid(format!(
"Database validation failed on {}: {}.{}: {}",
mode.name(),
@@ -2010,6 +2118,8 @@ mod tests {
use std::cell::{Cell, RefCell};
struct Fake {
character_baseline: RefCell<Option<crate::character_start_check::Baseline>>,
baseline_failed: Cell<bool>,
activation_expected: RefCell<Option<(PathBuf, String)>>,
activation_failed: Cell<bool>,
activated: Cell<bool>,
@@ -2027,6 +2137,8 @@ mod tests {
impl Fake {
fn ok() -> Fake {
Fake {
character_baseline: RefCell::new(None),
baseline_failed: Cell::new(false),
activation_expected: RefCell::new(None),
activation_failed: Cell::new(false),
activated: Cell::new(false),
@@ -2044,6 +2156,14 @@ mod tests {
}
impl Env for Fake {
fn character_start_baseline(
&self,
) -> Result<Option<crate::character_start_check::Baseline>> {
if self.baseline_failed.get() {
return Err(Error::Invalid("fixture baseline unavailable".into()));
}
Ok(self.character_baseline.borrow().clone())
}
fn activate(&self) -> Result<()> {
if let Some((meta, version)) = self.activation_expected.borrow().as_ref() {
ensure_recovered(meta)?;
@@ -3485,4 +3605,115 @@ mod tests {
.iter()
.any(|i| i.path == "Core/newfile.dll" && i.action == Action::Create));
}
fn baseline_fixture() -> crate::character_start_check::Baseline {
crate::character_start_check::Baseline {
schema: 1,
realms: BTreeMap::from([(
"coa".into(),
crate::character_start_check::parse_missing("1\t44\t14\n2\t44\t14\n3\t44\t14")
.unwrap(),
)]),
}
}
#[test]
fn character_baseline_is_captured_once_persisted_and_verified_for_retry() {
let w = world(&[], true);
let env = Fake::ok();
*env.character_baseline.borrow_mut() = Some(baseline_fixture());
env.healthy.set(false);
let out = run(&w, &env, BTreeMap::new(), None).unwrap();
assert_eq!(out.txn.state, State::NeedsDecision);
assert_eq!(out.preexisting_character_count, 3);
let baseline_path = txn_dir(&w.meta, &out.txn.id)
.unwrap()
.join(CHARACTER_BASELINE);
let original = fs::read(&baseline_path).unwrap();
assert_eq!(
read_character_baseline(&w.meta, &out.txn)
.unwrap()
.unwrap()
.realms["coa"]
.len(),
3
);
// A retry may not learn new gaps from an already modified database.
*env.character_baseline.borrow_mut() = None;
env.healthy.set(true);
fs::write(&baseline_path, b"{}").unwrap();
assert!(retry_validation(
&w.root,
&w.meta,
&out.txn.id,
&Source::Dir(w.pkg.clone()),
&w.key,
&env
)
.is_err());
fs::write(&baseline_path, original).unwrap();
let done = retry_validation(
&w.root,
&w.meta,
&out.txn.id,
&Source::Dir(w.pkg.clone()),
&w.key,
&env,
)
.unwrap();
assert_eq!(done.state, State::Committed);
}
#[test]
fn corrupt_character_baseline_does_not_prevent_safe_rollback() {
let w = world(&[], true);
let env = Fake::ok();
*env.character_baseline.borrow_mut() = Some(baseline_fixture());
env.healthy.set(false);
let out = run(&w, &env, BTreeMap::new(), None).unwrap();
fs::write(
txn_dir(&w.meta, &out.txn.id)
.unwrap()
.join(CHARACTER_BASELINE),
b"bad",
)
.unwrap();
let restored = rollback(&w.root, &w.meta, &out.txn.id, &env).unwrap();
assert_eq!(restored.state, State::RolledBack);
assert_eq!(read(&w, "Core/worldserver.exe"), b"world-v1");
}
#[test]
fn missing_or_unverified_character_baselines_fail_closed() {
let w = world(&[], true);
let env = Fake::ok();
env.healthy.set(false);
let out = run(&w, &env, BTreeMap::new(), None).unwrap();
assert!(read_character_baseline(&w.meta, &out.txn)
.unwrap()
.is_none());
let path = txn_dir(&w.meta, &out.txn.id)
.unwrap()
.join(CHARACTER_BASELINE);
fsx::atomic_write_json(&path, &baseline_fixture()).unwrap();
assert!(read_character_baseline(&w.meta, &out.txn).is_err());
let mut txn = out.txn;
txn.recovery_hashes.insert(
CHARACTER_BASELINE_HASH.into(),
fsx::sha256_file(&path).unwrap(),
);
fs::remove_file(path).unwrap();
assert!(read_character_baseline(&w.meta, &txn).is_err());
}
#[test]
fn baseline_capture_failure_precedes_file_and_database_changes() {
let w = world(&[], true);
let env = Fake::ok();
env.baseline_failed.set(true);
assert!(run(&w, &env, BTreeMap::new(), None).is_err());
assert_eq!(read(&w, "Core/worldserver.exe"), b"world-v1");
assert!(!env.calls.borrow().contains(&"migrate"));
assert!(!env.calls.borrow().contains(&"validate"));
assert!(unfinished(&w.meta).is_none());
}
}
+165
View File
@@ -0,0 +1,165 @@
# Existing Hide Races filter: internal research
Inspected 2026-10-27. No installed game files were changed. No game, server, database or desktop
automation was used for this investigation.
## Evidence
The owner supplied screenshots of the creation screen and Hide Races panel. The previously
extracted `Interface/GlueXML/CharacterCreate.lua` from `patch-ZZZF.MPQ` contains this implementation.
SHA-256 of the extracted Lua: `8816ef9b6839652db60da6de7d2a6d09ceed1f80323ca5c8e55271a4d5aacac3`.
This identifies the inspected file, not proven runtime archive precedence.
Line numbers below refer to the original LF-delimited file, ignoring carriage-return bytes.
The game source remains outside Git at `C:/games/source/per-race-evidence/`.
| Function / lines | Confirmed behavior |
| --- | --- |
| `CharacterCreate_LayoutRaceButtons`, 138–185 | Reads hidden entries by `#<button index>`, displayed name or lowercase name; hides and relays out buttons by faction |
| Same function, 173–180 | If no button remains visible, shows every button and clears its hidden marker |
| `CharacterCreateEnumerateRaces`, 1864–1899 | Uses native name/English-name/enabled triples; button indices follow enumeration order |
| `CharacterCreate_Finish`, 2184–2212 | Delegates to `CoACharacterNames.CreateCharacter`; no filter-policy check is present in this function |
| `CHAR_CREATE_RACE_IDS` and `SetRace` wrapper, 3404–3459 | Maps English display names and repeated occurrence order to a `bonusRaceID` originally used for racial text |
| Filter persistence, 4603–4701 | Registers `coaHiddenRaces` and `coaHiddenRaces2`; writes with `SetCVar` and optional C_Config setters/save, all protected by `pcall` |
| `RaceEntries`, 4703 onward | Displayed RaceID comes from `bonusRaceID`, first name-map ID, or finally button index |
| Row click, 4844–4856 | Saves the displayed name and `#<button index>`; the displayed RaceID is not the saved key |
| `SetAllChecked`, 4977–4985 | Builds the same name/index set; does not apply a server policy |
| Save handler, 4988–4995 | Stores draft and relays out buttons; does not explicitly choose a permitted replacement race |
| Row refresh, 5018–5041 | Stores `info.id` (button index) in `row.raceId`, while the label displays `info.raceID` |
| Click wrapper, 5056–5069 | Redirects a click on a hidden button to the first visible one |
The name-to-ID table is hardcoded and extended repeatedly later in the Lua. Examples of paired
names: Pandaren `{29,20}`, Murloc `{30,31}`, Earthen `{68,69}`, Haranir `{71,70}`,
Centaur `{75,102}` and Drakonid `{100,98}`. Name localization and enumeration-order changes
need validation; this table is not a universal verified RaceID API.
## Offline reproduction
An isolated harness executed the actual extracted layout, persistence and click-wrapper functions
using the already installed `lupa.lua51` runtime. Buttons, CVar storage, faction lookup and filter
button creation were mocked. No render, native race API, packet send, account or database was used.
Harness: `C:/games/source/per-race-evidence/probe_existing_filter.py`.
Machine-readable results: `C:/games/source/per-race-evidence/existing-filter-probe.json`.
All nine assertions were confirmed:
1. Saving one Pandaren by name hides both same-named Pandaren buttons.
2. A saved index plus saved name can hide two different races after reordering.
3. Hiding all buttons makes the layout show all buttons again.
4. Saving 128 synthetic index entries persists at most 480 characters; a fresh runtime recovered
only 115 of those indices. The exact losses depend on the input and sort order.
5. Saving/hiding the currently selected button leaves the harness's selection unchanged.
6. Clicking a hidden button redirects to the first visible one.
7. The same preference values apply across independent Glue runtimes; no realm identifier is read.
8. Saving `#82` does not hide Sethrak at button index 2, even when the button's `bonusRaceID`
is 82. Current serialization cannot simply be given real IDs instead of indices.
9. If persistent setters fail, saving still updates the in-memory list and reports no failure;
a fresh runtime loses that list. Protected calls suppress the errors.
The initial harness run lacked a stub for filter-button creation and failed six checks before
their assertions; adding that UI stub allowed the original assertions to run and pass. The later
expanded run passed all nine assertions. This correction
did not modify the inspected game Lua. These results are offline behavior checks, not live acceptance.
## Persistence and identity cross-check
Read-only searches of both the primary client and isolated copy found no `coaHiddenRaces` or
`coaHiddenRaces2` entries in their `WTF/Config.wtf` or `WTF/Custom/GlueConfig.json`, or in the
searched text configuration files. There is therefore no observed on-disk value establishing
where this installation persists the list. The presence of `SetCVar` calls alone does not prove
that an arbitrary registered CVar is archived. C_Config setters/save are optional and their
failures are suppressed. Physical persistence must be verified later by a controlled save/exit
and file comparison, when the owner allows game testing. The earlier Config.wtf suggestion
remains a hypothesis, not an established path.
Listfile-guided scanning of Lua members in patch-B, patch-T and patch-ZZZF found the filter's
setter calls but no implementation of these C_Config persistence methods. This does not establish
their absence at runtime: native code or another archive may provide them. No native client code
was executed or patched to investigate this.
The final `CHAR_CREATE_RACE_IDS` map was reconstructed by executing its literal declarations and
subsequent assignments in Lua 5.1. All 73 inspected ChrRaces rows whose NOT_PLAYABLE bit is clear
are represented by their English name and actual ID in that map. The comparison includes final
overrides, rather than only the initial table. Result:
`C:/games/source/per-race-evidence/race-filter-id-map-audit.json`.
This is good evidence that the map can support this version's UI integration. It is not proof
that each runtime button is assigned the right ID: repeated names depend on occurrence order,
the engine may enumerate a different set/order, and localized labels may not match the English
keys. `bonusRaceID` remains a candidate identity, not an authoritative native lookup.
## Suitability for CSM
The existing layout and UI are useful foundations. Directly replacing `coaHiddenRaces` with owner
restrictions is unsuitable: the player can clear the list, names can collide, indices can shift,
serialization truncates and the preferences are not realm-scoped. It would also overwrite the
player's own display choices. A local filter cannot enforce server creation policy.
Recommended integration to investigate next:
- Keep personal Hide Races preferences independent from the server-managed disabled RaceID set.
- Resolve actual RaceID per button from validated version-specific client data and faction/identity.
Never use a button-index fallback as an authoritative RaceID. Ambiguous mapping is unsupported,
not permission to hide another race with the same name.
- Compute visibility from personal preference OR the server restriction. Check All may clear
personal preferences but must not remove the server restriction.
- Preserve stock-race behavior and the existing layout, class-selection and Esteria wrappers.
The empty-layout fallback must not reveal a server-prohibited race.
- Validate selected race before advancing/creating, including after save, randomization, sex
changes and native selection resets. Do not renumber native race indices.
- Reconcile the selected local realm before PLAY with the client closed. Do not guess public-server
policy or mutate the player's saved preference when switching realms.
- Independently enforce creation on the server and in new-bot factories, preserving existing
character login/import and existing-bot admission.
One possible delivery is a small GlueXML extension in the single managed overlay, reusing existing
layout entry points while supplying a separately generated policy table. This is a proposal, not
an existing API or a selected filename. It still requires proven loading order and live validation.
An alternative CVar-based channel needs its own persistence and truncation checks and must not
reuse the personal hidden-list keys.
## Decision
Prioritize investigation of the existing GlueXML mechanism as the client integration candidate.
Do not yet commit to a DBC-only overlay, and do not declare the DBC hypothesis failed: it has not
been live-tested. No gameplay/client support claim follows from these screenshots or mock tests.
The next live acceptance must establish correct real RaceID mapping, one disabled race, independent
faction variants, selected-race replacement, Check All resistance to owner-policy removal, ordinary
race creation, existing-character login and profile switching. Interactive/database tests remain
deferred at the owner's request.
## User-operated visibility experiment and disabled-row prototype
The owner subsequently authorized a temporary patch in the isolated client. The first probe added
only a real-ID predicate for Sethrak 82, Gnoll 83 and Saberon 97 to the existing layout. A single
`Data/patch-ZZZZZ.MPQ` contained the modified CharacterCreate.lua; original archives and DBCs
were unchanged. The owner reported the races disappeared and supplied screenshots consistent
with that result. This is evidence that this particular Lua overlay affects this installation's
creation screen, not proof of universal MPQ precedence or completed creation/login tests.
The owner then selected the UI behavior: hide owner-prohibited races on the creation screen;
show them grey, unchecked and disabled in Hide Races, with a server-disabled label. Personal
preferences remain independent, including when the owner later re-enables the race.
`tools/race_visibility_lua_poc.py` now generates a version-pinned second laboratory probe. It
accepts only the exact inspected Lua fingerprint and the three previously tested RaceIDs.
Unknown identity is not interpreted as a button index. It guards disabled row clicks, restores
enabled state when a scroll row is reused, and prevents the empty-layout fallback from revealing
an owner-prohibited race. The disabled label has EN/RU/DE/FR/ES/ZH translations.
Eleven tests passed under Lua 5.1, covering syntax, disabled row state, personal preference,
scroll-row reuse, ambiguous identity, Check All, direct disabled-row click, six translations,
unsupported input rejection, empty-layout fallback and lifting restrictions.
Probe v2 was MPQ-roundtrip verified and installed only after observing that the isolated client
was closed. The previous owned probe's SHA-256 was checked before replacement, the existing
client patch lock was held, and the prior bytes were preserved outside the client. Its evidence
is `C:/games/source/per-race-evidence/lua-visibility-probe-v2/report.json`.
The primary client, all databases and all server processes were untouched.
This prototype still contains a fixed laboratory restriction set, not the future server-driven
policy. The owner confirmed grey, unchecked rows for the three probe races in game and supplied
screenshots. Selected-race validation, realm policy
reconciliation, source update handling, server enforcement and new-bot integration remain work.
+145
View File
@@ -0,0 +1,145 @@
# Per-race toggles: internal design and implementation status
This is an internal specification and work-in-progress record, not a released user guide.
Current verdict: **PARTIAL**. Client hiding and disabled rows were confirmed by the owner;
server policy, new-bot integration and Manager controls are now implemented in feature branches.
Native build qualification and server gameplay acceptance are still pending.
See [audit](../PER_RACE_TOGGLES_AUDIT.md) and [verification record](PER_RACE_TOGGLES_TESTS.md).
## Verified data and outstanding client decision
The local manifest identifies CoA Custom 1.9.2. The candidate source archive is `patch-ZZZF.MPQ`.
Its ChrRaces has WDBC layout 95/69/276/2428 (records/fields/record bytes/string bytes).
Its DBC SHA-256 is `b78635b08bf0bd63d2898fce97c1fb162c8a9c41632703172eefa88bae79061f`.
Observed IDs include Sethrak 82, Gnoll 83 and Saberon 97, all initially Flags 12.
The experiment sets `originalFlags | 0x01` only for selected IDs. Empty selection preserves
every original byte. Each run reads the explicitly selected source MPQ anew; it never consumes
the previous generated DBC. Re-enabling must restore the original record, including an original
NOT_PLAYABLE bit if present; it must not make an originally nonplayable race playable.
These observations do not qualify a client version. Actual archive precedence, menu behavior,
other-race creation and existing-character login are untested. No managed overlay filename has
been chosen. The tool does not infer precedence from filename sorting.
## Intended integration
```mermaid
flowchart TD
P[Existing realm configuration snapshot] --> S[Server creation policy]
P --> G[Availability generation, after client qualification]
O[Original effective client DBC] --> G
G --> V[Validate bytes and MPQ roundtrip]
V --> T[Existing client lock and transaction journal]
T --> M[One managed overlay]
S --> H[Normal account creation hook]
S --> C[Companions new-character creation]
S --> Q[SQUID new-character creation]
```
The new server key is `CoACustomRaces.DisabledRaceIds` in the existing module config.
It requires a newly built server; no installed server binary has been replaced. Empty or missing
key retains the previous master-switch behavior.
Validate the entire set before applying it; reject malformed, unknown and stock IDs without a
partial policy. Validate identity against effective server/client data, not numeric ranges alone.
Creation policy is independent of login and import. It must not modify existing characters,
appearance, items, spells, progress or Portable Characters identity. Bot creation additionally
obeys master switches, module switches, user exclusions and crashing-race restrictions. Existing
bot admission must not inherit a new-character restriction accidentally.
Use current module configuration, additive `.dist` merge and `Settings/realm-profiles/` snapshots.
Do not introduce another authoritative policy store. The future client record is provenance and
ownership metadata, not a replacement for the realm configuration.
Local PLAY must reconcile the selected profile before launch while the client is closed, using
the same `.coa-races.lock` as package operations. Shared clients have one currently installed
overlay; remote policies cannot be guessed. Unknown formats or conflicting ownership must fail
with a truthful status. Client and server application status must be separate in the UI.
Client repair/update must invalidate the previous overlay when the original effective DBC
changes and regenerate from the new original only after compatibility checks. Empty restrictions
must remove only the verified CSM-owned overlay. Actual install/recovery/update behavior is
not implemented by the offline tool.
## Offline tool
`tools/race_availability_poc.py` extracts with an explicitly supplied, existing Unicode StormLib
DLL. That DLL is a laboratory dependency only; no Manager/user dependency has been selected.
The tool writes `original.dbc`, `generated.dbc`, `experiment.MPQ` and `report.json` to a new output
directory after successful verification. It never installs an overlay, edits an input MPQ or
launches a process. The archive contains one game payload plus StormLib's internal listfile.
The fingerprint includes original DBC hash, sorted unique disabled IDs, algorithm version and
recorded client profile. It supports reproducibility checks; runtime caching is not implemented.
An empty selection still produces an offline test artifact so byte equality can be checked;
production empty-set removal is a separate, unimplemented requirement.
No game files or DLLs are checked into Git. Tests generate synthetic DBC/MPQ fixtures locally.
No export/distribution feature, release-channel change or publication is included.
## Remaining acceptance gate
The owner subsequently confirmed the Lua visibility and disabled-row probes through screenshots.
The selected client approach reuses the existing GlueXML filter rather than changing DBC flags.
This does not establish whether the earlier DBC-bit hypothesis works.
The owner deferred database/server testing while another server runs bot tests.
Do not launch the game, servers or MySQL or capture/control the screen without renewed authorization.
Use the owner-confirmed GlueXML approach for the next client integration stage. It preserves
the original DBC. The DBC-bit approach has not been declared incompatible; it was not live-tested.
## Server controls implemented in the feature branches
### Maintenance when new races are added
Whenever upstream adds races, include every new playable custom RaceID in the availability
list and verify its name and Horde/Alliance grouping. The Manager reads this list from the
installed server catalog automatically; update the server catalog rather than maintaining a
second hardcoded UI list. Review and explicitly save existing restrictions after the catalog
changes, preserving the owner's choices for unchanged IDs.
Also update and verify the client Lua RaceID mapping and filtering for the new races. A race
appearing in the Manager does not by itself establish client support. Check creation restrictions
and new-bot generation in both CoA Companions and SQUID, retaining user and crashing-race exclusions.
### Current implementation
Manager exposes a versioned catalog read from the server's `DataDir/dbc_races/ChrRaces.dbc`, with
strict WDBC layout/ID/name validation and stock/nonplayable rows excluded. The UI supports search,
counts, per-race allow checkboxes, Allow all, explicit Save/Discard and navigation guards. New
strings exist in all six Manager languages.
Saving requires a stopped server, no unfinished update, the existing control lock, an unchanged
catalog SHA-256 and the same selected realm as the loaded draft.
It uses the normal module backup/config writer. Servers whose distributed configuration does
not declare the new key cannot be configured through this control. The executable is also checked
for the key, following existing realm capability detection. The UI reports saved settings
and restart requirements, not a verified running-server Applied status. Template detection does
not independently attest the identity of a manually modified server executable.
Saved restrictions include the source catalog SHA-256. A changed catalog or orphaned IDs requires
explicit review and save; simply opening the panel does not migrate settings. Core and the offline
bot factory reject a mismatched bound catalog before creating characters. Empty hashes remain
supported for manually authored legacy configurations.
The core module stages a whole policy, validates configured IDs against loaded server race data,
and applies it atomically on startup/reload. Invalid input retains the previous policy; on an
initial invalid configuration, new custom creation remains disabled. Stock creation remains
available. The normal account hook remains in place and import/login paths are unchanged.
CoA Companions' common clone entry calls the account creation hook before inserting a new bot;
its selection also preserves explicit crashing exclusions. SQUID's random factory calls the
same hook while constructing candidate races, without adding owner restrictions to existing-bot
admission lists. The offline Companions factory reads configuration and filters prohibited
templates before creating accounts or generating insert SQL. No SQL was executed for verification.
The old Manager synchronization now preserves explicit user race exclusions. It only replaces
lists carrying its old ownership comment with an exact known generated value. Crashing-race
settings are never rewritten. BotsEnable is read directly from the Custom Races configuration
when available rather than inferred from unrelated exclusion choices.
Automatic production client synchronization and client update invalidation remain unimplemented.
Server-side catalog binding is implemented. The fixed three-race test overlay is not automatically changed
by these new server controls. This limitation is explicitly visible in the Manager UI.
+92
View File
@@ -0,0 +1,92 @@
# Per-race toggles: internal verification record
Date: 2026-10-27. Verdict: **PARTIAL**. Scope: source implementation, native builds and offline verification; live acceptance remains pending.
Latest source implementation checks additionally include:
- Manager catalog/configuration tests: 10 passed, including catalog binding, unknown-ID review, stale/invalid input rejection,
Allow all, preserving unknown configuration keys and leaving bot exclusions unchanged.
- Focused Manager race regression selection: 34 passed, 3 ignored because they require release
archives or another writable volume. The three ignored tests are not counted as passes.
- Frontend TypeScript/Vite build: passed after correcting the new component's error rendering.
- Existing i18n and module-settings checks: passed; new keys exist in all six languages.
- Core production-module harness: passed with synthetic Config/DBC stubs through verify_all.
- Companions production selector harness and five offline-factory policy tests: passed without
running a MySQL client or server.
- Complete native core build with staged Companions and SQUID: passed in the dedicated
`build-utf8` directory. Final source/build/harness verification passed in
`C:/games/source/per-race-core/.cache/verify-all/20261027-112640/report.json`.
Unit and gameplay stages were skipped. No installed binaries or services were changed.
- Rust Clippy with warnings denied: passed for coa-core.
- Final Tauri debug application build: passed after the catalog-review changes. Artifact:
`C:/games/source/per-race-manager/target/debug/coa-server-manager.exe`.
Frontend bundle-size and localized linker-output warnings were emitted; neither failed the build.
The first native configure lacked an OpenSSL root. A subsequent build was deliberately stopped
when its MSVC dependency prefix was found misencoded. The replacement uses the existing dynamic
OpenSSL/MySQL development libraries and a fresh UTF-8 environment. These earlier verify_all runs
ended FAILED and are not successful build evidence.
## Executed automated checks
Run from the Manager feature checkout:
```powershell
$env:COA_TEST_STORMLIB = '<absolute path to an existing Unicode StormLib DLL>'
python -B -m unittest discover -s tools -p 'test_race_availability_*.py' -v
```
The recorded run used the bundled repack Python at
`C:/games/CoA Server 2/Runtime/python/python.exe` and the existing DLL at
`C:/Users/Dion/AppData/Local/Programs/Python/Python311/Lib/site-packages/pympq/StormLib.dll`.
No database or game process is used. Without the explicit DLL environment variable, MPQ tests
are skipped; that is not equivalent to the recorded full pass.
| Group | Result | Actual scope |
| --- | --- | --- |
| DBC and fingerprint | PASS, 17 tests | Exact changed bytes; 1/5/50 IDs; other bits; original restoration; duplicate normalization; stock/unknown IDs; duplicate/invalid table IDs; corrupt/truncated/unknown layouts; localized name bounds and UTF-8; source/profile/set fingerprint inputs |
| Synthetic MPQ | PASS, 8 tests | 1/50 IDs produce one archive; one game payload; extraction equality; identical regenerated DBC/fingerprint; source unchanged; existing output preserved; packaging/readback/read/input errors publish no result; empty set preserves bytes |
| Total | PASS, 25 tests, zero skipped | Offline files only |
| Real three-race DBC/MPQ | PASS | Sethrak 82, Gnoll 83, Saberon 97; only Flags 12 → 13; one MPQ; re-extracted DBC equals expected; original MPQ hash unchanged |
| Existing filter behavior | CONFIRMED, 9 offline assertions | Original extracted Lua functions under Lua 5.1 with UI/CVar mocks; see existing-filter research |
| English name/ID map vs original DBC | PASS, 73 rows with NOT_PLAYABLE clear | Every inspected ID appears in the final literal Lua name map; runtime button identity remains unverified |
| Managed disabled-row Lua probe | PASS, 11 tests | Lua 5.1 syntax; grey/unchecked/disabled rows; personal choices; scroll reuse; unknown identity; Check All; click guard; six languages; input rejection; layout fallback; lifting restrictions |
| First Lua visibility probe | USER-OBSERVED | Owner reported Sethrak/Gnoll/Saberon absent and supplied screenshots; creation, login and grey rows not tested |
An initial new MPQ assertion expected one block-table entry and failed for both cardinalities.
Inspection showed StormLib also writes `(listfile)`. The corrected check requires two entries
and verifies the listfile names exactly one game file. All 25 tests then passed. This was a test
assumption correction, not a change to the functional requirement of one overlay.
Local evidence for real game files stays outside Git:
`C:/games/source/per-race-evidence/multiple-races-offline/report.json`.
Original DBC hash: `b78635b08bf0bd63d2898fce97c1fb162c8a9c41632703172eefa88bae79061f`.
Generated three-race DBC hash: `243fb36837b76ebd6943da574cc095be548b4530be7f06487debea6703db10d3`.
## Unexecuted checks
| Scope | Status | Reason |
| --- | --- | --- |
| Effective running-client DBC and general MPQ load order | NOT RUN | First Lua probe visibly affected this one installation, but effective DBC/general precedence remain unverified |
| LIVE-01 one disabled race | NOT RUN | Requires client and isolated server |
| LIVE-02 multiple disabled races and re-enable | NOT RUN | Requires client and isolated server |
| LIVE-03 existing character data/login | NOT RUN | No database/login testing performed |
| LIVE-04 bot generation, both systems separately | NOT RUN | Other bot tests are in progress; MySQL must remain untouched |
| LIVE-05 Portable Characters | NOT RUN | Requires disposable realm/database setup |
| LIVE-06 client repair/update | NOT RUN | Runtime overlay integration not implemented |
| LIVE-07 shared client | NOT RUN | Runtime profile reconciliation not implemented |
| Server config/parser/hook tests | PASS, offline | Actual module compiled with Config/DBC/crypto stubs; native build also passed |
| Client transaction crash/recovery matrix | NOT RUN | Offline result staging is not client install/recovery |
| Manager visual interaction | NOT RUN | Owner requested no screen capture/control; translation checks and frontend build passed |
| Full Rust workspace tests | NOT RUN | Focused race tests and native Manager build used instead |
| C++ build and verify_all | PASS, source/build/harness | No server/database process started; gameplay excluded |
| Release packaging and upgrades | NOT RUN | No release or runtime implementation prepared |
The copied client initially displayed a missing-critical-files message and crashed on exit.
The fault address maps to AMD's AMDXN32.DLL; root cause is unresolved. No experimental overlay
was installed at the time of that crash. Later Lua probes were installed only in the isolated copy,
and the owner confirmed hidden races and disabled grey rows. Creation could not be checked.
Neither observation is an availability live-test pass.
Existing character data and original game archives were not changed. No SQL was executed.
The feature must not be declared READY on these results.
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "coa-server-manager",
"version": "0.8.2",
"version": "0.9.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "coa-server-manager",
"version": "0.8.2",
"version": "0.9.4",
"dependencies": {
"@tauri-apps/api": "^2.12.0",
"@tauri-apps/plugin-dialog": "^2.8.0",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "coa-server-manager",
"private": true,
"version": "0.8.2",
"version": "0.9.4",
"license": "AGPL-3.0-only",
"type": "module",
"scripts": {
+11
View File
@@ -445,6 +445,17 @@
"max": 3600000,
"unit": "ms"
},
{
"key": "PortableSession.Enable",
"type": "bool",
"category": "characters",
"title": "Portable characters",
"description": "Allow players to play on this realm with portable characters saved in their Manager.",
"default": true,
"advanced": false,
"restartRequired": "world",
"dangerous": false
},
{
"key": "CharactersPerAccount",
"type": "int",
+1 -1
View File
@@ -12,7 +12,7 @@ crate-type = ["staticlib", "cdylib", "rlib"]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = [] }
tauri = { version = "2", features = ["tray-icon"] }
tauri-plugin-dialog = "2"
tauri-plugin-updater = "2"
tauri-plugin-process = "2"
+109 -3
View File
@@ -28,6 +28,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) -> std::result::Result<Value, String> {
tauri::async_runtime::spawn_blocking(move || {
coa_core::release_history::load(&component, &data_dir().join("release-history"))
})
.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).
@@ -1260,6 +1270,32 @@ async fn custom_races_status(
.await
}
#[tauri::command]
async fn race_availability(
state: State<'_, AppState>,
id: String,
) -> std::result::Result<coa_core::race_availability::Availability, UiError> {
let root = path_of(&state, &id)?;
blocking(move || coa_core::race_availability::status(&root)).await
}
#[tauri::command]
async fn race_availability_save(
state: State<'_, AppState>,
id: String,
catalog_sha256: String,
realm: coa_core::realms::Mode,
disabled_race_ids: Vec<u32>,
) -> std::result::Result<coa_core::race_availability::Availability, UiError> {
let root = path_of(&state, &id)?;
let _guard = BusyGuard::acquire(&state, &id)?;
blocking(move || {
let (dir, _) = install_meta(&root)?;
coa_core::race_availability::save(&root, &dir, &catalog_sha256, realm, &disabled_race_ids)
})
.await
}
#[tauri::command]
async fn custom_races_install(
app: AppHandle,
@@ -2756,6 +2792,8 @@ async fn console_command(
.await
}
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"));
@@ -2778,6 +2816,7 @@ pub fn run() {
host_control,
})
.invoke_handler(tauri::generate_handler![
release_history,
default_install_dir,
game_data_folder,
set_game_data_folder,
@@ -2875,6 +2914,8 @@ pub fn run() {
console_risk,
console_command,
custom_races_status,
race_availability,
race_availability_save,
custom_races_install,
custom_races_uninstall,
custom_races_toggle_client,
@@ -2909,11 +2950,75 @@ pub fn run() {
control_cmds::join_characters,
control_cmds::join_claim
])
.on_window_event(|window, event| {
if let tauri::WindowEvent::CloseRequested { api, .. } = event {
api.prevent_close();
let _ = window.hide();
}
})
.setup(|app| {
#[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 quit = MenuItem::with_id(app, "quit", "Exit", true, None::<&str>)?;
let menu = Menu::with_items(app, &[&show, &quit])?;
let mut builder = TrayIconBuilder::new()
.tooltip("CoA Server Manager")
.menu(&menu)
.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();
}
}
"quit" => {
QUIT_REQUESTED.store(true, std::sync::atomic::Ordering::SeqCst);
app.exit(0);
}
_ => {}
})
.on_tray_icon_event(|tray, event| {
if let TrayIconEvent::Click {
button: MouseButton::Left,
button_state: MouseButtonState::Up,
..
} = 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();
}
}
});
if let Some(icon) = app.default_window_icon() {
builder = builder.icon(icon.clone());
}
builder.build(app)?;
}
Ok(())
})
.build(tauri::generate_context!())
.expect("error while building CoA Server Manager")
.run(|app, event| {
// the Host loop stops with the application: what it is doing is finished first, the stores keep every session
if let tauri::RunEvent::Exit = event {
.run(|app, event| match event {
tauri::RunEvent::ExitRequested { api, .. } => {
if !QUIT_REQUESTED.load(std::sync::atomic::Ordering::SeqCst) {
api.prevent_exit();
}
}
tauri::RunEvent::Exit => {
// the Host loop stops with the application: what it is doing is finished first, the stores keep every session
if let Some(rt) = app.state::<AppState>().portable.clone() {
rt.shutdown();
}
@@ -2924,6 +3029,7 @@ pub fn run() {
rt.shutdown();
}
}
_ => {}
});
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "CoA Server Manager",
"version": "0.8.2",
"version": "0.9.4",
"identifier": "com.coa.servermanager",
"build": {
"beforeDevCommand": "npm run dev",
+1 -1
View File
@@ -15,7 +15,7 @@ const buttonVariants = cva(
size: {
sm: "h-9 px-3 text-sm",
md: "h-11 px-5 text-[15px]",
xl: "h-16 px-10 text-lg tracking-wide",
xl: "h-12 px-6 text-base",
},
},
defaultVariants: { variant: "secondary", size: "md" },
+15
View File
@@ -0,0 +1,15 @@
import { Button, type ButtonProps } from "./button";
/** Two explicit actions, each with its own enabled state and keyboard focus. */
export function SplitButton({ label, primary, secondary }: {
label: string;
primary: ButtonProps;
secondary: ButtonProps;
}) {
return <div role="group" aria-label={label} className="inline-flex max-w-full items-stretch rounded-md">
<Button type="button" variant="primary" {...primary}
className="h-auto min-h-12 min-w-0 rounded-r-none px-5 py-2 text-sm whitespace-normal" />
<Button type="button" variant="secondary" {...secondary}
className="h-auto min-h-12 min-w-0 rounded-l-none border-l border-l-gold/30 px-4 py-2 text-sm whitespace-normal" />
</div>;
}
+24
View File
@@ -0,0 +1,24 @@
# Release history data (internal)
The Manager feed is imported from the canonical `changelog/history.json`. The
server snapshot in this directory is copied from `Corfirean/coa-server-build`
commit `9bf1411de93e98cbcd0e8ebbcdac3a457d5fbaf0`, path
`changelog/history.json`, on 2026-10-28. Only schema, component, repository and
releases are retained. Do not independently edit historical records here.
At runtime the native read-only command fetches the fixed canonical URL, bounds
and validates the feed, and caches it for offline use. The bundled records appear
immediately and remain available if neither network nor cache is usable. These
records cannot select a package or authorize an update.
`latest-note-translations.json` contains the reviewed Manager notes through 0.9.3, the new
0.9.4 Manager entries, and the 0.261028.83 server notes in Russian, German, French, Spanish and Simplified
Chinese. English remains canonical. Translations are keyed by exact original
text: changing an original invalidates its translation. A partly translated
release falls back entirely to English and displays an explicit notice.
When preparing future release notes, refresh the server snapshot from a pinned
canonical commit and add all five translations for each new original note.
Never rewrite released fragments to add translations. Run
`node --test tools/release-history.test.mjs`; its completeness check expects the
latest bundled record of each component to have every translation.
+261
View File
@@ -0,0 +1,261 @@
{
"manager": {
"ru": {
"Choose Parallel or Global level scaling in module settings": "Выбирайте параллельное или глобальное масштабирование уровней в настройках модуля",
"Report Content Scaling problems directly to its repository": "Отправляйте отчёты о проблемах Content Scaling прямо в его репозиторий",
"Send custom race problem reports directly to their maintainer": "Отправляйте отчёты о проблемах дополнительных рас напрямую их разработчику",
"Internet sharing restores the LAN address after server restarts": "Общий доступ через интернет восстанавливает адрес локальной сети после перезапуска сервера",
"Configure custom race availability for new characters": "Настраивайте доступность дополнительных рас для новых персонажей",
"Public listing offers every realm that starts together, not just the main one": "Публиковать можно каждый реалм, запускаемый вместе с основным",
"Public listing is a short list of realms with a window for the details": "Публичные реалмы представлены компактным списком с отдельным окном подробностей",
"Configure profession and defense skill gains in server settings": "Настраивайте рост навыков профессий и защиты в настройках сервера",
"Starting a server sets the character classes of the realm chosen on Overview": "При запуске применяются классы персонажей реалма, выбранного на экране «Обзор»",
"Start Wildcard and Warcraft Reborn together with Conquest of Azeroth": "Запускайте Wildcard и Warcraft Reborn вместе с Conquest of Azeroth",
"Control portable characters and keep Manager running in the system tray": "Управляйте переносимыми персонажами и оставляйте Manager работать в системном трее",
"Existing unsupported character records no longer block unrelated server updates": "Старые неподдерживаемые записи персонажей больше не блокируют несвязанные обновления сервера",
"New server installation waits for slower database startup": "Установка нового сервера дольше ожидает запуска базы на медленных дисках",
"Find and edit CoA options in the existing server settings": "Параметры CoA доступны для поиска и редактирования в настройках сервера",
"Simultaneous update checks share results or wait their turn": "Одновременные проверки обновлений используют общий результат или ожидают своей очереди",
"Recovery can stop an unfinished world startup after restoring an older launcher": "Восстановление может остановить зависший запуск мира после возврата старого launcher",
"Slow server startup no longer triggers an early update rollback": "Медленный запуск сервера больше не вызывает преждевременный откат обновления",
"Settings group updates, startup and maintenance with translated release history": "Настройки сгруппированы по обновлениям, запуску и обслуживанию с переведённой историей выпусков",
"Update and launch without updating share a divided button": "Обновление и запуск без обновления объединены в разделённую кнопку",
"Maximizing the window keeps text and controls at a comfortable size": "При разворачивании окна текст и элементы управления сохраняют удобный размер"
},
"de": {
"Choose Parallel or Global level scaling in module settings": "Parallele oder globale Levelskalierung in den Moduleinstellungen wählen",
"Report Content Scaling problems directly to its repository": "Probleme mit Content Scaling direkt in dessen Repository melden",
"Send custom race problem reports directly to their maintainer": "Probleme mit zusätzlichen Völkern direkt an deren Entwickler melden",
"Internet sharing restores the LAN address after server restarts": "Internetfreigabe stellt nach Serverneustarts die LAN-Adresse wieder her",
"Configure custom race availability for new characters": "Verfügbarkeit zusätzlicher Völker für neue Charaktere festlegen",
"Public listing offers every realm that starts together, not just the main one": "Alle gemeinsam gestarteten Realms können veröffentlicht werden, nicht nur der Hauptrealm",
"Public listing is a short list of realms with a window for the details": "Öffentliche Realms erscheinen als kurze Liste mit einem Detailfenster",
"Configure profession and defense skill gains in server settings": "Zuwachs von Berufs- und Verteidigungsfertigkeiten in den Servereinstellungen festlegen",
"Starting a server sets the character classes of the realm chosen on Overview": "Beim Serverstart werden die Charakterklassen des in der Übersicht gewählten Realms angewendet",
"Start Wildcard and Warcraft Reborn together with Conquest of Azeroth": "Wildcard und Warcraft Reborn gemeinsam mit Conquest of Azeroth starten",
"Control portable characters and keep Manager running in the system tray": "Portable Charaktere verwalten und Manager im Infobereich weiterlaufen lassen",
"Existing unsupported character records no longer block unrelated server updates": "Bestehende nicht unterstützte Charakterdatensätze blockieren keine unabhängigen Serverupdates mehr",
"New server installation waits for slower database startup": "Die Neuinstallation wartet länger auf einen langsamen Datenbankstart",
"Find and edit CoA options in the existing server settings": "CoA-Optionen in den bestehenden Servereinstellungen suchen und bearbeiten",
"Simultaneous update checks share results or wait their turn": "Gleichzeitige Updateprüfungen teilen Ergebnisse oder warten aufeinander",
"Recovery can stop an unfinished world startup after restoring an older launcher": "Die Wiederherstellung stoppt einen unvollständigen Weltstart auch mit altem Launcher",
"Slow server startup no longer triggers an early update rollback": "Ein langsamer Serverstart löst keinen vorzeitigen Update-Rollback mehr aus",
"Settings group updates, startup and maintenance with translated release history": "Einstellungen bündeln Updates, Start und Wartung mit übersetztem Versionsverlauf",
"Update and launch without updating share a divided button": "Aktualisieren und ohne Update starten teilen sich eine geteilte Schaltfläche",
"Maximizing the window keeps text and controls at a comfortable size": "Beim Maximieren bleiben Text und Bedienelemente angenehm groß"
},
"fr": {
"Choose Parallel or Global level scaling in module settings": "Choisissez une progression parallèle ou globale des niveaux dans les paramètres du module",
"Report Content Scaling problems directly to its repository": "Signalez les problèmes de Content Scaling directement dans son dépôt",
"Send custom race problem reports directly to their maintainer": "Envoyez les signalements concernant les races supplémentaires directement à leur développeur",
"Internet sharing restores the LAN address after server restarts": "Le partage Internet rétablit l’adresse du réseau local après un redémarrage du serveur",
"Configure custom race availability for new characters": "Configurez les races supplémentaires disponibles pour les nouveaux personnages",
"Public listing offers every realm that starts together, not just the main one": "Tous les royaumes démarrant ensemble peuvent être publiés, pas seulement le principal",
"Public listing is a short list of realms with a window for the details": "Les royaumes publics apparaissent dans une liste compacte avec une fenêtre de détails",
"Configure profession and defense skill gains in server settings": "Configurez les gains de compétences de métier et de défense dans les paramètres du serveur",
"Starting a server sets the character classes of the realm chosen on Overview": "Le démarrage applique les classes du royaume choisi sur l’écran Aperçu",
"Start Wildcard and Warcraft Reborn together with Conquest of Azeroth": "Démarrez Wildcard et Warcraft Reborn avec Conquest of Azeroth",
"Control portable characters and keep Manager running in the system tray": "Gérez les personnages portables et laissez Manager fonctionner dans la zone de notification",
"Existing unsupported character records no longer block unrelated server updates": "Les anciennes fiches de personnage non prises en charge ne bloquent plus les mises à jour sans rapport",
"New server installation waits for slower database startup": "L’installation attend le démarrage de la base sur les disques plus lents",
"Find and edit CoA options in the existing server settings": "Recherchez et modifiez les options CoA dans les paramètres du serveur",
"Simultaneous update checks share results or wait their turn": "Les vérifications simultanées partagent leurs résultats ou attendent leur tour",
"Recovery can stop an unfinished world startup after restoring an older launcher": "La restauration peut arrêter un démarrage du monde inachevé avec un ancien lanceur",
"Slow server startup no longer triggers an early update rollback": "Un démarrage lent du serveur ne déclenche plus un retour arrière prématuré",
"Settings group updates, startup and maintenance with translated release history": "Les paramètres regroupent les mises à jour, le démarrage et la maintenance avec un historique traduit",
"Update and launch without updating share a divided button": "La mise à jour et le lancement sans mise à jour partagent un bouton divisé",
"Maximizing the window keeps text and controls at a comfortable size": "Le texte et les commandes gardent une taille confortable lorsque la fenêtre est maximisée"
},
"es": {
"Choose Parallel or Global level scaling in module settings": "Elige escalado de nivel paralelo o global en los ajustes del módulo",
"Report Content Scaling problems directly to its repository": "Informa de problemas de Content Scaling directamente en su repositorio",
"Send custom race problem reports directly to their maintainer": "Envía los informes sobre razas adicionales directamente a su desarrollador",
"Internet sharing restores the LAN address after server restarts": "El acceso por Internet restaura la dirección de red local tras reiniciar el servidor",
"Configure custom race availability for new characters": "Configura las razas adicionales disponibles para personajes nuevos",
"Public listing offers every realm that starts together, not just the main one": "Puedes publicar todos los reinos que se inician juntos, no solo el principal",
"Public listing is a short list of realms with a window for the details": "Los reinos públicos se muestran en una lista breve con una ventana de detalles",
"Configure profession and defense skill gains in server settings": "Configura las mejoras de habilidades de profesión y defensa en los ajustes del servidor",
"Starting a server sets the character classes of the realm chosen on Overview": "Al iniciar el servidor se aplican las clases del reino elegido en Resumen",
"Start Wildcard and Warcraft Reborn together with Conquest of Azeroth": "Inicia Wildcard y Warcraft Reborn junto con Conquest of Azeroth",
"Control portable characters and keep Manager running in the system tray": "Gestiona personajes portátiles y mantén Manager en la bandeja del sistema",
"Existing unsupported character records no longer block unrelated server updates": "Los registros antiguos de personajes no compatibles ya no bloquean actualizaciones del servidor no relacionadas",
"New server installation waits for slower database startup": "La instalación espera más tiempo al inicio de la base de datos en discos lentos",
"Find and edit CoA options in the existing server settings": "Busca y edita opciones de CoA en la configuración actual del servidor",
"Simultaneous update checks share results or wait their turn": "Las comprobaciones simultáneas comparten resultados o esperan su turno",
"Recovery can stop an unfinished world startup after restoring an older launcher": "La recuperación puede detener el inicio del mundo tras restaurar un lanzador antiguo",
"Slow server startup no longer triggers an early update rollback": "El inicio lento del servidor ya no provoca una reversión prematura de la actualización",
"Settings group updates, startup and maintenance with translated release history": "Los ajustes agrupan actualizaciones, inicio y mantenimiento con un historial de versiones traducido",
"Update and launch without updating share a divided button": "Actualizar e iniciar sin actualizar comparten un botón dividido",
"Maximizing the window keeps text and controls at a comfortable size": "Al maximizar la ventana, el texto y los controles mantienen un tamaño cómodo"
},
"zh": {
"Choose Parallel or Global level scaling in module settings": "在模块设置中选择并行或全局等级缩放",
"Report Content Scaling problems directly to its repository": "直接向 Content Scaling 仓库报告问题",
"Send custom race problem reports directly to their maintainer": "将自定义种族问题直接报告给其维护者",
"Internet sharing restores the LAN address after server restarts": "服务器重启后,互联网共享会恢复局域网地址",
"Configure custom race availability for new characters": "设置新角色可选的自定义种族",
"Public listing offers every realm that starts together, not just the main one": "可以发布所有同时启动的服务器,而不仅是主服务器",
"Public listing is a short list of realms with a window for the details": "公开服务器使用简短列表展示,详情在单独窗口中查看",
"Configure profession and defense skill gains in server settings": "在服务器设置中调整专业和防御技能的提升",
"Starting a server sets the character classes of the realm chosen on Overview": "启动时会应用“概览”中所选服务器的角色职业",
"Start Wildcard and Warcraft Reborn together with Conquest of Azeroth": "将 Wildcard 和 Warcraft Reborn 与 Conquest of Azeroth 一同启动",
"Control portable characters and keep Manager running in the system tray": "管理可携带角色,并让 Manager 继续在系统托盘中运行",
"Existing unsupported character records no longer block unrelated server updates": "已有的不受支持角色记录不再阻止无关的服务器更新",
"New server installation waits for slower database startup": "安装新服务器时会等待较慢的数据库启动",
"Find and edit CoA options in the existing server settings": "在现有服务器设置中查找和编辑 CoA 选项",
"Simultaneous update checks share results or wait their turn": "同时进行的更新检查会共用结果或依次执行",
"Recovery can stop an unfinished world startup after restoring an older launcher": "恢复旧版启动器后,恢复流程也能停止未完成启动的世界服务器",
"Slow server startup no longer triggers an early update rollback": "服务器启动缓慢不再导致更新过早回滚",
"Settings group updates, startup and maintenance with translated release history": "设置按更新、启动和维护分组,并提供已翻译的版本历史",
"Update and launch without updating share a divided button": "更新和不更新直接启动使用同一个分段按钮",
"Maximizing the window keeps text and controls at a comfortable size": "最大化窗口时,文字和控件仍保持舒适的大小"
}
},
"server": {
"ru": {
"Restrict new characters by custom race without changing existing characters": "Ограничивайте выбор дополнительных рас для новых персонажей, не меняя существующих",
"More class abilities, items and Pale Reach quests work as intended": "Исправлена работа ряда классовых способностей, предметов и заданий Pale Reach",
"Witch Doctor and Guardian bots use their totems and standards, and fewer casts are refused": "Боты Witch Doctor и Guardian используют тотемы и штандарты; заклинания реже отклоняются",
"Venomancer Fortitude tanks use their real defensive abilities": "Танки Venomancer Fortitude используют свои настоящие защитные способности",
"Healer bots waste fewer big heals and tank bots spread their defensives": "Лекари реже тратят мощное исцеление впустую, а танки распределяют защитные способности",
"Dungeon bots drink and rest until the tank is ready to go on": "Боты в подземельях пьют и отдыхают, пока танк не будет готов продолжить",
"Archery Rangers use Precision Shot and Brutal Shot": "Archery Ranger использует Precision Shot и Brutal Shot",
"Black Knight tank bots can pull in auto-dungeon mode": "Танк Black Knight может начинать бой в автоматическом режиме подземелий",
"Boltslinger bots use spells they actually know": "Boltslinger использует только изученные заклинания",
"Bots with unsuitable gear are refitted at login": "Боты с неподходящим снаряжением переодеваются при входе",
"Bots with full bags make room to hand in finished quests": "Боты с полными сумками освобождают место для сдачи выполненных заданий",
"Bots pick weapons and shields for their combat spells, not for enchanting recipes": "Боты подбирают оружие и щиты для боевых способностей, а не для рецептов зачарования",
"Bots get their gear repaired and stop looping to the repairer": "Боты чинят снаряжение и перестают ходить к ремонтнику по кругу",
"Bots stay out of Outland and Northrend when those are not scaled to the level cap": "Боты не отправляются в Запределье и Нордскол, если те не масштабированы под предел уровня",
"Bots plan long walks around areas too strong for them": "При дальних переходах боты обходят слишком опасные для них области",
"Dead bots run back to their bodies and come back healthy": "Погибшие боты возвращаются к телам и воскресают здоровыми",
"Meet travelling companions and rivals in dynamic open-world encounters": "Встречайте попутчиков и соперников в динамических событиях открытого мира",
"New companions respect the server's custom race restrictions": "Новые спутники соблюдают ограничения дополнительных рас сервера",
"Ranged bots no longer stand still while Auto Shot or Shoot is active": "Боты дальнего боя больше не замирают при активном Auto Shot или Shoot",
"Battleground bots no longer travel in a straight line": "Боты на полях боя больше не перемещаются по прямой",
"Far less server lag with hundreds of bots online": "Значительно снижены задержки сервера при сотнях ботов в сети",
"Inspect the mana restoration spells recognized by an online companion": "Просматривайте заклинания восстановления маны, распознанные у спутника в сети",
"Bots stop hitting mobs they cannot reach": "Боты прекращают атаковать недоступных противников",
"Bot economy errands skip groups, battlegrounds and dungeons": "Экономические поручения ботов не выполняются в группах, на полях боя и в подземельях",
"Dungeon finder fills your group with bots that really join you": "Поиск подземелий заполняет группу ботами, которые действительно присоединяются к вам",
"Stop an unfinished server startup before restoring its database": "Перед восстановлением базы данных можно остановить незавершённый запуск сервера",
"Imported 40 upstream commits with class, item and Pale Reach quest fixes, optional account-wide friends, and corrected Vanity purchases": "Включены 40 изменений апстрима: исправления классов, предметов и заданий Pale Reach, необязательные друзья на весь аккаунт и исправленные покупки Vanity"
},
"de": {
"Restrict new characters by custom race without changing existing characters": "Neue Charaktere nach zusätzlichem Volk beschränken, ohne bestehende Charaktere zu ändern",
"More class abilities, items and Pale Reach quests work as intended": "Weitere Klassenfähigkeiten, Gegenstände und Pale-Reach-Quests funktionieren korrekt",
"Witch Doctor and Guardian bots use their totems and standards, and fewer casts are refused": "Witch-Doctor- und Guardian-Bots nutzen Totems und Standarten; weniger Zauber werden abgelehnt",
"Venomancer Fortitude tanks use their real defensive abilities": "Venomancer-Fortitude-Tanks nutzen ihre tatsächlichen Defensivfähigkeiten",
"Healer bots waste fewer big heals and tank bots spread their defensives": "Heiler verschwenden weniger große Heilungen und Tanks verteilen ihre Defensivfähigkeiten",
"Dungeon bots drink and rest until the tank is ready to go on": "Dungeon-Bots trinken und ruhen, bis der Tank bereit ist",
"Archery Rangers use Precision Shot and Brutal Shot": "Archery Ranger nutzen Precision Shot und Brutal Shot",
"Black Knight tank bots can pull in auto-dungeon mode": "Black-Knight-Tanks können im automatischen Dungeonmodus Gegner heranziehen",
"Boltslinger bots use spells they actually know": "Boltslinger nutzen nur tatsächlich erlernte Zauber",
"Bots with unsuitable gear are refitted at login": "Bots mit ungeeigneter Ausrüstung werden beim Anmelden neu ausgestattet",
"Bots with full bags make room to hand in finished quests": "Bots mit vollen Taschen schaffen Platz zum Abgeben erledigter Quests",
"Bots pick weapons and shields for their combat spells, not for enchanting recipes": "Bots wählen Waffen und Schilde nach Kampffähigkeiten statt Verzauberungsrezepten",
"Bots get their gear repaired and stop looping to the repairer": "Bots reparieren Ausrüstung und laufen nicht mehr wiederholt zum Reparateur",
"Bots stay out of Outland and Northrend when those are not scaled to the level cap": "Bots meiden Scherbenwelt und Nordend, wenn diese nicht auf das Levellimit skaliert sind",
"Bots plan long walks around areas too strong for them": "Bots umgehen auf langen Wegen Gebiete mit zu starken Gegnern",
"Dead bots run back to their bodies and come back healthy": "Tote Bots kehren zu ihren Körpern zurück und werden gesund wiederbelebt",
"Meet travelling companions and rivals in dynamic open-world encounters": "Begegne reisenden Begleitern und Rivalen in dynamischen Ereignissen der offenen Welt",
"New companions respect the server's custom race restrictions": "Neue Begleiter beachten die Beschränkungen zusätzlicher Völker",
"Ranged bots no longer stand still while Auto Shot or Shoot is active": "Fernkampf-Bots bleiben bei aktivem Auto Shot oder Shoot nicht mehr stehen",
"Battleground bots no longer travel in a straight line": "Schlachtfeld-Bots bewegen sich nicht mehr geradlinig",
"Far less server lag with hundreds of bots online": "Deutlich weniger Serververzögerungen bei Hunderten aktiven Bots",
"Inspect the mana restoration spells recognized by an online companion": "Erkannte Manaregeneration-Zauber eines aktiven Begleiters anzeigen",
"Bots stop hitting mobs they cannot reach": "Bots greifen unerreichbare Gegner nicht weiter an",
"Bot economy errands skip groups, battlegrounds and dungeons": "Wirtschaftsaufgaben der Bots überspringen Gruppen, Schlachtfelder und Dungeons",
"Dungeon finder fills your group with bots that really join you": "Der Dungeonfinder füllt Gruppen mit Bots, die sich tatsächlich anschließen",
"Stop an unfinished server startup before restoring its database": "Unvollständigen Serverstart vor dem Wiederherstellen der Datenbank stoppen",
"Imported 40 upstream commits with class, item and Pale Reach quest fixes, optional account-wide friends, and corrected Vanity purchases": "40 Upstream-Änderungen mit Klassen-, Gegenstands- und Pale-Reach-Questkorrekturen, optionalen accountweiten Freunden und korrigierten Vanity-Käufen übernommen"
},
"fr": {
"Restrict new characters by custom race without changing existing characters": "Restreignez les races supplémentaires des nouveaux personnages sans modifier les personnages existants",
"More class abilities, items and Pale Reach quests work as intended": "Davantage de capacités de classe, d’objets et de quêtes de Pale Reach fonctionnent correctement",
"Witch Doctor and Guardian bots use their totems and standards, and fewer casts are refused": "Les bots Witch Doctor et Guardian utilisent leurs totems et étendards ; moins de sorts sont refusés",
"Venomancer Fortitude tanks use their real defensive abilities": "Les tanks Venomancer Fortitude utilisent leurs véritables capacités défensives",
"Healer bots waste fewer big heals and tank bots spread their defensives": "Les soigneurs gaspillent moins de gros soins et les tanks répartissent leurs défenses",
"Dungeon bots drink and rest until the tank is ready to go on": "Les bots de donjon boivent et se reposent jusqu’à ce que le tank soit prêt",
"Archery Rangers use Precision Shot and Brutal Shot": "Les Archery Rangers utilisent Precision Shot et Brutal Shot",
"Black Knight tank bots can pull in auto-dungeon mode": "Les tanks Black Knight peuvent engager les ennemis en mode donjon automatique",
"Boltslinger bots use spells they actually know": "Les Boltslingers utilisent les sorts qu’ils connaissent réellement",
"Bots with unsuitable gear are refitted at login": "Les bots mal équipés reçoivent un équipement adapté à la connexion",
"Bots with full bags make room to hand in finished quests": "Les bots aux sacs pleins font de la place pour rendre les quêtes terminées",
"Bots pick weapons and shields for their combat spells, not for enchanting recipes": "Les bots choisissent armes et boucliers selon leurs sorts de combat, pas les recettes d’enchantement",
"Bots get their gear repaired and stop looping to the repairer": "Les bots font réparer leur équipement sans retourner en boucle chez le réparateur",
"Bots stay out of Outland and Northrend when those are not scaled to the level cap": "Les bots évitent l’Outreterre et le Norfendre si leur niveau n’est pas adapté au plafond",
"Bots plan long walks around areas too strong for them": "Les bots contournent les zones trop dangereuses lors des longs trajets",
"Dead bots run back to their bodies and come back healthy": "Les bots morts rejoignent leur corps et reviennent en bonne santé",
"Meet travelling companions and rivals in dynamic open-world encounters": "Rencontrez des compagnons voyageurs et des rivaux lors d’événements dynamiques en monde ouvert",
"New companions respect the server's custom race restrictions": "Les nouveaux compagnons respectent les restrictions de races supplémentaires du serveur",
"Ranged bots no longer stand still while Auto Shot or Shoot is active": "Les bots à distance ne restent plus immobiles lorsque Auto Shot ou Shoot est actif",
"Battleground bots no longer travel in a straight line": "Les bots des champs de bataille ne se déplacent plus en ligne droite",
"Far less server lag with hundreds of bots online": "Beaucoup moins de ralentissements avec des centaines de bots connectés",
"Inspect the mana restoration spells recognized by an online companion": "Consultez les sorts de restauration de mana reconnus chez un compagnon connecté",
"Bots stop hitting mobs they cannot reach": "Les bots cessent d’attaquer les ennemis inaccessibles",
"Bot economy errands skip groups, battlegrounds and dungeons": "Les tâches économiques des bots ignorent groupes, champs de bataille et donjons",
"Dungeon finder fills your group with bots that really join you": "La recherche de donjon remplit votre groupe avec des bots qui vous rejoignent réellement",
"Stop an unfinished server startup before restoring its database": "Arrêtez un démarrage de serveur inachevé avant de restaurer sa base de données",
"Imported 40 upstream commits with class, item and Pale Reach quest fixes, optional account-wide friends, and corrected Vanity purchases": "Intégration de 40 changements amont : classes, objets et quêtes de Pale Reach corrigés, amis de compte facultatifs et achats Vanity corrigés"
},
"es": {
"Restrict new characters by custom race without changing existing characters": "Restringe las razas adicionales de personajes nuevos sin modificar los existentes",
"More class abilities, items and Pale Reach quests work as intended": "Más habilidades de clase, objetos y misiones de Pale Reach funcionan correctamente",
"Witch Doctor and Guardian bots use their totems and standards, and fewer casts are refused": "Los bots Witch Doctor y Guardian usan sus tótems y estandartes y se rechazan menos hechizos",
"Venomancer Fortitude tanks use their real defensive abilities": "Los tanques Venomancer Fortitude usan sus verdaderas habilidades defensivas",
"Healer bots waste fewer big heals and tank bots spread their defensives": "Los sanadores desperdician menos curas grandes y los tanques distribuyen sus defensivos",
"Dungeon bots drink and rest until the tank is ready to go on": "Los bots de mazmorra beben y descansan hasta que el tanque está listo",
"Archery Rangers use Precision Shot and Brutal Shot": "Los Archery Rangers usan Precision Shot y Brutal Shot",
"Black Knight tank bots can pull in auto-dungeon mode": "Los tanques Black Knight pueden iniciar combates en el modo automático de mazmorras",
"Boltslinger bots use spells they actually know": "Los Boltslingers usan hechizos que realmente conocen",
"Bots with unsuitable gear are refitted at login": "Los bots con equipo inadecuado reciben equipo apropiado al conectarse",
"Bots with full bags make room to hand in finished quests": "Los bots con bolsas llenas hacen espacio para entregar misiones completadas",
"Bots pick weapons and shields for their combat spells, not for enchanting recipes": "Los bots eligen armas y escudos por sus hechizos de combate, no por recetas de encantamiento",
"Bots get their gear repaired and stop looping to the repairer": "Los bots reparan su equipo y dejan de volver al reparador en bucle",
"Bots stay out of Outland and Northrend when those are not scaled to the level cap": "Los bots evitan Terrallende y Rasganorte si no están escalados al límite de nivel",
"Bots plan long walks around areas too strong for them": "Los bots evitan zonas demasiado peligrosas en los viajes largos",
"Dead bots run back to their bodies and come back healthy": "Los bots muertos vuelven a sus cuerpos y regresan con buena salud",
"Meet travelling companions and rivals in dynamic open-world encounters": "Encuentra compañeros viajeros y rivales en encuentros dinámicos de mundo abierto",
"New companions respect the server's custom race restrictions": "Los nuevos compañeros respetan las restricciones de razas adicionales del servidor",
"Ranged bots no longer stand still while Auto Shot or Shoot is active": "Los bots a distancia ya no se quedan inmóviles con Auto Shot o Shoot activo",
"Battleground bots no longer travel in a straight line": "Los bots de campos de batalla ya no viajan en línea recta",
"Far less server lag with hundreds of bots online": "Mucho menos lag del servidor con cientos de bots conectados",
"Inspect the mana restoration spells recognized by an online companion": "Consulta los hechizos de restauración de maná reconocidos en un compañero conectado",
"Bots stop hitting mobs they cannot reach": "Los bots dejan de atacar a enemigos inalcanzables",
"Bot economy errands skip groups, battlegrounds and dungeons": "Las tareas económicas de los bots omiten grupos, campos de batalla y mazmorras",
"Dungeon finder fills your group with bots that really join you": "El buscador de mazmorras llena tu grupo con bots que realmente se unen",
"Stop an unfinished server startup before restoring its database": "Detén un inicio de servidor incompleto antes de restaurar su base de datos",
"Imported 40 upstream commits with class, item and Pale Reach quest fixes, optional account-wide friends, and corrected Vanity purchases": "Integrados 40 cambios del proyecto original: correcciones de clases, objetos y misiones de Pale Reach, amigos opcionales de toda la cuenta y compras Vanity corregidas"
},
"zh": {
"Restrict new characters by custom race without changing existing characters": "限制新角色可选的自定义种族,不影响现有角色",
"More class abilities, items and Pale Reach quests work as intended": "修复更多职业技能、物品和 Pale Reach 任务",
"Witch Doctor and Guardian bots use their totems and standards, and fewer casts are refused": "Witch Doctor 和 Guardian 机器人会使用图腾和旗帜,施法被拒绝的情况减少",
"Venomancer Fortitude tanks use their real defensive abilities": "Venomancer Fortitude 坦克会使用实际拥有的防御技能",
"Healer bots waste fewer big heals and tank bots spread their defensives": "治疗机器人减少浪费大型治疗,坦克会错开使用防御技能",
"Dungeon bots drink and rest until the tank is ready to go on": "副本机器人会喝水和休息,直到坦克准备好继续",
"Archery Rangers use Precision Shot and Brutal Shot": "Archery Ranger 会使用 Precision Shot 和 Brutal Shot",
"Black Knight tank bots can pull in auto-dungeon mode": "Black Knight 坦克可以在自动副本模式中拉怪",
"Boltslinger bots use spells they actually know": "Boltslinger 只会使用实际学会的法术",
"Bots with unsuitable gear are refitted at login": "装备不合适的机器人会在登录时更换装备",
"Bots with full bags make room to hand in finished quests": "背包已满的机器人会腾出空间以提交已完成的任务",
"Bots pick weapons and shields for their combat spells, not for enchanting recipes": "机器人根据战斗法术选择武器和盾牌,而不是根据附魔配方",
"Bots get their gear repaired and stop looping to the repairer": "机器人会修理装备,不再反复往返修理商",
"Bots stay out of Outland and Northrend when those are not scaled to the level cap": "如果外域和诺森德未缩放到等级上限,机器人会避开这些地区",
"Bots plan long walks around areas too strong for them": "机器人长途行走时会绕开过于危险的区域",
"Dead bots run back to their bodies and come back healthy": "死亡的机器人会跑回尸体并以健康状态复活",
"Meet travelling companions and rivals in dynamic open-world encounters": "在动态开放世界事件中遇见旅行伙伴和对手",
"New companions respect the server's custom race restrictions": "新伙伴会遵守服务器的自定义种族限制",
"Ranged bots no longer stand still while Auto Shot or Shoot is active": "远程机器人不再因 Auto Shot 或 Shoot 启用而原地不动",
"Battleground bots no longer travel in a straight line": "战场机器人不再沿直线移动",
"Far less server lag with hundreds of bots online": "数百个机器人在线时,服务器延迟显著降低",
"Inspect the mana restoration spells recognized by an online companion": "查看在线伙伴所识别的法力恢复法术",
"Bots stop hitting mobs they cannot reach": "机器人会停止攻击无法接近的敌人",
"Bot economy errands skip groups, battlegrounds and dungeons": "机器人的经济事务会跳过队伍、战场和副本",
"Dungeon finder fills your group with bots that really join you": "地下城查找器会用真正加入队伍的机器人补齐队伍",
"Stop an unfinished server startup before restoring its database": "恢复数据库前可以停止尚未完成的服务器启动",
"Imported 40 upstream commits with class, item and Pale Reach quest fixes, optional account-wide friends, and corrected Vanity purchases": "合入 40 项上游更改:职业、物品及 Pale Reach 任务修复,可选的账号共享好友,以及 Vanity 购买修复"
}
}
}
File diff suppressed because it is too large. Load diff
+7 -2
View File
@@ -25,9 +25,14 @@ export {};
notes:["worldserver.exe differs from the one listed in RELEASE.json (release 2026-09-11); this looks like a customised build."],modifies_files:false};
const svc=(n: string,p: number,st: string)=>({name:n,state:st,pid:st==="running"?100:null,port:p,port_ready:st==="running",conflict:null,uptime_secs:st==="running"?4206:null});
{ const q = new URLSearchParams(location.search); const w0 = window as any; if (q.get("client")) w0.__client = q.get("client"); if (q.get("modified")) w0.__modified = true; }
(window as any).__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener() {} };
(window as any).__TAURI_INTERNALS__ = {
transformCallback: (cb: unknown)=>cb, unregisterCallback(){}, convertFileSrc:(x: unknown)=>x,
invoke: async (cmd: string, args?: any)=>{
if(cmd==="open_link") return null;
if(cmd==="pending_update") return null;
if(cmd==="plugin:app|version") return "0.8.2";
if(cmd==="release_history") throw new Error("Offline demo: using bundled notes");
if(cmd==="realm_profiles") return {active:realm,wildcard_created:wildcardCreated,reborn_created:rebornCreated,reborn_supported:true,supported:true,recovery_pending:false,simultaneous,secondary_world_port:simultaneous?8086:null,secondary_running:simultaneous&&running,with_reborn:withReborn,reborn_world_port:withReborn?8087:null,reborn_running:withReborn&&running};
if(cmd==="realm_simultaneous") { if(running) throw new Error("Stop both realms before changing simultaneous startup."); simultaneous=args.enabled; wildcardCreated ||= simultaneous; return {active:realm,wildcard_created:wildcardCreated,reborn_created:rebornCreated,reborn_supported:true,supported:true,recovery_pending:false,simultaneous,secondary_world_port:simultaneous?8086:null,secondary_running:false,with_reborn:withReborn,reborn_world_port:withReborn?8087:null,reborn_running:false}; }
if(cmd==="realm_with_reborn") { if(running) throw new Error("Stop all realms before changing which realms start together."); withReborn=args.enabled; rebornCreated ||= withReborn; return {active:realm,wildcard_created:wildcardCreated,reborn_created:rebornCreated,reborn_supported:true,supported:true,recovery_pending:false,simultaneous,secondary_world_port:simultaneous?8086:null,secondary_running:false,with_reborn:withReborn,reborn_world_port:withReborn?8087:null,reborn_running:false}; }
@@ -49,8 +54,8 @@ export {};
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==="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.261001.8":"0.260930.5",to_version:"0.261001.8",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.261001.8"},migrations:null};}
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};}
if(cmd==="get_population"){if(!running) return null;let b=(window as any).__bots??85;const t=(window as any).__target??0;if(t>b){b=Math.min(t,b+25);(window as any).__bots=b;}return {online_total:b,bots_online:Math.max(0,b-7),players_online:0,bots_total:b};}
if(cmd==="get_performance") return running?{mean_ms:14,median_ms:15,p95_ms:24,p99_ms:30,max_ms:61,ticks_per_sec:71.4}:null;
if(cmd==="run_diagnostics") return {problems:2,checks:[{id:"files",title:"Server files",level:"ok",detail:"All expected server parts were found."},{id:"world",title:"World server",level:"warn",detail:"Not running."},{id:"disk",title:"Free disk space",level:"warn",detail:"Only 3 GB free; backups and updates need room."},{id:"exposure",title:"Private services",level:"ok",detail:"Database and server console are not reachable from the network."}]};
+67
View File
@@ -2,6 +2,47 @@ import type en from "./en";
/** Deutsch. Entwurf einer Übersetzung; vor der Veröffentlichung von Muttersprachlern zu prüfen. */
const de: Partial<Record<keyof typeof en, string>> = {
"upd.preexistingCharacters": "Bereits vor dem Update fehlten bei {n} Charakterdatensätzen die Startdaten für Volk/Klasse. Unveränderte Datensätze wurden bewahrt und blockierten das Update nicht. Details stehen in der Diagnose; diese älteren Unstimmigkeiten wurden nicht automatisch behoben.",
"settings.autoManager": "Updates im Hintergrund herunterladen",
"settings.startServer": "Nach dem Update starten",
"settings.version": "Version {v}",
"settings.startupHelp": "Details zum Start",
"settings.section.updates": "Updates",
"settings.section.startup": "Start",
"settings.section.client": "Client und Dateien",
"settings.section.service": "Wartung",
"settings.section.interface": "Oberfläche",
"settings.organized": "Updates, Serverstart und Spieldateien verwalten",
"settings.clientLink": "Clientdateien und Spieldaten",
"history.title": "Änderungsverlauf",
"history.open": "Was sich ändert",
"history.server": "Server",
"history.manager": "Manager",
"history.all": "Alle Versionen",
"history.range": "Für dieses Update",
"history.language": "Sprache der Einträge",
"history.fallback": "Englisches Original: Diese Version wurde noch nicht übersetzt",
"history.empty": "Für dieses Update sind noch keine Einträge veröffentlicht",
"history.files": "Dateiänderungen",
"history.offline": "Gespeicherter Verlauf · offline verfügbar",
"history.refreshed": "Veröffentlichter Verlauf aktualisiert",
"history.experimental": "Portable Charaktere sind experimentell. Sichere deine Charaktere vor der Verwendung.",
"settings.attention": "Ein Update erfordert Aufmerksamkeit. Öffne Updates für die Wiederherstellungsoptionen.",
"races.unknownIds": "Nicht mehr im Katalog vorhandene Völker-IDs: {ids}. Beim Speichern werden diese alten Einschränkungen entfernt.",
"races.reviewCatalog": "Der Völkerkatalog wurde geändert oder noch nicht geprüft. Prüfe die Liste und speichere sie erneut.",
"races.available": "Verfügbare Völker",
"races.count": "{allowed} erlaubt · {disabled} deaktiviert",
"races.allowCreation": "Neue Charaktere erlauben",
"races.allowAll": "Alle erlauben",
"races.alliance": "Allianz",
"races.horde": "Horde",
"races.updateServer": "Aktualisiere den Server für individuelle Völkerbeschränkungen.",
"races.restart": "Stoppe den Server vor dem Speichern und starte ihn danach erneut.",
"races.saved": "Serverkonfiguration gespeichert. Starte den Server zum Anwenden.",
"races.clientPending": "Client: Die automatische Synchronisierung ist noch nicht eingerichtet.",
"races.existing": "Bestehende Charaktere behalten ihr Volk und ihre Daten.",
"mod.switching": "Änderungen werden angewendet… Bitte warten.",
"portable.experimental": "Experimentelle Funktion: Portable Charaktere befinden sich noch in aktiver Entwicklung. Fehler können auftreten.",
"remote.clientReady": "Dein Client ist bereit. Speichere die Hostadresse und klicke auf Spielen.",
@@ -999,6 +1040,32 @@ const de: Partial<Record<keyof typeof en, string>> = {
"access.relay": "Relay",
"access.relayUp": "Spiel-Relay verbunden",
"access.relayDown": "Spiel-Relay nicht verbunden",
"realm.withReborn": "Warcraft Reborn zusammen mit CoA starten",
"realm.rebornPort": "Warcraft Reborn-Weltport: {port}",
"realm.rebornWorld": "Warcraft Reborn-Welt",
"realm.rebornNeedsCoa": "Warcraft Reborn kann nur zusammen mit Conquest of Azeroth starten. Zuerst Conquest of Azeroth in der Übersicht auswählen.",
"realm.allThree": "Beide Optionen sind aktiv: Conquest of Azeroth, Wildcard und Warcraft Reborn starten zusammen.",
"browse.realmOffline": "Offline",
"browse.offlineWarning": "Der Server ist derzeit offline. Der Beitritt mit einem portablen Charakter ist möglich, sobald der Betreiber den Server startet.",
"registry.dialogTitle": "Öffentlicher Eintrag · {realm}",
"registry.publishAll": "Alle Realms veröffentlichen",
"registry.publishAllText": "Beschreibung, Sprache und Region gelten für alle noch nicht veröffentlichten Realms. Jeder Realm erscheint unter dem Servernamen; zusätzliche Realms erhalten ihren Realmnamen als Zusatz.",
"registry.publishAllButton": "{n} Realms veröffentlichen",
"registry.alreadyListed": "Bereits veröffentlicht",
"registry.configure": "Konfigurieren",
"registry.publishShort": "Veröffentlichen",
"registry.short.starting": "Wird veröffentlicht…",
"registry.accessFailed": "Der Realm ist veröffentlicht, aber die Beitrittsoptionen wurden nicht gespeichert: {reason}",
"registry.short.waiting_for_realm": "Nicht veröffentlicht",
"registry.short.realm_stopped": "Veröffentlicht, Realm gestoppt",
"registry.short.online": "Veröffentlicht",
"registry.short.retrying": "Verzeichnis nicht erreichbar",
"registry.short.rejected": "Vom Verzeichnis abgelehnt",
"registry.short.unpublishing": "Wird aus der Liste entfernt",
"registry.short.disabled": "Nicht veröffentlicht",
"registry.realmStoppedHint": "Der Realm ist gestoppt. Den Server starten, damit Spieler beitreten und Charaktersitzungen verfolgen können.",
"access.portableEnabled": "Portable Charaktere zulassen",
"access.portableEnabledHint": "Spieler können auf diesem Realm mit ihren im Manager gespeicherten Charakteren spielen.",
};
export default de;
+64 -2
View File
@@ -1,5 +1,46 @@
/** English is the source of truth: every key must exist here; other locales fall back to it. */
const en = {
"upd.preexistingCharacters": "Before the update, {n} character records already lacked race/class starting data. Unchanged records were preserved and did not block the update. Details are saved in diagnostics; these older inconsistencies have not been automatically repaired.",
"settings.autoManager": "Download updates in the background",
"settings.startServer": "Start after updating",
"settings.version": "Version {v}",
"settings.startupHelp": "Startup details",
"settings.section.updates": "Updates",
"settings.section.startup": "Startup",
"settings.section.client": "Client and files",
"settings.section.service": "Maintenance",
"settings.section.interface": "Interface",
"settings.organized": "Manage updates, startup and your game files",
"settings.clientLink": "Client files and game data",
"history.title": "Release history",
"history.open": "What changed",
"history.server": "Server",
"history.manager": "Manager",
"history.all": "All versions",
"history.range": "For this update",
"history.language": "Notes language",
"history.fallback": "Original English notes: this release has not been translated yet",
"history.empty": "No published notes for this update",
"history.files": "File changes",
"history.offline": "Saved release history · available offline",
"history.refreshed": "Published notes refreshed",
"history.experimental": "Portable Characters is experimental. Back up your characters before using it.",
"settings.attention": "An update needs attention. Open Updates to review recovery options.",
"races.unknownIds": "RaceIDs no longer in this catalog: {ids}. Saving the reviewed list removes these old restrictions.",
"races.reviewCatalog": "The race catalog changed or has not been verified. Review the list and save it before applying restrictions.",
"races.available": "Available races",
"races.count": "{allowed} allowed · {disabled} disabled",
"races.allowCreation": "Allow new characters",
"races.allowAll": "Allow all",
"races.alliance": "Alliance",
"races.horde": "Horde",
"races.updateServer": "Update the server to a build supporting individual race restrictions.",
"races.restart": "Stop the server before saving; start it again to apply the policy.",
"races.saved": "Server configuration saved. Start the server to apply it.",
"races.clientPending": "Client visibility: automatic synchronization is not configured yet.",
"races.existing": "Existing characters keep their race and data.",
"mod.switching": "Applying changes… Please wait.",
"remote.clientReady": "Your client is ready. Save the host’s address, then press Play.",
"remote.clientIntro": "Choose an existing game client or download one here. No local server is needed.",
@@ -1011,7 +1052,7 @@ const en = {
"portable.note.blocked_ruleset": "This character is for another kind of realm.",
"portable.note.blocked_format": "This realm reads another version of the character format. Update the Manager or the realm.",
"portable.note.blocked_online_import": "This realm cannot take characters while it runs. Update the realm.",
"portable.note.blocked_sessions": "This realm cannot follow a game session. Ask its owner to enable portable play.",
"portable.note.blocked_sessions": "This realm cannot follow a game session. The server or host's Server Manager is offline, or portable play is not enabled.",
"portable.note.blocked_client_data": "The game data the Manager sees is not the data the realm loaded.",
"portable.note.blocked_progression": "The realm’s level cap is not known yet or cannot be handled. Start the realm and try again.",
"portable.note.realm_offline": "The realm cannot be reached.",
@@ -1106,9 +1147,27 @@ const en = {
"browse.noCharacter": "You have no portable character yet. Make one portable on the Characters page to see whether it can play here.",
"browse.canPlay": "Can play",
"browse.cannotPlay": "Cannot play here",
"browse.realmOffline": "Offline",
"browse.offlineWarning": "The server is currently offline. Joining with a portable character will become available once the host starts the server.",
"browse.play": "Play",
"browse.playSoon": "Joining arrives with the account support of the next step.",
"registry.title": "Public listing",
"registry.title": "Public realms",
"registry.dialogTitle": "Public listing · {realm}",
"registry.publishAll": "Publish all realms",
"registry.publishAllText": "One description, language and region for every realm that is not listed yet. Each realm is listed under the server name; the realms that start next to the main one get their realm name added.",
"registry.publishAllButton": "Publish {n} realms",
"registry.alreadyListed": "Already published",
"registry.configure": "Configure",
"registry.publishShort": "Publish",
"registry.short.starting": "Publishing…",
"registry.accessFailed": "The realm is published, but its joining options were not saved: {reason}",
"registry.short.waiting_for_realm": "Not published",
"registry.short.realm_stopped": "Published, realm is off",
"registry.short.online": "Published",
"registry.short.retrying": "Registry unreachable",
"registry.short.rejected": "Refused by the registry",
"registry.short.unpublishing": "Removing from the list",
"registry.short.disabled": "Not published",
"registry.text": "Publish this realm in the central list so that players can find it. Only its name, description, language, region, rates, modules, player counts, version and capabilities are shared: no passwords, no characters, no accounts. The realm keeps running if the list is unreachable.",
"registry.url": "Registry address",
"registry.urlSave": "Save address",
@@ -1126,6 +1185,7 @@ const en = {
"registry.state.starting": "Starting to publish…",
"registry.state.waiting_for_realm": "Waiting for the realm to be ready…",
"registry.state.realm_stopped": "The realm is not running; it is listed as offline.",
"registry.realmStoppedHint": "The realm is currently stopped. Start the server so players can join and track character sessions.",
"registry.state.online": "Published and online.",
"registry.state.retrying": "The Registry could not be reached; trying again. Your realm is not affected.",
"registry.state.rejected": "The Registry refused this realm. Publishing is stopped.",
@@ -1185,6 +1245,8 @@ const en = {
"join.err.unavailable": "The server could not do that right now.",
"access.title": "Joining players",
"access.text": "How players who find this realm in the list get in.",
"access.portableEnabled": "Allow portable characters (portable play)",
"access.portableEnabledHint": "Allows players with Manager-saved characters to play on this realm (PortableSession.Enable).",
"access.existingOnly": "Do not create accounts for new players",
"access.existingOnlyHint": "Players can only link an account they already have on this realm.",
"access.route": "Address players connect to",
+67
View File
@@ -2,6 +2,47 @@ import type en from "./en";
/** Español. Traducción provisional; debe revisarla un hablante nativo antes de publicarse. */
const es: Partial<Record<keyof typeof en, string>> = {
"upd.preexistingCharacters": "Antes de actualizar, a {n} registros de personaje ya les faltaban datos iniciales de raza/clase. Los registros sin cambios se conservaron y no bloquearon la actualización. Los detalles están en el diagnóstico; estas inconsistencias anteriores no se repararon automáticamente.",
"settings.autoManager": "Descargar actualizaciones en segundo plano",
"settings.startServer": "Iniciar tras actualizar",
"settings.version": "Versión {v}",
"settings.startupHelp": "Detalles del inicio",
"settings.section.updates": "Actualizaciones",
"settings.section.startup": "Inicio",
"settings.section.client": "Cliente y archivos",
"settings.section.service": "Mantenimiento",
"settings.section.interface": "Interfaz",
"settings.organized": "Gestiona actualizaciones, inicio y archivos del juego",
"settings.clientLink": "Archivos del cliente y datos del juego",
"history.title": "Historial de cambios",
"history.open": "Qué cambia",
"history.server": "Servidor",
"history.manager": "Manager",
"history.all": "Todas las versiones",
"history.range": "Para esta actualización",
"history.language": "Idioma de las notas",
"history.fallback": "Original en inglés: esta versión aún no está traducida",
"history.empty": "No hay notas publicadas para esta actualización",
"history.files": "Cambios en archivos",
"history.offline": "Historial guardado · disponible sin conexión",
"history.refreshed": "Historial publicado actualizado",
"history.experimental": "Los personajes portátiles son experimentales. Haz una copia de seguridad de tus personajes antes de usarlos.",
"settings.attention": "Una actualización requiere atención. Abre Actualizaciones para ver las opciones de recuperación.",
"races.unknownIds": "RaceID que ya no están en el catálogo: {ids}. Al guardar la lista revisada se eliminan estas restricciones antiguas.",
"races.reviewCatalog": "El catálogo de razas ha cambiado o aún no está verificado. Revisa la lista y guárdala.",
"races.available": "Razas disponibles",
"races.count": "{allowed} permitidas · {disabled} desactivadas",
"races.allowCreation": "Permitir nuevos personajes",
"races.allowAll": "Permitir todas",
"races.alliance": "Alianza",
"races.horde": "Horda",
"races.updateServer": "Actualiza el servidor para restringir razas individualmente.",
"races.restart": "Detén el servidor antes de guardar y vuelve a iniciarlo después.",
"races.saved": "Configuración guardada. Inicia el servidor para aplicarla.",
"races.clientPending": "Cliente: la sincronización automática aún no está configurada.",
"races.existing": "Los personajes existentes conservan su raza y sus datos.",
"mod.switching": "Aplicando cambios… Espera un momento.",
"portable.experimental": "Función experimental: los personajes portátiles siguen en desarrollo activo. Pueden producirse errores.",
"remote.clientReady": "Tu cliente está listo. Guarda la dirección del anfitrión y pulsa Jugar.",
@@ -999,6 +1040,32 @@ const es: Partial<Record<keyof typeof en, string>> = {
"access.relay": "Relay",
"access.relayUp": "Relay del juego conectado",
"access.relayDown": "Relay del juego desconectado",
"realm.withReborn": "Iniciar Warcraft Reborn junto con CoA",
"realm.rebornPort": "Puerto del mundo de Warcraft Reborn: {port}",
"realm.rebornWorld": "Mundo de Warcraft Reborn",
"realm.rebornNeedsCoa": "Warcraft Reborn solo puede iniciarse junto con Conquest of Azeroth. Selecciona primero Conquest of Azeroth en Resumen.",
"realm.allThree": "Ambas opciones están activadas: Conquest of Azeroth, Wildcard y Warcraft Reborn se inician juntos.",
"browse.realmOffline": "Sin conexión",
"browse.offlineWarning": "El servidor está desconectado. Podrás entrar con un personaje portátil cuando el anfitrión inicie el servidor.",
"registry.dialogTitle": "Publicación · {realm}",
"registry.publishAll": "Publicar todos los reinos",
"registry.publishAllText": "Una descripción, idioma y región para todos los reinos aún no publicados. Cada reino usa el nombre del servidor; los reinos adicionales añaden su nombre.",
"registry.publishAllButton": "Publicar {n} reinos",
"registry.alreadyListed": "Ya publicado",
"registry.configure": "Configurar",
"registry.publishShort": "Publicar",
"registry.short.starting": "Publicando…",
"registry.accessFailed": "El reino está publicado, pero no se guardaron sus opciones de acceso: {reason}",
"registry.short.waiting_for_realm": "Sin publicar",
"registry.short.realm_stopped": "Publicado, reino detenido",
"registry.short.online": "Publicado",
"registry.short.retrying": "Directorio inaccesible",
"registry.short.rejected": "Rechazado por el directorio",
"registry.short.unpublishing": "Quitando de la lista",
"registry.short.disabled": "Sin publicar",
"registry.realmStoppedHint": "El reino está detenido. Inicia el servidor para que los jugadores entren y se registren las sesiones de personajes.",
"access.portableEnabled": "Permitir personajes portátiles",
"access.portableEnabledHint": "Los jugadores pueden usar en este reino sus personajes guardados en Manager.",
};
export default es;
+67
View File
@@ -2,6 +2,47 @@ import type en from "./en";
/** Français. Traduction provisoire ; à faire relire par un locuteur natif avant la publication. */
const fr: Partial<Record<keyof typeof en, string>> = {
"upd.preexistingCharacters": "Avant la mise à jour, {n} fiches de personnage n’avaient déjà pas de données de départ pour leur race/classe. Les fiches inchangées ont été conservées sans bloquer la mise à jour. Les détails sont dans le diagnostic ; ces incohérences anciennes n’ont pas été corrigées automatiquement.",
"settings.autoManager": "Télécharger les mises à jour en arrière-plan",
"settings.startServer": "Démarrer après la mise à jour",
"settings.version": "Version {v}",
"settings.startupHelp": "Détails du démarrage",
"settings.section.updates": "Mises à jour",
"settings.section.startup": "Démarrage",
"settings.section.client": "Client et fichiers",
"settings.section.service": "Maintenance",
"settings.section.interface": "Interface",
"settings.organized": "Gérer les mises à jour, le démarrage et les fichiers du jeu",
"settings.clientLink": "Fichiers du client et données du jeu",
"history.title": "Historique des changements",
"history.open": "Ce qui change",
"history.server": "Serveur",
"history.manager": "Manager",
"history.all": "Toutes les versions",
"history.range": "Pour cette mise à jour",
"history.language": "Langue des notes",
"history.fallback": "Original anglais : cette version n’est pas encore traduite",
"history.empty": "Aucune note publiée pour cette mise à jour",
"history.files": "Fichiers modifiés",
"history.offline": "Historique enregistré · disponible hors ligne",
"history.refreshed": "Historique publié actualisé",
"history.experimental": "Les personnages portables sont expérimentaux. Sauvegardez vos personnages avant utilisation.",
"settings.attention": "Une mise à jour nécessite votre attention. Ouvrez Mises à jour pour les options de récupération.",
"races.unknownIds": "RaceID absents de ce catalogue : {ids}. Sauvegarder la liste vérifiée supprime ces anciennes restrictions.",
"races.reviewCatalog": "Le catalogue des races a changé ou n’a pas été vérifié. Vérifiez la liste et sauvegardez-la.",
"races.available": "Races disponibles",
"races.count": "{allowed} autorisées · {disabled} désactivées",
"races.allowCreation": "Autoriser les nouveaux personnages",
"races.allowAll": "Tout autoriser",
"races.alliance": "Alliance",
"races.horde": "Horde",
"races.updateServer": "Mettez le serveur à jour pour restreindre les races individuellement.",
"races.restart": "Arrêtez le serveur avant de sauvegarder, puis redémarrez-le.",
"races.saved": "Configuration sauvegardée. Démarrez le serveur pour l’appliquer.",
"races.clientPending": "Client : la synchronisation automatique n’est pas encore configurée.",
"races.existing": "Les personnages existants conservent leur race et leurs données.",
"mod.switching": "Application des modifications… Veuillez patienter.",
"portable.experimental": "Fonction expérimentale : les personnages portables sont encore en développement actif. Des bugs peuvent survenir.",
"remote.clientReady": "Votre client est prêt. Enregistrez l’adresse de l’hôte, puis cliquez sur Jouer.",
@@ -999,6 +1040,32 @@ const fr: Partial<Record<keyof typeof en, string>> = {
"access.relay": "Relay",
"access.relayUp": "Relais de jeu connecté",
"access.relayDown": "Relais de jeu déconnecté",
"realm.withReborn": "Démarrer Warcraft Reborn avec CoA",
"realm.rebornPort": "Port du monde Warcraft Reborn : {port}",
"realm.rebornWorld": "Monde Warcraft Reborn",
"realm.rebornNeedsCoa": "Warcraft Reborn ne peut démarrer qu’avec Conquest of Azeroth. Sélectionnez d’abord Conquest of Azeroth dans la vue d’ensemble.",
"realm.allThree": "Les deux options sont activées : Conquest of Azeroth, Wildcard et Warcraft Reborn démarrent ensemble.",
"browse.realmOffline": "Hors ligne",
"browse.offlineWarning": "Le serveur est hors ligne. La connexion avec un personnage portable sera disponible lorsque l’hôte démarrera le serveur.",
"registry.dialogTitle": "Publication publique · {realm}",
"registry.publishAll": "Publier tous les royaumes",
"registry.publishAllText": "Une description, une langue et une région pour tous les royaumes non publiés. Chaque royaume utilise le nom du serveur ; les royaumes supplémentaires ajoutent leur nom.",
"registry.publishAllButton": "Publier {n} royaumes",
"registry.alreadyListed": "Déjà publié",
"registry.configure": "Configurer",
"registry.publishShort": "Publier",
"registry.short.starting": "Publication…",
"registry.accessFailed": "Le royaume est publié, mais ses options de connexion n’ont pas été enregistrées : {reason}",
"registry.short.waiting_for_realm": "Non publié",
"registry.short.realm_stopped": "Publié, royaume arrêté",
"registry.short.online": "Publié",
"registry.short.retrying": "Annuaire inaccessible",
"registry.short.rejected": "Refusé par l’annuaire",
"registry.short.unpublishing": "Retrait de la liste",
"registry.short.disabled": "Non publié",
"registry.realmStoppedHint": "Le royaume est arrêté. Démarrez le serveur pour permettre la connexion et le suivi des sessions des personnages.",
"access.portableEnabled": "Autoriser les personnages portables",
"access.portableEnabledHint": "Les joueurs peuvent utiliser sur ce royaume leurs personnages enregistrés dans Manager.",
};
export default fr;
+64 -2
View File
@@ -2,6 +2,47 @@ import type en from "./en";
/** Русский. Черновой перевод; требует проверки носителем перед релизом. */
const ru: Partial<Record<keyof typeof en, string>> = {
"upd.preexistingCharacters": "До обновления у {n} записей персонажей уже отсутствовали стартовые данные расы/класса. Неизменившиеся записи сохранены и не заблокировали обновление. Подробности есть в диагностике; эти старые несоответствия автоматически не исправлялись.",
"settings.autoManager": "Скачивать обновления в фоне",
"settings.startServer": "Запустить после обновления",
"settings.version": "Версия {v}",
"settings.startupHelp": "Подробнее о запуске",
"settings.section.updates": "Обновления",
"settings.section.startup": "Запуск",
"settings.section.client": "Клиент и файлы",
"settings.section.service": "Обслуживание",
"settings.section.interface": "Интерфейс",
"settings.organized": "Обновления, запуск сервера и файлы игры",
"settings.clientLink": "Файлы клиента и игровые данные",
"history.title": "История изменений",
"history.open": "Что изменится",
"history.server": "Сервер",
"history.manager": "Manager",
"history.all": "Все версии",
"history.range": "К обновлению",
"history.language": "Язык записей",
"history.fallback": "Английский оригинал: этот выпуск пока не переведён",
"history.empty": "Для этого обновления пока нет опубликованных записей",
"history.files": "Изменения файлов",
"history.offline": "Сохранённая история · доступна без сети",
"history.refreshed": "Опубликованная история обновлена",
"history.experimental": "Переносимые персонажи — экспериментальная функция. Перед использованием сохраните резервную копию персонажей.",
"settings.attention": "Обновление требует внимания. Откройте «Обновления», чтобы выбрать способ восстановления.",
"races.unknownIds": "RaceID, которых больше нет в каталоге: {ids}. Сохранение проверенного списка удалит эти старые ограничения.",
"races.reviewCatalog": "Каталог рас изменился или ещё не проверен. Проверьте список и сохраните его перед применением ограничений.",
"races.available": "Доступные расы",
"races.count": "Разрешено: {allowed} · Отключено: {disabled}",
"races.allowCreation": "Разрешить создание",
"races.allowAll": "Разрешить все",
"races.alliance": "Альянс",
"races.horde": "Орда",
"races.updateServer": "Обновите сервер для поддержки ограничений по расам.",
"races.restart": "Остановите сервер перед сохранением и запустите снова для применения.",
"races.saved": "Настройки сервера сохранены. Запустите сервер для применения.",
"races.clientPending": "Клиент: автоматическая синхронизация пока не настроена.",
"races.existing": "Существующие персонажи сохраняют расу и данные.",
"mod.switching": "Применяем изменения… Подождите.",
"portable.experimental": "Экспериментальная функция: портативные персонажи ещё в активной разработке. Возможны ошибки.",
"remote.clientReady": "Клиент готов. Сохраните адрес хоста и нажмите «Играть».",
@@ -993,7 +1034,7 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"portable.note.blocked_ruleset": "Этот персонаж — для реалма другого типа.",
"portable.note.blocked_format": "Реалм читает другую версию формата персонажа. Обновите Менеджер или реалм.",
"portable.note.blocked_online_import": "Этот реалм не принимает персонажей, пока работает. Обновите реалм.",
"portable.note.blocked_sessions": "Этот реалм не может следить за игровой сессией. Попросите владельца включить переносимую игру.",
"portable.note.blocked_sessions": "Этот реалм не может следить за игровой сессией. Сервер или Server Manager хоста выключен, либо в ядре не включена переносимая игра.",
"portable.note.blocked_client_data": "Игровые данные, которые видит Менеджер, не те, что загрузил реалм.",
"portable.note.blocked_progression": "Предел уровня реалма пока неизвестен или не поддерживается. Запустите реалм и попробуйте снова.",
"portable.note.realm_offline": "Реалм недоступен.",
@@ -1088,9 +1129,27 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"browse.noCharacter": "У вас пока нет переносимого персонажа. Сделайте его переносимым на странице «Персонажи», чтобы увидеть, сможет ли он играть здесь.",
"browse.canPlay": "Можно играть",
"browse.cannotPlay": "Здесь играть нельзя",
"browse.realmOffline": "Оффлайн",
"browse.offlineWarning": "Сервер сейчас не запущен хостом. Игра переносимым персонажем станет доступна, когда владелец включит сервер.",
"browse.play": "Играть",
"browse.playSoon": "Вход на сервер появится вместе с поддержкой аккаунтов на следующем шаге.",
"registry.title": "Публичный список",
"registry.title": "Публичные реалмы",
"registry.dialogTitle": "Публичный список · {realm}",
"registry.publishAll": "Опубликовать все реалмы",
"registry.publishAllText": "Одно описание, язык и регион для каждого реалма, которого ещё нет в списке. Реалмы публикуются под названием сервера; к реалмам, которые запускаются рядом с основным, добавляется название реалма.",
"registry.publishAllButton": "Опубликовать реалмов: {n}",
"registry.alreadyListed": "Уже опубликован",
"registry.configure": "Настроить",
"registry.publishShort": "Опубликовать",
"registry.short.starting": "Публикуется…",
"registry.accessFailed": "Реалм опубликован, но настройки входа игроков не сохранены: {reason}",
"registry.short.waiting_for_realm": "Не опубликован",
"registry.short.realm_stopped": "Опубликован, реалм выключен",
"registry.short.online": "Опубликован",
"registry.short.retrying": "Нет связи с реестром",
"registry.short.rejected": "Реестр отклонил",
"registry.short.unpublishing": "Снимается с публикации",
"registry.short.disabled": "Не опубликован",
"registry.text": "Опубликуйте этот реалм в общем списке, чтобы игроки могли его найти. Передаются только название, описание, язык, регион, рейты, модули, число игроков и ботов, версия и возможности реалма: никаких паролей, персонажей и аккаунтов. Если список недоступен, реалм продолжает работать.",
"registry.url": "Адрес реестра",
"registry.urlSave": "Сохранить адрес",
@@ -1108,6 +1167,7 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"registry.state.starting": "Начинаю публикацию…",
"registry.state.waiting_for_realm": "Жду, пока реалм будет готов…",
"registry.state.realm_stopped": "Реалм не запущен; в списке он отмечен как недоступный.",
"registry.realmStoppedHint": "Сервер сейчас выключен. Запустите реалм, чтобы игроки могли подключаться и отслеживать сессии персонажей.",
"registry.state.online": "Опубликован и доступен.",
"registry.state.retrying": "Реестр недоступен, пробую снова. На ваш реалм это не влияет.",
"registry.state.rejected": "Реестр отклонил этот реалм. Публикация остановлена.",
@@ -1167,6 +1227,8 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"join.err.unavailable": "Сервер сейчас не смог этого сделать.",
"access.title": "Вход игроков",
"access.text": "Как попадают на этот мир игроки, нашедшие его в списке.",
"access.portableEnabled": "Разрешить вход переносимым персонажам (переносимая игра)",
"access.portableEnabledHint": "Позволяет игрокам с сохранёнными в Менеджере персонажами играть на этом сервере (PortableSession.Enable).",
"access.existingOnly": "Не создавать аккаунты для новых игроков",
"access.existingOnlyHint": "Игроки смогут только привязать аккаунт, который у них уже есть на этом мире.",
"access.route": "Адрес для подключения игроков",
+67
View File
@@ -1,5 +1,46 @@
/** Simplified Chinese localization (zh-CN) */
const zh = {
"upd.preexistingCharacters": "更新前已有 {n} 条角色记录缺少种族/职业初始数据。未变化的记录已保留,不会阻止更新。详情已保存到诊断报告;这些既有问题尚未自动修复。",
"settings.autoManager": "在后台下载更新",
"settings.startServer": "更新后启动",
"settings.version": "版本 {v}",
"settings.startupHelp": "启动详情",
"settings.section.updates": "更新",
"settings.section.startup": "启动",
"settings.section.client": "客户端与文件",
"settings.section.service": "维护",
"settings.section.interface": "界面",
"settings.organized": "管理更新、服务器启动与游戏文件",
"settings.clientLink": "客户端文件与游戏数据",
"history.title": "更新日志",
"history.open": "更新内容",
"history.server": "服务器",
"history.manager": "Manager",
"history.all": "所有版本",
"history.range": "本次更新",
"history.language": "日志语言",
"history.fallback": "英文原文:此版本尚未翻译",
"history.empty": "本次更新暂无已发布的日志",
"history.files": "文件变更",
"history.offline": "已保存的日志 · 离线可用",
"history.refreshed": "已刷新发布日志",
"history.experimental": "可携带角色功能仍处于实验阶段。使用前请备份角色。",
"settings.attention": "某次更新需要处理。请打开“更新”查看恢复选项。",
"races.unknownIds": "此目录中已不存在的种族 ID:{ids}。保存检查后的列表将移除这些旧限制。",
"races.reviewCatalog": "种族目录已更改或尚未验证。请检查列表并保存后再应用限制。",
"races.available": "可用种族",
"races.count": "已允许 {allowed} · 已禁用 {disabled}",
"races.allowCreation": "允许创建新角色",
"races.allowAll": "允许全部",
"races.alliance": "联盟",
"races.horde": "部落",
"races.updateServer": "请更新服务器以支持单独限制种族。",
"races.restart": "保存前请停止服务器,然后重新启动以应用设置。",
"races.saved": "服务器配置已保存。请启动服务器以应用。",
"races.clientPending": "客户端:尚未配置自动同步。",
"races.existing": "现有角色保留其种族和数据。",
"mod.switching": "正在应用更改…请稍候。",
"portable.experimental": "实验性功能:便携角色仍在积极开发中,可能存在错误。",
"remote.clientReady": "客户端已就绪。保存服主地址,然后点击开始游戏。",
@@ -1001,6 +1042,32 @@ const zh = {
"access.relay": "Relay",
"access.relayUp": "游戏中继已连接",
"access.relayDown": "游戏中继未连接",
"realm.withReborn": "与 CoA 一起启动 Warcraft Reborn",
"realm.rebornPort": "Warcraft Reborn 世界端口:{port}",
"realm.rebornWorld": "Warcraft Reborn 世界",
"realm.rebornNeedsCoa": "Warcraft Reborn 只能与 Conquest of Azeroth 一起启动。请先在概览中选择 Conquest of Azeroth。",
"realm.allThree": "两个选项均已开启:Conquest of Azeroth、Wildcard 和 Warcraft Reborn 将一起启动。",
"browse.realmOffline": "离线",
"browse.offlineWarning": "服务器当前离线。服主启动服务器后,才能使用便携角色加入。",
"registry.dialogTitle": "公开发布 · {realm}",
"registry.publishAll": "发布所有服务器",
"registry.publishAllText": "为所有尚未发布的服务器使用同一描述、语言和地区。每个服务器均使用服务器名称,额外启动的服务器还会附加其世界名称。",
"registry.publishAllButton": "发布 {n} 个服务器",
"registry.alreadyListed": "已发布",
"registry.configure": "配置",
"registry.publishShort": "发布",
"registry.short.starting": "正在发布…",
"registry.accessFailed": "服务器已发布,但加入选项未保存:{reason}",
"registry.short.waiting_for_realm": "未发布",
"registry.short.realm_stopped": "已发布,世界已停止",
"registry.short.online": "已发布",
"registry.short.retrying": "无法连接目录",
"registry.short.rejected": "目录已拒绝",
"registry.short.unpublishing": "正在从列表移除",
"registry.short.disabled": "未发布",
"registry.realmStoppedHint": "世界当前已停止。请启动服务器,以便玩家加入并跟踪角色会话。",
"access.portableEnabled": "允许便携角色",
"access.portableEnabledHint": "允许玩家在此服务器使用保存在 Manager 中的角色。",
} as const;
export default zh;
+4
View File
@@ -380,6 +380,10 @@
"t": "Autospeicher-Intervall",
"d": "Wie oft Spielercharaktere gespeichert werden, solange sie online sind."
},
"PortableSession.Enable": {
"t": "Portable Charaktere (portables Spiel)",
"d": "Erlaubt Spielern, mit ihren im Manager gespeicherten portablen Charakteren auf diesem Realm zu spielen."
},
"CharactersPerAccount": {
"t": "Charaktere pro Konto",
"d": "Maximale Zahl an Charakteren, die ein Konto über alle Realms hat."
+4
View File
@@ -380,6 +380,10 @@
"t": "Intervalo de autoguardado",
"d": "Con qué frecuencia se guardan los personajes de los jugadores mientras están conectados."
},
"PortableSession.Enable": {
"t": "Personajes portátiles (juego portátil)",
"d": "Permite a los jugadores jugar en este reino con personajes portátiles guardados en su Manager."
},
"CharactersPerAccount": {
"t": "Personajes por cuenta",
"d": "Máximo de personajes que puede tener una cuenta entre todos los reinos."
+4
View File
@@ -380,6 +380,10 @@
"t": "Intervalle de sauvegarde automatique",
"d": "Fréquence de sauvegarde des personnages des joueurs pendant qu’ils sont en ligne."
},
"PortableSession.Enable": {
"t": "Personnages portables (jeu portable)",
"d": "Permet aux joueurs de jouer sur ce royaume avec des personnages portables enregistrés dans leur Manager."
},
"CharactersPerAccount": {
"t": "Personnages par compte",
"d": "Nombre maximal de personnages qu’un compte peut avoir sur tous les royaumes."
+4
View File
@@ -380,6 +380,10 @@
"t": "Интервал автосохранения",
"d": "Как часто персонажи игроков сохраняются, пока они в сети."
},
"PortableSession.Enable": {
"t": "Переносимые персонажи (переносимая игра)",
"d": "Разрешает игрокам заходить на этот сервер переносимыми персонажами, сохранёнными в их Менеджере."
},
"CharactersPerAccount": {
"t": "Персонажей на учётную запись",
"d": "Наибольшее число персонажей на учётной записи во всех мирах."
+4
View File
@@ -380,6 +380,10 @@
"t": "角色数据自动保存间隔",
"d": "在线玩家角色数据写入数据库的时间间隔。"
},
"PortableSession.Enable": {
"t": "便携式角色(跨服漫游)",
"d": "允许玩家使用保存在管理器中的便携式角色进入此服务器进行游玩。"
},
"CharactersPerAccount": {
"t": "每个账号最大角色数",
"d": "单个账号在所有服务器可创建的角色总数上限。"
+3 -3
View File
@@ -16,10 +16,10 @@
--font-sans: "Segoe UI Variable Text", "Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", system-ui, sans-serif;
}
/* Everything is sized in rem, so scaling the root font grows the whole interface with the window
(16px up to about 1280px wide, then gradually larger; capped at 26px). */
/* Window size changes layout, not UI density. Keep rem tied to the user's default
font size; browser zoom and operating-system display scaling still apply. */
html {
font-size: clamp(16px, calc(0.75vw + 6.4px), 26px);
font-size: 100%;
}
html,
+21 -2
View File
@@ -1,4 +1,7 @@
import { invoke } from "@tauri-apps/api/core";
import { updateCheckQueue } from "./updateCheckQueue";
const queuedUpdateCheck = updateCheckQueue<UpdatePreview>();
export const REMOTE_CLIENT_ID = "@remote-client";
export interface RemoteConnection { host: string; client_path: string | null }
@@ -393,6 +396,16 @@ export interface ClientDownloadCheck {
export type ClientPatchState = "not-installed" | "enabled" | "disabled" | "partially-installed";
export interface RaceAvailability {
realm: RealmMode;
races: { id: number; name: string; faction: "alliance" | "horde" | null }[];
disabledRaceIds: number[];
catalogSha256: string;
serverConfigSupported: boolean;
catalogNeedsReview: boolean;
unrecognizedRaceIds: number[];
}
export interface CustomRacesClientStatus {
version: string | null;
state: ClientPatchState;
@@ -529,10 +542,13 @@ export const api = {
createAccount: (id: string, username: string, password: string, administrator: boolean) =>
invoke<void>("create_account", { id, username, password, administrator }),
/** `background`: the repeating check, which must not start the database of a stopped server. */
checkUpdate: (id: string, source?: string, background?: boolean) => invoke<UpdatePreview>("check_update", { id, source: source ?? null, background: background ?? false }),
checkUpdate: (id: string, source?: string, background?: boolean) => queuedUpdateCheck(
id, JSON.stringify([source ?? null, background ?? false]),
() => invoke<UpdatePreview>("check_update", { id, source: source ?? null, background: background ?? false }),
),
pendingUpdate: (id: string) => invoke<UpdateTxn | null>("pending_update", { id }),
applyUpdate: (id: string, resolutions: Record<string, "keep" | "replace">, source?: string) =>
invoke<{ txn: UpdateTxn }>("apply_update", { id, source: source ?? null, resolutions }),
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 }),
population: (id: string) => invoke<Population | null>("get_population", { id }),
@@ -555,6 +571,9 @@ export const api = {
clientDownload: (id: string, parent: string) => invoke<ClientInfo>("client_download", { id, parent }),
clientCancel: () => invoke<void>("client_cancel"),
customRacesStatus: (id: string) => invoke<CustomRacesClientStatus | null>("custom_races_status", { id }),
raceAvailability: (id: string) => invoke<RaceAvailability>("race_availability", { id }),
raceAvailabilitySave: (id: string, catalogSha256: string, realm: RealmMode, disabledRaceIds: number[]) =>
invoke<RaceAvailability>("race_availability_save", { id, catalogSha256, realm, disabledRaceIds }),
customRacesUninstall: (id: string) => invoke<void>("custom_races_uninstall", { id }),
customRacesInstall: (id: string) => invoke<void>("custom_races_install", { id }),
customRacesToggleClient: (id: string, enabled: boolean) => invoke<void>("custom_races_toggle_client", { id, enabled }),
+4 -2
View File
@@ -77,8 +77,10 @@ add(scaling + "LFG.DefaultMode", "enum", ["Dungeon Finder group", "Группа
] });
add(scaling + "LFG.DefaultChallengeSize", "int", ["Challenge group size", "Размер группы для расчёта сложности", "Gruppengröße für die Schwierigkeit", "Taille du groupe pour la difficulté", "Tamaño del grupo para dificultad", "难度目标人数"], ["0 follows actual party size. 1–40 simulates that many players. Players can override with .lfgchallenge.", "0 — реальный размер группы. 1–40 — сложность как для указанного числа игроков. Игрок может изменить через .lfgchallenge.", "0 nutzt die tatsächliche Gruppe. 1–40 simuliert diese Spielerzahl. Mit .lfgchallenge änderbar.", "0 suit le groupe réel. 1–40 simule ce nombre de joueurs. Modifiable avec .lfgchallenge.", "0 usa el grupo real. 1–40 simula ese número de jugadores. Modificable con .lfgchallenge.", "0按实际人数,1–40模拟指定人数。玩家可通过 .lfgchallenge 更改。"], { min: 0, max: 40 });
add(scaling + "GroupScaling.LockOnEncounterStart", "bool", ["Lock scaling during combat", "Фиксировать скейлинг на время боя", "Skalierung im Kampf sperren", "Figer l’adaptation en combat", "Fijar ajuste durante combate", "战斗期间锁定缩放"], ["Joining or leaving during a boss fight does not change its scaling.", "Вход и выход игроков во время боя с боссом не меняют скейлинг.", "Beitreten oder Verlassen während eines Bosskampfs ändert die Skalierung nicht.", "Les arrivées et départs pendant un boss ne changent pas l’adaptation.", "Entrar o salir durante un jefe no cambia el ajuste.", "首领战期间玩家进出不会改变缩放。"], { advanced: true });
add(scaling + "Progression.Mode", "enum", ["Progression boundaries", "Границы прогрессии", "Fortschrittsgrenzen", "Limites de progression", "Límites de progresión", "进度边界"], ["Automatic boundaries follow the level cap and enabled expansions. Custom uses the levels below.", "Автоматические границы зависят от максимального уровня и включённых дополнений. Ручные используют уровни ниже.", "Automatisch folgt der Maximalstufe und Erweiterungen. Benutzerdefiniert nutzt die folgenden Stufen.", "Automatique suit le niveau maximal et les extensions. Manuel utilise les niveaux ci-dessous.", "Automático sigue el nivel máximo y las expansiones. Manual usa los niveles siguientes.", "自动边界按等级上限和启用的资料片计算,自定义使用以下等级。"], { advanced: true, options: [
add(scaling + "Progression.Mode", "enum", ["Progression boundaries", "Границы прогрессии", "Fortschrittsgrenzen", "Limites de progression", "Límites de progresión", "进度边界"], ["Automatic splits the level cap between the expansions one after another. Parallel scales Classic over 1 to the level cap and TBC and WotLK over 45 to the level cap. Global scales every expansion over 1 to the level cap. Custom uses the levels below.", "Автоматически делит максимальный уровень между дополнениями по очереди. Параллельно: классика на уровнях 1 — максимум, TBC и WotLK на 45 — максимум. Глобально: все дополнения на 1 — максимум. Вручную использует уровни ниже.", "Automatisch teilt die Maximalstufe nacheinander auf die Erweiterungen auf. Parallel skaliert Classic über 1 bis zur Maximalstufe und TBC und WotLK über 45 bis zur Maximalstufe. Global skaliert alle Erweiterungen über 1 bis zur Maximalstufe. Benutzerdefiniert nutzt die folgenden Stufen.", "Automatique répartit le niveau maximal entre les extensions l'une après l'autre. Parallèle étend Classic de 1 au niveau maximal, TBC et WotLK de 45 au niveau maximal. Global étend toutes les extensions de 1 au niveau maximal. Manuel utilise les niveaux ci-dessous.", "Automático reparte el nivel máximo entre las expansiones una tras otra. Paralelo escala Classic de 1 al nivel máximo y TBC y WotLK de 45 al nivel máximo. Global escala todas las expansiones de 1 al nivel máximo. Manual usa los niveles siguientes.", "自动:按顺序在各资料片之间分配等级上限。并行:经典旧世为 1 至等级上限,TBC 和 WotLK 为 45 至等级上限。全局:所有资料片均为 1 至等级上限。自定义:使用以下等级。"], { advanced: true, options: [
{ value: "Auto", label: ["Automatic", "Автоматически", "Automatisch", "Automatique", "Automático", "自动"] },
{ value: "Parallel", label: ["Parallel (Classic 1-cap, TBC/WotLK 45-cap)", "Параллельно (классика 1–макс., TBC/WotLK 45–макс.)", "Parallel (Classic 1–Max., TBC/WotLK 45–Max.)", "Parallèle (Classic 1–max., TBC/WotLK 45–max.)", "Paralelo (Classic 1–máx., TBC/WotLK 45–máx.)", "并行(经典 1–上限,TBC/WotLK 45–上限)"] },
{ value: "Global", label: ["Global (everything 1-cap)", "Глобально (всё на 1–макс.)", "Global (alles 1–Max.)", "Global (tout 1–max.)", "Global (todo 1–máx.)", "全局(全部 1–上限)"] },
{ value: "Custom", label: ["Custom", "Вручную", "Benutzerdefiniert", "Manuel", "Manual", "自定义"] },
] });
for (const era of ["Classic", "Tbc"]) add(scaling + `Progression.${era}End`, "int", [`${era} last level`, `Последний уровень ${era}`, `${era}-Endstufe`, `Dernier niveau ${era}`, `Último nivel ${era}`, `${era} 最高等级`], ["Used in custom progression. 0 chooses automatically.", "Для ручной прогрессии. 0 — автоматически.", "Für benutzerdefinierten Fortschritt. 0 wählt automatisch.", "Pour la progression manuelle. 0 choisit automatiquement.", "Para progresión manual. 0 elige automáticamente.", "用于自定义进度,0为自动。"], { min: 0, max: 80, advanced: true });
@@ -213,6 +215,6 @@ export function canonicalModuleValue(key: string, value: string): string {
const v = value.trim().replace(/^"|"$/g, "");
if (key === scaling + "SoloAssist.Mode") return ({ "0": "None", "1": "Light", "2": "Full", none: "None", light: "Light", full: "Full" } as Record<string, string>)[v.toLowerCase()] ?? v;
if (key === scaling + "LFG.DefaultMode") return ({ "0": "Matchmaking", "1": "BotFill", "2": "CurrentParty", matchmaking: "Matchmaking", botfill: "BotFill", currentparty: "CurrentParty" } as Record<string, string>)[v.toLowerCase()] ?? v;
if (key === scaling + "Progression.Mode") return v.toLowerCase() === "auto" ? "Auto" : v.toLowerCase() === "custom" ? "Custom" : v;
if (key === scaling + "Progression.Mode") return ({ auto: "Auto", parallel: "Parallel", global: "Global", all: "Global", "1-60": "Global", custom: "Custom" } as Record<string, string>)[v.toLowerCase()] ?? v;
return v;
}
+48
View File
@@ -0,0 +1,48 @@
import { useEffect, useState } from "react";
import { api, type RealmMode } from "@/lib/api";
import type { PublishState, RealmPublishStatus } from "@/lib/registry";
export const REALM_LABEL: Record<RealmMode, string> = { coa: "Conquest of Azeroth", wildcard: "Wildcard", reborn: "Warcraft Reborn" };
/** One realm of this server that can be listed publicly. */
export interface PublishRealm {
/** The main realm keeps the plain id it was published under; each realm that starts next to it has its own. */
localId: string;
mode: RealmMode;
label: string;
/** The server name; the realms that start next to the main one get their realm name added. */
defaultName: string;
}
/** The realms this server runs, main realm first; `null` until they are known. */
export function usePublishRealms(serverId: string, serverName: string): PublishRealm[] | null {
const [realms, setRealms] = useState<PublishRealm[] | null>(null);
useEffect(() => {
let alive = true;
const build = (active: RealmMode, extra: RealmMode[]) => [
{ localId: `srv-${serverId}`, mode: active, label: REALM_LABEL[active], defaultName: serverName },
...extra.map((mode) => ({ localId: `srv-${serverId}:${mode}`, mode, label: REALM_LABEL[mode], defaultName: `${serverName} · ${REALM_LABEL[mode]}` })),
];
void api.realmProfiles(serverId).then((r) => {
if (!alive) return;
const extra: RealmMode[] = [];
if (r.simultaneous) extra.push(r.active === "coa" ? "wildcard" : "coa");
if (r.with_reborn) extra.push("reborn");
setRealms(build(r.active, extra));
}).catch(() => { if (alive) setRealms(build("coa", [])); });
return () => { alive = false; };
}, [serverId, serverName]);
return realms;
}
export function stateTone(state: PublishState | undefined): string {
if (state === "online") return "text-ok";
if (state === "rejected") return "text-bad";
if (state === "retrying" || state === "realm_stopped" || state === "waiting_for_realm") return "text-warn";
return "text-muted";
}
/** Listed on the public list now (or being removed from it). */
export function isListed(s: RealmPublishStatus | undefined): boolean {
return !!s && (s.enabled || s.state === "unpublishing");
}
+16
View File
@@ -0,0 +1,16 @@
import manager from "../../changelog/history.json";
import server from "@/data/server-history.json";
import translations from "@/data/latest-note-translations.json";
import type { Locale } from "@/i18n";
import { localizeNotes, type Component, type History, type Release } from "./releaseHistoryModel";
export { compareVersions, releasesForUpdate } from "./releaseHistoryModel";
export type { Component, History } from "./releaseHistoryModel";
export const bundledHistories: Record<Component, History> = { manager: manager as History, server: server as History };
export const repositories = { manager: "Corfirean/coa-server-manager", server: "Corfirean/coa-server-build" };
export function translatedNotes(component: Component, release: Release, locale: Locale): { notes: string[]; fallback: boolean } {
if (locale === "en") return { notes: release.notes, fallback: false };
const dict = (translations[component] as Record<string, Record<string, string>>)[locale] ?? {};
return localizeNotes(release.notes, dict);
}
+23
View File
@@ -0,0 +1,23 @@
export type Component = "server" | "manager";
export interface Release { version: string; tag: string; date: string; notes: string[]; prerelease?: boolean; experimentalFeatures?: string[] }
export interface History { component: Component; releases: Release[]; source?: "remote" | "cache" }
// Only stable numeric versions participate in an installed-to-target update range.
export function compareVersions(a: string, b: string): number {
const aa = a.split(".").map(Number), bb = b.split(".").map(Number);
for (let i = 0; i < Math.max(aa.length, bb.length); i++) {
const d = (aa[i] ?? 0) - (bb[i] ?? 0);
if (d) return d;
}
return 0;
}
export function releasesForUpdate(releases: Release[], from?: string, to?: string): Release[] {
if (!to || !/^\d+(\.\d+)+$/.test(to)) return [];
const knownFrom = from && /^\d+(\.\d+)+$/.test(from);
return releases.filter(r => !r.prerelease && /^\d+(\.\d+)+$/.test(r.version) &&
(knownFrom ? compareVersions(r.version, from) > 0 && compareVersions(r.version, to) <= 0 : r.version === to));
}
export function localizeNotes(notes: string[], dictionary: Record<string, string> = {}) {
const complete = notes.every(note => dictionary[note]);
return { notes: complete ? notes.map(note => dictionary[note]) : notes, fallback: !complete };
}
+2 -2
View File
@@ -21,7 +21,7 @@ export interface ServerUpdateState {
stateError: UiError | null;
stateRevision: number;
/** How the last update ended; kept here so the Settings card can show it after the user left and came back. */
result: { committed: string } | { pending: UpdateTxn } | null;
result: { committed: string; preexistingCharacters?: number } | { pending: UpdateTxn } | null;
}
const EMPTY: ServerUpdateState = { preview: null, available: false, checking: false, applying: false, step: null, percent: 0, error: null, uiError: null, stateError: null, stateRevision: 0, result: null };
@@ -98,7 +98,7 @@ export async function applyServerUpdate(id: string, opts?: { choices: Record<str
}
try {
const out = await api.applyUpdate(id, opts?.choices ?? {}, opts?.source);
set(id, { result: out.txn.state === "committed" ? { committed: out.txn.to_version ?? "" } : { pending: out.txn } });
set(id, { result: out.txn.state === "committed" ? { committed: out.txn.to_version ?? "", ...(out.preexisting_character_count ? { preexistingCharacters: out.preexisting_character_count } : {}) } : { pending: out.txn } });
if (out.txn.state === "committed" && !wasRunning && !startAfterUpdate("server", id)) await api.stop(id).catch(() => undefined);
return true;
} catch (e) {
+19
View File
@@ -0,0 +1,19 @@
export function updateCheckQueue<T>() {
const requests = new Map<string, Promise<T>>();
const servers = new Map<string, Promise<unknown>>();
return (server: string, request: string, run: () => Promise<T>): Promise<T> => {
const key = JSON.stringify([server, request]);
const existing = requests.get(key);
if (existing) return existing;
const previous = servers.get(server) ?? Promise.resolve();
const result = previous.catch(() => undefined).then(run);
requests.set(key, result);
servers.set(server, result);
const clear = () => {
if (requests.get(key) === result) requests.delete(key);
if (servers.get(server) === result) servers.delete(server);
};
void result.then(clear, clear);
return result;
};
}
+11 -33
View File
@@ -1,12 +1,12 @@
import { useEffect, useState } from "react";
import { getVersion } from "@tauri-apps/api/app";
import { Loader2 } from "lucide-react";
import { Loader2, RefreshCw, Monitor } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { useT } from "@/i18n";
import { autoUpdateEnabled, installNow, lookForUpdate, setAutoUpdate, useSelfUpdate } from "@/lib/selfUpdate";
export function AboutCard() {
export function AboutCard({ onHistory }: { onHistory?: () => void }) {
const t = useT();
const s = useSelfUpdate();
const [version, setVersion] = useState("");
@@ -21,37 +21,12 @@ export function AboutCard() {
return (
<Card className="mt-6 p-6">
<h2 className="font-semibold">{t("app.name")}</h2>
<p className="mt-1 text-sm text-muted">{t("about.version", { v: version || "…" })}</p>
<label className="mt-3 flex cursor-pointer items-start gap-2 text-sm">
<input
type="checkbox"
className="mt-1"
checked={auto}
onChange={(e) => {
setAuto(e.target.checked);
setAutoUpdate(e.target.checked);
}}
/>
<span>
{t("about.auto")}
<span className="block text-xs text-muted">{t("about.autoHint")}</span>
</span>
</label>
<div className="flex items-start justify-between gap-3">
<div><h2 className="flex items-center gap-2 font-semibold"><Monitor className="h-4 w-4 text-gold" aria-hidden />{t("history.manager")}</h2><p className="mt-2 text-sm text-muted">{t("settings.version", { v: version || "…" })}</p></div>
<Button size="sm" disabled={busy} aria-label={t("about.check")} title={t("about.check")} onClick={() => { setAsked(true); void lookForUpdate({ download: false }); }}><RefreshCw className={`h-4 w-4 ${s.phase === "checking" ? "animate-spin" : ""}`} aria-hidden /></Button>
</div>
<p className="mt-3 text-xs text-muted">{t("about.autoHint")}</p>
<div className="mt-4 flex flex-wrap items-center gap-3">
<Button
size="sm"
disabled={busy}
onClick={() => {
setAsked(true);
void lookForUpdate({ download: false });
}}
>
{s.phase === "checking" && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{t("about.check")}
</Button>
{s.version && s.phase !== "current" && (
<Button size="sm" variant="primary" disabled={busy} onClick={() => void installNow()}>
{(s.phase === "downloading" || s.phase === "installing") && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
@@ -64,7 +39,7 @@ export function AboutCard() {
</span>
)}
</div>
{s.version && s.notes && s.phase !== "current" && <p className="mt-3 whitespace-pre-line text-sm text-muted">{s.notes}</p>}
{onHistory ? <button className="mt-3 cursor-pointer text-sm text-gold hover:underline" onClick={onHistory}>{t(s.version && s.phase !== "current" ? "history.open" : "history.title")}</button> : s.version && s.notes && s.phase !== "current" && <p className="mt-3 whitespace-pre-line text-sm text-muted">{s.notes}</p>}
{s.phase === "ready" && <p className="mt-3 text-sm text-ok" role="status">{t("selfupd.onClose")}</p>}
{asked && s.phase === "current" && <p className="mt-3 text-sm text-ok" role="status">{t("about.upToDate")}</p>}
{s.phase === "error" && (
@@ -73,6 +48,9 @@ export function AboutCard() {
{s.error && <p className="selectable mt-1 break-all text-xs text-muted">{s.error}</p>}
</div>
)}
<label className="mt-5 flex cursor-pointer items-center justify-between gap-3 border-t border-line pt-4 text-sm" title={t("about.auto")}>
<span>{t("settings.autoManager")}</span><input type="checkbox" role="switch" aria-description={t("about.auto")} checked={auto} onChange={e => { setAuto(e.target.checked); setAutoUpdate(e.target.checked); }} className="h-4 w-4 accent-[#c9a24a]" />
</label>
</Card>
);
}
+2
View File
@@ -117,6 +117,7 @@ function Drawer({ summary, catalog, onClose }: { summary: RealmSummary; catalog:
<h2 className="truncate text-lg font-semibold" data-testid="drawer-title">{summary.display_name}</h2>
<p className="mt-0.5 text-sm text-muted"><Mode ruleset={summary.ruleset} /> · {t("browse.cap")} {summary.level_cap ?? "—"}</p>
<p className="text-sm"><Online p={summary.population} />{summary.population.capacity !== null && <span className="text-muted"> · {t("browse.capacity", { n: summary.population.capacity })}</span>}</p>
{!summary.online && <span className="mt-1 inline-block rounded bg-bad/15 px-2 py-0.5 text-xs font-medium text-bad">{t("browse.realmOffline")}</span>}
</div>
<button onClick={onClose} aria-label={t("portable.close")} className="cursor-pointer text-muted hover:text-ink"><X className="h-5 w-5" /></button>
</div>
@@ -180,6 +181,7 @@ function Drawer({ summary, catalog, onClose }: { summary: RealmSummary; catalog:
<p className="font-medium">{blocked ? t("browse.cannotPlay") : t("browse.canPlay")}</p>
{pre.projection && <Projection from={pre.projection[0]} to={pre.projection[1]} cap={summary.level_cap} />}
<Notes notes={pre.notes} />
{!summary.online && <p className="mt-2 border-t border-line/40 pt-2 text-xs text-warn">{t("browse.offlineWarning")}</p>}
</div>}
</>}
</section>
+13 -3
View File
@@ -8,6 +8,7 @@ import { Card } from "@/components/ui/card";
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 type { UnsavedChangesGuard } from "@/lib/unsavedGuard";
/** The GitHub mark (lucide dropped its brand icons). */
@@ -104,11 +105,17 @@ export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId
}
}, [serverId]);
const [guard, setGuard] = useState<UnsavedChangesGuard | null>(null);
const [racesGuard, setRacesGuard] = useState<UnsavedChangesGuard | null>(null);
useEffect(() => {
onRegisterGuard?.(guard);
const guards = [guard, racesGuard].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, onRegisterGuard]);
}, [guard, racesGuard, onRegisterGuard]);
const load = useCallback(async () => {
try {
@@ -317,6 +324,9 @@ export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId
<SettingsPanel key={selected.id} className="sm:col-span-2">
<h2 className="font-semibold">{t("mod.settingsOf", { name: selected.name })}</h2>
<ModuleSettings serverId={serverId} module={selected} onSaved={() => setChanged(true)} onRegisterGuard={setGuard} />
{selected.id === "custom-races" && <RaceAvailabilitySettings serverId={serverId}
blocked={racesInstalling || toggling !== null} onSaved={() => setChanged(true)}
onRegisterGuard={setRacesGuard} />}
</SettingsPanel>
)}
</Fragment>
@@ -409,7 +419,7 @@ function ModuleSettings({ serverId, module, onSaved, onRegisterGuard }: { server
else next[key] = value;
return next;
});
const available = items?.filter(s => s.key !== moduleEnableKey(module.id) && !retiredModuleKeys.has(s.key)) ?? [];
const available = items?.filter(s => s.key !== moduleEnableKey(module.id) && !["CoACustomRaces.DisabledRaceIds", "CoACustomRaces.DisabledRaceCatalogSha256"].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;
+30 -29
View File
@@ -10,7 +10,12 @@ import { ClientDialog, type ClientDialogMode } from "@/screens/ClientDialog";
import { RealmlistMenu } from "@/screens/RealmlistMenu";
import { RealmPicker } from "@/screens/RealmPicker";
import { CrashHistoryModal } from "@/screens/CrashHistoryModal";
import { ListingChip } from "@/screens/PublishCard";
import { PublishRealmDialog } from "@/screens/PublishDialog";
import { useRegistryStatus } from "@/lib/registry";
import { usePublishRealms, type PublishRealm } from "@/lib/publishRealms";
import { useAutoRestart } from "@/lib/autoRestartPrefs";
import { SplitButton } from "@/components/ui/split-button";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
@@ -114,6 +119,14 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
const [crashCount, setCrashCount] = useState(0);
const crashCountRef = useRef(0);
const [showCrashModal, setShowCrashModal] = useState(false);
const publishRealms = usePublishRealms(server.id, server.name);
const { status: registry } = useRegistryStatus(5000);
const [publishing, setPublishing] = useState<PublishRealm | null>(null);
// The realm a card shows: the first card is the main realm, then the realm that starts next to it, then Warcraft Reborn.
const chipOf = (realm: PublishRealm | undefined) => realm && <ListingChip status={registry?.realms.find((r) => r.local_id === realm.localId)} hasUrl={!!registry?.url} onOpen={() => setPublishing(realm)} />;
const mainRealm = publishRealms?.[0];
const secondRealm = publishRealms?.find((r) => r !== mainRealm && r.mode !== "reborn");
const rebornRealm = publishRealms?.find((r) => r !== mainRealm && r.mode === "reborn");
const [hasCrashHistory, setHasCrashHistory] = useState(false);
const [crashLoopPaused, setCrashLoopPaused] = useState(false);
const [crashRestartNotice, setCrashRestartNotice] = useState<string | null>(null);
@@ -317,7 +330,7 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
<RealmPicker serverId={server.id} running={anyUp} disabled={transitioning || upd.applying} onBusy={setRealmBusy} onChanged={() => { onRealmChanged(); void poll(); }} />
<Card className="mt-6 p-7">
<div className="mb-1 text-xs font-medium uppercase tracking-[0.14em] text-muted">{realms ? `${realms.first} · ${t("overview.server")}` : t("overview.server")}</div>
<div className="mb-1 flex items-center justify-between gap-3 text-xs font-medium uppercase tracking-[0.14em] text-muted"><span>{realms ? `${realms.first} · ${t("overview.server")}` : t("overview.server")}</span>{chipOf(mainRealm)}</div>
<div className="flex flex-wrap items-center justify-between gap-3">
<div className={cn("flex items-center gap-3 text-3xl font-semibold", tone)} role="status" aria-live="polite">
<span
@@ -398,32 +411,21 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
<div className="mt-7 flex flex-wrap items-center gap-x-4 gap-y-3">
{running ? (
<Button variant="secondary" size="xl" disabled={transitioning} onClick={() => run("stopping")} className="min-w-56">
<Button variant="secondary" size="xl" disabled={transitioning} onClick={() => run("stopping")} className="min-w-40">
{transitioning && <Loader2 className="h-5 w-5 animate-spin" aria-hidden />}
{t("btn.stop")}
</Button>
) : upd.available ? (
<Button
variant="primary"
size="xl"
disabled={transitioning || upd.applying}
onClick={() => (needsDecision ? onOpenUpdates() : void runServerUpdate())}
className="min-w-56"
>
{upd.applying && <Loader2 className="h-5 w-5 animate-spin" aria-hidden />}
{upd.applying ? t("btn.updating") : needsDecision ? t("overview.openUpdates") : t("btn.update")}
</Button>
<SplitButton label={t("overview.server")}
primary={{ disabled: transitioning || upd.applying, onClick: () => (needsDecision ? onOpenUpdates() : void runServerUpdate()), children: <>{upd.applying && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}{upd.applying ? t("btn.updating") : needsDecision ? t("overview.openUpdates") : t("btn.update")}</> }}
secondary={{ disabled: transitioning || upd.applying, onClick: () => run("starting"), children: t("btn.startWithoutUpdate") }}
/>
) : (
<Button variant="primary" size="xl" disabled={transitioning} onClick={() => run("starting")} className="min-w-56">
<Button variant="primary" size="xl" disabled={transitioning} onClick={() => run("starting")} className="min-w-40">
{transitioning && <Loader2 className="h-5 w-5 animate-spin" aria-hidden />}
{transitioning ? (action === "stopping" ? t("btn.stoppingCaps") : t("btn.startingCaps")) : t("btn.start")}
</Button>
)}
{!running && upd.available && (
<Button variant="secondary" size="sm" disabled={transitioning || upd.applying} onClick={() => run("starting")}>
{t("btn.startWithoutUpdate")}
</Button>
)}
{running && (
<Button variant="ghost" size="sm" disabled={transitioning || upd.applying} onClick={() => run("restarting")}>
{t("btn.restart")}
@@ -444,7 +446,7 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
{client && <RealmlistMenu serverId={server.id} />}
{client && jobBusy ? (
<div
className="relative flex h-16 min-w-64 items-center overflow-hidden rounded-md border border-gold/50 bg-card-2"
className="relative flex h-12 min-w-64 items-center overflow-hidden rounded-md border border-gold/50 bg-card-2"
role="progressbar"
aria-valuenow={jobPct}
aria-valuemin={0}
@@ -470,9 +472,10 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
</button>
</div>
) : client && (clientStatus?.update_available || job.phase === "choose") ? (
<Button variant="primary" size="xl" disabled={playing || job.phase === "choose"} onClick={() => void startClientUpdate(server.id)} className="min-w-40">
{t("btn.updateClient")}
</Button>
<SplitButton label={t("btn.play")}
primary={{ disabled: playing || job.phase === "choose", onClick: () => void startClientUpdate(server.id), children: t("btn.updateClient") }}
secondary={{ disabled: realmBusy || playing || upd.applying, onClick: () => void play(), children: <>{playing && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}{t("btn.playWithoutUpdate")}</> }}
/>
) : client ? (
<Button variant="primary" size="xl" disabled={realmBusy || playing} onClick={() => void play()} className="min-w-40">
{playing && <Loader2 className="h-5 w-5 animate-spin" aria-hidden />}
@@ -483,11 +486,6 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
{t("btn.setupClient")}
</Button>
) : null}
{client && !jobBusy && (clientStatus?.update_available || job.phase === "choose") && (
<Button variant="secondary" size="sm" disabled={realmBusy || playing || upd.applying} onClick={() => void play()}>
{t("btn.playWithoutUpdate")}
</Button>
)}
</div>
</div>
<div className="mt-6 flex flex-wrap items-center justify-between gap-3 border-t border-line/60 pt-4 text-xs text-muted">
@@ -542,10 +540,12 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
<Button size="sm" variant="ghost" onClick={() => void startClientUpdate(server.id)}>{t("client.dl.retry")}</Button>
</p>
)}
{upd.result && "committed" in upd.result && !!upd.result.preexistingCharacters && <p className="mt-3 text-sm text-warn" role="status">{t("upd.preexistingCharacters", { n: upd.result.preexistingCharacters })}</p>}
{upd.available && upd.preview && (
<div className="mt-4 rounded-md border border-gold/40 bg-gold/5 p-3 text-sm">
<p>{t("overview.updateAvail", { to: upd.preview.to_version, from: upd.preview.from_version ?? "?" })}</p>
{upd.preview.latest_version && <p>{t("upd.intermediate", { to: upd.preview.to_version, latest: upd.preview.latest_version })}</p>}
<button className="mt-2 cursor-pointer text-gold hover:underline" onClick={onOpenUpdates}>{t("history.open")}</button>
{needsDecision && <p className="mt-1 text-muted">{t("overview.updateConflicts")}</p>}
{upd.applying && (
<div className="mt-2">
@@ -565,7 +565,7 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
{secondary_world && (
<Card className="mt-4 p-7">
<div className="mb-1 text-xs font-medium uppercase tracking-[0.14em] text-muted">{realms ? `${realms.second} · ${t("overview.server")}` : t("realm.secondWorld")}</div>
<div className="mb-1 flex items-center justify-between gap-3 text-xs font-medium uppercase tracking-[0.14em] text-muted"><span>{realms ? `${realms.second} · ${t("overview.server")}` : t("realm.secondWorld")}</span>{chipOf(secondRealm)}</div>
<div
className={cn("flex items-center gap-3 text-3xl font-semibold", secondary_world.state === "running" ? "text-ok" : secondary_world.state === "starting" || transitioning ? "text-warn" : "text-muted")}
role="status"
@@ -587,7 +587,7 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
{reborn_world && (
<Card className="mt-4 p-7">
<div className="mb-1 text-xs font-medium uppercase tracking-[0.14em] text-muted">{realms ? `${realms.reborn} · ${t("overview.server")}` : t("realm.rebornWorld")}</div>
<div className="mb-1 flex items-center justify-between gap-3 text-xs font-medium uppercase tracking-[0.14em] text-muted"><span>{realms ? `${realms.reborn} · ${t("overview.server")}` : t("realm.rebornWorld")}</span>{chipOf(rebornRealm)}</div>
<div
className={cn("flex items-center gap-3 text-3xl font-semibold", reborn_world.state === "running" ? "text-ok" : reborn_world.state === "starting" || transitioning ? "text-warn" : "text-muted")}
role="status"
@@ -649,6 +649,7 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
/>
)}
{publishing && <PublishRealmDialog realm={publishing} onClose={() => setPublishing(null)} />}
{showCrashModal && (
<CrashHistoryModal
serverId={server.id}
+3 -2
View File
@@ -2,10 +2,11 @@ import { useState } from "react";
import { Globe, Network } from "lucide-react";
import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
import { PublishCard } from "./PublishCard";
import { BrowsePage } from "@/screens/BrowsePage";
import { FriendsPage } from "@/screens/FriendsPage";
export function PlayWithFriends({ serverId }: { serverId: string; path?: string }) {
export function PlayWithFriends({ serverId, serverName = "" }: { serverId: string; serverName?: string; path?: string }) {
const t = useT();
const [tab, setTab] = useState<"servers" | "lan">("servers");
@@ -38,7 +39,7 @@ export function PlayWithFriends({ serverId }: { serverId: string; path?: string
</button>
</div>
{tab === "servers" && <BrowsePage />}
{tab === "servers" && <><PublishCard serverId={serverId} serverName={serverName} /><BrowsePage /></>}
{tab === "lan" && <FriendsPage serverId={serverId} />}
</div>
);
+49 -123
View File
@@ -1,138 +1,64 @@
import { useEffect, useState } from "react";
import { Loader2 } from "lucide-react";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { cn } from "@/lib/utils";
import { useT, type Key } from "@/i18n";
import { api, asUiError, type RealmMode } from "@/lib/api";
import { realmRegistry, useRegistryStatus } from "@/lib/registry";
import { asControlError, control, type ControlStatus } from "@/lib/control";
import { useRegistryStatus } from "@/lib/registry";
import { isListed, stateTone, usePublishRealms, type PublishRealm } from "@/lib/publishRealms";
import type { RealmPublishStatus } from "@/lib/registry";
import { PublishAllDialog, PublishRealmDialog } from "@/screens/PublishDialog";
const LANGUAGES = ["en", "ru", "de", "fr", "es", "zh", "pt", "pl", "uk"];
const REALM_LABEL: Record<RealmMode, string> = { coa: "Conquest of Azeroth", wildcard: "Wildcard", reborn: "Warcraft Reborn" };
/** The realms this server runs: the main one keeps the plain id it was published under, each realm that starts next to it has its own. */
export function PublishCard({ serverId, serverName }: { serverId: string; serverName: string }) {
const [realms, setRealms] = useState<{ localId: string; mode: RealmMode }[] | null>(null);
useEffect(() => {
let alive = true;
void api.realmProfiles(serverId).then((r) => {
if (!alive) return;
const extra: RealmMode[] = [];
if (r.simultaneous) extra.push(r.active === "coa" ? "wildcard" : "coa");
if (r.with_reborn) extra.push("reborn");
setRealms([{ localId: `srv-${serverId}`, mode: r.active }, ...extra.map((mode) => ({ localId: `srv-${serverId}:${mode}`, mode }))]);
}).catch(() => { if (alive) setRealms([{ localId: `srv-${serverId}`, mode: "coa" }]); });
return () => { alive = false; };
}, [serverId]);
if (!realms) return null;
const several = realms.length > 1;
return <>{realms.map((r) => (
<RealmPublish key={r.localId} localId={r.localId} serverName={several && r.mode !== realms[0].mode ? `${serverName} · ${REALM_LABEL[r.mode]}` : serverName} realmLabel={several ? REALM_LABEL[r.mode] : null} />
))}</>;
/** A small button on a realm card: the listing state of that realm; it opens the window to publish or configure it. */
export function ListingChip({ status, hasUrl, onOpen }: { status: RealmPublishStatus | undefined; hasUrl: boolean; onOpen: () => void }) {
const t = useT();
const listed = isListed(status);
if (!listed && !hasUrl) return null;
return (
<button
type="button"
onClick={onOpen}
className={cn("inline-flex cursor-pointer items-center gap-1.5 rounded-full border px-3 py-1 text-xs font-medium normal-case tracking-normal transition-colors", listed ? "border-line bg-card-2 hover:border-gold/40" : "border-gold/40 text-gold hover:bg-gold/10")}
title={t("registry.title")}
>
{listed ? <span className={stateTone(status?.state)}>{t(`registry.short.${status!.state}` as Key)}</span> : t("registry.publishShort")}
</button>
);
}
/** Publishing one realm to the central Registry: a name, a description, a language. Nothing else leaves this machine. */
function RealmPublish({ localId, serverName, realmLabel }: { localId: string; serverName: string; realmLabel: string | null }) {
/** The public listing of this server's realms: one line per realm; the form opens in a window. */
export function PublishCard({ serverId, serverName }: { serverId: string; serverName: string }) {
const t = useT();
const { status, refresh } = useRegistryStatus();
const mine = status?.realms.find((r) => r.local_id === localId);
const published = !!mine?.enabled;
const [name, setName] = useState(serverName);
const [description, setDescription] = useState("");
const [language, setLanguage] = useState("en");
const [region, setRegion] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [allowPortable, setAllowPortable] = useState(false);
const [existingOnly, setExistingOnly] = useState(false);
const [route, setRoute] = useState("");
const [accessSaved, setAccessSaved] = useState(false);
const [ctl, setCtl] = useState<ControlStatus | null>(null);
const host = ctl?.hosting.find((h) => h.local_id === localId);
const link = host?.link;
useEffect(() => {
const load = () => void control.status().then(setCtl).catch(() => {});
load();
const timer = setInterval(load, 3000);
return () => clearInterval(timer);
}, []);
useEffect(() => { if (mine) { setExistingOnly(mine.existing_only); setAllowPortable(mine.allow_portable); setRoute(mine.route ?? ""); } }, [mine?.existing_only, mine?.allow_portable, mine?.route]);
async function saveAccess() {
setBusy(true); setError(null); setAccessSaved(false);
try { await control.setAccess(localId, existingOnly, allowPortable, route.trim() === "" ? null : route.trim()); await refresh(); setAccessSaved(true); } catch (e) { setError(asControlError(e).message); } finally { setBusy(false); }
}
useEffect(() => {
if (mine && mine.display_name) { setName(mine.display_name); setDescription(mine.description); setLanguage(mine.language || "en"); setRegion(mine.region ?? ""); }
}, [mine?.display_name, mine?.description, mine?.language]);
async function run(action: () => Promise<void>) {
setBusy(true);
setError(null);
try { await action(); await refresh(); } catch (e) { setError(asUiError(e).technical); } finally { setBusy(false); }
}
const tone = mine?.state === "online" ? "text-ok" : mine?.state === "rejected" ? "text-bad" : mine?.state === "retrying" || mine?.state === "realm_stopped" || mine?.state === "waiting_for_realm" ? "text-warn" : "text-muted";
const realms = usePublishRealms(serverId, serverName);
const { status } = useRegistryStatus();
const [open, setOpen] = useState<PublishRealm | "all" | null>(null);
if (!realms) return null;
const listed = (r: PublishRealm) => isListed(status?.realms.find((s) => s.local_id === r.localId));
const someUnlisted = realms.some((r) => !listed(r));
return (
<Card className="mt-6 p-6">
<h2 className="font-semibold">{t("registry.title")}{realmLabel ? ` · ${realmLabel}` : ""}</h2>
<div className="flex flex-wrap items-center justify-between gap-3">
<h2 className="font-semibold">{t("registry.title")}</h2>
{realms.length > 1 && someUnlisted && <Button size="sm" onClick={() => setOpen("all")}>{t("registry.publishAll")}</Button>}
</div>
<p className="mt-1 text-sm text-muted">{t("registry.text")}</p>
{!published && <>
<label htmlFor={`registry-name-${localId}`} className="mt-4 block text-sm font-medium">{t("registry.name")}</label>
<input id={`registry-name-${localId}`} value={name} maxLength={80} onChange={(e) => setName(e.target.value)} className="mt-1 w-full rounded-md border border-line bg-card px-3 py-2" />
<label htmlFor={`registry-description-${localId}`} className="mt-3 block text-sm font-medium">{t("registry.description")}</label>
<textarea id={`registry-description-${localId}`} value={description} rows={3} onChange={(e) => setDescription(e.target.value)} className="mt-1 w-full rounded-md border border-line bg-card px-3 py-2" />
<p className="mt-1 text-xs text-muted">{t("registry.descriptionHint")}</p>
<label htmlFor={`registry-language-${localId}`} className="mt-3 block text-sm font-medium">{t("registry.language")}</label>
<select id={`registry-language-${localId}`} value={language} onChange={(e) => setLanguage(e.target.value)} className="mt-1 rounded-md border border-line bg-card px-3 py-2">
{LANGUAGES.map((l) => <option key={l} value={l}>{l}</option>)}
</select>
<label htmlFor={`registry-region-${localId}`} className="mt-3 block text-sm font-medium">{t("registry.region")}</label>
<input id={`registry-region-${localId}`} value={region} maxLength={16} placeholder="EU" onChange={(e) => setRegion(e.target.value)} className="mt-1 w-32 rounded-md border border-line bg-card px-3 py-2" />
<div className="mt-4">
<Button variant="primary" disabled={busy || !status?.url || name.trim() === ""} onClick={() => void run(() => realmRegistry.publish(localId, name, description, language, region.trim() === "" ? null : region.trim()))}>
{busy && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}{t("registry.publish")}
</Button>
{!status?.url && <p className="mt-2 text-xs text-muted">{t("registry.noUrl")}</p>}
</div>
</>}
{mine && (published || mine.state === "unpublishing") && <div className="mt-4 rounded-md border border-line p-3 text-sm" role="status">
<p className={cn("font-medium", tone)} data-state={mine.state}>{t(`registry.state.${mine.state}` as Key)}</p>
<p className="mt-1 text-xs text-muted">{mine.display_name}{mine.metadata_revision ? ` · ${t("registry.revision", { n: mine.metadata_revision })}` : ""}</p>
{mine.last_error && <p className="mt-1 text-xs text-warn">{mine.last_error}</p>}
{mine.state === "retrying" && mine.retry_in_secs !== null && <p className="mt-1 text-xs text-muted">{t("registry.retryIn", { s: mine.retry_in_secs })}</p>}
<div className="mt-3 flex gap-2">
{mine.state === "rejected" && <Button size="sm" onClick={() => void run(async () => { await realmRegistry.retry(localId); })}>{t("registry.retry")}</Button>}
<Button size="sm" disabled={busy} onClick={() => void run(() => realmRegistry.unpublish(localId))}>{t("registry.stop")}</Button>
</div>
</div>}
{mine && (published || mine.state === "unpublishing") && <div className="mt-4 rounded-md border border-line p-3 text-sm" data-testid="access-options">
<p className="font-medium">{t("access.title")}</p>
<p className="mt-1 text-xs text-muted">{t("access.text")}</p>
<label className="mt-3 flex items-start gap-2"><input type="checkbox" checked={existingOnly} onChange={(e) => setExistingOnly(e.target.checked)} className="mt-1" data-testid="existing-only" /><span>{t("access.existingOnly")}<span className="block text-xs text-muted">{t("access.existingOnlyHint")}</span></span></label>
<label className="mt-3 flex items-start gap-2"><input type="checkbox" checked={allowPortable} onChange={(e) => setAllowPortable(e.target.checked)} className="mt-1" data-testid="allow-portable" /><span>{t("access.allowPortable")}<span className="block text-xs text-muted">{t("access.allowPortableHint")}</span></span></label>
<label htmlFor={`access-route-${localId}`} className="mt-3 block font-medium">{t("access.route")}</label>
<input id={`access-route-${localId}`} value={route} placeholder="play.example.org:3724" onChange={(e) => setRoute(e.target.value)} className="mt-1 w-full rounded-md border border-line bg-card px-3 py-2" data-testid={`access-route-${localId}`} />
<p className="mt-1 text-xs text-muted">{t("access.routeHint")}</p>
<div className="mt-3 flex items-center gap-3">
<Button size="sm" disabled={busy} onClick={() => void saveAccess()}>{t("access.save")}</Button>
{accessSaved && <span className="text-xs text-ok" role="status">{t("access.saved")}</span>}
</div>
<p className={cn("mt-3 text-xs", link?.connected ? "text-ok" : "text-muted")} data-testid="control-link" data-connected={link?.connected ? "yes" : "no"}>
{link?.connected ? t("access.linkUp") : t("access.linkDown")}{link?.last_error && !link.connected ? ` — ${link.last_error}` : ""}
</p>
<p className={cn("mt-2 text-xs", host?.relay?.connected ? "text-ok" : "text-warn")} data-testid="relay-link">{host?.relay?.connected ? t("access.relayUp") : t("access.relayDown")}{host?.relay?.last_error ? ` — ${host.relay.last_error}` : ""}</p>
{ctl && ctl.secret_store === "file" && <p className="mt-1 text-xs text-warn">{t("access.fileStore")}</p>}
</div>}
{error && <p className="mt-3 text-sm text-bad" role="alert">{error}</p>}
<ul className="mt-4 divide-y divide-line border-y border-line">
{realms.map((r) => {
const mine = status?.realms.find((s) => s.local_id === r.localId);
return (
<li key={r.localId} className="flex flex-wrap items-center justify-between gap-3 py-3">
<div>
<p className="font-medium">{r.label}</p>
<p className={cn("text-xs", stateTone(isListed(mine) ? mine?.state : undefined))} data-state={mine?.state}>{t(`registry.short.${isListed(mine) ? mine!.state : "disabled"}` as Key)}</p>
</div>
<Button size="sm" onClick={() => setOpen(r)}>{isListed(mine) ? t("registry.configure") : t("registry.publishShort")}</Button>
</li>
);
})}
</ul>
{!status?.url && <p className="mt-3 text-xs text-muted">{t("registry.noUrl")}</p>}
{open === "all" && <PublishAllDialog realms={realms} onClose={() => setOpen(null)} />}
{open && open !== "all" && <PublishRealmDialog realm={open} onClose={() => setOpen(null)} />}
</Card>
);
}
+253
View File
@@ -0,0 +1,253 @@
import { useEffect, useState, type ReactNode } from "react";
import { Loader2, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { cn } from "@/lib/utils";
import { useT, type Key } from "@/i18n";
import { asUiError, api } from "@/lib/api";
import { realmRegistry, useRegistryStatus } from "@/lib/registry";
import { asControlError, control, type ControlStatus } from "@/lib/control";
import { isListed, stateTone, type PublishRealm } from "@/lib/publishRealms";
const LANGUAGES = ["en", "ru", "de", "fr", "es", "zh", "pt", "pl", "uk"];
function Modal({ title, onClose, children }: { title: string; onClose: () => void; children: ReactNode }) {
const t = useT();
useEffect(() => {
const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [onClose]);
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 md:p-6" role="presentation" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
<Card className="flex max-h-[88vh] w-full max-w-xl flex-col p-6 shadow-2xl" role="dialog" aria-modal="true" aria-label={title}>
<div className="flex items-center justify-between border-b border-line pb-4">
<h2 className="text-lg font-semibold">{title}</h2>
<button type="button" onClick={onClose} className="cursor-pointer text-muted transition-colors hover:text-ink" aria-label={t("btn.close")}>
<X className="h-5 w-5" aria-hidden />
</button>
</div>
<div className="flex-1 overflow-y-auto pt-4">{children}</div>
</Card>
</div>
);
}
/** The name, description, language and region of a listing; the fields are the same for one realm and for all of them. */
function ListingFields({ idPrefix, name, setName, description, setDescription, language, setLanguage, region, setRegion, hideName }: {
idPrefix: string; name: string; setName: (v: string) => void; description: string; setDescription: (v: string) => void;
language: string; setLanguage: (v: string) => void; region: string; setRegion: (v: string) => void; hideName?: boolean;
}) {
const t = useT();
return <>
{!hideName && <>
<label htmlFor={`${idPrefix}-name`} className="block text-sm font-medium">{t("registry.name")}</label>
<input id={`${idPrefix}-name`} value={name} maxLength={80} onChange={(e) => setName(e.target.value)} className="mt-1 w-full rounded-md border border-line bg-card px-3 py-2" />
</>}
<label htmlFor={`${idPrefix}-description`} className="mt-3 block text-sm font-medium">{t("registry.description")}</label>
<textarea id={`${idPrefix}-description`} value={description} rows={3} onChange={(e) => setDescription(e.target.value)} className="mt-1 w-full rounded-md border border-line bg-card px-3 py-2" />
<p className="mt-1 text-xs text-muted">{t("registry.descriptionHint")}</p>
<div className="mt-3 flex flex-wrap gap-4">
<div>
<label htmlFor={`${idPrefix}-language`} className="block text-sm font-medium">{t("registry.language")}</label>
<select id={`${idPrefix}-language`} value={language} onChange={(e) => setLanguage(e.target.value)} className="mt-1 rounded-md border border-line bg-card px-3 py-2">
{LANGUAGES.map((l) => <option key={l} value={l}>{l}</option>)}
</select>
</div>
<div>
<label htmlFor={`${idPrefix}-region`} className="block text-sm font-medium">{t("registry.region")}</label>
<input id={`${idPrefix}-region`} value={region} maxLength={16} placeholder="EU" onChange={(e) => setRegion(e.target.value)} className="mt-1 w-32 rounded-md border border-line bg-card px-3 py-2" />
</div>
</div>
</>;
}
/** Who may join and how: shown before publishing, so the choice is made once, not found later. */
function JoinChoices({ existingOnly, setExistingOnly, allowPortable, setAllowPortable }: { existingOnly: boolean; setExistingOnly: (v: boolean) => void; allowPortable: boolean; setAllowPortable: (v: boolean) => void }) {
const t = useT();
return (
<div className="mt-4 rounded-md border border-line p-3 text-sm">
<p className="font-medium">{t("access.title")}</p>
<p className="mt-1 text-xs text-muted">{t("access.text")}</p>
<label className="mt-3 flex items-start gap-2"><input type="checkbox" checked={existingOnly} onChange={(e) => setExistingOnly(e.target.checked)} className="mt-1" /><span>{t("access.existingOnly")}<span className="block text-xs text-muted">{t("access.existingOnlyHint")}</span></span></label>
<label className="mt-3 flex items-start gap-2"><input type="checkbox" checked={allowPortable} onChange={(e) => setAllowPortable(e.target.checked)} className="mt-1" /><span>{t("access.allowPortable")}<span className="block text-xs text-muted">{t("access.allowPortableHint")}</span></span></label>
</div>
);
}
/** Publishing, stopping and the access options of one realm. */
export function PublishRealmDialog({ realm, onClose }: { realm: PublishRealm; onClose: () => void }) {
const t = useT();
const { localId } = realm;
const { status, refresh } = useRegistryStatus();
const mine = status?.realms.find((r) => r.local_id === localId);
const published = !!mine?.enabled;
const [name, setName] = useState(realm.defaultName);
const [description, setDescription] = useState("");
const [language, setLanguage] = useState("en");
const [region, setRegion] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
// New listings start with portable characters allowed and accounts created for new players; the choice is shown before publishing.
const [allowPortable, setAllowPortable] = useState(true);
const [existingOnly, setExistingOnly] = useState(false);
const [route, setRoute] = useState("");
const [accessSaved, setAccessSaved] = useState(false);
const [portableEnabled, setPortableEnabled] = useState<boolean | null>(null);
const primaryRealm = !localId.includes(":");
const [ctl, setCtl] = useState<ControlStatus | null>(null);
const host = ctl?.hosting.find((h) => h.local_id === localId);
const link = host?.link;
useEffect(() => {
if (!primaryRealm) return;
let active = true;
void api.allSettings(localId.slice(4)).then((items) => {
const item = items.find((i) => i.key === "PortableSession.Enable");
if (active && item) setPortableEnabled(item.value === "1" || item.value.toLowerCase() === "true");
}).catch((e) => { if (active) setError(asUiError(e).technical); });
return () => { active = false; };
}, [localId, primaryRealm]);
useEffect(() => {
const load = () => void control.status().then(setCtl).catch(() => {});
load();
const timer = setInterval(load, 3000);
return () => clearInterval(timer);
}, []);
useEffect(() => { if (mine) { setExistingOnly(mine.existing_only); setAllowPortable(mine.allow_portable); setRoute(mine.route ?? ""); } }, [mine?.existing_only, mine?.allow_portable, mine?.route]);
useEffect(() => {
if (mine && mine.display_name) { setName(mine.display_name); setDescription(mine.description); setLanguage(mine.language || "en"); setRegion(mine.region ?? ""); }
}, [mine?.display_name, mine?.description, mine?.language]);
async function saveAccess() {
setBusy(true); setError(null); setAccessSaved(false);
try {
if (primaryRealm && portableEnabled !== null) {
await api.allSettingsSave(localId.slice(4), {
"PortableSession.Enable": portableEnabled ? "1" : "0",
...(portableEnabled ? { "CharacterDatabase.WorkerThreads": "1" } : {}),
});
}
await control.setAccess(localId, existingOnly, allowPortable, route.trim() === "" ? null : route.trim());
await refresh();
setAccessSaved(true);
} catch (e) { setError(asControlError(e).message); } finally { setBusy(false); }
}
async function run(action: () => Promise<void>) {
setBusy(true);
setError(null);
try { await action(); await refresh(); } catch (e) { setError(asUiError(e).technical); } finally { setBusy(false); }
}
async function publish() {
setBusy(true);
setError(null);
try {
await realmRegistry.publish(localId, name, description, language, region.trim() === "" ? null : region.trim());
// Saving the joining options needs the listing to exist; if it cannot be saved now (for example the server is running), the options stay available below.
try { await control.setAccess(localId, existingOnly, allowPortable, route.trim() === "" ? null : route.trim()); }
catch (e) { setError(t("registry.accessFailed", { reason: asControlError(e).message })); }
await refresh();
} catch (e) { setError(asUiError(e).technical); } finally { setBusy(false); }
}
return (
<Modal title={t("registry.dialogTitle", { realm: realm.label })} onClose={onClose}>
<p className="text-sm text-muted">{t("registry.text")}</p>
{!published && <div className="mt-4">
<ListingFields idPrefix={`pub-${localId}`} name={name} setName={setName} description={description} setDescription={setDescription} language={language} setLanguage={setLanguage} region={region} setRegion={setRegion} />
<JoinChoices existingOnly={existingOnly} setExistingOnly={setExistingOnly} allowPortable={allowPortable} setAllowPortable={setAllowPortable} />
<div className="mt-4">
<Button variant="primary" disabled={busy || !status?.url || name.trim() === ""} onClick={() => void publish()}>
{busy && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}{t("registry.publish")}
</Button>
{!status?.url && <p className="mt-2 text-xs text-muted">{t("registry.noUrl")}</p>}
</div>
</div>}
{mine && isListed(mine) && <div className="mt-4 rounded-md border border-line p-3 text-sm" role="status">
<p className={cn("font-medium", stateTone(mine.state))} data-state={mine.state}>{t(`registry.state.${mine.state}` as Key)}</p>
{mine.state === "realm_stopped" && <p className="mt-2 text-xs text-warn">{t("registry.realmStoppedHint")}</p>}
<p className="mt-1 text-xs text-muted">{mine.display_name}{mine.metadata_revision ? ` · ${t("registry.revision", { n: mine.metadata_revision })}` : ""}</p>
{mine.last_error && <p className="mt-1 text-xs text-warn">{mine.last_error}</p>}
{mine.state === "retrying" && mine.retry_in_secs !== null && <p className="mt-1 text-xs text-muted">{t("registry.retryIn", { s: mine.retry_in_secs })}</p>}
<div className="mt-3 flex gap-2">
{mine.state === "rejected" && <Button size="sm" onClick={() => void run(async () => { await realmRegistry.retry(localId); })}>{t("registry.retry")}</Button>}
<Button size="sm" disabled={busy} onClick={() => void run(() => realmRegistry.unpublish(localId))}>{t("registry.stop")}</Button>
</div>
</div>}
{mine && isListed(mine) && <div className="mt-4 rounded-md border border-line p-3 text-sm" data-testid="access-options">
<p className="font-medium">{t("access.title")}</p>
<p className="mt-1 text-xs text-muted">{t("access.text")}</p>
{primaryRealm && <label className="mt-3 flex items-start gap-2"><input type="checkbox" checked={portableEnabled ?? false} disabled={portableEnabled === null} onChange={(e) => setPortableEnabled(e.target.checked)} className="mt-1" data-testid="portable-enabled" /><span>{t("access.portableEnabled")}<span className="block text-xs text-muted">{t("access.portableEnabledHint")}</span></span></label>}
<label className="mt-3 flex items-start gap-2"><input type="checkbox" checked={existingOnly} onChange={(e) => setExistingOnly(e.target.checked)} className="mt-1" data-testid="existing-only" /><span>{t("access.existingOnly")}<span className="block text-xs text-muted">{t("access.existingOnlyHint")}</span></span></label>
<label className="mt-3 flex items-start gap-2"><input type="checkbox" checked={allowPortable} onChange={(e) => setAllowPortable(e.target.checked)} className="mt-1" data-testid="allow-portable" /><span>{t("access.allowPortable")}<span className="block text-xs text-muted">{t("access.allowPortableHint")}</span></span></label>
<label htmlFor={`access-route-${localId}`} className="mt-3 block font-medium">{t("access.route")}</label>
<input id={`access-route-${localId}`} value={route} placeholder="play.example.org:3724" onChange={(e) => setRoute(e.target.value)} className="mt-1 w-full rounded-md border border-line bg-card px-3 py-2" data-testid="access-route" />
<p className="mt-1 text-xs text-muted">{t("access.routeHint")}</p>
<div className="mt-3 flex items-center gap-3">
<Button size="sm" disabled={busy} onClick={() => void saveAccess()}>{t("access.save")}</Button>
{accessSaved && <span className="text-xs text-ok" role="status">{t("access.saved")}</span>}
</div>
<p className={cn("mt-3 text-xs", link?.connected ? "text-ok" : "text-muted")} data-testid="control-link" data-connected={link?.connected ? "yes" : "no"}>
{link?.connected ? t("access.linkUp") : t("access.linkDown")}{link?.last_error && !link.connected ? ` — ${link.last_error}` : ""}
</p>
<p className={cn("mt-2 text-xs", host?.relay?.connected ? "text-ok" : "text-warn")} data-testid="relay-link">{host?.relay?.connected ? t("access.relayUp") : t("access.relayDown")}{host?.relay?.last_error ? ` — ${host.relay.last_error}` : ""}</p>
{ctl && ctl.secret_store === "file" && <p className="mt-1 text-xs text-warn">{t("access.fileStore")}</p>}
</div>}
{error && <p className="mt-3 text-sm text-bad" role="alert">{error}</p>}
</Modal>
);
}
/** One description, language and region for every realm that is not listed yet. */
export function PublishAllDialog({ realms, onClose }: { realms: PublishRealm[]; onClose: () => void }) {
const t = useT();
const { status, refresh } = useRegistryStatus();
const [description, setDescription] = useState("");
const [language, setLanguage] = useState("en");
const [region, setRegion] = useState("");
const [allowPortable, setAllowPortable] = useState(true);
const [existingOnly, setExistingOnly] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const todo = realms.filter((r) => !isListed(status?.realms.find((s) => s.local_id === r.localId)));
async function publishAll() {
setBusy(true); setError(null);
try {
for (const r of todo) await realmRegistry.publish(r.localId, r.defaultName, description, language, region.trim() === "" ? null : region.trim());
// The joining options are saved realm by realm; one that cannot be saved now (for example the server is running) does not stop the others.
const failed: string[] = [];
for (const r of todo) {
try { await control.setAccess(r.localId, existingOnly, allowPortable, null); }
catch (e) { failed.push(`${r.label}: ${asControlError(e).message}`); }
}
await refresh();
if (failed.length === 0) onClose();
else setError(t("registry.accessFailed", { reason: failed.join(" · ") }));
} catch (e) { setError(asUiError(e).technical); await refresh(); } finally { setBusy(false); }
}
return (
<Modal title={t("registry.publishAll")} onClose={onClose}>
<p className="text-sm text-muted">{t("registry.publishAllText")}</p>
<ul className="mt-3 space-y-1 text-sm">
{realms.map((r) => <li key={r.localId} className="flex justify-between gap-3"><span>{r.defaultName}</span><span className="text-muted">{todo.includes(r) ? t("registry.short.disabled") : t("registry.alreadyListed")}</span></li>)}
</ul>
{todo.length > 0 && <div className="mt-4">
<ListingFields idPrefix="pub-all" name="" setName={() => undefined} description={description} setDescription={setDescription} language={language} setLanguage={setLanguage} region={region} setRegion={setRegion} hideName />
<JoinChoices existingOnly={existingOnly} setExistingOnly={setExistingOnly} allowPortable={allowPortable} setAllowPortable={setAllowPortable} />
<div className="mt-4">
<Button variant="primary" disabled={busy || !status?.url} onClick={() => void publishAll()}>
{busy && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}{t("registry.publishAllButton", { n: todo.length })}
</Button>
{!status?.url && <p className="mt-2 text-xs text-muted">{t("registry.noUrl")}</p>}
</div>
</div>}
{error && <p className="mt-3 text-sm text-bad" role="alert">{error}</p>}
</Modal>
);
}
+120
View File
@@ -0,0 +1,120 @@
import { useEffect, useState } from "react";
import { api, asUiError, type RaceAvailability, type UiError } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { useHuman, useI18n } from "@/i18n";
import type { UnsavedChangesGuard } from "@/lib/unsavedGuard";
export function RaceAvailabilitySettings({ serverId, blocked, onSaved, onRegisterGuard }: {
serverId: string;
blocked: boolean;
onSaved: () => void;
onRegisterGuard: (guard: UnsavedChangesGuard | null) => void;
}) {
const { t } = useI18n();
const human = useHuman();
const [data, setData] = useState<RaceAvailability | null>(null);
const [disabled, setDisabled] = useState<number[]>([]);
const [query, setQuery] = useState("");
const [busy, setBusy] = useState(false);
const [saved, setSaved] = useState(false);
const [error, setError] = useState<UiError | null>(null);
const canonical = (ids: number[]) => [...ids].sort((a, b) => a - b).join(",");
const dirty = !!data && canonical(disabled) !== canonical(data.disabledRaceIds);
const locked = blocked || busy || !data?.serverConfigSupported;
useEffect(() => {
let active = true;
setData(null);
setDisabled([]);
setError(null);
setSaved(false);
void api.raceAvailability(serverId).then(result => {
if (active) { setData(result); setDisabled(result.disabledRaceIds); }
}).catch(reason => { if (active) setError(asUiError(reason)); });
return () => { active = false; };
}, [serverId]);
async function save(): Promise<boolean> {
if (!data || locked) return false;
setBusy(true);
setError(null);
try {
const result = await api.raceAvailabilitySave(serverId, data.catalogSha256, data.realm, disabled);
setData(result);
setDisabled(result.disabledRaceIds);
setSaved(true);
onSaved();
return true;
} catch (reason) {
setError(asUiError(reason));
return false;
} finally {
setBusy(false);
}
}
useEffect(() => {
onRegisterGuard(dirty ? {
isDirty: () => dirty,
save,
discard: () => { setDisabled(data?.disabledRaceIds ?? []); setSaved(false); },
} : null);
return () => onRegisterGuard(null);
}, [dirty, disabled, data, busy, blocked, serverId, onRegisterGuard]);
return (
<section className="mt-3 space-y-3 border-t border-line/40 pt-3" aria-label={t("races.available")}>
<h3 className="text-sm font-semibold">{t("races.available")}</h3>
{error && <p role="alert" className="text-xs text-bad">{error.human.code === "unknown" ? error.technical : human(error.human).message}</p>}
{data && <>
<p className="text-xs text-muted">{t("races.count", { allowed: data.races.length - disabled.length, disabled: disabled.length })}</p>
{!data.serverConfigSupported && <p className="text-xs text-warn">{t("races.updateServer")}</p>}
{data.catalogNeedsReview && <p className="text-xs text-warn">{t("races.reviewCatalog")}</p>}
{data.unrecognizedRaceIds.length > 0 && <p className="text-xs text-warn">{t("races.unknownIds", { ids: data.unrecognizedRaceIds.join(", ") })}</p>}
<input value={query} onChange={event => setQuery(event.target.value)} placeholder={t("set.search")}
aria-label={t("set.search")} className="w-full rounded border border-line bg-bg px-2 py-1 text-sm" />
<div className="grid gap-3 sm:grid-cols-2">
{(["horde", "alliance", null] as const).map(faction => {
const races = data.races.filter(race => race.faction === faction);
if (faction === null && !races.length) return null;
const title = t(faction === "horde" ? "races.horde" : faction === "alliance" ? "races.alliance" : "races.available");
return (
<div key={faction ?? "other"} className={faction === null ? "sm:col-span-2" : undefined}>
<div className="max-h-52 overflow-auto rounded-md border border-line/60">
<table className="w-full text-left text-xs" aria-label={title}>
<thead className="sticky top-0 bg-bg text-muted">
<tr><th scope="col" className="w-12 px-3 py-2 font-medium">ID</th>
<th scope="col" className="px-3 py-2 font-medium text-ink">{title}</th>
<th scope="col" className="w-10 px-3 py-2"><span className="sr-only">{t("races.allowCreation")}</span></th></tr>
</thead>
<tbody className="divide-y divide-line/40">
{races.filter(race => `${race.name} ${race.id}`.toLowerCase().includes(query.trim().toLowerCase())).map(race => (
<tr key={race.id} className="hover:bg-line/20">
<td className="px-3 py-1.5 tabular-nums text-muted">{race.id}</td>
<td className="px-3 py-1.5">{race.name}</td>
<td className="px-3 py-1.5 text-right">
<input type="checkbox" checked={!disabled.includes(race.id)} disabled={locked}
aria-label={`${race.name} (${race.id}): ${t("races.allowCreation")}`}
onChange={event => { setSaved(false); setDisabled(previous => event.target.checked ? previous.filter(id => id !== race.id) : [...previous, race.id]); }} />
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
})}
</div>
<div className="flex flex-wrap gap-2">
<Button size="sm" variant="ghost" disabled={locked} onClick={() => { setDisabled([]); setSaved(false); }}>{t("races.allowAll")}</Button>
<Button size="sm" variant="primary" disabled={locked || (!dirty && !data.catalogNeedsReview)} onClick={() => void save()}>{t("set.save")}</Button>
<Button size="sm" variant="ghost" disabled={busy || !dirty} onClick={() => { setDisabled(data.disabledRaceIds); setSaved(false); }}>{t("set.discard")}</Button>
</div>
<p className="text-xs text-muted">{t(saved ? "races.saved" : "races.restart")}</p>
<p className="text-xs text-muted">{t("races.clientPending")}</p>
<p className="text-xs text-muted">{t("races.existing")}</p>
</>}
</section>
);
}
+1 -1
View File
@@ -33,7 +33,7 @@ export function RealmStartupSettings({ serverId }: { serverId: string }) {
{view?.with_reborn && <p className="mt-1 text-sm text-muted">{t("realm.rebornPort", { port: view.reborn_world_port ?? "—" })}</p>}
{view && view.active !== "coa" && !view.with_reborn && <p className="mt-1 text-sm text-warn">{t("realm.rebornNeedsCoa")}</p>}
{view?.simultaneous && view.with_reborn && <p className="mt-3 text-sm">{t("realm.allThree")}</p>}
<p className="mt-3 text-sm text-muted">{t("realm.simultaneousHint")}</p>
<details className="mt-4 text-sm text-muted"><summary className="cursor-pointer">{t("settings.startupHelp")}</summary><p className="mt-2 leading-relaxed">{t("realm.simultaneousHint")}</p></details>
{busy && <p className="mt-2 text-sm" role="status">{t("realm.preparing")}</p>}
{error && <p className="mt-3 text-sm text-bad" role="alert">{error}</p>}
</Card>;
+1 -1
View File
@@ -92,7 +92,7 @@ export function RealmlistMenu({ serverId, className }: { serverId: string; class
onClick={() => setOpen((v) => !v)}
aria-haspopup="menu"
aria-expanded={open}
className="flex h-16 cursor-pointer items-center gap-3 rounded-md border border-line bg-card-2 px-4 text-left transition-colors hover:border-gold/50"
className="flex h-12 cursor-pointer items-center gap-3 rounded-md border border-line bg-card-2 px-4 text-left transition-colors hover:border-gold/50"
>
<span>
<span className="block text-[11px] uppercase tracking-wide text-muted">{t("realm.label")}</span>
+76
View File
@@ -0,0 +1,76 @@
import { useEffect, useRef, useState } from "react";
import { invoke } from "@tauri-apps/api/core";
import { getVersion } from "@tauri-apps/api/app";
import { useI18n, LOCALES, type Locale } from "@/i18n";
import { useSelfUpdate } from "@/lib/selfUpdate";
import { bundledHistories, compareVersions, releasesForUpdate, repositories, translatedNotes, type Component, type History } from "@/lib/releaseHistory";
import { api } from "@/lib/api";
import { Card } from "@/components/ui/card";
export interface HistorySelection { component: Component; from?: string; to?: string }
export function ReleaseHistory({ selection, onSelect }: { selection: HistorySelection; onSelect: (selection: HistorySelection) => void }) {
const { locale, t } = useI18n();
const [language, setLanguage] = useState<Locale>(locale);
const [feeds, setFeeds] = useState(bundledHistories);
const [fresh, setFresh] = useState<Partial<Record<Component, boolean>>>({});
const [mode, setMode] = useState<"all" | "range">("all");
const [selected, setSelected] = useState("");
const [installed, setInstalled] = useState<string>();
const updater = useSelfUpdate();
const { component } = selection;
const lastServer = useRef<HistorySelection>({ component: "server" });
const [linkError, setLinkError] = useState<string>();
useEffect(() => { if (component === "server") lastServer.current = selection; setLinkError(undefined); }, [selection, component]);
const target = component === "manager" ? updater.version : selection.to;
const from = component === "manager" ? installed : selection.from;
useEffect(() => setLanguage(locale), [locale]);
useEffect(() => { void getVersion().then(setInstalled).catch(() => {}); }, []);
useEffect(() => {
setSelected("");
setMode(selection.to || (component === "manager" && updater.version) ? "range" : "all");
}, [selection, component, updater.version]);
useEffect(() => {
let live = true;
void invoke<History>("release_history", { component }).then(feed => {
if (live && feed.component === component && Array.isArray(feed.releases)) {
setFeeds(previous => ({ ...previous, [component]: feed }));
setFresh(previous => ({ ...previous, [component]: feed.source === "remote" }));
}
}).catch(() => {}); // Bundled reviewed notes remain visible offline.
return () => { live = false; };
}, [component]);
const releases = [...(mode === "range" ? releasesForUpdate(feeds[component].releases, from, target) : feeds[component].releases)]
.sort((a, b) => compareVersions(b.version.split("-")[0], a.version.split("-")[0]) || b.date.localeCompare(a.date));
const record = releases.find(r => r.version === selected) ?? releases[0];
const notes = record ? translatedNotes(component, record, language) : undefined;
return <Card id="release-history" tabIndex={-1} className="mt-6 scroll-mt-4 overflow-hidden">
<div className="flex flex-wrap items-center justify-between gap-4 border-b border-line p-5">
<h2 className="font-semibold">{t("history.title")}</h2>
<div className="flex rounded-md border border-line p-1" aria-label={t("history.title")}>
{(["server", "manager"] as const).map(c => <button key={c} aria-pressed={component === c} onClick={() => onSelect(c === "server" ? lastServer.current : { component: c })} className={`cursor-pointer rounded px-3 py-1.5 text-sm ${component === c ? "bg-gold/10 text-gold" : "text-muted hover:text-ink"}`}>{t(`history.${c}`)}</button>)}
</div>
</div>
<div className="flex flex-wrap items-center justify-between gap-3 border-b border-line px-5 py-3 text-sm">
<div className="flex gap-3">
<button className={mode === "all" ? "text-gold" : "cursor-pointer text-muted"} aria-pressed={mode === "all"} onClick={() => setMode("all")}>{t("history.all")}</button>
{target && <button className={mode === "range" ? "text-gold" : "cursor-pointer text-muted"} aria-pressed={mode === "range"} onClick={() => setMode("range")}>{t("history.range")}{from ? ` · ${from} → ${target}` : ` · ${target}`}</button>}
</div>
<label className="flex items-center gap-2 text-muted">{t("history.language")}<select value={language} onChange={e => setLanguage(e.target.value as Locale)} className="rounded border border-line bg-panel px-2 py-1 text-ink">{LOCALES.map(l => <option key={l.id} value={l.id}>{l.name}</option>)}</select></label>
</div>
<div className="grid min-h-64 md:grid-cols-[180px_1fr]">
<div className="flex max-h-96 gap-1 overflow-auto border-b border-line p-3 md:block md:border-r md:border-b-0" aria-label={t("history.all")}>
{releases.map(r => <button key={r.tag} aria-pressed={r.version === record?.version} onClick={() => setSelected(r.version)} className={`mb-1 block shrink-0 cursor-pointer rounded-md px-3 py-2 text-left text-sm md:w-full ${r.version === record?.version ? "bg-gold/10 text-gold" : "text-muted hover:bg-white/5"}`}><span className="block font-medium">{r.version}</span><span className="text-xs text-muted">{r.date}{r.prerelease ? " · Pre-release" : ""}</span></button>)}
</div>
<div className="min-w-0 p-5" aria-live="polite">
{record && notes ? <><h3 className="text-lg font-semibold">{t(`history.${component}`)} {record.version}</h3>
{notes.fallback && <p className="mt-2 text-xs text-warn">{t("history.fallback")}</p>}
<ul lang={notes.fallback ? "en" : language} className="mt-4 list-disc space-y-2 pl-5 text-sm leading-relaxed">{notes.notes.map((note, i) => <li key={i}>{note}</li>)}</ul>
{record.experimentalFeatures?.includes("portable-characters") && <p className="mt-4 rounded border border-warn/30 p-3 text-sm text-warn">{t("history.experimental")}</p>}
<a className="mt-5 inline-block text-sm text-gold hover:underline" href={`https://github.com/${repositories[component]}/releases/tag/${encodeURIComponent(record.tag)}`} onClick={e => { e.preventDefault(); void api.openLink(e.currentTarget.href).catch(error => setLinkError(String(error))); }}>GitHub ↗</a>
{linkError && <p className="mt-2 break-words text-xs text-bad" role="alert">{linkError}</p>}
</> : <p className="text-sm text-muted">{t("history.empty")}</p>}
</div>
</div>
<p className="border-t border-line px-5 py-3 text-xs text-muted">{fresh[component] ? t("history.refreshed") : t("history.offline")}</p>
</Card>;
}
+256
View File
@@ -0,0 +1,256 @@
import { useEffect, useState } from "react";
import { open } from "@tauri-apps/plugin-dialog";
import { ChevronDown, ChevronRight, Loader2, RefreshCw, Server } from "lucide-react";
import { applyServerUpdate, clearServerUpdateResult, refreshServerUpdateState, useServerUpdate } from "@/lib/serverUpdate";
import { isUpdateCurrent } from "@/lib/serverUpdateStatus";
import { api, asUiError, type UiError, type UpdatePreview, type UpdateTxn } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { useStartAfterUpdate } from "@/lib/updatePrefs";
import { hasKey, useHuman, useI18n, type Key } from "@/i18n";
function mb(bytes: number) {
return bytes >= 1 << 20 ? `${(bytes / (1 << 20)).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`;
}
export function ServerUpdateCard({ serverId, onHistory, onAttention }: { serverId: string; onHistory: (from?: string | null, to?: string) => void; onAttention: (value: boolean) => void }) {
const { t } = useI18n();
const upd = useServerUpdate(serverId);
const human = useHuman();
const [preview, setPreview] = useState<UpdatePreview | null>(upd.preview);
const [pending, setPending] = useState<UpdateTxn | null>(null);
const [pendingChecked, setPendingChecked] = useState(false);
const [pendingStateError, setPendingStateError] = useState<UiError | null>(null);
const [localBusy, setBusy] = useState<"check" | "rollback" | "retry" | null>(null);
// an update keeps running in the background when this tab is left, so its state is the shared one
const busy = upd.applying ? "update" : localBusy;
const progress = upd.applying ? { step: upd.step ?? "Starting", percent: upd.percent } : null;
const [localError, setError] = useState<UiError | null>(null);
const error = pendingStateError ?? localError ?? upd.uiError;
const [localDone, setDone] = useState<string | null>(null);
const done = upd.result && "committed" in upd.result ? t("upd.updatedTo", { v: upd.result.committed }) : localDone;
const [choices, setChoices] = useState<Record<string, "keep" | "replace">>(() => Object.fromEntries((upd.preview?.conflicts ?? []).map(c => [c, "keep" as const])));
const [advanced, setAdvanced] = useState(false);
const [source, setSource] = useState("");
const [startAfter, setStartAfter] = useStartAfterUpdate("server", serverId);
useEffect(() => {
let active = true;
setPendingChecked(false);
setPending(null);
setPendingStateError(null);
void api.pendingUpdate(serverId).then((txn) => {
if (active) { setPending(txn); setPendingChecked(true); }
}).catch((e) => { if (active) setPendingStateError(asUiError(e)); });
return () => { active = false; };
}, [serverId]);
// Every finished attempt refreshes the disk state, including failures in the background.
useEffect(() => {
if (!upd.stateRevision) return;
setPreview(null);
setPendingChecked(!upd.stateError);
setPendingStateError(upd.stateError);
if (!upd.stateError) setPending(upd.result && "pending" in upd.result ? upd.result.pending : null);
}, [upd.stateRevision, serverId]);
useEffect(() => { onAttention(!!pending || !!pendingStateError); }, [pending, pendingStateError, onAttention]);
async function refreshPending() {
setPendingChecked(false);
try {
const txn = await refreshServerUpdateState(serverId);
setPending(txn);
setPendingStateError(null);
setPendingChecked(true);
return txn;
} catch (e) { setPendingStateError(asUiError(e)); throw e; }
}
async function check() {
setBusy("check");
setError(null);
setDone(null);
clearServerUpdateResult(serverId);
setPreview(null);
try {
const txn = await refreshPending();
if (txn) return;
const p = await api.checkUpdate(serverId, source.trim() || undefined);
setPreview(p);
setChoices(Object.fromEntries(p.conflicts.map((c) => [c, "keep" as const])));
} catch (e) {
setError(asUiError(e));
} finally {
setBusy(null);
}
}
async function update() {
if (!pendingChecked || pendingStateError || pending) return;
setError(null);
setDone(null);
await applyServerUpdate(serverId, { choices, source: source.trim() || undefined });
}
async function rollback(txn: UpdateTxn) {
if (!window.confirm(t("upd.confirmBack"))) return;
setBusy("rollback");
setError(null);
try {
await api.rollbackUpdate(serverId, txn.id);
setPending(null);
setDone(t("upd.wentBack"));
} catch (e) {
setError(asUiError(e));
} finally {
try { await refreshPending(); } catch { /* Keep the disk-state error visible. */ }
setBusy(null);
}
}
async function retryValidation(txn: UpdateTxn) {
setBusy("retry");
setError(null);
try {
const result = await api.retryUpdateValidation(serverId, txn.id);
if (result.state === "committed") {
setPending(null);
setPreview(null);
setDone(t("upd.updatedTo", { v: result.to_version }));
clearServerUpdateResult(serverId);
} else setPending(result);
} catch (e) { setError(asUiError(e)); }
finally {
try { await refreshPending(); } catch { /* Keep the disk-state error visible. */ }
setBusy(null);
}
}
async function browse() {
const p = await open({ directory: true, multiple: false, title: t("upd.dialogTitle") });
if (typeof p === "string") setSource(p);
}
return (
<div>
{pending && (
<Card className="mt-6 border-warn/40 p-5" role="alert">
<p className="font-medium text-warn">
{pending.state === "needs-decision" ? t("upd.pendingBad") : t("upd.pendingUnfinished")}
</p>
<p className="mt-1 whitespace-pre-wrap text-sm text-muted">{pending.message ?? t("upd.safeBack")}</p>
{pending.state === "needs-decision" && (
<Button className="mt-3 mr-3" size="sm" disabled={!!busy} onClick={() => void retryValidation(pending)}>
{busy === "retry" && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{t("upd.retryValidation")}
</Button>
)}
<p className="mt-1 text-sm text-muted">{t("upd.backNote")}</p>
<Button className="mt-3" size="sm" disabled={!!busy} onClick={() => void rollback(pending)}>
{busy === "rollback" && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{pending.from_version ? t("upd.goBackTo", { v: pending.from_version }) : t("upd.goBackBefore")}
</Button>
</Card>
)}
<Card className="mt-6 p-6">
<div className="flex items-start justify-between gap-3">
<div><h2 className="flex items-center gap-2 font-semibold"><Server className="h-4 w-4 text-gold" aria-hidden />{t("history.server")}</h2>
<p className="mt-2 text-sm text-muted">{preview?.from_version ? t("settings.version", { v: preview.from_version }) : "…"}</p></div>
<Button size="sm" disabled={!!busy} onClick={() => void check()} aria-label={t("upd.check")} title={t("upd.check")}><RefreshCw className={`h-4 w-4 ${busy === "check" ? "animate-spin" : ""}`} aria-hidden /></Button>
</div>
<button className="mt-3 cursor-pointer text-sm text-gold hover:underline" onClick={() => onHistory(preview?.from_version, preview && !isUpdateCurrent(preview) ? preview.to_version : undefined)}>{t(preview && !isUpdateCurrent(preview) ? "history.open" : "history.title")}</button>
<div className="mt-3"><button onClick={() => setAdvanced((v) => !v)} aria-expanded={advanced} className="flex cursor-pointer items-center gap-1 text-xs text-muted hover:text-ink">
{advanced ? <ChevronDown className="h-3 w-3" aria-hidden /> : <ChevronRight className="h-3 w-3" aria-hidden />}{t("install.advanced")}
</button></div>
{advanced && (
<div className="mt-3 flex gap-2">
<input aria-label={t("upd.folderLabel")} value={source} onChange={(e) => setSource(e.target.value)} placeholder={t("upd.folderHint")} className="selectable flex-1 rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none focus:border-gold" />
<Button size="sm" onClick={browse}>{t("install.browse")}</Button>
</div>
)}
{done && pendingChecked && !pendingStateError && <p className="mt-4 text-sm text-ok" role="status">{done}</p>}
{error && (
<div className="mt-4" role="alert">
<p className="selectable whitespace-pre-wrap break-words text-sm text-bad">
{error.human.code === "unknown" ? error.technical : human(error.human).message}
</p>
<button className="mt-1 cursor-pointer text-xs text-muted underline" onClick={() => void navigator.clipboard.writeText(error.technical)}>
{t("common.copyError")}
</button>
</div>
)}
{preview?.database_check_error && (
<p className="selectable mt-4 break-words text-sm text-warn" role="status">{t("upd.dbUnchecked", { why: preview.database_check_error })}</p>
)}
{preview && isUpdateCurrent(preview) && (
<div className="mt-5 border-t border-line pt-4">
<p className="font-medium text-ok" role="status">{t("upd.current", { v: preview.to_version })}</p>
</div>
)}
{preview && !isUpdateCurrent(preview) && (
<div className="mt-5 border-t border-line pt-4">
<p className="font-medium">
{preview.from_version ? t("upd.availableFrom", { to: preview.to_version, from: preview.from_version }) : t("upd.available", { to: preview.to_version })}
</p>
{preview.latest_version && <p className="mt-1 text-sm text-warn" role="status">{t("upd.intermediate", { to: preview.to_version, latest: preview.latest_version })}</p>}
<p className="mt-1 text-sm text-muted">
{!preview.database_check_error && (preview.pending_migrations ?? preview.migrations) > 0
? t("upd.summaryDb", { size: mb(preview.download_bytes), files: preview.items.filter((i) => i.action !== "skip").length, db: preview.pending_migrations ?? preview.migrations })
: t("upd.summary", { size: mb(preview.download_bytes), files: preview.items.filter((i) => i.action !== "skip").length })}
</p>
<details className="mt-3" open={preview.items.some(i => i.action === "conflict")}><summary className="cursor-pointer text-sm text-muted">{t("history.files")}</summary><ul className="mt-3 max-h-56 divide-y divide-line overflow-auto text-sm">
{preview.items.filter((i) => i.action !== "skip").map((i) => (
<li key={i.path} className="py-2">
<div className="flex justify-between gap-3">
<span className="selectable break-all">{i.path}</span>
<span className={i.action === "conflict" ? "shrink-0 text-warn" : "shrink-0 text-muted"}>{t(`upd.act.${i.action}` as Key)}</span>
</div>
{i.action === "conflict" && (
<fieldset className="mt-2 flex flex-wrap gap-4 text-xs text-muted">
<legend className="sr-only">{t("upd.conflict")}</legend>
<span className="text-warn">{t("upd.conflict")}</span>
{(["keep", "replace"] as const).map((c) => (
<label key={c} className="flex cursor-pointer items-center gap-1">
<input type="radio" name={i.path} checked={choices[i.path] === c} onChange={() => setChoices((x) => ({ ...x, [i.path]: c }))} />
{c === "keep" ? t("upd.keep") : t("upd.replace")}
</label>
))}
</fieldset>
)}
</li>
))}
</ul></details>
<Button className="mt-4" variant="primary" disabled={!!busy || !pendingChecked || !!pendingStateError || !!pending} onClick={() => void update()}>
{busy === "update" && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{t("upd.now")}
</Button>
<p className="mt-2 text-xs text-muted">{t("upd.stopNote")}</p>
</div>
)}
{busy === "update" && progress && (
<div className="mt-5">
<div className="flex justify-between text-sm">
<span role="status">{hasKey(`ustep.${progress.step}`) ? t(`ustep.${progress.step}` as Key) : progress.step}</span>
<span className="text-muted">{progress.percent}%</span>
</div>
<div className="mt-2 h-2 overflow-hidden rounded-full bg-white/10" role="progressbar" aria-valuenow={progress.percent} aria-valuemin={0} aria-valuemax={100}>
<div className="h-full rounded-full bg-gold transition-[width] duration-300" style={{ width: `${progress.percent}%` }} />
</div>
</div>
)}
<label className="mt-5 flex cursor-pointer items-center justify-between gap-3 border-t border-line pt-4 text-sm" title={t("upd.startAfter")}>
<span>{t("settings.startServer")}</span><input type="checkbox" role="switch" checked={startAfter} onChange={(e) => setStartAfter(e.target.checked)} className="h-4 w-4 accent-[#c9a24a]" />
</label>
</Card>
</div>
);
}
+49 -285
View File
@@ -1,291 +1,55 @@
import { useEffect, useState } from "react";
import { open } from "@tauri-apps/plugin-dialog";
import { ChevronDown, ChevronRight, Loader2 } from "lucide-react";
import { applyServerUpdate, clearServerUpdateResult, refreshServerUpdateState, useServerUpdate } from "@/lib/serverUpdate";
import { isUpdateCurrent } from "@/lib/serverUpdateStatus";
import { api, asUiError, type UiError, type UpdatePreview, type UpdateTxn } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { ClientCard } from "@/screens/ClientCard";
import { GameDataCard } from "@/screens/GameDataCard";
import { DiagnosticsCard } from "@/screens/DiagnosticsCard";
import { AboutCard } from "@/screens/AboutCard";
import { RemoveServerCard } from "@/screens/RemoveServerCard";
import { useStartAfterUpdate } from "@/lib/updatePrefs";
import { hasKey, useHuman, useI18n, type Key } from "@/i18n";
import { useState } from "react";
import { Download, Power, FolderOpen, Wrench, Languages } from "lucide-react";
import { useI18n } from "@/i18n";
import { LanguagePicker } from "@/components/LanguagePicker";
import { RealmStartupSettings } from "@/screens/RealmStartupSettings";
import { RepairCard } from "@/screens/RepairCard";
import { PublishCard } from "@/screens/PublishCard";
import { AutoRestartSettings } from "@/screens/AutoRestartSettings";
import { Card } from "@/components/ui/card";
import { useServerUpdate } from "@/lib/serverUpdate";
import { ServerUpdateCard } from "./ServerUpdateCard";
import { AboutCard } from "./AboutCard";
import { ReleaseHistory, type HistorySelection } from "./ReleaseHistory";
import { ClientCard } from "./ClientCard";
import { GameDataCard } from "./GameDataCard";
import { RealmStartupSettings } from "./RealmStartupSettings";
import { AutoRestartSettings } from "./AutoRestartSettings";
import { DiagnosticsCard } from "./DiagnosticsCard";
import { RepairCard } from "./RepairCard";
import { RemoveServerCard } from "./RemoveServerCard";
function mb(bytes: number) {
return bytes >= 1 << 20 ? `${(bytes / (1 << 20)).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`;
}
export function SettingsHome({ serverId, serverName = "", path, onForget }: { serverId: string; serverName?: string; path: string; onForget: () => Promise<void> }) {
const sections = [["updates", Download], ["startup", Power], ["client", FolderOpen], ["service", Wrench], ["interface", Languages]] as const;
export function SettingsHome({ serverId, path, onForget }: { serverId: string; serverName?: string; path: string; onForget: () => Promise<void> }) {
const { t } = useI18n();
const upd = useServerUpdate(serverId);
const human = useHuman();
const [preview, setPreview] = useState<UpdatePreview | null>(null);
const [pending, setPending] = useState<UpdateTxn | null>(null);
const [pendingChecked, setPendingChecked] = useState(false);
const [pendingStateError, setPendingStateError] = useState<UiError | null>(null);
const [localBusy, setBusy] = useState<"check" | "rollback" | "retry" | null>(null);
// an update keeps running in the background when this tab is left, so its state is the shared one
const busy = upd.applying ? "update" : localBusy;
const progress = upd.applying ? { step: upd.step ?? "Starting", percent: upd.percent } : null;
const [localError, setError] = useState<UiError | null>(null);
const error = pendingStateError ?? localError ?? upd.uiError;
const [localDone, setDone] = useState<string | null>(null);
const done = upd.result && "committed" in upd.result ? t("upd.updatedTo", { v: upd.result.committed }) : localDone;
const [choices, setChoices] = useState<Record<string, "keep" | "replace">>({});
const [advanced, setAdvanced] = useState(false);
const [source, setSource] = useState("");
const [startAfter, setStartAfter] = useStartAfterUpdate("server", serverId);
useEffect(() => {
let active = true;
setPendingChecked(false);
setPending(null);
setPreview(null);
setPendingStateError(null);
void api.pendingUpdate(serverId).then((txn) => {
if (active) { setPending(txn); setPendingChecked(true); }
}).catch((e) => { if (active) setPendingStateError(asUiError(e)); });
return () => { active = false; };
}, [serverId]);
// Every finished attempt refreshes the disk state, including failures in the background.
useEffect(() => {
if (!upd.stateRevision) return;
setPreview(null);
setPendingChecked(!upd.stateError);
setPendingStateError(upd.stateError);
if (!upd.stateError) setPending(upd.result && "pending" in upd.result ? upd.result.pending : null);
}, [upd.stateRevision, serverId]);
async function refreshPending() {
setPendingChecked(false);
try {
const txn = await refreshServerUpdateState(serverId);
setPending(txn);
setPendingStateError(null);
setPendingChecked(true);
return txn;
} catch (e) { setPendingStateError(asUiError(e)); throw e; }
const [section, setSection] = useState<(typeof sections)[number][0]>("updates");
const [attention, setAttention] = useState(false);
const update = useServerUpdate(serverId);
const [history, setHistory] = useState<HistorySelection>(() => ({ component: "server", from: update.preview?.from_version ?? undefined, to: update.available ? update.preview?.to_version : undefined }));
function showHistory(selection: HistorySelection) {
setHistory(selection);
requestAnimationFrame(() => {
const element = document.getElementById("release-history");
element?.scrollIntoView({ behavior: "smooth", block: "start" });
element?.focus({ preventScroll: true });
});
}
async function check() {
setBusy("check");
setError(null);
setDone(null);
clearServerUpdateResult(serverId);
setPreview(null);
try {
const txn = await refreshPending();
if (txn) return;
const p = await api.checkUpdate(serverId, source.trim() || undefined);
setPreview(p);
setChoices(Object.fromEntries(p.conflicts.map((c) => [c, "keep" as const])));
} catch (e) {
setError(asUiError(e));
} finally {
setBusy(null);
}
}
async function update() {
if (!pendingChecked || pendingStateError || pending) return;
setError(null);
setDone(null);
await applyServerUpdate(serverId, { choices, source: source.trim() || undefined });
}
async function rollback(txn: UpdateTxn) {
if (!window.confirm(t("upd.confirmBack"))) return;
setBusy("rollback");
setError(null);
try {
await api.rollbackUpdate(serverId, txn.id);
setPending(null);
setDone(t("upd.wentBack"));
} catch (e) {
setError(asUiError(e));
} finally {
try { await refreshPending(); } catch { /* Keep the disk-state error visible. */ }
setBusy(null);
}
}
async function retryValidation(txn: UpdateTxn) {
setBusy("retry");
setError(null);
try {
const result = await api.retryUpdateValidation(serverId, txn.id);
if (result.state === "committed") {
setPending(null);
setPreview(null);
setDone(t("upd.updatedTo", { v: result.to_version }));
clearServerUpdateResult(serverId);
} else setPending(result);
} catch (e) { setError(asUiError(e)); }
finally {
try { await refreshPending(); } catch { /* Keep the disk-state error visible. */ }
setBusy(null);
}
}
async function browse() {
const p = await open({ directory: true, multiple: false, title: t("upd.dialogTitle") });
if (typeof p === "string") setSource(p);
}
return (
<div className="max-w-2xl">
<h1 className="text-2xl font-semibold">{t("settings.title")}</h1>
<p className="mt-1 text-muted">{t("q.settings")}</p>
{pending && (
<Card className="mt-6 border-warn/40 p-5" role="alert">
<p className="font-medium text-warn">
{pending.state === "needs-decision" ? t("upd.pendingBad") : t("upd.pendingUnfinished")}
</p>
<p className="mt-1 whitespace-pre-wrap text-sm text-muted">{pending.message ?? t("upd.safeBack")}</p>
{pending.state === "needs-decision" && (
<Button className="mt-3 mr-3" size="sm" disabled={!!busy} onClick={() => void retryValidation(pending)}>
{busy === "retry" && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{t("upd.retryValidation")}
</Button>
)}
<p className="mt-1 text-sm text-muted">{t("upd.backNote")}</p>
<Button className="mt-3" size="sm" disabled={!!busy} onClick={() => void rollback(pending)}>
{busy === "rollback" && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{pending.from_version ? t("upd.goBackTo", { v: pending.from_version }) : t("upd.goBackBefore")}
</Button>
</Card>
)}
<Card className="mt-6 p-6">
<h2 className="font-semibold">{t("settings.language")}</h2>
<p className="mt-1 text-sm text-muted">{t("settings.languageHint")}</p>
<LanguagePicker className="mt-3" />
</Card>
<ClientCard serverId={serverId} />
<RealmStartupSettings serverId={serverId} />
<AutoRestartSettings serverId={serverId} />
<GameDataCard serverId={serverId} />
<DiagnosticsCard serverId={serverId} />
<RepairCard key={serverId} serverId={serverId} />
<PublishCard key={`publish-${serverId}`} serverId={serverId} serverName={serverName} />
<AboutCard />
<Card className="mt-6 p-6">
<h2 className="font-semibold">{t("upd.title")}</h2>
<p className="mt-1 text-sm text-muted">{t("upd.text")}</p>
<label className="mt-3 flex cursor-pointer items-center gap-2 text-sm">
<input type="checkbox" checked={startAfter} onChange={(e) => setStartAfter(e.target.checked)} className="h-4 w-4 accent-[#c9a24a]" />
<span>{t("upd.startAfter")}</span>
</label>
<div className="mt-4 flex items-center gap-3">
<Button variant="primary" disabled={!!busy} onClick={() => void check()}>
{busy === "check" && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{t("upd.check")}
</Button>
<button onClick={() => setAdvanced((v) => !v)} aria-expanded={advanced} className="flex cursor-pointer items-center gap-1 text-sm text-muted hover:text-ink">
{advanced ? <ChevronDown className="h-4 w-4" aria-hidden /> : <ChevronRight className="h-4 w-4" aria-hidden />}
{t("install.advanced")}
</button>
</div>
{advanced && (
<div className="mt-3 flex gap-2">
<input aria-label={t("upd.folderLabel")} value={source} onChange={(e) => setSource(e.target.value)} placeholder={t("upd.folderHint")} className="selectable flex-1 rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none focus:border-gold" />
<Button size="sm" onClick={browse}>{t("install.browse")}</Button>
</div>
)}
{done && pendingChecked && !pendingStateError && <p className="mt-4 text-sm text-ok" role="status">{done}</p>}
{error && (
<div className="mt-4" role="alert">
<p className="selectable whitespace-pre-wrap break-words text-sm text-bad">
{error.human.code === "unknown" ? error.technical : human(error.human).message}
</p>
<button className="mt-1 cursor-pointer text-xs text-muted underline" onClick={() => void navigator.clipboard.writeText(error.technical)}>
{t("common.copyError")}
</button>
</div>
)}
{preview?.database_check_error && (
<p className="selectable mt-4 break-words text-sm text-warn" role="status">{t("upd.dbUnchecked", { why: preview.database_check_error })}</p>
)}
{preview && isUpdateCurrent(preview) && (
<div className="mt-5 border-t border-line pt-4">
<p className="font-medium text-ok" role="status">{t("upd.current", { v: preview.to_version })}</p>
</div>
)}
{preview && !isUpdateCurrent(preview) && (
<div className="mt-5 border-t border-line pt-4">
<p className="font-medium">
{preview.from_version ? t("upd.availableFrom", { to: preview.to_version, from: preview.from_version }) : t("upd.available", { to: preview.to_version })}
</p>
{preview.latest_version && <p className="mt-1 text-sm text-warn" role="status">{t("upd.intermediate", { to: preview.to_version, latest: preview.latest_version })}</p>}
<p className="mt-1 text-sm text-muted">
{!preview.database_check_error && (preview.pending_migrations ?? preview.migrations) > 0
? t("upd.summaryDb", { size: mb(preview.download_bytes), files: preview.items.filter((i) => i.action !== "skip").length, db: preview.pending_migrations ?? preview.migrations })
: t("upd.summary", { size: mb(preview.download_bytes), files: preview.items.filter((i) => i.action !== "skip").length })}
</p>
<ul className="mt-3 max-h-56 divide-y divide-line overflow-auto text-sm">
{preview.items.filter((i) => i.action !== "skip").map((i) => (
<li key={i.path} className="py-2">
<div className="flex justify-between gap-3">
<span className="selectable break-all">{i.path}</span>
<span className={i.action === "conflict" ? "shrink-0 text-warn" : "shrink-0 text-muted"}>{t(`upd.act.${i.action}` as Key)}</span>
</div>
{i.action === "conflict" && (
<fieldset className="mt-2 flex flex-wrap gap-4 text-xs text-muted">
<legend className="sr-only">{t("upd.conflict")}</legend>
<span className="text-warn">{t("upd.conflict")}</span>
{(["keep", "replace"] as const).map((c) => (
<label key={c} className="flex cursor-pointer items-center gap-1">
<input type="radio" name={i.path} checked={choices[i.path] === c} onChange={() => setChoices((x) => ({ ...x, [i.path]: c }))} />
{c === "keep" ? t("upd.keep") : t("upd.replace")}
</label>
))}
</fieldset>
)}
</li>
))}
</ul>
<Button className="mt-4" variant="primary" disabled={!!busy || !pendingChecked || !!pendingStateError || !!pending} onClick={() => void update()}>
{busy === "update" && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{t("upd.now")}
</Button>
<p className="mt-2 text-xs text-muted">{t("upd.stopNote")}</p>
</div>
)}
{busy === "update" && progress && (
<div className="mt-5">
<div className="flex justify-between text-sm">
<span role="status">{hasKey(`ustep.${progress.step}`) ? t(`ustep.${progress.step}` as Key) : progress.step}</span>
<span className="text-muted">{progress.percent}%</span>
</div>
<div className="mt-2 h-2 overflow-hidden rounded-full bg-white/10" role="progressbar" aria-valuenow={progress.percent} aria-valuemin={0} aria-valuemax={100}>
<div className="h-full rounded-full bg-gold transition-[width] duration-300" style={{ width: `${progress.percent}%` }} />
</div>
</div>
)}
</Card>
<RemoveServerCard serverId={serverId} path={path} onForget={onForget} />
return <div className="mx-auto w-full max-w-5xl pb-8">
<h1 className="text-2xl font-semibold">{t("settings.title")}</h1>
<p className="mt-1 text-sm text-muted">{t("settings.organized")}</p>
<nav aria-label={t("settings.title")} className="mt-6 flex flex-wrap gap-1 border-b border-line pb-3">
{sections.map(([id, Icon]) => <button key={id} aria-current={section === id ? "page" : undefined} onClick={() => setSection(id)} className={`flex cursor-pointer items-center gap-2 rounded-md px-3 py-2 text-sm ${section === id ? "bg-gold/10 text-gold" : "text-muted hover:bg-white/5 hover:text-ink"}`}>
<Icon className="h-4 w-4" aria-hidden />{t(`settings.section.${id}`)}
</button>)}
</nav>
{attention && section !== "updates" && <button role="alert" onClick={() => setSection("updates")} className="mt-4 w-full cursor-pointer rounded-lg border border-warn/40 p-4 text-left text-sm text-warn">{t("settings.attention")}</button>}
<div hidden={section !== "updates"}>
<div className="grid items-start gap-x-5 lg:grid-cols-2">
<ServerUpdateCard onAttention={setAttention} serverId={serverId} onHistory={(from, to) => showHistory({ component: "server", from: from ?? undefined, to })} />
<AboutCard onHistory={() => showHistory({ component: "manager" })} />
</div>
<button onClick={() => setSection("client")} className="mt-5 flex w-full cursor-pointer items-center justify-between gap-3 rounded-lg border border-line px-5 py-4 text-left text-sm hover:bg-white/5"><span>{t("settings.clientLink")}</span><span aria-hidden>→</span></button>
<ReleaseHistory selection={history} onSelect={setHistory} />
</div>
);
<div hidden={section !== "startup"} className="max-w-3xl"><RealmStartupSettings serverId={serverId} /><AutoRestartSettings serverId={serverId} /></div>
<div hidden={section !== "client"} className="max-w-3xl"><ClientCard serverId={serverId} /><GameDataCard serverId={serverId} /></div>
<div hidden={section !== "service"} className="max-w-3xl"><DiagnosticsCard serverId={serverId} /><RepairCard serverId={serverId} /><RemoveServerCard serverId={serverId} path={path} onForget={onForget} /></div>
<div hidden={section !== "interface"} className="max-w-3xl"><Card className="mt-6 p-6"><h2 className="font-semibold">{t("settings.language")}</h2><p className="mt-1 text-sm text-muted">{t("settings.languageHint")}</p><LanguagePicker className="mt-4" /></Card></div>
</div>;
}
+1 -1
View File
@@ -284,8 +284,8 @@ export function SettingsPage(props: {
const q = query.trim().toLowerCase();
const searching = q !== "";
const hit = (...parts: string[]) => parts.some((x) => x.toLowerCase().includes(q));
const curatedKeys = new Set(view.settings.map((s) => s.key));
const collections = collectionsOf(cols);
const curatedKeys = new Set([...view.settings.map((s) => s.key), ...collections.map((c) => c.item.key)]);
const curatedHits = searching ? view.settings.filter((s) => hit(s.key, sx.title(s), sx.description(s))) : [];
const collectionHits = searching ? collections.filter((c) => hit(c.item.key, t(c.label), t(c.text))) : [];
const rawHits = (raw ?? []).filter(
+1 -1
View File
@@ -161,7 +161,7 @@ export function Shell(props: {
) : page === "report" ? (
<ReportPage key={server.id} serverId={server.id} />
) : page === "friends" ? (
<PlayWithFriends key={server.id} serverId={server.id} path={server.path} />
<PlayWithFriends key={server.id} serverName={server.name} serverId={server.id} path={server.path} />
) : page === "settings" ? (
<SettingsHome key={server.id} serverId={server.id} serverName={server.name} path={server.path} onForget={() => props.onForget(server.id)} />
) : page === "characters" ? (
+5
View File
@@ -15,6 +15,10 @@ const stubs = {
"@/lib/clientJob": `export const dismissClientJob=()=>{}; export const startClientUpdate=()=>{}; export const stopClientJob=()=>{}; export const syncClient=()=>{}; export const useClientJob=()=>({phase:'idle'});`,
"@/lib/clientUpdate": `export const checkClient=()=>{}; export const useClientStatus=()=>({status:null});`,
"@/lib/autoRestartPrefs": `export const useAutoRestart=()=>[false,()=>{}];`,
"@/screens/PublishCard": `export const ListingChip=()=>null;`,
"@/screens/PublishDialog": `export const PublishRealmDialog=()=>null;`,
"@/lib/registry": `export const useRegistryStatus=()=>({status:null});`,
"@/lib/publishRealms": `export const usePublishRealms=()=>[];`,
"@/components/ui/button": `import {createElement} from 'react'; export const Button=({children,disabled,onClick,className})=>createElement('button',{disabled,onClick,className},children);`,
"@/components/ui/card": `import {createElement} from 'react'; export const Card=({children,...props})=>createElement('div',props,children);`,
};
@@ -24,6 +28,7 @@ const bundle = await rolldown({
external: (id, importer) => id === "react/jsx-runtime" || id === "lucide-react" || (id === "react" && !importer?.endsWith("Overview.tsx")),
plugins: [{ name: "overview-test",
resolveId(id, importer) {
if (id === "@/components/ui/split-button") return fileURLToPath(new URL("../src/components/ui/split-button.tsx", import.meta.url));
if (id.startsWith("@/") || (id === "react" && importer?.endsWith("Overview.tsx"))) return "\0" + id;
},
load(id) {
+184
View File
@@ -0,0 +1,184 @@
"""Offline experiment only; does not install patches or infer client load order."""
import argparse
import ctypes
import hashlib
import json
from pathlib import Path
import struct
import tempfile
MEMBER = r"DBFilesClient\ChrRaces.dbc"
STOCK = {1, 2, 3, 4, 5, 6, 7, 8, 10, 11}
LAYOUT = (69, 276)
ALGORITHM_VERSION = 1
NAME_FIELDS = (*range(14, 30), *range(31, 47), *range(48, 64))
def read_dbc(data):
if len(data) < 20:
raise ValueError("Truncated DBC header")
magic, count, fields, size, strings_size = struct.unpack_from("<4sIIII", data)
if magic != b"WDBC" or (fields, size) != LAYOUT or not count:
raise ValueError("Unsupported ChrRaces layout")
strings_start = 20 + count * size
if strings_start + strings_size != len(data) or not strings_size:
raise ValueError("Invalid DBC bounds")
strings = data[strings_start:]
if strings[-1] != 0:
raise ValueError("Invalid string block")
rows = {}
for index in range(count):
offset = 20 + index * size
race, flags = struct.unpack_from("<II", data, offset)
if not 0 < race <= 255 or race in rows:
raise ValueError("Invalid or duplicate RaceID")
names = {}
for field in NAME_FIELDS:
name_offset = struct.unpack_from("<I", data, offset + field * 4)[0]
if name_offset >= strings_size:
raise ValueError("Invalid race name offset")
names[field] = strings[name_offset:].split(b"\0", 1)[0].decode("utf-8", errors="strict")
name = names[14]
rows[race] = {"offset": offset, "flags": flags, "name": name}
return rows
def patch_dbc(original, disabled):
rows = read_dbc(original)
disabled = set(disabled)
if disabled & STOCK or not disabled <= rows.keys():
raise ValueError("Only known custom RaceIDs can be disabled")
result = bytearray(original)
for race in disabled:
row = rows[race]
struct.pack_into("<I", result, row["offset"] + 4, row["flags"] | 1)
verified = read_dbc(result)
restored = bytearray(result)
for race in disabled:
row = rows[race]
if verified[race]["flags"] != row["flags"] | 1:
raise ValueError("Flags verification failed")
struct.pack_into("<I", restored, row["offset"] + 4, row["flags"])
if restored != original:
raise ValueError("Unexpected byte changes")
return bytes(result)
def fingerprint(original, disabled, profile):
inputs = {"sourceDbcSha256": hashlib.sha256(original).hexdigest(),
"disabledRaceIds": sorted(set(disabled)), "algorithmVersion": ALGORITHM_VERSION,
"profile": profile}
return hashlib.sha256(json.dumps(inputs, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
class Storm:
def __init__(self, library):
self.api = ctypes.WinDLL(str(library), use_last_error=True)
handle = ctypes.c_void_p
word = ctypes.c_uint32
signatures = {
"SFileOpenArchive": [ctypes.c_wchar_p, word, word, ctypes.POINTER(handle)],
"SFileCloseArchive": [handle],
"SFileExtractFile": [handle, ctypes.c_char_p, ctypes.c_wchar_p, word],
"SFileCreateArchive": [ctypes.c_wchar_p, word, word, ctypes.POINTER(handle)],
"SFileAddFileEx": [handle, ctypes.c_wchar_p, ctypes.c_char_p, word, word, word],
}
for name, arguments in signatures.items():
function = getattr(self.api, name)
function.argtypes = arguments
function.restype = ctypes.c_int
def check(self, name, *args):
if not getattr(self.api, name)(*args):
raise OSError(ctypes.get_last_error(), name)
def extract(self, archive, member, destination):
handle = ctypes.c_void_p()
self.check("SFileOpenArchive", str(archive), 0, 0x100, ctypes.byref(handle))
try:
self.check("SFileExtractFile", handle, member.encode("ascii"),
str(destination), 0)
finally:
self.check("SFileCloseArchive", handle)
def create(self, archive, source):
handle = ctypes.c_void_p()
self.check("SFileCreateArchive", str(archive), 0, 4, ctypes.byref(handle))
try:
self.check("SFileAddFileEx", handle, str(source), MEMBER.encode("ascii"),
0x01000000, 0, 0)
finally:
self.check("SFileCloseArchive", handle)
def generate_experiment(storm, source_mpq, output, disabled, profile="unverified"):
source_mpq = Path(source_mpq).resolve(strict=True)
output = Path(output).absolute()
if output.exists():
raise FileExistsError(output)
output.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix=".race-experiment-", dir=output.parent) as temp:
staging = Path(temp) / "result"
staging.mkdir()
report = build_experiment(storm, source_mpq, staging, disabled, profile)
staging.rename(output)
return report
def build_experiment(storm, source_mpq, output, disabled, profile):
with source_mpq.open("rb") as source:
source_sha = hashlib.file_digest(source, "sha256").hexdigest()
original_path = output / "original.dbc"
storm.extract(source_mpq, MEMBER, original_path)
original = original_path.read_bytes()
rows = read_dbc(original)
generated = patch_dbc(original, disabled)
generated_path = output / "generated.dbc"
generated_path.write_bytes(generated)
overlay = output / "experiment.MPQ"
storm.create(overlay, generated_path)
with tempfile.TemporaryDirectory() as temp:
extracted = Path(temp) / "roundtrip.dbc"
storm.extract(overlay, MEMBER, extracted)
if extracted.read_bytes() != generated:
raise ValueError("MPQ extraction does not match generated DBC")
report = {
"sourceMpq": str(source_mpq), "sourceMpqSha256": source_sha,
"algorithmVersion": ALGORITHM_VERSION, "profile": profile,
"fingerprint": fingerprint(original, disabled, profile),
"sourceDbcSha256": hashlib.sha256(original).hexdigest(),
"generatedDbcSha256": hashlib.sha256(generated).hexdigest(),
"disabled": [{"id": race, "name": rows[race]["name"],
"oldFlags": rows[race]["flags"], "newFlags": rows[race]["flags"] | 1}
for race in sorted(set(disabled))],
"catalog": [{"id": race, "name": row["name"], "flags": row["flags"]}
for race, row in sorted(rows.items())],
"dbcValidation": "PASS", "onlyRequestedBitChanged": "PASS", "mpqRoundtrip": "PASS",
"effectiveSourceInRunningClient": "UNVERIFIED", "overlayPriority": "UNVERIFIED",
"creationMenu": "NOT RUN", "otherRaceCreation": "NOT RUN",
"existingCharacterLogin": "NOT RUN", "rollbackInGame": "NOT RUN",
"verdict": "PARTIAL",
}
with source_mpq.open("rb") as source:
if hashlib.file_digest(source, "sha256").hexdigest() != source_sha:
raise ValueError("Source archive changed during the experiment")
(output / "report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
return report
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--storm", type=Path, required=True)
parser.add_argument("--source-mpq", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--disable", type=int, nargs="*", required=True)
parser.add_argument("--profile", default="unverified", help="Recorded input; not a support declaration")
args = parser.parse_args()
report = generate_experiment(Storm(args.storm), args.source_mpq, args.output, args.disable, args.profile)
print(json.dumps({key: value for key, value in report.items() if key != "catalog"}, indent=2))
if __name__ == "__main__":
main()
+59
View File
@@ -0,0 +1,59 @@
"""Version-pinned offline experiment; never installs files or launches the game."""
import hashlib
SOURCE_SHA256 = "8816ef9b6839652db60da6de7d2a6d09ceed1f80323ca5c8e55271a4d5aacac3"
PROBE_IDS = {82, 83, 97}
def build_probe(source, disabled):
if hashlib.sha256(source).hexdigest() != SOURCE_SHA256:
raise ValueError("Unsupported CharacterCreate.lua fingerprint")
disabled = set(disabled)
if not disabled <= PROBE_IDS:
raise ValueError("This experiment supports only previously verified probe RaceIDs")
text = source.decode("utf-8").replace("\r", "")
prefix = "local CoaManagedDisabled = {" + ",".join(f"[{race}]=true" for race in sorted(disabled)) + "}\n"
prefix += """local function CoaManagedRaceDisabled(raceId)
return raceId ~= nil and CoaManagedDisabled[raceId] == true
end
local function CoaManagedDisabledLabel()
local labels = {
enUS = "Disabled by server", enGB = "Disabled by server",
ruRU = "Отключено сервером", deDE = "Vom Server deaktiviert",
frFR = "Désactivé par le serveur", esES = "Desactivada por el servidor",
esMX = "Desactivada por el servidor", zhCN = "服务器已禁用"
}
return labels[GetLocale and GetLocale() or "enUS"] or labels.enUS
end
"""
replacements = [
('local hide = hidden["#"..i] or hidden[name] or hidden[strlower(name or "")]',
'local hide = CoaManagedRaceDisabled(button.bonusRaceID) or hidden["#"..i] or hidden[name] or hidden[strlower(name or "")]'),
('\t\t\t\tbutton.coaUserHidden = nil\n\t\t\t\tbutton:Show()\n',
'\t\t\t\tbutton.coaUserHidden = CoaManagedRaceDisabled(button.bonusRaceID) or nil\n'
'\t\t\t\tif not button.coaUserHidden then button:Show() else button:Hide() end\n'),
("tinsert(rows, { id = i, raceID = raceID, name = name, faction = (ok and faction) or 'Alliance' })",
"tinsert(rows, { id = i, raceID = raceID, policyRaceID = button.bonusRaceID, name = name, faction = (ok and faction) or 'Alliance' })"),
('if not f.draft or not self.raceName then',
'if self.coaServerDisabled or not f.draft or not self.raceName then'),
("\t\t\t\trow.label:SetText((info.faction == 'Horde' and '|cffff2020' or '|cff00a0ff')..info.name..' |cffaaa37a(ID '..info.raceID..')|r')\n"
"\t\t\t\tlocal hidden = f.draft and (f.draft['#'..info.id] or f.draft[info.name] or f.draft[strlower(info.name)])\n"
"\t\t\t\trow:SetChecked(not hidden)",
""" row.coaServerDisabled = CoaManagedRaceDisabled(info.policyRaceID)
local hidden = f.draft and (f.draft['#'..info.id] or f.draft[info.name] or f.draft[strlower(info.name)])
if row.coaServerDisabled then
row.label:SetText('|cff808080'..info.name..' (ID '..info.raceID..') - '..CoaManagedDisabledLabel()..'|r')
row:Disable()
else
row.label:SetText((info.faction == 'Horde' and '|cffff2020' or '|cff00a0ff')..info.name..' |cffaaa37a(ID '..info.raceID..')|r')
row:Enable()
end
row:SetChecked(not row.coaServerDisabled and not hidden)"""),
]
for old, new in replacements:
if text.count(old) != 1:
raise ValueError("Expected exactly one known Lua integration point")
text = text.replace(old, new)
return (prefix + text).encode("utf-8")
+27
View File
@@ -0,0 +1,27 @@
import assert from "node:assert/strict";
import test from "node:test";
import { readFileSync } from "node:fs";
import { releasesForUpdate, localizeNotes } from "../src/lib/releaseHistoryModel.ts";
const release = (version, prerelease = false) => ({ version, prerelease, notes: [], tag: version, date: "2026-10-28" });
test("intermediate update shows only versions actually being installed", () => {
const records = [release("0.9.0"), release("0.10.0"), release("0.11.0"), release("0.10.1", true)];
assert.deepEqual(releasesForUpdate(records, "0.9.0", "0.10.0").map(r => r.version), ["0.10.0"]);
assert.deepEqual(releasesForUpdate(records, "0.9.0", "0.11.0").map(r => r.version), ["0.10.0", "0.11.0"]);
assert.deepEqual(releasesForUpdate(records, "custom", "0.10.0").map(r => r.version), ["0.10.0"]);
assert.deepEqual(releasesForUpdate(records, "0.10.0", "0.10.0"), []);
});
test("a changed or partly translated record falls back as a whole", () => {
assert.deepEqual(localizeNotes(["Changed", "New"], { Changed: "Переведено" }), { notes: ["Changed", "New"], fallback: true });
});
test("latest published Manager and server records have complete translations in five languages", () => {
const translations = JSON.parse(readFileSync(new URL("../src/data/latest-note-translations.json", import.meta.url)));
for (const component of ["server", "manager"]) {
const path = component === "server" ? "../src/data/server-history.json" : "../changelog/history.json";
const history = JSON.parse(readFileSync(new URL(path, import.meta.url)));
const latest = history.releases.at(-1);
for (const locale of ["ru", "de", "fr", "es", "zh"]) {
assert.equal(localizeNotes(latest.notes, translations[component][locale]).fallback, false, `${component}/${locale}`);
}
}
});
+13
View File
@@ -52,6 +52,19 @@ test("refresh after recovery returns the latest disk state, then its absence", a
assert.equal(await refreshServerUpdateState("recovery-case"), null);
});
test("successful update keeps the existing-character warning across disk refresh", async () => {
const original = globalThis.__hotfixApi.applyUpdate;
try {
applyFailure = false;
stateFailure = false;
pending = null;
globalThis.__hotfixApi.applyUpdate = async () => ({ txn: { state: "committed", to_version: "2" }, preexisting_character_count: 174 });
assert.equal(await applyServerUpdate("old-character-warnings", { choices: {} }), true);
await refreshServerUpdateState("old-character-warnings");
assert.deepEqual(useServerUpdate("old-character-warnings").result, { committed: "2", preexistingCharacters: 174 });
} finally { globalThis.__hotfixApi.applyUpdate = original; }
});
test("a stopped server is left stopped after a successful update by default", async () => {
calls.length = 0;
serverRunning = false;
+171
View File
@@ -0,0 +1,171 @@
import pathlib
import runpy
import sys
import tempfile
import unittest
import time
from unittest.mock import patch
BRIDGE = pathlib.Path(__file__).resolve().parents[1] / 'crates/coa-core/src/launcher_bridge.py'
class LauncherBridgeTests(unittest.TestCase):
def launch(self, action, body):
with tempfile.TemporaryDirectory() as directory:
script = pathlib.Path(directory) / 'Scripts/manage.py'
script.parent.mkdir()
script.write_text(body, encoding='utf8')
original = runpy.run_path
def capture(*args, **kwargs):
self.launcher = original(*args, **kwargs)
return self.launcher
with patch.object(sys, 'argv', ['bridge', str(script), action]), patch.object(runpy, 'run_path', side_effect=capture):
return original(str(BRIDGE))
def shutdown_fixture(self, *, console_error='RuntimeError', stopped=True, foreign=False, same=True, modern=False, terminate_error=False):
return f'''
from pathlib import Path
from contextlib import nullcontext
calls = []
world = {{'pid': 123, 'created': 456, 'exe': str(Path(__file__).resolve().parents[1] / {'"foreign.exe"' if foreign else '"Core/worldserver.exe"'})}}
def wait_ready(*args): pass
def start_mysql(): raise AssertionError('must not start')
def main(): raise AssertionError('must not prepare')
def settings(): return {{}}
def control_lock(): return nullcontext()
def process(name): return world if name == 'world' else None
def same_process(record): return {same!r}
def ra(command, config):
calls.append('console')
{'raise '+console_error+'("Start this repack worldserver first")' if console_error else 'return "Graceful shutdown"'}
def terminate(record):
assert record is world
calls.append('terminate')
{'raise RuntimeError("identity changed")' if terminate_error else 'pass'}
def wait_stopped(record, seconds):
assert record is world
calls.append('wait')
return {stopped!r}
def stop_all(config):
record = process('world')
if record:
if {modern!r}:
try: ra('server shutdown 1s 0', config)
except (OSError, RuntimeError): terminate(record)
else:
ra('server shutdown 1s 0', config)
if not wait_stopped(record, 60): raise RuntimeError('world still alive')
calls.append('mysql-shutdown')
'''
def test_unavailable_console_in_restored_legacy_launcher_stops_owned_world_before_mysql(self):
for error in ['RuntimeError', 'OSError']:
with self.subTest(error=error):
result = self.launch('stop-all', self.shutdown_fixture(console_error=error))
self.assertEqual(result['launcher']['calls'], ['console', 'terminate', 'wait', 'wait', 'mysql-shutdown'])
def test_healthy_console_keeps_graceful_shutdown(self):
result = self.launch('stop-all', self.shutdown_fixture(console_error=None))
self.assertEqual(result['launcher']['calls'], ['console', 'wait', 'mysql-shutdown'])
def test_foreign_or_reused_process_is_never_terminated_even_by_a_modern_launcher_catch(self):
for modern in [False, True]:
for identity in [{'foreign': True}, {'same': False}]:
with self.subTest(modern=modern, **identity):
with self.assertRaisesRegex(Exception, 'ownership could not be verified'):
self.launch('stop-all', self.shutdown_fixture(modern=modern, **identity))
self.assertEqual(self.launcher['calls'], ['console'])
def test_world_that_stays_alive_blocks_database_shutdown(self):
for modern in [False, True]:
with self.subTest(modern=modern):
with self.assertRaisesRegex(Exception, 'database was left running'):
self.launch('stop-all', self.shutdown_fixture(stopped=False, modern=modern))
self.assertEqual(self.launcher['calls'], ['console', 'terminate', 'wait'])
def test_termination_identity_failure_leaves_mysql_untouched(self):
for modern in [False, True]:
with self.subTest(modern=modern):
with self.assertRaisesRegex(Exception, 'could not be stopped safely'):
self.launch('stop-all', self.shutdown_fixture(terminate_error=True, modern=modern))
self.assertEqual(self.launcher['calls'], ['console', 'terminate'])
def test_slow_mysql_gets_time_to_finish_but_other_waits_are_unchanged(self):
result = self.launch('start-mysql', '''
calls = []
def wait_ready(name, port, seconds=180):
calls.append((name, seconds))
if name == 'mysql' and seconds < 162:
raise RuntimeError('mysql is still starting')
def start_mysql():
wait_ready('mysql', 12345, 60)
def main():
start_mysql()
wait_ready('world', 23456, 180)
wait_ready('mysql', 12345, 900)
''')
calls = result['launcher']['calls']
self.assertEqual(calls[0], ('mysql', 300))
self.assertEqual(calls[2], ('mysql', 900))
self.assertEqual(calls[1][0], 'world')
self.assertAlmostEqual(calls[1][1], 1500, delta=1)
def world_start(self, *, game_at=420, console_at=480, dies_at=None, requested=180):
clock = [0.0]
def sleep(seconds): clock[0] += seconds
body = f'''
import time
calls = []
dies_at = {dies_at!r}
def wait_ready(name, port, seconds=180):
until = time.monotonic() + seconds
while time.monotonic() < until:
if dies_at is not None and time.monotonic() >= dies_at:
raise RuntimeError('world stopped during startup')
if time.monotonic() >= ({game_at!r} if port == 1 else {console_at!r}):
calls.append(port)
return
time.sleep(0.5)
raise RuntimeError('world is still starting')
def start_mysql(): pass
def main():
wait_ready('world', 1, {requested})
wait_ready('world', 2, {requested})
'''
with patch('time.monotonic', side_effect=lambda: clock[0]), patch('time.sleep', side_effect=sleep):
result = self.launch('start-all', body)
return clock[0], result['launcher']['calls']
def test_legacy_coa_world_waits_for_both_ports_after_three_minutes(self):
elapsed, calls = self.world_start()
self.assertEqual((elapsed, calls), (480, [1, 2]))
def test_console_wait_shares_the_world_deadline(self):
with self.assertRaisesRegex(RuntimeError, 'still starting'):
self.world_start(game_at=1490, console_at=1510)
self.assertEqual(self.launcher['calls'], [1])
def test_world_exit_is_reported_without_waiting_out_the_extended_budget(self):
with self.assertRaisesRegex(RuntimeError, 'stopped during startup'):
self.world_start(dies_at=12)
self.assertEqual(self.launcher['calls'], [])
def test_existing_longer_world_timeout_is_preserved(self):
self.assertEqual(self.world_start(game_at=1600, console_at=1700, requested=1800), (1700, [1, 2]))
def test_stop_dispatch_does_not_prepare_or_start_anything(self):
result = self.launch('stop-all', '''
from contextlib import nullcontext
calls = []
def wait_ready(*args): raise AssertionError('must not wait')
def start_mysql(): raise AssertionError('must not start')
def main(): raise AssertionError('must not prepare')
def settings(): return {'mysqlPort': 12345}
def control_lock(): return nullcontext()
def stop_all(config): calls.append(config['mysqlPort'])
''')
self.assertEqual(result['launcher']['calls'], [12345])
if __name__ == '__main__':
unittest.main()
+108
View File
@@ -0,0 +1,108 @@
"""Synthetic MPQ roundtrips using an explicitly selected local Unicode StormLib DLL."""
import hashlib
import os
from pathlib import Path
import struct
import tempfile
import unittest
from unittest.mock import patch
from race_availability_poc import Storm, generate_experiment, patch_dbc
from test_race_availability_poc import fixture
@unittest.skipUnless(os.environ.get("COA_TEST_STORMLIB"), "Set COA_TEST_STORMLIB to a Unicode StormLib DLL")
class MpqExperimentTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name)
self.storm = Storm(Path(os.environ["COA_TEST_STORMLIB"]))
self.original = fixture(ids=(1, *range(12, 62)))
source_dbc = self.root / "source.dbc"
source_dbc.write_bytes(self.original)
self.source_mpq = self.root / "source.MPQ"
self.storm.create(self.source_mpq, source_dbc)
self.source_bytes = self.source_mpq.read_bytes()
self.output = self.root / "output"
def test_one_and_fifty_races_still_one_archive_with_one_game_file(self):
for count in [1, 50]:
with self.subTest(count=count):
output = self.root / f"output-{count}"
disabled = list(range(12, 12 + count))
report = generate_experiment(self.storm, self.source_mpq, output, disabled)
archives = list(output.glob("*.MPQ"))
self.assertEqual(len(archives), 1)
header = struct.unpack_from("<4sIIHHIIII", archives[0].read_bytes())
self.assertEqual(header[0], b"MPQ\x1a")
self.assertEqual(header[-1], 2)
listfile = self.root / f"listfile-{count}.txt"
self.storm.extract(archives[0], "(listfile)", listfile)
self.assertEqual(listfile.read_text().splitlines(), [r"DBFilesClient\ChrRaces.dbc"])
self.assertEqual((output / "generated.dbc").read_bytes(), patch_dbc(self.original, disabled))
self.assertEqual(report["mpqRoundtrip"], "PASS")
self.assertEqual(report["creationMenu"], "NOT RUN")
self.assertEqual(self.source_mpq.read_bytes(), self.source_bytes)
def test_regeneration_has_identical_dbc_and_fingerprint(self):
first = generate_experiment(self.storm, self.source_mpq, self.output, [12, 15])
other = self.root / "other"
second = generate_experiment(self.storm, self.source_mpq, other, [15, 12, 12])
self.assertEqual(first["fingerprint"], second["fingerprint"])
self.assertEqual((self.output / "generated.dbc").read_bytes(), (other / "generated.dbc").read_bytes())
def test_existing_output_and_user_files_not_overwritten(self):
self.output.mkdir()
user_file = self.output / "experiment.MPQ"
user_file.write_bytes(b"user archive")
with self.assertRaises(FileExistsError):
generate_experiment(self.storm, self.source_mpq, self.output, [12])
self.assertEqual(user_file.read_bytes(), b"user archive")
self.assertEqual(self.source_mpq.read_bytes(), self.source_bytes)
def test_failed_packaging_does_not_publish_output(self):
with patch.object(self.storm, "create", side_effect=OSError("synthetic packaging failure")):
with self.assertRaises(OSError):
generate_experiment(self.storm, self.source_mpq, self.output, [12])
self.assertFalse(self.output.exists())
self.assertEqual(self.source_mpq.read_bytes(), self.source_bytes)
self.assertEqual(list(self.root.glob(".race-experiment-*")), [])
def test_unreadable_archive_does_not_publish_output(self):
broken = self.root / "broken.MPQ"
broken.write_bytes(b"not an archive")
with self.assertRaises(OSError):
generate_experiment(self.storm, broken, self.output, [12])
self.assertFalse(self.output.exists())
self.assertEqual(broken.read_bytes(), b"not an archive")
def test_invalid_race_does_not_publish_output(self):
with self.assertRaises(ValueError):
generate_experiment(self.storm, self.source_mpq, self.output, [255])
self.assertFalse(self.output.exists())
def test_empty_selection_preserves_original_bytes(self):
report = generate_experiment(self.storm, self.source_mpq, self.output, [])
self.assertEqual((self.output / "generated.dbc").read_bytes(), self.original)
self.assertEqual(report["sourceMpqSha256"], hashlib.sha256(self.source_bytes).hexdigest())
self.assertEqual(report["disabled"], [])
def test_failed_roundtrip_does_not_publish_output(self):
extract = self.storm.extract
def corrupt_roundtrip(archive, member, destination):
extract(archive, member, destination)
if archive.name == "experiment.MPQ":
destination.write_bytes(b"incorrect extracted bytes")
with patch.object(self.storm, "extract", side_effect=corrupt_roundtrip):
with self.assertRaisesRegex(ValueError, "MPQ extraction"):
generate_experiment(self.storm, self.source_mpq, self.output, [12])
self.assertFalse(self.output.exists())
self.assertEqual(self.source_mpq.read_bytes(), self.source_bytes)
if __name__ == "__main__":
unittest.main()
+113
View File
@@ -0,0 +1,113 @@
import struct
import unittest
from race_availability_poc import NAME_FIELDS, STOCK, fingerprint, patch_dbc, read_dbc
def fixture(ids=(1, 82, 83, 97), flags=0x8C):
rows = bytearray()
for race in ids:
row = bytearray(276)
struct.pack_into("<II", row, 0, race, flags)
struct.pack_into("<I", row, 14 * 4, 1)
rows.extend(row)
strings = b"\0Synthetic race\0"
return struct.pack("<4sIIII", b"WDBC", len(ids), 69, 276, len(strings)) + rows + strings
class DbcExperimentTests(unittest.TestCase):
def test_only_requested_bit_changes(self):
original = fixture()
generated = patch_dbc(original, [82, 97])
self.assertEqual([i for i, pair in enumerate(zip(original, generated)) if pair[0] != pair[1]],
[20 + 276 + 4, 20 + 3 * 276 + 4])
self.assertEqual(read_dbc(generated)[82]["flags"], 0x8D)
def test_empty_set_preserves_original(self):
self.assertEqual(patch_dbc(fixture(), []), fixture())
def test_duplicates_and_order_normalized(self):
self.assertEqual(patch_dbc(fixture(), [97, 82, 82]), patch_dbc(fixture(), [82, 97]))
def test_already_disabled_idempotent(self):
original = fixture(flags=0x8D)
self.assertEqual(patch_dbc(original, [82]), original)
def test_each_generation_uses_original(self):
original = fixture()
patch_dbc(original, [82])
self.assertEqual(read_dbc(patch_dbc(original, [97]))[82]["flags"], 0x8C)
def test_unknown_or_stock_rejected(self):
for race in [0, 42, 256, -1, *sorted(STOCK)]:
with self.subTest(race=race), self.assertRaises(ValueError):
patch_dbc(fixture(), [race])
def test_bad_headers_rejected(self):
for data in [b"", fixture()[:19], b"WDB2" + fixture()[4:], fixture(ids=()),
fixture()[:-1], fixture() + b"x", fixture(ids=(82, 82))]:
with self.subTest(data=data[:20]), self.assertRaises(ValueError):
read_dbc(data)
def test_unrecognized_layout_rejected(self):
for offset, value in [(8, 68), (12, 272), (16, 0), (4, 0xFFFFFFFF)]:
data = bytearray(fixture())
struct.pack_into("<I", data, offset, value)
with self.subTest(offset=offset), self.assertRaises(ValueError):
read_dbc(data)
def test_bad_string_offset_rejected(self):
for field in NAME_FIELDS:
data = bytearray(fixture())
struct.pack_into("<I", data, 20 + field * 4, 99999)
with self.subTest(field=field), self.assertRaises(ValueError):
read_dbc(data)
def test_nonempty_first_string_supported(self):
data = bytearray(fixture())
data[20 + 4 * 276] = ord("x")
self.assertEqual(len(read_dbc(data)), 4)
def test_reenable_restores_original_flags_including_original_bit(self):
for flags in [0, 1, 12, 13, 0xFFFFFFFF]:
original = fixture(flags=flags)
patch_dbc(original, [82])
self.assertEqual(patch_dbc(original, []), original)
def test_one_five_and_fifty_races(self):
original = fixture(ids=(1, *range(12, 62)))
for count in [1, 5, 50]:
disabled = set(range(12, 12 + count))
generated = patch_dbc(original, disabled)
original_rows, generated_rows = read_dbc(original), read_dbc(generated)
self.assertEqual({race for race in original_rows
if original_rows[race]["flags"] != generated_rows[race]["flags"]}, disabled)
def test_invalid_id_in_table(self):
for race in [0, 256, 0xFFFFFFFF]:
with self.subTest(race=race), self.assertRaises(ValueError):
read_dbc(fixture(ids=(race,)))
def test_string_block_must_terminate(self):
with self.assertRaises(ValueError):
read_dbc(fixture()[:-1] + b"x")
def test_invalid_utf8_in_localized_name(self):
data = bytearray(fixture())
data[20 + 4 * 276 + 1] = 0xFF
with self.assertRaises(ValueError):
read_dbc(data)
def test_fingerprint_normalizes_order_and_duplicates(self):
self.assertEqual(fingerprint(fixture(), [97, 82, 82], "test"),
fingerprint(fixture(), [82, 97], "test"))
def test_fingerprint_changes_with_every_input(self):
baseline = fingerprint(fixture(), [82], "test")
self.assertNotEqual(baseline, fingerprint(fixture(flags=0), [82], "test"))
self.assertNotEqual(baseline, fingerprint(fixture(), [97], "test"))
self.assertNotEqual(baseline, fingerprint(fixture(), [82], "other-profile"))
if __name__ == "__main__":
unittest.main()
+157
View File
@@ -0,0 +1,157 @@
import importlib.util
import os
from pathlib import Path
import unittest
from race_visibility_lua_poc import build_probe
@unittest.skipUnless(os.environ.get("COA_TEST_CHARACTER_CREATE_LUA") and importlib.util.find_spec("lupa"),
"Requires an explicitly selected extracted Lua and installed Lua 5.1 runtime")
class ManagedFilterProbeTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
from lupa.lua51 import LuaRuntime
cls.runtime_type = LuaRuntime
cls.source = Path(os.environ["COA_TEST_CHARACTER_CREATE_LUA"]).read_bytes()
cls.generated = build_probe(cls.source, [82, 83, 97]).decode()
cls.prefix = cls.generated[:cls.generated.index("CHAR_CREATE_HELP_NEXT_BUTTON")]
def rows(self, race=82, personal=False, locale="enUS"):
lua = self.runtime_type(unpack_returned_tuples=True)
lua.execute("""
F = {offset=0, entries={}, draft={}, rows={}}
strlower = string.lower
function makeRow()
local row={label={}}
row.label.SetText=function(self,value) self.text=value end
row.SetChecked=function(self,value) self.checked=value end
row.Disable=function(self) self.enabled=false end
row.Enable=function(self) self.enabled=true end
row.Show=function(self) self.visible=true end
row.Hide=function(self) self.visible=false end
return row
end
F.rows[1]=makeRow()
""")
lua.globals().GetLocale = lambda: locale
entry = lua.table_from({"id": 2, "raceID": race, "policyRaceID": race, "name": "Synthetic", "faction": "Alliance"})
lua.globals().F.entries[1] = entry
if personal:
lua.globals().F.draft.Synthetic = True
start = self.generated.index("function CharacterCreate_RefreshRaceFilterRows()")
end = self.generated.index("function CharacterCreate_ToggleRaceFilter()", start)
lua.execute(self.prefix + "\nlocal filter=F; local VISIBLE=1; local UpdateScrollBar=function() end\n"
+ self.generated[start:end])
lua.globals().CharacterCreate_RefreshRaceFilterRows()
return lua
def test_entire_generated_source_compiles_in_lua51(self):
self.runtime_type().execute("assert(loadstring(...))", self.generated)
def test_disabled_row_unchecked_disabled_and_labelled(self):
for race in [82, 83, 97]:
with self.subTest(race=race):
lua = self.rows(race)
row = lua.globals().F.rows[1]
self.assertFalse(row.checked)
self.assertFalse(row.enabled)
self.assertIn("Disabled by server", row.label.text)
self.assertTrue(row.label.text.startswith("|cff808080"))
def test_allowed_row_retains_personal_preference(self):
for personal in [False, True]:
with self.subTest(personal=personal):
row = self.rows(13, personal).globals().F.rows[1]
self.assertTrue(row.enabled)
self.assertEqual(bool(row.checked), not personal)
def test_recycled_scroll_row_is_reenabled(self):
lua = self.rows()
lua.globals().F.entries[1].policyRaceID = 13
lua.globals().F.entries[1].raceID = 13
lua.globals().CharacterCreate_RefreshRaceFilterRows()
self.assertTrue(lua.globals().F.rows[1].enabled)
self.assertTrue(lua.globals().F.rows[1].checked)
def test_unknown_identity_never_treated_as_button_index(self):
lua = self.rows()
lua.globals().F.entries[1].policyRaceID = None
lua.globals().F.entries[1].id = 82
lua.globals().CharacterCreate_RefreshRaceFilterRows()
self.assertTrue(lua.globals().F.rows[1].enabled)
def test_check_all_cannot_remove_managed_restriction(self):
lua = self.rows(82, True)
start = self.generated.index("local function SetAllChecked(checked)")
end = self.generated.index("local save = MakeGlueButton", start)
check_all = lua.execute(self.prefix + "\nlocal f=F;\n" + self.generated[start:end] + "\nreturn SetAllChecked")
check_all(True)
self.assertFalse(lua.globals().F.rows[1].checked)
self.assertFalse(lua.globals().F.rows[1].enabled)
self.assertIsNone(lua.globals().F.draft.Synthetic)
def test_disabled_click_callback_does_not_mutate_draft(self):
lua = self.rows(82, True)
start = self.generated.index("row:SetScript('OnClick', function(self)") + len("row:SetScript('OnClick', function(self)")
end = self.generated.index("\n\t\t\tend)", start)
callback = lua.execute("local f=F; return function(self)" + self.generated[start:end] + "\nend")
row = lua.globals().F.rows[1]
row.raceName = "Synthetic"
callback(row)
self.assertTrue(lua.globals().F.draft.Synthetic)
def test_six_languages(self):
for locale, label in [("enUS", "Disabled by server"), ("ruRU", "Отключено сервером"),
("deDE", "Vom Server deaktiviert"), ("frFR", "Désactivé par le serveur"),
("esES", "Desactivada por el servidor"), ("zhCN", "服务器已禁用")]:
with self.subTest(locale=locale):
self.assertIn(label, self.rows(locale=locale).globals().F.rows[1].label.text)
def test_layout_fallback_never_reveals_managed_race(self):
lua = self.runtime_type()
lua.execute("""
strlower=string.lower
CharacterCreate_GetHiddenRaceSet=function() return {['#1']=true,['#2']=true} end
GetFactionForRace=function() return '', 'Alliance' end
function makeButton(i,race)
local b={bonusRaceID=race,Text={GetText=function() return 'Synthetic' end}}
b.Hide=function(self) self.visible=false end
b.Show=function(self) self.visible=true end
b.SetScale=function() end; b.ClearAllPoints=function() end
b.SetPoint=function() end; b.SetFaction=function() end
_G['CharCreateRaceButton'..i]=b
end
makeButton(1,1); makeButton(2,82)
""")
start = self.generated.index("function CharacterCreate_LayoutRaceButtons(")
end = self.generated.index("MAX_CLASSES_PER_RACE =", start)
lua.execute(self.prefix + self.generated[start:end])
lua.globals().CharacterCreate_LayoutRaceButtons(2)
self.assertTrue(lua.globals().CharCreateRaceButton1.visible)
self.assertFalse(lua.globals().CharCreateRaceButton2.visible)
def test_lifting_restriction_keeps_previous_personal_choice(self):
for personal in [False, True]:
with self.subTest(personal=personal):
lua = self.rows(82, personal)
generated = build_probe(self.source, []).decode()
prefix = generated[:generated.index("CHAR_CREATE_HELP_NEXT_BUTTON")]
start = generated.index("function CharacterCreate_RefreshRaceFilterRows()")
end = generated.index("function CharacterCreate_ToggleRaceFilter()", start)
lua.execute(prefix + "\nlocal filter=F; local VISIBLE=1; local UpdateScrollBar=function() end\n"
+ generated[start:end])
lua.globals().CharacterCreate_RefreshRaceFilterRows()
row = lua.globals().F.rows[1]
self.assertTrue(row.enabled)
self.assertEqual(bool(row.checked), not personal)
def test_unsupported_source_and_ids_fail(self):
with self.assertRaises(ValueError):
build_probe(b"unknown client source", [82])
with self.assertRaises(ValueError):
build_probe(self.source, [1])
if __name__ == "__main__":
unittest.main()
+32
View File
@@ -0,0 +1,32 @@
import assert from "node:assert/strict";
import test from "node:test";
import { updateCheckQueue } from "../src/lib/updateCheckQueue.ts";
test("duplicate checks share one result and foreground waits for background on the same server", async () => {
const check = updateCheckQueue();
let release;
let calls = 0;
const background = check("server", "background", () => { calls++; return new Promise(resolve => { release = resolve; }); });
assert.equal(check("server", "background", () => { throw Error("duplicate"); }), background);
const foreground = check("server", "foreground", async () => { calls++; return "full preview"; });
await Promise.resolve();
await Promise.resolve();
assert.equal(calls, 1);
release("background preview");
assert.equal(await background, "background preview");
assert.equal(await foreground, "full preview");
assert.equal(calls, 2);
});
test("one server's failure releases its queue and does not block other servers", async () => {
const check = updateCheckQueue();
let fail;
const first = check("one", "a", () => new Promise((_, reject) => { fail = reject; }));
const failed = assert.rejects(first, /offline/);
const next = check("one", "b", async () => "retry");
assert.equal(await check("two", "a", async () => "independent"), "independent");
fail(Error("offline"));
await failed;
assert.equal(await next, "retry");
assert.equal(await check("one", "a", async () => "recovered"), "recovered");
});