Author SHA1 Message Date
N0VAN0M4LY 0bec173396 Add the public key that adaptation packs are verified with
Adaptation pack / release (push) Canceled after 0s
Launchers accept a downloaded adaptation pack only when its signature verifies against this key. The private key is kept outside the repository, in the PATCH_SIGNING_KEY secret of the release workflow.
2026-11-29 16:48:02 +08:00
N0VAN0M4LY fd9b8068cb docs: update Readme 2026-11-29 16:41:10 +08:00
N0VAN0M4LY edcab5c72c Point two comments at public files 2026-11-29 16:35:46 +08:00
N0VAN0M4LY abf958e2a6 Show whether a game version is verified instead of a nearest adaptation
Patches locate themselves in each game build, so nothing is chosen per
game version: a version without a check record is installed with every
patch tried, and the copy's patch check says which features work. The
pages showed an "adaptation version" and, for an unchecked version, the
nearest checked one as if its patches were used. They now show whether
the version is verified, and say that an unverified one still tries
every patch.
2026-11-29 16:34:54 +08:00
N0VAN0M4LY f4d2916f0d Show adaptation pack updates in the launcher
- IPC patches:active / check / apply / useBundled and the event
  patch-set-changed; installing or reverting is refused while a copy is
  being maintained, since a build reads the patch set as it runs.
- Setting checkPatchPacksOnStart (on by default): the window checks once
  when it opens and stays quiet when the check fails.
- The footer shows an available pack at the right end and leads to the
  About page, which shows the patch set in use, checks on request, and
  downloads and activates a pack only when the player clicks for it;
  a pack that needs a newer offline version, or a failed check, is
  explained there. Supported game versions follow the active set.
- Chinese and English text.
2026-11-29 16:32:13 +08:00
N0VAN0M4LY 6068d5bc65 Configure tuning for each game copy 2026-11-29 16:24:21 +08:00
N0VAN0M4LY 3e08e9314e Edit research branches in local saves 2026-11-29 16:16:42 +08:00
N0VAN0M4LY 3e2acc5a17 Release adaptation packs and let the launcher install them
An adaptation pack is the patch set (exe, GUI, native definitions and
version records) released on its own, so a new game build can be adapted
without a new offline version. It is a zip with a manifest, signed with
Ed25519, published as a GitHub release tagged patches-<YYYY.MM.DD[.N]>.

- packages/patcher/src/patch-pack: manifest and version numbers, zip
  writing and reading with path and size checks, signatures, a check that
  a patch set reads as a whole; tuning/patch-pack.jsonc holds the
  repository and the limits.
- scripts/generate-patch-signing-key.ts writes the public key for the
  repository and the private key outside it; scripts/build-patch-pack.ts
  packs only committed files and signs with PATCH_SIGNING_KEY.
- .github/workflows/patch-pack.yml packs, signs and publishes on a
  patches-* tag or a manual run.
- Launcher main process: find the newest pack release, download, verify,
  unpack into user data and make it active; resource paths use the
  active pack when it is usable (a repository checkout only with
  WTO_USE_PATCH_PACK=1). The pages that show and start this come later.
2026-11-29 16:08:37 +08:00
N0VAN0M4LY 19990fc9de Import official game backups into local saves 2026-11-29 16:03:31 +08:00
N0VAN0M4LY 20a5b3ebf1 Record the patch check of game build 2.61.0.43
All 12 exe patches, 35 GUI patches and 10 native modules apply; a lab
battle on the build (vehicle spawn, killstreak aircraft, nuclear win)
worked. The README no longer names a single target client version and
points to the check records instead.
2026-11-29 15:56:36 +08:00
N0VAN0M4LY c957cecee4 Support save archives and copy transfers 2026-11-29 15:55:23 +08:00
N0VAN0M4LY d19baec90b Add local save selection and editing 2026-11-29 15:42:28 +08:00
N0VAN0M4LY 900eb90b42 Add explicit local account registration 2026-11-29 15:30:34 +08:00
N0VAN0M4LY 2246e3f68e Add maintenance for installed game copies 2026-11-29 15:24:21 +08:00
N0VAN0M4LY 0e851ff920 Manage multiple game copies in the launcher 2026-11-29 15:14:41 +08:00
N0VAN0M4LY 6c09525834 Launch the game through the guarded lab 2026-11-29 15:02:39 +08:00
N0VAN0M4LY 462b49b5c4 Add launcher logging and diagnostics export 2026-11-29 14:45:49 +08:00
N0VAN0M4LY 6ce93ee962 Have the LocalMP modules read their addresses and offsets from the build
wto_ws.dll no longer scans aces.exe or carries structure offsets of a game
build. It reads the values the patcher resolved (wto_ws.cfg native.* lines)
into g_lmp through one table that names, per module, which value fills which
field (local_mp_values.c), and installs each module whose values are all
present, in dependency order, instead of giving up on the whole bridge when
one subsystem is missing. When the settings were resolved for another
executable (PE time stamp and image size differ), the bridge stays off.

local_mp_offsets.h keeps the existing names so the module code reads as
before; only Dagor library layouts (dag::Vector, DataBlock), protocol enums,
the reflection buffer size and the two change request members with no reader
in the client remain constants. A few fields are derived where the client has
no instruction of its own for them (local_mp_values.c derive_values). The
signatures moved to patches/native, and the header-based check-offsets
command is gone: record-game-version and the launcher's patch check resolve
the native modules now.

Shared sites moved to local_mp_core (mission customBots, the player's unit
eid) so modules do not depend on each other for them.

Checked: DLL build (no warnings outside MinHook); root and launcher type
checks; check-patches on 2.61.0.37; version records for 2.61.0.37 and
2.61.0.43 (10 native modules each); a lab run of the 2.61.0.37 copy logs
239 native values and "9 of 9 LocalMP modules installed". Battles were not
played in this run.
2026-11-29 12:26:11 +08:00
N0VAN0M4LY ddec5c59c0 Locate what the native LocalMP modules need from data
The LocalMP modules of wto_ws.dll scanned for 42 functions at start-up and
used about a hundred structure offsets compiled in as constants, so a game
update could move a field without anything noticing. Their needs are now
definitions under patches/native/<module>.jsonc, resolved by the patcher when
it builds the game copy, the same way exe patches are located:

- Locate methods: "string_ref" finds code by the string it loads (optionally
  with a pattern around the lea, to read the field a scoreboard row stores
  under that name), and "within" searches a short pattern inside the function
  of a site located before it (function ranges from the exception directory).
- Each module lists its sites (functions, globals, call targets and the
  instructions whose captures give structure offsets), its features and the
  modules it requires. A module whose sites are not all found is reported
  like an unavailable patch, with the modules depending on it.
- The resolved values go into wto_ws.cfg as native.<site>[.<capture>] lines,
  with the executable's PE time stamp and image size so the library can
  refuse values resolved for another build.
- Version records include the native module variants and values.
- Patch-set folders: the patcher, the scripts and the launcher take the root
  of a patch set (exe, gui, native, versions) instead of separate folders.
- New feature tags K-Chat and radio and K-Nuclear bomb in both language packs.

The library still scans by itself; reading these values is the next change.

Checked: root and launcher type checks; all 10 modules resolve on 2.61.0.37,
where the 239 values equal what the drafting tool read with a disassembler, and
on 2.61.0.43, where every structure offset is unchanged except the GameSaveData
HUD event queue (0xae8 -> 0xb18); build-game-copy from 2.61.0.37 into a
temporary folder writes the values into wto_ws.cfg.
2026-11-29 12:15:30 +08:00
N0VAN0M4LY fdf859c4c9 Record the patch check of game build 2.61.0.37
The build every patch was written for and that has been played in the game; written by scripts/record-game-version.ts.
2026-11-29 11:47:19 +08:00
N0VAN0M4LY b819912733 Let each patch carry variants written for different game builds
A game update used to fail a patch whenever any byte it compared moved, even
when only an address in the instruction changed. Patch definitions now say
what a change needs and read the rest from the code:

- patch.jsonc holds a list of variants, each written for one game build
  (written_for) with its own locate block and edit; locate.jsonc is merged
  into it. Exactly one variant must apply, otherwise the patch is left out.
  GUI script patches use the same variants rule.
- expect_original and the bytes to write use the signature syntax, so
  addresses that differ between builds can be wildcards.
- A locate block can capture values at the site (rel32 targets, immediates,
  displacements); a rel32 fixup fills a hole in the written bytes from a
  capture. allow-local-host-bot-spawns now jumps to the target of the
  conditional jump it replaces instead of a stored distance, which makes it
  apply to 2.61.0.43 as well.
- verified_on is gone from the definitions. patches/versions/<version>.jsonc
  records, per checked game build, which variant of every patch applies and
  where; scripts/record-game-version.ts writes it and the launcher reads the
  recorded versions from there.

The Python tools (check-patches, patch-exe, check-gui) read the same format;
check-patches assembles a variant whose assembly names captures at the site
it was located at.

Checked: root and launcher type checks; check-patches and check-gui on
2.61.0.37 and 2.61.0.43 (12 exe and 35 GUI patches each); check-patches and
check-gui report a deliberately broken patch with a non-zero exit;
build-game-copy from 2.61.0.43 into a temporary folder. The computed bytes of
allow-local-host-bot-spawns on 2.61.0.37 equal the bytes it stored before.
2026-11-29 11:47:08 +08:00
N0VAN0M4LY 3f366651bd Docs: commit init item and docs 2026-11-29 11:34:44 +08:00
N0VAN0M4LY f863b1022c Name patch feature tags in English
The features listed by every exe and GUI patch definition now use English
tags, so contributors can read them without knowing Chinese. Each tag keeps
its feature inventory section letter (A- to O-) and translates the inventory
row it stands for. Tags that named the same row in two languages are merged
(store, premium account, marketplace), and the external inventory tag on the
coupon redemption patch joins the coupons tag it describes: 32 tags become 28.

The three essential tags in the patcher and the launcher's feature labels in
both locales follow the rename.

Checked: check-patches, check-gui, root and launcher typecheck, launcher
build, a build-game-copy run into a temporary folder (12 exe and 35 GUI
patches ready, as before), and install:listFeatures in the launcher
returning 28 tags with the three essential ones flagged.
2026-11-29 11:25:44 +08:00
N0VAN0M4LY 5df305e2f9 Make source comments and build tools self-contained 2026-11-29 08:46:08 +08:00
N0VAN0M4LY 4a2f1c120c Improve launcher contrast and streamline interface copy 2026-11-29 08:43:21 +08:00
N0VAN0M4LY b30df83c8b Show background pictures from the website gallery and the game copy
The window background now comes from two sources, served to the window
over a wto-art:// scheme from the launcher's cache:

- Website wallpapers: the newest entries of the public wallpaper gallery
  on warthunder.com (two pages), list refreshed at most daily, each
  1920x1080 picture downloaded when first shown and kept in the cache.
  No cookies, no sign-in; a setting turns it off. Without a connection
  the pictures downloaded before stay available.
- Game pictures: the nation pictures the game's own launcher keeps in
  launcherr.dat next to the game, extracted from the installed copy
  (fflate) once per archive version.

Without either, the window keeps its drawn background. The settings
choose a random picture per start or a fixed one (thumbnail grid); the
home page shows the picture's name with previous / next.

Checked: launcher typecheck, electron-vite build. Ran the window from a
scratch user data folder with a fake copy holding a copy of the real
launcherr.dat: 18 website wallpapers and 9 game pictures listed, both
sizes and the game pictures load through wto-art://, an unknown picture
is refused, stepping saves the choice, turning wallpapers off leaves
the game pictures, no console errors.
2026-11-29 07:45:26 +08:00
N0VAN0M4LY b83d3e54f3 Redesign the launcher window after the game's launcher and website
The window is now a fixed 1120x720 frameless window with its own title
bar: page navigation, language, minimize and close. The layout follows
the game's launcher: a side panel, the main area over the background,
and a bottom bar with the state of the current task and the primary
action. The colours and type follow the game's website: dark blue-grey,
red actions, Roboto Condensed (bundled, OFL), cyan progress.

- Pages: home (requirements before installation, the current copy
  after), copies (copy details with folders to open, feature status
  grouped by inventory section), settings (language), about.
- The install wizard is a hook shared by the side panel (step list),
  the main area (current step) and the bottom bar (back, next, install,
  cancel, copy progress).
- The adaptation shown for a game version is the version itself when
  the patches were verified on it, otherwise the nearest verified one.
- Both language packs are rewritten in consistent product wording.
- New IPC: app:openFolder, install:listFeatures (patcher's new
  patchFeatures), window:minimize, window:close; app:getInfo reports the
  supported game versions.

Launching is not built yet; its button stays disabled.

Checked: launcher typecheck (main and renderer), electron-vite build,
root typecheck. Ran the window from a scratch user data folder over the
remote debugging port: every page and section in Chinese and English,
empty and installed state, the wizard's first step, both new IPC calls,
no console errors and no overflow.
2026-11-29 07:39:12 +08:00
N0VAN0M4LY 303dbf24e6 Add the install wizard to the launcher window
The window now installs the offline version in five steps:

1. Game: the player picks their War Thunder folder; the launcher says
   whether it is one and whether its version is the one the patches were
   verified on (another version is pointed out, not refused).
2. Method: copy into a new folder (recommended; shows the size of the
   installation, the room on the target drive, and why a folder cannot
   be used) or install into the chosen folder itself. A Steam library
   brings up the three risks and needs a tick before going on.
3. Data: the folder for saves, caches and logs, the launcher's own data
   folder by default.
4. Check: the patch check runs each time the step is entered. Missing
   essential changes stop the installation; other missing changes are
   listed as the features they cost, translated, with the patches behind
   them folded away, and need a tick to go on.
5. Install: phase, a byte progress bar and file counts while copying,
   and a cancel button. An error goes back to the check step with its
   translated message.

The first screen shows either the invitation to install or what is
installed (copy, data folder, version, method, missing features) with a
button to install again. Feature tags of the patch definitions have
names in both languages; a tag without one is shown as it is.

The app's productName gives its user data folder a readable name.

Checked with the launcher typecheck and build, and a start on a scratch
user data folder: the first screen and the wizard's first step render
in Chinese and English with no console errors.
2026-11-29 06:29:53 +08:00
N0VAN0M4LY 54a783b80e Install the offline version: check, copy, back up, record
The launcher's main process can now install the game copy, driven over
IPC by the install wizard to come:

- install:checkPatches builds the copy in memory in a utility process
  (workers/patch-check-worker.ts, a second main entry) and reports the
  patches that do not fit, each marked essential or not. Nothing is
  written.
- install:start checks first, on the stock files the copy would get, so
  a game whose essential patches do not fit is refused before tens of
  gigabytes are copied; other missing patches need the player's
  acceptance. Then, for the copy method, it measures, checks the target
  drive's free space (plus 1 GB) and copies; it keeps the four stock
  files in <copy>/wtoffline/stock, never replacing a file already there;
  and it writes <user data>/install.json. Patched files are written by
  the build at every launch with that launch's port, not here.
- The copy leaves out the top-level folders that hold what the game
  produced while played online (.game_logs, cache, Replays, Screenshots,
  UserMissions). It copies in chunks through streams, so progress moves
  within a large data pack and install:cancel stops at once; it never
  overwrites a file, and after a failure or a cancel it removes what it
  copied, which is safe because the target was new or empty. One failing
  parallel copy stops the others before the cleanup starts.
- Progress goes to the window as event:install-progress, at most every
  250 ms. install:getRecord returns the record and the default data
  folder (<user data>/data).
- New error codes, translated in both languages: not_a_game_folder,
  target_not_usable, steam_library_not_confirmed, not_enough_space,
  essential_patches_unavailable, missing_features_not_accepted,
  patch_check_failed, copy_failed, install_cancelled, install_busy.

Checked with the launcher typecheck and build, and the calls made from a
running launcher window on a 2 GB test game folder holding the real
stock files: the check (12 exe and 35 GUI patches ready), a copy
install (player data folders left out, stock files backed up, record
written, 51 progress events), a second install into the same folder
(not_empty), a cancel 36 MB into a copy (install_cancelled, the copy
removed), an in-place install of the copy (its backup used) and a
folder that is not a game.
2026-11-29 05:03:40 +08:00
N0VAN0M4LY d06989622f Inspect the folders the player chooses for installation
The install wizard needs to tell whether the chosen folder is a War
Thunder installation, which version it is, whether it is a Steam
library, and whether the folder for the copy can take it.

The patcher reads the game version from win64/aces.exe (the
VS_FIXEDFILEINFO block of its version resource) and works out the
versions every exe and GUI patch was verified on, from their
verified_on lists, so the version check follows the patch definitions
instead of a constant.

The launcher gets four IPC calls, each validated against the contract:
- dialog:pickFolder, a folder picker titled by the window;
- install:inspectGameFolder: missing game files, version, verified
  versions, Steam library;
- install:inspectTargetFolder: new or empty, not overlapping the stock
  installation, Steam library, free space on its drive, and whether it
  is on the stock installation's drive (the space saving copy needs
  that);
- install:measureFolder: bytes and files of the stock installation,
  regular files only, links not followed.
A folder that does not exist or cannot be read is the folder_unreadable
error code, translated in both languages. In development the patch
folders and the hook library come from this repository; the packaged
layout comes with the installer build.

Checked with both typechecks, the launcher build, and the calls made
from a running launcher window: the stock folder (2.61.0.37, verified),
a non-game folder, a missing path, a Steam library path, four target
folders (new, inside the stock folder, not empty, other drive) and the
size of the offline copy (96.9 GB in 10,972 files).
2026-11-29 03:36:00 +08:00
N0VAN0M4LY c8d4972cf0 Let the patcher report unavailable patches and build in memory
The launcher has to show the player which patches do not fit their game
build, let them go on without the features those patches cover, and
refuse when a patch that keeps the copy apart from the online game is
missing. The patcher could only refuse the whole build.

- GUI patches are applied one by one. A patch with an edit whose stock
  text is not found exactly once, or whose script is missing, is left
  out whole and reported with its features, like an unavailable exe
  patch; the others are applied.
- patchExecutable always produces the executable with the available
  patches; unavailable ones and those depending on them are listed.
- essential-features.ts names the features whose patches stop an
  installation: A-离线启动, A-与正版隔离, A-不连 Gaijin (the copy does not
  start, touches the online game's data or identity, or connects to
  Gaijin without them). Patches tagged with them are 9 exe patches and
  one GUI patch today.
- buildGameCopy builds every file of the copy in memory from the stock
  files and the caller's inputs (patch folders, hook library, port,
  store pack ids) and returns them with a structured report;
  writeGameCopy writes them, replacing each file instead of writing
  through a hard link. readStockGameFiles reads the four stock files.
- assertWritableCopy takes steamLibraryConfirmed for a Steam library the
  player chose after the warning; isInSteamLibrary is exported.

scripts/build-game-copy.ts uses buildGameCopy and still writes nothing
when any patch is unavailable, unless --skip-unavailable is given and
none of the unavailable patches is essential.

Checked with the root typecheck and three runs of build-game-copy.ts
into scratch folders: all patches as they are (12 exe, 35 GUI, 496
bundle GUIDs, six files written); one ordinary exe patch and one GUI
patch broken (both reported with their features, nothing written, then
written with --skip-unavailable); the network hook patch broken (it and
the TLS patch depending on it reported as essential, nothing written
even with --skip-unavailable).
2026-11-29 03:32:36 +08:00
N0VAN0M4LY 90cc6b0bb1 Say local server in the comments and titles the rename missed
Comments where "local" and "service" fell on two lines, and the Chinese
titles of five patch definitions, still named the local service.

Checked with the root typecheck, check-patches and check-gui.
2026-11-29 03:28:56 +08:00
N0VAN0M4LY ff65f6f3c9 Add the launcher app skeleton
The installer and launcher is an Electron app in apps/launcher: main
process, a sandboxed preload that only forwards allowed channels, and a
React window translated into Chinese and English.

Every renderer -> main call is declared once in the IPC contract
(shared/ipc/contract.ts) with zod schemas for its input and output; the
main side validates both when it registers a handler. The main process
throws error codes only, and the window translates them. The launcher's
own settings (for now the window language) are kept in the user data
folder and written through a temporary file and a rename. Development
runs can point the user data folder elsewhere with
WTO_LAUNCHER_USER_DATA.

The workspace packages (@wto/patcher, @wto/server) stay external to the
bundle: they ship as TypeScript sources and will run in utility
processes, where Electron's Node strips the types and they find their
web pages, tuning and keys next to their sources as they do today.

The root typecheck leaves out the launcher, which has its own tsconfig
files for the main process and the window.

Checked with the launcher typecheck, electron-vite build, the root
typecheck, and a start on a scratch user data folder.
2026-11-29 03:22:38 +08:00
N0VAN0M4LY 27fc535301 Split the repository into apps, packages and patches
Everything sat in packages/: two programs next to the small libraries
they use, and the patch data loose at the root. The programs now live in
apps/ and the shared libraries in packages/:

  apps/server        the local server (was packages/local-service),
                     package @wto/server
  packages/patcher   builds the game copy (was packages/build),
                     package @wto/patcher
  patches/exe        exe patch definitions (was exe-patches)
  patches/gui        GUI script patches (was gui-patches)

Inside the server, the network layer folder becomes transport/ so it is
not server/server/, the entry module is server.ts, and startLocalService
and its types become startServer, ServerOptions and RunningServer. The
health answer names the app wto-server, and the TLS files in the data
folder are server.key and server.crt (made again on the next start).
Comments, logs and tool texts say "local server".

The patcher no longer reaches into the server's folder. It read the
default tuning/store.jsonc by a relative path to register bundle GUIDs
for the multi-vehicle packs, which also ignored the player's overrides
in <data>/tuning/. It now takes the pack ids from its caller; the
server exports multiVehiclePackIds(dataFolder), which reads them the way
the running server does. rebuildGuiPack takes the patch folder from its
caller as well.

The development build moves out of the patcher to
scripts/build-game-copy.ts, since it uses both the server and the
patcher. It needs --data (the folder the server will run with) and
defaults the patch folders and the hook library to this repository.


Checked with the root typecheck, check-patches, check-gui,
check-offsets, the native build, a run of build-game-copy.ts into a
scratch folder (12 exe patches, 35 GUI patches, 496 bundle GUIDs as
before) and a server start from apps/server answering wto-server.
2026-11-29 03:20:54 +08:00
N0VAN0M4LY f6cdab7ec7 Free the support unit reference after control returns
Clearing missionSupportUnitRef as soon as the support unit died kept the
player from getting the vehicle back: the unit update (2.61.0.37
0xfd1450, 0xfd2f01 / 0xfd25a7) recognises the player's dead support
unit by that reference (unit +0x88 == MPlayer +0xb58) and only then calls
setControlledUnit(mp, 0) (0x598a70) to return control. In game the
camera stayed on the wreck until the player respawned.

Remember the player and the dead unit's entity id at the death, and
clear the reference after setControlledUnit has run for that player
(new hook, LMP_SIG_SET_CONTROLLED_UNIT, 2.61.0.37 hit 0x598a70), as
long as it still names that unit.

Checked with the native build and check-offsets; not yet verified in
game.
2026-11-29 02:53:34 +08:00
N0VAN0M4LY 2065514d16 Free a destroyed mission support unit on the LocalMP host
After the first nuclear carrier was shot down, the next launch respawned
it in the air where it died and the player could not fly it. The host
gives a player a support unit only while missionSupportUnitRef (MPlayer
+0xb50 / +0xb58) is empty (2.61.0.37 0x59d9c8), and the client clears
the reference only when the player is re-initialised, never during a
battle. The second launch reused the dead unit: control was refused
("changed controlled unit to already dead unit"), and without an owner
the respawn (0xe4fdf0) placed it at its old position instead of an
airfield.

Clear a player's reference when the unit it names dies (in the existing
onUnitDeadOnce hook, host only), so the stock update creates a new
support unit the next time the spawn score threshold is reached.

Checked with the native build and check-offsets; not yet verified in
game.
2026-11-29 02:37:19 +08:00
N0VAN0M4LY a67b966de3 Give profiles the modifications support plane presets need
The respawn screen showed an empty loadout for the nuclear carrier: a
preset is listed only when shop_is_weapon_available passes (2.61.0.37
0x17a38a0 -> 0x912d20 -> 0x90f2c0 / 0x9662f0), which needs every
reqModification of the preset and of its sum_weapons to be a bought
modification of the unit in the profile. The forced preset of
f_16a_block_15_adf_killstreak carries bombguns_us_b61_30kt with
reqModification us_500lb_mk82, and the player never owns that unit.

Derive the modifications of each missionSupportPlane unit's forced
preset from wpcost.blk and keep them in every profile as owned, in the
profile refresh. Only those killstreak units are touched.

Checked with typecheck and a run over the stock data (30 records, the
F-16 one included); not yet verified in game.
2026-11-28 22:29:45 +08:00
N0VAN0M4LY b3c565fdc7 Settle nothing for mission support planes
Online the time flown in the nuclear carrier (gameplay.blk
missionSupportPlane) and its kills are not settled, while other aircraft
are. Its lives were settled like any vehicle when it was spawned from
the lineup slot: battle time, research points and repair for a unit the
player does not own.

Collect the support plane units from missionSupportPlane and drop their
lives and combat events from the battle facts before the settlement and
the live award judging. The nuclear strike fact and its award are kept.

Checked with typecheck; not yet verified in game.
2026-11-28 22:25:19 +08:00
N0VAN0M4LY 91563f05cb Take the LocalMP battle outcome when the battle is left
The MissionResult HUD event did not reach the scripts before the battle
was left (a nuclear win in game still settled as not won): the HUD can
hold the result back (2.61.0.37 0x183edc0, delay at Hud +0xb8). The
eventbus event onQuitToDebriefing, however, is raised both on the fade
to the debriefing after the battle ends and when leaving from the menu,
while the mission still exists; the stock debriefing gathers its result
on it too.

Record the end time, the closing life and the outcome there, from the
mission status (success / fail; a running battle records no outcome),
and drop the MissionResult subscription.

Checked with check-gui; not yet verified in game.
2026-11-28 20:33:54 +08:00
N0VAN0M4LY 6ab941a086 Award the nuclear strike in LocalMP battles
Online the battle server gives killStreak_bomber_nuclear_success (mode
killStreakNuclearSuccess, 10000 SL) when a player's nuclear bomb
explodes; the LocalMP host has no battle server, so the award was never
given.

The native nuke module now remembers whether the local player launched
the instant-win bomb and, when it explodes, raises the HUD script event
wtoLocalMpNuclearStrike. The battle record keeps it as a strike, sends
it live (wto_battle.fact kind "strike") and reports it after the battle
(strikes{}); the local service awards killStreakNuclearSuccess once per
strike, live as the award banner and in the settlement.

Checked with typecheck, check-gui, check-offsets and the native build;
not yet verified in game.
2026-11-28 19:03:24 +08:00
N0VAN0M4LY 28aa6ec971 Record the LocalMP battle outcome when the mission ends
The settlement report read get_mission_status() when the debriefing
opened. By then the mission scene has been unloaded and the status reads
as running, so every battle that ended on its own (tickets or nuclear
strike) was settled as not won. The end time was lost the same way and
the last life was never closed: onQuitToDebriefing is only raised when
the battle is left from the menu, not by the automatic FadeToDebriefing.

AcesMission::endFinally (2.61.0.37 0x11203f0) raises the HUD event
MissionResult with the local team's result while the mission still
exists. Record the outcome, the end time and the closing life there;
leaving from the menu still records the end time without an outcome.

Checked with check-gui; not yet verified in game.
2026-11-28 19:01:15 +08:00
N0VAN0M4LY 752346d877 Read mission variable values at +0x10
cta_logic_action walks the variable array with r15 = entry+8, compares the name
at [r15-8] and takes the value at r15+8 (0x11bd1a6), so the int value is at
entry+0x10; the nuclear win wrote the wrong field and the tickets stayed.
2026-11-28 18:31:43 +08:00
N0VAN0M4LY 1c32dc71b0 Take the nuclear win at the projectile explosion handler
create_nuke_destr_area_es does not run on the LocalMP host. The projectile
explosion handler 0xbe7c00 gets the launch record's instant-win flag as its
8th argument (0x2fd778 / 0x2fd7c3) and is what plays the nuclear explosion,
so the winner is now taken there.
2026-11-28 18:10:39 +08:00
N0VAN0M4LY f470585136 End a LocalMP battle on a nuclear instant-win explosion
Online the battle server ends the battle when a bomb with isInstantWinOnExplode
explodes; the 2.61.0.37 client only flags the bomb, so the LocalMP host played on.
The host now remembers the team of a flagged bomb (0x1431c10), takes it as the
winner when create_nuke_destr_area_es runs (0x63caf0), and zeroes the loser's
mission ticket variable before cta_logic_action (0x11bc400), which then ends the
battle the stock way.
2026-11-28 17:57:47 +08:00
N0VAN0M4LY 7d29723f0d Send gameModeName so the native mission support plane is enabled
The 2.61.0.37 mission loader looks up the gameplay.blk missionSupportPlane
preset by the mission's gameModeName; without it the native nuclear carrier
is never assigned, so no action bar item and no instant-win bomb.
2026-11-28 17:05:35 +08:00
N0VAN0M4LY bfb97de6c7 Load LocalMP bot pools from mission custom rules
The 2.61.0.37 client reads customRules/customBots into its bot settings. Send the existing matchmaking pools and both country lists through that block. Verified both coalitions in an isolated Ground Realistic battle.
2026-11-28 15:29:49 +08:00
N0VAN0M4LY a634a59976 Preserve LocalMP battle state for the debriefing 2026-11-28 14:45:02 +08:00
N0VAN0M4LY 99c59551fd Show random battle vehicles before fixed support slots 2026-11-28 14:42:31 +08:00
N0VAN0M4LY 442b9a1c32 Calculate LocalMP base spawn scores before launch 2026-11-28 14:39:46 +08:00
N0VAN0M4LY b63b45fabd Apply per-vehicle free repairs after local battles 2026-11-28 14:35:26 +08:00
N0VAN0M4LY 8ee5ca66b2 Require confirmation of every Quirrel script compilation
Pass the manifest path to the harness directly and require per-script success and a completion marker. The standalone interpreter can exit with status zero after a harness failure. Resolve merged interface exports and provide integer bindings for stock constant expressions.
2026-11-28 14:13:14 +08:00
N0VAN0M4LY 7d05d25b94 Fix LocalMP reward script compilation during login
Use baseReward for the reward amounts because Quirrel reserves base. The compile error interrupts post-login script loading before hangar selection and leaves the hangar waiting for its one-minute fallback.
2026-11-28 13:37:07 +08:00
N0VAN0M4LY 1ce54df4c0 Describe what the LocalMP loadout module does in its header
The header of local_mp_loadout.c still named per-unit economic multipliers that
the economy rework removed from the module. It now says what the module does: on a
host the client has no receiver for its own vehicle change request, so the send
hook builds the ChangeUnitReflection and calls Unit::changeAircraft. Comment only.

Checked: native build, check-offsets.
2026-11-28 13:03:29 +08:00
N0VAN0M4LY ff755ce551 Replace placeholder headers of six baseline battle patches
Two exe patches (allow-local-host-bot-spawns, allow-local-host-player-respawn) and
four GUI patches (local-host-spawn-score, quit-local-host-to-debriefing,
quit-local-host-spectator-to-debriefing, ready-local-host-respawn) still carried
the migration placeholder comment and partly non-English titles. Each now has the
three header lines (what it changes, why the client, what happens without it), an
English title, feature tags that name existing feature inventory rows, and a note
that it is kept from the baseline without a re-review in the LocalMP rework.
No patch content changes.

Checked: check-patches (12 ready), check-gui (35 patches compile).
2026-11-28 13:02:07 +08:00
N0VAN0M4LY 4e62508335 Restore source references in local service file headers
The unreviewed baseline shortened many file headers and dropped their sources: the
research notes sections, architecture sections, stock script paths and client
addresses. They are put back where the code still does what they describe, and the
headers of research, modification and research action files now also describe the
banked excess RP flow (cln_move_exp_to_unit, cln_move_exp_to_module) that the
baseline added. Comments only.

Checked: typecheck.
2026-11-28 12:59:51 +08:00
N0VAN0M4LY 09973884ae Repair damaged vehicles for free over their full repair time
The client never raises a vehicle's hp by itself; the hangar shows (1 - hp) x the
full repair time as what is left (shop_time_until_repair, aces.exe 2.61.0.37
0x17a5040). The local service now restores hp whenever it hands out or changes a
profile: hp grows by the hours since it was last set over the full repair time, and
the damage is cleared at 1.

The full repair time follows the client (0x937330): repairTimeHrs<Mode> times the
repair cost's modification factor (0x964750 -> 0x964900) times a crew multiplier
when a crew has the vehicle as its current one, else repairTimeHrsNoCrew<Mode> (or
repairTimeHrs x rTimeNoCrewMul, 0x964e30). The crew multiplier runs from 1 to 1/3
(hangarRepairSpeed default, 0x95cee0) over the groundService/repair level plus the
specialization share of specialization<k>_add (0x95d200), and applies only when
repair_ranks covers the vehicle's rank for the crew's repairRank level (0x95d7b0).
The vehicle-repair dataset gains the repair times, rTimeNoCrewMul and these crew
skill values; RepairRules is built with the profiles so the refresh can use it.
Inferred: the skill fields the client divides are level and maximum level, the
rank compared is the tech tree rank, linear growth at the current crew's pace.

Checked: typecheck; full repair times for us_m1a1_abrams from the game data (no
crew 678 h, untrained 171 h, maxed ace 57 h) and the hp growth over time.
2026-11-28 12:56:12 +08:00
N0VAN0M4LY 5b75dd5c59 Promote expert crews to ace when their vehicle RP reaches train3Cost_exp
Settlement already added an expert crew's battle RP to expertToAceProgress but capped
it at train3Cost_exp and left the crew at expert. The stock tooltip says ace is
"obtained for free when the crew gets {expAmount} with the current vehicle"
(crew/qualification/specDescriptionPart), and the client's discount stages end at
75 % (wp_get_specialization_cost_gold -> aces.exe 2.61.0.37 0x9165f0). The crew now
becomes ace once the RP reaches the target and its progress entry is dropped, as
the client drops an empty expertToAceProgress block (0x93b4eb). The ace price no
longer has its own "free at 100 %" case, so it matches the price the client shows.

Checked: typecheck.
2026-11-28 12:48:59 +08:00
N0VAN0M4LY 2b1c300203 Keep redirected battle RP in the destination branch without a target
With "Research of helicopters by playing ground vehicles" on, the stock text says
ground vehicles are not researched and all their vehicle RP goes to helicopters
(lang shop/research_helicopters_by_ground_vehicles_tooltip). Settlement fell back
to the ground branch whenever the helicopter branch had no current research target;
now the RP stays in the destination branch (banked there until the player picks
the next helicopter) and returns to the vehicle's own branch only when the
destination has nothing left to research. The redirection moves from the profile
helper into the RP investment, which has the tech tree.

Checked: typecheck.
2026-11-28 12:48:49 +08:00
N0VAN0M4LY a6f37418e6 Deliver decal indexes through char.vromfs.bin instead of the CDN
The client never downloads downloadable_decals.<hash>.blk: webdlcontent only looks
for it in its web cache folder (aces.exe 2.61.0.37 0xd3e710 -> 0xd3f610) and deletes
a file whose signature check fails (0xd383e0), so the index the local service served
never reached it and every decal was dropped for lack of a texture.

The build now stores dldata/downloadable_skins.blk and dldata/downloadable_decals.blk
in char.vromfs.bin. The client's vromfs index path (0xd3bc40 -> 0xd3cc60) loads both
without hash or signature checks and skips the download path. Each decal points at
a built-in decals.dxp.bin texture (star, or panther for wide decals) as placeholder;
the texture manager strips the "?options" suffix before the lookup (DagorEngine
TextureMetaData::decode), so the existing textures are used.

--decal-cache <folder> copies the cache/content folder of the player's online
installation into the game copy instead; the client then uses that signed index and
its cached textures, and falls back to the cached dldata_s.info because the local
service now answers the dldata hosts with 404. The service's index generation, the
content hash helper and the decal texture dataset are removed.

Checked: typecheck; client startup log shows 1598 decals registered from the vromfs index
with no missing textures.
2026-11-28 12:44:45 +08:00
N0VAN0M4LY 7da47bffa3 Damage, repair and compensate vehicles after LocalMP battles
The local service now settles vehicle repair after a battle and charges
hangar repairs at the price the client shows.

- New dataset vehicle-repair (wpcost.blk repairCost<Mode>,
  repairCostPerMin<Mode>, modifications' repairCostCoef<Mode>) and
  RepairRules, which follow the client's own formulas: full cost =
  repairCost<Mode> x (1 + coefficients of the owned modifications)
  (aces.exe 2.61.0.37 0x10517b0, 0x964900); current cost =
  max(1, (1 - hp) x full cost) in the vehicle's lastGameMode
  (getAircraftRepairCost 0x90e0b0).
- The price table now carries aircrafts/<vehicle>/repair/<mode>/cost,
  where the client looks the full repair cost up; it read 0 before.
- After a battle each life costs the official lifetime share: destroyed
  = repairCostPerMin x minutes started, at most the full cost; leaving
  the vehicle (or the battle) early = full cost; surviving = nothing;
  destroyed by an ally = nothing. The cost is written as hp,
  lastGameMode and time on the hangar entry, so the client's own repair
  cost matches it.
- Automatic repair (autoRepairAircrafts, on by default) pays for the
  damaged vehicles the player can afford; premium accounts with
  automatic repair and ammunition purchase get the expenses beyond the
  battle's earnings back. The battle log gets aircrafts hp,
  autoRepairWasOn, container.aircraftsRepaired and
  wpExpensesCompensation; the debriefing gets the ExpensesCompensation
  row.
- cln_prepare_aircraft, cln_repair_all and cln_repair_all_in_slots
  carry no price; they now charge the current repair cost instead of
  repairing for free.

Not yet verified in game.
2026-11-28 12:08:20 +08:00
N0VAN0M4LY 19be0d2443 Apply boosters and wagers in LocalMP battle settlement
Boosters (rateBooster items) now add to the settled battle as the stock
client and the official wiki describe: each booster adds its percent of
the base reward; boosters stack per event type and personal / all-allies
group with the client's calc_public_boost factors; a battle uses one
battle of a booster plus one per spentInSessionTimeMin span, and a
booster with R battles left covers the first R spans; kill, ground kill
and assist boosters add only to that event and end after their kill
count. The debriefing table gets the booster columns, the session log
lists affectedBoosters, the research breakdown carries boosterExpTotal,
progress is saved and used-up boosters are removed with an
EULT_REMOVE_ITEM log.

The active wager now moves with each battle that meets its active
conditions (lineup rank range, random battle, mission postfix): a stage
when its win condition holds (battle won, players killed, or the listed
battle awards, hidden ones included), otherwise a failed battle. It ends
at maxWins or maxFails and pays a x stake x stages^b + c of the reached
stage. Each counted battle logs EULT_CHARD_AWARD in the battle's room and
the session log lists affectedWagers, which the stock debriefing shows.

Hidden battle awards are now judged (not shown or logged) so wagers can
name them; awards of mode missionsWon are supported, and "unlocks"
awards honour num.

The new GUI patch battle/match-settled-battle-room-logs matches the
settled battle's logs by room id in isUserlogVisible, the one filter all
"this battle's logs" queries use; it replaces the two per-call edits in
use-settled-debriefing-stats.

Not yet verified in game.
2026-11-28 11:55:19 +08:00
N0VAN0M4LY f8735e5ca5 Settle the open questions of three LocalMP respawn and scoreboard patches
The extra game modes now use the battle rating the matching server
computed for the lineup also out of a squad, so the local service decides
it and the client no longer recomputes the lineup's rank.

The scoreboard flag fallback and the countdown button patch keep their
behaviour; their comments now state what the stock code does, why the
fallback is needed before the first spawn, and that the countdown
flicker's trigger on the host is still to be found.
2026-11-28 08:36:57 +08:00
N0VAN0M4LY 8febf2d94e Judge LocalMP battle awards in the local service
The battle awards (streaks) of unlocks.blk are now judged by the local
service from the battle's facts: the player's combat events, each life
and whether it ended in death, the HUD kill log and the final
scoreboard. The record patch also sends each fact live over the
matching connection (wto_battle.fact); the awards it completes come
back and are shown with the stock award banner and kill log entry.

After the battle the awards become EULT_NEW_STREAK logs, which the
stock debriefing lists on its left, and their Silver Lions are paid and
shown in the Unlocks row. Modes whose facts are not reported, and
best-player awards limited by battle rating, are never given.
2026-11-28 08:32:35 +08:00
N0VAN0M4LY 1803cc00da Apply research efficiency rules to LocalMP battle research points
Vehicle research points now follow rank.blk: the predecessor bonus
(expBonusPercentForChildForMode), the rank difference penalty
(expPenaltyPercentForHigherRank / LowerRank) and the Vehicle Research
Bonus (ExpNewNationBonus, five battles per nation and type per UTC day).
Modifications keep the research points before these terms.

The settlement records each vehicle's breakdown in the session log's
container.researchPoints, which the stock debriefing explains in its
research rows. The debriefing patch now selects the battle's logs by
room id, since a LocalMP host is in no matching room and the stock
current-room check cannot match them.
2026-11-28 08:20:40 +08:00
N0VAN0M4LY d5df921d7f Show LocalMP extra lineup vehicles as plain vehicles
The live game draws one vehicle from each RandomSpawnUnits group at
launch and shows it as a plain lineup vehicle (a 12.7 US lineup gets an
M1A1 12.0 and an ADATS 12.0, no dice), so the random_units state and the
patch that filled it are gone. The strike UCAV costs 750 spawn points,
the live game's value, now in tuning/battle.jsonc.
2026-11-28 07:28:48 +08:00
N0VAN0M4LY c17c3d3384 Narrow the LocalMP native bridge to documented engine gaps
- Scoreboard scores come from the local service: BattleEconomy
  missionScores() writes the official mission scores into the stock
  mission block customScoreParams, which the client copies into
  MissionSettings+0x6d8 without reading it; local_mp_scores.c reads them
  with DataBlock::getReal. The hardcoded scores and the death score go.
- countActivePlayers already counts players with a living vehicle; the
  only LocalMP gap is its filter skipping bots (MPlayer+0x1d8 bit 7). A
  one-byte exe patch drops that filter bit instead of a rewrite hook.
- ucavLaunch returns early on a host; an exe patch skips that return
  instead of clearing the global host flag around the call.
- onBecameDead no longer runs with isLocalMP cleared: that only queued an
  EventOnPlayerDeath stock LocalMP skips on purpose, and broke the local
  player id remap inside the function.
- The host chat object keeps its two-field layout, now documented from
  the host chat handler that reads it.
2026-11-28 07:09:07 +08:00
N0VAN0M4LY 901f504dc6 Choose LocalMP extra lineup vehicles from the game data
Rebuild the extra vehicles a battle adds to the player's lineup on the
game files and the official rules:

- Random vehicles (dice slots): one per gameplay.blk RandomSpawnUnits
  group of the event economic name and country, offered from the
  group's minPlayerMRank on, with no condition on the lineup. The option
  window follows the official changelog examples (never the session's
  top BR, lower BR when nothing fits); its formula is inferred from the
  group parameters. Only the listed addModification items are enabled.
- Nuclear carrier: missionSupportPlane preset of the session rank, cost
  spawnScoreToUse.
- Strike UCAV: offered by an offline tuning rule, priced by the stock
  spawn score formula, no forced preset.

The spawn request enables exactly the slot's modifications, and every
forced weapon travels in the slot, so the event-name fallback is gone.
2026-11-28 06:48:17 +08:00
N0VAN0M4LY 101c7260a2 Use the stock event economic names for ground and naval modes
The per-event game tables (rank.blk ExpSkillBonus, gameplay.blk
RandomSpawnUnits) and the stock scripts that read them through
getEventEconomicName key ground and naval events as
tank_event_in_random_battles_arcade, tank_random_battles_historical_base,
tank_event_in_random_battles_simulation and
ship_event_in_random_battles_{arcade,realistic}. The catalogue used the
leaderboard mode ids instead, so the skill bonus and random spawn units
of those modes were never found.
2026-11-28 05:13:56 +08:00
N0VAN0M4LY 7f570c85c3 Price LocalMP battle rewards in the local service
The LocalMP host has no battle server, and the previous bridge filled the
gap by computing money in the client: the native ledger wrote invented
amounts into SessionStatsNet, the spawn patch derived reward rates from
warpoints.blk, and the settlement patch summed and rescaled the result.
Rewards came out as zero or several orders of magnitude too high.

Now the client reports facts and the local service prices them.

Native (wto_ws.dll):
- local_mp_ledger.c is removed together with its SessionStatsNet
  offsets and four signatures (43 -> 39).
- local_mp_awards.c raises the HUD script event wtoLocalMpExpEvent for
  every combat event of the local player (event code, victim expClass
  and name, player or AI victim, friendly, naval damage). The DataBlock
  helpers and the HUD event queue are resolved from call sites inside
  GameSaveData::addScoreMessage, which already has a signature.

GUI patches:
- record-local-battle-awards records events and lives in nestdb and
  raises the stock InBattleReward banner from launch-time parameters.
- report-local-battle-settlement sends only facts and rebuilds the
  debriefing from the settled table; failures show the stock error box.
- use-settled-debriefing-stats makes gatherDebriefingResult read that
  table instead of the empty stat_get_exp().
- pass-spawn-modifications-blk no longer computes economy factors.

Local service:
- battle-economy dataset reads every reward factor from wpcost.blk,
  warpoints.blk and rank.blk; tuning/battle-economy.jsonc holds the
  mission score per event with its source (official values where
  published, otherwise marked).
- battle-economy.ts is the single pricing function, shared by the
  banner parameters and the settlement; battle-rewards.ts adds battle
  time, timed award, win/defeat bonus, activity, premium account,
  talisman, skill bonus and free research points; the debriefing table
  has the stat_get_exp() layout and travels in EULT_SESSION_RESULT.
- Crews earn skill points from the battle's research points.
- A battle left before it ends counts as a defeat.

Verified: npm run typecheck, check-gui (35 patches), check-patches,
check-offsets, native build. Not yet run in game.
2026-11-28 04:42:27 +08:00
N0VAN0M4LY b1392c0512 Build the local battle mission settings in the local service
The launch script patch used to assemble the whole MissionSettings block
on the client: reading the mission file for localization keys and ticket
rules, filling the AI vehicle pool, rank window and extra slot costs.
All of that is pre-battle data the local service already owns.

- multiplayer-missions dataset v3 keeps the scalar parameters of
  mission_settings.mission and of each per-difficulty sub-block, with
  their BLK types.
- battle-mission-settings.ts builds the complete MissionSettings block
  from the launch plan (same parameters as before).
- battle-launch-notify.ts sends it as a typed tree, so ints and reals
  keep the types the engine reads, plus the lobby settings and the
  per-battle record the in-battle patches read from nestdb.
- The launch patch shrinks from 208 to about 70 lines: rebuild the
  DataBlock, set _gameMode from the client's own native constant, enter
  the session lobby and start the LocalMP battle.

Behaviour is unchanged; coalitions, extra slots and economy are reworked
in later commits. Verified: npm run typecheck, check-gui (33 patches).
2026-11-28 03:39:53 +08:00
N0VAN0M4LY 16b5d3cab1 Store patch definitions as commented JSONC with separate script fragments
Patch definitions under exe-patches/ and gui-patches/ move from
patch.json/locate.json to patch.jsonc/locate.jsonc. Each file now holds
only the data needed to apply the patch plus a short English comment
stating what it changes, why the local service cannot provide it, and
what happens without it. Every definition records the game versions it
was verified on (verified_on, required).

GUI patches keep their stock text and replacement in find.nut and
replace.nut next to patch.jsonc instead of escaped JSON strings, so the
script edits are readable, diffable and can carry Quirrel comments.
Matching treats CRLF and LF as the same line break because stock
scripts mix both; only the matched span is rewritten.

Loaders on both sides (packages/build, packages/exepatch, wtotools)
reject unknown keys so analysis text cannot creep back into the data.
JSONC parsing moves into a shared @wto/jsonc package; the build now
parses tuning/store.jsonc instead of scanning it with a regex.

Verified: npm run typecheck; check-patches (10/10 ready on 2.61.0.37);
check-gui (33 patches, 24 scripts compile); the TypeScript and Python
appliers produce identical scripts, byte-identical to the previous
definitions except one stock script with mixed line endings.

The 15 battle patches are migrated mechanically and still carry the
pending-review comment; they are rewritten by the LocalMP review.
2026-11-28 03:24:12 +08:00
N0VAN0M4LY 6a189513b0 Snapshot unreviewed LocalMP battle work as rework baseline
Records the uncommitted battle-session work exactly as it was left
(local service matchmaking, settlement, chat, native LocalMP hooks,
battle gui/exe patches) so the following review and rework commits
show every correction as a diff against this state.

This commit is not reviewed and is known to be incomplete: in-game
testing reported wrong settlement rewards, single-country teams,
missing random/fixed supplement slots, misattributed hit messages and
other regressions. Do not merge this branch before the rework lands.
2026-11-28 03:15:47 +08:00
N0VAN0M4LY aa272fc82b Refresh the storefront and autoplay pack demos
Cache allowlisted official media so the in-game browser can load it locally. Match the official catalog snapshot and start pack demos muted and looping on entry.
2026-11-27 00:43:50 +08:00
N0VAN0M4LY 81e3add520 Add a shopping cart and refresh the local storefront
Save carts per account and settle each order in one profile update. Add featured packs, a screenshot and video gallery, and premium artwork from the game files.
2026-11-26 19:07:48 +08:00
N0VAN0M4LY 9a495e6a0f Accept native inventory exchange material tuples
Resolve item definitions from saved stacks and validate the combined quantity when a request repeats a stack.
2026-11-26 19:07:48 +08:00
N0VAN0M4LY 64b11d56bf Serve stock artwork and link official store media
Show the installed game artwork in the local store and marketplace. Use the official cover and gallery for each mapped product, with on-demand video playback. Include store cover images and screenshots in optional offline asset packs.

Verified TypeScript, browser script syntax, local service startup, game artwork endpoints, a sample image pack, and BMD-4M WebM byte-range delivery. In-game verification is pending.
2026-11-26 17:18:32 +08:00
N0VAN0M4LY b15cece581 Use localized store titles in vehicle pack receipts
Include the catalogue titles in the entitlement price data and select the matching language in the client receipt formatter. Checked TypeScript, the GUI pack rebuild, and the patched Quirrel script.
2026-11-26 17:18:32 +08:00
N0VAN0M4LY 2d9ac527fb Show native rewards after manual coupon redemption
Open the stock reward window after a successful coupon activation using its existing reward definition.
2026-11-26 10:24:08 +08:00
N0VAN0M4LY 55846a91e9 Enable the native opening window for supply chests
Select the stock Silver Lion chest style so buying an external chest can continue through the existing opening flow.
2026-11-26 10:24:07 +08:00
N0VAN0M4LY 66d8cd6efe Document retention of unread purchase receipts 2026-11-26 10:14:58 +08:00
N0VAN0M4LY 44adec01f6 Honor configured marketplace fees and validate result text
Display the fee supplied by the marketplace service. Use the unconfirmed notice when the returned message is missing or invalid.
2026-11-26 10:14:58 +08:00
N0VAN0M4LY 1b86da28d2 Show marketplace trade results above item details
Place the existing transaction notice above the item dialog and report unconfirmed results when a request fails or returns invalid data. Prevent older responses from overwriting the latest notice.

Verified JavaScript syntax.
2026-11-26 10:00:19 +08:00
N0VAN0M4LY 8b63cb5211 Refresh profiles when commerce windows close
Use the existing entitlement refresh task when leaving the local store, marketplace, currency shop, or Premium Account shop. Use the same path for the explicit and ordinary browser close actions.

Verified GUI patch application and Quirrel syntax.
2026-11-26 10:00:19 +08:00
N0VAN0M4LY 4c2aa876b6 Show native receipts for store purchases
Persist the actual grant in the purchase log and open one native receipt per unread entry. Keep pending receipts during log trimming and resume them when the price table becomes available.

Verified TypeScript types, GUI patch application, and Quirrel syntax.
2026-11-26 10:00:19 +08:00
N0VAN0M4LY d7fc94e551 Update the store and marketplace pages and image sources
Add catalogue filters, item detail views, and purchase and resale
actions. Resolve images from the player's asset pack, public image
URLs, or local game data. Add a utility for creating the optional
local asset pack.

Type checking and JavaScript syntax checks passed. Embedded browser
appearance and in-game behavior still need acceptance.
2026-11-26 07:12:38 +08:00
N0VAN0M4LY c01ee8ae5a Add store and marketplace deep links and coupon resale
Register bundle GUIDs at build time and return local store item URLs.
Route marketplace item links to the requested coupon. Update vehicle
and cosmetic prices from the marketplace snapshot and support selling
coupons back to the system at the configured fee.

Type checking, an isolated build, and local service checks passed.
In-game acceptance is pending.
2026-11-26 07:12:38 +08:00
N0VAN0M4LY b6964658d7 Persist custom weapon presets and fix decal research state
Save revisions to custom weapon presets and return the full profile.
Keep an empty top-level weaponPresets block after the final deletion
so the client clears its cached presets. Treat the tier-zero
allowPremDecals modification as researchable.

Type checking passed. In-game acceptance is pending.
2026-11-26 07:01:06 +08:00
N0VAN0M4LY 885966aa7e Stock newly unlocked ammunition and crew replenishment
Extract weapon prerequisites, default equipment states, and exclusive
groups. Grant eligible zero-cost modifications in dependency order and
initialize newly unlocked consumables and weapon presets at capacity.

When automatic restocking is enabled, replenish existing stock subject
to the Silver Lions balance. Enforce purchase prerequisites and
exclusive equipment groups.

Type checking, patch checks, and local data extraction and restocking
checks passed. In-game acceptance is pending.
2026-11-26 02:14:00 +08:00
N0VAN0M4LY 9e759197d0 Sign external inventory responses for the offline client
Sign the inventory JSON payload using the local signing key and
provide the required signature headers. Register the corresponding
public key in the rebuilt GUI pack so the client can verify the
definitions.

Type checking, pack checks, and local signature verification passed.
In-game acceptance requires a rebuilt offline copy and restarted service.
2026-11-26 02:13:23 +08:00
N0VAN0M4LY 7ef442271f Fix cloud settings replies and persist skipped tutorials
Return the unframed BLK expected by the cloud settings client.
Allow the basic ground tutorial to be skipped and save the tutorial
preference immediately.
2026-11-25 22:46:35 +08:00
N0VAN0M4LY 533a263d6e Persist acknowledged user logs and hangar preferences
Handle cln_update so acknowledged notifications do not reappear.
Persist client preferences and ignore unrelated placeholder blocks.
2026-11-25 22:46:35 +08:00
N0VAN0M4LY 3e21c2c993 Prevent saved showcases from crashing the profile parser
Store local showcase selections separately from the client's top-level
showcase block.
2026-11-25 22:46:35 +08:00
N0VAN0M4LY f4bb5ccf46 Separate research rules from character price encoding
Keep ResearchRules focused on vehicle research and purchases. Move
cln_get_price_ex encoding into the character protocol layer and inject
its catalogue dependencies explicitly. Load only the catalogues needed
by each service and save editing command.

Type checking and isolated service and save CLI checks passed.
In-game acceptance is pending.
2026-11-25 16:33:27 +08:00
N0VAN0M4LY 2b123194e1 Offer a free offline payment option
Expose free payment in the in-game dialog, local store, and marketplace.
Grant the selected item without debiting GJN and reject unknown payment
methods. Apply the configured per-purchase limit consistently.

Type checking, binary and GUI patch checks, and local purchase checks
passed. In-game acceptance is pending.
2026-11-25 13:41:37 +08:00
N0VAN0M4LY ec2d3ffbc4 Fix vehicle icon lookup and default web account selection
Match archive paths without regard to case and include Golden Eagle
vehicles in icon extraction. Default read-only page state to the
current in-game account. Keep web mutations gated on an explicit
account ID.

Type checking and local icon and account selection checks passed.
In-game acceptance is pending.
2026-11-25 13:41:35 +08:00
N0VAN0M4LY 26fd6b51b7 Sell multi-vehicle packs and load localized country names
Offer the five three-vehicle packs and nine starter packs as bundles.
Grant their unowned vehicles and bonuses on purchase. Encode each
vehicle in an aircraftGift field and validate duplicate IDs and
vehicle assignments.

Read group labels from units.csv and country names from
_common_languages.csv. Use those names in packs and browser filters.

Type checking and local catalogue and price response checks passed.
In-game acceptance is pending.
2026-11-25 13:41:32 +08:00
N0VAN0M4LY a09ac41299 Keep a default vehicle research target for each branch
The accelerated research dialog reads currUnit when it first opens.
Assign a valid target whenever an eligible vehicle exists and replace
stale selections when refreshing a profile.

Prefer an available direct successor when configured. Otherwise use
the configured rank or tech tree order. Type checking and profile
initialization passed. In-game acceptance is pending.
2026-11-25 13:41:29 +08:00
N0VAN0M4LY d609188acc Open store pages in-game and centralize economy tuning
Use the native embedded browser and pass the game language through
auto_local. Share web assets and extract vehicle icons, flags, and
localized names from the installed client.

Load and validate per-domain JSONC tuning and merge local overrides
by field. Use official store USD prices for GJN products, keep GJN
balances in integer cents, and split the native and web store
handlers by protocol. Multi-vehicle packs are still listed as single
vehicles at this point.

Type checking, patch checks, and configuration loading passed.
In-game acceptance is pending.
2026-11-25 11:01:05 +08:00
N0VAN0M4LY cf08034060 Use 64-bit VROMFS digest offsets
Read and write the digest table start as a 64-bit field in both codecs.
The truncated offset caused SHA-1 mismatches in large packs such as
ui/images.vromfs.bin and ui/atlases.vromfs.bin.

Type checking passed and the service extracted icons and flags from
the large packs.
2026-11-25 11:00:48 +08:00
N0VAN0M4LY 8012cf7954 Fix squadron persistence and align inventory wire formats
Read squadron action parameters from the request headers and persist
squadron state on profile refresh. Use floating-point trophy weights
to match the client probability display and assign unique log IDs
when opening multiple chests.

Tighten shop, marketplace, squadron, and cloud settings validation.
Move PBBD and inventory encoding into the protocol modules and share
CSV reading. Update the research and acceptance instructions.

Type checking and all eight executable patch checks passed.
In-game acceptance is pending.
2026-11-25 09:10:09 +08:00
N0VAN0M4LY 0b604c76f1 Separate inventory, squadron, and web responsibilities
Split inventory definition generation by category and select chest
contents deterministically. Move squadron queries, membership, and
lifecycle into focused modules and enforce role permissions.

Serve store and marketplace pages as static files with shared web
helpers. Share profile field readers and keep response encoding in
the protocol modules. Restrict cloud settings to registered blocks.

Type checking and the save CLI ran successfully. In-game acceptance
is pending.
2026-11-25 08:26:11 +08:00
N0VAN0M4LY 58241a513f Require explicit accounts and register GUI script edits
Reject game requests whose token or account hint cannot be resolved
and require a valid explicit user ID for web mutations. Remove the
entitlement action without a verified client call site.

Register the loopback store URL script edit and require a unique match
during pack construction. Type checking and patch loading passed.
In-game acceptance is pending.
2026-11-25 08:08:29 +08:00
N0VAN0M4LY 929e4b1e78 Persist cloud settings with each local save 2026-11-25 07:59:47 +08:00
N0VAN0M4LY 2e2c4a5234 Add local squadrons, activity, and squadron vehicle research 2026-11-25 07:47:33 +08:00
N0VAN0M4LY 3cacb34422 Add external inventory, marketplace, and supply chests
Define external inventory items and support GJN purchases, recycling,
and supply chest drops.
2026-11-25 07:19:07 +08:00
N0VAN0M4LY cfa6c04aa6 Add GJN balances, the local store, and redemption codes
Support currency and entitlement purchases, including packs, from the
local store and the in-game payment flow. Expose the supported
redemption codes.
2026-11-25 06:33:41 +08:00
N0VAN0M4LY d95a5d8f0c Complete local HTTPS handling and allow shared log reads
Use the loopback service certificate for the offline HTTPS path. Retain
original host names for host-based routing and allow the network log
to be read while the client is running.
2026-11-25 06:05:20 +08:00
N0VAN0M4LY 6e11156b90 Preserve stock socket export ordinals
Keep the original ordinals for functions imported by number so Windows
can resolve the socket library imports during startup.
2026-11-25 05:04:28 +08:00
N0VAN0M4LY afb22c4f08 Route client traffic to the loopback service
Build the socket library and client-local port configuration for redirecting
traffic to the offline service. Accept HTTPS and the existing matching and
HTTP protocols on the same port. Route requests by the original host.
2026-11-25 05:02:34 +08:00
N0VAN0M4LY ae6958f291 Add classic items and fix initial showcase responses
Store and activate boosters, personal discounts, wagers, and universal
spares. Apply active personal discounts when pricing vehicle purchases.
Return the server time and default fields for every showcase type.

Add developer commands for inspecting game logs, strings, references,
callers, and disassembly.
2026-11-25 04:17:34 +08:00
N0VAN0M4LY 76670121a9 Add unlock purchases and profile showcases
Load unlock prices from unlocks.blk and expose them in Common/unlocks.
Support purchasing unlocks and saving showcases, and count qualified
crews for the ace showcase.

Read charRequestBlk action parameters from HTTP headers and apply this
to cln_get_users_terse_info.
2026-11-25 02:49:13 +08:00
N0VAN0M4LY c971dad167 Fix modification status and support weapon presets
Write modStatus in modsResearch so the client recognizes purchasable
modifications. Persist ownership and initial equipment state for free
modifications and quantities for free weapon presets.

Persist preset inventory in the weapon records and handle cln_buy_weapon
using the maximum quantity extracted from the game data.
2026-11-25 02:44:16 +08:00
N0VAN0M4LY 71c44a085d Save profile appearance and return player summaries
Persist titles, avatars, backgrounds, and frames. Return the corresponding
appearance fields in the player summary response.
2026-11-24 22:06:48 +08:00
N0VAN0M4LY 81d33f3048 Implement crew skills, qualifications, and training fees
Support spending crew skill points, buying skill point packs, and
purchasing expert and ace qualifications. Charge for training a crew on
an unfamiliar vehicle and expose the skill pack prices.
2026-11-24 22:05:15 +08:00
N0VAN0M4LY 391082278f Support purchasing cosmetics
Handle cln_buy_resource, persist ownership in resourcesInfo, and expose
the prices of skins, decals, and attachments.
2026-11-24 21:56:00 +08:00
N0VAN0M4LY c6c8f85ddd Save decal and attachment layouts
Handle cln_save_decals and cln_save_attachables and return the complete
updated layout block for the affected resource type.
2026-11-24 21:51:53 +08:00
N0VAN0M4LY 8692a13577 Add modification, ammunition, and spare vehicle actions
Include modification, weapon, and spare vehicle prices, omitting zero
prices. Recalculate modification research and ranks and handle research
target selection, purchases, bulk purchases, and equipment toggles.
2026-11-24 21:43:35 +08:00
N0VAN0M4LY 56731efa76 Wrap the price table in the Common block
Use the block expected by the client to fix zero vehicle prices.
Document hangar settings, modification state, and price table paths.
2026-11-24 21:34:31 +08:00
N0VAN0M4LY 7a08fff85e Implement vehicle research and purchases
Recompute unlocked ranks, prerequisites, and unit states before serving
profiles. Add research target selection, research conversion, vehicle
and slot purchases, and the price table. Support editing convertible RP
and restrict hidden vehicle visibility to eligible entries.

The client still displays zero purchase prices pending price table
integration.
2026-11-24 21:04:19 +08:00
N0VAN0M4LY 8b31277c58 Seed new saves and reveal hidden vehicles in the tech tree
Set initial Silver Lions and Golden Eagles balances and add a save
editing command. Open rank I for each nation and branch and migrate
older saves to format 3. Reveal eligible hidden vehicles while keeping
split air-defense launchers out of the tech tree.

Document the currency, rank, and unit status fields observed in the offline client.
2026-11-24 14:45:28 +08:00
N0VAN0M4LY 2fc28dd7a5 Grant reserve vehicles and support crew presets
Derive reserve vehicles from the stock economy data. Grant all reserves
and mark the basic takeoff and landing tutorials complete in new saves.
Apply the same grants through the format 2 migration.

Use shared crew slot rules for first-run selection, presets, training,
assignment, and removal.
2026-11-24 14:18:02 +08:00
N0VAN0M4LY 40af06edad Serve game modes from extracted mission data
Publish stable mode IDs and matching responses in the stock format.
Build the mission pools from the multiplayer mission data and provide
required fields and localized names. Load datasets before listening and
reuse cached results when the source file digests match.

Preserve invalid UTF-8 bytes when round-tripping BLK strings and names.
The game mode list appeared in the offline client.
2026-11-24 11:02:30 +08:00
N0VAN0M4LY 6ed498e4d0 Support first-run selection and optional tutorials
Save the selected country, starting crew, and unlocks when the client
submits its first-run selection. Use the stock unlock and crew formats.
Enable the existing option to skip the basic tutorial.

The client reached the hangar. Tutorial verification is pending.
2026-11-24 10:01:47 +08:00
N0VAN0M4LY c3c5f583ad Persist EULA acceptance
Persist the accepted EULA version before responding and return both
agreement fields in the profile. Respond to matching heartbeats.
2026-11-24 09:05:31 +08:00
N0VAN0M4LY ce389c2154 Return matching clusters in the stock response envelope
Return recognizable regions from fetch_clusters_list and place matching
results in data.data. Document the handshake, heartbeat, and EULA
requirements. The offline client remains logged in after the cluster reply.
2026-11-24 08:44:44 +08:00
N0VAN0M4LY 5a1fd594e0 Handle matching login and decorative content manifests
Add matching frame and message handling, per-connection session
encryption, and loopback traffic dispatch. Serve the decorative content
manifest and empty indices to remove startup download waits.

Resolve character requests to their explicit account ID, include the
nickname in profile replies, and redact matching traffic logs.
2026-11-24 08:12:40 +08:00
N0VAN0M4LY 18f63bf33e Implement local login
Route login and character requests by their original host names on one
loopback port. Add local accounts, saves, and credential redaction.
2026-11-24 05:01:26 +08:00
N0VAN0M4LY 5421268fbf Build a loopback client copy with TypeScript
Add the shared BLK, VROMFS, executable patch, and build packages. Preserve
typed fields and shared name tables when reading BLK data. Rewrite the
service endpoints in place so the original environment names remain
available to the client, then build the client copy.
2026-11-24 00:35:13 +08:00
N0VAN0M4LY 0117c02677 Restore the build tools and define the workspace layout
Restore the reviewed pack, PE, and patch tooling. Specify a TypeScript
build pipeline, a type-preserving BLK codec, and a configurable loopback
port selected at launch. Document the package boundaries.
2026-11-24 00:19:04 +08:00
N0VAN0M4LY 65f9377f24 Archive the prototype and map the hangar request flow
Archive the earlier backend, client, build, and patch definitions. Document
the stock login and profile requests required to reach the hangar, along
with the profile structure and the relevant configuration blocks.
2026-11-24 00:07:51 +08:00
N0VAN0M4LY e094131a7a Define the local server architecture
Describe how the stock client can handle login and profiles with a
loopback service using the native protocols. Record the service endpoints,
login and profile flow, and character action inventory. Update the feature
checklist and archive the replaced design material.
2026-11-23 23:49:19 +08:00
N0VAN0M4LY b6d72f4792 Add Quirrel script checks and a GUI build command
Compile the upstream Quirrel checker with MSVC and invoke syntax and
static analysis for each input file. Treat reported errors and warnings
as failures because the checker can return a zero exit code for them.

Split the command line by purpose and add GUI pack construction from
declared edits and injected scripts. Verify the checker against stock
scripts and invalid inputs, and confirm that patch checks still run.
2026-11-23 14:36:15 +08:00
N0VAN0M4LY 8fa50b7804 Add the executable patch engine and local archive compatibility
Keep patch definitions and dependencies separate from the patch engine.
Resolve all patches before writing, verify expected bytes, and refuse to
overwrite the input executable. Include a read-only check command for
comparing definitions with their assembly source.

Allow locally rebuilt script archives to load in the offline client.
Verify the patch against the 2.61.0.37 executable and confirm that the
patched copy remains readable as PE.
2026-11-23 13:32:36 +08:00
N0VAN0M4LY c9e10b0db7 Read and rebuild VROMFS script packs
Split container handling from the file table and add a read-only PE view
for the patch engine. Apply declarative script edits at unique anchors and
preserve the input line endings and unmodified bytes.

Round-trip the 2.61.0.37 GUI pack byte-for-byte and verify that invalid
edit definitions and ambiguous matches are rejected.
2026-11-23 13:19:27 +08:00
N0VAN0M4LY 3dac2ca6ed Standardize terminology and document patch design criteria
Use standard names for executable patches, adapters, and subscriptions.
Document how each change follows from a feature requirement and how
dependencies and generated code are represented. Mark the feature list
entries whose implementation still needs investigation.
2026-11-23 11:13:15 +08:00
N0VAN0M4LY b26de2651b Initialize the offline project workspace
Add a TypeScript backend skeleton with a health endpoint and read-only
PE analysis tools for the target client.

Ignore game files, build outputs, saves, logs, and virtual environments.
2026-11-23 09:21:52 +08:00
687 changed files with 2423 additions and 82650 deletions

No files matched your search

-29
View File
@@ -1,29 +0,0 @@
## 简体中文
`v0.1.0` 是 WTOffline 启动器的首个公开版本。
### 主要功能
- **本地人机对局。** 在支持的陆战、空战和海战模式中与 AI 队友和对手交战。对局结束后可以查看结算和回放。
- **离线机库与成长。** 组建编队、研发载具和改装件、训练乘员,并使用本地商店与交易所。
- **客户端、存档和数值。** 管理多个离线客户端,备份、恢复和迁移存档,调整对局、收益和研发数值。
- **内置更新检查。** 在「关于」检查启动器和适配包更新。启动器会验证下载的适配包签名,通过后启用。
### 客户端兼容性
已在 `2.61.0.37`、`2.61.0.43` 和 `2.61.0.55` 上实机验证。补丁会根据客户端文件内容查找匹配位置,因此也可能适配之后的其他小版本更新。
## English
`v0.1.0` is the first public release of the WTOffline Launcher.
### Highlights
- **Local battles with AI.** Play supported ground, air, and naval modes with AI teammates and opponents. View your results and replays after a battle.
- **Offline hangar and progression.** Build lineups, research vehicles and modifications, train crews, and use the local store and marketplace.
- **Clients, saves, and tuning.** Manage multiple offline clients, back up, restore, and transfer saves, and adjust battle, reward, and research settings.
- **Built-in update checks.** Check for launcher and adaptation pack updates under **About**. The launcher verifies each downloaded pack's signature before enabling it.
### Client compatibility
Tested in-game with client versions `2.61.0.37`, `2.61.0.43`, and `2.61.0.55`. The patches match patterns in the client files, so they may also work with other later minor updates.
-35
View File
@@ -1,35 +0,0 @@
## 简体中文
> **重要升级提示:** 所有使用 **Gaijin 官方独立版客户端**,或者 **Steam 版但曾经通过官方启动器(更新器)启动过游戏** 的用户,**必须更新到 `v0.1.1` 启动器**(更新后请对已有离线副本重新执行一次「构建客户端」)。旧版启动器在存在官方清单 `content/warthunder.blk` 时会触发游戏拉起官方启动器并还原离线补丁,导致启动闪退、弹出官服更新或报原版备份不一致。
`v0.1.1` 是 WTOffline 启动器的重要维护更新,重点修复官方客户端/官方启动器用户无法正常启动的问题、修复对局中非本机载具受损提示串台,并增强启动稳定性与故障诊断能力。
### 修复与改进
- **解决官方独立版 / 官方启动器拉起官服更新的问题。** 启动参数新增 `-skip_pkg_validation`,跳过 `aces.exe` 启动时对官方 `content/warthunder.blk` 的文件体积校验;同时新增可执行文件隔离补丁,阻止游戏在异常情况下拉起官方 `launcher.exe -fullcheck` 联网覆盖离线文件,修复“启动数秒后以退出码 `1` 退出 → 弹出官服更新 → 离线文件被还原/报备份不一致”的死循环。
- **局内受损提示与敌方部件归属。** 修复空战与现代陆战中 AI 载具航电、传感器、雷达、红外干扰和瞄准吊舱受损时错误向玩家弹出白字提示(及误退光电视角)的问题;过滤陆战与海战右侧敌方部件损毁列表及特殊命中反馈中的非本机攻击记录,保留本机在途弹药与观战视角显示。
- **启动与写盘稳定性。** 游戏补丁文件写入改为临时文件原子替换并带短暂占用重试,降低安全软件实时扫描导致写入失败的风险;优化 `wto_ws.dll` 加载时的钩子批量启用流程,减少初始化期的线程冻结次数并记录详细错误码。
- **原版备份检测与报错。** 修复旧版 `wtoffline\stock` 备份在客户端更新后遮蔽实际版本、无法自动刷新的问题;启动时区分「原版文件备份缺失/损坏」与「版本不一致」,并在日志中记录双方实际版本号。
- **启动前检查与诊断导出。** 启动游戏前核对核心文件是否可读(提前提示可能被安全软件隔离);异常退出时在启动器日志记录现场文件状态与带十六进制的系统退出码;导出的诊断 ZIP 自动附带 `wto_ws.log`、最新一份游戏 `.clog` 日志和环境摘要(不含玩家存档)。
### 客户端兼容性
支持已核对版本 `2.61.0.37`、`2.61.0.43` 和 `2.61.0.55`(自带补丁集 `2026.12.02`),并支持按特征码自动尝试适配后续小版本更新。
## English
> **Important upgrade notice:** All users on the **standalone Gaijin client**, as well as **Steam users who have ever launched the game through the official Gaijin launcher/updater**, **must upgrade to `v0.1.1`** (and rebuild existing offline copies after updating). On earlier launcher versions, the presence of `content/warthunder.blk` causes `aces.exe` to spawn the official launcher and overwrite patched offline files, resulting in startup exit code `1`, official updater popups, or stock-backup version mismatches.
`v0.1.1` is an important maintenance release of the WTOffline Launcher that fixes startup failures on standalone/official-launcher clients, fixes cross-unit battle damage notices, improves launch reliability, and strengthens crash diagnostics.
### Fixes and improvements
- **Skip startup package validation and block official launcher spawns.** Added `-skip_pkg_validation` to offline launch arguments so `aces.exe` skips the startup `content/warthunder.blk` file-size integrity check, and added an executable isolation patch that blocks `aces.exe` from spawning the official `launcher.exe -fullcheck` updater. This eliminates the loop where the game exits with code `1`, opens the official launcher, and overwrites offline files back to the online build.
- **In-battle damage notices and enemy parts feedback.** Fixed AI avionics, sensor, radar, RWR/countermeasures, and targeting-pod failures in air and modern ground battles incorrectly showing white damage notices (or forcing the player out of optic view). Filtered non-local AI-on-AI hits out of the ground/naval enemy damaged-parts list and special hit-camera events while preserving in-flight player munitions and spectator views.
- **Launch and file-write reliability.** Rebuilt game files are now written via temporary files with atomic rename and brief retry on transient antivirus locks. Batched MinHook activation in `wto_ws.dll` into two passes to cut startup thread-freeze cycles and log detailed `MH_STATUS` diagnostics on failure.
- **Stock backup detection and errors.** Fixed stale `wtoffline\stock` backups masking an externally updated client and blocking backup refresh. Launch checks now distinguish missing/unreadable backups from version mismatches and log the exact copy and backup versions.
- **Pre-launch checks and richer diagnostics.** Verify core launch files before starting `aces.exe` (flagging possible antivirus quarantine early), log post-exit file snapshots and hex-annotated Windows exit codes, and include `wto_ws.log`, the latest `.clog`, and a metadata summary (without player saves) in exported diagnostic ZIPs.
### Client compatibility
Verified with client versions `2.61.0.37`, `2.61.0.43`, and `2.61.0.55` (bundled patch set `2026.12.02`), with pattern-based matching for later minor updates.
-27
View File
@@ -1,27 +0,0 @@
## 简体中文
`v0.1.2` 是 WTOffline 启动器的维护更新,重点放开「节省空间的复制」对游戏版本的硬锁定、修复维护页更新客户端时的路径校验误报,并内置 `2.61.0.58` 版本核对记录。
### 修复与改进
- **省空间复制改为跨版本规则。** 取消原先绑定单一版本号(`2.61.0.43`)与 8 MiB 体积门槛的静态哈希清单,改为基于只读资源规则自动共用 `content/` 与 `content.hq/` 下的 `.dxp.bin` 和 `.grp` 资源包;小版本更新后无需等待新清单即可继续省空间安装或转换,且同卷省空间客户端执行「从在线版更新」时会保持或重建硬链接,不再拆分为完整复制。
- **修复维护页「从在线版更新」误报路径越界。** 扫描安装来源时排除顶层残留的 `wtoffline` 目录;安装向导第 3 步与后台同步拦截将数据目录设为客户端目录或其父目录的配置,并解除旧安装把数据目录放在客户端父目录时的误报;所有路径安全校验失败均在启动器日志中记录具体原因与路径以便排查。
- **「关于」页快速导出日志与关闭日志开关。** 在「关于」页新增「保存日志 ZIP…」快捷按钮(导出内容同时纳入最新一份内置浏览器 `-browser.log`,仍不含玩家存档),并在「设置 → 诊断」新增「生成运行日志」开关,允许关闭启动器日志、本地服务器流量日志及 `wto_ws.log` 的磁盘写入。
### 客户端兼容性
支持已核对版本 `2.61.0.37`、`2.61.0.43`、`2.61.0.55` 和 `2.61.0.58`(自带补丁集 `2026.12.02`),并支持按特征码自动尝试适配后续小版本更新。
## English
`v0.1.2` is a maintenance release of the WTOffline Launcher that makes space-saving copies resilient across minor game updates, fixes false path-scope errors during client updates, and bundles the `2.61.0.58` version check record.
### Fixes and improvements
- **Version-independent space-saving copies.** Replaced the single-version (`2.61.0.43`) SHA-256 manifest and 8 MiB cutoff with declarative read-only asset rules covering `.dxp.bin` and `.grp` archives under `content/` and `content.hq/`. Space-saving installs and conversions now keep working across minor updates, and updating a same-volume space-saving client preserves or recreates hard links instead of detaching them into full copies.
- **Fix false `maintenance_location` errors when updating.** Ignore stray top-level `wtoffline` folders when scanning a stock source, prevent picking a data folder that equals or contains the client folder during installation (with inline Step 3 validation), stop blocking updates when an existing installation placed `dataPath` at an ancestor of the client folder, and log the exact reason and paths on every path-scope rejection.
- **Quick log ZIP export on About and runtime logging toggle.** Added a quick "Save log ZIP…" button on the About page (now also bundling the latest embedded browser `-browser.log`, still excluding saves), and added a "Record runtime logs" toggle under Settings → Diagnostics to stop writing launcher logs, local server traffic logs, and `wto_ws.log`.
### Client compatibility
Verified with client versions `2.61.0.37`, `2.61.0.43`, `2.61.0.55`, and `2.61.0.58` (bundled patch set `2026.12.02`), with pattern-based matching for later minor updates.
-97
View File
@@ -1,97 +0,0 @@
## 简体中文
`v0.1.3` 是 WTOffline的一次大型功能更新,正式引入**第一版模组系统(开放社区模组制作)**、初步接通**原子雷霆**模式,并包含多项对局机制、存档容量、贴花导入与更新链路修复。
### 该下载哪一个文件?
- **绝大多数玩家**:下载 **`wtoffline-launcher-0.1.3-win-x64.exe`** ,下载后安装即可。
- **想要免安装 / 解压即用**:下载 **`wtoffline-launcher-0.1.3-win-x64-portable.zip`** ,解压到任意目录后运行其中的启动器即可。
### 重点新功能
- **第一版模组系统与开放模组制作(实验性)。**
- 启动器新增「模组」管理页:支持为每个客户端独立开关模组、调整加载顺序、保存/切换模组方案以及自定义模组目录,并可直接一键打开完整模组开发文档。
- 支持客户端数据包增量覆写(BLK / CSV / 附加包挂载,且核心隔离补丁受保护不可被误覆盖)、服务端 JS/TS 脚本钩子与独立模组数据存储,以及数值列表增量修改。
- 内置并首次自动生成 3 套官方示例模组模板(含可直接使用的「官方地图选择器」、服务端脚本示例与载具参数微调示例),配套完整中英文 `mod-dev-docs` 开发手册,欢迎玩家与创作者制作并分享自己的模组。
- **接通「原子雷霆」模式。**
- 完整接入空战历史子模式「原子雷霆」的专用 HUD、阶段推进门槛、不限出击次数与机场独立冷却机制,并按 10 国与房间权重自动分配战术核弹载机(5 kt / 30 kt)。
- 在启动器「数值 → 对局」新增「原子雷霆战略核轰炸机」开关(默认开启),可在阶段 3 追加战略核轰炸机(`B-52H` / `Tu-95M`)。
### 修复与改进
- **对局与战斗体验**:
- 恢复陆战街机空中支援事件(呼叫战斗机 / 攻击机 / 轰炸机);
- 修复本地主机下玩家乘员技能与专家 / 王牌资格在战局内未生效的问题;
- 恢复空战街机模式下的空中重新装填弹药;
- 修复部分载具出生时改装件效果反转,以及单弹链航空武器被未选中的隐身弹链覆盖导致无曳光弹的问题;
- 恢复对战模式飞机有限燃油消耗与油量倒计时,并修复局内小队黄色标记;
- 支持在机库切换并保存载具的可选分房权重(如部分直升机 / 挂载升档),开局按所选权重参与匹配;
- 修复空战街机等多槽模式下 AI 飞机重生次数受限,以及坦克 AI 重生次数配置未对全部模式生效的问题(感谢 `duduyagame`);
- 修复新手教程完成进度未保存的问题:通关后重启不再反复提示教程,并按原版规则发放首次通关的贴花、基础教程金鹰及各难度银狮奖励(感谢 `duduyagame`)。
- **启动器、存档与更新链路**:
- 修复新版在线客户端贴花与可下载涂装缓存导入失败的问题(兼容现行 `regional.vromfs.bin` + `.ddsx` 及旧版缓存格式);
- 修复全车库改装件总数超过 65,535 个时的存档溢出问题;
- 将启动器「存档 → 载具和研发」中的「全部研发」与「获得常规载具」合并为一步到位的「全部研发并购买」;
- 优化默认更新线路并保留 GitHub 自动回退,全流程继续保持 Ed25519 签名校验;
- 「关于」页改版为双栏布局,新增「项目主页」与「Discord」快捷入口,修复切换页面时维护进度丢失的问题。
### 社区交流与模组分享
欢迎加入 WTOffline 官方 Discord 服务器,一起交流玩法、反馈 Bug、分享你的调参或自制模组,并关注最新客户端适配进度:
- **Discord 社区**:https://discord.gg/P566xWNpEs
- **项目主页**:https://wto-project.net
### 客户端兼容性
支持已核对版本 `2.61.0.37`、`2.61.0.43`、`2.61.0.55` 和 `2.61.0.58`,并支持按特征码自动尝试适配后续小版本更新。
---
## English
`v0.1.3` is a major feature release of WTOffline introducing the **first version of the experimental Mod System** (opening up community mod authoring), Add support for **Nuclear Escalation**, and a broad set of battle, save, decal import, and launcher fixes.
### Which file should I download?
- **Most players (Recommended)**: Download **`wtoffline-launcher-0.1.3-win-x64.exe`** — the standard Windows installer with built-in automatic update checks.
- **No-install / Portable**: Download **`wtoffline-launcher-0.1.3-win-x64-portable.zip`** — extract anywhere and run the launcher directly.
### Highlights
- **Experimental Mod System v1 & Mod Authoring.**
- New **Mods** page in the launcher with per-client enablement, load-order management, presets, custom mod repository folder, and a quick-open button for the mod developer handbook.
- Supports additive client archive overlays (BLK / CSV / addon mounts while protecting essential isolation patches), server-side JS/TS lifecycle hooks with isolated mod storage, and tuning list operations.
- Ships with 3 bundled example mod templates (including a ready-to-use **Official Map Selector**, a server script example, and a vehicle tweak example) plus full bilingual documentation in `mod-dev-docs/`.
- **Nuclear Escalation mode.**
- Full support for Air Realistic sub-mode **Nuclear Escalation**, including custom HUD, stage thresholds, unlimited respawns, per-airfield cooldowns, and nation-matched tactical nuclear carriers (5 kt / 30 kt) scaled to room BR.
- Added a **Nuclear Escalation strategic bombers** toggle under **Tuning → Battle** (enabled by default) to unlock stage-3 strategic nuclear bombers (`B-52H` / `Tu-95M`).
### Fixes and improvements
- **Battles & gameplay**:
- Restored Ground Arcade air support events (fighters, attackers, bombers).
- Fixed player crew skills and Expert / Ace qualifications not applying on the local host.
- Restored in-flight ammunition reload in Air Arcade.
- Fixed inverted modification effects on spawn and single-belt aircraft tracers being overwritten by unselected stealth belts.
- Restored limited fuel consumption / HUD fuel timer in versus modes and yellow squad target markers.
- Persisted selectable battle ratings for units with BR-changing modifications and applied them during matchmaking.
- Fixed AI aircraft respawn limits in Air Arcade and other multi-slot modes, and applied configured ground AI respawn counts across all modes (thanks to `duduyagame`).
- Persisted stock training/tutorial completion progress so finished tutorials no longer re-prompt after restart, and granted one-time first-completion decals, basic tutorial Golden Eagles, and per-difficulty Silver Lions rewards (thanks to `duduyagame`).
- **Launcher, saves & updates**:
- Fixed online decal and downloadable skin cache import on modern 2.61 clients (supports both `regional.vromfs.bin` + `.ddsx` and legacy cache layouts).
- Fixed save overflow when total owned modifications exceed 65,535 by splitting across native sibling blocks.
- Merged "Research all" and "Grant regular vehicles" into a single **Research and buy all** action in the launcher.
- Improved default release update routing with automatic GitHub fallback and continued Ed25519 signature verification.
- Updated the About page to a two-column layout with **Project homepage** and **Discord** buttons, and preserved copy maintenance progress across tab switches.
### Community & Mod Sharing
Join the official WTOffline Discord server to chat, report issues, share tuning presets or custom mods, and follow client adaptation updates:
- **Discord**: https://discord.gg/P566xWNpEs
- **Homepage**: https://wto-project.net
### Client compatibility
Verified with client versions `2.61.0.37`, `2.61.0.43`, `2.61.0.55`, and `2.61.0.58`, with signature-based matching for later minor updates.
-101
View File
@@ -1,101 +0,0 @@
## 简体中文
`v0.1.4` 带来**实验性新版陆战 AI(第一阶段)**、启动器全新**「Bot 参数」调参页(含陆战 AI 出车权重)**、**Dagor 风格 `.blk.patch.blk` 模组补丁引擎**,以及多项对局伤害反馈、改装件批量购买与启动器便携更新修复。
### 该下载哪一个文件?
- **绝大多数玩家**:下载 **`wtoffline-launcher-0.1.4-win-x64.exe`**,下载后直接安装即可(覆盖安装保留全部存档与配置)。
- **想要免安装 / 解压即用**:下载 **`wtoffline-launcher-0.1.4-win-x64-portable.zip`**,解压到任意目录后运行其中的启动器即可。
### 重点新功能
- **实验性新版陆战 AI(第一阶段,默认启用)。**
- 引入全新的模块化陆战 AI 架构:包含整队指挥层与任务单(按坚守 / 征服 / 制霸模式分配进攻、侧翼、架枪与防空角色,支持分路包抄、集结出发、占点回防与防空阵位)、曝光积分视觉感知与唯一弹道开火许可门(含植被透光、硬遮挡弹道扫掠与友军走廊防误伤)、单车车体状态机(短停射击预算、掩体装填回缩、摆角、僵持换位与受损维修)、本车目击测速提前量与失联守出口,以及按待发架容量配置主/副双弹种出生装弹与局内自动切弹。
- 当前为第一阶段实验版本,默认以完整模式(`full`)运行并持续调优中;若遇到寻路或行为异常,可随时在启动器「数值 → Bot 参数」切回「原版 AI(`stock`)」。
- 移动射击的车速上限随距离缩短而提高。车辆会主动减速,持续无法开火时可短停争取一炮,瞄准也改为按跟踪目标的误差判断。同步更新了出车权重、感知、占点与车体动作的默认参数。
- **启动器新增「数值 → Bot 参数」页面。**
- 统一集中管理陆战 AI 模式切换、AI 坦克 / 飞机重生次数、每类载具候选池上限、**陆战 AI 出车权重**(中坦 / 主战、重坦、坦歼、轻坦、防空车、其他)与出生携弹策略。
- 同时以折叠分组开放全部陆战 AI 进阶参数(指挥配额、占点宏观、状态机、视觉感知、测速偏差、火控开火门、机动寻路、编队避让与地形约束),支持参数校验与一键恢复默认值。
- **模组系统新增 Dagor 风格 `.blk.patch.blk` 与 `include` 编译支持。**
- 支持原生风格的 `*.blk.patch.blk` 与 `client/config-blk.patch.blk` 增量补丁、编译期 `include` / `includeOnce` 展开,以及 Dagor `@` 指令(`@override`、`@replace`、`@delete`、`@clone`、`@inherit`、`@after`、`@before` 等),同时完全保留 `*.blk.patch.jsonc` 兼容。
- 同步重写并补齐中英双语开发者手册(`dev-docs/`)与模组制作手册(`mod-dev-docs/`)。
### 修复与改进
- **对局伤害反馈与改装件**:
- 修复空战右下角敌机部件受损播报串台(仅显示本机及观战目标,不再混入 AI 互打记录)以及空战持续命中时重复普通命中丢失的问题;
- 修正普通命中与跳弹等引擎判定无效命中的奖励分类,并修正右侧部件受损反馈的攻击者与收件人归属;
- 修复机库一键「购买所有已研发改装件」时因前置依赖状态与价格核算不一致报「角色服务器内部错误」的问题。
- **对局奖励与备用载具**
- 空战街机可因伤害或摧毁敌方小基地获得个人分,摧毁奖励也会列入战后明细。
- 修复重生界面中已购买的单车备用载具显示。每日免费出击、单车备用和通用备用按实际成功出击结算。
- 修复部分任务单位击杀被误计为首杀的问题,并加固助攻事件处理。
- **启动器维护、便携版更新与界面**:
- 客户端维护页新增「设置 / 更换在线版安装来源」,方便在线版移动目录后继续一键增量更新;
- 复制安装与「从在线版更新」自动跳过并保留玩家自定义内容目录(`UserSkins`、`UserSights`、`WarThunderCDK` 与启动器日志),避免更新覆盖自制涂装或瞄具;
- 复制安装与增量更新会跳过下载不完整的超清材质包(UHQ)。已有离线客户端遇到残缺材质包时,启动器会在启动前提示处理。
- 修复便携版原地更新在 Windows 下的文件复制、Electron `.asar` 检查冲突与进程分离重启问题,并防止客户端或数据目录嵌套于启动器安装目录内;
- 更新日志改为支持 Markdown 排版的弹窗展示。
### 社区交流与反馈
欢迎加入 WTOffline 官方 Discord 服务器,反馈新版陆战 AI 实机体验、分享你的 Bot 调参或自制模组,并关注最新客户端适配进度:
- **Discord 社区**:https://discord.gg/P566xWNpEs
- **项目主页**:https://wto-project.net
### 客户端兼容性
支持已核对版本 `2.61.0.37`、`2.61.0.43`、`2.61.0.55` 和 `2.61.0.58`,并支持按特征码自动适配后续小版本(已在 `2.61.0.60` 通过静态与构建核对)。
---
## English
`v0.1.4` introduces the **experimental Ground AI Rebuild (Phase 1)**, a new **Bot parameters** page in the launcher (including **ground AI vehicle class weights**), **Dagor-style `.blk.patch.blk` mod patching**, and a set of battle damage feedback, bulk modification purchase, and portable updater fixes.
### Which file should I download?
- **Most players (Recommended)**: Download **`wtoffline-launcher-0.1.4-win-x64.exe`** — the standard Windows installer with built-in automatic update checks (safe to install over previous versions; preserves all saves and tuning).
- **No-install / Portable**: Download **`wtoffline-launcher-0.1.4-win-x64-portable.zip`** — extract anywhere and run the launcher directly.
### Highlights
- **Experimental Ground AI Rebuild (Phase 1, enabled by default).**
- Introduces a modular custom ground AI architecture: a team commander & task orders (mode-aware Assault / Flank / Overwatch / SPAA role quotas for Battle, Conquest, and Domination with flank lanes, rally staging, cap recall, and air-aware SPAA positioning), exposure-based visual perception and a single ballistic fire gate (foliage transparency, hard-cover ballistic sweeps, and friendly-fire corridor protection), a hull state machine (short-halt budget, cover reload retreat, angling, stalemate repositioning, and damage repair), sample-based velocity lead estimation with last-seen exit watch, and ready-rack dual-ammo bot spawn loadouts with automatic shell switching.
- Ships in `full` mode by default for testing and live tuning; if you run into pathing or behavior issues, you can switch back to **Stock AI (`stock`)** anytime under **Tuning → Bot parameters**.
- The speed limit for firing on the move rises as targets get closer. Bots slow down and can briefly stop when they cannot fire while moving. Aim stability now uses tracking error. Vehicle weights, perception, capture assignments, and hull behavior also have updated defaults.
- **New "Tuning → Bot parameters" page in the launcher.**
- Brings together ground AI mode selection, AI tank / aircraft respawn limits, per-type AI pool cap, **ground AI vehicle class weights** (Medium/MBT, Heavy, TD, Light, SPAA, Other), and spawn ammunition rules in one place.
- Exposes all advanced ground AI tuning sections in collapsible groups (commander, macro, state machine, perception, tactics, estimation, fire control, navigation, crowd, terrain, and runtime cadence/diagnostics) with validation and one-click section reset.
- **Dagor-style `.blk.patch.blk` & compile-time `include` support for mods.**
- Supports native-style `*.blk.patch.blk` and `client/config-blk.patch.blk` incremental patching, `include` / `includeOnce` expansion, and Dagor `@`-directives (`@override`, `@replace`, `@delete`, `@clone`, `@inherit`, `@after`, `@before`, etc.) while maintaining full backwards compatibility with `*.blk.patch.jsonc`.
- Rewrote and expanded both the bilingual Developer Handbook (`dev-docs/`) and Mod Developer Handbook (`mod-dev-docs/`).
### Fixes and improvements
- **Battle feedback & modifications**:
- Fixed Air battle bottom-right enemy part damage feed bleed-through from AI-vs-AI fights (now filtered to the local player or spectated unit) and stopped dropping repeated normal hits on aircraft.
- Corrected normal hit vs. ineffective hit (e.g., ricochet) award classification and right-side component damage feedback ownership.
- Fixed "Internal character server error" when clicking **Buy all researched modifications** by emitting native `RESEARCHED` status for prerequisite chains and aligning bulk pricing.
- **Battle rewards and backups**
- Damaging or destroying enemy mini-bases in Air Arcade now awards personal score. Base destruction rewards appear in the post-battle breakdown.
- Fixed how purchased vehicle backups appear in the respawn screen. Daily free spawns, vehicle backups, and universal backups are accounted for after a confirmed spawn.
- Fixed some mission-unit kills being counted as the first player kill and tightened assist event handling.
- **Launcher maintenance, portable updater & UI**:
- Added support for setting or changing the online client update source on the client maintenance page.
- Skipped and preserved player-created folders (`UserSkins`, `UserSights`, `WarThunderCDK`, and launcher logs) when copying or updating from the online client.
- Copy installs and incremental updates skip incomplete Ultra High Quality (UHQ) texture packs. The launcher flags incomplete packs in existing offline installations before starting the client.
- Fixed portable in-place updates on Windows (`original-fs`, removing unused `default_app.asar`, detached `Start-Process` relaunch) and guarded against nested launcher/data directories.
- Rendered launcher release notes in a dedicated Markdown modal.
### Community & Feedback
Join the official WTOffline Discord server to share feedback on the new ground AI, post custom Bot tuning presets or mods, and follow client adaptation updates:
- **Discord**: https://discord.gg/P566xWNpEs
- **Homepage**: https://wto-project.net
### Client compatibility
Verified with client versions `2.61.0.37`, `2.61.0.43`, `2.61.0.55`, and `2.61.0.58`, with signature-based matching for later minor updates (static and build checks pass on `2.61.0.60`).
-89
View File
@@ -1,89 +0,0 @@
## 简体中文
`v0.1.5` 是一次集中维护与修复版本,重点解决 **空战坠机后偶发崩溃(`0xC0000374`)**、**备用载具无法出击与扣减失效**、**单车涂装/挂载/弹链与配平未保存**、**联队时间与 20,000 研发点上限异常**、**贴花缓存缺失导致大面积无法显示**,以及 **启动器客户端移除防误删与安装体验改进**。
### 该下载哪一个文件?
- **绝大多数玩家(推荐)**:下载 **`wtoffline-launcher-0.1.5-win-x64.exe`**,直接覆盖安装即可(保留全部存档与配置)。
- **想要免安装 / 解压即用**:下载 **`wtoffline-launcher-0.1.5-win-x64-portable.zip`**,解压到任意目录后运行其中的启动器即可。
### 重点修复
- **对局与战斗**:
- 修复空战与核战冲突中飞机坠毁后 0.1–4 秒内偶发堆损坏崩溃(`0xC0000374`)的问题:新增原生模块 `local_mp_air_ai_sync`,在本地主机下串行化 AI 飞机队列扩容操作,同时保留多核并行物理更新;
- 修复战局内选择备用载具后无法点击出击,以及陆战 / 海战载具因内部路径前缀导致备用载具结算扣减失效、未修车槽位被误拦的问题;
- 修复新版陆战 AI 在单人试驾中错误接管靶车的问题,限定仅在多人对局中运行。
- **档案、联队与商店**:
- 修复载具涂装、挂载预设、弹链选择以及试飞配平(副翼 / 升降舵 / 方向舵)在重启后未保存的问题(感谢 `duduyagame`);
- 修复联队活跃度下次结算时间与排行榜赛季时间显示为 1970 年的问题;预置普通联队补齐 58–60 名 NPC 成员以恢复 20,000 周期研发点上限,接通对局活跃度累计与 3 天周期结算,并在 `tuning/clans.jsonc` 开放初始周期与初始活跃度配置(默认 `0`);
- 解除部分联动促销载具(`bf-109c_1_promo`、`us_m4_sherman_promo`、`jp_destroyer_hatsuzuki`)的跨平台促销锁定,支持在科技树直接订购;
- 免扣款支付按钮默认名称改为「直接获取」(`Direct Claim`),并可在 `tuning/store.jsonc`(`freePaymentLabel`)中自定义,同步热生效于游戏内支付弹窗、内置商城和内置交易所。
- **贴花缓存与涂装索引**:
- 修复从在线版导入贴花缓存时因部分 `.ddsx` 文件尚未缓存而导致贴花大面积读取失败的问题:构建时自动按实际缓存文件过滤索引、自动补齐缺失 LOD、未缓存标准贴花回退内置占位图并丢弃残缺涂装;
- 支持直接选择游戏根目录识别贴花缓存,安装向导可自动探测并预填在线版贴花缓存,客户端详情页新增一键从在线版来源导入贴花缓存。
### 启动器改进
- **更安全的客户端移除与还原流程**:
- 彻底拆分「从列表移除客户端」与「删除磁盘文件」,默认均不勾选;坏记录或已移动目录可直接安全移出列表;
- 新增 `wtoffline/client.json` 来源标记,仅允许对明确标记为独立副本 / 硬链接副本、非 Steam 且不与其他客户端来源目录重叠的目录执行删除;原地安装或无标记目录提供原子「还原原版文件并清理离线补丁」与「打开所在文件夹」入口。
- **安装进度与对话框体验**:
- 省空间复制进度条拆分展示实际写入字节与硬链接共享字节,并补充 Windows 资源管理器属性会重复统计硬链接空间的说明;
- 启动器所有分类文件 / 目录选择与导出对话框自动记住上次路径,并在原路径不存在时回退至最近的现存父目录。
### 社区交流与反馈
欢迎加入 WTOffline 官方 Discord 服务器反馈问题、分享调参配置或自制模组,并关注最新客户端适配进度:
- **Discord 社区**:https://discord.gg/P566xWNpEs
- **项目主页**:https://wto-project.net
### 客户端兼容性
支持已核对版本 `2.61.0.37`、`2.61.0.43`、`2.61.0.55` 和 `2.61.0.58`,并支持按特征码自动适配后续小版本(已在 `2.61.0.60` 通过静态与构建核对)。
---
## English
`v0.1.5` is a maintenance and bug-fix release addressing the **Air battle post-crash heap corruption (`0xC0000374`)**, **backup vehicle respawn and accounting issues**, **vehicle camouflage/loadout/trim persistence**, **squadron timestamps and 20,000 RP cap**, **decal cache missing-file failures**, and **safer launcher client removal and installation UX**.
### Which file should I download?
- **Most players (Recommended)**: Download **`wtoffline-launcher-0.1.5-win-x64.exe`** — the standard Windows installer with built-in automatic update checks (safe to install over previous versions; preserves all saves and tuning).
- **No-install / Portable**: Download **`wtoffline-launcher-0.1.5-win-x64-portable.zip`** — extract anywhere and run the launcher directly.
### Key Fixes
- **Battles & gameplay**:
- Fixed intermittent heap corruption crashes (`0xC0000374`) 0.1–4 seconds after aircraft crashes in Air battles and Nuclear Escalation via a new native module (`local_mp_air_ai_sync`) that serializes `TeamAiManager::addToUnsortedPlanes` on the local host while keeping multi-threaded aircraft updates intact.
- Fixed backup vehicles failing to respawn in LocalMP battles, normalized ground/naval unit path prefixes so backup deductions match correctly after battle, and stopped unrepaired crew slots from blocking backup spawns.
- Restricted the custom ground AI runtime to multiplayer battles so it no longer takes over target vehicles in single-player test drives.
- **Profile, squadrons & store**:
- Persisted per-vehicle camouflage, weapon preset, ammo belt selections, and test-flight trim preferences across restarts (thanks to `duduyagame`).
- Fixed 1970 timestamps for squadron activity rewards and leaderboard seasons, backfilled preset normal squadrons to 58–60 NPC members to restore the 20,000 RP period cap, wired battle RP into 3-day squadron activity cycles, and made initial periods/activity configurable in `tuning/clans.jsonc` (defaulting to `0`).
- Stripped cross-promotion locks from promo gift vehicles (`bf-109c_1_promo`, `us_m4_sherman_promo`, `jp_destroyer_hatsuzuki`) so they can be ordered directly from the tech tree.
- Changed the default free offline payment button label to **Direct Claim** (Chinese: 「直接获取」) and made it tunable via `tuning/store.jsonc` (`freePaymentLabel`) across the in-game payment dialog, local store, and local marketplace.
- **Decal & skin cache**:
- Fixed widespread decal load failures when importing partially cached online `cache/content` folders by filtering against locally present `.ddsx` files, repairing single-LOD hits, falling back uncached stock decals to built-in placeholders, and dropping incomplete downloadable skins.
- Added support for picking a game root folder directly, auto-detecting decal cache in the install wizard, and one-click import from the recorded online source in client details.
### Launcher Improvements
- **Safer client removal & stock restore**:
- Separated removing a client from the launcher list from deleting files on disk (both unchecked by default), allowing broken or missing entries to be removed cleanly.
- Added a `wtoffline/client.json` origin marker so disk deletion is only permitted for verified copy/hardlink clients outside Steam that do not overlap any registered source folder, plus an atomic **Restore stock files & clean offline patches** flow and **Open folder** action for in-place or unmarked directories.
- **Install progress & file pickers**:
- Split actual disk-copied bytes from hardlinked shared bytes in space-saving install progress, with a note explaining that Windows Explorer properties double-count hardlinked space.
- Remembered the last selected directory per category across all file/folder picker and export dialogs with automatic parent fallback.
### Community & Feedback
Join the official WTOffline Discord server to report issues, share custom tuning presets or mods, and follow client adaptation updates:
- **Discord**: https://discord.gg/P566xWNpEs
- **Homepage**: https://wto-project.net
### Client compatibility
Verified with client versions `2.61.0.37`, `2.61.0.43`, `2.61.0.55`, and `2.61.0.58`, with signature-based matching for later minor updates (static and build checks pass on `2.61.0.60`).
-61
View File
@@ -1,61 +0,0 @@
## 简体中文
V0.1.6 改进了陆战 AI 的驾驶和交战,加入空战全真无间断作战、陆战全真和空陆守卫模式。启动器新增乘员组编辑和独立的地图适配包更新入口。
### 陆战 AI 与地图适配包
- AI **按车宽选择行驶路线**,同队坦克尽量分路推进。遇到停着的车辆或残骸时会尝试绕行,反复受阻时会后退并重新规划路线。
- AI **记住敌人上次出现的位置**,优先盯住近处或正在攻击自己的威胁。射击时综合考虑视线、炮口方向和命中机会,必要时减速、短停或转动车体。固定主炮也会借助车体转向进入射界。
- **首个地图适配包** `2026.12.06` 基于 Steam `2.61.0.64` 制作,覆盖 57 张陆战地图,下载约 541 MB。地图包单独分发,发布后可在启动器「关于 → 地图适配包」检查更新并安装。缺少对应地图数据时默认沿用原版寻路。
### 对局与结算
- **空战全真**采用 15 个原版无间断作战(EC)任务,支持无限重生。**陆战全真**使用出生点数(SP)出击。
- **空战和陆战守卫**可进入离线对局,按编队权重选择任务。陆战守卫的敌方进攻波次由原版任务 AI 控制,友方守卫使用新版 AI。
- 修复核战冲突等无限重生模式的 AI 重生规则,以及玩家无限重生时被误要求支付银狮的问题。
- 空战历史和全真中的敌方小基地伤害与摧毁现在计入个人分和战果收益。陆战占点给实际参与完成占领的玩家计分,并纳入银狮和研发点结算。
- 修复陆战命中标记、换弹种提示和右侧部件受损提示混入与玩家无关的事件。修复自定义陆战 AI 坦克行驶时缺少发动机声的问题。
### 启动器与模组
- 游戏退出后,可在「存档 → 乘员组」按国家开放、关闭或重新开放槽位,按兵种预览并调整技能等级。关闭前会自动备份,重新开放时可恢复该组的技能、训练和专精。
- 多个模组现在可在同一段科技树研发线上插入载具。启动器按模组加载顺序串接,并同步显示的连线与实际研发前置条件。
### 下载与兼容性
- **安装版** `wtoffline-launcher-0.1.6-win-x64.exe` 可覆盖安装。**便携版** `wtoffline-launcher-0.1.6-win-x64-portable.zip` 解压后即可使用。
- 已登记核对的客户端版本为 `2.61.0.37`、`2.61.0.43`、`2.61.0.55`、`2.61.0.58` 和 `2.61.0.64`。建议使用 `2.61.0.64` 搭配首个地图适配包。
- 此版本会自动把旧存档升级到格式 4。如需继续用旧版启动器,请保留升级前的存档备份。
- 首批地图的寻路已通过加载检查,部分路线仍需局内复核。全真、守卫、乘员组和发动机声修复仍待实机验收。
---
## English
V0.1.6 improves ground AI driving and combat, adds Air Simulator Enduring Confrontation, Ground Simulator and Air and Ground Assault, and gives the launcher a crew editor and a separate map pack updater.
### Ground AI and map packs
- **Driving and detours** use routes that fit each vehicle's width. Bots on the same team spread out where possible. They try to go around stopped vehicles and wrecks, and back up and replan after repeated blockages.
- **Spotting, aiming and firing** account for the last place a target was seen, nearby threats and incoming fire. Bots consider visibility, gun alignment and the chance of hitting. They can slow down, stop briefly or turn the hull, including to bring fixed guns on target.
- **The first map pack** (`2026.12.06`) covers 57 ground maps from Steam client `2.61.0.64` and is about 541 MB to download. The launcher lists it separately under **About → Map Adaptation Pack** when it is available. By default, battles use stock pathfinding when a map has no pack data.
### Battles and rewards
- **Air Simulator** uses 15 stock Enduring Confrontation missions with unlimited respawns. **Ground Simulator** uses Spawn Points.
- **Air and Ground Assault** can be played offline, with missions selected for the lineup's battle rating. In Ground Assault, stock mission AI controls the attacking waves and the new ground AI controls friendly defenders.
- Fixed bot respawns in unlimited-respawn modes such as Nuclear Escalation and removed unintended Silver Lion respawn charges in those modes.
- Damaging and destroying enemy mini-bases in Air Realistic and Simulator now counts toward personal score and battle rewards. Players who complete a ground capture receive score and credit toward Silver Lion and research rewards.
- Fixed ground hit markers, shell-change prompts and part-damage notices showing events unrelated to the player. Restored engine sound for ground AI tanks under custom driving control.
### Launcher and mods
- With the game closed, use **Saves → Crews** to open, close or reopen crew slots by nation, and preview and adjust skill levels by vehicle type. Closing a slot creates a backup. Reopening can restore its skills, training and qualifications.
- Multiple mods can insert vehicles into the same tech-tree link. The launcher composes the additions in mod load order and updates both the visible links and the research prerequisites.
### Downloads and compatibility
- **Installer** `wtoffline-launcher-0.1.6-win-x64.exe` can be installed over a previous version. **Portable** `wtoffline-launcher-0.1.6-win-x64-portable.zip` runs after extraction.
- Recorded client versions are `2.61.0.37`, `2.61.0.43`, `2.61.0.55`, `2.61.0.58` and `2.61.0.64`. We recommend `2.61.0.64` with the first map pack.
- Existing saves upgrade automatically to format 4. Keep a pre-upgrade backup if you need to use an older launcher.
- The first set of maps passed loading checks. Some routes still need in-game checks, along with Simulator and Assault modes, the crew editor, and the engine audio fix.
+68
View File
@@ -0,0 +1,68 @@
# Release an adaptation pack (packages/patcher/src/patch-pack/): pack and sign patches/ and publish
# it as a GitHub release tagged patches-<version>, where the launcher looks for it.
#
# Start it either way:
# - push a tag: git tag patches-2026.11.29 && git push origin patches-2026.11.29
# - from the Actions page (Run workflow), giving the version; the tag is created on the chosen
# branch's latest commit.
# The signing key comes from the repository secret PATCH_SIGNING_KEY
# (scripts/generate-patch-signing-key.ts).
name: Adaptation pack
on:
push:
tags: ['patches-*']
workflow_dispatch:
inputs:
version:
description: 'Pack version, YYYY.MM.DD or YYYY.MM.DD.N'
required: true
type: string
permissions:
contents: write
jobs:
release:
runs-on: ubuntu-latest
env:
# Packing needs no Electron binary.
ELECTRON_SKIP_BINARY_DOWNLOAD: '1'
VERSION: ${{ github.event_name == 'workflow_dispatch' && inputs.version || '' }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 24
cache: npm
- run: npm ci
- name: Pack and sign
env:
PATCH_SIGNING_KEY: ${{ secrets.PATCH_SIGNING_KEY }}
run: |
if [ -n "$VERSION" ]; then
node scripts/build-patch-pack.ts --version "$VERSION" --out dist
else
# The version comes from the pushed tag (GITHUB_REF_NAME).
node scripts/build-patch-pack.ts --out dist
fi
- name: Publish the release
env:
GH_TOKEN: ${{ github.token }}
run: |
manifest=$(ls dist/*.manifest.json)
field() { node -e "const m=JSON.parse(require('fs').readFileSync(process.argv[1],'utf8'));const v=m[process.argv[2]];process.stdout.write(Array.isArray(v)?v.join(', '):String(v))" "$manifest" "$1"; }
version=$(field version)
printf 'Adaptation pack %s.\n\nChecked game versions: %s\nNeeds offline version %s or newer.\n' \
"$version" "$(field game_versions)" "$(field min_app_version)" > dist/notes.md
gh release create "patches-$version" \
"dist/wtoffline-patches-$version.zip" \
"dist/wtoffline-patches-$version.zip.sig" \
"dist/wtoffline-patches-$version.manifest.json" \
--title "Adaptation pack $version" \
--notes-file dist/notes.md \
--target "$GITHUB_SHA"
+1 -6
View File
@@ -1,8 +1,5 @@
# Never commit game files (copyright, size). The build reads them from a game folder.
*.vromfs.bin
# Allow additive patch directories named after target packs inside mod templates (never binary archives).
!mod-dev-docs/templates/**/client/packs/*.vromfs.bin/
!mod-dev-docs/templates/**/client/packs/ui/*.vromfs.bin/
*.vromfs.bin.orig
aces.exe
aces*.exe
@@ -18,7 +15,6 @@ aces*.exe
/apps/launcher/out/
**/dist/
**/unpacked/
tools/navgen/extract/target/
# Node
node_modules/
@@ -29,11 +25,10 @@ __pycache__/
*.pyc
.venv/
# Saves, logs, local runtime data, local secrets
# Saves, logs, local runtime data
/data/
/saves/
*.log
.env*.local
# Editors / OS
.vscode/
+14 -42
View File
@@ -2,14 +2,12 @@
<a id="zh-cn"></a>
简体中文 · [English](#english) · [Discord](https://discord.gg/P566xWNpEs)
简体中文 · [English](#english)
------
WTOffline 是《战争雷霆》(War Thunder)Windows 客户端的单机离线项目。本地服务器模拟 Gaijin 的线上服务,客户端的所有请求都发到本机。客户端照常登录、读取档案、进入机库、提交玩家操作,游戏规则、存档和对局结算都在本地服务器上完成,对手和队友全部是 AI。
> **项目定位**:WTOffline 是为了方便玩家离线游玩的**单机**《战争雷霆》项目。为保持项目边界清晰、避免争议,项目组**不会提供也不会制作包括局域网联机在内的任何形式联机功能**。
仓库只包含源码和补丁定义,不包含任何游戏文件。构建时从玩家本机的原版安装读取文件,生成一份独立的游戏副本。
## 状态
@@ -23,10 +21,6 @@ WTOffline 是《战争雷霆》(War Thunder)Windows 客户端的单机离线
`patches/versions/` 中每份核对记录对应一个检查通过并在游戏中验证过的客户端版本。补丁和 native 模块按特征码、字符串引用和从代码中读出的值定位,不依赖固定地址,小版本更新后通常仍能命中,但没有核对记录的版本不保证功能正确。
## 开发讨论、交流与求助
欢迎加入 [WTOffline Discord 服务器](https://discord.gg/P566xWNpEs),用于日常交流、使用求助、问题反馈、调参分享以及开发和版本适配讨论。
## 功能
| 领域 | 已实现 |
@@ -43,7 +37,7 @@ WTOffline 是《战争雷霆》(War Thunder)Windows 客户端的单机离线
| 战后 | 结算页、战斗历史、个人统计、战斗奖章、加成道具与合同结算、修理费与自动修理 |
| 回放 | 录制与回放,回放中切换到 AI 视角 |
尚未实现:全真模式、自定义战斗、单人任务与动态战役、世界大战、战令、成就进度和称号获取、排行榜。本项目仅面向单人离线游玩,不制作包括局域网联机在内的任何联机功能;好友、组队等多人社交功能不适用,只保证界面不报错。
尚未实现:全真模式、自定义战斗、单人任务与动态战役、世界大战、战令、成就进度和称号获取、排行榜。好友、组队等多人社交功能不适用,只保证界面不报错。
AI 的驾驶、寻路和战术使用游戏自带的 AI,目前仍有明显不足。
@@ -79,8 +73,8 @@ AI 的驾驶、寻路和战术使用游戏自带的 AI,目前仍有明显不
- **服务地址**:`config/network.blk`(`char.vromfs.bin`)和 `config/settings.blk`(`aces.vromfs.bin`)中所有 Gaijin 地址改写为 `127.0.0.1:<端口>`。端口在构建时写入,因此服务器必须使用相同的端口。
- **配置表**:开启离线需要的功能开关,放出隐藏载具,写入贴花索引,为本地商店的礼包登记 GUID。
- **exe 补丁**:`patches/exe/` 下共 13 项,见下表。
- **界面脚本补丁**:`patches/gui/` 下共 40 项,用于本地账号注册、本地对局的开局与结算、本地商店的购买回执,以及库存签名公钥等。
- **exe 补丁**:`patches/exe/` 下共 12 项,见下表。
- **界面脚本补丁**:`patches/gui/` 下共 35 项,用于本地对局的开局与结算、本地商店的购买回执,以及库存签名公钥等。
- **网络钩子库**:exe 的导入表把 `WS2_32.dll` 改为同长度的 `wto_ws.dll`。该库转发系统 `ws2_32.dll` 的全部导出,并用 MinHook 挂钩域名解析(`getaddrinfo` 等)、连接(`connect`、`ConnectEx` 等)和 UDP 发送,把所有外部连接重定向到本地服务器端口。端口从 exe 旁的 `wto_ws.cfg` 读取。
| exe 补丁 | 作用 |
@@ -90,7 +84,6 @@ AI 的驾驶、寻路和战术使用游戏自带的 AI,目前仍有明显不
| `isolation/registry-key` | 注册表位置改为 `Software\WTOffline` |
| `isolation/never-load-battleye` | 不加载 BattlEye |
| `isolation/never-upload-crash-reports` | 不上传崩溃报告 |
| `isolation/never-launch-official-launcher` | 不拉起官方启动器 `launcher.exe` |
| `online/network-hook-library` | 加载 `wto_ws.dll` 代替 `WS2_32.dll` |
| `online/accept-local-tls-certificate` | 让 libcurl 接受本地服务器的自签名证书 |
| `online/matching-server-public-key` | 匹配服务器公钥替换为本地服务器的公钥,用于解出会话密钥 |
@@ -128,7 +121,7 @@ AI 的驾驶、寻路和战术使用游戏自带的 AI,目前仍有明显不
| 路径 | 内容 |
|---|---|
| `accounts.json` | 本地账号 |
| `saves/` | 每个本地账号的存档 |
| `saves/` | 每个账号的存档。存档格式变更时,旧存档在读取时自动升级 |
| `clans.json` | 本地联队 |
| `cache/` | 从游戏文件提取的数据集缓存 |
| `logs/` | 流量日志,服务器每次启动新建一个子目录 |
@@ -157,8 +150,6 @@ AI 的驾驶、寻路和战术使用游戏自带的 AI,目前仍有明显不
## 开发
开发规范、补丁指南和 PR 自查清单见 [Dev Docs](dev-docs/README.md#zh-cn),开发与版本适配讨论欢迎前往 [Discord](https://discord.gg/P566xWNpEs)。
### 环境要求
- Windows x64
@@ -187,16 +178,13 @@ node scripts/build-game-copy.ts --game "<原版目录>" --out "<副本目录>" -
node apps/server/src/cli.ts --game "<副本目录>" --data "<数据目录>" --port 27015
```
第一次登录前,在游戏登录界面点击「注册」,或在启动器的「存档」页创建本地账号。已有本地账号可以直接登录。
`build-game-copy.ts` 的可选参数:
| 参数 | 说明 |
|---|---|
| `--decal-cache <目录>` | 线上版安装的 `cache/content`,复制到副本以显示真实贴花;不指定时使用占位贴图 |
| `--skip-unavailable` | 非必需补丁不可用时继续构建 |
| `--patches <目录>` | 指定补丁集根目录,包含 `exe/`、`gui/`、`native/` 和 `versions/` |
| `--native <目录>` | 指定 `wto_ws.dll` 所在目录 |
| `--patches`、`--gui-patches`、`--native` | 替换默认的补丁目录和 `wto_ws.dll` 所在目录 |
| `--verbose` | 输出每个补丁的定位结果 |
### 辅助命令
@@ -225,8 +213,6 @@ wtotools check-patches --exe "<原版目录>\win64\aces.exe" # 定位并核
wtotools check-gui --gui "<原版目录>\gui.vromfs.bin" --sq "<sq.exe 路径>" # 应用界面补丁并用 Quirrel 编译器编译
```
GUI 检查需要 Quirrel 编译器,准备方式见 [Dev Docs](dev-docs/contributing.md#quirrel)。
检查全部补丁和 native 模块并写入该客户端版本的核对记录:`node scripts/record-game-version.ts --game "<原版目录>"`。
## 目录结构
@@ -263,7 +249,7 @@ tools/ wtotools,补丁检查工具(Python)
## 声明
本项目是面向单人离线游玩的非商业同人爱好项目,项目组不会主动制作包括局域网联机在内的任何联机功能。本项目与 Gaijin Entertainment 没有任何关联,也未获其认可。War Thunder 及相关名称和素材归其各自所有者所有。仓库不分发任何游戏文件,使用者需要自行拥有合法的游戏客户端。
本项目是同人爱好项目,与 Gaijin Entertainment 没有任何关联,也未获其认可。War Thunder 及相关名称和素材归其各自所有者所有。仓库不分发任何游戏文件,使用者需要自行拥有合法的游戏客户端。
---
@@ -271,12 +257,10 @@ tools/ wtotools,补丁检查工具(Python)
# WTOffline (English)
[简体中文](#zh-cn) · English · [Discord](https://discord.gg/P566xWNpEs)
[简体中文](#zh-cn) · English
WTOffline is a single-player offline project for the Windows client of War Thunder. A local server emulates Gaijin's online services, and the client sends all of its requests to the local machine. The client logs in, loads its profile, enters the hangar, and submits player actions as usual. Game rules, saves, and battle settlement run on the local server, and all allies and opponents are AI.
> **Project scope**: WTOffline is a **single-player offline** War Thunder project built to make offline play convenient for players. The project team **will not develop or provided any kind of multiplayer or networking features, including LAN multiplayer**.
The repository contains source code and patch definitions only. It does not contain any game files. The build reads files from the player's own installation and produces a separate game copy.
## Status
@@ -290,10 +274,6 @@ The repository contains source code and patch definitions only. It does not cont
Each check record in `patches/versions/` stands for a client version that passed the checks and was verified in game. Patches and native modules are located by signatures, string references and values read from the code rather than fixed addresses, so they usually still match after a minor update, but correct behavior is not guaranteed for a version without a check record.
## Community
Join the [WTOffline Discord server](https://discord.gg/P566xWNpEs) for general discussion, troubleshooting, bug reports, and development or patch adaptation discussions.
## Features
| Area | Implemented |
@@ -310,7 +290,7 @@ Join the [WTOffline Discord server](https://discord.gg/P566xWNpEs) for general d
| After battle | Debriefing, battle history, personal statistics, battle awards, booster and contract settlement, repair costs and auto-repair |
| Replays | Recording and playback, switching to AI vehicles during playback |
Not yet implemented: Simulator modes, custom battles, single missions and dynamic campaigns, World War, the battle pass, achievement progress and title unlocks, leaderboards. This project is strictly for single-player offline play and will not develop any multiplayer features (including LAN multiplayer); social multiplayer features such as friends and squads do not apply and are only kept from breaking the interface.
Not yet implemented: Simulator modes, custom battles, single missions and dynamic campaigns, World War, the battle pass, achievement progress and title unlocks, leaderboards. Social multiplayer features such as friends and squads do not apply; the interface is only kept from breaking.
AI driving, pathfinding, and tactics come from the game's built-in AI and still have clear shortcomings.
@@ -346,8 +326,8 @@ Static data such as vehicles, tech trees, prices, and reward factors is extracte
- **Service addresses**: every Gaijin address in `config/network.blk` (`char.vromfs.bin`) and `config/settings.blk` (`aces.vromfs.bin`) is rewritten to `127.0.0.1:<port>`. The port is written at build time, so the server must use the same port.
- **Config tables**: enables feature flags the offline copy needs, reveals hidden vehicles, adds a decal index, and registers GUIDs for local store packs.
- **exe patches**: 13 patches under `patches/exe/`, listed below.
- **UI script patches**: 40 patches under `patches/gui/`, covering local account registration, battle start and settlement, store purchase receipts, and the inventory signing key.
- **exe patches**: 12 patches under `patches/exe/`, listed below.
- **UI script patches**: 35 patches under `patches/gui/`, covering local battle start and settlement, local store purchase receipts, and the inventory signing key, among others.
- **Network hook library**: the import table entry `WS2_32.dll` is renamed to `wto_ws.dll`, which has the same length. The library forwards every export of the system `ws2_32.dll` and uses MinHook to hook name resolution (`getaddrinfo` and others), connections (`connect`, `ConnectEx`, and others), and UDP sends, redirecting every external connection to the local server port. The port is read from `wto_ws.cfg` next to the exe.
| exe patch | Purpose |
@@ -357,7 +337,6 @@ Static data such as vehicles, tech trees, prices, and reward factors is extracte
| `isolation/registry-key` | Moves registry settings to `Software\WTOffline` |
| `isolation/never-load-battleye` | Never loads BattlEye |
| `isolation/never-upload-crash-reports` | Never uploads crash reports |
| `isolation/never-launch-official-launcher` | Never launches the official `launcher.exe` |
| `online/network-hook-library` | Loads `wto_ws.dll` instead of `WS2_32.dll` |
| `online/accept-local-tls-certificate` | Makes libcurl accept the local server's self-signed certificate |
| `online/matching-server-public-key` | Replaces the matching server public key with the local server's, so it can decrypt the session key |
@@ -395,7 +374,7 @@ The server and the build script share one data folder (`--data`):
| Path | Contents |
|---|---|
| `accounts.json` | Local accounts |
| `saves/` | One save per local account |
| `saves/` | One save per account. When the save format changes, older saves are upgraded on load |
| `clans.json` | Local squadrons |
| `cache/` | Dataset cache extracted from the game files |
| `logs/` | Traffic logs, one subfolder per server run |
@@ -424,8 +403,6 @@ To override defaults, create `tuning/<same file name>.jsonc` in the data folder
## Development
See [Dev Docs](dev-docs/README.md#english) for development rules, patch templates, and the PR checklist, or join [Discord](https://discord.gg/P566xWNpEs) for development and patch adaptation discussions.
### Requirements
- Windows x64
@@ -454,16 +431,13 @@ node scripts/build-game-copy.ts --game "<stock folder>" --out "<copy folder>" --
node apps/server/src/cli.ts --game "<copy folder>" --data "<data folder>" --port 27015
```
Before the first sign-in, select **Register** on the game login screen or create a local account on the launcher's **Saves** page. Existing local accounts can sign in directly.
Optional arguments for `build-game-copy.ts`:
| Argument | Description |
|---|---|
| `--decal-cache <folder>` | The online installation's `cache/content`, copied into the copy to show real decals. Without it, placeholder images are used |
| `--skip-unavailable` | Continue when non-essential patches are unavailable |
| `--patches <folder>` | Override the patch set root containing `exe/`, `gui/`, `native/`, and `versions/` |
| `--native <folder>` | Override the folder containing `wto_ws.dll` |
| `--patches`, `--gui-patches`, `--native` | Override the default patch folders and the folder containing `wto_ws.dll` |
| `--verbose` | Print the locate result of every patch |
### Helper commands
@@ -492,8 +466,6 @@ wtotools check-patches --exe "<stock folder>\win64\aces.exe" # locate and ve
wtotools check-gui --gui "<stock folder>\gui.vromfs.bin" --sq "<path to sq.exe>" # apply UI patches and compile them with the Quirrel compiler
```
The GUI check requires the Quirrel compiler. See [the build steps](dev-docs/contributing.md#quirrel).
To check every patch and native module and write the check record of that client version: `node scripts/record-game-version.ts --game "<stock folder>"`.
## Repository layout
@@ -530,4 +502,4 @@ This project is released under the [GNU Affero General Public License v3.0](LICE
## Disclaimer
This is a non-commercial fan project built strictly for single-player offline play; the project team will not actively develop any multiplayer features, including LAN multiplayer. It is not affiliated with or endorsed by Gaijin Entertainment. War Thunder and related names and assets belong to their respective owners. The repository does not distribute any game files; you need your own legitimate copy of the game client.
This is a non-commercial fan project. It is not affiliated with or endorsed by Gaijin Entertainment. War Thunder and related names and assets belong to their respective owners. The repository does not distribute any game files; you need your own legitimate copy of the game client.
-2
View File
@@ -1,2 +0,0 @@
lab.local.json
.cache/
-12
View File
@@ -1,12 +0,0 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WTOffline AI Lab</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
-6
View File
@@ -1,6 +0,0 @@
{
"mapsDir": "J:/GAME/WTOfflineProject-tank-ai/build/nav-stage2-fix/maps",
"geoDir": "J:/GAME/WTOfflineProject-tank-ai/build/nav-stage2-fix/work",
"logsDir": "J:/GAME/WTLab/client-2.61.0.58/.game_logs",
"python": "J:/GAME/WTOfflineProject/.venv/Scripts/python.exe"
}
-24
View File
@@ -1,24 +0,0 @@
{
"name": "@wto/ai-lab",
"version": "0.1.0",
"private": true,
"description": "Ground AI lab: replay viewer for battle traces and simulator runs.",
"type": "module",
"scripts": {
"dev": "vite",
"typecheck": "tsc --noEmit -p tsconfig.json"
},
"dependencies": {
"@wto/ground-sim": "*",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"three": "^0.187.0"
},
"devDependencies": {
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@types/three": "^0.187.0",
"@vitejs/plugin-react": "^5.2.0",
"vite": "^7.3.6"
}
}
-147
View File
@@ -1,147 +0,0 @@
/**
* Dev-server API of the AI lab (local only):
* GET /api/maps levels that have a navigation pack in mapsDir
* GET /api/maps/file?name= a pack or POI file of mapsDir
* GET /api/logs game logs (.clog) in logsDir, newest first
* GET /api/logs/text?name= a log decrypted with wtotools (cached until the log changes)
* GET /api/scene?name= the 3D map (.wtoscene) of a level, built from its .wtogeo in geoDir
* (cached until the geometry changes)
* Paths come from lab.local.json next to this app (see lab.local.example.json).
*/
import { execFile } from 'node:child_process';
import { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
import type { ServerResponse } from 'node:http';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { buildMapScene, encodeMapScene, readGeo } from '@wto/ground-sim';
import type { Connect, Plugin } from 'vite';
interface LabConfig {
readonly mapsDir: string;
/** Where the navigation bake left the levels' .wtogeo geometry. */
readonly geoDir: string;
readonly logsDir: string;
readonly python: string;
}
const APP_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const CACHE_DIR = path.join(APP_DIR, '.cache');
const SAFE_NAME = /^[\w.-]+$/;
function loadConfig(): LabConfig {
const file = path.join(APP_DIR, 'lab.local.json');
const raw = existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')) as Record<string, unknown>) : {};
const str = (key: string, fallback: string): string => (typeof raw[key] === 'string' ? (raw[key] as string) : fallback);
const mapsDir = str('mapsDir', path.resolve(APP_DIR, '../../build/nav-stage2-fix/maps'));
return {
mapsDir,
geoDir: str('geoDir', path.join(mapsDir, '..', 'work')),
logsDir: str('logsDir', ''),
python: str('python', 'python'),
};
}
function sendJson(res: ServerResponse, status: number, body: unknown): void {
res.statusCode = status;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify(body));
}
function sendFile(res: ServerResponse, file: string, type: string): void {
res.statusCode = 200;
res.setHeader('Content-Type', type);
createReadStream(file).pipe(res);
}
function listMaps(cfg: LabConfig): { level: string; pois: boolean; scene: boolean }[] {
if (!existsSync(cfg.mapsDir)) return [];
return readdirSync(cfg.mapsDir)
.filter((f) => f.endsWith('.wtonav'))
.map((f) => {
const level = f.slice(0, -'.wtonav'.length);
return {
level,
pois: existsSync(path.join(cfg.mapsDir, `${level}.pois.json`)),
scene: existsSync(path.join(cfg.geoDir, `${level}.wtogeo`)),
};
});
}
function listLogs(cfg: LabConfig): { name: string; size: number; mtime: number }[] {
if (cfg.logsDir === '' || !existsSync(cfg.logsDir)) return [];
return readdirSync(cfg.logsDir)
.filter((f) => f.endsWith('.clog'))
.map((name) => {
const st = statSync(path.join(cfg.logsDir, name));
return { name, size: st.size, mtime: st.mtimeMs };
})
.sort((a, b) => b.mtime - a.mtime);
}
/** Decrypts `name` into the cache unless the cached text is newer than the log. */
function decryptLog(cfg: LabConfig, name: string): Promise<string> {
const source = path.join(cfg.logsDir, name);
const out = path.join(CACHE_DIR, `${name}.txt`);
mkdirSync(CACHE_DIR, { recursive: true });
if (existsSync(out) && statSync(out).mtimeMs >= statSync(source).mtimeMs) return Promise.resolve(out);
return new Promise((resolve, reject) => {
execFile(cfg.python, ['-m', 'wtotools.cli', 'decrypt-clog', source, '--out', out], { timeout: 180_000 }, (err, _stdout, stderr) => {
if (err !== null) reject(new Error(`decrypt-clog failed: ${stderr || err.message}`));
else resolve(out);
});
});
}
/** Builds the level's 3D map into the cache unless the cached one is newer than its geometry. */
function sceneFile(cfg: LabConfig, level: string): string | undefined {
const geo = path.join(cfg.geoDir, `${level}.wtogeo`);
if (!existsSync(geo)) return undefined;
const out = path.join(CACHE_DIR, `${level}.wtoscene`);
if (existsSync(out) && statSync(out).mtimeMs >= statSync(geo).mtimeMs) return out;
mkdirSync(CACHE_DIR, { recursive: true });
writeFileSync(out, encodeMapScene(buildMapScene(readGeo(readFileSync(geo)))));
return out;
}
async function handle(cfg: LabConfig, url: URL, res: ServerResponse): Promise<boolean> {
const name = url.searchParams.get('name') ?? '';
if (url.pathname === '/api/maps') { sendJson(res, 200, listMaps(cfg)); return true; }
if (url.pathname === '/api/logs') { sendJson(res, 200, listLogs(cfg)); return true; }
const known = ['/api/maps/file', '/api/logs/text', '/api/scene'];
if (!known.includes(url.pathname)) return false;
if (!SAFE_NAME.test(name)) { sendJson(res, 400, { error: 'bad file name' }); return true; }
if (url.pathname === '/api/scene') {
const file = sceneFile(cfg, name);
if (file === undefined) sendJson(res, 404, { error: `no ${name}.wtogeo in ${cfg.geoDir}` });
else sendFile(res, file, 'application/octet-stream');
return true;
}
if (url.pathname === '/api/maps/file') {
const file = path.join(cfg.mapsDir, name);
if (!existsSync(file)) sendJson(res, 404, { error: `no ${name} in ${cfg.mapsDir}` });
else sendFile(res, file, name.endsWith('.json') ? 'application/json' : 'application/octet-stream');
return true;
}
if (!name.endsWith('.clog') || !existsSync(path.join(cfg.logsDir, name))) {
sendJson(res, 404, { error: `no log ${name}` });
return true;
}
sendFile(res, await decryptLog(cfg, name), 'text/plain; charset=utf-8');
return true;
}
export function labApi(): Plugin {
return {
name: 'wto-ai-lab-api',
configureServer(server) {
const middleware: Connect.NextHandleFunction = (req, res, next) => {
const url = new URL(req.url ?? '/', 'http://localhost');
if (!url.pathname.startsWith('/api/')) { next(); return; }
handle(loadConfig(), url, res)
.then((handled) => { if (!handled) sendJson(res, 404, { error: 'unknown endpoint' }); })
.catch((err: unknown) => sendJson(res, 500, { error: err instanceof Error ? err.message : String(err) }));
};
server.middlewares.use(middleware);
},
};
}
-144
View File
@@ -1,144 +0,0 @@
/** AI lab replay viewer: pick a game log, a battle in it, and play it back on the map. */
import type { TraceBattle } from '@wto/ground-sim';
import { useEffect, useMemo, useState } from 'react';
import { fetchLogs, fetchMaps, loadLog, loadMap, type LogEntry, type MapData, type MapEntry } from './data.ts';
import { sceneAt } from './frames.ts';
import { Inspector } from './Inspector.tsx';
import { Map3D, type MapLook } from './Map3D.tsx';
import { buildMapLayer } from './mapLayer.ts';
import type { ViewMode } from './three/cameraRig.ts';
import type { Layers } from './three/overlays.ts';
import { Timeline } from './Timeline.tsx';
const LAYER_LABELS: Readonly<Record<keyof Layers, string>> = {
goals: '目标点', links: '目标连线', cones: '炮塔视野', labels: '标签', events: '开火与受击',
};
const VIEW_LABELS: Readonly<Record<ViewMode, string>> = { top: '俯视', free: '自由', follow: '跟随选中车', gun: '炮口视角' };
function logLabel(l: LogEntry): string {
const when = new Date(l.mtime).toLocaleString();
return `${l.name}(${(l.size / 1e6).toFixed(1)} MB,${when})`;
}
export function App(): React.JSX.Element {
const [maps, setMaps] = useState<MapEntry[]>([]);
const [logs, setLogs] = useState<LogEntry[]>([]);
const [logName, setLogName] = useState('');
const [battles, setBattles] = useState<TraceBattle[]>([]);
const [battleIdx, setBattleIdx] = useState(0);
const [mapData, setMapData] = useState<MapData | undefined>(undefined);
const [exposure, setExposure] = useState(false);
const [covers, setCovers] = useState(false);
const [look, setLook] = useState<MapLook>({ view: 'top', navImage: true, objects: true, crushable: true });
const [layers, setLayers] = useState<Layers>({ goals: true, links: true, cones: false, labels: false, events: true });
const [t, setT] = useState(0);
const [playing, setPlaying] = useState(false);
const [speed, setSpeed] = useState(4);
const [selected, setSelected] = useState<string | undefined>(undefined);
const [status, setStatus] = useState('');
const refreshLogs = (): void => { fetchLogs().then(setLogs).catch((e: unknown) => setStatus(String(e))); };
useEffect(() => {
fetchMaps().then(setMaps).catch((e: unknown) => setStatus(String(e)));
refreshLogs();
}, []);
const openLog = (name: string): void => {
setLogName(name);
setPlaying(false);
setStatus('正在解密和读取日志…');
loadLog(name).then((list) => {
setBattles(list);
// The longest battle that has bots in its trace; a battle left right after loading has none.
let pick = list.length - 1;
let best = 0;
list.forEach((b, i) => {
const withBots = b.frames.filter((f) => f.bots.size > 0).length;
if (withBots > best) { best = withBots; pick = i; }
});
setBattleIdx(Math.max(0, pick));
setStatus(list.length === 0 ? '这份日志里没有对局。' : '');
}).catch((e: unknown) => setStatus(String(e)));
};
const battle = battles[battleIdx];
const level = battle?.level;
useEffect(() => {
setT(battle?.startT ?? 0);
setSelected(undefined);
}, [battle]);
useEffect(() => {
const entry = maps.find((m) => m.level === level);
setMapData(undefined);
if (entry === undefined) return;
loadMap(entry).then(setMapData).catch((e: unknown) => setStatus(String(e)));
}, [level, maps]);
const mapLayer = useMemo(
() => (mapData === undefined ? undefined : buildMapLayer(mapData.pack, { tier: 1, exposure, covers })),
[mapData, exposure, covers],
);
useEffect(() => {
if (!playing || battle === undefined) return;
let last = performance.now();
let handle = requestAnimationFrame(function step(now) {
const dt = (now - last) / 1000;
last = now;
setT((cur) => {
const next = cur + dt * speed;
if (next >= battle.endT) { setPlaying(false); return battle.endT; }
return next;
});
handle = requestAnimationFrame(step);
});
return () => cancelAnimationFrame(handle);
}, [playing, speed, battle]);
const scene = useMemo(() => (battle === undefined ? undefined : sceneAt(battle, t)), [battle, t]);
return (
<div className="app">
<header>
<select value={logName} onChange={(e) => openLog(e.target.value)}>
<option value="">选择游戏日志…</option>
{logs.map((l) => <option key={l.name} value={l.name}>{logLabel(l)}</option>)}
</select>
<button type="button" onClick={refreshLogs}>刷新</button>
{battles.length > 1 && (
<select value={battleIdx} onChange={(e) => setBattleIdx(Number(e.target.value))}>
{battles.map((b, i) => (
<option key={i} value={i}>{`第 ${i + 1} 局 ${b.level ?? '未知地图'}(${b.frames.length} 帧)`}</option>
))}
</select>
)}
{(Object.keys(LAYER_LABELS) as (keyof Layers)[]).map((k) => (
<label key={k}>
<input type="checkbox" checked={layers[k]} onChange={(e) => setLayers({ ...layers, [k]: e.target.checked })} />
{LAYER_LABELS[k]}
</label>
))}
<select value={look.view} onChange={(e) => setLook({ ...look, view: e.target.value as ViewMode })}>
{(Object.keys(VIEW_LABELS) as ViewMode[]).map((v) => <option key={v} value={v}>{VIEW_LABELS[v]}</option>)}
</select>
<label><input type="checkbox" checked={look.navImage} onChange={(e) => setLook({ ...look, navImage: e.target.checked })} />导航网格</label>
<label><input type="checkbox" checked={look.objects} onChange={(e) => setLook({ ...look, objects: e.target.checked })} />物体</label>
<label><input type="checkbox" checked={look.crushable} onChange={(e) => setLook({ ...look, crushable: e.target.checked })} />可碾压物</label>
<label><input type="checkbox" checked={exposure} onChange={(e) => setExposure(e.target.checked)} />暴露度</label>
<label><input type="checkbox" checked={covers} onChange={(e) => setCovers(e.target.checked)} />掩体点</label>
{status !== '' && <span className="status">{status}</span>}
{battle !== undefined && battle.frames.length === 0 && <span className="status">这一局没有轨迹(游戏里没开 diagnostics.trace)。</span>}
</header>
<main>
<Map3D mapScene={mapData?.scene} nav={mapLayer} battle={battle} scene={scene} selected={selected}
layers={layers} look={look} onSelect={setSelected} />
{battle !== undefined && <Inspector battle={battle} scene={scene} selected={selected} />}
</main>
{battle !== undefined && (
<Timeline battle={battle} t={t} playing={playing} speed={speed} selected={selected}
onSeek={setT} onPlaying={setPlaying} onSpeed={setSpeed} />
)}
</div>
);
}
-94
View File
@@ -1,94 +0,0 @@
/** Details of the selected vehicle at the current time, its recent log events, and the legends. */
import type { TraceBattle, TraceEvent } from '@wto/ground-sim';
import { eventsBetween, type SceneAt } from './frames.ts';
import {
BEHAVIOR_COLORS, BEHAVIOR_ZH, CLASS_ZH, COMMAND_ZH, DENY_COLORS, DENY_ZH, LANE_ZH, LOOK_COLORS, LOOK_ZH,
STATE_ZH, URGENCY_ZH, zh,
} from './labels.ts';
interface Props {
readonly battle: TraceBattle;
readonly scene: SceneAt | undefined;
readonly selected: string | undefined;
}
const RECENT_SEC = 20;
function angleDiff(a: number, b: number): number {
return Math.abs(((((a - b) % 360) + 540) % 360) - 180);
}
function involves(e: TraceEvent, eid: string): boolean {
return e.eid === eid || e.fields['tgt'] === eid || e.fields['off'] === eid || e.fields['target'] === eid;
}
function eventText(e: TraceEvent): string {
return Object.entries(e.fields)
.filter(([k]) => k !== 't' && k !== 'eid')
.map(([k, v]) => `${k}=${v}`)
.join(' ');
}
function Legend({ names, colors }: { names: readonly string[]; colors: readonly string[] }): React.JSX.Element {
return (
<div className="legend">
{names.map((n, i) => (
<span key={n}><i style={{ background: colors[i] ?? '#444' }} />{n}</span>
))}
</div>
);
}
function Row({ k, v }: { k: string; v: string }): React.JSX.Element {
return <tr><th>{k}</th><td>{v}</td></tr>;
}
export function Inspector({ battle, scene, selected }: Props): React.JSX.Element {
const u = selected !== undefined ? scene?.units.get(selected) : undefined;
const b = u?.bot;
const recent = selected !== undefined && scene !== undefined
? eventsBetween(battle, scene.t - RECENT_SEC, scene.t).filter((e) => involves(e, selected)).reverse()
: [];
return (
<aside className="inspector">
{u === undefined && <p className="hint">点击地图上的车辆查看详情。白框是玩家,黄色虚线是炮塔想看的方向,白线是实际炮管。</p>}
{u !== undefined && (
<table>
<tbody>
<Row k="编号" v={`${u.unit.eid}(${u.unit.army} 队,${u.unit.human ? '玩家' : u.unit.bot ? 'AI' : '原版 AI'})`} />
<Row k="存活" v={u.unit.alive ? '是' : '否'} />
<Row k="车速" v={`${u.unit.speed.toFixed(1)} m/s`} />
{b !== undefined && <>
<Row k="车型" v={zh(CLASS_ZH, b.vehicleClass)} />
<Row k="任务" v={b.hasOrder ? `${zh(COMMAND_ZH, b.command)},紧迫度${zh(URGENCY_ZH, b.urgency)},点 ${b.capIdx},${zh(LANE_ZH, b.lane)}` : '无'} />
<Row k="行为" v={`${zh(BEHAVIOR_ZH, b.behavior)}(分数 ${b.behaviorScore.toFixed(2)})`} />
<Row k="状态" v={zh(STATE_ZH, b.state)} />
<Row k="车速 期望/实际" v={`${b.wantSpeed.toFixed(1)} / ${b.forwardSpeed.toFixed(1)} m/s${b.reverseTravel ? ',倒车跟路' : ''}`} />
<Row k="感知目标" v={b.target === '0' ? '无' : `${b.target}${b.targetInSight ? '(可见)' : '(不可见)'}`} />
<Row k="威胁表" v={`${b.threatCount} 项,最高 ${b.topThreat},最高可见 ${b.topVisibleThreat}`} />
<Row k="炮塔依据" v={`${zh(LOOK_ZH, b.lookReason)}${b.lookAt !== '0' ? ` → ${b.lookAt}` : ''}`} />
<Row k="炮塔偏差" v={b.gunYaw === undefined ? '—' : `离想看的方向 ${angleDiff(b.gunYaw, b.wishYaw).toFixed(0)}°,离车头 ${angleDiff(b.gunYaw, u.yaw).toFixed(0)}°`} />
<Row k="主炮" v={b.reloading ? '装填中' : b.gunReady ? '就绪' : '未就绪'} />
<Row k="开火判定" v={`${zh(DENY_ZH, b.deny)},命中概率 ${(b.hitProb * 100).toFixed(0)}% / 门槛 ${(b.threshold * 100).toFixed(0)}%`} />
<Row k="扳机要求车速" v={b.requestedSpeed >= 99 ? '不限' : `${b.requestedSpeed.toFixed(1)} m/s`} />
</>}
</tbody>
</table>
)}
{recent.length > 0 && (
<div className="events">
<h4>最近 {RECENT_SEC} 秒的日志</h4>
{recent.map((e, i) => (
<div key={`${e.t}-${i}`}><b>{e.t.toFixed(1)}</b> {e.kind} <span>{eventText(e)}</span></div>
))}
</div>
)}
<h4>行为</h4>
<Legend names={BEHAVIOR_ZH} colors={BEHAVIOR_COLORS} />
<h4>拒绝开火</h4>
<Legend names={DENY_ZH} colors={DENY_COLORS} />
<h4>炮塔依据</h4>
<Legend names={LOOK_ZH} colors={LOOK_COLORS} />
</aside>
);
}
-179
View File
@@ -1,179 +0,0 @@
/**
* The battle in 3D: terrain and object collision shapes of the level, vehicles as simple shapes,
* and the replay's lines and markers. Left drag pans, right drag turns (except top-down), wheel
* zooms; a click on a vehicle selects it.
*/
import { BEHAVIOR_NAMES, type MapScene, type TraceBattle } from '@wto/ground-sim';
import { useEffect, useRef } from 'react';
import { AmbientLight, Color, DirectionalLight, HemisphereLight, Raycaster, Scene, Vector2, WebGLRenderer } from 'three';
import { CSS2DRenderer } from 'three/addons/renderers/CSS2DRenderer.js';
import type { SceneAt, UnitAt } from './frames.ts';
import type { MapLayer } from './mapLayer.ts';
import { CameraRig, type ViewMode } from './three/cameraRig.ts';
import { buildMapMeshes, setTerrainImage, type MapMeshes } from './three/mapMeshes.ts';
import { Overlays, type Layers } from './three/overlays.ts';
import { TankPool } from './three/tanks.ts';
export interface MapLook {
readonly view: ViewMode;
/** Drape the navigation mesh image over the terrain instead of height colours. */
readonly navImage: boolean;
readonly objects: boolean;
readonly crushable: boolean;
}
interface Props {
readonly mapScene: MapScene | undefined;
readonly nav: MapLayer | undefined;
readonly battle: TraceBattle | undefined;
readonly scene: SceneAt | undefined;
readonly selected: string | undefined;
readonly layers: Layers;
readonly look: MapLook;
readonly onSelect: (eid: string | undefined) => void;
}
interface World {
readonly renderer: WebGLRenderer;
readonly labels: CSS2DRenderer;
readonly scene: Scene;
readonly rig: CameraRig;
map: MapMeshes | undefined;
tanks: TankPool;
overlays: Overlays;
selected: string | undefined;
}
const CRUSHABLE_KIND = 3;
const CLICK_PX = 4;
function labelOf(u: UnitAt): string {
const name = u.bot !== undefined ? (BEHAVIOR_NAMES[u.bot.behavior] ?? '?') : u.unit.human ? 'player' : '';
return `${u.unit.eid.replace(/^0x/, '')} ${name}`;
}
function createWorld(host: HTMLDivElement): World {
const renderer = new WebGLRenderer({ antialias: true, logarithmicDepthBuffer: true });
renderer.setPixelRatio(window.devicePixelRatio);
host.appendChild(renderer.domElement);
const labels = new CSS2DRenderer();
labels.domElement.className = 'labels3d';
host.appendChild(labels.domElement);
const scene = new Scene();
scene.background = new Color(0x0b0c0d);
scene.add(new HemisphereLight(0xdfe8ff, 0x3a3326, 1.4), new AmbientLight(0xffffff, 0.25));
const sun = new DirectionalLight(0xffffff, 1.6);
sun.position.set(0.5, 1, 0.3);
scene.add(sun);
const tanks = new TankPool(undefined);
const overlays = new Overlays(tanks);
scene.add(tanks.group, overlays.group);
return { renderer, labels, scene, rig: new CameraRig(renderer.domElement), map: undefined, tanks, overlays, selected: undefined };
}
function replaceMap(w: World, mapScene: MapScene | undefined, nav: MapLayer | undefined): void {
if (w.map !== undefined) { w.scene.remove(w.map.group); w.map.dispose(); }
w.scene.remove(w.tanks.group, w.overlays.group);
w.tanks.dispose();
w.overlays.dispose();
w.map = mapScene === undefined ? undefined : buildMapMeshes(mapScene, nav);
w.tanks = new TankPool(mapScene?.terrain);
w.overlays = new Overlays(w.tanks);
if (w.map !== undefined) w.scene.add(w.map.group);
w.scene.add(w.tanks.group, w.overlays.group);
if (mapScene !== undefined) {
const t = mapScene.terrain;
let sum = 0;
for (const h of t.heights) sum += h;
w.rig.fit(mapScene.boundsMin[0], mapScene.boundsMin[1], mapScene.boundsMax[0], mapScene.boundsMax[1], sum / Math.max(1, t.heights.length));
}
}
export function Map3D({ mapScene, nav, battle, scene, selected, layers, look, onSelect }: Props): React.JSX.Element {
const hostRef = useRef<HTMLDivElement>(null);
const worldRef = useRef<World | undefined>(undefined);
const onSelectRef = useRef(onSelect);
onSelectRef.current = onSelect;
useEffect(() => {
const host = hostRef.current;
if (host === null) return;
const w = createWorld(host);
worldRef.current = w;
const resize = (): void => {
const r = host.getBoundingClientRect();
w.renderer.setSize(r.width, r.height);
w.labels.setSize(r.width, r.height);
w.rig.resize(r.width, r.height);
};
const obs = new ResizeObserver(resize);
obs.observe(host);
resize();
w.renderer.setAnimationLoop(() => {
w.rig.tick(w.selected === undefined ? undefined : w.tanks.get(w.selected));
w.renderer.render(w.scene, w.rig.camera);
w.labels.render(w.scene, w.rig.camera);
});
const down = new Vector2();
const el = w.renderer.domElement;
const onDown = (e: PointerEvent): void => { down.set(e.clientX, e.clientY); };
const onUp = (e: PointerEvent): void => {
if (e.button !== 0 || Math.hypot(e.clientX - down.x, e.clientY - down.y) > CLICK_PX) return;
const r = el.getBoundingClientRect();
const ray = new Raycaster();
ray.setFromCamera(new Vector2(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1), w.rig.camera);
const hit = ray.intersectObjects(w.tanks.pickables(), false)[0];
onSelectRef.current(hit?.object.userData['eid'] as string | undefined);
};
el.addEventListener('pointerdown', onDown);
el.addEventListener('pointerup', onUp);
return () => {
obs.disconnect();
el.removeEventListener('pointerdown', onDown);
el.removeEventListener('pointerup', onUp);
w.renderer.setAnimationLoop(null);
replaceMap(w, undefined, undefined);
w.rig.dispose();
w.renderer.dispose();
host.replaceChildren();
worldRef.current = undefined;
};
}, []);
useEffect(() => {
const w = worldRef.current;
if (w !== undefined) replaceMap(w, mapScene, nav);
// The navigation image is applied by the effect below; only a new level rebuilds the map.
}, [mapScene]);
useEffect(() => {
const w = worldRef.current;
if (w?.map !== undefined) setTerrainImage(w.map, look.navImage ? nav : undefined);
}, [nav, look.navImage, mapScene]);
useEffect(() => {
const w = worldRef.current;
if (w?.map === undefined) return;
w.map.kinds.forEach((g, k) => { g.visible = look.objects && (k !== CRUSHABLE_KIND || look.crushable); });
}, [look.objects, look.crushable, mapScene]);
useEffect(() => {
worldRef.current?.rig.setMode(look.view);
}, [look.view]);
useEffect(() => {
const w = worldRef.current;
if (w === undefined) return;
w.selected = selected;
w.rig.refollow();
}, [selected]);
useEffect(() => {
const w = worldRef.current;
if (w === undefined || battle === undefined || scene === undefined) return;
w.tanks.update(scene.units, selected, (u) => (layers.labels && u.unit.alive ? labelOf(u) : undefined));
w.overlays.update(battle, scene, layers);
}, [battle, scene, selected, layers, mapScene]);
return <div ref={hostRef} className="map3d" />;
}
-86
View File
@@ -1,86 +0,0 @@
/**
* Playback controls and, for the selected bot, three strips over the whole battle: its behavior,
* the reason it did not fire, and why its turret pointed where it did. Click a strip to seek.
*/
import type { TraceBattle } from '@wto/ground-sim';
import { useEffect, useRef } from 'react';
import { BEHAVIOR_COLORS, DENY_COLORS, LOOK_COLORS } from './labels.ts';
interface Props {
readonly battle: TraceBattle;
readonly t: number;
readonly playing: boolean;
readonly speed: number;
readonly selected: string | undefined;
readonly onSeek: (t: number) => void;
readonly onPlaying: (playing: boolean) => void;
readonly onSpeed: (speed: number) => void;
}
const SPEEDS = [0.5, 1, 2, 4, 8, 16];
const STRIP_H = 10;
function drawStrips(canvas: HTMLCanvasElement, battle: TraceBattle, eid: string | undefined, t: number): void {
const ctx = canvas.getContext('2d');
if (ctx === null) return;
const w = canvas.width;
const span = Math.max(1, battle.endT - battle.startT);
ctx.fillStyle = '#16181a';
ctx.fillRect(0, 0, w, canvas.height);
if (eid !== undefined) {
const frames = battle.frames;
for (let i = 0; i < frames.length; i++) {
const f = frames[i];
const bot = f?.bots.get(eid);
if (f === undefined || bot === undefined) continue;
const x0 = ((f.t - battle.startT) / span) * w;
const x1 = (((frames[i + 1]?.t ?? f.t + 0.5) - battle.startT) / span) * w;
const bw = Math.max(1, x1 - x0);
ctx.fillStyle = BEHAVIOR_COLORS[bot.behavior] ?? '#444';
ctx.fillRect(x0, 0, bw, STRIP_H);
ctx.fillStyle = DENY_COLORS[bot.deny] ?? '#444';
ctx.fillRect(x0, STRIP_H + 2, bw, STRIP_H);
ctx.fillStyle = LOOK_COLORS[bot.lookReason] ?? '#444';
ctx.fillRect(x0, 2 * (STRIP_H + 2), bw, STRIP_H);
}
}
const cx = ((t - battle.startT) / span) * w;
ctx.fillStyle = '#fff';
ctx.fillRect(cx - 1, 0, 2, canvas.height);
}
export function Timeline({ battle, t, playing, speed, selected, onSeek, onPlaying, onSpeed }: Props): React.JSX.Element {
const stripRef = useRef<HTMLCanvasElement>(null);
useEffect(() => {
const c = stripRef.current;
if (c === null) return;
c.width = Math.max(1, Math.floor(c.getBoundingClientRect().width));
drawStrips(c, battle, selected, t);
}, [battle, selected, t]);
return (
<div className="timeline">
<div className="controls">
<button type="button" onClick={() => onPlaying(!playing)}>{playing ? '暂停' : '播放'}</button>
<select value={speed} onChange={(e) => onSpeed(Number(e.target.value))}>
{SPEEDS.map((s) => <option key={s} value={s}>{s}×</option>)}
</select>
<span className="time">{t.toFixed(1)} s / {battle.endT.toFixed(0)} s</span>
<input
type="range" min={battle.startT} max={battle.endT} step={0.1} value={t}
onChange={(e) => onSeek(Number(e.target.value))}
/>
</div>
<div className="strip-labels"><span>行为</span><span>拒绝开火</span><span>炮塔依据</span></div>
<canvas
ref={stripRef}
className="strips"
height={3 * (STRIP_H + 2)}
onClick={(e) => {
const w = e.currentTarget.width;
onSeek(battle.startT + (e.nativeEvent.offsetX / w) * (battle.endT - battle.startT));
}}
/>
</div>
);
}
-56
View File
@@ -1,56 +0,0 @@
/** Loading maps and logs through the lab's dev-server API (server/lab-api.ts). */
import {
decodeMapScene, parsePois, parseTraceLog, readNavPack, type MapPois, type MapScene, type NavPack, type TraceBattle,
} from '@wto/ground-sim';
export interface LogEntry {
readonly name: string;
readonly size: number;
readonly mtime: number;
}
export interface MapEntry {
readonly level: string;
readonly pois: boolean;
/** The level's geometry is there, so it has a 3D map. */
readonly scene: boolean;
}
export interface MapData {
readonly pack: NavPack;
readonly pois: MapPois | undefined;
readonly scene: MapScene | undefined;
}
async function get(url: string): Promise<Response> {
const res = await fetch(url);
if (!res.ok) {
const body = await res.text();
throw new Error(`${url}: ${res.status} ${body}`);
}
return res;
}
export async function fetchMaps(): Promise<MapEntry[]> {
return (await (await get('/api/maps')).json()) as MapEntry[];
}
export async function fetchLogs(): Promise<LogEntry[]> {
return (await (await get('/api/logs')).json()) as LogEntry[];
}
export async function loadLog(name: string): Promise<TraceBattle[]> {
const text = await (await get(`/api/logs/text?name=${encodeURIComponent(name)}`)).text();
return parseTraceLog(text);
}
export async function loadMap(entry: MapEntry): Promise<MapData> {
const bytes = new Uint8Array(await (await get(`/api/maps/file?name=${encodeURIComponent(`${entry.level}.wtonav`)}`)).arrayBuffer());
const pois = entry.pois
? parsePois(await (await get(`/api/maps/file?name=${encodeURIComponent(`${entry.level}.pois.json`)}`)).text())
: undefined;
const scene = entry.scene
? decodeMapScene(new Uint8Array(await (await get(`/api/scene?name=${encodeURIComponent(entry.level)}`)).arrayBuffer()))
: undefined;
return { pack: readNavPack(bytes), pois, scene };
}
-95
View File
@@ -1,95 +0,0 @@
/** Looking up the battle state at any time between two trace samples. */
import type { BotSample, CapSample, TraceBattle, TraceEvent, UnitSample } from '@wto/ground-sim';
export interface UnitAt {
readonly unit: UnitSample;
/** Interpolated position, hull heading, pitch and roll. */
readonly x: number;
readonly y: number;
readonly z: number;
readonly yaw: number;
readonly hullPitch: number;
readonly hullRoll: number;
/** Interpolated gun world yaw and pitch; from the bot line, or the hull, when the unit line has none. */
readonly gunYaw: number;
readonly gunPitch: number;
/** Decision state of the sample at or before the time; undefined for players. */
readonly bot: BotSample | undefined;
}
export interface SceneAt {
readonly t: number;
readonly units: Map<string, UnitAt>;
readonly caps: CapSample[];
}
/** Index of the last frame at or before `t` (-1 before the first). */
export function frameIndexAt(battle: TraceBattle, t: number): number {
let lo = 0;
let hi = battle.frames.length - 1;
let found = -1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if ((battle.frames[mid]?.t ?? Infinity) <= t) { found = mid; lo = mid + 1; } else hi = mid - 1;
}
return found;
}
function lerpYaw(a: number, b: number, k: number): number {
const d = ((((b - a) % 360) + 540) % 360) - 180;
return a + d * k;
}
function lerp(a: number, b: number | undefined, k: number): number {
return a + ((b ?? a) - a) * k;
}
function gunOf(u: UnitSample, bot: BotSample | undefined): [number, number] {
return [u.gunYaw ?? bot?.gunYaw ?? u.yaw, u.gunPitch ?? 0];
}
export function sceneAt(battle: TraceBattle, t: number): SceneAt {
const i = Math.max(0, frameIndexAt(battle, t));
const a = battle.frames[i];
const b = battle.frames[i + 1];
const units = new Map<string, UnitAt>();
if (a === undefined) return { t, units, caps: [] };
const k = b !== undefined && b.t > a.t ? Math.min(1, Math.max(0, (t - a.t) / (b.t - a.t))) : 0;
for (const [eid, ua] of a.units) {
const ub = b?.units.get(eid);
const move = ub !== undefined && ua.alive && ub.alive ? k : 0;
const bot = a.bots.get(eid);
const [gyA, gpA] = gunOf(ua, bot);
const [gyB, gpB] = ub !== undefined ? gunOf(ub, b?.bots.get(eid)) : [gyA, gpA];
units.set(eid, {
unit: ua,
x: lerp(ua.x, ub?.x, move),
y: lerp(ua.y, ub?.y, move),
z: lerp(ua.z, ub?.z, move),
yaw: lerpYaw(ua.yaw, ub?.yaw ?? ua.yaw, move),
hullPitch: lerp(ua.hullPitch ?? 0, ub?.hullPitch, move),
hullRoll: lerp(ua.hullRoll ?? 0, ub?.hullRoll, move),
gunYaw: lerpYaw(gyA, gyB, move),
gunPitch: lerp(gpA, gpB, move),
bot,
});
}
return { t, units, caps: a.caps };
}
/** Events with time in [from, to], from the sorted event list. */
export function eventsBetween(battle: TraceBattle, from: number, to: number): TraceEvent[] {
let lo = 0;
let hi = battle.events.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if ((battle.events[mid]?.t ?? Infinity) < from) lo = mid + 1; else hi = mid;
}
const out: TraceEvent[] = [];
for (let i = lo; i < battle.events.length; i++) {
const e = battle.events[i];
if (e === undefined || e.t > to) break;
out.push(e);
}
return out;
}
-37
View File
@@ -1,37 +0,0 @@
/** Chinese display names for the trace codes (the codes themselves are in @wto/ground-sim). */
export const BEHAVIOR_ZH = ['推进', '交战推进', '短停', '回掩体', '换位', '守位', '疏散', '撤回', '维修'] as const;
export const BEHAVIOR_COLORS = ['#6c8ebf', '#e0884a', '#e5d34a', '#8fbf6c', '#b07cc6', '#5fb8b0', '#9a9a9a', '#c65f5f', '#7a5a3a'] as const;
export const STATE_ZH: Readonly<Record<number, string>> = {
0: '行军', 1: '行进交战', 3: '短停', 4: '退入掩体', 5: '掩体装填', 7: '原地守位', 8: '换位',
9: '失能', 10: '疏散', 11: '坡脊撤回',
};
export const DENY_ZH = [
'放行', '无目标', '炮未就绪', '命中概率不足', '远距窗口不足', '瞄准误差', '等待炮管稳定', '检查预算',
'炮口有硬物', '弹道有硬物', '友军', '多炮检查', '射界外', '点射间歇',
] as const;
export const DENY_COLORS = [
'#4caf50', '#333', '#666', '#e53935', '#8e24aa', '#fb8c00', '#fdd835', '#90a4ae',
'#6d4c41', '#795548', '#03a9f4', '#9e9e9e', '#d81b60', '#26a69a',
] as const;
export const LOOK_ZH = ['—', '交战目标', '威胁', '目标消失处', '记忆位置', '线索', '扫视'] as const;
export const LOOK_COLORS = ['#333', '#e53935', '#fb8c00', '#fdd835', '#8e24aa', '#03a9f4', '#607d8b'] as const;
export const COMMAND_ZH = ['主攻', '侧翼', '架枪', '防守', '预备', '防空'] as const;
export const URGENCY_ZH = ['低', '中', '高'] as const;
export const LANE_ZH = ['中路', '左翼', '右翼'] as const;
export const CLASS_ZH = ['中坦', '轻坦', '重坦', '歼击车', '防空'] as const;
export function zh(names: readonly string[] | Readonly<Record<number, string>>, code: number): string {
const name = Array.isArray(names) ? names[code] : (names as Readonly<Record<number, string>>)[code];
return name ?? String(code);
}
-7
View File
@@ -1,7 +0,0 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { App } from './App.tsx';
import './style.css';
const root = document.getElementById('root');
if (root !== null) createRoot(root).render(<StrictMode><App /></StrictMode>);
-89
View File
@@ -1,89 +0,0 @@
/**
* The navigation image draped over the 3D terrain, drawn once into an offscreen canvas: walkable polygons of one mesh tier coloured
* by surface, optionally the tactical grid's exposure and the baked cover points.
*/
import { NAV_AREA_NAMES, type NavPack } from '@wto/ground-sim';
export interface MapLayer {
readonly canvas: HTMLCanvasElement;
/** World x of the canvas's left edge and world z of its top edge. */
readonly x0: number;
readonly z1: number;
readonly pxPerM: number;
}
export interface MapLayerOptions {
readonly tier: number;
readonly exposure: boolean;
readonly covers: boolean;
}
const AREA_COLORS: Readonly<Record<string, string>> = {
road: '#77786a', bridge: '#a0a090', ground: '#3d4a33', rough: '#5a4d34', forest: '#29402a',
crushable: '#4f5f35', shallowWater: '#35607a', chokepoint: '#7a6a35', exposed: '#5f5f33',
deepWater: '#1d3a66', noGo: '#3a2626',
};
export function buildMapLayer(pack: NavPack, opts: MapLayerOptions): MapLayer {
const [x0, , z0] = pack.header.bmin;
const [x1, , z1] = pack.header.bmax;
const pxPerM = Math.min(2, 4096 / Math.max(x1 - x0, z1 - z0));
const canvas = document.createElement('canvas');
canvas.width = Math.ceil((x1 - x0) * pxPerM);
canvas.height = Math.ceil((z1 - z0) * pxPerM);
const ctx = canvas.getContext('2d');
if (ctx === null) return { canvas, x0, z1, pxPerM };
// Off the mesh (buildings, steep or blocked ground) when draped over the 3D terrain.
ctx.fillStyle = '#55584f';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const tier = pack.tiers[opts.tier] ?? pack.tiers[1];
if (tier !== undefined) {
for (let area = 1; area < NAV_AREA_NAMES.length; area++) {
ctx.beginPath();
for (let i = 0; i < tier.polyCount; i++) {
if (tier.areas[i] !== area) continue;
const ring = tier.rings[i];
if (ring === undefined) continue;
for (let k = 0; k < ring.length; k += 2) {
const px = ((ring[k] ?? 0) - x0) * pxPerM;
const py = (z1 - (ring[k + 1] ?? 0)) * pxPerM;
if (k === 0) ctx.moveTo(px, py);
else ctx.lineTo(px, py);
}
ctx.closePath();
}
ctx.fillStyle = AREA_COLORS[NAV_AREA_NAMES[area] ?? ''] ?? '#444';
ctx.fill();
}
}
if (opts.exposure) drawExposure(ctx, pack, x0, z1, pxPerM);
if (opts.covers) drawCovers(ctx, pack, x0, z1, pxPerM);
return { canvas, x0, z1, pxPerM };
}
function drawExposure(ctx: CanvasRenderingContext2D, pack: NavPack, x0: number, z1: number, pxPerM: number): void {
const g = pack.tactical;
const cell = g.cellM * pxPerM;
for (let r = 0; r < g.rows; r++) {
for (let c = 0; c < g.cols; c++) {
const e = g.exposure[r * g.cols + c] ?? 0;
if (e < 16) continue;
ctx.fillStyle = `rgba(255, 80, 40, ${(e / 255) * 0.45})`;
const wx = g.origin[0] + c * g.cellM;
const wz = g.origin[1] + r * g.cellM;
ctx.fillRect((wx - x0) * pxPerM, (z1 - wz - g.cellM) * pxPerM, cell, cell);
}
}
}
function drawCovers(ctx: CanvasRenderingContext2D, pack: NavPack, x0: number, z1: number, pxPerM: number): void {
for (const cv of pack.covers) {
const px = (cv.pos[0] - x0) * pxPerM;
const py = (z1 - cv.pos[2]) * pxPerM;
ctx.strokeStyle = cv.kind === 1 ? 'rgba(120, 220, 255, 0.8)' : 'rgba(255, 230, 120, 0.8)';
ctx.beginPath();
ctx.moveTo(px, py);
ctx.lineTo(px + cv.coverDir[0] * 6 * pxPerM, py - cv.coverDir[1] * 6 * pxPerM);
ctx.stroke();
}
}
-30
View File
@@ -1,30 +0,0 @@
* { box-sizing: border-box; }
html, body, #root { margin: 0; height: 100%; background: #0b0c0d; color: #ddd; font: 13px/1.4 system-ui, 'Microsoft YaHei', sans-serif; }
.app { display: flex; flex-direction: column; height: 100%; }
header { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; padding: 6px 10px; background: #16181a; border-bottom: 1px solid #2a2d30; }
header select { max-width: 420px; }
header label { display: inline-flex; align-items: center; gap: 3px; }
.status { color: #ffb74d; }
main { flex: 1; display: flex; min-height: 0; }
.map3d { flex: 1; min-width: 0; height: 100%; position: relative; overflow: hidden; }
.map3d canvas { display: block; }
.labels3d { position: absolute; inset: 0; pointer-events: none; }
.tank-label { color: rgba(255,255,255,0.9); font-size: 11px; text-shadow: 0 0 3px #000; white-space: nowrap; }
.tank-label.human { color: #ffe14a; }
.inspector { width: 360px; overflow-y: auto; padding: 8px 10px; background: #121416; border-left: 1px solid #2a2d30; }
.inspector table { width: 100%; border-collapse: collapse; }
.inspector th { text-align: left; color: #999; font-weight: normal; padding: 2px 8px 2px 0; white-space: nowrap; vertical-align: top; }
.inspector td { padding: 2px 0; }
.inspector h4 { margin: 12px 0 4px; color: #aaa; font-weight: normal; }
.hint { color: #999; }
.events { font-size: 12px; }
.events div { padding: 1px 0; border-bottom: 1px solid #1d2023; word-break: break-all; }
.events span { color: #999; }
.legend { display: flex; flex-wrap: wrap; gap: 4px 10px; font-size: 12px; }
.legend i { display: inline-block; width: 10px; height: 10px; margin-right: 3px; vertical-align: -1px; }
.timeline { padding: 6px 10px; background: #16181a; border-top: 1px solid #2a2d30; }
.controls { display: flex; gap: 8px; align-items: center; }
.controls input[type='range'] { flex: 1; }
.time { min-width: 120px; font-variant-numeric: tabular-nums; }
.strip-labels { display: flex; gap: 12px; font-size: 11px; color: #888; margin-top: 4px; }
canvas.strips { width: 100%; height: 36px; display: block; cursor: pointer; }
-119
View File
@@ -1,119 +0,0 @@
/**
* The 3D view's cameras: a top-down orthographic map view (world +z up the screen, like the old
* flat map), a free perspective view, a view that follows the selected vehicle, and a view out of
* its muzzle along the barrel.
*/
import { OrthographicCamera, PerspectiveCamera, Quaternion, Vector3, type Camera } from 'three';
import { MapControls } from 'three/addons/controls/MapControls.js';
import type { Tank } from './tanks.ts';
export type ViewMode = 'top' | 'free' | 'follow' | 'gun';
const TOP_HEIGHT = 3000;
/** Top-down camera sits this far south of its target, so the controls keep north up. */
const TOP_SOUTH = 0.01;
const FREE_MAX_POLAR = Math.PI * 0.49;
export class CameraRig {
readonly persp = new PerspectiveCamera(50, 1, 0.5, 20000);
readonly ortho = new OrthographicCamera(-1, 1, 1, -1, 1, 10000);
readonly controls: MapControls;
private mode: ViewMode = 'top';
private aspect = 1;
private readonly lastFollow = new Vector3();
private following = false;
constructor(dom: HTMLElement) {
this.controls = new MapControls(this.ortho, dom);
this.controls.enableDamping = true;
this.controls.dampingFactor = 0.15;
this.controls.screenSpacePanning = true;
this.limitTilt();
}
/** Top-down stays straight down; the other views may tilt down to just above the horizon. */
private limitTilt(): void {
this.controls.maxPolarAngle = this.mode === 'top' ? 0 : FREE_MAX_POLAR;
}
get camera(): Camera {
return this.mode === 'top' ? this.ortho : this.persp;
}
resize(w: number, h: number): void {
this.aspect = w / Math.max(1, h);
this.persp.aspect = this.aspect;
this.persp.updateProjectionMatrix();
const half = (this.ortho.top - this.ortho.bottom) / 2;
this.ortho.left = -half * this.aspect;
this.ortho.right = half * this.aspect;
this.ortho.updateProjectionMatrix();
}
/** Frames the world rectangle (x, z) in both cameras. */
fit(minX: number, minZ: number, maxX: number, maxZ: number, groundY: number): void {
const cx = (minX + maxX) / 2;
const cz = -(minZ + maxZ) / 2;
const half = (Math.max((maxX - minX) / this.aspect, maxZ - minZ) / 2) * 1.05;
Object.assign(this.ortho, { left: -half * this.aspect, right: half * this.aspect, top: half, bottom: -half, zoom: 1 });
this.ortho.updateProjectionMatrix();
this.ortho.position.set(cx, groundY + TOP_HEIGHT, cz + TOP_SOUTH);
this.persp.position.set(cx, groundY + half * 0.9, cz + half * 1.1);
this.controls.target.set(cx, groundY, cz);
this.ortho.lookAt(this.controls.target);
this.persp.lookAt(this.controls.target);
this.controls.update();
}
setMode(mode: ViewMode): void {
if (mode === this.mode) return;
const target = this.controls.target.clone();
if (this.mode === 'top' && mode !== 'gun') {
const span = (this.ortho.top - this.ortho.bottom) / this.ortho.zoom;
this.persp.position.set(target.x, target.y + span * 0.6, target.z + span * 0.6);
}
if (mode === 'top') this.ortho.position.set(target.x, target.y + TOP_HEIGHT, target.z + TOP_SOUTH);
this.mode = mode;
this.limitTilt();
this.following = false;
this.controls.object = this.camera;
this.controls.enableRotate = mode !== 'top';
this.controls.enabled = mode !== 'gun';
this.camera.lookAt(target);
this.controls.update();
}
/** The next follow frame starts over around the (newly) selected vehicle. */
refollow(): void {
this.following = false;
}
/** Per frame: keeps the followed vehicle centred, or puts the camera at the muzzle. */
tick(tank: Tank | undefined): void {
if (this.mode === 'follow' && tank !== undefined && tank.root.visible) {
const at = tank.root.position;
if (!this.following) {
this.controls.target.copy(at);
this.persp.position.set(at.x - 25, at.y + 15, at.z + 25);
this.following = true;
} else {
const d = at.clone().sub(this.lastFollow);
this.controls.target.add(d);
this.persp.position.add(d);
}
this.lastFollow.copy(at);
} else if (this.mode === 'gun' && tank !== undefined && tank.root.visible) {
const q = tank.barrel.getWorldQuaternion(new Quaternion());
const dir = new Vector3(1, 0, 0).applyQuaternion(q);
const tip = tank.barrel.getWorldPosition(new Vector3()).addScaledVector(dir, tank.length * 0.8);
this.persp.position.copy(tip);
this.persp.lookAt(tip.clone().add(dir));
return;
}
if (this.controls.enabled) this.controls.update();
}
dispose(): void {
this.controls.dispose();
}
}
-18
View File
@@ -1,18 +0,0 @@
/**
* Game world to three.js: Dagor is left-handed with Y up, three.js right-handed, so world z is
* mirrored (three z = -world z). A world heading (degrees of atan2(z, x)) then becomes the same
* angle of rotation about three's +Y, and a model's local +X is its front, +Y up, -Z its left.
*/
import { Vector3 } from 'three';
export const DEG = Math.PI / 180;
export function toThree(x: number, y: number, z: number, out: Vector3 = new Vector3()): Vector3 {
return out.set(x, y, -z);
}
/** Three.js direction of a world heading and pitch, in degrees. */
export function dirOf(yawDeg: number, pitchDeg: number, out: Vector3 = new Vector3()): Vector3 {
const c = Math.cos(pitchDeg * DEG);
return out.set(Math.cos(yawDeg * DEG) * c, Math.sin(pitchDeg * DEG), -Math.sin(yawDeg * DEG) * c);
}
-134
View File
@@ -1,134 +0,0 @@
/**
* The static 3D map: lit terrain (coloured by height, or draped with the navigation mesh image),
* the collision shapes of placed objects coloured by kind, and the water plane.
*/
import type { MapScene, SceneTerrain } from '@wto/ground-sim';
import {
BufferAttribute, BufferGeometry, CanvasTexture, Color, DoubleSide, Group, Mesh, MeshLambertMaterial,
PlaneGeometry, SRGBColorSpace, type Material,
} from 'three';
import type { MapLayer } from '../mapLayer.ts';
/** Colour and opacity per SCENE_KIND_NAMES entry. */
const KIND_LOOK: readonly (readonly [number, number])[] = [
[0xb9b2a3, 1], [0x7d7a74, 1], [0x9a7b55, 1], [0xe09a4a, 0.4], [0x4f8a3c, 1], [0x6f8aa0, 1],
];
const LOW = new Color(0x3c4a32);
const HIGH = new Color(0x9b9171);
export interface MapMeshes {
readonly group: Group;
readonly terrain: Mesh<BufferGeometry, MeshLambertMaterial>;
/** Objects per scene kind, to switch kinds on and off. */
readonly kinds: Group[];
dispose(): void;
}
function terrainGeometry(t: SceneTerrain, nav: MapLayer | undefined): BufferGeometry {
const n = t.cols * t.rows;
const pos = new Float32Array(n * 3);
const col = new Float32Array(n * 3);
const uv = new Float32Array(n * 2);
let lo = Infinity;
let hi = -Infinity;
for (const h of t.heights) { lo = Math.min(lo, h); hi = Math.max(hi, h); }
const c = new Color();
const navW = nav === undefined ? 1 : nav.canvas.width / nav.pxPerM;
const navH = nav === undefined ? 1 : nav.canvas.height / nav.pxPerM;
for (let r = 0; r < t.rows; r++) {
for (let k = 0; k < t.cols; k++) {
const i = r * t.cols + k;
const x = t.origin[0] + k * t.cellM;
const z = t.origin[1] + r * t.cellM;
const h = t.heights[i] ?? 0;
pos.set([x, h, -z], i * 3);
c.lerpColors(LOW, HIGH, hi > lo ? (h - lo) / (hi - lo) : 0);
col.set([c.r, c.g, c.b], i * 3);
if (nav !== undefined) uv.set([(x - nav.x0) / navW, (z - (nav.z1 - navH)) / navH], i * 2);
}
}
const idx = new Uint32Array((t.cols - 1) * (t.rows - 1) * 6);
let at = 0;
for (let r = 0; r + 1 < t.rows; r++) {
for (let k = 0; k + 1 < t.cols; k++) {
const i = r * t.cols + k;
idx.set([i, i + 1, i + t.cols, i + 1, i + t.cols + 1, i + t.cols], at);
at += 6;
}
}
const g = new BufferGeometry();
g.setAttribute('position', new BufferAttribute(pos, 3));
g.setAttribute('color', new BufferAttribute(col, 3));
g.setAttribute('uv', new BufferAttribute(uv, 2));
g.setIndex(new BufferAttribute(idx, 1));
g.computeVertexNormals();
return g;
}
/** Drapes the navigation image over the terrain, or goes back to height colours. */
export function setTerrainImage(m: MapMeshes, nav: MapLayer | undefined): void {
const mat = m.terrain.material;
mat.map?.dispose();
if (nav === undefined) {
mat.map = null;
mat.vertexColors = true;
} else {
const tex = new CanvasTexture(nav.canvas);
tex.colorSpace = SRGBColorSpace;
tex.anisotropy = 8;
mat.map = tex;
mat.vertexColors = false;
}
mat.needsUpdate = true;
}
function objectKinds(scene: MapScene, materials: Material[]): Group[] {
const kinds = KIND_LOOK.map(() => new Group());
const mats = KIND_LOOK.map(([color, opacity]) => new MeshLambertMaterial({
color, flatShading: true, side: DoubleSide, transparent: opacity < 1, opacity, depthWrite: opacity >= 1,
}));
materials.push(...mats);
for (const m of scene.meshes) {
const g = new BufferGeometry();
const pos = new Float32Array(m.positions);
for (let i = 2; i < pos.length; i += 3) pos[i] = -(pos[i] ?? 0);
g.setAttribute('position', new BufferAttribute(pos, 3));
g.setIndex(new BufferAttribute(m.indices, 1));
g.computeBoundingSphere();
const mat = mats[m.kind] ?? mats[0];
if (mat !== undefined) kinds[m.kind]?.add(new Mesh(g, mat));
}
return kinds;
}
export function buildMapMeshes(scene: MapScene, nav: MapLayer | undefined): MapMeshes {
const group = new Group();
const materials: Material[] = [];
const terrainMat = new MeshLambertMaterial({ vertexColors: true });
materials.push(terrainMat);
const terrain = new Mesh(terrainGeometry(scene.terrain, nav), terrainMat);
group.add(terrain);
const kinds = objectKinds(scene, materials);
for (const k of kinds) group.add(k);
if (scene.waterLevel !== undefined) {
const w = scene.boundsMax[0] - scene.boundsMin[0];
const d = scene.boundsMax[1] - scene.boundsMin[1];
const waterMat = new MeshLambertMaterial({ color: 0x2d5f8a, transparent: true, opacity: 0.55, depthWrite: false });
materials.push(waterMat);
const water = new Mesh(new PlaneGeometry(w, d), waterMat);
water.rotation.x = -Math.PI / 2;
water.position.set(scene.boundsMin[0] + w / 2, scene.waterLevel, -(scene.boundsMin[1] + d / 2));
group.add(water);
}
const meshes: MapMeshes = {
group, terrain, kinds,
dispose() {
group.traverse((o) => { if (o instanceof Mesh) (o.geometry as BufferGeometry).dispose(); });
terrainMat.map?.dispose();
for (const m of materials) m.dispose();
},
};
if (nav !== undefined) setTerrainImage(meshes, nav);
return meshes;
}
-182
View File
@@ -1,182 +0,0 @@
/**
* What is drawn over the map for one moment, rebuilt every update: goal, target and look lines,
* the gun's view cone, recent shots and hits, deaths so far, and the capture zones.
*/
import type { TraceBattle } from '@wto/ground-sim';
import {
AdditiveBlending, BufferAttribute, BufferGeometry, Color, DoubleSide, Group, LineBasicMaterial,
LineSegments, Mesh, MeshBasicMaterial, Points, PointsMaterial,
} from 'three';
import { eventsBetween, type SceneAt, type UnitAt } from '../frames.ts';
import { DEG } from './coords.ts';
import { ARMY_HEX, type TankPool } from './tanks.ts';
export interface Layers {
readonly goals: boolean;
readonly links: boolean;
readonly cones: boolean;
readonly labels: boolean;
readonly events: boolean;
}
const GUN_FOV_HALF_DEG = 30;
const CONE_M = 120;
const CONE_STEPS = 12;
const EVENT_WINDOW_SEC = 2;
const CAP_STEPS = 64;
const WISH_M = 25;
/** Line segments with per-vertex colour, refilled from scratch on every update. */
class Lines {
readonly obj: LineSegments;
private pos: number[] = [];
private col: number[] = [];
constructor(opacity: number, additive = false) {
const mat = new LineBasicMaterial({ vertexColors: true, transparent: true, opacity, depthTest: !additive });
if (additive) mat.blending = AdditiveBlending;
this.obj = new LineSegments(new BufferGeometry(), mat);
this.obj.frustumCulled = false;
}
add(ax: number, ay: number, az: number, bx: number, by: number, bz: number, c: Color): void {
this.pos.push(ax, ay, -az, bx, by, -bz);
this.col.push(c.r, c.g, c.b, c.r, c.g, c.b);
}
flush(): void {
const g = this.obj.geometry;
g.setAttribute('position', new BufferAttribute(Float32Array.from(this.pos), 3));
g.setAttribute('color', new BufferAttribute(Float32Array.from(this.col), 3));
g.computeBoundingSphere();
this.pos = [];
this.col = [];
}
}
const C = {
goal: new Color(0x9aa4ad), target: new Color(0xff4646), targetLost: new Color(0x803030),
look: new Color(0xffa028), wish: new Color(0xffe14a), shot: new Color(0xffff78), dead1: new Color(ARMY_HEX[1]),
dead2: new Color(ARMY_HEX[2]), cap: new Color(0xdddddd),
};
export class Overlays {
readonly group = new Group();
private readonly faint = new Lines(0.35);
private readonly bold = new Lines(0.9);
private readonly shots = new Lines(1, true);
private readonly cones: Mesh;
private readonly hits: Points;
constructor(private readonly tanks: TankPool) {
this.cones = new Mesh(new BufferGeometry(), new MeshBasicMaterial({
color: 0xffffc8, transparent: true, opacity: 0.08, side: DoubleSide, depthWrite: false,
}));
this.cones.frustumCulled = false;
this.hits = new Points(new BufferGeometry(), new PointsMaterial({ size: 6, sizeAttenuation: false, vertexColors: true }));
this.hits.frustumCulled = false;
this.group.add(this.faint.obj, this.bold.obj, this.shots.obj, this.cones, this.hits);
}
/** Height where lines leave a vehicle: its turret top. */
private eye(u: UnitAt): number {
return this.tanks.groundY(u.x, u.y, u.z) + (this.tanks.get(u.unit.eid)?.eyeY ?? 2);
}
update(battle: TraceBattle, scene: SceneAt, layers: Layers): void {
const cone: number[] = [];
for (const u of scene.units.values()) this.botLines(u, scene, layers, cone);
if (layers.events) this.events(battle, scene);
this.deaths(battle, scene.t);
this.caps(scene);
const g = this.cones.geometry;
g.setAttribute('position', new BufferAttribute(Float32Array.from(cone), 3));
this.faint.flush();
this.bold.flush();
this.shots.flush();
}
private botLines(u: UnitAt, scene: SceneAt, layers: Layers, cone: number[]): void {
const bot = u.bot;
if (bot === undefined || !u.unit.alive) return;
const y = this.eye(u);
if (layers.goals && bot.hasOrder) this.faint.add(u.x, y, u.z, bot.goalX, this.tanks.terrainY(bot.goalX, bot.goalZ) + 1, bot.goalZ, C.goal);
const wy = bot.wishYaw * DEG;
this.bold.add(u.x, y, u.z, u.x + Math.cos(wy) * WISH_M, y, u.z + Math.sin(wy) * WISH_M, C.wish);
if (layers.cones) {
for (let i = 0; i < CONE_STEPS; i++) {
const a = (u.gunYaw - GUN_FOV_HALF_DEG + (2 * GUN_FOV_HALF_DEG * i) / CONE_STEPS) * DEG;
const b = (u.gunYaw - GUN_FOV_HALF_DEG + (2 * GUN_FOV_HALF_DEG * (i + 1)) / CONE_STEPS) * DEG;
cone.push(u.x, y, -u.z, u.x + Math.cos(a) * CONE_M, y, -(u.z + Math.sin(a) * CONE_M),
u.x + Math.cos(b) * CONE_M, y, -(u.z + Math.sin(b) * CONE_M));
}
}
if (!layers.links) return;
const target = scene.units.get(bot.target);
if (target !== undefined && bot.target !== '0') {
(bot.targetInSight ? this.bold : this.faint).add(u.x, y, u.z, target.x, this.eye(target), target.z,
bot.targetInSight ? C.target : C.targetLost);
}
const look = scene.units.get(bot.lookAt);
if (look !== undefined && bot.lookAt !== bot.target) this.bold.add(u.x, y, u.z, look.x, this.eye(look), look.z, C.look);
}
private events(battle: TraceBattle, scene: SceneAt): void {
const pos: number[] = [];
const col: number[] = [];
const c = new Color();
for (const e of eventsBetween(battle, scene.t - EVENT_WINDOW_SEC, scene.t)) {
const fade = 1 - (scene.t - e.t) / EVENT_WINDOW_SEC;
if (e.kind === 'SHOT' && e.eid !== undefined) {
const from = scene.units.get(e.eid);
const to = scene.units.get(e.fields['tgt'] ?? '');
if (from === undefined || to === undefined) continue;
this.shots.add(from.x, this.eye(from), from.z, to.x, this.eye(to) - 1, to.z, c.copy(C.shot).multiplyScalar(fade));
} else if (e.kind === 'HIT') {
const x = Number(e.fields['x']);
const z = Number(e.fields['z']);
pos.push(x, this.tanks.terrainY(x, z) + 1.5, -z);
c.set(e.fields['drop'] === '1' ? 0xff3c3c : 0xc8c8c8).multiplyScalar(fade);
col.push(c.r, c.g, c.b);
}
}
this.hits.geometry.setAttribute('position', new BufferAttribute(Float32Array.from(pos), 3));
this.hits.geometry.setAttribute('color', new BufferAttribute(Float32Array.from(col), 3));
}
private deaths(battle: TraceBattle, t: number): void {
for (const e of eventsBetween(battle, battle.startT, t)) {
if (e.kind !== 'DEATH') continue;
const x = Number(e.fields['x']);
const z = Number(e.fields['z']);
const y = this.tanks.terrainY(x, z) + 0.5;
const c = e.fields['army'] === '1' ? C.dead1 : C.dead2;
this.faint.add(x - 4, y, z - 4, x + 4, y, z + 4, c);
this.faint.add(x - 4, y, z + 4, x + 4, y, z - 4, c);
}
}
private caps(scene: SceneAt): void {
for (const cap of scene.caps) {
const c = new Color(ARMY_HEX[cap.owner] ?? C.cap.getHex());
for (let i = 0; i < CAP_STEPS; i++) {
const a = (i / CAP_STEPS) * Math.PI * 2;
const b = ((i + 1) / CAP_STEPS) * Math.PI * 2;
const ax = cap.x + Math.cos(a) * cap.r;
const az = cap.z + Math.sin(a) * cap.r;
const bx = cap.x + Math.cos(b) * cap.r;
const bz = cap.z + Math.sin(b) * cap.r;
this.bold.add(ax, this.tanks.terrainY(ax, az) + 0.8, az, bx, this.tanks.terrainY(bx, bz) + 0.8, bz, c);
}
}
}
dispose(): void {
this.group.traverse((o) => {
if (o instanceof Mesh || o instanceof LineSegments || o instanceof Points) {
o.geometry.dispose();
(o.material as { dispose(): void }).dispose();
}
});
}
}
-141
View File
@@ -1,141 +0,0 @@
/**
* Every vehicle as simple shapes: a hull box tilted by the hull's pitch and roll, a turret box
* turned to the gun's heading, and a barrel at the gun's pitch. Sizes come from the bot's vehicle
* class (players: light or medium).
*/
import { sceneHeightAt, type SceneTerrain } from '@wto/ground-sim';
import {
BoxGeometry, Color, CylinderGeometry, Group, Mesh, MeshLambertMaterial, type Object3D,
} from 'three';
import { CSS2DObject } from 'three/addons/renderers/CSS2DRenderer.js';
import type { UnitAt } from '../frames.ts';
import { DEG } from './coords.ts';
/** Length, width, hull height per vehicle class (medium, light, heavy, tank destroyer, SPAA). */
const SIZES: readonly (readonly [number, number, number])[] = [
[7, 3.4, 1.3], [6, 3, 1.1], [7.6, 3.6, 1.4], [7, 3.3, 1.2], [6.5, 3.1, 1.2],
];
export const ARMY_HEX: Readonly<Record<number, number>> = { 1: 0x4aa3ff, 2: 0xff5c5c };
const DEAD = new Color(0x4a4a4a);
const SELECTED = new Color(0x6a5200);
const NONE = new Color(0);
/** A trace height further than this from the terrain is kept (bridge, building, platform). */
const OFF_GROUND_M = 1.5;
export interface Tank {
readonly root: Group;
readonly turret: Group;
readonly barrel: Group;
readonly label: CSS2DObject;
readonly mats: MeshLambertMaterial[];
/** Turret top above the hull origin, where lines and the gun camera start. */
readonly eyeY: number;
readonly length: number;
}
function sizeOf(u: UnitAt): readonly [number, number, number] {
const cls = u.bot?.vehicleClass ?? (u.unit.light ? 1 : 0);
return SIZES[cls] ?? SIZES[0] ?? [7, 3.4, 1.3];
}
function makeTank(u: UnitAt): Tank {
const [len, wid, hh] = sizeOf(u);
const hullMat = new MeshLambertMaterial();
const turretMat = new MeshLambertMaterial();
const root = new Group();
root.rotation.order = 'YZX';
const hull = new Mesh(new BoxGeometry(len, hh, wid), hullMat);
hull.position.y = hh / 2;
const turret = new Group();
turret.position.set(-len * 0.05, hh, 0);
const tw = wid * 0.7;
const th = hh * 0.65;
const turretBox = new Mesh(new BoxGeometry(len * 0.48, th, tw), turretMat);
turretBox.position.y = th / 2;
const barrel = new Group();
barrel.position.set(len * 0.2, th * 0.55, 0);
const tube = new Mesh(new CylinderGeometry(0.09, 0.11, len * 0.75, 8), turretMat);
tube.rotation.z = -Math.PI / 2;
tube.position.x = len * 0.375;
barrel.add(tube);
turret.add(turretBox, barrel);
root.add(hull, turret);
const div = document.createElement('div');
div.className = 'tank-label';
const label = new CSS2DObject(div);
label.position.y = hh + th + 2.5;
root.add(label);
for (const m of [hull, turretBox, tube]) m.userData['eid'] = u.unit.eid;
return { root, turret, barrel, label, mats: [hullMat, turretMat], eyeY: hh + th, length: len };
}
export class TankPool {
readonly group = new Group();
private readonly tanks = new Map<string, Tank>();
constructor(private readonly terrain: SceneTerrain | undefined) {}
get(eid: string): Tank | undefined {
return this.tanks.get(eid);
}
/** Meshes to pick with a ray. */
pickables(): Object3D[] {
const out: Object3D[] = [];
for (const t of this.tanks.values()) if (t.root.visible) t.root.traverse((o) => { if (o instanceof Mesh) out.push(o); });
return out;
}
terrainY(x: number, z: number): number {
return this.terrain === undefined ? 0 : sceneHeightAt(this.terrain, x, z);
}
/** Ground height for the vehicle: the terrain unless the trace puts it clearly above or below. */
groundY(x: number, y: number, z: number): number {
if (this.terrain === undefined) return y;
const g = sceneHeightAt(this.terrain, x, z);
return Math.abs(y - g) <= OFF_GROUND_M ? g : y;
}
update(units: ReadonlyMap<string, UnitAt>, selected: string | undefined, labels: (u: UnitAt) => string | undefined): void {
for (const [eid, t] of this.tanks) if (!units.has(eid)) t.root.visible = false;
for (const u of units.values()) {
let t = this.tanks.get(u.unit.eid);
if (t === undefined) {
t = makeTank(u);
this.tanks.set(u.unit.eid, t);
this.group.add(t.root);
}
this.place(t, u, u.unit.eid === selected, labels(u));
}
}
private place(t: Tank, u: UnitAt, selected: boolean, label: string | undefined): void {
t.root.visible = true;
t.root.position.set(u.x, this.groundY(u.x, u.y, u.z), -u.z);
t.root.rotation.set(u.hullRoll * DEG, u.yaw * DEG, u.hullPitch * DEG);
const rel = ((((u.gunYaw - u.yaw) % 360) + 540) % 360) - 180;
t.turret.rotation.y = rel * DEG;
const hullSlope = u.hullPitch * Math.cos(rel * DEG) + u.hullRoll * Math.sin(rel * DEG);
t.barrel.rotation.z = (u.gunPitch - hullSlope) * DEG;
const base = u.unit.alive ? new Color(ARMY_HEX[u.unit.army] ?? 0xcccccc) : DEAD;
t.mats.forEach((m, i) => {
m.color.copy(base).multiplyScalar(i === 0 ? 1 : 0.8);
m.emissive.copy(selected ? SELECTED : NONE);
});
t.label.visible = label !== undefined;
if (label !== undefined) t.label.element.textContent = label;
if (u.unit.human) t.label.element.classList.add('human');
}
dispose(): void {
for (const t of this.tanks.values()) {
t.root.traverse((o) => { if (o instanceof Mesh) o.geometry.dispose(); });
for (const m of t.mats) m.dispose();
t.label.element.remove();
}
this.tanks.clear();
}
}
-23
View File
@@ -1,23 +0,0 @@
{
// The lab is a Vite page plus its dev-server API (server/), so it has its own settings and stays
// out of the root typecheck, like the launcher.
"compilerOptions": {
"target": "ES2023",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"types": ["node"],
"jsx": "react-jsx",
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"exactOptionalPropertyTypes": true,
"verbatimModuleSyntax": true,
"allowImportingTsExtensions": true,
"noEmit": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"useDefineForClassFields": true
},
"include": ["src/**/*.ts", "src/**/*.tsx", "server/**/*.ts", "vite.config.ts"]
}
-8
View File
@@ -1,8 +0,0 @@
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
import { labApi } from './server/lab-api.ts';
export default defineConfig({
plugins: [react(), labApi()],
server: { host: '127.0.0.1', port: 47180, strictPort: false },
});
-1
View File
@@ -15,7 +15,6 @@ export default defineConfig({
input: {
index: resolve('src/main/index.ts'),
'build-worker': resolve('src/main/workers/build-worker.ts'),
'server-worker': resolve('src/main/workers/server-worker.ts'),
'save-worker': resolve('src/main/workers/save-worker.ts'),
'patch-check-worker': resolve('src/main/workers/patch-check-worker.ts'),
},
+1 -4
View File
@@ -1,7 +1,7 @@
{
"name": "@wto/launcher",
"productName": "WTOffline Launcher",
"version": "0.1.6",
"version": "0.1.0",
"private": true,
"description": "Installer and launcher of the War Thunder offline project.",
"type": "module",
@@ -9,17 +9,14 @@
"scripts": {
"dev": "electron-vite dev",
"build": "electron-vite build",
"package:win": "npm run build && node ../../scripts/build-windows-installer.ts",
"typecheck": "tsc --noEmit -p tsconfig.node.json && tsc --noEmit -p tsconfig.web.json"
},
"dependencies": {
"@fontsource/roboto-condensed": "^5.3.0",
"@wto/mods": "*",
"@wto/patcher": "*",
"@wto/server": "*",
"fflate": "^0.8.2",
"i18next": "^26.3.6",
"marked": "^18.4.0",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"react-i18next": "^17.0.10",
Binary file not shown.

Before

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.6 KiB

+24 -146
View File
@@ -1,40 +1,21 @@
import { app, BrowserWindow, dialog, shell } from 'electron';
import { isInSteamLibrary, patchFeatures, recordedGameVersions } from '@wto/patcher';
import { patchFeatures, recordedGameVersions } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import { appUpdatesSupported, checkAppUpdate, downloadAppUpdate, installAppUpdate } from '../services/app-update/app-update.ts';
import { listBackgroundPictures } from '../services/background-art/art-catalog.ts';
import { getCopyTuning, updateCopyTuning } from '../services/config/copy-tuning.ts';
import { getSettings, updateSettings } from '../services/config/settings-store.ts';
import { cancelMaintenance, maintainCopy, maintenanceInfo, maintenanceInProgress, maintenanceState } from '../services/copies/copy-maintenance.ts';
import { relocateCopy } from '../services/copies/relocate-copy.ts';
import { cancelMaintenance, maintainCopy, maintenanceInfo, maintenanceInProgress } from '../services/copies/copy-maintenance.ts';
import { exportDiagnostics, openLogsFolder } from '../services/diagnostics/diagnostics.ts';
import { measureFolder } from '../services/game-folder/folder-size.ts';
import { inspectGameFolder, requireFolder } from '../services/game-folder/inspect-game-folder.ts';
import { inspectPickedTargetFolder } from '../services/game-folder/inspect-target-folder.ts';
import { changeDecalSource, decalImportInProgress, detectDecalCacheSource } from '../services/install/decals.ts';
import { cancelInstall, checkGameFolder, dataFolderProblem, installGame, installationInProgress } from '../services/install/install-game.ts';
import { canonicalCopyPath, copyFolderMissing, createCopyDraft, hydrateCopiesStatus, listCopies, readInstallRecord, renameCopy, setCurrentCopy } from '../services/install/install-record.ts';
import { inspectTargetFolder } from '../services/game-folder/inspect-target-folder.ts';
import { cancelInstall, checkGameFolder, installGame } from '../services/install/install-game.ts';
import { createCopyDraft, listCopies, readInstallRecord, renameCopy, setCurrentCopy } from '../services/install/install-record.ts';
import { readInstalledLab } from '../services/launch/lab-handoff.ts';
import { getLaunchState, launchInProgress, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts';
import { activeMapNav, applyMapNavUpdate, checkMapNavUpdate, useLocalMapNav } from '../services/map-nav/map-nav-update.ts';
import { getLaunchState, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts';
import { activePatchSet, applyPackUpdate, checkPackUpdate, revertToBundledPatchSet } from '../services/patch-pack/pack-update.ts';
import {
applyModPreset,
autoSortMods,
deleteModPreset,
exportModPreset,
getModsState,
importModPreset,
openModsFolder,
saveModPreset,
setModEnabled,
setModsFolder,
setModsOrder,
} from '../services/mods/mods-service.ts';
import { resourcePaths } from '../services/resources/resource-paths.ts';
import { changeSaveCrew, getSaveCrews, previewSaveCrew } from '../services/saves/manage-save-crews.ts';
import { changeSaveAccount, changeSaveResearch, copyOnlineData, createSave, discoverOnlineData, exportSave, getSaveAvatarChoices, getSaveAvatarPreview, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts';
import { rememberDialogPath, resolveDialogDefaultPath } from '../util/dialog-paths.ts';
import { changeSaveResearch, createSave, exportSave, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts';
import { broadcast, handle } from './register.ts';
/** Registers the handler of every contract channel. One line per channel; the work is in services/. */
@@ -45,7 +26,6 @@ export function registerIpcHandlers(): void {
version: app.getVersion(),
electron: process.versions.electron,
development: !app.isPackaged,
appUpdatesSupported: appUpdatesSupported(),
systemLocale: app.getLocale(),
userDataPath: app.getPath('userData'),
supportedGameVersions: recordedGameVersions(resources.patches),
@@ -71,37 +51,16 @@ export function registerIpcHandlers(): void {
BrowserWindow.fromWebContents(sender)?.close();
});
handle('dialog:pickFolder', async ({ title, defaultPath }, sender) => {
handle('dialog:pickFolder', async ({ title }, sender) => {
const window = BrowserWindow.fromWebContents(sender);
const resolvedDefaultPath = await resolveDialogDefaultPath('folder', defaultPath);
const options = {
properties: ['openDirectory', 'createDirectory'] as Array<'openDirectory' | 'createDirectory'>,
...(title ? { title } : {}),
...(resolvedDefaultPath ? { defaultPath: resolvedDefaultPath } : {}),
};
const options = { properties: ['openDirectory', 'createDirectory'] as Array<'openDirectory' | 'createDirectory'>, ...(title ? { title } : {}) };
const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
const chosen = result.canceled ? null : (result.filePaths[0] ?? null);
if (chosen) await rememberDialogPath('folder', chosen);
return { path: chosen };
return { path: result.canceled ? null : (result.filePaths[0] ?? null) };
});
handle('install:prepareCopy', () => createCopyDraft());
handle('install:inspectGameFolder', ({ path }) => inspectGameFolder(path));
handle('install:inspectTargetFolder', ({ path, stockPath, version }) =>
inspectPickedTargetFolder(path, stockPath, version ?? null));
handle('install:inspectDataFolder', async ({ path, copyPath, sourcePath, stockSourcePath }) => {
const [resolved, resolvedCopy, resolvedSource, resolvedStock] = await Promise.all([
canonicalCopyPath(path),
copyPath ? canonicalCopyPath(copyPath) : Promise.resolve(null),
sourcePath ? canonicalCopyPath(sourcePath) : Promise.resolve(null),
stockSourcePath ? canonicalCopyPath(stockSourcePath) : Promise.resolve(null),
]);
return {
path: resolved,
inSteam: isInSteamLibrary(path) || isInSteamLibrary(resolved),
problem: dataFolderProblem(resolved, resolvedCopy, resolvedSource, resolvedStock),
};
});
handle('install:inspectTargetFolder', ({ path, stockPath }) => inspectTargetFolder(path, stockPath));
handle('install:measureFolder', async ({ path }) => {
await requireFolder(path);
try {
@@ -112,69 +71,45 @@ export function registerIpcHandlers(): void {
}
});
handle('install:checkPatches', ({ gamePath, dataPath, stockSourcePath }) =>
checkGameFolder(gamePath, dataPath, stockSourcePath));
handle('install:checkPatches', ({ gamePath, dataPath }) => checkGameFolder(gamePath, dataPath));
handle('install:start', async (request) => {
if (maintenanceInProgress()) throw new AppError('maintenance_busy');
const record = await installGame(request, (progress) => broadcast('event:install-progress', progress));
broadcast('event:copies-changed', await hydrateCopiesStatus(await listCopies()));
broadcast('event:copies-changed', await listCopies());
return record;
});
handle('install:cancel', () => ({ cancelled: cancelInstall() }));
handle('install:getRecord', async () => {
const record = await readInstallRecord();
if (!record) return { record: null };
return { record: (await copyFolderMissing(record.copyPath)) ? { ...record, folderMissing: true } : record };
});
handle('install:getRecord', async () => ({ record: await readInstallRecord() }));
handle('install:listFeatures', () => {
const resources = resourcePaths();
return patchFeatures(resources.patches).map((feature) => ({ ...feature, patchIds: [...feature.patchIds] }));
});
handle('copies:list', async () => hydrateCopiesStatus(await listCopies()));
handle('copies:list', () => listCopies());
handle('copies:setCurrent', async ({ id }) => {
const registry = await hydrateCopiesStatus(await setCurrentCopy(id));
const registry = await setCurrentCopy(id);
broadcast('event:copies-changed', registry);
return registry;
});
handle('copies:rename', async ({ id, name }) => {
const registry = await hydrateCopiesStatus(await renameCopy(id, name));
broadcast('event:copies-changed', registry);
return registry;
});
handle('copies:relocate', async ({ id, path }) => {
if (launchInProgress() || maintenanceInProgress() || installationInProgress() || saveWriteInProgress() || decalImportInProgress()) {
throw new AppError('maintenance_busy');
}
const registry = await relocateCopy(id, path);
const registry = await renameCopy(id, name);
broadcast('event:copies-changed', registry);
return registry;
});
handle('copies:setDecalSource', async ({ id, path }) => {
if (launchInProgress() || maintenanceInProgress() || installationInProgress()) throw new AppError('maintenance_busy');
const updated = await hydrateCopiesStatus(await changeDecalSource(id, path));
broadcast('event:copies-changed', updated);
return updated;
});
handle('copies:maintenanceInfo', ({ id }) => maintenanceInfo(id));
handle('copies:maintenanceState', () => maintenanceState());
handle('copies:maintain', async (request) => {
if (saveWriteInProgress() || decalImportInProgress()) throw new AppError('maintenance_busy');
const updated = await hydrateCopiesStatus(await maintainCopy(request, (progress) => broadcast('event:copy-maintenance', progress)));
if (saveWriteInProgress()) throw new AppError('maintenance_busy');
const updated = await maintainCopy(request, (progress) => broadcast('event:copy-maintenance', progress));
broadcast('event:copies-changed', updated);
return updated;
});
handle('copies:cancelMaintenance', () => cancelMaintenance());
handle('decals:detectSource', async ({ path }) => ({ path: await detectDecalCacheSource(path) }));
handle('saves:list', ({ copyId }) => getSaveList(copyId));
handle('saves:details', ({ copyId, userId }) => getSaveDetails(copyId, userId));
handle('saves:setCurrent', ({ copyId, userId }) => selectSave(copyId, userId));
handle('saves:create', (request) => createSave(request));
handle('saves:avatars', ({ copyId }) => getSaveAvatarChoices(copyId));
handle('saves:avatarPreview', ({ copyId, avatar }) => getSaveAvatarPreview(copyId, avatar));
handle('saves:editAccount', ({ copyId, userId, edits }) => changeSaveAccount(copyId, userId, edits));
handle('saves:editCurrencies', ({ copyId, userId, values }) => setSaveCurrencies(copyId, userId, values));
handle('saves:pickArchive', (_input, sender) => pickSaveArchive(BrowserWindow.fromWebContents(sender)));
@@ -185,69 +120,22 @@ export function registerIpcHandlers(): void {
handle('saves:takeBackup', ({ copyId, userId }) => takeSaveBackup(copyId, userId));
handle('saves:restoreBackup', ({ copyId, userId, name }) => restoreSaveBackup(copyId, userId, name));
handle('saves:discoverOnlineData', () => discoverOnlineData());
handle('saves:copyOnlineData', ({ copyId, userId, accountId }) => copyOnlineData(copyId, userId, accountId));
handle('saves:pickOfficialBackups', (_input, sender) => pickOfficialBackups(BrowserWindow.fromWebContents(sender)));
handle('saves:previewOfficial', ({ copyId, userId, paths }) =>
previewSelectedBackups(copyId, userId, paths));
handle('saves:previewOfficial', ({ copyId, userId, paths, includeUsedVehicles }) =>
previewSelectedBackups(copyId, userId, paths, includeUsedVehicles));
handle('saves:importOfficial', ({ copyId, userId, paths, options }) =>
importSelectedBackups(copyId, userId, paths, options));
handle('saves:research', ({ copyId, userId, branch }) => getSaveResearch(copyId, userId, branch));
handle('saves:editResearch', ({ copyId, userId, branch, action }) => changeSaveResearch(copyId, userId, branch, action));
handle('saves:crews', ({ copyId, userId, country }) => getSaveCrews(copyId, userId, country));
handle('saves:previewCrew', ({ copyId, userId, country, edit }) => previewSaveCrew(copyId, userId, country, edit));
handle('saves:editCrew', ({ copyId, userId, country, edit, token }) => changeSaveCrew(copyId, userId, country, edit, token));
handle('tuning:get', ({ copyId }) => getCopyTuning(copyId));
handle('tuning:update', ({ copyId, patch }) => updateCopyTuning(copyId, patch));
const requireModsWritable = (): void => {
if (launchInProgress() || maintenanceInProgress()) throw new AppError('mods_read_only');
};
handle('mods:getState', ({ copyId }) => getModsState(copyId));
handle('mods:setEnabled', ({ copyId, modId, enabled }) => {
requireModsWritable();
return setModEnabled(copyId, modId, enabled);
});
handle('mods:setOrder', ({ copyId, order }) => {
requireModsWritable();
return setModsOrder(copyId, order);
});
handle('mods:autoSort', ({ copyId }) => {
requireModsWritable();
return autoSortMods(copyId);
});
handle('mods:savePreset', ({ copyId, name, overwriteId }) => {
requireModsWritable();
return saveModPreset(copyId, name, overwriteId);
});
handle('mods:applyPreset', ({ copyId, presetId }) => {
requireModsWritable();
return applyModPreset(copyId, presetId);
});
handle('mods:deletePreset', ({ copyId, presetId }) => {
requireModsWritable();
return deleteModPreset(copyId, presetId);
});
handle('mods:exportPreset', ({ copyId, presetId }, sender) =>
exportModPreset(copyId, presetId, BrowserWindow.fromWebContents(sender)));
handle('mods:importPreset', ({ copyId }, sender) => {
requireModsWritable();
return importModPreset(copyId, BrowserWindow.fromWebContents(sender));
});
handle('mods:openFolder', () => openModsFolder());
handle('mods:setFolder', async ({ copyId, path }) => {
requireModsWritable();
const state = await setModsFolder(copyId, path);
broadcast('event:settings-changed', await getSettings());
return state;
});
handle('launch:getState', () => getLaunchState());
handle('launch:getLabInfo', () => readInstalledLab().catch(() => null));
handle('launch:start', () => {
if (maintenanceInProgress() || saveWriteInProgress() || decalImportInProgress()) throw new AppError('maintenance_busy');
if (maintenanceInProgress() || saveWriteInProgress()) throw new AppError('maintenance_busy');
return startLaunch((state) => broadcast('event:launch-state', state));
});
handle('launch:stop', async () => { await stopLaunch(); });
@@ -255,10 +143,10 @@ export function registerIpcHandlers(): void {
handle('patches:active', () => activePatchSet());
handle('patches:check', () => checkPackUpdate());
handle('patches:apply', async ({ version }) => {
handle('patches:apply', async () => {
// A build reads the patch set while it runs; switch only between builds.
if (maintenanceInProgress()) throw new AppError('maintenance_busy');
const result = await applyPackUpdate(version);
const result = await applyPackUpdate();
if (result.ok) broadcast('event:patch-set-changed', result.active);
return result;
});
@@ -269,16 +157,6 @@ export function registerIpcHandlers(): void {
return active;
});
handle('updates:check', () => checkAppUpdate());
handle('map-nav:active', () => activeMapNav());
handle('map-nav:check', () => checkMapNavUpdate());
handle('map-nav:apply', ({ version }) => applyMapNavUpdate(version, (progress) =>
broadcast('event:map-nav-progress', progress)));
handle('map-nav:deactivate', () => useLocalMapNav());
handle('updates:download', ({ version }) => downloadAppUpdate(version, (progress) => broadcast('event:app-update-progress', progress)));
handle('updates:install', ({ version }) => installAppUpdate(version, () =>
launchInProgress() || installationInProgress() || maintenanceInProgress() || saveWriteInProgress() || decalImportInProgress()));
handle('settings:get', () => getSettings());
handle('settings:update', async (patch) => {
const settings = await updateSettings(patch);
@@ -1,189 +0,0 @@
import { spawn } from 'node:child_process';
import { once } from 'node:events';
import { dirname, join } from 'node:path';
import { app } from 'electron';
import { compareAppVersions, packSigningPublicKey, PatchPackError, patchPackTuning, verifyEd25519 } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import {
LauncherReleaseManifest,
PortableReleaseManifest,
type AppUpdateCheck, type AppUpdateProgress,
} from '@shared/schemas/app-update.ts';
import { gameProcessRunning } from '../launch/game-process.ts';
import {
newestProjectRelease, projectReleaseVersion, ReleasePageLimitError, sameReleaseSource, withReleaseSources, type LauncherRelease,
} from '../patch-pack/release-feed.ts';
import {
FeedUnreachableError, readReleaseAsset, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES, stageReleaseAsset,
} from '../patch-pack/release-assets.ts';
import { installerDigest, launcherSignaturePayload, portableSignaturePayload } from './installer-integrity.ts';
import {
cleanupPreparedPortableInstall, isPortableLauncher, launchPortableUpdater, preparePortableInstall,
} from './portable-update.ts';
type UpdateMode = 'installer' | 'portable';
interface OfferedUpdate {
readonly mode: UpdateMode;
readonly release: LauncherRelease;
readonly manifest: LauncherReleaseManifest | PortableReleaseManifest;
}
class ManifestSignatureError extends Error {}
let offered: OfferedUpdate | null = null;
let updating = false;
export function appUpdatesSupported(): boolean {
return app.isPackaged && process.platform === 'win32' && process.arch === 'x64';
}
async function exclusively<T>(action: () => Promise<T>): Promise<T> {
if (!appUpdatesSupported()) throw new AppError('app_update_unavailable');
if (updating) throw new AppError('app_update_busy');
updating = true;
try {
return await action();
} finally {
updating = false;
}
}
function updatesRoot(): string {
return join(app.getPath('userData'), 'launcher-updates');
}
function stagedArtifact(mode: UpdateMode): string {
return join(updatesRoot(), mode === 'portable' ? 'portable.zip' : 'installer.exe');
}
async function matchesArtifact(path: string, manifest: LauncherReleaseManifest | PortableReleaseManifest): Promise<boolean> {
try {
const digest = await installerDigest(path, manifest.size);
return digest.size === manifest.size && digest.sha256 === manifest.sha256;
} catch {
return false;
}
}
function offerResult(offer: OfferedUpdate, ready: boolean): AppUpdateCheck {
return {
status: 'available',
release: { version: offer.manifest.version, size: offer.manifest.size, notes: offer.release.notes },
ready,
};
}
function selectedOffer(version: string): OfferedUpdate {
if (!offered || version !== offered.manifest.version || compareAppVersions(version, app.getVersion()) <= 0) {
throw new AppError('app_update_unavailable');
}
return offered;
}
async function signedOffer(release: LauncherRelease, key: string): Promise<OfferedUpdate> {
const deadline = AbortSignal.timeout(patchPackTuning().requestTimeoutMs);
if (isPortableLauncher(app.isPackaged) && release.portable) {
const [bytes, signature] = await Promise.all([
readReleaseAsset(release.portable.manifest, RELEASE_MANIFEST_MAX_BYTES, deadline, release.source),
readReleaseAsset(release.portable.signature, RELEASE_SIGNATURE_MAX_BYTES, deadline, release.source),
]);
if (!verifyEd25519(portableSignaturePayload(bytes), new TextDecoder().decode(signature), key)) {
throw new ManifestSignatureError('The portable release manifest signature does not match.');
}
const manifest = PortableReleaseManifest.parse(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)));
if (manifest.version !== release.version) throw new Error('The signed portable manifest version does not match the release tag.');
return { mode: 'portable', release, manifest };
}
const [bytes, signature] = await Promise.all([
readReleaseAsset(release.manifest, RELEASE_MANIFEST_MAX_BYTES, deadline, release.source),
readReleaseAsset(release.signature, RELEASE_SIGNATURE_MAX_BYTES, deadline, release.source),
]);
if (!verifyEd25519(launcherSignaturePayload(bytes), new TextDecoder().decode(signature), key)) {
throw new ManifestSignatureError('The release manifest signature does not match.');
}
const manifest = LauncherReleaseManifest.parse(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)));
if (manifest.version !== release.version) throw new Error('The signed manifest version does not match the release tag.');
return { mode: 'installer', release, manifest };
}
export function checkAppUpdate(): Promise<AppUpdateCheck> {
return exclusively(async () => {
offered = null;
try {
const key = packSigningPublicKey();
if (!key) return { status: 'failed', problem: 'no_signing_key' };
const installedVersion = app.getVersion();
const offer = await withReleaseSources(async (source) => {
const latest = await newestProjectRelease('launcher', installedVersion, source);
if (!latest || compareAppVersions(latest.version, installedVersion) <= 0) return null;
return signedOffer(latest, key);
});
if (!offer) return { status: 'current' };
offered = offer;
return offerResult(offer, await matchesArtifact(stagedArtifact(offer.mode), offer.manifest));
} catch (error) {
console.warn('[app-update] checking the release failed:', error);
if (error instanceof ReleasePageLimitError) return { status: 'failed', problem: 'page_limit' };
if (error instanceof ManifestSignatureError) return { status: 'failed', problem: 'signature' };
if (error instanceof FeedUnreachableError || (error instanceof Error && error.name === 'TimeoutError')) {
return { status: 'failed', problem: 'network' };
}
if (error instanceof PatchPackError && error.problem === 'key') return { status: 'failed', problem: 'no_signing_key' };
return { status: 'failed', problem: 'contents' };
}
});
}
export function downloadAppUpdate(
version: string, report: (progress: AppUpdateProgress) => void,
): Promise<AppUpdateCheck> {
return exclusively(async () => {
const offer = selectedOffer(version);
const target = stagedArtifact(offer.mode);
if (await matchesArtifact(target, offer.manifest)) return offerResult(offer, true);
try {
await withReleaseSources(async (source) => {
const release = sameReleaseSource(source, offer.release.source)
? offer.release : await projectReleaseVersion('launcher', version, source);
const assetUrl = offer.mode === 'portable' ? release.portable?.archive : release.installer;
if (!assetUrl) throw new FeedUnreachableError(`This update source does not have the ${offer.mode} asset for ${version}.`);
await stageReleaseAsset(assetUrl, release.source, offer.manifest, target, report);
}, offer.release.source);
return offerResult(offer, true);
} catch (error) {
console.warn('[app-update] preparing the update asset failed:', error);
throw new AppError('app_update_download_failed');
}
});
}
export function installAppUpdate(version: string, launcherBusy: () => boolean): Promise<void> {
return exclusively(async () => {
const offer = selectedOffer(version);
if (launcherBusy()) throw new AppError('app_update_launcher_busy');
const path = stagedArtifact(offer.mode);
if (!await matchesArtifact(path, offer.manifest)) throw new AppError('app_update_installer_invalid');
const signal = AbortSignal.timeout(5000);
if (await gameProcessRunning(signal) || launcherBusy()) throw new AppError('app_update_launcher_busy');
try {
if (offer.mode === 'portable') {
const prepared = await preparePortableInstall(path, offer.manifest.version, updatesRoot());
try {
await launchPortableUpdater(prepared);
} catch (launchError) {
await cleanupPreparedPortableInstall(prepared);
throw launchError;
}
app.quit();
return;
}
const installer = spawn(path, [], { cwd: dirname(path), detached: true, stdio: 'ignore', shell: false });
await once(installer, 'spawn');
installer.unref();
app.quit();
} catch (error) {
console.warn('[app-update] starting the update failed:', error);
throw new AppError('app_update_install_failed');
}
});
}
@@ -1,25 +0,0 @@
import { createHash } from 'node:crypto';
import { createReadStream } from 'node:fs';
import { MAX_INSTALLER_BYTES } from '../../../shared/schemas/app-update.ts';
const SIGNATURE_DOMAIN = Buffer.from('WTOffline launcher release v1\n', 'utf8');
const PORTABLE_SIGNATURE_DOMAIN = Buffer.from('WTOffline launcher portable release v1\n', 'utf8');
export function launcherSignaturePayload(manifest: Uint8Array): Uint8Array {
return Buffer.concat([SIGNATURE_DOMAIN, manifest]);
}
export function portableSignaturePayload(manifest: Uint8Array): Uint8Array {
return Buffer.concat([PORTABLE_SIGNATURE_DOMAIN, manifest]);
}
export async function installerDigest(path: string, limit = MAX_INSTALLER_BYTES): Promise<{ size: number; sha256: string }> {
const hash = createHash('sha256');
let size = 0;
for await (const chunk of createReadStream(path)) {
size += (chunk as Buffer).length;
if (size > limit) throw new Error('The installer is larger than expected.');
hash.update(chunk as Buffer);
}
return { size, sha256: hash.digest('hex') };
}
@@ -1,323 +0,0 @@
/**
* In-place updater for portable (unpacked ZIP) launcher builds on Windows.
*
* Extraction and path validation happen while the launcher is still running so a bad archive or
* read-only folder fails cleanly before quitting. Once staged, a detached PowerShell helper waits
* for this process to exit, overwrites only files listed in the new portable inventory, removes
* only obsolete files listed in the previous portable inventory (never touching unrelated user
* files in the same folder), and restarts the updated executable.
*/
import { execFile } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import * as nodeFs from 'node:fs';
import { existsSync } from 'node:fs';
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
import { promisify } from 'node:util';
import { z } from 'zod';
const execute = promisify(execFile);
const require = createRequire(import.meta.url);
export const PORTABLE_MARKER_FILE = 'portable-mode';
export const PORTABLE_FILES_MANIFEST = 'portable-files.json';
export const PORTABLE_UPDATE_LOG_FILENAME = 'portable-update.log';
const LAUNCHER_EXECUTABLE = 'WTOffline Launcher.exe';
const UNINSTALLER_EXECUTABLE = 'Uninstall WTOffline Launcher.exe';
// Electron patches node:fs to expose .asar archives as virtual directories, which makes
// lstat().isFile() return false and recursive rm() fail on staged .asar files.
function rawFsPromises(): typeof nodeFs.promises {
try {
return (require('original-fs') as typeof nodeFs).promises;
} catch {
return nodeFs.promises;
}
}
const PortableInventorySchema = z.object({
format: z.literal(1),
version: z.string().min(1),
files: z.array(z.string().min(1)).min(1),
});
export interface PreparedPortableUpdate {
readonly scriptPath: string;
readonly planPath: string;
readonly stagingDir: string;
}
export interface PortableUpdatePlan {
readonly pid: number;
readonly installDir: string;
readonly stagingDir: string;
readonly archivePath: string;
readonly logPath: string;
readonly executable: string;
readonly newFiles: readonly string[];
readonly staleFiles: readonly string[];
}
export function isPortableLauncher(isPackaged: boolean): boolean {
if (!isPackaged || process.platform !== 'win32') return false;
if (existsSync(join(process.resourcesPath, PORTABLE_MARKER_FILE))) return true;
return !existsSync(join(dirname(process.execPath), UNINSTALLER_EXECUTABLE));
}
/** Validate a POSIX-style relative path from a portable inventory against traversal or drive prefixes. */
export function isSafePortableRelativePath(entry: string): boolean {
if (!entry || entry.includes('\\') || entry.includes(':') || entry.startsWith('/')) return false;
if (/[\0-\x1f]/.test(entry)) return false;
const parts = entry.split('/');
return parts.every((part) => part.length > 0 && part !== '.' && part !== '..');
}
function resolveInside(root: string, relPosix: string): string {
if (!isSafePortableRelativePath(relPosix)) throw new Error(`Unsafe portable path: ${relPosix}`);
const target = resolve(root, ...relPosix.split('/'));
const rel = relative(root, target);
if (!rel || rel.startsWith('..') || isAbsolute(rel)) {
throw new Error(`Portable path escapes root: ${relPosix}`);
}
return target;
}
async function readPortableInventory(resourcesDir: string): Promise<readonly string[] | null> {
try {
const raw = await readFile(join(resourcesDir, PORTABLE_FILES_MANIFEST), 'utf8');
const parsed = PortableInventorySchema.parse(JSON.parse(raw));
return parsed.files.filter(isSafePortableRelativePath);
} catch {
return null;
}
}
async function assertWritableFolder(folder: string): Promise<void> {
const probe = join(folder, `.wto-update-probe-${randomUUID()}.tmp`);
await writeFile(probe, '', { flag: 'wx' });
await rm(probe, { force: true });
}
async function extractPortableArchive(zipPath: string, stagingDir: string, updatesRoot: string): Promise<void> {
const extractScriptPath = join(updatesRoot, `extract-portable-${randomUUID()}.ps1`);
const script = [
'param([string]$ZipPath, [string]$DestDir)',
"$ErrorActionPreference = 'Stop'",
'Add-Type -AssemblyName System.IO.Compression.FileSystem',
'$destFull = [System.IO.Path]::GetFullPath($DestDir)',
'if (-not $destFull.EndsWith([System.IO.Path]::DirectorySeparatorChar)) { $destFull += [System.IO.Path]::DirectorySeparatorChar }',
'$zip = [System.IO.Compression.ZipFile]::OpenRead($ZipPath)',
'try {',
' foreach ($entry in $zip.Entries) {',
' $name = $entry.FullName',
' if ([string]::IsNullOrEmpty($name) -or $name.EndsWith("/") -or $name.EndsWith("\\")) { continue }',
' if ($name.Contains("..") -or $name.StartsWith("/") -or $name.StartsWith("\\") -or $name.Contains(":")) {',
' throw "Unsafe zip entry: $name"',
' }',
' $target = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($destFull, $name))',
' if (-not $target.StartsWith($destFull, [System.StringComparison]::OrdinalIgnoreCase)) {',
' throw "Zip entry escapes destination: $name"',
' }',
' $parent = [System.IO.Path]::GetDirectoryName($target)',
' if ($parent) { [System.IO.Directory]::CreateDirectory($parent) | Out-Null }',
' [System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $target, $true)',
' }',
'} finally {',
' $zip.Dispose()',
'}',
].join('\r\n');
// UTF-8 BOM ensures Windows PowerShell 5.1 decodes non-ASCII paths properly.
await writeFile(extractScriptPath, `\uFEFF${script}\r\n`, 'utf8');
try {
await execute('powershell.exe', [
'-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
'-File', extractScriptPath, zipPath, stagingDir,
], { windowsHide: true, timeout: 180_000 });
} finally {
await rm(extractScriptPath, { force: true }).catch(() => undefined);
}
}
export function buildPortableApplyScript(): string {
return [
'param([string]$PlanPath)',
"$ErrorActionPreference = 'Stop'",
'$utf8 = New-Object System.Text.UTF8Encoding($false)',
'$plan = [System.IO.File]::ReadAllText($PlanPath, $utf8) | ConvertFrom-Json',
'function Write-Log([string]$msg) {',
' try {',
' $line = "$(Get-Date -Format o) $msg`r`n"',
' [System.IO.File]::AppendAllText($plan.logPath, $line, $utf8)',
' } catch {}',
'}',
'try {',
' Write-Log "Starting portable update in $($plan.installDir) (waiting for pid $($plan.pid))"',
' $deadline = (Get-Date).AddSeconds(30)',
' while ((Get-Date) -lt $deadline) {',
' if (-not (Get-Process -Id $plan.pid -ErrorAction SilentlyContinue)) { break }',
' Start-Sleep -Milliseconds 200',
' }',
' Start-Sleep -Milliseconds 400',
' foreach ($rel in $plan.newFiles) {',
' $winRel = $rel -replace "/", "\\"',
' $src = [System.IO.Path]::Combine($plan.stagingDir, $winRel)',
' $dst = [System.IO.Path]::Combine($plan.installDir, $winRel)',
' $parent = [System.IO.Path]::GetDirectoryName($dst)',
' if ($parent) { [System.IO.Directory]::CreateDirectory($parent) | Out-Null }',
' $copied = $false',
' for ($attempt = 1; $attempt -le 20; $attempt++) {',
' try {',
' if ([System.IO.File]::Exists($dst)) { [System.IO.File]::SetAttributes($dst, [System.IO.FileAttributes]::Normal) }',
' [System.IO.File]::Copy($src, $dst, $true)',
' $copied = $true',
' break',
' } catch {',
' if ($attempt -eq 20) { throw }',
' Start-Sleep -Milliseconds 300',
' }',
' }',
' if (-not $copied) { throw "Failed to copy $rel" }',
' }',
' $installRoot = [System.IO.Path]::GetFullPath($plan.installDir).TrimEnd("\\")',
' foreach ($rel in $plan.staleFiles) {',
' $winRel = $rel -replace "/", "\\"',
' $old = [System.IO.Path]::Combine($plan.installDir, $winRel)',
' if ([System.IO.File]::Exists($old)) {',
' try {',
' [System.IO.File]::SetAttributes($old, [System.IO.FileAttributes]::Normal)',
' [System.IO.File]::Delete($old)',
' } catch { Write-Log "Could not remove stale file ${rel}: $_" }',
' }',
' $dir = [System.IO.Path]::GetDirectoryName($old)',
' while ($dir -and ($dir.TrimEnd("\\") -ne $installRoot)) {',
' if (-not [System.IO.Directory]::Exists($dir)) { break }',
' $entries = [System.IO.Directory]::GetFileSystemEntries($dir)',
' if ($entries.Length -gt 0) { break }',
' try { [System.IO.Directory]::Delete($dir) } catch { break }',
' $dir = [System.IO.Path]::GetDirectoryName($dir)',
' }',
' }',
' Write-Log "Replaced $($plan.newFiles.Count) files and cleaned $($plan.staleFiles.Count) obsolete files."',
' if ($plan.stagingDir -and [System.IO.Directory]::Exists($plan.stagingDir)) {',
' try { Remove-Item -LiteralPath $plan.stagingDir -Recurse -Force } catch {}',
' }',
' if ($plan.archivePath -and [System.IO.File]::Exists($plan.archivePath)) {',
' try { Remove-Item -LiteralPath $plan.archivePath -Force } catch {}',
' }',
' if ([System.IO.File]::Exists($PlanPath)) {',
' try { Remove-Item -LiteralPath $PlanPath -Force } catch {}',
' }',
' $exe = [System.IO.Path]::Combine($plan.installDir, $plan.executable)',
' if ([System.IO.File]::Exists($exe)) {',
' Start-Process -FilePath $exe -WorkingDirectory $plan.installDir',
' Write-Log "Relaunched $exe"',
' }',
'} catch {',
' Write-Log "Portable update failed: $_"',
' exit 1',
'}',
].join('\r\n');
}
export async function preparePortableInstall(
archivePath: string,
expectedVersion: string,
updatesRoot: string,
installDir = dirname(process.execPath),
resourcesDir = process.resourcesPath,
parentPid = process.pid,
): Promise<PreparedPortableUpdate> {
await assertWritableFolder(installDir);
await mkdir(updatesRoot, { recursive: true });
const rawFs = rawFsPromises();
const stagingDir = join(updatesRoot, `portable-staging-${randomUUID()}`);
await mkdir(stagingDir, { recursive: true });
try {
await extractPortableArchive(archivePath, stagingDir, updatesRoot);
const stagedInventoryRaw = await readFile(join(stagingDir, 'resources', PORTABLE_FILES_MANIFEST), 'utf8');
const stagedInventory = PortableInventorySchema.parse(JSON.parse(stagedInventoryRaw));
if (stagedInventory.version !== expectedVersion) {
throw new Error(`Portable archive inventory version ${stagedInventory.version} does not match ${expectedVersion}.`);
}
const newFiles = stagedInventory.files;
const newSet = new Set(newFiles);
const requiredEntries = [
LAUNCHER_EXECUTABLE,
`resources/${PORTABLE_MARKER_FILE}`,
`resources/${PORTABLE_FILES_MANIFEST}`,
];
for (const required of requiredEntries) {
if (!newSet.has(required)) throw new Error(`Portable archive inventory is missing ${required}.`);
}
for (const rel of newFiles) {
const stagedPath = resolveInside(stagingDir, rel);
const stats = await rawFs.lstat(stagedPath);
if (!stats.isFile()) throw new Error(`Staged portable entry is not a file: ${rel}`);
}
const oldFiles = await readPortableInventory(resourcesDir);
const staleFiles = oldFiles
? oldFiles.filter((rel) => !newSet.has(rel) && isSafePortableRelativePath(rel))
: [];
const planPath = join(updatesRoot, `portable-plan-${randomUUID()}.json`);
const scriptPath = join(updatesRoot, 'apply-portable-update.ps1');
const plan: PortableUpdatePlan = {
pid: parentPid,
installDir: resolve(installDir),
stagingDir,
archivePath,
logPath: join(updatesRoot, PORTABLE_UPDATE_LOG_FILENAME),
executable: LAUNCHER_EXECUTABLE,
newFiles,
staleFiles,
};
await writeFile(planPath, `${JSON.stringify(plan, null, 2)}\n`, 'utf8');
await writeFile(scriptPath, `\uFEFF${buildPortableApplyScript()}\r\n`, 'utf8');
return { scriptPath, planPath, stagingDir };
} catch (error) {
await rawFs.rm(stagingDir, { recursive: true, force: true }).catch(() => undefined);
throw error;
}
}
export async function cleanupPreparedPortableInstall(prepared: PreparedPortableUpdate): Promise<void> {
const rawFs = rawFsPromises();
await rawFs.rm(prepared.stagingDir, { recursive: true, force: true }).catch(() => undefined);
await rm(prepared.planPath, { force: true }).catch(() => undefined);
}
/**
* Launch the portable apply script in a hidden PowerShell process that survives Electron exit.
*
* On Windows, spawning powershell.exe directly with Node's `detached: true` sets DETACHED_PROCESS
* (no console), causing Windows PowerShell 5.1 ConsoleHost to exit silently with code 0 before
* running `-File`. Spawning without `detached` lets PowerShell run, but Electron tears down
* attached children on `app.quit()`. Using a short hidden PowerShell helper with `Start-Process`
* gives the updater its own hidden console and cleanly detaches it before the launcher quits.
*/
export async function launchPortableUpdater(prepared: PreparedPortableUpdate): Promise<void> {
const workDir = dirname(prepared.scriptPath);
const launcherPath = join(workDir, `launch-portable-${randomUUID()}.ps1`);
const script = [
'param([string]$ScriptPath, [string]$PlanPath, [string]$WorkDir)',
"$ErrorActionPreference = 'Stop'",
'$argsList = @(',
" '-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-ExecutionPolicy', 'Bypass',",
' \'-File\', "`"$ScriptPath`"", "`"$PlanPath`""',
')',
"Start-Process -FilePath 'powershell.exe' -WorkingDirectory $WorkDir -WindowStyle Hidden -ArgumentList $argsList",
].join('\r\n');
// UTF-8 BOM ensures Windows PowerShell 5.1 decodes non-ASCII paths properly.
await writeFile(launcherPath, `\uFEFF${script}\r\n`, 'utf8');
try {
await execute('powershell.exe', [
'-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
'-File', launcherPath, prepared.scriptPath, prepared.planPath, workDir,
], { cwd: workDir, windowsHide: true, timeout: 30_000 });
} finally {
await rm(launcherPath, { force: true }).catch(() => undefined);
}
}
@@ -4,7 +4,6 @@ import { app } from 'electron';
import { AppError } from '@shared/errors.ts';
import { defaultSettings, SettingsSchema, type Settings, type SettingsPatch } from '@shared/schemas/settings.ts';
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
import { setLauncherLoggingEnabled } from '../diagnostics/launcher-log.ts';
/**
* The launcher's settings file, `<user data>/settings.json`. Read once and cached; every change is
@@ -12,7 +11,6 @@ import { setLauncherLoggingEnabled } from '../diagnostics/launcher-log.ts';
*/
let cached: Settings | null = null;
let pending: Promise<void> = Promise.resolve();
function settingsPath(): string {
return join(app.getPath('userData'), 'settings.json');
@@ -37,22 +35,17 @@ export async function getSettings(): Promise<Settings> {
return cached;
}
export function updateSettings(patch: SettingsPatch): Promise<Settings> {
const operation = pending.then(async () => {
const current = await getSettings();
const merged = SettingsSchema.parse({ ...current, ...definedFields(patch) });
try {
await writeJsonAtomic(settingsPath(), merged);
} catch (error) {
console.error('[settings] write failed:', error);
throw new AppError('settings_write_failed');
}
cached = merged;
setLauncherLoggingEnabled(merged.loggingEnabled);
return merged;
});
pending = operation.then(() => undefined, () => undefined);
return operation;
export async function updateSettings(patch: SettingsPatch): Promise<Settings> {
const current = await getSettings();
const merged = SettingsSchema.parse({ ...current, ...definedFields(patch) });
try {
await writeJsonAtomic(settingsPath(), merged);
} catch (error) {
console.error('[settings] write failed:', error);
throw new AppError('settings_write_failed');
}
cached = merged;
return merged;
}
/** The patch without the fields it leaves out, so they do not overwrite current values. */
@@ -1,11 +1,10 @@
import { lstat, mkdir, mkdtemp, rename, rm } from 'node:fs/promises';
import { dirname, isAbsolute, join, normalize, relative, sep } from 'node:path';
import { rawFs } from '../../util/raw-fs.ts';
import { canonicalCopyPath, copyPathContains } from '../install/install-record.ts';
export async function fileInfo(path: string) {
const fsPromises = rawFs().promises;
try {
return await fsPromises.lstat(path);
return await lstat(path);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
return null;
@@ -29,8 +28,7 @@ export async function changeCopyFiles<T>(
prepare: (folder: string) => Promise<{ replace: readonly string[]; remove: readonly string[] }>,
recordChange: () => Promise<T>,
): Promise<T> {
const fsPromises = rawFs().promises;
const work = await fsPromises.mkdtemp(join(dirname(root), '.wto-copy-'));
const work = await mkdtemp(join(dirname(root), '.wto-copy-'));
const incoming = join(work, 'new');
const backups = join(work, 'old');
const changes: Array<{ target: string; saved: string | null; replaced: boolean }> = [];
@@ -46,14 +44,14 @@ export async function changeCopyFiles<T>(
const entry = { target, saved: null as string | null, replaced: false };
if (old) {
const saved = join(backups, path);
await fsPromises.mkdir(dirname(saved), { recursive: true });
await fsPromises.rename(target, saved);
await mkdir(dirname(saved), { recursive: true });
await rename(target, saved);
entry.saved = saved;
}
changes.push(entry);
if (add) {
await fsPromises.mkdir(dirname(target), { recursive: true });
await fsPromises.rename(join(incoming, path), target);
await mkdir(dirname(target), { recursive: true });
await rename(join(incoming, path), target);
entry.replaced = true;
}
}
@@ -62,8 +60,8 @@ export async function changeCopyFiles<T>(
} catch (error) {
for (const { target, saved, replaced } of changes.reverse()) {
try {
if (replaced) await fsPromises.rm(target, { force: true });
if (saved) await fsPromises.rename(saved, target);
if (replaced) await rm(target, { force: true });
if (saved) await rename(saved, target);
} catch (rollbackError) {
keepBackups = true;
console.error('[copies] could not restore a file, recovery folder:', work, target, rollbackError);
@@ -72,7 +70,7 @@ export async function changeCopyFiles<T>(
throw error;
} finally {
if (!keepBackups && relative(dirname(root), dirname(work)) === '') {
await fsPromises.rm(work, { recursive: true, force: true }).catch((error) => console.warn('[copies] could not clear temporary files:', work, error));
await rm(work, { recursive: true, force: true }).catch((error) => console.warn('[copies] could not clear temporary files:', work, error));
}
}
}
@@ -1,297 +0,0 @@
import type { BigIntStats } from 'node:fs';
import { copyFile, lstat, mkdir } from 'node:fs/promises';
import { dirname, join, normalize, relative, sep } from 'node:path';
import { compareVersions, GAME_FILES, isHardlinkableResource } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schemas/install.ts';
import type { MaintenanceProgress } from '@shared/schemas/maintenance.ts';
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
import { sameVolume } from '../game-folder/inspect-target-folder.ts';
import { readClientMarker, writeClientMarker } from '../install/client-marker.ts';
import { copyPlannedFiles, isInSkippedSourceFolder, planCopy, type CopyPlan } from '../install/copy-game.ts';
import {
fileHash,
linkVerifiedResource,
sameInode,
sameResource,
statFile,
statHardlinkResource,
verifyMatchingResource,
} from '../install/hardlink-files.ts';
import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } from '../install/install-record.ts';
import { checkPatches } from '../install/patch-check.ts';
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
import { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts';
import { readSource } from './copy-source.ts';
export type Report = (phase: MaintenanceProgress['phase'], doneBytes?: number, totalBytes?: number) => void;
export function isNewer(source: GameFolderInspection | null, version: string | null): boolean {
return !!source?.version && !!version && compareVersions(source.version, version) > 0;
}
export async function repair(record: InstallRecord, root: string, applying: () => void): Promise<Copies> {
return changeCopyFiles(root, async (incoming) => {
const files = Object.values(GAME_FILES);
for (const file of files) await stageBackup(record.stockBackupPath, file, join(incoming, file));
applying();
return { replace: files, remove: [] };
}, listCopies);
}
export async function updatePreservesSpaceSaving(
record: InstallRecord,
source: GameFolderInspection,
root: string,
): Promise<boolean> {
return (record.hardlinkedFiles?.length ?? 0) > 0 && await canShareVolume(source.path, root);
}
export async function updateFromSource(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise<Copies> {
const game = await readSource(record);
if (!game || !isNewer(game, record.gameVersion)) throw new AppError('maintenance_no_update');
const dataPath = await canonicalCopyPath(record.dataPath);
const plan = await planCopy(game.path);
const inventory = plan.files.map((entry) => entry.relativePath);
const found = new Set(inventory.map(key));
const linked = record.hardlinkedFiles ?? [];
const linkedPaths = new Set(linked.map(key));
const preserveHardlinks = await updatePreservesSpaceSaving(record, game, root);
// Older installs may have tracked files in folders that source scans now skip.
const remove = [...new Set([...(record.sourceFiles ?? []), ...linked])].filter(
(name) => !found.has(key(name)) && !isInSkippedSourceFolder(name),
);
const { copy, linksToStage, hardlinkedFiles } = await planUpdateFiles(
game.path, root, dataPath, plan, linkedPaths, preserveHardlinks, signal,
);
for (const file of remove) await scopedInstallFile(dataPath, root, file);
signal.throwIfAborted();
const check = await checkPatches(game.path, record.dataPath);
signal.throwIfAborted();
const updated = await changeCopyFiles(root, async (incoming) => {
report('copying', 0, copy.totalBytes);
let lastReport = 0;
await copyPlannedFiles(game.path, incoming, copy, signal, ({ doneBytes }) => {
if (doneBytes === copy.totalBytes || Date.now() - lastReport >= 250) {
lastReport = Date.now();
report('copying', doneBytes, copy.totalBytes);
}
});
const stagedLinks = new Map<string, BigIntStats>();
for (const [relativePath, sourceStamp] of linksToStage) {
signal.throwIfAborted();
const staged = join(incoming, relativePath);
await mkdir(dirname(staged), { recursive: true });
const linkedStamp = await linkVerifiedResource(join(game.path, relativePath), staged, sourceStamp);
stagedLinks.set(staged, linkedStamp);
}
const stockFiles = Object.values(GAME_FILES).map((file) => join(STOCK_BACKUP_FOLDER, file));
for (const file of Object.values(GAME_FILES)) {
signal.throwIfAborted();
await stageBackup(game.path, file, join(incoming, STOCK_BACKUP_FOLDER, file));
}
await verifySourceFiles(game.path, plan, signal);
if (stagedLinks.size > 0) await verifyStagedLinks(record, game.version, stagedLinks, signal);
signal.throwIfAborted();
report('applying', copy.totalBytes, copy.totalBytes);
return {
replace: [...copy.files.map(({ relativePath }) => relativePath), ...linksToStage.keys(), ...stockFiles],
remove,
};
}, () => updateCopyRecord(record.id, (latest) => ({
...latest, gameVersion: game.version, unavailablePatches: check.unavailable,
lastCheckedAt: new Date().toISOString(), sourceFiles: inventory,
...(preserveHardlinks ? { hardlinkedFiles } : linked.length ? { hardlinkedFiles: [] } : {}),
})));
if (!preserveHardlinks && linked.length > 0) {
const marker = await readClientMarker(root);
if (marker?.origin === 'hardlink' || (marker === null && record.method === 'copy')) {
await writeClientMarker(root, 'copy');
}
}
return updated;
}
interface UpdateFilePlan {
readonly copy: CopyPlan;
readonly linksToStage: ReadonlyMap<string, BigIntStats>;
readonly hardlinkedFiles: string[];
}
async function planUpdateFiles(
source: string,
root: string,
dataPath: string,
plan: CopyPlan,
linked: ReadonlySet<string>,
preserveHardlinks: boolean,
signal: AbortSignal,
): Promise<UpdateFilePlan> {
const changed: CopyPlan['files'][number][] = [];
const linksToStage = new Map<string, BigIntStats>();
const hardlinkedFiles: string[] = [];
for (const file of plan.files) {
signal.throwIfAborted();
const target = await scopedInstallFile(dataPath, root, file.relativePath);
const sourceFile = join(source, file.relativePath);
const old = await statFile(target);
if (preserveHardlinks && isHardlinkableResource(file.relativePath, file.bytes)) {
const sourceStamp = await statHardlinkResource(sourceFile, file.bytes, signal);
if (!sourceStamp) throw new AppError('maintenance_source_changed');
if (!old || !sameResource(old, sourceStamp)) linksToStage.set(file.relativePath, sourceStamp);
hardlinkedFiles.push(file.relativePath);
continue;
}
const sourceStamp = await statFile(sourceFile);
if (!sourceStamp?.isFile() || sourceStamp.size !== BigInt(file.bytes)) {
throw new AppError('maintenance_source_changed');
}
if (linked.has(key(file.relativePath)) || !old?.isFile() || sameInode(old, sourceStamp) ||
old.size !== BigInt(file.bytes)) {
changed.push(file);
} else if (Math.trunc(Number(old.mtimeMs)) !== Math.trunc(file.modifiedAt)) {
const [targetHash, sourceHash] = await Promise.all([
fileHash(target, signal), fileHash(sourceFile, signal),
]);
if (targetHash !== sourceHash) changed.push(file);
}
}
return {
copy: {
files: changed,
folders: [...new Set(changed.map(({ relativePath }) => dirname(relativePath)))],
totalBytes: changed.reduce((total, file) => total + file.bytes, 0),
},
linksToStage,
hardlinkedFiles,
};
}
async function verifySourceFiles(source: string, plan: CopyPlan, signal: AbortSignal): Promise<void> {
for (const file of plan.files) {
signal.throwIfAborted();
const info = await fileInfo(join(source, file.relativePath));
if (!info?.isFile() || info.size !== file.bytes || info.mtimeMs !== file.modifiedAt) {
throw new AppError('maintenance_source_changed');
}
}
}
export async function convertibleCopy(record: InstallRecord, source: GameFolderInspection, root: string): Promise<boolean> {
return record.method === 'copy' && source.version !== null &&
source.version === record.gameVersion && await canShareVolume(source.path, root);
}
export async function compactCopy(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise<Copies> {
const source = await readSource(record);
if (!source || !await convertibleCopy(record, source, root) ||
(await inspectGameFolder(root)).version !== source.version) {
throw new AppError('hardlink_unavailable');
}
const plan = await planCopy(source.path);
const candidates = plan.files.filter(({ relativePath, bytes }) => isHardlinkableResource(relativePath, bytes));
const total = candidates.reduce((bytes, file) => bytes + file.bytes, 0);
const dataPath = await canonicalCopyPath(record.dataPath);
const linked = new Map((record.hardlinkedFiles ?? []).map((path) => [key(path), path]));
const updated = await changeCopyFiles(root, async (incoming) => {
const replacements: string[] = [];
const unchanged = new Map<string, BigIntStats>();
let checked = 0;
let matches = 0;
let lastReport = 0;
report('checking', 0, total);
for (const { relativePath, bytes } of candidates) {
const target = await scopedInstallFile(dataPath, root, relativePath);
const original = join(source.path, relativePath);
const match = await verifyMatchingResource(target, original, bytes, signal);
if (match.status === 'already-linked') {
linked.set(key(relativePath), relativePath);
matches += 1;
} else if (match.status === 'matched') {
const staged = join(incoming, relativePath);
await mkdir(dirname(staged), { recursive: true });
const stagedStamp = await linkVerifiedResource(original, staged, match.sourceStamp);
unchanged.set(target, match.copyStamp);
unchanged.set(staged, stagedStamp);
replacements.push(relativePath);
linked.set(key(relativePath), relativePath);
matches += 1;
}
checked += bytes;
if (checked === total || Date.now() - lastReport >= 250) {
lastReport = Date.now();
report('checking', checked, total);
}
}
if (!matches) throw new AppError('hardlink_no_match');
await verifyStagedLinks(record, source.version, unchanged, signal);
signal.throwIfAborted();
report('applying', total, total);
return { replace: replacements, remove: [] };
}, () => updateCopyRecord(record.id, (latest) => ({ ...latest, hardlinkedFiles: [...linked.values()] })));
await writeClientMarker(root, 'hardlink');
return updated;
}
async function canShareVolume(sourcePath: string, root: string): Promise<boolean> {
return await sameVolume(sourcePath, root) && await sameVolume(sourcePath, dirname(root));
}
async function verifyStagedLinks(
record: InstallRecord, version: string | null, unchanged: ReadonlyMap<string, BigIntStats>, signal: AbortSignal,
): Promise<void> {
signal.throwIfAborted();
if ((await readSource(record))?.version !== version) throw new AppError('hardlink_file_changed');
for (const [path, stamp] of unchanged) {
signal.throwIfAborted();
if (!sameResource(stamp, await lstat(path, { bigint: true }))) throw new AppError('hardlink_file_changed');
}
}
function key(path: string): string {
const name = normalize(path);
return process.platform === 'win32' ? name.toLowerCase() : name;
}
const OFFLINE_DATA_ENTRIES = new Set(['accounts.json', 'saves', 'tuning', 'logs', 'asset-pack', 'decals', 'cache']);
function failLocation(reason: string, details: Record<string, unknown>): never {
console.warn('[copies] maintenance_location:', reason, details);
throw new AppError('maintenance_location');
}
async function scopedInstallFile(dataPath: string, root: string, name: string): Promise<string> {
const target = await stagedPath(root, name);
if (copyPathContains(join(root, dirname(STOCK_BACKUP_FOLDER)), target)) {
failLocation('target_inside_wtoffline', { root, target, name });
}
// Protect the data folder when it is nested inside the client folder. If an older installation
// placed dataPath at an ancestor of the client folder, files inside the client folder do not
// overlap data files stored at the ancestor root.
if (copyPathContains(root, dataPath)) {
if (relative(root, dataPath) !== '') {
if (copyPathContains(dataPath, target)) {
failLocation('target_inside_nested_data_folder', { root, dataPath, target, name });
}
} else {
const topSegment = normalize(name).split(sep)[0]?.toLowerCase() ?? '';
if (OFFLINE_DATA_ENTRIES.has(topSegment)) {
failLocation('target_collides_with_data_entry', { root, dataPath, target, name });
}
}
}
return target;
}
async function stageBackup(folder: string, file: string, target: string): Promise<void> {
await mkdir(dirname(target), { recursive: true });
const source = join(folder, file);
if (!(await fileInfo(source))?.isFile()) {
failLocation('stock_backup_source_missing', { folder, file, source });
}
await copyFile(source, target);
}
@@ -1,110 +1,69 @@
import { isAbsolute, relative } from 'node:path';
import { isInSteamLibrary } from '@wto/patcher';
import { createHash } from 'node:crypto';
import { createReadStream } from 'node:fs';
import { copyFile, mkdir, readdir, rm } from 'node:fs/promises';
import { dirname, isAbsolute, join, normalize, parse, relative } from 'node:path';
import { app } from 'electron';
import { compareVersions, GAME_FILES, isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { Copies, InstallRecord } from '@shared/schemas/install.ts';
import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schemas/install.ts';
import type { MaintenanceInfo, MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts';
import { detectHardlinkedResources, readClientMarker } from '../install/client-marker.ts';
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
import { copyPlannedFiles, planCopy, type CopyPlan } from '../install/copy-game.ts';
import { installationInProgress } from '../install/install-game.ts';
import { canonicalCopyPath, listCopies, steamLibraryNeedsConfirmation, updateCopyRecord } from '../install/install-record.ts';
import { canonicalCopyPath, copyPathContains, listCopies, removeCopyRecord, updateCopyRecord } from '../install/install-record.ts';
import { checkPatches } from '../install/patch-check.ts';
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts';
import { readInstalledLab } from '../launch/lab-handoff.ts';
import { localServerReady } from '../launch/local-server.ts';
import { compactCopy, convertibleCopy, isNewer, repair, updateFromSource, updatePreservesSpaceSaving, type Report } from './copy-file-maintenance.ts';
import {
canDeleteCopyFiles,
canRestoreStock,
checkedRoot,
failLocation,
removeCopy,
resolveClientOrigin,
withCanonicalSources,
} from './copy-removal.ts';
import { readSource, setCopySource } from './copy-source.ts';
import { labStatusUrl, readInstalledLab } from '../launch/lab-handoff.ts';
import { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts';
export { canDeleteCopyFiles, canRestoreStock, resolveClientOrigin } from './copy-removal.ts';
let current: {
stop: AbortController;
interruptible: boolean;
progress: MaintenanceProgress;
} | null = null;
let current: { stop: AbortController; interruptible: boolean } | null = null;
export function maintenanceInProgress(): boolean {
return current !== null;
}
export function maintenanceState(): MaintenanceProgress | null {
return current ? { ...current.progress } : null;
}
export function cancelMaintenance(): void {
if (current?.interruptible) current.stop.abort();
}
export async function maintenanceInfo(id: string): Promise<MaintenanceInfo> {
const registry = await listCopies();
const record = registry.copies.find((copy) => copy.id === id);
if (!record) throw new AppError('copy_not_found');
const [source, copyPath, dataPath, canonicalCopies] = await Promise.all([
readSource(record),
canonicalCopyPath(record.copyPath),
canonicalCopyPath(record.dataPath),
withCanonicalSources(registry.copies),
]);
const [diskMarker, hasHardlinkedResources, canRestoreAndRemove] = await Promise.all([
readClientMarker(copyPath),
detectHardlinkedResources(copyPath),
canRestoreStock(record, copyPath),
]);
const clientOrigin = resolveClientOrigin(record, diskMarker);
const canDeleteFiles = canDeleteCopyFiles(record, copyPath, clientOrigin, registry.copies) &&
canDeleteCopyFiles(record, copyPath, clientOrigin, canonicalCopies);
const copyInSteam = isInSteamLibrary(record.copyPath) || isInSteamLibrary(copyPath);
const dataInSteam = isInSteamLibrary(record.dataPath) || isInSteamLibrary(dataPath);
return {
sourceVersion: source?.version ?? null,
updateAvailable: isNewer(source, record.gameVersion),
updatePreservesSpaceSaving: source !== null && await updatePreservesSpaceSaving(record, source, record.copyPath),
spaceSavingAvailable: source !== null && await convertibleCopy(record, source, record.copyPath),
steamConfirmationRequired: steamLibraryNeedsConfirmation(record, copyPath, dataPath),
steamLocations: copyInSteam || dataInSteam ? { copyPath, dataPath, copyInSteam, dataInSteam } : null,
clientOrigin,
hasHardlinkedResources,
canDeleteFiles,
canRestoreAndRemove,
};
const record = await requireCopy(id);
const source = await readSource(record);
return { sourceVersion: source?.version ?? null, updateAvailable: isNewer(source, record.gameVersion) };
}
export async function maintainCopy(
request: MaintenanceRequest,
publish: (progress: MaintenanceProgress | null) => void,
publish: (progress: MaintenanceProgress) => void,
): Promise<Copies> {
if (current || launchInProgress() || installationInProgress()) throw new AppError('maintenance_busy');
const initial: MaintenanceProgress = {
id: request.id,
operation: request.operation,
phase: 'checking',
doneBytes: 0,
totalBytes: 0,
};
const job = {
stop: new AbortController(),
interruptible: request.operation === 'update' || request.operation === 'compact',
progress: initial,
};
const job = { stop: new AbortController(), interruptible: request.operation === 'update' };
current = job;
const signal = job.stop.signal;
const report: Report = (phase, doneBytes = 0, totalBytes = 0) => {
const report = (phase: MaintenanceProgress['phase'], doneBytes = 0, totalBytes = 0): void => {
if (phase === 'applying') job.interruptible = false;
const next: MaintenanceProgress = { id: request.id, operation: request.operation, phase, doneBytes, totalBytes };
job.progress = next;
publish(next);
publish({ id: request.id, operation: request.operation, phase, doneBytes, totalBytes });
};
report('checking');
try {
report('checking');
return await performMaintenance(request, signal, report);
const record = await requireCopy(request.id);
const root = await checkedRoot(record);
if (await gameProcessRunning(signal) || await labServerUses(root)) throw new AppError('maintenance_busy');
signal.throwIfAborted();
switch (request.operation) {
case 'check':
return await recordCheck(record, record.stockBackupPath);
case 'repair':
return await repair(record, root, () => report('applying'));
case 'update':
return await updateFromSource(record, root, signal, report);
case 'delete':
report('applying');
return await remove(record, root, request.deleteData);
}
} catch (error) {
if (signal.aborted) throw new AppError('maintenance_cancelled');
if (error instanceof AppError) throw error;
@@ -112,56 +71,6 @@ export async function maintainCopy(
throw new AppError('maintenance_failed');
} finally {
current = null;
publish(null);
}
}
async function performMaintenance(request: MaintenanceRequest, signal: AbortSignal, report: Report): Promise<Copies> {
const { id, operation, steamLocations } = request;
const record = await requireCopy(id);
if (operation === 'set-source') return setCopySource(record, request.sourcePath);
if (operation === 'delete') {
return removeCopy(
record,
{
deleteFiles: request.deleteFiles === true,
restoreStock: request.restoreStock === true,
deleteData: request.deleteData === true,
},
signal,
report,
labServerUses,
);
}
const root = await checkedRoot(record);
const dataPath = await canonicalCopyPath(record.dataPath);
const needsConfirmation = steamLibraryNeedsConfirmation(record, root, dataPath);
if (await gameProcessRunning(signal) || await labServerUses(root)) throw new AppError('maintenance_busy');
signal.throwIfAborted();
if (operation !== 'confirm-steam' && needsConfirmation) {
throw new AppError('launch_steam_confirmation_required');
}
switch (operation) {
case 'confirm-steam':
if (!steamLocations || !isAbsolute(steamLocations.copyPath) || !isAbsolute(steamLocations.dataPath) ||
relative(root, steamLocations.copyPath) !== '' || relative(dataPath, steamLocations.dataPath) !== '') {
failLocation('steam_confirmation_mismatch', { root, dataPath, steamLocations });
}
if (!needsConfirmation) return listCopies();
return updateCopyRecord(id, (copy) => ({
...copy, steamLibraryConfirmation: { copyPath: root, dataPath },
}));
case 'check':
return recordCheck(record, record.stockBackupPath);
case 'repair':
return repair(record, root, () => report('applying'));
case 'update':
return updateFromSource(record, root, signal, report);
case 'compact':
return compactCopy(record, root, signal, report);
}
}
@@ -171,10 +80,52 @@ async function requireCopy(id: string): Promise<InstallRecord> {
return record;
}
async function readSource(record: InstallRecord): Promise<GameFolderInspection | null> {
if (!record.sourcePath) return null;
try {
const game = await inspectGameFolder(record.sourcePath);
return game.missingFiles.length > 0 ? null : game;
} catch (error) {
if (error instanceof AppError) return null;
throw error;
}
}
function isNewer(source: GameFolderInspection | null, version: string | null): boolean {
return !!source?.version && !!version && compareVersions(source.version, version) > 0;
}
async function checkedRoot(record: InstallRecord): Promise<string> {
const root = await safeFolder(record.copyPath);
const backup = await canonicalCopyPath(record.stockBackupPath);
if (relative(join(root, STOCK_BACKUP_FOLDER), backup) !== '') throw new AppError('maintenance_location');
if (record.sourcePath) {
const source = await canonicalCopyPath(record.sourcePath);
if (copyPathContains(source, root) || copyPathContains(root, source)) throw new AppError('maintenance_location');
}
return root;
}
async function safeFolder(path: string): Promise<string> {
const root = await canonicalCopyPath(path);
if (!isAbsolute(path) || root === parse(root).root || isInSteamLibrary(root) ||
copyPathContains(root, await canonicalCopyPath(app.getAppPath())) ||
copyPathContains(root, await canonicalCopyPath(app.getPath('userData')))) {
throw new AppError('maintenance_location');
}
if ((await fileInfo(path))?.isSymbolicLink()) throw new AppError('maintenance_location');
return root;
}
async function labServerUses(root: string): Promise<boolean> {
const lab = await readInstalledLab().catch(() => null);
if (!lab || relative(lab.copyPath, root) !== '') return false;
return localServerReady(lab.port);
try {
const response = await fetch(labStatusUrl(lab.port), { signal: AbortSignal.timeout(800) });
return response.ok && (await response.json() as { app?: string }).app === 'wto-server';
} catch {
return false;
}
}
async function recordCheck(record: InstallRecord, folder: string): Promise<Copies> {
@@ -183,3 +134,134 @@ async function recordCheck(record: InstallRecord, folder: string): Promise<Copie
...copy, unavailablePatches: check.unavailable, lastCheckedAt: new Date().toISOString(),
}));
}
async function repair(record: InstallRecord, root: string, applying: () => void): Promise<Copies> {
return changeCopyFiles(root, async (incoming) => {
const files = Object.values(GAME_FILES);
for (const file of files) await stageBackup(record.stockBackupPath, file, join(incoming, file));
applying();
return { replace: files, remove: [] };
}, listCopies);
}
type Report = (phase: MaintenanceProgress['phase'], doneBytes?: number, totalBytes?: number) => void;
async function updateFromSource(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise<Copies> {
const game = await readSource(record);
if (!game || !isNewer(game, record.gameVersion)) throw new AppError('maintenance_no_update');
const dataPath = await canonicalCopyPath(record.dataPath);
const plan = await planCopy(game.path);
const inventory = plan.files.map((entry) => entry.relativePath);
const found = new Set(inventory.map(key));
const remove = (record.sourceFiles ?? []).filter((name) => !found.has(key(name)));
const changed: CopyPlan['files'][number][] = [];
for (const file of plan.files) {
signal.throwIfAborted();
const target = await scopedInstallFile(dataPath, root, file.relativePath);
const old = await fileInfo(target);
if (!old?.isFile() || old.size !== file.bytes) {
changed.push(file);
} else if (Math.trunc(old.mtimeMs) !== Math.trunc(file.modifiedAt)) {
const [targetHash, sourceHash] = await Promise.all([
fileHash(target, signal), fileHash(join(game.path, file.relativePath), signal),
]);
if (targetHash !== sourceHash) changed.push(file);
}
}
for (const file of remove) await scopedInstallFile(dataPath, root, file);
signal.throwIfAborted();
const check = await checkPatches(game.path, record.dataPath);
signal.throwIfAborted();
const copy: CopyPlan = {
files: changed,
folders: [...new Set(changed.map(({ relativePath }) => dirname(relativePath)))],
totalBytes: changed.reduce((total, file) => total + file.bytes, 0),
};
return changeCopyFiles(root, async (incoming) => {
report('copying', 0, copy.totalBytes);
let lastReport = 0;
await copyPlannedFiles(game.path, incoming, copy, signal, ({ doneBytes }) => {
if (doneBytes === copy.totalBytes || Date.now() - lastReport >= 250) {
lastReport = Date.now();
report('copying', doneBytes, copy.totalBytes);
}
});
const stockFiles = Object.values(GAME_FILES).map((file) => join(STOCK_BACKUP_FOLDER, file));
for (const file of Object.values(GAME_FILES)) {
signal.throwIfAborted();
await stageBackup(game.path, file, join(incoming, STOCK_BACKUP_FOLDER, file));
}
for (const file of plan.files) {
signal.throwIfAborted();
const info = await fileInfo(join(game.path, file.relativePath));
if (!info?.isFile() || info.size !== file.bytes || info.mtimeMs !== file.modifiedAt) {
throw new AppError('maintenance_source_changed');
}
}
signal.throwIfAborted();
report('applying', copy.totalBytes, copy.totalBytes);
return { replace: [...changed.map(({ relativePath }) => relativePath), ...stockFiles], remove };
}, () => updateCopyRecord(record.id, (latest) => ({
...latest, gameVersion: game.version, unavailablePatches: check.unavailable,
lastCheckedAt: new Date().toISOString(), sourceFiles: inventory,
})));
}
function key(path: string): string {
const name = normalize(path);
return process.platform === 'win32' ? name.toLowerCase() : name;
}
async function scopedInstallFile(dataPath: string, root: string, name: string): Promise<string> {
const target = await stagedPath(root, name);
if (copyPathContains(join(root, dirname(STOCK_BACKUP_FOLDER)), target) ||
copyPathContains(dataPath, target)) {
throw new AppError('maintenance_location');
}
return target;
}
async function fileHash(path: string, signal: AbortSignal): Promise<string> {
const hash = createHash('sha256');
for await (const bytes of createReadStream(path, { signal })) hash.update(bytes as Buffer);
return hash.digest('hex');
}
async function stageBackup(folder: string, file: string, target: string): Promise<void> {
await mkdir(dirname(target), { recursive: true });
const source = join(folder, file);
if (!(await fileInfo(source))?.isFile()) throw new AppError('maintenance_location');
await copyFile(source, target);
}
async function remove(record: InstallRecord, root: string, deleteData: boolean): Promise<Copies> {
const data = deleteData ? await safeFolder(record.dataPath) : await canonicalCopyPath(record.dataPath);
const source = record.sourcePath ? await canonicalCopyPath(record.sourcePath) : null;
if (deleteData && ((source && (copyPathContains(data, source) || copyPathContains(source, data))) ||
(relative(data, root) !== '' && copyPathContains(data, root)))) {
throw new AppError('maintenance_location');
}
if (!deleteData && copyPathContains(root, data)) {
await removeExcept(root, data);
} else {
await rm(root, { recursive: true, force: true });
}
if (deleteData && !copyPathContains(root, data)) await rm(data, { recursive: true, force: true });
return removeCopyRecord(record.id);
}
/** Keep the data folder in place when it was chosen inside this copy. */
async function removeExcept(folder: string, kept: string): Promise<void> {
if (relative(folder, kept) === '' || !(await fileInfo(folder))) return;
for (const entry of await readdir(folder, { withFileTypes: true })) {
const path = join(folder, entry.name);
if (copyPathContains(path, kept)) {
if (!entry.isDirectory()) throw new AppError('maintenance_location');
await removeExcept(path, kept);
} else {
await rm(path, { recursive: true, force: true });
}
}
}
@@ -1,272 +0,0 @@
import { constants } from 'node:fs';
import { dirname, isAbsolute, join, parse, relative, resolve } from 'node:path';
import { app } from 'electron';
import { GAME_FILES, isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { ClientOrigin, Copies, InstallRecord } from '@shared/schemas/install.ts';
import { rawFs } from '../../util/raw-fs.ts';
import { readClientMarker, type ClientMarker } from '../install/client-marker.ts';
import { canonicalCopyPath, copyPathContains, listCopies, removeCopyRecord } from '../install/install-record.ts';
import { requireStockBackupLocation, STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
import { gameProcessRunning } from '../launch/launch-controller.ts';
import { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts';
import type { Report } from './copy-file-maintenance.ts';
const OFFLINE_HOOK_FILES = ['wto_ws.dll', 'wto_ws.cfg', 'wto_ws.log'] as const;
export interface RemoveCopyOptions {
readonly deleteFiles: boolean;
readonly restoreStock: boolean;
readonly deleteData: boolean;
}
export function failLocation(reason: string, details: Record<string, unknown>): never {
console.warn('[copies] maintenance_location:', reason, details);
throw new AppError('maintenance_location');
}
/**
* Resolve the effective client origin by preferring a valid on-disk marker while
* keeping in-place registrations conservatively locked as `in-place`.
*/
export function resolveClientOrigin(
record: InstallRecord,
diskMarker: ClientMarker | null,
): ClientOrigin | null {
if (record.method === 'in-place') return 'in-place';
if (diskMarker) return diskMarker.origin;
if (record.method === 'copy') return record.hardlinkedFiles?.length ? 'hardlink' : 'copy';
return null;
}
/**
* Only launcher-created copies or existing folders carrying a valid copy/hardlink marker
* outside any Steam library and disjoint from every registered copy's sourcePath may be deleted.
*/
export function canDeleteCopyFiles(
record: InstallRecord,
root: string,
effectiveOrigin: ClientOrigin | null,
allCopies: readonly InstallRecord[] = [],
): boolean {
if (isInSteamLibrary(record.copyPath) || isInSteamLibrary(root)) return false;
if (effectiveOrigin !== 'copy' && effectiveOrigin !== 'hardlink') return false;
const normalizedRoot = resolve(root);
const normalizedCopyPath = resolve(record.copyPath);
const sources = record.sourcePath
? [record.sourcePath, ...allCopies.map((copy) => copy.sourcePath)]
: allCopies.map((copy) => copy.sourcePath);
for (const candidate of sources) {
if (!candidate) continue;
const source = resolve(candidate);
if (pathsOverlap(normalizedRoot, source) || pathsOverlap(normalizedCopyPath, source)) {
return false;
}
}
return true;
}
/** Check that `record` has a safe root and all four original core files readable in wtoffline/stock. */
export async function canRestoreStock(record: InstallRecord, root: string): Promise<boolean> {
try {
const safeRoot = await checkedRoot(record);
const canonicalRoot = await canonicalCopyPath(root);
if (relative(safeRoot, canonicalRoot) !== '') return false;
const backup = await requireStockBackupLocation(safeRoot);
const fsPromises = rawFs().promises;
for (const file of Object.values(GAME_FILES)) {
const stockFile = join(backup, file);
const info = await fileInfo(stockFile);
if (!info?.isFile()) return false;
await fsPromises.access(stockFile, constants.R_OK);
}
return true;
} catch {
return false;
}
}
/** Resolve every copy's `sourcePath` through symlinks/junctions for overlap checks. */
export async function withCanonicalSources(copies: readonly InstallRecord[]): Promise<InstallRecord[]> {
return Promise.all(copies.map(async (copy) => (
copy.sourcePath ? { ...copy, sourcePath: await canonicalCopyPath(copy.sourcePath) } : copy
)));
}
export async function checkedRoot(record: InstallRecord): Promise<string> {
const root = await safeFolder(record.copyPath, true);
const backup = await canonicalCopyPath(record.stockBackupPath);
const expectedBackup = join(root, STOCK_BACKUP_FOLDER);
if (relative(expectedBackup, backup) !== '') {
failLocation('stock_backup_outside_copy', { root, expectedBackup, backup, recordedBackup: record.stockBackupPath });
}
if (record.sourcePath) {
const source = await canonicalCopyPath(record.sourcePath);
if (pathsOverlap(source, root)) {
failLocation('copy_overlaps_source', { root, source, sourcePath: record.sourcePath });
}
}
return root;
}
export async function safeFolder(path: string, steamAllowed = false): Promise<string> {
const root = await canonicalCopyPath(path);
const inSteam = isInSteamLibrary(path) || isInSteamLibrary(root);
const appPath = await canonicalCopyPath(app.getAppPath());
const userDataPath = await canonicalCopyPath(app.getPath('userData'));
if (!isAbsolute(path) || root === parse(root).root || (!steamAllowed && inSteam) ||
copyPathContains(root, appPath) || copyPathContains(root, userDataPath)) {
failLocation('unsafe_folder', { path, root, inSteam, steamAllowed, appPath, userDataPath });
}
if ((!steamAllowed || !inSteam) && (await fileInfo(path))?.isSymbolicLink()) {
failLocation('folder_is_symlink', { path, root });
}
return root;
}
export async function removeCopy(
record: InstallRecord,
options: RemoveCopyOptions,
signal: AbortSignal,
report: Report,
labServerUses: (root: string) => Promise<boolean>,
): Promise<Copies> {
const { deleteFiles, restoreStock, deleteData } = options;
if (deleteFiles && restoreStock) {
failLocation('delete_files_and_restore_stock_conflict', { id: record.id });
}
const canonicalRoot = await canonicalCopyPath(record.copyPath);
if (await gameProcessRunning(signal) || await labServerUses(canonicalRoot)) {
throw new AppError('maintenance_busy');
}
signal.throwIfAborted();
// Pure list removal touches no files on disk and skips copyPath/stockBackup checks
// so missing, moved, or damaged client registrations can always be removed safely.
if (!deleteFiles && !deleteData && !restoreStock) {
report('applying');
return removeCopyRecord(record.id);
}
const copyInSteam = isInSteamLibrary(record.copyPath) || isInSteamLibrary(canonicalRoot);
if ((deleteFiles || deleteData) && copyInSteam) {
failLocation(deleteFiles ? 'delete_files_blocked_in_steam' : 'delete_data_blocked_in_steam', {
method: record.method,
copyPath: record.copyPath,
root: canonicalRoot,
});
}
let root = canonicalRoot;
if (deleteFiles) {
const allCopies = (await listCopies()).copies;
const canonicalCopies = await withCanonicalSources(allCopies);
const initialOrigin = resolveClientOrigin(record, await readClientMarker(canonicalRoot));
if (!canDeleteCopyFiles(record, canonicalRoot, initialOrigin, allCopies) ||
!canDeleteCopyFiles(record, canonicalRoot, initialOrigin, canonicalCopies)) {
failLocation('delete_files_blocked', { method: record.method, origin: initialOrigin, copyPath: record.copyPath, root: canonicalRoot });
}
root = await checkedRoot(record);
const verifiedOrigin = resolveClientOrigin(record, await readClientMarker(root));
if (!canDeleteCopyFiles(record, root, verifiedOrigin, allCopies) ||
!canDeleteCopyFiles(record, root, verifiedOrigin, canonicalCopies)) {
failLocation('delete_files_blocked', { method: record.method, origin: verifiedOrigin, copyPath: record.copyPath, root });
}
} else if (restoreStock) {
root = await checkedRoot(record);
if (!(await canRestoreStock(record, root))) {
failLocation('restore_stock_unavailable', { copyPath: record.copyPath, root, stockBackupPath: record.stockBackupPath });
}
}
const data = deleteData ? await safeFolder(record.dataPath, false) : await canonicalCopyPath(record.dataPath);
const source = record.sourcePath ? await canonicalCopyPath(record.sourcePath) : null;
const stockBackup = await canonicalCopyPath(record.stockBackupPath);
if (deleteData) {
const rawRoot = resolve(record.copyPath);
const overlapsSource = source !== null && pathsOverlap(data, source);
const containsCopy = deleteFiles
? relative(data, root) !== '' && copyPathContains(data, root)
: copyPathContains(data, root) || copyPathContains(data, rawRoot) || copyPathContains(data, stockBackup);
if (overlapsSource || containsCopy) {
failLocation('delete_data_overlaps_source_or_copy', { root, data, source, stockBackup, deleteFiles, restoreStock });
}
}
report('applying');
const fsPromises = rawFs().promises;
if (restoreStock) {
await restoreStockAndCleanOfflineFiles(root, data, deleteData);
} else if (deleteFiles) {
if (!deleteData && copyPathContains(root, data)) {
await removeExcept(root, data);
} else {
await fsPromises.rm(root, { recursive: true, force: true });
}
}
if (deleteData && (!deleteFiles || !copyPathContains(root, data))) {
await fsPromises.rm(data, { recursive: true, force: true });
}
return removeCopyRecord(record.id);
}
/**
* Atomically restore the four stock core files from `wtoffline/stock`, then remove
* only launcher-created hook files and the `wtoffline` folder without touching base game files.
*/
async function restoreStockAndCleanOfflineFiles(root: string, data: string, deleteData: boolean): Promise<void> {
const fsPromises = rawFs().promises;
const backup = await requireStockBackupLocation(root);
await changeCopyFiles(root, async (incoming) => {
const files = Object.values(GAME_FILES);
for (const file of files) {
const sourceFile = join(backup, file);
if (!(await fileInfo(sourceFile))?.isFile()) {
failLocation('stock_backup_source_missing', { root, file, sourceFile });
}
const targetFile = join(incoming, file);
await fsPromises.mkdir(dirname(targetFile), { recursive: true });
await fsPromises.copyFile(sourceFile, targetFile);
}
return { replace: files, remove: [] };
}, async () => undefined);
const exeDir = dirname(GAME_FILES.executable);
for (const name of OFFLINE_HOOK_FILES) {
const hookFile = await stagedPath(root, join(exeDir, name));
const info = await fileInfo(hookFile);
if (info && !info.isDirectory()) {
await fsPromises.rm(hookFile, { force: true });
}
}
const wtofflineFolder = await stagedPath(root, dirname(STOCK_BACKUP_FOLDER));
const wtofflineInfo = await fileInfo(wtofflineFolder);
if (wtofflineInfo?.isDirectory()) {
if (!deleteData && copyPathContains(wtofflineFolder, data)) {
await removeExcept(wtofflineFolder, data);
} else {
await fsPromises.rm(wtofflineFolder, { recursive: true, force: true });
}
}
}
function pathsOverlap(left: string, right: string): boolean {
return copyPathContains(left, right) || copyPathContains(right, left);
}
/** Keep the data folder in place when it was chosen inside this copy. */
async function removeExcept(folder: string, kept: string): Promise<void> {
if (relative(folder, kept) === '' || !(await fileInfo(folder))) return;
const fsPromises = rawFs().promises;
for (const entry of await fsPromises.readdir(folder, { withFileTypes: true })) {
const path = join(folder, entry.name);
if (copyPathContains(path, kept)) {
if (!entry.isDirectory()) failLocation('kept_data_ancestor_not_directory', { folder, kept, path });
await removeExcept(path, kept);
} else {
await fsPromises.rm(path, { recursive: true, force: true });
}
}
}
@@ -1,52 +0,0 @@
import { isAbsolute, join } from 'node:path';
import { AppError } from '@shared/errors.ts';
import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schemas/install.ts';
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
import { canonicalCopyPath, copyPathContains, updateCopyRecord } from '../install/install-record.ts';
import { fileInfo } from './change-copy-files.ts';
export async function readSource(record: InstallRecord): Promise<GameFolderInspection | null> {
if (!record.sourcePath) return null;
try {
return await inspectSource(record, record.sourcePath);
} catch (error) {
if (error instanceof AppError) return null;
throw error;
}
}
export async function setCopySource(record: InstallRecord, path: string | undefined): Promise<Copies> {
const source = await inspectSource(record, path);
return updateCopyRecord(record.id, (latest) => {
if (latest.copyPath !== record.copyPath || latest.dataPath !== record.dataPath) {
throw new AppError('maintenance_location');
}
return { ...latest, sourcePath: source.resolvedPath };
});
}
async function inspectSource(record: InstallRecord, path: string | undefined): Promise<GameFolderInspection> {
if (!path || !isAbsolute(path)) throw new AppError('maintenance_source_invalid');
const [game, copyPath, dataPath] = await Promise.all([
inspectGameFolder(path), canonicalCopyPath(record.copyPath), canonicalCopyPath(record.dataPath),
]);
const source = game.resolvedPath;
const overlapsCopy = copyPathContains(source, copyPath) || copyPathContains(copyPath, source);
if (overlapsCopy || copyPathContains(source, dataPath)) {
throw new AppError('maintenance_source_overlap');
}
if (game.missingFiles.length || !game.version || game.hasOfflineBackup || game.needsStockSource) {
throw new AppError('maintenance_source_invalid');
}
// Verify that the directory has game resources beyond the four files used for patching.
const [content, languages, missions] = await Promise.all([
fileInfo(join(source, 'content')),
fileInfo(join(source, 'lang.vromfs.bin')),
fileInfo(join(source, 'mis.vromfs.bin')),
]);
if (!content?.isDirectory() || !languages?.isFile() || !missions?.isFile()) {
throw new AppError('maintenance_source_invalid');
}
return { ...game, path: source };
}
@@ -1,25 +0,0 @@
import { AppError } from '@shared/errors.ts';
import type { Copies } from '@shared/schemas/install.ts';
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
import { hydrateCopiesStatus, relocateCopyRecord } from '../install/install-record.ts';
import { backUpStockFiles, installStockSource, refreshStockBackup } from '../install/stock-backup.ts';
/**
* Re-point an existing registered client to its moved folder while keeping its id, name, saves,
* and data folder intact.
*/
export async function relocateCopy(id: string, newPath: string): Promise<Copies> {
const game = await inspectGameFolder(newPath);
if (game.missingFiles.length) throw new AppError('not_a_game_folder', { path: newPath });
if (game.needsStockSource) throw new AppError('stock_source_invalid');
const stock = await installStockSource(game.resolvedPath, game.version);
const stockBackupPath = stock.refresh
? await refreshStockBackup(game.resolvedPath)
: await backUpStockFiles(game.resolvedPath);
const updated = await relocateCopyRecord(id, {
copyPath: newPath,
stockBackupPath,
gameVersion: game.version,
});
return hydrateCopiesStatus(updated);
}
@@ -1,32 +1,15 @@
import { randomUUID } from 'node:crypto';
import { lstat, mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
import { release } from 'node:os';
import { dirname, join } from 'node:path';
import { join } from 'node:path';
import { app, dialog, shell, type BrowserWindow } from 'electron';
import { zipSync } from 'fflate';
import { GAME_FILES } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import { PORTABLE_UPDATE_LOG_FILENAME } from '../app-update/portable-update.ts';
import { getSettings } from '../config/settings-store.ts';
import { COPIES_FILENAME, readInstallRecord } from '../install/install-record.ts';
import { LAUNCHER_LOG_FILES, launcherLogFolder } from './launcher-log.ts';
type ArchiveFiles = Record<string, Uint8Array>;
/** Bound individual client log files so a huge crash dump or session log cannot exhaust memory. */
const MAX_CLIENT_LOG_BYTES = 16 * 1024 * 1024;
/** Number of recent .game_logs entries listed in client-logs/summary.json. */
const RECENT_GAME_LOGS_LIMIT = 10;
const HOOK_LOG_FILENAME = 'wto_ws.log';
const HOOK_CONFIG_FILENAME = 'wto_ws.cfg';
interface ListedFile {
readonly name: string;
readonly size: number;
readonly modifiedAt: string;
}
export async function openLogsFolder(): Promise<void> {
const path = launcherLogFolder();
try {
@@ -59,15 +42,9 @@ export async function exportDiagnostics(window: BrowserWindow | null): Promise<{
await addFile(files, `launcher-logs/${name}`, join(launcherLogs, name));
}
}
await addFile(
files,
`launcher-logs/${PORTABLE_UPDATE_LOG_FILENAME}`,
join(userData, 'launcher-updates', PORTABLE_UPDATE_LOG_FILENAME),
);
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
const dataPath = (settings.developerMode ? settings.labDataPath : null) ?? record?.dataPath;
if (dataPath) await addServerLogs(files, dataPath);
if (record) await addClientLogs(files, record, settings.loggingEnabled);
const temporary = `${result.filePath}.${randomUUID()}.tmp`;
try {
@@ -96,173 +73,6 @@ async function addServerLogs(files: ArchiveFiles, dataPath: string): Promise<voi
}
}
/**
* Include the hook library log, the latest game .clog and embedded browser log, and a small
* metadata summary for the active client so crashes and web-UI issues can be diagnosed without
* touching player saves.
*/
async function addClientLogs(files: ArchiveFiles, record: InstallRecord, loggingEnabled: boolean): Promise<void> {
const exeFolder = join(record.copyPath, dirname(GAME_FILES.executable));
const hookLogPath = join(exeFolder, HOOK_LOG_FILENAME);
const hookConfigPath = join(exeFolder, HOOK_CONFIG_FILENAME);
const gameLogsFolder = join(record.copyPath, '.game_logs');
const [hookLogStat, hookConfigStat] = await Promise.all([
readRegularFileStat(hookLogPath),
readRegularFileStat(hookConfigPath),
]);
let hookLogIncluded = false;
let hookLogOmittedReason: string | null = null;
if (hookLogStat) {
const added = await addBoundedClientFile(files, `client-logs/${HOOK_LOG_FILENAME}`, hookLogPath, hookLogStat.size);
hookLogIncluded = added.included;
hookLogOmittedReason = added.omittedReason;
}
const recentGameLogs: ListedFile[] = [];
let latestClog: ListedFile | null = null;
let latestClogIncluded = false;
let latestClogOmittedReason: string | null = null;
let latestBrowserLog: ListedFile | null = null;
let latestBrowserLogIncluded = false;
let latestBrowserLogOmittedReason: string | null = null;
const gameLogsDirStat = await safeStat(gameLogsFolder);
if (gameLogsDirStat?.isDirectory()) {
const entries = await safeReadDir(gameLogsFolder);
const inspected: Array<ListedFile & { readonly mtimeMs: number }> = [];
for (const entry of entries) {
if (!entry.isFile()) continue;
const stats = await readRegularFileStat(join(gameLogsFolder, entry.name));
if (!stats) continue;
inspected.push({
name: entry.name,
size: stats.size,
modifiedAt: new Date(stats.mtimeMs).toISOString(),
mtimeMs: stats.mtimeMs,
});
}
inspected.sort((left, right) => right.mtimeMs - left.mtimeMs);
for (const item of inspected.slice(0, RECENT_GAME_LOGS_LIMIT)) {
recentGameLogs.push({ name: item.name, size: item.size, modifiedAt: item.modifiedAt });
}
const newestClog = inspected.find((item) => item.name.toLowerCase().endsWith('.clog')) ?? null;
if (newestClog) {
latestClog = { name: newestClog.name, size: newestClog.size, modifiedAt: newestClog.modifiedAt };
const added = await addBoundedClientFile(
files,
`client-logs/game-logs/${newestClog.name}`,
join(gameLogsFolder, newestClog.name),
newestClog.size,
);
latestClogIncluded = added.included;
latestClogOmittedReason = added.omittedReason;
}
const newestBrowserLog = inspected.find((item) => item.name.toLowerCase().endsWith('-browser.log')) ?? null;
if (newestBrowserLog) {
latestBrowserLog = {
name: newestBrowserLog.name,
size: newestBrowserLog.size,
modifiedAt: newestBrowserLog.modifiedAt,
};
const added = await addBoundedClientFile(
files,
`client-logs/game-logs/${newestBrowserLog.name}`,
join(gameLogsFolder, newestBrowserLog.name),
newestBrowserLog.size,
);
latestBrowserLogIncluded = added.included;
latestBrowserLogOmittedReason = added.omittedReason;
}
}
const summary = {
exportedAt: new Date().toISOString(),
launcherVersion: app.getVersion(),
loggingEnabled,
platform: process.platform,
arch: process.arch,
osRelease: release(),
copyId: record.id,
gameVersion: record.gameVersion,
hookConfig: hookConfigStat
? { present: true, size: hookConfigStat.size, modifiedAt: new Date(hookConfigStat.mtimeMs).toISOString() }
: { present: false },
hookLog: hookLogStat
? {
present: true,
size: hookLogStat.size,
modifiedAt: new Date(hookLogStat.mtimeMs).toISOString(),
included: hookLogIncluded,
...(hookLogOmittedReason ? { omittedReason: hookLogOmittedReason } : {}),
}
: { present: false },
gameLogsFolderPresent: gameLogsDirStat?.isDirectory() ?? false,
recentGameLogs,
latestClog: latestClog
? {
...latestClog,
included: latestClogIncluded,
...(latestClogOmittedReason ? { omittedReason: latestClogOmittedReason } : {}),
}
: null,
latestBrowserLog: latestBrowserLog
? {
...latestBrowserLog,
included: latestBrowserLogIncluded,
...(latestBrowserLogOmittedReason ? { omittedReason: latestBrowserLogOmittedReason } : {}),
}
: null,
};
files['client-logs/summary.json'] = new TextEncoder().encode(`${JSON.stringify(summary, null, 2)}\n`);
}
async function addBoundedClientFile(
files: ArchiveFiles,
entry: string,
path: string,
size: number,
): Promise<{ readonly included: boolean; readonly omittedReason: string | null }> {
if (size > MAX_CLIENT_LOG_BYTES) return { included: false, omittedReason: 'too-large' };
try {
const bytes = await readFile(path);
if (bytes.byteLength > MAX_CLIENT_LOG_BYTES) return { included: false, omittedReason: 'too-large' };
files[entry] = bytes;
return { included: true, omittedReason: null };
} catch (error) {
console.warn('[diagnostics] could not read client log:', path, error);
return { included: false, omittedReason: 'unreadable' };
}
}
async function readRegularFileStat(path: string) {
const stats = await safeStat(path);
return stats?.isFile() ? stats : null;
}
async function safeStat(path: string) {
try {
return await lstat(path);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
console.warn('[diagnostics] could not inspect path:', path, error);
}
return null;
}
}
async function safeReadDir(path: string) {
try {
return await readdir(path, { withFileTypes: true });
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
console.warn('[diagnostics] could not read folder:', path, error);
}
return [];
}
}
async function addFile(files: ArchiveFiles, entry: string, path: string): Promise<void> {
if (!(await ifPresent(() => lstat(path)))?.isFile()) return;
const bytes = await ifPresent(() => readFile(path));
@@ -1,5 +1,5 @@
import { Console } from 'node:console';
import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
import { appendFileSync, existsSync, mkdirSync, renameSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { Writable } from 'node:stream';
import { app } from 'electron';
@@ -12,26 +12,13 @@ export const LAUNCHER_LOG_FILES = [
'launcher.4.log',
] as const;
let loggingEnabled = true;
let activeLogPath: string | null = null;
let fileFailed = false;
let originalConsole = console;
export function launcherLogFolder(): string {
return join(app.getPath('userData'), 'logs');
}
function readInitialLoggingEnabled(): boolean {
try {
const raw = JSON.parse(readFileSync(join(app.getPath('userData'), 'settings.json'), 'utf8')) as { loggingEnabled?: unknown };
return raw?.loggingEnabled !== false;
} catch {
return true;
}
}
function ensureLogFileReady(): boolean {
if (activeLogPath) return !fileFailed;
/** Rotate after taking the single-instance lock and keep the original console destinations. */
export function startLauncherLogging(): void {
const originalConsole = console;
const folder = launcherLogFolder();
const active = join(folder, LAUNCHER_LOG_FILES[0]);
try {
@@ -41,37 +28,17 @@ function ensureLogFileReady(): boolean {
if (existsSync(previous)) renameSync(previous, join(folder, LAUNCHER_LOG_FILES[index]!));
}
writeFileSync(active, '', { flag: 'wx' });
activeLogPath = active;
fileFailed = false;
return true;
} catch (error) {
fileFailed = true;
originalConsole.error('[logs] opening the launcher log failed:', error);
return false;
return;
}
}
/** Enable or disable writing launcher console output to launcher.log at runtime. */
export function setLauncherLoggingEnabled(enabled: boolean): void {
loggingEnabled = enabled;
if (enabled && !activeLogPath && !fileFailed) {
if (ensureLogFileReady()) {
console.info(`WTOffline Launcher ${app.getVersion()} logging enabled.`);
}
}
}
/** Rotate after taking the single-instance lock and keep the original console destinations. */
export function startLauncherLogging(): void {
originalConsole = console;
loggingEnabled = readInitialLoggingEnabled();
if (loggingEnabled) ensureLogFileReady();
let fileFailed = false;
const mirror = (destination: NodeJS.WriteStream, stream: string): Writable => new Writable({
write(chunk: Buffer, _encoding, done) {
if (loggingEnabled && activeLogPath && !fileFailed) {
if (!fileFailed) {
try {
appendFileSync(activeLogPath, `${new Date().toISOString()} [${stream}] ${chunk.toString('utf8')}`);
appendFileSync(active, `${new Date().toISOString()} [${stream}] ${chunk.toString('utf8')}`);
} catch (error) {
fileFailed = true;
originalConsole.error('[logs] writing the launcher log failed:', error);
@@ -1,11 +1,26 @@
import { isHardlinkableResource } from '@wto/patcher';
import { lstat, readdir } from 'node:fs/promises';
import { join } from 'node:path';
import type { FolderSize } from '@shared/schemas/install.ts';
import { planCopy } from '../install/copy-game.ts';
/** Estimate the installation size and the bytes eligible for space-saving hard links. */
/**
* The size of a folder tree, counted the way the copy will copy it: regular files only. Links
* and junctions are not followed. Asynchronous, so the window stays responsive on a large
* installation.
*/
export async function measureFolder(root: string): Promise<FolderSize> {
const plan = await planCopy(root);
const linkableBytes = plan.files.reduce((total, file) =>
total + (isHardlinkableResource(file.relativePath, file.bytes) ? file.bytes : 0), 0);
return { bytes: plan.totalBytes, files: plan.files.length, linkableBytes };
let bytes = 0;
let files = 0;
const pending = [root];
while (pending.length) {
const folder = pending.pop()!;
for (const entry of await readdir(folder, { withFileTypes: true })) {
const path = join(folder, entry.name);
if (entry.isDirectory()) pending.push(path);
else if (entry.isFile()) {
bytes += (await lstat(path)).size;
files += 1;
}
}
}
return { bytes, files };
}
@@ -1,97 +1,34 @@
import { access, readFile, realpath, stat } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { access, readFile, stat } from 'node:fs/promises';
import { join } from 'node:path';
import { executableVersion, GAME_FILES, isInSteamLibrary, recordedGameVersions } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { GameFolderInspection } from '@shared/schemas/install.ts';
import { detectHardlinkedResources, readClientMarker } from '../install/client-marker.ts';
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
import { resourcePaths } from '../resources/resource-paths.ts';
const PATCH_MARKER_FILES = ['wto_ws.dll', 'wto_ws.cfg'] as const;
const PATCHED_EXE_MARKER = Buffer.from('wto_ws.dll', 'ascii');
/**
* Look at a folder the player chose as their War Thunder installation: is it one, which version,
* whether it already has an offline stock backup, whether it is already patched without one,
* and whether it is inside a Steam library. Only reads.
* and is it a Steam library. Only reads.
*/
export async function inspectGameFolder(path: string): Promise<GameFolderInspection> {
await requireFolder(path);
const resolved = await realpath(path);
const required = Object.values(GAME_FILES);
const missingFiles: string[] = [];
for (const file of required) {
if (!(await exists(join(resolved, file)))) missingFiles.push(file);
}
const stockRoot = join(resolved, STOCK_BACKUP_FOLDER);
let hasStockFiles = true;
for (const file of required) {
if (!(await exists(join(stockRoot, file)))) {
hasStockFiles = false;
break;
}
if (!(await exists(join(path, file)))) missingFiles.push(file);
}
const resources = resourcePaths();
const liveExeBytes = missingFiles.includes(GAME_FILES.executable)
? null
: await readBytes(join(resolved, GAME_FILES.executable));
const liveVersion = liveExeBytes ? readVersionFromBytes(liveExeBytes) : null;
const backupExeBytes = hasStockFiles
? await readBytes(join(stockRoot, GAME_FILES.executable))
: null;
const backupVersion = backupExeBytes ? readVersionFromBytes(backupExeBytes) : null;
// Always report the live executable's version when readable so an externally updated client
// (for example, an in-place folder updated by the official launcher) is never masked by a stale
// wtoffline/stock backup.
const version = liveVersion ?? backupVersion;
const hasOfflineBackup = hasStockFiles && backupVersion !== null && (liveVersion === null || backupVersion === liveVersion);
const liveExePatched = liveExeBytes !== null && liveExeBytes.includes(PATCHED_EXE_MARKER);
let needsStockSource = false;
if (!hasOfflineBackup && missingFiles.length === 0) {
if (hasStockFiles && backupVersion !== null && liveVersion !== null && backupVersion !== liveVersion) {
// A stale stock backup only needs an external stock source if the live executable is already
// patched; an unpatched live executable can refresh wtoffline/stock directly during install.
needsStockSource = liveExePatched;
} else {
const exeDir = join(resolved, dirname(GAME_FILES.executable));
const hasMarkerFile = (await Promise.all(
PATCH_MARKER_FILES.map((file) => exists(join(exeDir, file))),
)).some(Boolean);
needsStockSource = hasMarkerFile || liveExePatched;
}
}
const [clientMarker, hasHardlinkedResources] = await Promise.all([
readClientMarker(resolved),
detectHardlinkedResources(resolved),
]);
return {
path,
resolvedPath: resolved,
missingFiles,
version,
version: missingFiles.includes(GAME_FILES.executable) ? null : await readVersion(join(path, GAME_FILES.executable)),
verifiedVersions: recordedGameVersions(resources.patches),
inSteamLibrary: isInSteamLibrary(path) || isInSteamLibrary(resolved),
hasOfflineBackup,
needsStockSource,
clientOrigin: clientMarker?.origin ?? null,
hasHardlinkedResources,
inSteamLibrary: isInSteamLibrary(path),
};
}
async function readBytes(filePath: string): Promise<Buffer | null> {
async function readVersion(executablePath: string): Promise<string | null> {
try {
return await readFile(filePath);
} catch (error) {
console.warn('[game-folder] reading the executable failed:', error);
return null;
}
}
function readVersionFromBytes(bytes: Buffer): string | null {
try {
return executableVersion(bytes);
return executableVersion(await readFile(executablePath));
} catch (error) {
// Not a PE file, or unreadable: the folder is then not a usable installation, which the
// missing version already says.
@@ -1,99 +1,24 @@
import { readdir, stat, statfs } from 'node:fs/promises';
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
import { readdir, realpath, stat, statfs } from 'node:fs/promises';
import { dirname, parse, relative, resolve, isAbsolute } from 'node:path';
import { isInSteamLibrary } from '@wto/patcher';
import type { TargetFolderInspection } from '@shared/schemas/install.ts';
import { canonicalCopyPath, listCopies } from '../install/install-record.ts';
const DEFAULT_SUBFOLDER = 'WTOffline';
const SUBFOLDER_PATTERN = /^wtoffline(?:[-_].+)?$/i;
const MAX_DUPLICATE_SUFFIX = 99;
/**
* Look at the exact folder for the game copy (install by copying): it must be new or
* Look at the folder the player chose for the game copy (install by copying): it must be new or
* empty, must not overlap the stock installation, and the drive must have room. Only reads.
*/
export async function inspectTargetFolder(path: string, stockPath: string): Promise<TargetFolderInspection> {
const [target, stock] = await Promise.all([canonicalCopyPath(path), canonicalCopyPath(stockPath)]);
const target = await canonical(path);
const stock = await canonical(stockPath);
return {
path,
resolvedPath: target,
problem: await targetProblem(target, stock),
inSteamLibrary: isInSteamLibrary(path) || isInSteamLibrary(target),
inSteamLibrary: isInSteamLibrary(target),
freeBytes: await freeBytes(target),
sameDriveAsStock: await sameVolume(target, stock),
sameDriveAsStock: parse(target).root.toLowerCase() === parse(stock).root.toLowerCase(),
};
}
/**
* Resolve a player-picked parent folder into a dedicated `WTOffline` subfolder (falling back to
* `WTOffline-<version>` and `WTOffline-2`, `WTOffline-3`, ... when an earlier folder already has
* files or is registered), unless the picked folder is already an empty `WTOffline*` directory.
*/
export async function inspectPickedTargetFolder(
pickedPath: string,
stockPath: string,
version: string | null,
): Promise<TargetFolderInspection> {
const [picked, stock] = await Promise.all([canonicalCopyPath(pickedPath), canonicalCopyPath(stockPath)]);
if (contains(stock, picked) || contains(picked, stock)) {
return inspectTargetFolder(pickedPath, stockPath);
}
try {
const info = await stat(picked);
if (!info.isDirectory()) return inspectTargetFolder(pickedPath, stockPath);
} catch {
// Picked folder does not exist yet; still check it directly if it already looks like WTOffline*.
}
const registered = await registeredCopyPaths();
if (SUBFOLDER_PATTERN.test(basename(pickedPath)) && !registered.has(picked.toLowerCase())) {
const directProblem = await targetProblem(picked, stock);
if (directProblem === null) return inspectTargetFolder(pickedPath, stockPath);
}
const candidateNames = [DEFAULT_SUBFOLDER];
const safeVersion = version?.replace(/[^0-9A-Za-z._-]/g, '').trim();
if (safeVersion) candidateNames.push(`${DEFAULT_SUBFOLDER}-${safeVersion}`);
for (let i = 2; i <= MAX_DUPLICATE_SUFFIX; i += 1) {
candidateNames.push(`${DEFAULT_SUBFOLDER}-${i}`);
}
for (const name of candidateNames) {
const candidate = join(pickedPath, name);
const resolvedCandidate = await canonicalCopyPath(candidate);
if (registered.has(resolvedCandidate.toLowerCase())) continue;
const problem = await targetProblem(resolvedCandidate, stock);
if (problem === null) return inspectTargetFolder(candidate, stockPath);
}
return inspectTargetFolder(join(pickedPath, DEFAULT_SUBFOLDER), stockPath);
}
async function registeredCopyPaths(): Promise<Set<string>> {
try {
const { copies } = await listCopies();
const resolved = await Promise.all(copies.map((entry) => canonicalCopyPath(entry.copyPath).catch(() => entry.copyPath)));
return new Set(resolved.map((folder) => folder.toLowerCase()));
} catch {
return new Set();
}
}
/** Compare actual volumes, including directories reached through junctions. */
export async function sameVolume(left: string, right: string): Promise<boolean> {
const [first, second] = await Promise.all([volumeDevice(left), volumeDevice(right)]);
return first !== null && first === second;
}
async function volumeDevice(path: string): Promise<bigint | null> {
for (let folder = resolve(path); ; folder = dirname(folder)) {
try {
return (await stat(folder, { bigint: true })).dev || null;
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || dirname(folder) === folder) return null;
}
}
}
async function targetProblem(target: string, stock: string): Promise<TargetFolderInspection['problem']> {
if (contains(stock, target) || contains(target, stock)) return 'overlaps_stock';
let entries: string[];
@@ -114,7 +39,7 @@ function contains(outer: string, inner: string): boolean {
}
/** Free bytes on the drive of the nearest existing folder at or above `path`. */
export async function freeBytes(path: string): Promise<number | null> {
async function freeBytes(path: string): Promise<number | null> {
for (let folder = path; ; folder = dirname(folder)) {
try {
const info = await statfs(folder);
@@ -124,3 +49,15 @@ export async function freeBytes(path: string): Promise<number | null> {
}
}
}
/** The real path of the nearest existing part, with the rest appended as given. */
async function canonical(path: string): Promise<string> {
const absolute = resolve(path);
try {
return await realpath(absolute);
} catch {
const parent = dirname(absolute);
if (parent === absolute) return absolute;
return resolve(await canonical(parent), relative(parent, absolute));
}
}
@@ -1,114 +0,0 @@
import { join } from 'node:path';
import { z } from 'zod';
import { hardlinkResourceRules, isHardlinkableResource } from '@wto/patcher';
import { ClientOriginSchema, type ClientOrigin } from '@shared/schemas/install.ts';
import { writeJsonAtomic } from '../../util/atomic-json.ts';
import { rawFs } from '../../util/raw-fs.ts';
/** Relative path of the self-describing client identity marker inside a client folder. */
export const CLIENT_MARKER_FILE = join('wtoffline', 'client.json');
export const ClientMarkerSchema = z.object({
format: z.literal(1),
origin: ClientOriginSchema,
createdBy: z.literal('wtoffline-launcher'),
createdAt: z.string().min(1),
updatedAt: z.string().min(1).optional(),
});
export type ClientMarker = z.output<typeof ClientMarkerSchema>;
/** Cap on qualifying resource files inspected when sampling for hard links. */
const MAX_RESOURCE_SAMPLES = 64;
export function clientMarkerPath(copyFolder: string): string {
return join(copyFolder, CLIENT_MARKER_FILE);
}
/**
* Safely read and validate `<copyFolder>/wtoffline/client.json`.
* Returns `null` when missing, unreadable, malformed, or schema-invalid without throwing.
*/
export async function readClientMarker(copyFolder: string): Promise<ClientMarker | null> {
try {
const text = await rawFs().promises.readFile(clientMarkerPath(copyFolder), 'utf8');
const parsed = ClientMarkerSchema.safeParse(JSON.parse(text) as unknown);
return parsed.success ? parsed.data : null;
} catch {
return null;
}
}
/**
* Atomically write `<copyFolder>/wtoffline/client.json`.
* Preserves `createdAt` and records `updatedAt` when updating an existing valid marker.
*/
export async function writeClientMarker(copyFolder: string, origin: ClientOrigin): Promise<ClientMarker> {
const existing = await readClientMarker(copyFolder);
const now = new Date().toISOString();
const marker: ClientMarker = existing
? {
format: 1,
origin,
createdBy: 'wtoffline-launcher',
createdAt: existing.createdAt,
updatedAt: now,
}
: {
format: 1,
origin,
createdBy: 'wtoffline-launcher',
createdAt: now,
};
await writeJsonAtomic(clientMarkerPath(copyFolder), marker);
return marker;
}
/**
* Lightweight probe for hard-linked read-only resource packs under allowed content directories.
* Returns `true` as soon as a single qualifying resource reports `nlink >= 2`, or `false` on
* missing/unreadable directories or when no sampled resource is hard-linked.
*/
export async function detectHardlinkedResources(copyFolder: string): Promise<boolean> {
const fsPromises = rawFs().promises;
const rules = hardlinkResourceRules();
const queue: Array<{ absDir: string; relDir: string }> = rules.allowedDirectories.map((dir) => {
const clean = dir.replace(/\/+$/, '');
return { absDir: join(copyFolder, clean), relDir: clean };
});
let sampled = 0;
while (queue.length > 0 && sampled < MAX_RESOURCE_SAMPLES) {
const current = queue.shift()!;
let entries;
try {
entries = await fsPromises.readdir(current.absDir, { withFileTypes: true });
} catch {
continue;
}
for (const entry of entries) {
if (entry.isSymbolicLink()) continue;
const absPath = join(current.absDir, entry.name);
const relPath = `${current.relDir}/${entry.name}`;
if (entry.isDirectory()) {
queue.push({ absDir: absPath, relDir: relPath });
continue;
}
if (!entry.isFile()) continue;
const lower = entry.name.toLowerCase();
if (!rules.allowedExtensions.some((ext) => lower.endsWith(ext))) continue;
try {
const stats = await fsPromises.lstat(absPath);
if (!stats.isFile() || !isHardlinkableResource(relPath, stats.size)) continue;
if (stats.nlink >= 2) return true;
sampled += 1;
if (sampled >= MAX_RESOURCE_SAMPLES) return false;
} catch {
continue;
}
}
}
return false;
}
@@ -1,11 +1,8 @@
import type { BigIntStats, Dirent } from 'node:fs';
import { join, normalize, relative, sep } from 'node:path';
import { createReadStream, createWriteStream } from 'node:fs';
import { lstat, mkdir, readdir, rm, utimes } from 'node:fs/promises';
import { join, relative } from 'node:path';
import { Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { AppError } from '@shared/errors.ts';
import { rawFs } from '../../util/raw-fs.ts';
import { linkVerifiedResource, sameResource } from './hardlink-files.ts';
import { findIncompleteUhqPacks, isPathInUhqPacks } from './uhq-packages.ts';
/**
* Copy a War Thunder installation into a new or empty folder (install method "copy"). The stock
@@ -13,45 +10,12 @@ import { findIncompleteUhqPacks, isPathInUhqPacks } from './uhq-packages.ts';
*/
/**
* Top-level folders of an installation that hold player-generated data or user content from
* playing online, not the stock client itself: logs, the web content cache, replays, screenshots,
* and user missions, skins and sights. The offline copy does not take the online game's data; the
* Top-level folders of an installation that hold what the game produced while the player played
* online, not the game itself: logs, the web content cache, replays, screenshots and the player's
* own missions. The offline copy does not take the online game's data (working rules 18); the
* game creates these folders again when it needs them.
*/
export const PLAYER_DATA_FOLDERS = new Set([
'.game_logs',
'cache',
'replays',
'screenshots',
'usermissions',
'userskins',
'usersights',
]);
/**
* Top-level folders ignored when scanning a stock source in addition to player data:
* official launcher/updater logs and obsolete files, the War Thunder CDK toolkit, and any stray
* offline backup directory.
*/
const SKIPPED_SOURCE_FOLDERS = new Set([
...PLAYER_DATA_FOLDERS,
'.gaijin_updater_logs',
'.launcher_log',
'.obsolete',
'.start_app_logs',
'warthundercdk',
'wtoffline',
]);
const LAUNCHER_EXECUTABLE_LOWER = 'wtoffline launcher.exe';
/** Whether a relative path starts with a top-level entry excluded from source scans. */
export function isInSkippedSourceFolder(relativePath: string): boolean {
const [topLevel = ''] = normalize(relativePath).split(sep, 1);
return SKIPPED_SOURCE_FOLDERS.has(topLevel.toLowerCase());
}
function isLauncherFolder(entries: readonly Dirent[]): boolean {
return entries.some((entry) => entry.isFile() && entry.name.toLowerCase() === LAUNCHER_EXECUTABLE_LOWER);
}
const PLAYER_DATA_FOLDERS = new Set(['.game_logs', 'cache', 'replays', 'screenshots', 'usermissions']);
interface CopyEntry {
readonly relativePath: string;
@@ -68,44 +32,25 @@ export interface CopyPlan {
export interface CopyProgress {
readonly doneBytes: number;
readonly doneFiles: number;
/** Bytes actually written to disk so far (excludes hard-linked files). */
readonly copiedBytes: number;
/** Bytes shared via hard links so far (occupies no extra disk space). */
readonly linkedBytes: number;
/** Number of hard-linked files created so far. */
readonly linkedFiles: number;
}
/** Every file and folder to copy, relative to `source`. Links and junctions are not followed. */
export async function planCopy(source: string): Promise<CopyPlan> {
const fsPromises = rawFs().promises;
const incompleteUhq = await findIncompleteUhqPacks(source);
const skippedUhq = new Set(incompleteUhq);
if (incompleteUhq.length > 0) {
console.warn(`[install] skipping incomplete optional UHQ pack(s) in ${source}: ${incompleteUhq.join(', ')}`);
}
const files: CopyEntry[] = [];
const folders: string[] = [];
let totalBytes = 0;
const pending = [source];
while (pending.length) {
const folder = pending.pop()!;
const entries = await fsPromises.readdir(folder, { withFileTypes: true });
if (folder !== source) {
// Skip any WTOffline Launcher folder that was previously extracted inside the game directory.
if (isLauncherFolder(entries)) continue;
folders.push(relative(source, folder));
}
for (const entry of entries) {
for (const entry of await readdir(folder, { withFileTypes: true })) {
const path = join(folder, entry.name);
if (folder === source && isInSkippedSourceFolder(entry.name)) continue;
const relPath = relative(source, path);
if (isPathInUhqPacks(relPath, skippedUhq)) continue;
if (folder === source && PLAYER_DATA_FOLDERS.has(entry.name.toLowerCase())) continue;
if (entry.isDirectory()) {
folders.push(relative(source, path));
pending.push(path);
} else if (entry.isFile()) {
const { size, mtimeMs } = await fsPromises.lstat(path);
files.push({ relativePath: relPath, bytes: size, modifiedAt: mtimeMs });
const { size, mtimeMs } = await lstat(path);
files.push({ relativePath: relative(source, path), bytes: size, modifiedAt: mtimeMs });
totalBytes += size;
}
}
@@ -127,27 +72,16 @@ export async function copyPlannedFiles(
plan: CopyPlan,
signal: AbortSignal,
onProgress: (progress: CopyProgress) => void,
hardlinks?: ReadonlyMap<string, BigIntStats>,
): Promise<void> {
const fs = rawFs();
const fsPromises = fs.promises;
await fsPromises.mkdir(target, { recursive: true });
for (const folder of plan.folders) await fsPromises.mkdir(join(target, folder), { recursive: true });
const linkedTargets = hardlinks ? new Map<string, BigIntStats>() : undefined;
await mkdir(target, { recursive: true });
for (const folder of plan.folders) await mkdir(join(target, folder), { recursive: true });
let next = 0;
let copiedBytes = 0;
let linkedBytes = 0;
let linkedFiles = 0;
let doneBytes = 0;
let doneFiles = 0;
const emitProgress = (): void => {
// Keep doneBytes aligned with actual bytes written to disk so hard-linked files
// do not inflate copy progress.
onProgress({ doneBytes: copiedBytes, doneFiles, copiedBytes, linkedBytes, linkedFiles });
};
const countBytes = (): Transform => new Transform({
transform(chunk: Buffer, _encoding, callback) {
copiedBytes += chunk.length;
emitProgress();
doneBytes += chunk.length;
onProgress({ doneBytes, doneFiles });
callback(null, chunk);
},
});
@@ -155,54 +89,31 @@ export async function copyPlannedFiles(
// caller cleaning up after an error never races a copy still writing.
const stop = new AbortController();
const stopSignal = AbortSignal.any([signal, stop.signal]);
let firstError: unknown = null;
let hasError = false;
const copyNext = async (): Promise<void> => {
try {
while (next < plan.files.length) {
stopSignal.throwIfAborted();
const file = plan.files[next++]!;
const from = join(source, file.relativePath);
const to = join(target, file.relativePath);
const verified = hardlinks?.get(file.relativePath);
if (verified) {
const linked = await linkVerifiedResource(from, to, verified);
linkedTargets?.set(to, linked);
linkedBytes += file.bytes;
linkedFiles += 1;
} else {
await pipeline(
fs.createReadStream(from),
countBytes(),
// 'wx': fail instead of overwriting a file that is already there.
fs.createWriteStream(to, { flags: 'wx' }),
{ signal: stopSignal },
);
const modified = new Date(file.modifiedAt);
await fsPromises.utimes(to, modified, modified);
}
await pipeline(
createReadStream(join(source, file.relativePath)),
countBytes(),
// 'wx': fail instead of overwriting a file that is already there.
createWriteStream(join(target, file.relativePath), { flags: 'wx' }),
{ signal: stopSignal },
);
const modified = new Date(file.modifiedAt);
await utimes(join(target, file.relativePath), modified, modified);
doneFiles += 1;
emitProgress();
onProgress({ doneBytes, doneFiles });
}
} catch (error) {
if (!hasError && !stop.signal.aborted && !signal.aborted) {
hasError = true;
firstError = error;
}
stop.abort(error);
throw error;
}
};
const results = await Promise.allSettled(Array.from({ length: PARALLEL_COPIES }, copyNext));
if (hasError) throw firstError;
const failed = results.find((result): result is PromiseRejectedResult => result.status === 'rejected');
if (failed) throw failed.reason;
if (linkedTargets) {
for (const [path, stamp] of linkedTargets) {
signal.throwIfAborted();
if (!sameResource(stamp, await fsPromises.lstat(path, { bigint: true }))) throw new AppError('hardlink_file_changed');
}
}
}
/**
@@ -210,10 +121,9 @@ export async function copyPlannedFiles(
* when the copy started, so everything in it came from the copy.
*/
export async function removeInterruptedCopy(target: string, targetExisted: boolean): Promise<void> {
const fsPromises = rawFs().promises;
if (!targetExisted) {
await fsPromises.rm(target, { recursive: true, force: true });
await rm(target, { recursive: true, force: true });
return;
}
for (const entry of await fsPromises.readdir(target)) await fsPromises.rm(join(target, entry), { recursive: true, force: true });
for (const entry of await readdir(target)) await rm(join(target, entry), { recursive: true, force: true });
}
@@ -1,43 +0,0 @@
import { readdir } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { AppError } from '@shared/errors.ts';
import type { DataFolderProblem } from '@shared/schemas/install.ts';
import { copyPathContains } from './install-record.ts';
import { STOCK_BACKUP_FOLDER } from './stock-backup.ts';
/**
* Validate where the offline data folder sits relative to the client and stock folders.
* A subfolder inside the client (outside wtoffline/) is allowed, while setting dataPath to the
* client folder itself or an ancestor of it would mix game files into the data root.
*/
export function dataFolderProblem(
dataPath: string,
copyPath: string | null,
sourcePath: string | null,
externalStockPath: string | null,
): DataFolderProblem | null {
if (copyPath && (copyPathContains(dataPath, copyPath) ||
copyPathContains(join(copyPath, dirname(STOCK_BACKUP_FOLDER)), dataPath))) {
return 'overlaps_client';
}
if ((sourcePath && copyPathContains(sourcePath, dataPath)) ||
(externalStockPath && copyPathContains(externalStockPath, dataPath))) {
return 'overlaps_stock';
}
return null;
}
/** A data tree must keep the server's saves, logs and caches inside the selected folder. */
export async function requireUnredirectedData(root: string): Promise<void> {
const folders = [root];
for (let folder = folders.pop(); folder !== undefined; folder = folders.pop()) {
const entries = await readdir(folder, { withFileTypes: true }).catch((error: NodeJS.ErrnoException) => {
if (folder === root && error.code === 'ENOENT') return [];
throw error;
});
for (const entry of entries) {
if (entry.isSymbolicLink()) throw new AppError('launch_location');
if (entry.isDirectory()) folders.push(join(folder, entry.name));
}
}
}
@@ -1,141 +0,0 @@
import { randomUUID } from 'node:crypto';
import { cp, lstat, mkdir, realpath, rm } from 'node:fs/promises';
import { dirname, isAbsolute, join, relative } from 'node:path';
import {
isInSteamLibrary,
playerDecalCacheProblem,
resolvePlayerDecalCacheFolder,
writeDecalCacheIndexSnapshot,
} from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { Copies } from '@shared/schemas/install.ts';
import { canonicalCopyPath, copyPathContains, listCopies, steamLibraryNeedsConfirmation, updateCopyRecord } from './install-record.ts';
const CACHE_FOLDER = 'decal-cache';
let changing = false;
export function decalImportInProgress(): boolean {
return changing;
}
export function decalCachePath(dataPath: string, cacheId: string): string {
return join(dataPath, CACHE_FOLDER, cacheId);
}
/**
* Read-only check whether a player-chosen or registered folder contains a usable decal cache
* (<game>, <game>/cache, or <game>/cache/content). Returns the canonical cache/content path when
* valid, or null when absent, invalid, or unreadable.
*/
export async function detectDecalCacheSource(folderPath: string): Promise<string | null> {
if (!folderPath || !isAbsolute(folderPath)) return null;
try {
const rawSource = await realpath(folderPath).catch(() => null);
if (!rawSource) return null;
const resolved = resolvePlayerDecalCacheFolder(rawSource);
const canonical = await realpath(resolved).catch(() => null);
if (!canonical) return null;
return playerDecalCacheProblem(canonical) === undefined ? canonical : null;
} catch {
return null;
}
}
async function cacheRoot(dataPath: string, steamDataConfirmed: boolean): Promise<string> {
if (!isAbsolute(dataPath)) throw new AppError('decal_import_failed');
const data = await canonicalCopyPath(dataPath);
const root = join(data, CACHE_FOLDER);
if ((isInSteamLibrary(data) && (!steamDataConfirmed || relative(dataPath, data) !== '')) ||
relative(root, await canonicalCopyPath(root)) !== '') {
throw new AppError('decal_import_failed');
}
return root;
}
/** Import the selected cache as its own snapshot so a later build can use the copy's data alone. */
export async function importDecalCache(
dataPath: string, sourcePath: string, signal?: AbortSignal, steamDataConfirmed = false,
): Promise<string> {
if (!isAbsolute(sourcePath)) throw new AppError('decal_source_invalid');
const rawSource = await realpath(sourcePath).catch(() => null);
const source = rawSource ? await realpath(resolvePlayerDecalCacheFolder(rawSource)).catch(() => null) : null;
const problem = source ? playerDecalCacheProblem(source) : 'selected folder could not be resolved';
if (!source || problem) {
console.warn('[decals] invalid decal cache source:', sourcePath, '->', problem);
throw new AppError('decal_source_invalid');
}
const root = await cacheRoot(dataPath, steamDataConfirmed);
if (copyPathContains(source, root) || copyPathContains(root, source)) {
throw new AppError('decal_source_invalid');
}
const id = randomUUID();
const target = join(root, id);
try {
await mkdir(root, { recursive: true });
await cp(source, target, {
recursive: true,
force: false,
errorOnExist: true,
filter: async (path) => {
signal?.throwIfAborted();
const entry = await lstat(path);
if (!entry.isDirectory() && !entry.isFile()) throw new AppError('decal_source_invalid');
return true;
},
});
signal?.throwIfAborted();
writeDecalCacheIndexSnapshot(source, target);
const copiedProblem = playerDecalCacheProblem(target);
if (copiedProblem) {
console.warn('[decals] copied decal cache failed validation:', copiedProblem);
throw new AppError('decal_source_invalid');
}
return id;
} catch (error) {
await discardDecalCache(dataPath, id, steamDataConfirmed);
if (signal?.aborted || error instanceof AppError) throw error;
console.error('[decals] could not import the cache:', error);
throw new AppError('decal_import_failed');
}
}
export async function discardDecalCache(dataPath: string, id: string, steamDataConfirmed = false): Promise<void> {
try {
const root = await cacheRoot(dataPath, steamDataConfirmed);
const target = decalCachePath(dataPath, id);
const actual = await realpath(target).catch(() => null);
if (actual && relative(root, dirname(actual)) === '' && relative(join(root, id), actual) === '') {
await rm(actual, { recursive: true, force: true });
}
} catch (error) {
console.warn('[decals] could not remove the replaced cache:', error);
}
}
export async function changeDecalSource(id: string, source: string | null): Promise<Copies> {
if (changing) throw new AppError('maintenance_busy');
changing = true;
try {
const record = (await listCopies()).copies.find((copy) => copy.id === id);
if (!record) throw new AppError('copy_not_found');
const [copyPath, dataPath] = await Promise.all([canonicalCopyPath(record.copyPath), canonicalCopyPath(record.dataPath)]);
if (steamLibraryNeedsConfirmation(record, copyPath, dataPath)) throw new AppError('launch_steam_confirmation_required');
const dataInSteam = isInSteamLibrary(dataPath);
const cacheId = source === null ? undefined : await importDecalCache(dataPath, source, undefined, dataInSteam);
let copies: Copies;
try {
copies = await updateCopyRecord(id, (current) => {
const { decalCacheId, ...other } = current;
return cacheId === undefined ? other : { ...other, decalCacheId: cacheId };
});
} catch (error) {
if (cacheId) await discardDecalCache(dataPath, cacheId, dataInSteam);
throw error;
}
if (record.decalCacheId) await discardDecalCache(dataPath, record.decalCacheId, dataInSteam);
return copies;
} finally {
changing = false;
}
}
@@ -1,113 +0,0 @@
import { createHash } from 'node:crypto';
import { createReadStream, type BigIntStats } from 'node:fs';
import { link, lstat } from 'node:fs/promises';
import { join } from 'node:path';
import { isHardlinkableResource } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { InstallProgress } from '@shared/schemas/install.ts';
import type { CopyPlan } from './copy-game.ts';
export type ResourceMatchResult =
| { readonly status: 'already-linked'; readonly copyStamp: BigIntStats; readonly sourceStamp: BigIntStats }
| { readonly status: 'matched'; readonly copyStamp: BigIntStats; readonly sourceStamp: BigIntStats }
| { readonly status: 'mismatch' };
export async function fileHash(path: string, signal: AbortSignal): Promise<string> {
const hash = createHash('sha256');
for await (const chunk of createReadStream(path, { signal })) hash.update(chunk as Buffer);
return hash.digest('hex');
}
export async function statFile(path: string): Promise<BigIntStats | null> {
return lstat(path, { bigint: true }).catch((error: NodeJS.ErrnoException) => {
if (error.code === 'ENOENT') return null;
throw error;
});
}
/** Capture the file identity of a stock asset right before hardlinking it. */
export async function statHardlinkResource(
path: string,
expectedBytes: number,
signal: AbortSignal,
): Promise<BigIntStats | null> {
signal.throwIfAborted();
const stats = await statFile(path);
if (!stats?.isFile() || stats.size !== BigInt(expectedBytes)) return null;
return stats;
}
/**
* Verify that an existing copy file and stock file have identical contents before replacing the
* copy file with a hard link. Already-linked pairs return immediately without re-hashing.
*/
export async function verifyMatchingResource(
copyPath: string,
sourcePath: string,
expectedBytes: number,
signal: AbortSignal,
): Promise<ResourceMatchResult> {
signal.throwIfAborted();
const [copyBefore, sourceBefore] = await Promise.all([statFile(copyPath), statFile(sourcePath)]);
const size = BigInt(expectedBytes);
if (!copyBefore?.isFile() || !sourceBefore?.isFile() || copyBefore.size !== size || sourceBefore.size !== size) {
return { status: 'mismatch' };
}
if (sameResource(copyBefore, sourceBefore)) {
return { status: 'already-linked', copyStamp: copyBefore, sourceStamp: sourceBefore };
}
const [copyHash, sourceHash] = await Promise.all([fileHash(copyPath, signal), fileHash(sourcePath, signal)]);
const [copyAfter, sourceAfter] = await Promise.all([statFile(copyPath), statFile(sourcePath)]);
if (!copyAfter || !sourceAfter || !sameResource(copyBefore, copyAfter) || !sameResource(sourceBefore, sourceAfter)) {
throw new AppError('hardlink_file_changed');
}
return copyHash === sourceHash
? { status: 'matched', copyStamp: copyAfter, sourceStamp: sourceAfter }
: { status: 'mismatch' };
}
export function sameInode(left: BigIntStats, right: BigIntStats): boolean {
return left.isFile() && right.isFile() && left.dev === right.dev && left.ino === right.ino;
}
export function sameResource(left: BigIntStats, right: BigIntStats): boolean {
return sameIdentityAndContents(left, right) && left.ctimeNs === right.ctimeNs;
}
export async function linkVerifiedResource(source: string, target: string, verified: BigIntStats): Promise<BigIntStats> {
if (!sameResource(verified, await lstat(source, { bigint: true }))) throw new AppError('hardlink_file_changed');
await link(source, target);
// Linking may change ctime. The inode, contents and modification time must stay the same.
const linked = await lstat(target, { bigint: true });
if (!sameIdentityAndContents(verified, linked)) throw new AppError('hardlink_file_changed');
return linked;
}
function sameIdentityAndContents(left: BigIntStats, right: BigIntStats): boolean {
return right.isFile() && left.dev === right.dev && left.ino === right.ino &&
left.size === right.size && left.mtimeNs === right.mtimeNs;
}
/** Collect and stat every eligible read-only resource pack in `plan` before hard-linking. */
export async function prepareHardlinks(
source: string,
plan: CopyPlan,
signal: AbortSignal,
report: (progress: InstallProgress) => void,
): Promise<ReadonlyMap<string, BigIntStats>> {
const candidates = plan.files.filter((file) => isHardlinkableResource(file.relativePath, file.bytes));
const totalBytes = candidates.reduce((total, file) => total + file.bytes, 0);
const links = new Map<string, BigIntStats>();
let doneBytes = 0;
let doneFiles = 0;
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
for (const file of candidates) {
const verified = await statHardlinkResource(join(source, file.relativePath), file.bytes, signal);
if (verified) links.set(file.relativePath, verified);
doneBytes += file.bytes;
doneFiles += 1;
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
}
if (!links.size) throw new AppError('hardlink_no_match');
return links;
}
@@ -1,21 +1,12 @@
import { access, mkdir } from 'node:fs/promises';
import { dirname, isAbsolute, relative } from 'node:path';
import { app } from 'electron';
import { isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { ClientOrigin, InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
import type { InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
import { freeBytes, inspectTargetFolder, sameVolume } from '../game-folder/inspect-target-folder.ts';
import { readClientMarker, writeClientMarker } from './client-marker.ts';
import { inspectTargetFolder } from '../game-folder/inspect-target-folder.ts';
import { copyPlannedFiles, planCopy, removeInterruptedCopy } from './copy-game.ts';
import { dataFolderProblem, requireUnredirectedData } from './data-location.ts';
import { discardDecalCache, importDecalCache } from './decals.ts';
import { prepareHardlinks } from './hardlink-files.ts';
import { canonicalCopyPath, copyPathContains, requireAvailableCopy, writeInstallRecord } from './install-record.ts';
import { requireAvailableCopy, writeInstallRecord } from './install-record.ts';
import { checkPatches } from './patch-check.ts';
import { backUpStockFiles, installStockSource, refreshStockBackup, refreshStockBackupFrom, requireStockBackupLocation } from './stock-backup.ts';
export { dataFolderProblem } from './data-location.ts';
import { backUpStockFiles, stockBackupPath } from './stock-backup.ts';
/**
* Install the offline version: check the patches against the player's game,
@@ -44,9 +35,6 @@ export async function installGame(request: InstallRequest, onProgress: (progress
running = controller;
try {
return await install(request, controller.signal, throttled(onProgress));
} catch (error) {
if (controller.signal.aborted) throw new AppError('install_cancelled');
throw error;
} finally {
running = null;
}
@@ -59,198 +47,92 @@ export function cancelInstall(): boolean {
return true;
}
/**
* The stock files a check of `gameFolder` starts from: its backup folder when it already has one
* (a folder installed before, whose own files may be patched), otherwise its own files.
*/
export async function stockFolderOf(gameFolder: string): Promise<string> {
const backup = stockBackupPath(gameFolder);
try {
await access(backup);
return backup;
} catch {
return gameFolder;
}
}
/** Which patches fit the game in `gameFolder`, for the window to show before installing. */
export async function checkGameFolder(gameFolder: string, dataPath: string, stockSourcePath?: string): Promise<PatchCheck> {
const game = await requireGameFolder(gameFolder);
const stock = stockSourcePath
? await resolveExternalStockSource(stockSourcePath, game.version)
: game.needsStockSource
? (() => { throw new AppError('stock_source_invalid'); })()
: await installStockSource(game.resolvedPath, game.version);
const data = await canonicalCopyPath(dataPath);
await requireUnredirectedData(data);
return checkPatches(stock.path, data);
export async function checkGameFolder(gameFolder: string, dataPath: string): Promise<PatchCheck> {
await requireGameFolder(gameFolder);
return checkPatches(await stockFolderOf(gameFolder), dataPath);
}
async function install(request: InstallRequest, signal: AbortSignal, report: (progress: InstallProgress) => void): Promise<InstallRecord> {
const { version, requestedCopyPath, copyPath, dataPath, sourcePath, externalStockPath, target, useHardLinks, copyInSteam, dataInSteam } =
await inspectInstallation(request);
const gameFolder = request.method === 'copy' ? request.sourcePath : request.gamePath;
const game = await requireGameFolder(gameFolder);
const copyPath = request.method === 'copy' ? request.copyPath : request.gamePath;
await requireAvailableCopy(request.id, copyPath, request.dataPath);
const target = request.method === 'copy' ? await inspectTargetFolder(copyPath, gameFolder) : null;
if (target?.problem) throw new AppError('target_not_usable', { problem: target.problem });
const inSteamLibrary = target ? target.inSteamLibrary : game.inSteamLibrary;
if (inSteamLibrary && !request.steamLibraryConfirmed) throw new AppError('steam_library_not_confirmed');
report({ phase: 'checking', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
const stock = externalStockPath
? { path: externalStockPath, refresh: false }
: await installStockSource(sourcePath, version);
await mkdir(dataPath, { recursive: true });
const check = await checkPatches(stock.path, dataPath);
await mkdir(request.dataPath, { recursive: true });
const check = await checkPatches(await stockFolderOf(gameFolder), request.dataPath);
const essential = check.unavailable.filter((patch) => patch.essential);
if (essential.length) throw new AppError('essential_patches_unavailable', { patches: essential.map((patch) => patch.patchId).join(', ') });
if (check.unavailable.length && !request.missingFeaturesAccepted) throw new AppError('missing_features_not_accepted');
signal.throwIfAborted();
let decalCacheId: string | undefined;
if (request.decalSourcePath) {
report({ phase: 'importing-decals', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
decalCacheId = await importDecalCache(dataPath, request.decalSourcePath, signal, dataInSteam);
}
try {
const copied = request.method === 'copy'
? await copyGame(sourcePath, copyPath, target!.freeBytes, useHardLinks, version, signal, report)
: undefined;
const sourceFiles = request.method === 'copy'
? await copyGame(request.sourcePath, copyPath, target!.freeBytes, signal, report)
: undefined;
report({ phase: 'backing-up', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
const stockBackup = externalStockPath
? await refreshStockBackupFrom(copyPath, externalStockPath)
: (request.method === 'in-place' || request.method === 'existing') && stock.refresh
? await refreshStockBackup(copyPath)
: await backUpStockFiles(copyPath);
report({ phase: 'backing-up', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
const stockBackup = await backUpStockFiles(copyPath);
// Record launcher-created client origin on disk; never overwrite or fabricate a marker for existing folders.
let detectedOrigin: ClientOrigin | undefined;
if (request.method === 'copy') {
await writeClientMarker(copyPath, useHardLinks ? 'hardlink' : 'copy');
} else if (request.method === 'in-place') {
await writeClientMarker(copyPath, 'in-place');
} else {
detectedOrigin = (await readClientMarker(copyPath))?.origin;
}
report({ phase: 'recording', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
const record: InstallRecord = {
id: request.id,
name: request.name,
sourcePath: request.method === 'copy' ? sourcePath : null,
method: request.method,
copyPath: requestedCopyPath,
dataPath: request.dataPath,
...(copyInSteam || dataInSteam ? { steamLibraryConfirmation: { copyPath, dataPath } } : {}),
stockBackupPath: stockBackup,
gameVersion: version,
unavailablePatches: check.unavailable,
installedAt: new Date().toISOString(),
lastCheckedAt: new Date().toISOString(),
...(decalCacheId ? { decalCacheId } : {}),
...(detectedOrigin ? { detectedOrigin } : {}),
...copied,
};
await writeInstallRecord(record);
return record;
} catch (error) {
if (decalCacheId) await discardDecalCache(dataPath, decalCacheId, dataInSteam);
throw error;
}
}
async function inspectInstallation(request: InstallRequest) {
const gameFolder = request.method === 'copy' ? request.sourcePath : request.gamePath;
const game = await requireGameFolder(gameFolder);
let externalStockPath: string | null = null;
if (request.method === 'copy') {
if (game.needsStockSource) throw new AppError('stock_source_invalid');
} else if (request.stockSourcePath) {
externalStockPath = (await resolveExternalStockSource(request.stockSourcePath, game.version)).path;
} else if (game.needsStockSource) {
throw new AppError('stock_source_invalid');
}
const requestedCopyPath = request.method === 'copy' ? request.copyPath : request.gamePath;
const [copyPath, dataPath, sourcePath] = await Promise.all([
canonicalCopyPath(requestedCopyPath), canonicalCopyPath(request.dataPath), canonicalCopyPath(gameFolder),
]);
if (request.method === 'copy' && app.isPackaged) {
const launcherDir = await canonicalCopyPath(dirname(process.execPath));
if (copyPathContains(sourcePath, launcherDir)) {
throw new AppError('launcher_inside_source');
}
}
await requireAvailableCopy(request.id, copyPath, dataPath);
const dataProblem = dataFolderProblem(
dataPath,
report({ phase: 'recording', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
const record: InstallRecord = {
id: request.id,
name: request.name,
sourcePath: request.method === 'copy' ? request.sourcePath : null,
method: request.method,
copyPath,
request.method === 'copy' ? sourcePath : null,
externalStockPath,
);
if (!isAbsolute(request.dataPath) || dataProblem !== null) {
throw new AppError('target_not_usable', { problem: dataProblem ?? 'overlaps_stock' });
}
const target = request.method === 'copy' ? await inspectTargetFolder(copyPath, sourcePath) : null;
if (target?.problem) throw new AppError('target_not_usable', { problem: target.problem });
const useHardLinks = request.method === 'copy' && request.useHardLinks === true;
if (useHardLinks && !target?.sameDriveAsStock) {
throw new AppError('hardlink_unavailable');
}
const copyInSteam = isInSteamLibrary(requestedCopyPath) || isInSteamLibrary(copyPath);
const dataInSteam = isInSteamLibrary(request.dataPath) || isInSteamLibrary(dataPath);
const { confirmedSteamCopyPath, confirmedSteamDataPath } = request;
const copyConfirmed = confirmedSteamCopyPath !== undefined && relative(copyPath, confirmedSteamCopyPath) === '';
const dataConfirmed = confirmedSteamDataPath !== undefined && relative(dataPath, confirmedSteamDataPath) === '';
if ((copyInSteam && !copyConfirmed) || (dataInSteam && !dataConfirmed)) {
throw new AppError('steam_library_not_confirmed');
}
await Promise.all([requireStockBackupLocation(copyPath), requireUnredirectedData(dataPath)]);
return { version: game.version, requestedCopyPath, copyPath, dataPath, sourcePath, externalStockPath, target, useHardLinks, copyInSteam, dataInSteam };
}
async function resolveExternalStockSource(stockSourcePath: string, expectedVersion: string | null) {
const stockGame = await requireGameFolder(stockSourcePath);
if (stockGame.needsStockSource) throw new AppError('stock_source_invalid');
if (expectedVersion !== null && stockGame.version !== null && expectedVersion !== stockGame.version) {
throw new AppError('stock_source_version_mismatch', { expected: expectedVersion, actual: stockGame.version });
}
return installStockSource(stockGame.resolvedPath, stockGame.version);
dataPath: request.dataPath,
stockBackupPath: stockBackup,
gameVersion: game.version,
unavailablePatches: check.unavailable,
installedAt: new Date().toISOString(),
lastCheckedAt: new Date().toISOString(),
...(sourceFiles ? { sourceFiles } : {}),
};
await writeInstallRecord(record);
return record;
}
async function copyGame(
source: string,
target: string,
initialFreeBytes: number | null,
useHardLinks: boolean,
sourceVersion: string | null,
freeBytes: number | null,
signal: AbortSignal,
report: (progress: InstallProgress) => void,
): Promise<Pick<InstallRecord, 'sourceFiles' | 'hardlinkedFiles'>> {
): Promise<string[]> {
report({ phase: 'measuring', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
const plan = await planCopy(source);
const hardlinks = useHardLinks ? await prepareHardlinks(source, plan, signal, report) : undefined;
const linkTotalBytes = hardlinks ? [...hardlinks.values()].reduce((total, file) => total + Number(file.size), 0) : 0;
const linkTotalFiles = hardlinks ? hardlinks.size : 0;
const copyTotalBytes = Math.max(0, plan.totalBytes - linkTotalBytes);
const neededBytes = copyTotalBytes + SPARE_BYTES;
if (hardlinks && (!await sameVolume(source, target) || (await inspectGameFolder(source)).version !== sourceVersion)) {
throw new AppError('hardlink_file_changed');
}
const available = hardlinks ? await freeBytes(target) : initialFreeBytes;
if (available !== null && available < neededBytes) {
throw new AppError('not_enough_space', { neededGb: gigabytes(neededBytes), freeGb: gigabytes(available) });
if (freeBytes !== null && freeBytes < plan.totalBytes + SPARE_BYTES) {
throw new AppError('not_enough_space', { neededGb: gigabytes(plan.totalBytes + SPARE_BYTES), freeGb: gigabytes(freeBytes) });
}
const targetExisted = await exists(target);
// Track actual disk-copy bytes in doneBytes/totalBytes so hard-linked resource archives
// do not inflate the progress bar or cause sudden jumps when links are created.
const totals = {
totalBytes: copyTotalBytes > 0 ? copyTotalBytes : plan.files.length,
totalFiles: plan.files.length,
copyTotalBytes,
...(hardlinks ? { linkTotalBytes, linkTotalFiles } : {}),
};
const toProgress = (done: { doneFiles: number; copiedBytes: number; linkedBytes: number; linkedFiles: number }): InstallProgress => ({
phase: 'copying',
doneBytes: copyTotalBytes > 0 ? done.copiedBytes : done.doneFiles,
doneFiles: done.doneFiles,
copiedBytes: done.copiedBytes,
...(hardlinks ? { linkedBytes: done.linkedBytes, linkedFiles: done.linkedFiles } : {}),
...totals,
});
report(toProgress({ doneFiles: 0, copiedBytes: 0, linkedBytes: 0, linkedFiles: 0 }));
const totals = { totalBytes: plan.totalBytes, totalFiles: plan.files.length };
report({ phase: 'copying', doneBytes: 0, doneFiles: 0, ...totals });
try {
await copyPlannedFiles(source, target, plan, signal,
(done) => report(toProgress(done)), hardlinks);
if (hardlinks && (await inspectGameFolder(source)).version !== sourceVersion) throw new AppError('hardlink_file_changed');
return {
sourceFiles: plan.files.map((file) => file.relativePath),
...(hardlinks ? { hardlinkedFiles: [...hardlinks.keys()] } : {}),
};
await copyPlannedFiles(source, target, plan, signal, (done) => report({ phase: 'copying', ...done, ...totals }));
return plan.files.map((file) => file.relativePath);
} catch (error) {
await removeInterruptedCopy(target, targetExisted).catch((cleanup) => console.error('[install] removing the interrupted copy failed:', cleanup));
if (signal.aborted) throw new AppError('install_cancelled');
if (error instanceof AppError) throw error;
console.error('[install] copying failed:', error);
throw new AppError('copy_failed');
}
@@ -1,8 +1,7 @@
import { randomUUID } from 'node:crypto';
import { access, realpath } from 'node:fs/promises';
import { realpath } from 'node:fs/promises';
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
import { app } from 'electron';
import { GAME_FILES, isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import { CopiesSchema, type Copies, type InstallRecord } from '@shared/schemas/install.ts';
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
@@ -75,72 +74,11 @@ export function renameCopy(id: string, name: string): Promise<Copies> {
return updateCopyRecord(id, (record) => ({ ...record, name }));
}
export async function copyFolderMissing(copyPath: string): Promise<boolean> {
for (const file of Object.values(GAME_FILES)) {
try {
await access(join(copyPath, file));
} catch {
return true;
}
}
return false;
}
/** Attach live `folderMissing` status to each registered copy without modifying `copies.json`. */
export async function hydrateCopiesStatus(registry: Copies): Promise<Copies> {
const copies = await Promise.all(registry.copies.map(async (copy) => {
const missing = await copyFolderMissing(copy.copyPath);
const { folderMissing: _old, ...base } = copy;
return missing ? { ...base, folderMissing: true } : base;
}));
return { ...registry, copies };
}
export function relocateCopyRecord(
id: string,
next: { readonly copyPath: string; readonly stockBackupPath: string; readonly gameVersion: string | null },
): Promise<Copies> {
return changeRegistry(async (registry) => {
const current = registry.copies.find((copy) => copy.id === id);
if (!current) throw new AppError('copy_not_found');
const resolvedCopy = await canonicalCopyPath(next.copyPath);
const resolvedData = await canonicalCopyPath(current.dataPath);
if (overlaps(resolvedCopy, resolvedData) && copyPathContains(next.stockBackupPath, resolvedData)) {
throw new AppError('copy_location_in_use');
}
for (const existing of registry.copies) {
if (existing.id === id) continue;
const used = await Promise.all([canonicalCopyPath(existing.copyPath), canonicalCopyPath(existing.dataPath)]);
if (used.some((other) => overlaps(resolvedCopy, other))) {
throw new AppError('copy_location_in_use');
}
}
return {
...registry,
copies: registry.copies.map((record) => {
if (record.id !== id) return record;
const { steamLibraryConfirmation: _staleSteam, folderMissing: _staleMissing, ...rest } = record;
return {
...rest,
copyPath: next.copyPath,
stockBackupPath: next.stockBackupPath,
gameVersion: next.gameVersion,
};
}),
};
});
}
/** Serialize writes so switching, renaming and completing an installation preserve each other. */
function changeRegistry(change: (registry: Copies) => Promise<Copies> | Copies): Promise<Copies> {
const operation = pending.then(async () => {
try {
const next = await change(await readRegistry());
const sanitized: Copies = {
...next,
copies: next.copies.map(({ folderMissing: _ignored, ...rest }) => rest),
};
const updated = CopiesSchema.parse(sanitized);
const updated = CopiesSchema.parse(await change(await readRegistry()));
await writeJsonAtomic(recordPath(), updated);
return updated;
} catch (error) {
@@ -168,12 +106,6 @@ export function copyPathContains(parent: string, child: string): boolean {
return !isAbsolute(remainder) && remainder !== '..' && !remainder.startsWith('..' + sep);
}
export function steamLibraryNeedsConfirmation(record: InstallRecord, copyPath: string, dataPath: string): boolean {
if (![record.copyPath, record.dataPath, copyPath, dataPath].some(isInSteamLibrary)) return false;
const confirmed = record.steamLibraryConfirmation;
return !confirmed || relative(confirmed.copyPath, copyPath) !== '' || relative(confirmed.dataPath, dataPath) !== '';
}
function overlaps(left: string, right: string): boolean {
return copyPathContains(left, right) || copyPathContains(right, left);
}
@@ -1,10 +1,7 @@
import { constants } from 'node:fs';
import { access, copyFile, mkdir, readFile } from 'node:fs/promises';
import { dirname, join, relative } from 'node:path';
import { executableVersion, GAME_FILES } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import { changeCopyFiles } from '../copies/change-copy-files.ts';
import { canonicalCopyPath } from './install-record.ts';
import { access, copyFile, mkdir } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { GAME_FILES } from '@wto/patcher';
/**
* The stock files every build starts from, kept inside the game copy: the three data packs and
@@ -18,73 +15,21 @@ export function stockBackupPath(copyFolder: string): string {
return join(copyFolder, STOCK_BACKUP_FOLDER);
}
export async function requireStockBackupLocation(copyFolder: string): Promise<string> {
const backup = stockBackupPath(await canonicalCopyPath(copyFolder));
for (const file of Object.values(GAME_FILES)) {
const path = join(backup, file);
if (relative(path, await canonicalCopyPath(path)) !== '') throw new AppError('launch_location');
}
return backup;
}
/**
* Copies each stock file from the copy into the backup folder, unless the backup already has it:
* a backed-up file is never replaced, because the copy's own file may be a patched one by then.
*/
export async function backUpStockFiles(copyFolder: string): Promise<string> {
return backUpStockFilesFrom(copyFolder, copyFolder);
}
/**
* Copies the four stock files from `sourceFolder` (read-only) into `<copyFolder>/wtoffline/stock`,
* keeping any file that is already backed up.
*/
export async function backUpStockFilesFrom(copyFolder: string, sourceFolder: string): Promise<string> {
const backup = await requireStockBackupLocation(copyFolder);
const backup = stockBackupPath(copyFolder);
for (const file of Object.values(GAME_FILES)) {
const kept = join(backup, file);
if (await exists(kept)) continue;
await mkdir(dirname(kept), { recursive: true });
await copyFile(join(sourceFolder, file), kept, constants.COPYFILE_EXCL);
await copyFile(join(copyFolder, file), kept, constants.COPYFILE_EXCL);
}
return backup;
}
/** A new game version or damaged backup must pass the patch checks before replacing wtoffline/stock. */
export async function installStockSource(copyFolder: string, version: string | null) {
const backup = await requireStockBackupLocation(copyFolder);
const backupExe = join(backup, GAME_FILES.executable);
if (!await exists(backupExe)) return { path: copyFolder, refresh: await exists(backup) };
let backedUpVersion: string | null = null;
try {
backedUpVersion = executableVersion(await readFile(backupExe));
} catch (error) {
console.warn('[stock-backup] unreadable backed-up executable, will refresh:', backupExe, error);
return { path: copyFolder, refresh: true };
}
return backedUpVersion === null || (version !== null && backedUpVersion !== version)
? { path: copyFolder, refresh: true }
: { path: backup, refresh: false };
}
export async function refreshStockBackup(copyFolder: string): Promise<string> {
return refreshStockBackupFrom(copyFolder, copyFolder);
}
/** Replace wtoffline/stock atomically with the four stock files from `sourceFolder`. */
export async function refreshStockBackupFrom(copyFolder: string, sourceFolder: string): Promise<string> {
const backup = await requireStockBackupLocation(copyFolder);
return await changeCopyFiles(copyFolder, async (incoming) => {
const replace = Object.values(GAME_FILES).map((file) => join(STOCK_BACKUP_FOLDER, file));
for (const file of Object.values(GAME_FILES)) {
const target = join(incoming, STOCK_BACKUP_FOLDER, file);
await mkdir(dirname(target), { recursive: true });
await copyFile(join(sourceFolder, file), target);
}
return { replace, remove: [] };
}, async () => backup);
}
async function exists(path: string): Promise<boolean> {
try {
await access(path);
@@ -1,104 +0,0 @@
import { join, normalize } from 'node:path';
import { rawFs } from '../../util/raw-fs.ts';
/**
* Detection of incomplete optional UHQ texture packs (`uhq_vehicles`, `uhq_aircraft`,
* `uhq_environment`, etc.) inside a War Thunder folder.
*
* War Thunder writes `content/pkg_<name>.rq2` when an optional pack is requested and only writes
* `content/pkg_<name>.ver` once its download finishes (`PACKAGE_STATUS_OK`). However, at startup
* `aces.exe` mounts `content.hq/<name>/res/grp_hdr.vromfs.bin` without requiring the `.ver` file,
* registering every `.dxp.bin` listed in the header and crashing later with fatal error 81110007
* (`Can't open TexPack`) if any texture pack is missing.
*/
const UHQ_PACK_PATTERN = /^uhq_[a-z0-9_]+$/i;
const UHQ_RQ2_PATTERN = /^pkg_(uhq_[a-z0-9_]+)\.rq2$/i;
const UHQ_VER_PATTERN = /^pkg_(uhq_[a-z0-9_]+)\.ver$/i;
export interface IncompleteUhqPack {
readonly name: string;
readonly hasHeader: boolean;
}
/**
* Inspects `root` for optional UHQ packs that are incomplete:
* - `content/pkg_<name>.rq2` exists without `content/pkg_<name>.ver` (`PACKAGE_STATUS_REQUESTED`), or
* - `content.hq/<name>/res/grp_hdr.vromfs.bin` exists with no `.dxp.bin` texture packs beside it.
*/
export async function inspectIncompleteUhqPacks(root: string): Promise<IncompleteUhqPack[]> {
const rq2Packs = new Set<string>();
const verPacks = new Set<string>();
const candidates = new Set<string>();
for (const name of await readDirNames(join(root, 'content'))) {
const rq2 = UHQ_RQ2_PATTERN.exec(name);
if (rq2) {
const pack = rq2[1]!.toLowerCase();
rq2Packs.add(pack);
candidates.add(pack);
continue;
}
const ver = UHQ_VER_PATTERN.exec(name);
if (ver) verPacks.add(ver[1]!.toLowerCase());
}
for (const name of await readDirNames(join(root, 'content.hq'))) {
if (UHQ_PACK_PATTERN.test(name)) candidates.add(name.toLowerCase());
}
const incomplete: IncompleteUhqPack[] = [];
for (const pack of [...candidates].sort()) {
const resDir = join(root, 'content.hq', pack, 'res');
const resFiles = await readDirNames(resDir);
const hasHeader = resFiles.some((file) => file.toLowerCase() === 'grp_hdr.vromfs.bin');
const hasDxp = resFiles.some((file) => file.toLowerCase().endsWith('.dxp.bin'));
const requestedWithoutVer = rq2Packs.has(pack) && !verPacks.has(pack);
const emptyHeaderOnly = hasHeader && !hasDxp;
if (requestedWithoutVer || emptyHeaderOnly) {
incomplete.push({ name: pack, hasHeader });
}
}
return incomplete;
}
/** Names of all incomplete optional UHQ packs in `root`. */
export async function findIncompleteUhqPacks(root: string): Promise<string[]> {
return (await inspectIncompleteUhqPacks(root)).map((pack) => pack.name);
}
/**
* Names of incomplete optional UHQ packs in `root` whose `grp_hdr.vromfs.bin` is present,
* which causes `aces.exe` to mount the pack and fail with 81110007 when streaming textures.
*/
export async function findBlockingIncompleteUhqPacks(root: string): Promise<string[]> {
return (await inspectIncompleteUhqPacks(root))
.filter((pack) => pack.hasHeader)
.map((pack) => pack.name);
}
/**
* Whether `relativePath` (relative to the War Thunder root) belongs to any UHQ pack in `packs`:
* `content.hq/<pack>/...`, `patch/content.hq/<pack>/...`, or `content/pkg_<pack>.rq2`.
*/
export function isPathInUhqPacks(relativePath: string, packs: ReadonlySet<string>): boolean {
if (packs.size === 0) return false;
const parts = normalize(relativePath).replace(/\\/g, '/').toLowerCase().split('/').filter(Boolean);
if (parts.length >= 2 && parts[0] === 'content.hq') return packs.has(parts[1]!);
if (parts.length >= 3 && parts[0] === 'patch' && parts[1] === 'content.hq') return packs.has(parts[2]!);
if (parts.length === 2 && parts[0] === 'content') {
const rq2 = UHQ_RQ2_PATTERN.exec(parts[1]!);
return rq2 !== null && packs.has(rq2[1]!);
}
return false;
}
async function readDirNames(folder: string): Promise<string[]> {
try {
const fsPromises = rawFs().promises;
await fsPromises.access(folder);
return await fsPromises.readdir(folder);
} catch {
return [];
}
}
@@ -1,172 +0,0 @@
import { execFile, spawn } from 'node:child_process';
import { constants } from 'node:fs';
import { access, lstat, open, readdir } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { promisify } from 'node:util';
import { GAME_FILES } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import offlineGameArguments from '@shared/offline-game-arguments.json';
import { formatExitCode, type GameExit } from '@shared/schemas/launch.ts';
const execute = promisify(execFile);
const HOOK_DLL_FILENAME = 'wto_ws.dll';
const HOOK_CFG_FILENAME = 'wto_ws.cfg';
const HOOK_LOG_FILENAME = 'wto_ws.log';
const HOOK_LOG_TAIL_BYTES = 8 * 1024;
const HOOK_LOG_TAIL_LINES = 8;
const HOOK_LOG_LINE_LIMIT = 200;
/** Allow small filesystem timestamp skew when matching newly created .game_logs entries. */
const MTIME_SKEW_MS = 2000;
export async function gameProcessRunning(signal: AbortSignal): Promise<boolean> {
if (process.platform !== 'win32') return false;
const games = await execute('tasklist.exe', ['/FI', 'IMAGENAME eq aces.exe', '/FO', 'CSV', '/NH'], { windowsHide: true, signal });
return /^"aces\.exe",/im.test(games.stdout);
}
export async function runGameProcess(
copyPath: string, additionalArguments: readonly string[], signal: AbortSignal, onStart: () => void,
): Promise<GameExit> {
if (await gameProcessRunning(signal)) throw new AppError('launch_game_running');
await verifyLaunchFiles(copyPath);
signal.throwIfAborted();
const executable = join(copyPath, GAME_FILES.executable);
const args = [...offlineGameArguments, ...additionalArguments];
const startedAt = Date.now();
console.info('[game] starting:', executable, args);
const child = spawn(executable, args, {
cwd: copyPath, shell: false, stdio: 'ignore',
});
const stop = (): void => { child.kill(); };
try {
return await new Promise<GameExit>((resolve, reject) => {
child.once('spawn', () => {
console.info('[game] process started, pid:', child.pid ?? 'unknown');
if (signal.aborted) stop();
else onStart();
});
child.once('error', (error) => {
console.error('[game] process error:', error);
reject(new AppError('launch_game_failed'));
});
child.once('close', (code, reason) => {
const logFolder = join(copyPath, '.game_logs');
const elapsedMs = Date.now() - startedAt;
const summary = code !== null ? formatExitCode(code) : (reason ?? 'unknown');
if (code !== 0 && !signal.aborted) {
console.warn('[game] process exited:', summary, `after ${elapsedMs} ms`, logFolder);
void logAbnormalExitContext(copyPath, startedAt)
.catch((error: unknown) => console.warn('[game] inspecting post-exit files failed:', error))
.finally(() => resolve({ code, signal: reason, logFolder }));
return;
}
console.info('[game] process exited:', summary, `after ${elapsedMs} ms`);
resolve({ code, signal: reason, logFolder });
});
signal.addEventListener('abort', stop, { once: true });
});
} finally {
signal.removeEventListener('abort', stop);
}
}
/** Verify the patched executable and hook files are still present and readable right before spawn. */
async function verifyLaunchFiles(copyPath: string): Promise<void> {
const exeFolder = dirname(GAME_FILES.executable);
const required = [
GAME_FILES.executable,
join(exeFolder, HOOK_DLL_FILENAME),
join(exeFolder, HOOK_CFG_FILENAME),
];
const missing: string[] = [];
for (const relativePath of required) {
const fullPath = join(copyPath, relativePath);
try {
const stats = await lstat(fullPath);
if (!stats.isFile() || stats.size === 0) {
missing.push(`${relativePath} (not a non-empty file)`);
continue;
}
await access(fullPath, constants.R_OK);
} catch (error) {
const code = (error as NodeJS.ErrnoException).code ?? 'error';
missing.push(`${relativePath} (${code})`);
}
}
if (missing.length > 0) {
console.error('[game] required launch files unavailable before start:', missing.join(', '));
throw new AppError('launch_game_files_missing');
}
}
/** Record a compact read-only snapshot of hook and game log files after an unexpected non-zero exit. */
async function logAbnormalExitContext(copyPath: string, startedAt: number): Promise<void> {
const exeFolder = join(copyPath, dirname(GAME_FILES.executable));
const [dllState, cfgState, hookLogStat, newGameLogs] = await Promise.all([
describeFile(join(exeFolder, HOOK_DLL_FILENAME)),
describeFile(join(exeFolder, HOOK_CFG_FILENAME)),
safeRegularStat(join(exeFolder, HOOK_LOG_FILENAME)),
listNewGameLogs(join(copyPath, '.game_logs'), startedAt),
]);
const hookLogDesc = hookLogStat
? `${hookLogStat.size} bytes (${hookLogStat.mtimeMs >= startedAt - MTIME_SKEW_MS ? 'updated' : 'stale'})`
: 'missing';
console.warn(
`[game] post-exit check: ${HOOK_DLL_FILENAME}=${dllState}, ${HOOK_CFG_FILENAME}=${cfgState}, ` +
`${HOOK_LOG_FILENAME}=${hookLogDesc}, newGameLogs=${newGameLogs}`,
);
if (hookLogStat && hookLogStat.size > 0) {
const tail = await readTailLines(join(exeFolder, HOOK_LOG_FILENAME), hookLogStat.size);
if (tail.length > 0) {
console.warn(`[game] ${HOOK_LOG_FILENAME} tail:\n ${tail.join('\n ')}`);
}
}
}
async function describeFile(path: string): Promise<string> {
const stats = await safeRegularStat(path);
return stats ? `${stats.size} bytes` : 'missing';
}
async function safeRegularStat(path: string) {
try {
const stats = await lstat(path);
return stats.isFile() ? stats : null;
} catch {
return null;
}
}
async function listNewGameLogs(folder: string, startedAt: number): Promise<string> {
try {
const entries = await readdir(folder, { withFileTypes: true });
const recent: string[] = [];
for (const entry of entries) {
if (!entry.isFile()) continue;
const stats = await safeRegularStat(join(folder, entry.name));
if (!stats || stats.mtimeMs < startedAt - MTIME_SKEW_MS) continue;
recent.push(`${entry.name} (${stats.size} bytes)`);
}
return recent.length > 0 ? recent.slice(0, 6).join(', ') : 'none';
} catch {
return 'unavailable';
}
}
async function readTailLines(path: string, fileSize: number): Promise<string[]> {
const length = Math.min(fileSize, HOOK_LOG_TAIL_BYTES);
const start = fileSize - length;
const handle = await open(path, 'r');
try {
const buffer = Buffer.alloc(length);
const { bytesRead } = await handle.read(buffer, 0, length, start);
const text = buffer.subarray(0, bytesRead).toString('utf8');
const lines = text.split(/\r?\n/).filter((line) => line.length > 0);
return lines.slice(-HOOK_LOG_TAIL_LINES).map((line) => (
line.length > HOOK_LOG_LINE_LIMIT ? `${line.slice(0, HOOK_LOG_LINE_LIMIT)}…` : line
));
} finally {
await handle.close();
}
}
@@ -3,9 +3,8 @@ import { lstat, readFile, realpath, writeFile } from 'node:fs/promises';
import { isAbsolute, join, relative, resolve } from 'node:path';
import { app } from 'electron';
import { z } from 'zod';
import { HEALTH_PATH } from '@wto/server';
import { AppError } from '@shared/errors.ts';
import offlineGameArguments from '@shared/offline-game-arguments.json';
import { localServerReady } from './local-server.ts';
import { forwardProcessOutput } from './process-output.ts';
const Configuration = z.object({
@@ -13,13 +12,13 @@ const Configuration = z.object({
copy: z.string().min(1),
port: z.number().int().min(1).max(65535),
labUser: z.literal('wto-lab'),
gameArguments: z.array(z.string()),
});
const Status = z.object({
state: z.string(),
message: z.string(),
guardExitCode: z.number().nullable().optional(),
});
const Health = z.object({ app: z.literal('wto-server'), pid: z.number() });
export interface Lab {
readonly installPath: string;
@@ -35,10 +34,6 @@ export async function readInstalledLab(): Promise<Lab> {
const installPath = join(programData, 'WTOffline-lab');
try {
const config = Configuration.parse(JSON.parse(await readFile(join(installPath, 'lab.json'), 'utf8')));
if (config.gameArguments.length !== offlineGameArguments.length ||
offlineGameArguments.some((argument, index) => config.gameArguments[index] !== argument)) {
throw new Error('The installed lab launch arguments are out of date.');
}
const root = await realpath(config.lab);
const copyPath = await realpath(resolve(root, config.copy));
const relation = relative(root, copyPath);
@@ -63,6 +58,10 @@ export async function readInstalledLab(): Promise<Lab> {
}
}
export function labStatusUrl(port: number): string {
return `http://127.0.0.1:${port}${HEALTH_PATH}`;
}
async function readStatus(lab: Lab): Promise<z.output<typeof Status> | null> {
try {
return Status.parse(JSON.parse(await readFile(join(lab.controlPath, 'status.json'), 'utf8')));
@@ -71,6 +70,15 @@ async function readStatus(lab: Lab): Promise<z.output<typeof Status> | null> {
}
}
async function isReady(port: number, pid: number): Promise<boolean> {
try {
const response = await fetch(labStatusUrl(port), { signal: AbortSignal.timeout(900) });
return response.ok && Health.parse(await response.json()).pid === pid;
} catch {
return false;
}
}
async function stopGame(lab: Lab): Promise<void> {
await writeFile(join(lab.controlPath, 'stop-request'), '', { flag: 'wx' }).catch((error: NodeJS.ErrnoException) => {
if (error.code !== 'EEXIST') throw error;
@@ -137,7 +145,7 @@ export async function runLab(
return;
}
checking = true;
void localServerReady(lab.port, serverPid).then((ready) => {
void isReady(lab.port, serverPid).then((ready) => {
if (!running || processClosed) return;
failures = ready ? 0 : failures + 1;
if (failures < 3) return;
@@ -1,28 +1,21 @@
import { execFile } from 'node:child_process';
import { readFile } from 'node:fs/promises';
import { createServer } from 'node:net';
import { isAbsolute, join } from 'node:path';
import { app, BrowserWindow, shell } from 'electron';
import { AccountStore, LOOPBACK } from '@wto/server';
import { isAbsolute, join, relative } from 'node:path';
import { promisify } from 'node:util';
import { BrowserWindow, shell } from 'electron';
import { AccountStore } from '@wto/server';
import { executableVersion, GAME_FILES, isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import type { GameExit, LaunchState } from '@shared/schemas/launch.ts';
import type { Settings } from '@shared/schemas/settings.ts';
import type { LaunchState } from '@shared/schemas/launch.ts';
import { getSettings } from '../config/settings-store.ts';
import { decalCachePath } from '../install/decals.ts';
import { canonicalCopyPath, copyPathContains, readInstallRecord } from '../install/install-record.ts';
import { findBlockingIncompleteUhqPacks } from '../install/uhq-packages.ts';
import { resolveEnabledModsForLaunch } from '../mods/mods-service.ts';
import { readInstallRecord } from '../install/install-record.ts';
import { resourcePaths } from '../resources/resource-paths.ts';
import { selectedMapNavPack } from '../map-nav/map-nav-store.ts';
import { saveBackup } from '../saves/save-archive.ts';
import { buildCopy } from './build-copy.ts';
import { gameProcessRunning } from './game-process.ts';
import { readInstalledLab, runLab, type Lab } from './lab-handoff.ts';
import { localServerStatusUrl } from './local-server.ts';
import { ordinaryLaunchPaths, runOrdinaryLaunch } from './ordinary-launch.ts';
import { labStatusUrl, readInstalledLab, runLab } from './lab-handoff.ts';
export { gameProcessRunning } from './game-process.ts';
const execute = promisify(execFile);
interface LaunchJob {
readonly stop: AbortController;
@@ -38,31 +31,30 @@ export function launchInProgress(): boolean {
return active !== null;
}
export async function gameProcessRunning(signal: AbortSignal): Promise<boolean> {
if (process.platform !== 'win32') return false;
const games = await execute('tasklist.exe', ['/FI', 'IMAGENAME eq aces.exe', '/FO', 'CSV', '/NH'], { windowsHide: true, signal });
return /^"aces\.exe",/im.test(games.stdout);
}
export function getLaunchState(): LaunchState {
return state;
}
export function startLaunch(report: LaunchJob['report']): LaunchState {
const previous = active;
if (previous && state.phase !== 'server-running') throw new AppError('launch_busy');
if (active) throw new AppError('launch_busy');
const job: LaunchJob = { stop: new AbortController(), report, done: Promise.resolve() };
active = job;
previous?.stop.abort();
update(job, { phase: 'checking' });
job.done = (async () => {
// A new build may only write after the server from the previous session has stopped.
await previous?.done;
job.stop.signal.throwIfAborted();
await launch(job);
})().catch((error: unknown) => {
job.done = launch(job).catch((error: unknown) => {
const port = state.port;
const context = port === undefined ? {} : { port };
if (job.stop.signal.aborted) {
update(job, { phase: 'ready' });
return;
}
const { port } = state;
const context = port === undefined ? {} : { port };
console.error('[launch] launch failed:', error);
const code = error instanceof AppError ? error.code : 'launch_failed';
const code = error instanceof AppError ? error.code : 'launch_lab_failed';
switch (code) {
case 'launch_port_busy':
update(job, { phase: 'port-busy', ...context });
@@ -70,16 +62,12 @@ export function startLaunch(report: LaunchJob['report']): LaunchState {
case 'launch_server_exited':
update(job, { phase: 'server-exited', ...context });
break;
default: {
const errorParams = error instanceof AppError && Object.keys(error.params).length > 0
? { errorParams: { ...error.params } }
: {};
update(job, { phase: 'failed', error: code, ...errorParams, ...context });
default:
update(job, { phase: 'failed', error: code, ...context });
break;
}
}
}).finally(() => {
if (active === job) active = null;
active = null;
});
return state;
}
@@ -95,125 +83,48 @@ export function stopLaunch(): Promise<void> | null {
}
export async function openServerStatus(): Promise<void> {
if ((state.phase !== 'running' && state.phase !== 'server-running') || state.port === undefined) {
throw new AppError('launch_server_exited');
}
await shell.openExternal(localServerStatusUrl(state.port));
if (state.phase !== 'running' || state.port === undefined) throw new AppError('launch_server_exited');
await shell.openExternal(labStatusUrl(state.port));
}
function update(job: LaunchJob, next: LaunchState): void {
if (active !== job) return;
state = job.copyId ? { ...next, copyId: job.copyId } : next;
job.report(state);
}
async function launch(job: LaunchJob): Promise<void> {
if (process.platform !== 'win32') throw new AppError('launch_platform_unsupported');
const signal = job.stop.signal;
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
if (!record) throw new AppError('launch_no_copy');
job.copyId = record.id;
const plan = await planLaunch(job, record, settings);
if (plan === null) return;
const { lab, copyPath, stockPath, dataPath, port, modsDir, enabledModIds } = plan;
await buildForLaunch(job, record, plan, settings);
const publish = (phase: LaunchState['phase'], gameExit?: GameExit): void => {
if (signal.aborted) return;
update(job, { phase, port, gameExit });
if (phase === 'running' && settings.afterGameStarts === 'minimize') {
for (const window of BrowserWindow.getAllWindows()) window.minimize();
}
};
if (lab) {
await runLab(lab, stockPath, dataPath, signal, publish);
update(job, { phase: 'ready' });
return;
}
const gameExit = await runOrdinaryLaunch(
copyPath,
dataPath,
port,
settings,
signal,
publish,
{ modsDir, enabledModIds },
);
update(job, { phase: 'game-exited', gameExit });
}
interface LaunchPlan {
readonly lab: Lab | null;
readonly copyPath: string;
readonly stockPath: string;
readonly dataPath: string;
readonly steamLibraryConfirmed: boolean;
readonly port: number;
readonly modsDir: string;
readonly enabledModIds: readonly string[];
}
async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Settings): Promise<LaunchPlan | null> {
const signal = job.stop.signal;
const useLab = !app.isPackaged && settings.developerMode;
if (useLab && (isInSteamLibrary(record.copyPath) || isInSteamLibrary(await canonicalCopyPath(record.copyPath)))) {
throw new AppError('launch_copy_in_steam');
}
if (!settings.developerMode) throw new AppError('launch_lab_required');
if (isInSteamLibrary(record.copyPath)) throw new AppError('launch_copy_in_steam');
const currentVersion = await readVersion(record.copyPath, signal);
if (!currentVersion || currentVersion !== record.gameVersion) {
console.warn(
`[launch] client version changed: recorded=${record.gameVersion ?? 'unknown'}, ` +
`actual=${currentVersion ?? 'missing'} (${record.copyPath})`,
);
update(job, { phase: 'version-changed', actualVersion: currentVersion });
return null;
return;
}
const lab = useLab ? await readInstalledLab() : null;
const { copyPath, stockPath, dataPath, steamLibraryConfirmed } = lab ? {
copyPath: lab.copyPath,
stockPath: settings.labStockPath ?? record.stockBackupPath,
dataPath: settings.labDataPath ?? record.dataPath,
steamLibraryConfirmed: false,
} : await ordinaryLaunchPaths(record);
const lab = await readInstalledLab();
const stockPath = settings.labStockPath ?? record.stockBackupPath;
const dataPath = settings.labDataPath ?? record.dataPath;
if (!isAbsolute(stockPath) || !isAbsolute(dataPath)) {
throw new AppError('folder_unreadable', { path: !isAbsolute(stockPath) ? stockPath : dataPath });
}
if (lab && (isInSteamLibrary(copyPath) || isInSteamLibrary(dataPath) || isInSteamLibrary(await canonicalCopyPath(dataPath)))) {
const relativeData = relative(stockPath, dataPath);
if (isInSteamLibrary(dataPath) || (!isAbsolute(relativeData) && !relativeData.startsWith('..'))) {
throw new AppError('launch_copy_in_steam');
}
if (copyPathContains(stockPath, dataPath)) throw new AppError('launch_location');
const requestedPort = lab?.port ?? (settings.launchPortMode === 'fixed' ? settings.launchPort : 0);
if (requestedPort) update(job, { phase: 'checking', port: requestedPort });
const [copyVersion, stockVersion, games] = await Promise.all([
lab ? readVersion(copyPath, signal) : currentVersion,
update(job, { phase: 'checking', port: lab.port });
const [labVersion, stockVersion, games] = await Promise.all([
readVersion(lab.copyPath, signal),
readVersion(stockPath, signal),
gameProcessRunning(signal),
]);
signal.throwIfAborted();
if (!copyVersion || copyVersion !== stockVersion) {
console.warn(
`[launch] copy/stock version mismatch: copy=${copyVersion ?? 'missing'} (${copyPath}), ` +
`stock=${stockVersion ?? 'missing'} (${stockPath})`,
);
if (!lab && !stockVersion) throw new AppError('launch_stock_missing');
throw new AppError(lab ? 'launch_lab_version' : 'launch_stock_version');
}
if (!labVersion || labVersion !== stockVersion) throw new AppError('launch_lab_version');
if (games) throw new AppError('launch_game_running');
const incompleteUhq = await findBlockingIncompleteUhqPacks(copyPath);
if (incompleteUhq.length > 0) {
console.warn(`[launch] incomplete optional UHQ pack(s) detected in ${copyPath}: ${incompleteUhq.join(', ')}`);
throw new AppError('launch_incomplete_uhq_packs', { packs: incompleteUhq.join(', ') });
}
const { modsDir, enabledMods } = await resolveEnabledModsForLaunch(dataPath, copyVersion);
const enabledModIds = enabledMods.map((mod) => mod.manifest.id);
const port = await selectPort(requestedPort);
return { lab, copyPath, stockPath, dataPath, steamLibraryConfirmed, port, modsDir, enabledModIds };
}
async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: LaunchPlan, settings: Settings): Promise<void> {
const signal = job.stop.signal;
const { lab, copyPath, stockPath, dataPath, port, steamLibraryConfirmed, modsDir, enabledModIds } = plan;
await checkPort(lab.port);
if (settings.autoSaveBackups) {
for (const { userId } of new AccountStore(dataPath).all()) {
signal.throwIfAborted();
@@ -221,31 +132,28 @@ async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: Launc
}
}
signal.throwIfAborted();
update(job, { phase: 'building', port });
const buildStart = Date.now();
const mapNavFolder = selectedMapNavPack(dataPath)?.folder;
let writtenFiles = 0;
update(job, { phase: 'building', port: lab.port });
await buildCopy({
kind: 'build',
stockPath,
copyPath,
copyPath: lab.copyPath,
dataPath,
port,
steamLibraryConfirmed,
port: lab.port,
...resourcePaths(),
...(mapNavFolder === undefined ? {} : { mapNavFolder }),
...(record.decalCacheId ? { decalCache: decalCachePath(lab ? record.dataPath : dataPath, record.decalCacheId) } : {}),
hookLogging: settings.loggingEnabled,
acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId),
modsDir,
enabledModIds,
}, signal, (filesWritten, filesTotal, file) => {
writtenFiles = filesWritten;
if (!signal.aborted) update(job, {
phase: 'building', port, filesWritten, filesTotal, ...(file === undefined ? {} : { file }),
phase: 'building', port: lab.port, filesWritten, filesTotal, ...(file === undefined ? {} : { file }),
});
});
console.info(`[launch] prepared ${writtenFiles} game files for port ${port} in ${Date.now() - buildStart} ms`);
await runLab(lab, stockPath, dataPath, signal, (phase) => {
if (!signal.aborted) update(job, { phase, port: lab.port });
if (phase === 'running' && !signal.aborted && settings.afterGameStarts === 'minimize') {
for (const window of BrowserWindow.getAllWindows()) window.minimize();
}
});
update(job, { phase: 'ready' });
}
async function readVersion(folder: string, signal: AbortSignal): Promise<string | null> {
@@ -258,19 +166,12 @@ async function readVersion(folder: string, signal: AbortSignal): Promise<string
}
}
async function selectPort(port: number): Promise<number> {
return new Promise((resolve, reject) => {
async function checkPort(port: number): Promise<void> {
await new Promise<void>((resolve, reject) => {
const listener = createServer();
listener.once('error', (error: NodeJS.ErrnoException) => reject(
error.code === 'EADDRINUSE' ? new AppError('launch_port_busy') : error,
));
listener.listen(port, LOOPBACK, () => {
const address = listener.address();
listener.close((error) => {
if (error) reject(error);
else if (address && typeof address === 'object') resolve(address.port);
else reject(new AppError('launch_server_failed'));
});
});
listener.listen(port, '127.0.0.1', () => listener.close((error) => error ? reject(error) : resolve()));
});
}
@@ -1,105 +0,0 @@
import { once } from 'node:events';
import { join } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { utilityProcess } from 'electron';
import { z } from 'zod';
import { HEALTH_PATH, LOOPBACK, type ServerOptions } from '@wto/server';
import { AppError } from '@shared/errors.ts';
import type { ServerWorkerStatus } from '../../workers/server-worker.ts';
import { forwardProcessOutput } from './process-output.ts';
const Health = z.object({ app: z.literal('wto-server'), pid: z.number() });
interface LocalServer {
readonly exited: Promise<number>;
close(): Promise<void>;
}
export function localServerStatusUrl(port: number): string {
return `http://${LOOPBACK}:${port}${HEALTH_PATH}`;
}
export async function localServerReady(port: number, pid?: number, signal?: AbortSignal): Promise<boolean> {
const deadline = AbortSignal.timeout(900);
try {
const response = await fetch(localServerStatusUrl(port), {
redirect: 'error', signal: signal ? AbortSignal.any([signal, deadline]) : deadline,
});
if (!response.ok) return false;
const health = Health.parse(await response.json());
return pid === undefined || health.pid === pid;
} catch {
return false;
}
}
export interface StartLocalServerOptions extends Omit<ServerOptions, 'report' | 'mods'> {
readonly modsDir?: string;
readonly enabledModIds?: readonly string[];
}
export async function startLocalServer(
{ gameFolder, dataFolder, port, loggingEnabled = true, modsDir, enabledModIds }: StartLocalServerOptions, signal: AbortSignal,
): Promise<LocalServer> {
signal.throwIfAborted();
const workerArgs = [gameFolder, dataFolder, String(port), loggingEnabled ? '1' : '0'];
if (modsDir && enabledModIds && enabledModIds.length > 0) {
workerArgs.push(modsDir, JSON.stringify(enabledModIds));
}
const worker = utilityProcess.fork(
join(import.meta.dirname, 'server-worker.js'),
workerArgs,
{
serviceName: 'WTOffline local server',
stdio: 'pipe',
},
);
forwardProcessOutput(worker.stdout, 'server', 'info');
forwardProcessOutput(worker.stderr, 'server', 'error');
let ended = false;
const exited = new Promise<number>((resolve) => worker.once('exit', (code) => {
ended = true;
resolve(code);
}));
worker.on('error', (type, location) => console.error('[server] utility process error:', type, location));
const stop = async (graceful: boolean): Promise<void> => {
if (!ended && graceful) {
worker.postMessage('close');
await Promise.race([exited, delay(3000, undefined, { ref: false })]);
}
if (!ended && !worker.kill() && worker.pid === undefined) {
worker.once('spawn', () => worker.kill());
}
await exited;
};
const startup = AbortSignal.any([signal, AbortSignal.timeout(60_000)]);
let listening = false;
try {
const reply: ServerWorkerStatus = await Promise.race([
once(worker, 'message', { signal: startup }).then(([status]) => status as ServerWorkerStatus),
exited.then(() => 'failed' as const),
]);
if (reply === 'port-busy') throw new AppError('launch_port_busy');
const pid = worker.pid;
if (reply !== 'listening' || pid === undefined) throw new AppError('launch_server_failed');
listening = true;
while (!ended) {
startup.throwIfAborted();
if (await localServerReady(port, pid, startup)) {
startup.throwIfAborted();
if (!ended) return { exited, close: () => stop(true) };
break;
}
await delay(150, undefined, { signal: startup });
}
throw new AppError('launch_server_failed');
} catch (error) {
await stop(listening);
signal.throwIfAborted();
console.error('[server] startup failed:', error);
throw error instanceof AppError ? error : new AppError('launch_server_failed');
}
}
@@ -1,80 +0,0 @@
import { once } from 'node:events';
import { isAbsolute, join, relative } from 'node:path';
import { GAME_FILES, isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import { parseLaunchArguments } from '@shared/launch-arguments.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import type { GameExit } from '@shared/schemas/launch.ts';
import type { Settings } from '@shared/schemas/settings.ts';
import { requireUnredirectedData } from '../install/data-location.ts';
import { PLAYER_DATA_FOLDERS } from '../install/copy-game.ts';
import { canonicalCopyPath, copyPathContains, steamLibraryNeedsConfirmation } from '../install/install-record.ts';
import { requireStockBackupLocation, stockBackupPath } from '../install/stock-backup.ts';
import { runGameProcess } from './game-process.ts';
import { startLocalServer } from './local-server.ts';
export async function ordinaryLaunchPaths(record: InstallRecord) {
const paths = [record.copyPath, record.stockBackupPath, record.dataPath] as const;
if (paths.some((path) => !isAbsolute(path))) throw new AppError('launch_location');
const [copyPath, stockPath, dataPath] = await Promise.all([
canonicalCopyPath(record.copyPath), canonicalCopyPath(record.stockBackupPath), canonicalCopyPath(record.dataPath),
]);
const source = record.sourcePath === null ? null : await canonicalCopyPath(record.sourcePath);
if (relative(stockBackupPath(copyPath), stockPath) !== '' ||
copyPathContains(stockPath, dataPath) ||
(source !== null && [copyPath, dataPath].some((path) => copyPathContains(source, path)))) {
throw new AppError('launch_location');
}
await Promise.all([requireUnredirectedGamePaths(copyPath), requireStockBackupLocation(copyPath), requireUnredirectedData(dataPath)]);
if (steamLibraryNeedsConfirmation(record, copyPath, dataPath)) throw new AppError('launch_steam_confirmation_required');
return { copyPath, stockPath, dataPath, steamLibraryConfirmed: isInSteamLibrary(record.copyPath) || isInSteamLibrary(copyPath) };
}
/** The game and build write to these copy-relative locations. */
async function requireUnredirectedGamePaths(copyPath: string): Promise<void> {
const paths = ['config.blk', join('cache', 'content'), ...PLAYER_DATA_FOLDERS, ...Object.values(GAME_FILES)];
const checks = await Promise.all(paths.map(async (name) => {
const intended = join(copyPath, name);
return relative(intended, await canonicalCopyPath(intended)) === '';
}));
if (checks.includes(false)) throw new AppError('launch_location');
}
type OrdinaryPhase = 'starting-server' | 'starting-game' | 'running' | 'server-running';
export async function runOrdinaryLaunch(
copyPath: string, dataPath: string, port: number, settings: Settings, signal: AbortSignal,
publish: (phase: OrdinaryPhase, gameExit?: GameExit) => void,
mods?: { readonly modsDir: string; readonly enabledModIds: readonly string[] },
): Promise<GameExit> {
const args = parseLaunchArguments(settings.launchArguments);
if (!args) throw new AppError('launch_game_failed');
publish('starting-server');
const server = await startLocalServer(
{
gameFolder: copyPath,
dataFolder: dataPath,
port,
loggingEnabled: settings.loggingEnabled,
...(mods && mods.enabledModIds.length > 0 ? { modsDir: mods.modsDir, enabledModIds: mods.enabledModIds } : {}),
},
signal,
);
const stop = new AbortController();
const runSignal = AbortSignal.any([signal, stop.signal]);
const serverExited = server.exited.then(() => { throw new AppError('launch_server_exited'); });
publish('starting-game');
const game = runGameProcess(copyPath, args, runSignal, () => publish('running'));
try {
const gameExit = await Promise.race([game, serverExited]);
if (!runSignal.aborted && !settings.closeServerOnGameExit) {
publish('server-running', gameExit);
if (!runSignal.aborted) await Promise.race([once(runSignal, 'abort'), serverExited]);
}
return gameExit;
} finally {
stop.abort();
await game.catch(() => undefined);
await server.close();
}
}
@@ -1,7 +1,6 @@
import { join } from 'node:path';
import { app, BrowserWindow, Menu, nativeImage, shell, Tray } from 'electron';
import { app, BrowserWindow, Menu, shell, Tray } from 'electron';
import { getSettings } from './config/settings-store.ts';
import { bundledResourcePaths } from './resources/resource-paths.ts';
/**
* The launcher's single window: a fixed size without the system frame, like the game's own
@@ -26,9 +25,7 @@ export function beginWindowQuit(): void {
async function hideToTray(window: BrowserWindow): Promise<void> {
if (!tray) {
const customIcon = nativeImage.createFromPath(bundledResourcePaths().appIcon);
const icon = customIcon.isEmpty() ? await app.getFileIcon(process.execPath, { size: 'small' }) : customIcon;
tray = new Tray(icon);
tray = new Tray(await app.getFileIcon(process.execPath, { size: 'small' }));
tray.setToolTip(app.getName());
tray.setContextMenu(Menu.buildFromTemplate([{ role: 'quit' }]));
tray.on('click', () => showMainWindow());
@@ -37,7 +34,6 @@ async function hideToTray(window: BrowserWindow): Promise<void> {
}
export function createMainWindow(): BrowserWindow {
const appIcon = nativeImage.createFromPath(bundledResourcePaths().appIcon);
const window = new BrowserWindow({
width: CONTENT_WIDTH,
height: CONTENT_HEIGHT,
@@ -48,7 +44,6 @@ export function createMainWindow(): BrowserWindow {
frame: false,
backgroundColor: BACKGROUND,
show: false,
...(!appIcon.isEmpty() ? { icon: appIcon } : {}),
webPreferences: {
preload: join(import.meta.dirname, '../preload/index.cjs'),
sandbox: true,
@@ -1,65 +0,0 @@
import { execFile } from 'node:child_process';
import { readFile, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { promisify } from 'node:util';
import { PatchPackError } from '@wto/patcher';
import { MapNavManifestSchema, type MapNavManifest } from '@shared/schemas/map-nav-pack.ts';
import { installerDigest } from '../app-update/installer-integrity.ts';
import { RELEASE_MANIFEST_MAX_BYTES } from '../patch-pack/release-assets.ts';
const execute = promisify(execFile);
/** Compare the exact maps written by the installer with the signed release manifest. */
export async function verifyMapNavFolder(folder: string, manifest: MapNavManifest): Promise<void> {
const stored = MapNavManifestSchema.parse(JSON.parse(await readFile(join(folder, 'manifest.json'), 'utf8')));
if (JSON.stringify(stored) !== JSON.stringify(MapNavManifestSchema.parse(manifest))) {
throw new PatchPackError('contents', 'The map pack manifest does not match the signed release.');
}
for (const entry of manifest.maps) {
const digest = await installerDigest(join(folder, 'maps', entry.level + '.wtonav'), entry.size);
if (digest.size !== entry.size || digest.sha256 !== entry.sha256) {
throw new PatchPackError('contents', 'The map file does not match the signed release: ' + entry.level);
}
}
}
/** The ZIP is already verified. Extract only the exact file names and sizes the manifest promises. */
export async function extractMapNavArchive(zip: string, staging: string, manifest: MapNavManifest): Promise<string> {
const folder = join(staging, 'map-nav');
const index = join(staging, 'expected-maps.json');
const script = join(staging, 'extract-maps.ps1');
const expected = manifest.maps.map(({ level, size }) => ({ name: 'map-nav/maps/' + level + '.wtonav', size }));
await writeFile(index, JSON.stringify(expected));
await writeFile(script, '\uFEFF' + EXTRACTION_SCRIPT.join('\r\n'), 'utf8');
await execute('powershell.exe', [
'-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', script,
zip, staging, index, String(RELEASE_MANIFEST_MAX_BYTES),
], { windowsHide: true, timeout: 180_000 });
await verifyMapNavFolder(folder, manifest);
return folder;
}
const EXTRACTION_SCRIPT = [
'param([string]$ZipPath, [string]$Root, [string]$IndexPath, [long]$ManifestLimit)',
"$ErrorActionPreference = 'Stop'",
'Add-Type -AssemblyName System.IO.Compression.FileSystem',
'$expected = [System.Collections.Generic.Dictionary[string,long]]::new([StringComparer]::Ordinal)',
'foreach ($item in (Get-Content -LiteralPath $IndexPath -Raw -Encoding UTF8 | ConvertFrom-Json)) { $expected.Add($item.name, $item.size) }',
'$seenManifest = $false',
'$zip = [System.IO.Compression.ZipFile]::OpenRead($ZipPath)',
'try {',
' [System.IO.Directory]::CreateDirectory((Join-Path $Root "map-nav/maps")) | Out-Null',
' foreach ($entry in $zip.Entries) {',
' $name = $entry.FullName',
' if ($entry.Length -eq 0 -and ($name -ceq "map-nav/" -or $name -ceq "map-nav/maps/")) { continue }',
' if (!$seenManifest -and $name -ceq "map-nav/manifest.json" -and $entry.Length -le $ManifestLimit) {',
' $seenManifest = $true',
' } else {',
' if (!$expected.ContainsKey($name) -or $entry.Length -ne $expected[$name]) { throw "Unexpected map pack entry: $name" }',
' [void]$expected.Remove($name)',
' }',
' [System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, (Join-Path $Root $name), $false)',
' }',
' if (!$seenManifest -or $expected.Count -gt 0) { throw "The map pack is incomplete." }',
'} finally { $zip.Dispose() }',
];
@@ -1,89 +0,0 @@
import { readFileSync, readdirSync } from 'node:fs';
import { mkdir, rename, rm } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { app } from 'electron';
import { compareAppVersions } from '@wto/patcher';
import {
MAP_NAV_FORMAT, MapNavManifestSchema, MapNavVersionSchema, type ActiveMapNav, type MapNavManifest,
} from '@shared/schemas/map-nav-pack.ts';
import { writeJsonAtomic } from '../../util/atomic-json.ts';
import { bundledResourcePaths } from '../resources/resource-paths.ts';
interface MapNavPack {
readonly folder: string;
readonly info: NonNullable<ActiveMapNav>;
}
export function mapNavStoreFolder(): string {
return join(app.getPath('userData'), 'map-nav');
}
function activeFile(): string {
return join(mapNavStoreFolder(), 'active.json');
}
export function needsMapNavLauncherUpdate(manifest: MapNavManifest): boolean {
return manifest.format !== MAP_NAV_FORMAT || compareAppVersions(app.getVersion(), manifest.minAppVersion) < 0;
}
function readManifest(folder: string): MapNavManifest | null {
try {
return MapNavManifestSchema.parse(JSON.parse(readFileSync(join(dirname(folder), 'manifest.json'), 'utf8')));
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') console.warn('[map-nav] could not read the pack manifest:', error);
return null;
}
}
function foundPack(folder: string, source: NonNullable<ActiveMapNav>['source']): MapNavPack | null {
let maps: string[];
try {
maps = readdirSync(folder, { withFileTypes: true })
.filter((file) => (file.isFile() || file.isSymbolicLink()) && file.name.endsWith('.wtonav'))
.map((file) => file.name);
} catch (error) {
if (!['ENOENT', 'ENOTDIR'].includes((error as NodeJS.ErrnoException).code ?? '')) {
console.warn('[map-nav] could not read the maps folder:', error);
}
return null;
}
if (maps.length === 0) return null;
const manifest = readManifest(folder);
if (manifest && needsMapNavLauncherUpdate(manifest)) return null;
return {
folder,
info: { source, version: manifest?.version ?? null, gameVersions: manifest?.gameVersions ?? [], mapCount: maps.length },
};
}
function downloadedPack(): MapNavPack | null {
try {
const active = JSON.parse(readFileSync(activeFile(), 'utf8')) as { version?: unknown };
const version = MapNavVersionSchema.parse(active.version);
const pack = foundPack(join(mapNavStoreFolder(), version, 'maps'), 'downloaded');
return pack?.info.version === version ? pack : null;
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') console.warn('[map-nav] the active pack is unusable:', error);
return null;
}
}
export function selectedMapNavPack(dataPath: string | null): MapNavPack | null {
return downloadedPack() ??
(dataPath ? foundPack(join(dataPath, 'map-nav', 'maps'), 'local') : null) ??
foundPack(bundledResourcePaths().bundledMapNavFolder, 'bundled');
}
/** Commit a verified map directory, then switch the pointer used by new launches. */
export async function activateMapNavPack(version: string, stagedFolder?: string): Promise<void> {
const store = mapNavStoreFolder();
if (stagedFolder !== undefined) {
await mkdir(store, { recursive: true });
await rename(stagedFolder, join(store, version));
}
await writeJsonAtomic(activeFile(), { version });
}
export async function deactivateMapNavPack(): Promise<void> {
await rm(activeFile(), { force: true });
}
@@ -1,145 +0,0 @@
import { lstat, mkdir, mkdtemp, realpath, rm } from 'node:fs/promises';
import { join } from 'node:path';
import { app } from 'electron';
import {
comparePackVersions, packSigningPublicKey, PatchPackError, patchPackTuning, verifyEd25519,
} from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { AppUpdateProgress } from '@shared/schemas/app-update.ts';
import {
MapNavReleaseManifestSchema, mapNavSignaturePayload, type ActiveMapNav, type MapNavApplyResult,
type MapNavCheck, type MapNavReleaseManifest,
} from '@shared/schemas/map-nav-pack.ts';
import { getSettings } from '../config/settings-store.ts';
import { readInstallRecord } from '../install/install-record.ts';
import { packUpdateProblem } from '../patch-pack/pack-update.ts';
import {
readReleaseAsset, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES, stageReleaseAsset,
} from '../patch-pack/release-assets.ts';
import {
newestProjectRelease, projectReleaseVersion, withReleaseSources, type PackReleaseFiles,
} from '../patch-pack/release-feed.ts';
import { extractMapNavArchive, verifyMapNavFolder } from './map-nav-archive.ts';
import {
activateMapNavPack, deactivateMapNavPack, mapNavStoreFolder, needsMapNavLauncherUpdate, selectedMapNavPack,
} from './map-nav-store.ts';
let updating = false;
async function duringMapNavUpdate<T>(update: () => Promise<T>): Promise<T> {
if (updating) throw new AppError('map_nav_update_busy');
updating = true;
try {
return await update();
} finally {
updating = false;
}
}
export async function activeMapNav(): Promise<ActiveMapNav> {
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
const useLab = !app.isPackaged && settings.developerMode;
const dataPath = (useLab ? settings.labDataPath : null) ?? record?.dataPath ?? null;
return selectedMapNavPack(dataPath)?.info ?? null;
}
function isNewer(version: string, active: ActiveMapNav): boolean {
return !active?.version || comparePackVersions(version, active.version) > 0;
}
async function signedManifest(files: PackReleaseFiles, key: string): Promise<MapNavReleaseManifest> {
const signal = AbortSignal.timeout(patchPackTuning().requestTimeoutMs);
const [bytes, signature] = await Promise.all([
readReleaseAsset(files.manifestUrl, RELEASE_MANIFEST_MAX_BYTES, signal, files.source),
readReleaseAsset(files.signatureUrl, RELEASE_SIGNATURE_MAX_BYTES, signal, files.source),
]);
const decoder = new TextDecoder('utf-8', { fatal: true });
if (!verifyEd25519(mapNavSignaturePayload(bytes), decoder.decode(signature), key)) {
throw new PatchPackError('signature', 'The map pack manifest signature does not match.');
}
const manifest = MapNavReleaseManifestSchema.parse(JSON.parse(decoder.decode(bytes)));
if (manifest.version !== files.version) throw new PatchPackError('contents', 'The signed map pack version does not match the release.');
return manifest;
}
export async function checkMapNavUpdate(): Promise<MapNavCheck> {
const active = await activeMapNav();
const key = packSigningPublicKey();
if (!key) return { status: 'failed', active, latest: null, problem: 'no_signing_key' };
try {
const offer = await withReleaseSources(async (source) => {
const files = await newestProjectRelease('mapNav', active?.version ?? null, source);
return files ? { files, manifest: await signedManifest(files, key) } : null;
});
if (!offer) return { status: 'up_to_date', active, latest: null, problem: null };
const { files, manifest } = offer;
const latest = {
version: manifest.version, gameVersions: manifest.gameVersions, minAppVersion: manifest.minAppVersion,
publishedAt: files.publishedAt, mapCount: manifest.maps.length, size: manifest.archive.size,
};
const status = !isNewer(manifest.version, active) ? 'up_to_date'
: needsMapNavLauncherUpdate(manifest) ? 'needs_app_update' : 'available';
return { status, active, latest, problem: null };
} catch (error) {
console.warn('[map-nav] update check failed:', error);
return { status: 'failed', active, latest: null, problem: packUpdateProblem(error) };
}
}
async function installMapNav(
files: PackReleaseFiles, manifest: MapNavReleaseManifest, report: (progress: AppUpdateProgress) => void,
): Promise<void> {
const root = mapNavStoreFolder();
const installed = join(root, manifest.version);
const existing = await lstat(installed).catch((error: NodeJS.ErrnoException) => {
if (error.code !== 'ENOENT') throw error;
return null;
});
if (existing) {
if (!existing.isDirectory()) throw new PatchPackError('contents', 'The destination for this map pack is not a directory.');
await verifyMapNavFolder(installed, manifest);
await activateMapNavPack(manifest.version);
return;
}
await mkdir(root, { recursive: true });
const staging = await mkdtemp(join(await realpath(root), '.map-nav-install-'));
try {
const zip = join(staging, 'maps.zip');
await stageReleaseAsset(files.zipUrl, files.source, manifest.archive, zip, report);
const folder = await extractMapNavArchive(zip, staging, manifest);
await activateMapNavPack(manifest.version, folder);
} finally {
await rm(staging, { recursive: true, force: true }).catch((error: unknown) =>
console.warn('[map-nav] could not remove the installation staging directory:', error));
}
}
export function applyMapNavUpdate(version: string, report: (progress: AppUpdateProgress) => void): Promise<MapNavApplyResult> {
return duringMapNavUpdate(async () => {
const key = packSigningPublicKey();
if (!key) return { ok: false, problem: 'no_signing_key' };
if (!isNewer(version, await activeMapNav())) return { ok: false, problem: 'up_to_date' };
try {
const installed = await withReleaseSources(async (source) => {
const files = await projectReleaseVersion('mapNav', version, source);
const manifest = await signedManifest(files, key);
if (needsMapNavLauncherUpdate(manifest)) return false;
await installMapNav(files, manifest, report);
return true;
});
if (!installed) return { ok: false, problem: 'needs_app_update' };
return { ok: true, active: await activeMapNav() };
} catch (error) {
console.warn('[map-nav] update failed:', error);
return { ok: false, problem: packUpdateProblem(error) };
}
});
}
export function useLocalMapNav(): Promise<ActiveMapNav> {
return duringMapNavUpdate(async () => {
await deactivateMapNavPack();
return activeMapNav();
});
}
@@ -1,436 +0,0 @@
import { randomUUID } from 'node:crypto';
import { access, cp, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';
import { isAbsolute, join } from 'node:path';
import { app, BrowserWindow, dialog, shell } from 'electron';
import {
computeAutoSortOrder,
discoverMods,
emptyClientModsConfig,
MOD_API_VERSION,
normalizeClientModsConfig,
resolveModLoadOrder,
type ClientModsConfig,
type DiscoveredMod,
type ModPreset,
} from '@wto/mods';
import { AppError } from '@shared/errors.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import { ModPresetTransferSchema, type ModListItem, type ModsStateView } from '@shared/schemas/mods.ts';
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
import { rememberDialogPath, resolveDialogDefaultPath } from '../../util/dialog-paths.ts';
import { getSettings, updateSettings } from '../config/settings-store.ts';
import { listCopies } from '../install/install-record.ts';
import { resourcePaths } from '../resources/resource-paths.ts';
const CLIENT_MODS_CONFIG_FILE = 'mods-config.json';
const EXAMPLES_SEEDED_MARKER = '.wto-examples-seeded';
const inFlightSeeds = new Map<string, Promise<void>>();
export function defaultModsFolder(): string {
return join(app.getPath('userData'), 'mods');
}
export async function resolveModsFolder(): Promise<{ readonly modsDir: string; readonly defaultModsDir: string; readonly isCustomModsDir: boolean }> {
const settings = await getSettings();
const defaultModsDir = defaultModsFolder();
const isCustomModsDir = settings.modsFolder !== null;
const modsDir = settings.modsFolder ?? defaultModsDir;
await mkdir(modsDir, { recursive: true });
await seedBundledExampleModsOnce(modsDir);
return { modsDir, defaultModsDir, isCustomModsDir };
}
/**
* Copy newly shipped bundled template mods into the mods folder once each (disabled by default).
* Tracks which template folder names have already been seeded in `.wto-examples-seeded` so
* deleting a bundled template never restores it, while newly added official templates still
* appear for existing users. Serialized per directory to prevent concurrent seeding races.
*/
async function seedBundledExampleModsOnce(modsDir: string): Promise<void> {
const key = modsDir.toLowerCase();
const pending = inFlightSeeds.get(key);
if (pending) {
await pending;
return;
}
const task = (async () => {
const markerPath = join(modsDir, EXAMPLES_SEEDED_MARKER);
try {
const templatesRoot = resourcePaths().modTemplates;
if (!(await pathExists(templatesRoot))) return;
const seeded = await readSeededTemplateNames(markerPath, modsDir);
const templates = await readdir(templatesRoot, { withFileTypes: true });
let changed = false;
for (const entry of templates) {
if (!entry.isDirectory()) continue;
if (seeded.has(entry.name)) continue;
const dest = join(modsDir, entry.name);
if (!(await pathExists(dest))) {
await cp(join(templatesRoot, entry.name), dest, { recursive: true });
}
seeded.add(entry.name);
changed = true;
}
if (changed || !(await pathExists(markerPath))) {
await writeFile(markerPath, JSON.stringify({ seeded: [...seeded].sort() }, null, 2) + '\n', 'utf8');
}
} catch (error) {
console.warn('[mods] seeding bundled example mods skipped:', error);
}
})().finally(() => {
inFlightSeeds.delete(key);
});
inFlightSeeds.set(key, task);
await task;
}
async function readSeededTemplateNames(markerPath: string, modsDir: string): Promise<Set<string>> {
if (!(await pathExists(markerPath))) return new Set();
try {
const raw = (await readFile(markerPath, 'utf8')).trim();
if (raw === '1') {
// Legacy marker from initial 2-template version: mark existing folders as already seeded
// so newly added official templates (e.g. official-map-selector) are still delivered once.
const existing = await readdir(modsDir);
const set = new Set(['example-vehicle-tweak', 'example-server-script']);
for (const name of existing) set.add(name);
return set;
}
const parsed = JSON.parse(raw) as { seeded?: unknown };
if (Array.isArray(parsed.seeded)) {
return new Set(parsed.seeded.filter((item): item is string => typeof item === 'string'));
}
} catch { /* ignore */ }
return new Set();
}
async function pathExists(path: string): Promise<boolean> {
try {
await access(path);
return true;
} catch {
return false;
}
}
export async function openModsFolder(): Promise<void> {
const { modsDir } = await resolveModsFolder();
const failure = await shell.openPath(modsDir);
if (failure) console.warn('[mods] opening the mods folder failed:', modsDir, failure);
}
export async function getModsState(copyId: string): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
return buildModsStateView(copy);
}
export async function setModEnabled(copyId: string, modId: string, enabled: boolean): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
const next: ClientModsConfig = {
...current,
activePresetId: null,
enabled: { ...current.enabled, [modId]: enabled },
};
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function setModsOrder(copyId: string, order: readonly string[]): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
const next = normalizeClientModsConfig({ ...current, activePresetId: null, order }, discovered.mods);
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function autoSortMods(copyId: string): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
const sortedOrder = computeAutoSortOrder(discovered.mods, current.order);
const next: ClientModsConfig = {
...current,
activePresetId: null,
order: sortedOrder,
};
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function saveModPreset(copyId: string, name: string, overwriteId?: string): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
const now = new Date().toISOString();
let presets: ModPreset[];
let presetId: string;
if (overwriteId && current.presets.some((preset) => preset.id === overwriteId)) {
presetId = overwriteId;
presets = current.presets.map((preset) => (
preset.id === overwriteId
? { id: preset.id, name, order: [...current.order], enabled: { ...current.enabled }, updatedAt: now }
: preset
));
} else {
presetId = randomUUID();
presets = [
...current.presets,
{ id: presetId, name, order: [...current.order], enabled: { ...current.enabled }, updatedAt: now },
];
}
const next: ClientModsConfig = {
...current,
activePresetId: presetId,
presets,
};
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function applyModPreset(copyId: string, presetId: string): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
const preset = current.presets.find((item) => item.id === presetId);
if (!preset) throw new AppError('mods_preset_invalid');
const next = normalizeClientModsConfig({
...current,
order: preset.order,
enabled: preset.enabled,
activePresetId: preset.id,
}, discovered.mods);
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function deleteModPreset(copyId: string, presetId: string): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const current = await readClientModsConfig(copy.dataPath);
const next: ClientModsConfig = {
...current,
activePresetId: current.activePresetId === presetId ? null : current.activePresetId,
presets: current.presets.filter((preset) => preset.id !== presetId),
};
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function exportModPreset(
copyId: string,
presetId: string,
window: BrowserWindow | null,
): Promise<{ readonly path: string | null }> {
const copy = await requireCopy(copyId);
const current = await readClientModsConfig(copy.dataPath);
const preset = current.presets.find((item) => item.id === presetId);
if (!preset) throw new AppError('mods_preset_invalid');
const safeName = preset.name.replace(/[^A-Za-z0-9\u4e00-\u9fa5._-]+/g, '-').replace(/^-+|-+$/g, '') || 'preset';
const defaultDir = await resolveDialogDefaultPath('mod-preset');
const fileName = `${safeName}.wto-mods-preset.json`;
const dialogOptions = {
defaultPath: defaultDir ? join(defaultDir, fileName) : fileName,
filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }],
};
const choice = window
? await dialog.showSaveDialog(window, dialogOptions)
: await dialog.showSaveDialog(dialogOptions);
if (choice.canceled || !choice.filePath) return { path: null };
const payload = {
format: 1 as const,
name: preset.name,
order: [...preset.order],
enabled: { ...preset.enabled },
};
await writeFile(choice.filePath, JSON.stringify(payload, null, 2) + '\n', 'utf8');
await rememberDialogPath('mod-preset', choice.filePath);
return { path: choice.filePath };
}
export async function importModPreset(
copyId: string,
window: BrowserWindow | null,
): Promise<{ readonly imported: boolean; readonly state: ModsStateView }> {
const copy = await requireCopy(copyId);
const defaultPath = await resolveDialogDefaultPath('mod-preset');
const dialogOptions = {
properties: ['openFile'] as Array<'openFile'>,
filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }],
...(defaultPath ? { defaultPath } : {}),
};
const choice = window
? await dialog.showOpenDialog(window, dialogOptions)
: await dialog.showOpenDialog(dialogOptions);
if (choice.canceled || !choice.filePaths[0]) {
return { imported: false, state: await buildModsStateView(copy) };
}
await rememberDialogPath('mod-preset', choice.filePaths[0]);
let parsedRaw: unknown;
try {
parsedRaw = JSON.parse(await readFile(choice.filePaths[0], 'utf8')) as unknown;
} catch {
throw new AppError('mods_preset_invalid');
}
const validated = ModPresetTransferSchema.safeParse(parsedRaw);
if (!validated.success) throw new AppError('mods_preset_invalid');
const current = await readClientModsConfig(copy.dataPath);
const newPreset: ModPreset = {
id: randomUUID(),
name: validated.data.name,
order: validated.data.order,
enabled: validated.data.enabled,
updatedAt: new Date().toISOString(),
};
const next: ClientModsConfig = {
...current,
presets: [...current.presets, newPreset],
};
await writeClientModsConfig(copy.dataPath, next);
return { imported: true, state: await buildModsStateView(copy, next) };
}
export async function setModsFolder(copyId: string, folderPath: string | null): Promise<ModsStateView> {
if (folderPath !== null) {
if (!isAbsolute(folderPath)) throw new AppError('mods_folder_invalid');
try {
await mkdir(folderPath, { recursive: true });
const info = await stat(folderPath);
if (!info.isDirectory()) throw new AppError('mods_folder_invalid');
} catch (error) {
if (error instanceof AppError) throw error;
throw new AppError('mods_folder_invalid');
}
}
await updateSettings({ modsFolder: folderPath });
if (folderPath !== null) await rememberDialogPath('mods-folder', folderPath);
const copy = await requireCopy(copyId);
return buildModsStateView(copy);
}
/** Resolve ordered enabled mods for a launch; rejects when blocking dependency/conflict errors exist. */
export async function resolveEnabledModsForLaunch(
dataPath: string,
gameVersion: string | null,
): Promise<{ readonly modsDir: string; readonly enabledMods: readonly DiscoveredMod[] }> {
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const config = normalizeClientModsConfig(await readClientModsConfig(dataPath), discovered.mods);
const resolved = resolveModLoadOrder(discovered.mods, config, gameVersion);
if (resolved.hasBlockingErrors) {
console.error('[mods] blocking mod issues prevented launch:', resolved.issues.filter((i) => i.severity === 'error'));
throw new AppError('mods_blocking_issues');
}
return { modsDir, enabledMods: resolved.enabledMods };
}
async function buildModsStateView(copy: InstallRecord, preloadedConfig?: ClientModsConfig): Promise<ModsStateView> {
const { modsDir, defaultModsDir, isCustomModsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const rawConfig = preloadedConfig ?? await readClientModsConfig(copy.dataPath);
const config = normalizeClientModsConfig(rawConfig, discovered.mods);
const resolved = resolveModLoadOrder(discovered.mods, config, copy.gameVersion);
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
const orderedMods: ModListItem[] = config.order
.map((id) => byId.get(id))
.filter((mod): mod is DiscoveredMod => mod !== undefined)
.map(toModListItem);
return {
modsDir,
defaultModsDir,
isCustomModsDir,
apiVersion: MOD_API_VERSION,
mods: orderedMods,
discoveryErrors: [...discovered.errors],
order: [...config.order],
enabled: { ...config.enabled },
activePresetId: config.activePresetId,
presets: config.presets.map((preset) => ({
id: preset.id,
name: preset.name,
order: [...preset.order],
enabled: { ...preset.enabled },
updatedAt: preset.updatedAt,
})),
issues: [...resolved.issues],
hasBlockingErrors: resolved.hasBlockingErrors,
};
}
function toModListItem(mod: DiscoveredMod): ModListItem {
return {
id: mod.manifest.id,
folderName: mod.folderName,
rootDir: mod.rootDir,
name: mod.manifest.name,
...(mod.manifest.description !== undefined ? { description: mod.manifest.description } : {}),
version: mod.manifest.version,
author: mod.manifest.author,
apiVersion: mod.manifest.apiVersion,
gameVersions: [...mod.manifest.gameVersions],
requires: [...mod.manifest.requires],
conflicts: [...mod.manifest.conflicts],
loadAfter: [...mod.manifest.loadAfter],
loadBefore: [...mod.manifest.loadBefore],
badges: [...mod.content.badges],
hasServerScript: mod.content.serverEntry !== undefined,
serverTuningFiles: [...mod.content.serverTuningFiles],
packOperations: [...mod.content.packOperations],
guiPatchCount: mod.content.guiPatchDirs.length,
exePatchCount: mod.content.exePatchDirs.length,
hasClientAddon: mod.content.hasClientAddon,
addonFileCount: mod.content.addonRelativeFiles.length,
clientFileCount: mod.content.clientFiles.length,
hasConfigBlkPatch: mod.content.configBlkPatch !== undefined,
};
}
async function requireCopy(copyId: string): Promise<InstallRecord> {
const copies = await listCopies();
const copy = copies.copies.find((entry) => entry.id === copyId);
if (!copy) throw new AppError('copy_not_found');
return copy;
}
async function readClientModsConfig(dataPath: string): Promise<ClientModsConfig> {
const path = join(dataPath, CLIENT_MODS_CONFIG_FILE);
try {
const raw = await readJsonOr(path, null);
if (!raw || typeof raw !== 'object') return emptyClientModsConfig();
const obj = raw as Partial<ClientModsConfig>;
return {
format: 1,
order: Array.isArray(obj.order) ? obj.order.filter((item): item is string => typeof item === 'string') : [],
enabled: obj.enabled && typeof obj.enabled === 'object' ? { ...obj.enabled } : {},
activePresetId: typeof obj.activePresetId === 'string' ? obj.activePresetId : null,
presets: Array.isArray(obj.presets) ? obj.presets : [],
};
} catch (error) {
console.warn('[mods] unreadable client mods config, using defaults:', path, error);
return emptyClientModsConfig();
}
}
async function writeClientModsConfig(dataPath: string, config: ClientModsConfig): Promise<void> {
try {
await writeJsonAtomic(join(dataPath, CLIENT_MODS_CONFIG_FILE), config);
} catch (error) {
console.error('[mods] writing client mods config failed:', error);
throw new AppError('mods_write_failed');
}
}
@@ -11,13 +11,12 @@
* Only the active pack is kept.
*/
import { randomBytes } from 'node:crypto';
import { existsSync, readFileSync } from 'node:fs';
import { readFileSync } from 'node:fs';
import { mkdir, readdir, rename, rm, writeFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { app } from 'electron';
import {
checkPatchSet,
comparePackVersions,
formatManifest,
isPackVersion,
manifestIncompatibility,
@@ -45,31 +44,17 @@ function activeFile(): string {
return join(storeFolder(), 'active.json');
}
/** The version of a bundled set that carries a manifest (a packaged launcher's), else null. */
export function bundledPatchVersion(bundledRoot: string): string | null {
const path = join(bundledRoot, MANIFEST_FILE);
if (!existsSync(path)) return null;
try {
return parseManifest(readFileSync(path, 'utf8')).version;
} catch (error) {
console.warn('[patch-pack] the bundled manifest is unreadable:', error);
return null;
}
}
/**
* The active downloaded pack, when there is one this launcher can use and it is newer than the
* bundled patch set. Synchronous, because the resource paths are; it reads two small files.
* The active downloaded pack, when there is one this launcher can use. Synchronous, because the
* resource paths are; it reads two small files.
*/
export function activeDownloadedPack(bundledRoot?: string): DownloadedPack | null {
export function activeDownloadedPack(): DownloadedPack | null {
try {
const active = JSON.parse(readFileSync(activeFile(), 'utf8')) as { version?: unknown };
if (typeof active.version !== 'string' || !isPackVersion(active.version)) return null;
const root = join(storeFolder(), active.version);
const manifest = parseManifest(readFileSync(join(root, MANIFEST_FILE), 'utf8'));
if (manifest.version !== active.version || manifestIncompatibility(manifest, app.getVersion())) return null;
const bundled = bundledRoot ? bundledPatchVersion(bundledRoot) : null;
if (bundled && comparePackVersions(manifest.version, bundled) <= 0) return null;
return { root, manifest };
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') console.warn('[patch-pack] the active pack is unusable:', error);
@@ -1,14 +1,17 @@
/**
* Adaptation pack updates: which patch set the builds use, whether a source has a newer pack, and
* Adaptation pack updates: which patch set the builds use, whether GitHub has a newer pack, and
* installing it. The launcher checks at start (when the setting allows) and from the About page;
* a pack is installed only when the player confirms.
*
* A pack is newer when its version is above the active set's. A bundled set without a version
* (a repository checkout) is older than every pack.
*/
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { app } from 'electron';
import {
comparePackVersions,
MANIFEST_FILE,
manifestIncompatibility,
parseManifest,
PatchPackError,
@@ -19,57 +22,51 @@ import {
} from '@wto/patcher';
import type { ActivePatchSet, PackApplyResult, PackCheck, PackProblem, PackRelease } from '@shared/schemas/patch-pack.ts';
import { bundledResourcePaths, usesDownloadedPacks } from '../resources/resource-paths.ts';
import { activeDownloadedPack, bundledPatchVersion, installPack, useBundledPatchSet } from './pack-store.ts';
import {
newestProjectRelease, projectReleaseVersion, ReleasePageLimitError, withReleaseSources, type PackReleaseFiles, type ReleaseSource,
} from './release-feed.ts';
import { FeedUnreachableError, readReleaseAsset, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES } from './release-assets.ts';
import { activeDownloadedPack, installPack, useBundledPatchSet } from './pack-store.ts';
import { downloadReleaseFile, FeedUnreachableError, newestPackRelease, type PackReleaseFiles } from './release-feed.ts';
/** The manifest copy beside a release is a few hundred bytes. */
const MANIFEST_COPY_MAX_BYTES = 64 * 1024;
/** A signature file is 89 bytes. */
const SIGNATURE_MAX_BYTES = 1024;
export function activePatchSet(): ActivePatchSet {
const root = bundledResourcePaths().patches;
const pack = usesDownloadedPacks() ? activeDownloadedPack(root) : null;
const pack = usesDownloadedPacks() ? activeDownloadedPack() : null;
if (pack) return { source: 'downloaded', version: pack.manifest.version, gameVersions: [...pack.manifest.gameVersions] };
return { source: 'bundled', version: bundledPatchVersion(root), gameVersions: recordedGameVersions(root) };
const root = bundledResourcePaths().patches;
return { source: 'bundled', version: bundledVersion(root), gameVersions: recordedGameVersions(root) };
}
export async function checkPackUpdate(): Promise<PackCheck> {
const active = activePatchSet();
if (!packSigningPublicKey()) return { status: 'failed', active, latest: null, problem: 'no_signing_key' };
try {
const found = await withReleaseSources((source) => newestRelease(active.version, source));
const found = await newestRelease();
if (!found || !isNewer(found.manifest.version, active.version)) return { status: 'up_to_date', active, latest: found ? release(found) : null, problem: null };
const status = manifestIncompatibility(found.manifest, app.getVersion()) ? 'needs_app_update' : 'available';
return { status, active, latest: release(found), problem: null };
} catch (error) {
console.warn('[patch-pack] update check failed:', error);
return { status: 'failed', active, latest: null, problem: packUpdateProblem(error) };
return { status: 'failed', active, latest: null, problem: problemOf(error) };
}
}
/** Download and activate the selected pack when it is newer than the active set and usable. */
export async function applyPackUpdate(version: string): Promise<PackApplyResult> {
/** Download and activate the newest pack, when it is newer than the active set and usable. */
export async function applyPackUpdate(): Promise<PackApplyResult> {
if (!packSigningPublicKey()) return { ok: false, problem: 'no_signing_key' };
if (!isNewer(version, activePatchSet().version)) return { ok: false, problem: 'up_to_date' };
try {
const downloaded = await withReleaseSources(async (source) => {
const files = await projectReleaseVersion('pack', version, source);
const manifest = await readPackManifest(files);
if (manifestIncompatibility(manifest, app.getVersion())) return null;
const tuning = patchPackTuning();
const zip = await readReleaseAsset(files.zipUrl, tuning.maxPackBytes, AbortSignal.timeout(tuning.requestTimeoutMs), source);
const signature = new TextDecoder().decode(await readReleaseAsset(
files.signatureUrl, RELEASE_SIGNATURE_MAX_BYTES, AbortSignal.timeout(tuning.requestTimeoutMs), source,
));
return { zip, signature };
});
if (!downloaded) return { ok: false, problem: 'needs_app_update' };
if (!isNewer(version, activePatchSet().version)) return { ok: false, problem: 'up_to_date' };
await installPack(version, downloaded.zip, downloaded.signature);
console.info(`[patch-pack] pack ${version} installed and active`);
const found = await newestRelease();
if (!found || !isNewer(found.manifest.version, activePatchSet().version)) return { ok: false, problem: 'up_to_date' };
if (manifestIncompatibility(found.manifest, app.getVersion())) return { ok: false, problem: 'needs_app_update' };
const tuning = patchPackTuning();
const zip = await downloadReleaseFile(found.files.zipUrl, tuning.maxPackBytes);
const signature = new TextDecoder().decode(await downloadReleaseFile(found.files.signatureUrl, SIGNATURE_MAX_BYTES));
await installPack(found.files.version, zip, signature);
console.info(`[patch-pack] pack ${found.files.version} installed and active`);
return { ok: true, active: activePatchSet() };
} catch (error) {
console.warn('[patch-pack] update failed:', error);
return { ok: false, problem: packUpdateProblem(error) };
return { ok: false, problem: problemOf(error) };
}
}
@@ -84,17 +81,13 @@ interface FoundRelease {
readonly manifest: PatchPackManifest;
}
async function newestRelease(installedVersion: string | null, source: ReleaseSource): Promise<FoundRelease | null> {
const files = await newestProjectRelease('pack', installedVersion, source);
return files ? { files, manifest: await readPackManifest(files) } : null;
}
async function readPackManifest(files: PackReleaseFiles): Promise<PatchPackManifest> {
const deadline = AbortSignal.timeout(patchPackTuning().requestTimeoutMs);
const text = new TextDecoder().decode(await readReleaseAsset(files.manifestUrl, RELEASE_MANIFEST_MAX_BYTES, deadline, files.source));
async function newestRelease(): Promise<FoundRelease | null> {
const files = await newestPackRelease();
if (!files) return null;
const text = new TextDecoder().decode(await downloadReleaseFile(files.manifestUrl, MANIFEST_COPY_MAX_BYTES));
const manifest = parseManifest(text);
if (manifest.version !== files.version) throw new PatchPackError('contents', `release ${files.version} carries the manifest of ${manifest.version}`);
return manifest;
return { files, manifest };
}
function release(found: FoundRelease): PackRelease {
@@ -110,8 +103,19 @@ function isNewer(candidate: string, active: string | null): boolean {
return active === null || comparePackVersions(candidate, active) > 0;
}
export function packUpdateProblem(error: unknown): PackProblem {
if (error instanceof ReleasePageLimitError) return 'page_limit';
/** The version of a bundled set that carries a manifest (a packaged launcher's), else null. */
function bundledVersion(root: string): string | null {
const path = join(root, MANIFEST_FILE);
if (!existsSync(path)) return null;
try {
return parseManifest(readFileSync(path, 'utf8')).version;
} catch (error) {
console.warn('[patch-pack] the bundled manifest is unreadable:', error);
return null;
}
}
function problemOf(error: unknown): PackProblem {
if (error instanceof FeedUnreachableError) return 'network';
if (error instanceof PatchPackError) {
if (error.problem === 'signature') return 'signature';
@@ -1,139 +0,0 @@
import { createHash } from 'node:crypto';
import { createWriteStream } from 'node:fs';
import { mkdir, rename, unlink } from 'node:fs/promises';
import { dirname } from 'node:path';
import { Transform, type Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { net, type IncomingMessage } from 'electron';
import { PatchPackError } from '@wto/patcher';
import type { ReleaseSource } from './release-feed.ts';
const GITHUB_ASSET_HOSTS = new Set(['github.com', 'release-assets.githubusercontent.com', 'objects.githubusercontent.com']);
export const UPDATE_USER_AGENT = 'WTOffline-Launcher';
export const RELEASE_MANIFEST_MAX_BYTES = 64 * 1024;
export const RELEASE_SIGNATURE_MAX_BYTES = 1024;
export class FeedUnreachableError extends Error {
override readonly name = 'FeedUnreachableError';
}
function isReleaseAsset(value: string, source: ReleaseSource): boolean {
try {
const url = new URL(value);
if (url.protocol !== 'https:' || url.username || url.password) return false;
return !source.githubDownloads || (!url.port && GITHUB_ASSET_HOSTS.has(url.hostname));
} catch {
return false;
}
}
/** Download over HTTPS, including redirects, without sending session credentials. */
export function requestReleaseAsset(
url: URL, signal: AbortSignal, source: ReleaseSource,
): Promise<IncomingMessage & Readable> {
if (signal.aborted) return Promise.reject(new FeedUnreachableError('The release download timed out.'));
if (!isReleaseAsset(url.href, source)) {
return Promise.reject(new FeedUnreachableError('The release asset URL is not allowed.'));
}
return new Promise((resolve, reject) => {
const request = net.request({ url: url.href, credentials: 'omit', redirect: 'manual' });
request.setHeader('User-Agent', UPDATE_USER_AGENT);
const cleanup = (): void => signal.removeEventListener('abort', abort);
const fail = (error: FeedUnreachableError): void => {
cleanup();
reject(error);
request.abort();
};
const abort = (): void => fail(new FeedUnreachableError('The release download timed out.'));
signal.addEventListener('abort', abort, { once: true });
request.once('error', (error) => {
cleanup();
reject(new FeedUnreachableError('The release asset could not be downloaded.', { cause: error }));
});
request.on('redirect', (_status, _method, destination) => {
if (isReleaseAsset(destination, source)) request.followRedirect();
else fail(new FeedUnreachableError('The release asset redirected to a disallowed URL.'));
});
request.once('response', (response) => {
if (response.statusCode !== 200) {
fail(new FeedUnreachableError(`The update source answered HTTP ${response.statusCode} for a release asset.`));
return;
}
const stream = response as IncomingMessage & Readable;
stream.once('end', cleanup);
stream.once('close', cleanup);
resolve(stream);
});
request.end();
});
}
export async function* releaseAssetChunks(response: Readable): AsyncGenerator<Buffer> {
try {
for await (const chunk of response) yield chunk as Buffer;
} catch (error) {
throw new FeedUnreachableError('The release asset download was interrupted.', { cause: error });
}
}
export async function readReleaseAsset(
url: URL, limit: number, signal: AbortSignal, source: ReleaseSource,
): Promise<Uint8Array> {
const response = await requestReleaseAsset(url, signal, source);
const chunks: Buffer[] = [];
let size = 0;
for await (const chunk of releaseAssetChunks(response)) {
size += chunk.length;
if (size > limit) throw new PatchPackError('size', 'the release asset is larger than expected');
chunks.push(chunk);
}
return Buffer.concat(chunks);
}
/** Stream a large, signed asset to disk and install the file only after its size and hash match. */
export async function stageReleaseAsset(
url: URL, source: ReleaseSource, file: { readonly size: number; readonly sha256: string }, target: string,
report: (progress: { received: number; total: number }) => void,
): Promise<void> {
const partial = target + '.partial';
const deadline = AbortSignal.timeout(30 * 60_000);
const hash = createHash('sha256');
let received = 0;
let reportedAt = 0;
try {
await mkdir(dirname(target), { recursive: true });
await removePartial(partial);
const response = await requestReleaseAsset(url, deadline, source);
const monitor = new Transform({
transform(chunk: Buffer, _encoding, done) {
received += chunk.length;
if (received > file.size) {
done(new PatchPackError('size', 'The download is larger than its signed size.'));
return;
}
hash.update(chunk);
if (received === file.size || Date.now() - reportedAt >= 200) {
reportedAt = Date.now();
report({ received, total: file.size });
}
done(null, chunk);
},
});
await pipeline(releaseAssetChunks(response), monitor, createWriteStream(partial, { flags: 'wx' }), { signal: deadline });
if (received !== file.size) throw new FeedUnreachableError('The update download is incomplete.');
if (hash.digest('hex') !== file.sha256) throw new PatchPackError('signature', 'The download does not match the signed release.');
await rename(partial, target);
} catch (error) {
if (deadline.aborted) throw new FeedUnreachableError('The update download timed out.', { cause: error });
throw error;
} finally {
await removePartial(partial).catch((error: unknown) => console.warn('[release-assets] removing a partial download failed:', error));
}
}
async function removePartial(path: string): Promise<void> {
await unlink(path).catch((error: NodeJS.ErrnoException) => {
if (error.code !== 'ENOENT') throw error;
});
}
@@ -1,296 +1,80 @@
/**
* The launcher and adaptation pack channels share an anonymous, GitHub-compatible release list.
* The primary release source is tried first, followed by any player-configured mirror and default fallbacks.
* Adaptation pack releases on GitHub: the newest release tagged `patches-<version>` that carries
* all three files (zip, signature, manifest copy), and downloads of those files.
*
* Requests send no account, no cookie and nothing about the player; GitHub sees an anonymous
* request with a generic user agent.
*/
import { net } from 'electron';
import {
compareAppVersions, comparePackVersions, packFileNames, packVersionOfTag, PatchPackError, patchPackTuning,
} from '@wto/patcher';
import { z } from 'zod';
import { AppReleaseVersionSchema, launcherReleaseFiles, portableLauncherReleaseFiles } from '@shared/schemas/app-update.ts';
import { MAP_NAV_TAG_PREFIX, MapNavVersionSchema, mapNavReleaseFiles } from '@shared/schemas/map-nav-pack.ts';
import { releaseRepositoryUrl } from '@shared/update-source.ts';
import { getSettings } from '../config/settings-store.ts';
import { FeedUnreachableError, UPDATE_USER_AGENT } from './release-assets.ts';
export interface ReleaseSource {
readonly feed: URL;
readonly githubDownloads: URL | null;
}
export interface PortableReleaseAssets {
readonly archive: URL;
readonly manifest: URL;
readonly signature: URL;
}
export interface LauncherRelease {
readonly source: ReleaseSource;
readonly version: string;
readonly notes: string;
readonly installer: URL;
readonly manifest: URL;
readonly signature: URL;
readonly portable?: PortableReleaseAssets;
}
import { comparePackVersions, packFileNames, packVersionOfTag, PatchPackError, patchPackTuning } from '@wto/patcher';
export interface PackReleaseFiles {
readonly source: ReleaseSource;
readonly version: string;
readonly publishedAt: string | null;
readonly zipUrl: URL;
readonly signatureUrl: URL;
readonly manifestUrl: URL;
readonly zipUrl: string;
readonly signatureUrl: string;
readonly manifestUrl: string;
}
interface ReleaseByChannel {
launcher: LauncherRelease;
pack: PackReleaseFiles;
mapNav: PackReleaseFiles;
/** Thrown when GitHub cannot be reached or answers with an error. */
export class FeedUnreachableError extends Error {
override readonly name = 'FeedUnreachableError';
}
type ReleaseChannel = keyof ReleaseByChannel;
type ReleaseVersions = { [Channel in ReleaseChannel]: Map<string, ReleaseByChannel[Channel]> };
const HEADERS = { Accept: 'application/vnd.github+json', 'User-Agent': 'WTOffline-Launcher', 'X-GitHub-Api-Version': '2022-11-28' };
interface ReleaseListing {
readonly versions: ReleaseVersions;
readonly incomplete: Readonly<Partial<Record<ReleaseChannel, string>>>;
readonly pageLimit: number | null;
}
/** Thrown when the list ends at the configured page limit without finding a newer release. */
export class ReleasePageLimitError extends Error {
override readonly name = 'ReleasePageLimitError';
}
const GITHUB_HEADERS = { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' };
const MAX_RELEASE_NOTES_CHARS = 64 * 1024;
const ReleaseAsset = z.object({ name: z.string(), browser_download_url: z.string().optional() });
const LauncherReleaseEntry = z.object({
draft: z.literal(false),
prerelease: z.literal(false),
assets: z.array(ReleaseAsset),
body: z.string().nullable().optional(),
});
const listings = new Map<string, Promise<ReleaseListing>>();
function releaseSource(repository: URL): ReleaseSource {
const githubPath = repository.origin === 'https://github.com' ? repository.pathname
: repository.origin === 'https://api.github.com'
? /^\/repos(\/[\w.-]+\/[\w.-]+)(?:\/releases)?$/.exec(repository.pathname)?.[1]
: null;
if (githubPath) {
return {
feed: new URL(`https://api.github.com/repos${githubPath}/releases`),
githubDownloads: new URL(`https://github.com${githubPath}/releases/download/`),
};
}
const feed = new URL(repository);
if (!feed.pathname.endsWith('/releases')) feed.pathname = `${feed.pathname.replace(/\/$/, '')}/releases`;
return { feed, githubDownloads: null };
}
export function sameReleaseSource(a: ReleaseSource, b: ReleaseSource): boolean {
return a.githubDownloads && b.githubDownloads
? a.feed.href.toLowerCase() === b.feed.href.toLowerCase()
: a.feed.href === b.feed.href;
}
/** Keep a check or download on its preferred source until that source becomes unavailable. */
export async function withReleaseSources<T>(
read: (source: ReleaseSource) => Promise<T>, preferred?: ReleaseSource,
): Promise<T> {
/** The newest complete pack release, or null when none is released (or the repository is not public yet). */
export async function newestPackRelease(): Promise<PackReleaseFiles | null> {
const tuning = patchPackTuning();
const candidates: ReleaseSource[] = [];
const add = (url: URL | null): void => {
if (!url) return;
const source = releaseSource(url);
if (!candidates.some((existing) => sameReleaseSource(existing, source))) candidates.push(source);
};
add(releaseRepositoryUrl(tuning.primarySource));
add(releaseRepositoryUrl((await getSettings()).updateMirrorUrl));
for (const fallback of tuning.fallbackSources) add(releaseRepositoryUrl(fallback));
if (candidates.length === 0) throw new FeedUnreachableError('No valid release sources are configured.');
const url = `https://api.github.com/repos/${tuning.repository}/releases?per_page=${tuning.releasesPerCheck}`;
const response = await request(url, HEADERS, tuning.requestTimeoutMs);
if (response.status === 404) return null;
if (!response.ok) throw new FeedUnreachableError(`GitHub answered HTTP ${response.status} for the release list`);
const releases = (await response.json()) as unknown;
if (!Array.isArray(releases)) throw new PatchPackError('contents', 'the release list is not a list');
const ordered = preferred
? [preferred, ...candidates.filter((source) => !sameReleaseSource(source, preferred))]
: candidates;
const packs = releases.map(packRelease).filter((release): release is PackReleaseFiles => release !== null);
packs.sort((a, b) => comparePackVersions(b.version, a.version));
return packs[0] ?? null;
}
let lastError: unknown;
for (let index = 0; index < ordered.length; index += 1) {
const current = ordered[index]!;
try {
return await read(current);
} catch (error) {
if (!(error instanceof FeedUnreachableError || error instanceof ReleasePageLimitError)) throw error;
lastError = error;
const next = ordered[index + 1];
if (next) console.info(`[release-feed] ${current.feed.hostname} was unavailable, trying ${next.feed.hostname}.`);
}
function packRelease(value: unknown): PackReleaseFiles | null {
if (typeof value !== 'object' || value === null) return null;
const release = value as Record<string, unknown>;
if (release['draft'] === true || release['prerelease'] === true || typeof release['tag_name'] !== 'string') return null;
const version = packVersionOfTag(release['tag_name']);
if (!version || !Array.isArray(release['assets'])) return null;
const urls = new Map<string, string>();
for (const asset of release['assets'] as unknown[]) {
if (typeof asset !== 'object' || asset === null) continue;
const { name, browser_download_url: download } = asset as Record<string, unknown>;
if (typeof name === 'string' && typeof download === 'string' && download.startsWith('https://')) urls.set(name, download);
}
throw lastError;
}
function listingFor(source: ReleaseSource): Promise<ReleaseListing> {
const key = source.feed.href;
const existing = listings.get(key);
if (existing) return existing;
const pending = readProjectReleases(source).finally(() => { listings.delete(key); });
listings.set(key, pending);
return pending;
}
export async function newestProjectRelease<Channel extends ReleaseChannel>(
channel: Channel, installedVersion: string | null, source: ReleaseSource,
): Promise<ReleaseByChannel[Channel] | null> {
const { versions, incomplete, pageLimit } = await listingFor(source);
const compare = channel === 'launcher' ? compareAppVersions : comparePackVersions;
let candidate: ReleaseByChannel[Channel] | null = null;
for (const release of versions[channel].values()) {
if (!candidate || compare(release.version, candidate.version) > 0) candidate = release;
}
if (candidate && (installedVersion === null || compare(candidate.version, installedVersion) > 0)) return candidate;
if (pageLimit !== null) {
throw new ReleasePageLimitError(`No newer ${channel} release was confirmed within ${pageLimit} pages.`);
}
const partial = incomplete[channel];
if (partial && (!candidate || installedVersion === null || compare(partial, installedVersion) > 0)) {
throw new PatchPackError('contents', `Release ${partial} for the ${channel} channel is missing required files.`);
}
return candidate;
}
/** The fallback must supply the same release the player selected. */
export async function projectReleaseVersion<Channel extends ReleaseChannel>(
channel: Channel, version: string, source: ReleaseSource,
): Promise<ReleaseByChannel[Channel]> {
const release = (await listingFor(source)).versions[channel].get(version);
if (!release) throw new FeedUnreachableError(`This update source does not have the files for ${version}.`);
return release;
}
async function readProjectReleases(source: ReleaseSource): Promise<ReleaseListing> {
const tuning = patchPackTuning();
const versions: ReleaseVersions = { launcher: new Map(), pack: new Map(), mapNav: new Map() };
const incomplete: Partial<Record<ReleaseChannel, string>> = {};
const url = new URL(source.feed);
url.searchParams.set('per_page', String(tuning.releasePageSize));
const headers = {
Accept: 'application/json', 'User-Agent': UPDATE_USER_AGENT,
...(source.githubDownloads ? GITHUB_HEADERS : {}),
};
for (let page = 1; page <= tuning.maxReleasePages; page += 1) {
url.searchParams.set('page', String(page));
const result = await requestReleasePage(url, headers, tuning.requestTimeoutMs);
collectReleases(result.releases, versions, incomplete, source);
// GitHub does not sort release pages by tag version.
if (!result.hasNextPage) return { versions, incomplete, pageLimit: null };
}
console.info(`[release-feed] More releases exist after the configured limit of ${tuning.maxReleasePages} pages.`);
return { versions, incomplete, pageLimit: tuning.maxReleasePages };
}
async function requestReleasePage(url: URL, headers: Record<string, string>, timeoutMs: number) {
try {
const response = await net.fetch(url.href, { credentials: 'omit', headers, signal: AbortSignal.timeout(timeoutMs) });
if (!response.ok) throw new FeedUnreachableError(`The update source answered HTTP ${response.status} for a release page.`);
const releases: unknown = await response.json();
if (!Array.isArray(releases)) throw new FeedUnreachableError('The update source did not return a release list.');
const hasNextPage = /;\s*rel="next"\s*(?:,|$)/i.test(response.headers.get('link') ?? '');
return { releases: releases as readonly unknown[], hasNextPage };
} catch (error) {
if (error instanceof FeedUnreachableError) throw error;
throw new FeedUnreachableError('The update source could not be read.', { cause: error });
}
}
function collectReleases(
entries: readonly unknown[], versions: ReleaseVersions, incomplete: Partial<Record<ReleaseChannel, string>>, source: ReleaseSource,
): void {
for (const entry of entries) {
if (typeof entry !== 'object' || entry === null) continue;
const release = entry as Record<string, unknown>;
const tag = release['tag_name'];
if (typeof tag !== 'string' || release['draft'] === true) continue;
if (tag.startsWith('v')) {
if (release['prerelease'] === true) continue;
const version = AppReleaseVersionSchema.safeParse(tag.slice(1));
if (!version.success) continue;
const launcher = launcherRelease(release, version.data, source);
if (launcher) versions.launcher.set(launcher.version, launcher);
else if (!incomplete.launcher || compareAppVersions(version.data, incomplete.launcher) > 0) incomplete.launcher = version.data;
continue;
}
const mapNav = tag.startsWith(MAP_NAV_TAG_PREFIX);
const channel = mapNav ? 'mapNav' : 'pack';
const version = mapNav ? MapNavVersionSchema.safeParse(tag.slice(MAP_NAV_TAG_PREFIX.length)).data : packVersionOfTag(tag);
if (!version) continue;
const pack = packRelease(release, version, tag, source, mapNav ? mapNavReleaseFiles(version) : packFileNames(version));
if (pack) versions[channel].set(pack.version, pack);
else {
const partial = incomplete[channel];
if (!partial || comparePackVersions(version, partial) > 0) incomplete[channel] = version;
}
}
}
function assetUrls(assets: readonly unknown[], tag: string, source: ReleaseSource): Map<string, URL> {
const urls = new Map<string, URL>();
for (const asset of assets) {
const parsed = ReleaseAsset.safeParse(asset);
if (!parsed.success) continue;
const { name, browser_download_url: download } = parsed.data;
if (source.githubDownloads) {
urls.set(name, new URL(`${tag}/${encodeURIComponent(name)}`, source.githubDownloads));
continue;
}
const url = download ? URL.parse(download, source.feed.href) : null;
if (url?.protocol === 'https:' && !url.username && !url.password) urls.set(name, url);
}
return urls;
}
function launcherRelease(entry: Record<string, unknown>, version: string, source: ReleaseSource): LauncherRelease | null {
const parsed = LauncherReleaseEntry.safeParse(entry);
if (!parsed.success) return null;
const { assets, body } = parsed.data;
const names = launcherReleaseFiles(version);
const portableNames = portableLauncherReleaseFiles(version);
const urls = assetUrls(assets, `v${version}`, source);
const installer = urls.get(names.installer);
const manifest = urls.get(names.manifest);
const signature = urls.get(names.signature);
if (!installer || !manifest || !signature) return null;
const portableArchive = urls.get(portableNames.archive);
const portableManifest = urls.get(portableNames.manifest);
const portableSignature = urls.get(portableNames.signature);
const portable = portableArchive && portableManifest && portableSignature
? { archive: portableArchive, manifest: portableManifest, signature: portableSignature }
: undefined;
return {
source,
version,
notes: body?.trim().slice(0, MAX_RELEASE_NOTES_CHARS) ?? '',
installer,
manifest,
signature,
...(portable ? { portable } : {}),
};
}
function packRelease(
release: Record<string, unknown>, version: string, tag: string, source: ReleaseSource,
names: ReturnType<typeof packFileNames>,
): PackReleaseFiles | null {
if (!Array.isArray(release['assets'])) return null;
const urls = assetUrls(release['assets'], tag, source);
const names = packFileNames(version);
const zipUrl = urls.get(names.zip);
const signatureUrl = urls.get(names.signature);
const manifestUrl = urls.get(names.manifest);
if (!zipUrl || !signatureUrl || !manifestUrl) return null;
const publishedAt = typeof release['published_at'] === 'string' ? release['published_at'] : null;
return { source, version, publishedAt, zipUrl, signatureUrl, manifestUrl };
return { version, publishedAt, zipUrl, signatureUrl, manifestUrl };
}
/** Download a release file, refusing anything larger than `maxBytes`. */
export async function downloadReleaseFile(url: string, maxBytes: number): Promise<Uint8Array> {
const tuning = patchPackTuning();
const response = await request(url, { 'User-Agent': HEADERS['User-Agent'] }, tuning.requestTimeoutMs);
if (!response.ok) throw new FeedUnreachableError(`HTTP ${response.status} for ${url}`);
const declared = Number(response.headers.get('content-length') ?? '0');
if (declared > maxBytes) throw new PatchPackError('size', `${url} is ${declared} bytes, more than ${maxBytes}`);
const content = new Uint8Array(await response.arrayBuffer());
if (content.length > maxBytes) throw new PatchPackError('size', `${url} is more than ${maxBytes} bytes`);
return content;
}
async function request(url: string, headers: Record<string, string>, timeoutMs: number): Promise<Response> {
try {
return await net.fetch(url, { credentials: 'omit', headers, signal: AbortSignal.timeout(timeoutMs) });
} catch (error) {
throw new FeedUnreachableError(`${url}: ${(error as Error).message}`);
}
}
@@ -4,7 +4,7 @@ import { activeDownloadedPack } from '../patch-pack/pack-store.ts';
/**
* Where the launcher finds what it ships besides its own code: the patch set (exe, GUI and native
* definitions and version records, @wto/patcher patch-set.ts) and the network hook library.
* definitions and version records, @wto/patcher patch-set.ts) and the network hook library. In development they are this repository's folders.
*
* The patch set is the active downloaded adaptation pack when there is a usable one
* (services/patch-pack/), otherwise the bundled one. A repository checkout uses its own patches/
@@ -15,43 +15,25 @@ export interface ResourcePaths {
readonly patches: string;
/** wto_ws.dll, built by native/wto-net/build.ps1. */
readonly networkHookLibrary: string;
/** Multi-resolution Windows icon for the window and system tray. */
readonly appIcon: string;
/** Bundled example mod templates seeded into an empty mods folder on first use. */
readonly modTemplates: string;
/** Modular ground AI daScript sources injected into `game.vromfs.bin` when active. */
readonly groundAiScripts: string;
/** Location of the baseline navigation maps, when included with the launcher. */
readonly bundledMapNavFolder: string;
}
export function resourcePaths(): ResourcePaths {
const bundled = bundledResourcePaths();
const pack = usesDownloadedPacks() ? activeDownloadedPack(bundled.patches) : null;
const pack = usesDownloadedPacks() ? activeDownloadedPack() : null;
return pack ? { ...bundled, patches: pack.root } : bundled;
}
/** The resources that ship with the launcher, ignoring downloaded packs. */
export function bundledResourcePaths(): ResourcePaths {
if (app.isPackaged) {
return {
patches: join(process.resourcesPath, 'patches'),
networkHookLibrary: join(process.resourcesPath, 'native', 'wto_ws.dll'),
appIcon: join(process.resourcesPath, 'icon.ico'),
modTemplates: join(process.resourcesPath, 'mod-templates'),
groundAiScripts: join(process.resourcesPath, 'game-ai', 'ground'),
bundledMapNavFolder: join(process.resourcesPath, 'map-nav', 'maps'),
};
// The packaged layout is decided with the installer build; nothing ships it yet.
throw new Error('resource paths of a packaged launcher are not defined yet');
}
// The app path is apps/launcher; the repository is two levels up.
const repository = resolve(app.getAppPath(), '..', '..');
return {
patches: join(repository, 'patches'),
networkHookLibrary: join(repository, 'build', 'native', 'wto_ws.dll'),
appIcon: join(repository, 'apps', 'launcher', 'resources', 'icon.ico'),
modTemplates: join(repository, 'mod-dev-docs', 'templates'),
groundAiScripts: join(repository, 'game-ai', 'ground'),
bundledMapNavFolder: join(repository, 'build', 'map-nav', 'maps'),
};
}
@@ -1,30 +0,0 @@
import { AppError } from '@shared/errors.ts';
import type { SaveCrewEdit, SaveCrewPreview, SaveCrewView } from '@shared/schemas/crew-saves.ts';
import { offlineClientCacheFolders, requireSaveCopy, runSaveTask, saveLocation, writeSave } from './manage-saves.ts';
import { captureSave, restoreDirectory, saveBackup } from './save-archive.ts';
export async function getSaveCrews(copyId: string, userId: string, country: string | undefined): Promise<SaveCrewView> {
const copy = await requireSaveCopy(copyId);
return await runSaveTask({ operation: 'readCrews', ...saveLocation(copy), userId, country }) as SaveCrewView;
}
export async function previewSaveCrew(copyId: string, userId: string, country: string, edit: SaveCrewEdit): Promise<SaveCrewPreview> {
const copy = await requireSaveCopy(copyId);
return await runSaveTask({ operation: 'previewCrew', ...saveLocation(copy), userId, country, edit }) as SaveCrewPreview;
}
export async function changeSaveCrew(copyId: string, userId: string, country: string, edit: SaveCrewEdit, token: string): Promise<SaveCrewView> {
return writeSave(async () => {
const copy = await requireSaveCopy(copyId);
const before = await captureSave(copy, userId);
const cacheFolders = edit.action === 'close' ? await offlineClientCacheFolders(userId) : [];
if (edit.action === 'close') await saveBackup(copy, userId, 'crew', before);
try {
return await runSaveTask({ operation: 'editCrew', ...saveLocation(copy), userId, country, edit, token, cacheFolders }) as SaveCrewView;
} catch (error) {
const refused = error instanceof AppError && ['save_not_found', 'save_crew_invalid', 'save_crew_slot_limit', 'save_crew_stale'].includes(error.code);
if (!refused) await restoreDirectory(copy, userId, before);
throw error;
}
});
}
@@ -1,22 +1,17 @@
import { copyFile, lstat, mkdir, readdir, rm } from 'node:fs/promises';
import { isAbsolute, join } from 'node:path';
import { app, dialog, utilityProcess, type BrowserWindow } from 'electron';
import { compareVersions, isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import type { AccountEdits, CurrencyEdits, OfficialImportOptions, OfficialPreview, OnlineDataSource, SaveBackup, SaveDetails, SaveList, SaveRegistration, SaveTransfer, ResearchBranch, ResearchOperation, SaveAvatarChoices, SaveResearch } from '@shared/schemas/saves.ts';
import type { CurrencyEdits, OfficialImportOptions, OfficialPreview, SaveBackup, SaveDetails, SaveList, SaveRegistration, SaveTransfer, ResearchBranch, ResearchOperation, SaveResearch } from '@shared/schemas/saves.ts';
import type { SaveReply, SaveResult, SaveTask } from '../../workers/save-protocol.ts';
import { rememberDialogPath, resolveDialogDefaultPath } from '../../util/dialog-paths.ts';
import { maintenanceInProgress } from '../copies/copy-maintenance.ts';
import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } from '../install/install-record.ts';
import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts';
import { readInstalledLab } from '../launch/lab-handoff.ts';
import { localServerReady } from '../launch/local-server.ts';
import { labStatusUrl, readInstalledLab } from '../launch/lab-handoff.ts';
import { forwardProcessOutput } from '../launch/process-output.ts';
import { archivedBackup, backupList, captureSave, changeSaveFolder, readArchive, restoreDirectory, saveBackup, writeArchive, type SaveArchive } from './save-archive.ts';
export { location as saveLocation, offlineClientCacheFolders, requireCopy as requireSaveCopy, run as runSaveTask, write as writeSave };
let writing = false;
export function saveWriteInProgress(): boolean {
@@ -60,35 +55,6 @@ export async function createSave({ copyId, login, password, nick }: SaveRegistra
});
}
export async function getSaveAvatarChoices(copyId: string): Promise<SaveAvatarChoices> {
const copy = await requireCopy(copyId);
return await run({ operation: 'avatars', ...location(copy) }) as SaveAvatarChoices;
}
export async function getSaveAvatarPreview(copyId: string, avatar: string): Promise<string | null> {
const copy = await requireCopy(copyId);
return await run({ operation: 'avatarPreview', ...location(copy), avatar }) as string | null;
}
export async function changeSaveAccount(copyId: string, userId: string, edits: AccountEdits): Promise<SaveDetails> {
return write(async () => {
const copy = await requireCopy(copyId);
const changesProfile = edits.premiumDays !== undefined || edits.avatar !== undefined || edits.level !== undefined;
const before = changesProfile ? await captureSave(copy, userId) : null;
try {
await run({ operation: 'editAccount', ...location(copy), userId, edits });
} catch (error) {
const rejectedEdit = error instanceof AppError &&
['save_nick_invalid', 'save_avatar_invalid', 'save_level_invalid', 'save_not_found'].includes(error.code);
if (before && !rejectedEdit) {
await restoreDirectory(copy, userId, before);
}
throw error;
}
return getSaveDetails(copyId, userId);
});
}
export async function setSaveCurrencies(copyId: string, userId: string, values: CurrencyEdits): Promise<SaveDetails> {
return write(async () => {
const copy = await requireCopy(copyId);
@@ -98,27 +64,15 @@ export async function setSaveCurrencies(copyId: string, userId: string, values:
}
export async function pickSaveArchive(window: BrowserWindow | null): Promise<{ path: string | null }> {
const defaultPath = await resolveDialogDefaultPath('save-archive');
const options = {
properties: ['openFile' as const],
filters: [{ name: 'ZIP', extensions: ['zip'] }],
...(defaultPath ? { defaultPath } : {}),
};
const options = { properties: ['openFile' as const], filters: [{ name: 'ZIP', extensions: ['zip'] }] };
const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
const chosen = result.canceled ? null : (result.filePaths[0] ?? null);
if (chosen) await rememberDialogPath('save-archive', chosen);
return { path: chosen };
return { path: result.canceled ? null : result.filePaths[0] ?? null };
}
export async function exportSave(copyId: string, userId: string, window: BrowserWindow | null): Promise<{ path: string | null }> {
const copy = await requireCopy(copyId);
await getSaveDetails(copyId, userId);
const defaultDir = await resolveDialogDefaultPath('save-archive');
const fileName = `WTOffline-save-${userId}.zip`;
const options = {
defaultPath: defaultDir ? join(defaultDir, fileName) : fileName,
filters: [{ name: 'ZIP', extensions: ['zip'] }],
};
const options = { defaultPath: `WTOffline-save-${userId}.zip`, filters: [{ name: 'ZIP', extensions: ['zip'] }] };
const result = window ? await dialog.showSaveDialog(window, options) : await dialog.showSaveDialog(options);
if (result.canceled || !result.filePath) return { path: null };
try {
@@ -128,7 +82,6 @@ export async function exportSave(copyId: string, userId: string, window: Browser
console.error('[saves] could not export the save:', error);
throw new AppError('save_operation_failed');
}
await rememberDialogPath('save-archive', result.filePath);
return { path: result.filePath };
}
@@ -193,133 +146,25 @@ export async function restoreSaveBackup(copyId: string, userId: string, name: st
await getSaveDetails(copyId, userId);
const archive = await archivedBackup(copy, userId, name);
await validateProfile(archive, copy);
const before = await captureSave(copy, userId);
const cacheFolders = name.split('.')[1] === 'crew' ? await offlineClientCacheFolders(userId) : undefined;
await saveBackup(copy, userId, 'restore', before);
await saveBackup(copy, userId, 'restore');
await restoreDirectory(copy, userId, archive);
if (cacheFolders) {
try {
await run({ operation: 'syncRestoredCrewPresets', ...location(copy), userId, cacheFolders });
} catch (error) {
await restoreDirectory(copy, userId, before);
throw error;
}
}
return getSaveDetails(copyId, userId);
});
}
const ONLINE_DATA_FILES = ['global.blk', 'machine.blk', 'storage.blk'] as const;
const ONLINE_DATA_MAX_BYTES = 32 * 1024 * 1024;
function onlineSavesRoot(): string {
return join(app.getPath('documents'), 'My Games', 'WarThunder', 'Saves');
}
async function offlineClientCacheFolders(userId: string): Promise<string[]> {
if (!/^\d+$/.test(userId)) return [];
const root = await canonicalCopyPath(join(app.getPath('documents'), 'My Games', 'WTOffline', 'Saves'));
const candidates = [join(root, userId, 'production'), join(root, 'last', 'production')];
const folders: string[] = [];
for (const candidate of candidates) {
const resolved = await canonicalCopyPath(candidate);
if (copyPathContains(root, resolved)) folders.push(resolved);
}
return folders;
}
/** Read-only discovery of local online client settings under Documents/My Games/WarThunder/Saves. */
export async function discoverOnlineData(): Promise<OnlineDataSource[]> {
const root = onlineSavesRoot();
const entries = await readdir(root, { withFileTypes: true }).catch(() => []);
const found: Array<OnlineDataSource & { readonly mtimeMs: number }> = [];
for (const entry of entries) {
if (!entry.isDirectory() || !/^\d+$/.test(entry.name)) continue;
const production = join(root, entry.name, 'production');
const files: Array<(typeof ONLINE_DATA_FILES)[number]> = [];
let latestMtime = 0;
for (const fileName of ONLINE_DATA_FILES) {
const stats = await lstat(join(production, fileName)).catch(() => null);
if (!stats || !stats.isFile() || stats.size === 0 || stats.size > ONLINE_DATA_MAX_BYTES) continue;
files.push(fileName);
if (stats.mtimeMs > latestMtime) latestMtime = stats.mtimeMs;
}
if (files.length > 0) {
found.push({
accountId: entry.name,
folder: production,
files,
updatedAt: new Date(latestMtime).toISOString(),
mtimeMs: latestMtime,
});
}
}
return found
.sort((a, b) => b.mtimeMs - a.mtimeMs || a.accountId.localeCompare(b.accountId))
.map(({ mtimeMs: _ignored, ...item }) => item);
}
/**
* Copy the player's selected online settings files into the offline copy's own staging folder
* without writing to or modifying the online directory.
*/
export async function copyOnlineData(copyId: string, userId: string, accountId: string): Promise<string[]> {
if (!/^\d+$/.test(accountId) || !/^\d+$/.test(userId)) throw new AppError('save_official_invalid');
const copy = await requireCopy(copyId);
await getSaveDetails(copyId, userId);
const onlineRoot = await canonicalCopyPath(onlineSavesRoot());
const sourceDir = await canonicalCopyPath(join(onlineRoot, accountId, 'production'));
if (!copyPathContains(onlineRoot, sourceDir)) throw new AppError('save_official_location');
const dataRoot = await canonicalCopyPath(copy.dataPath);
const stageDir = await canonicalCopyPath(join(dataRoot, 'imported-online-data', userId, accountId));
if (!copyPathContains(dataRoot, stageDir)) throw new AppError('save_operation_failed');
const existingFiles: Array<(typeof ONLINE_DATA_FILES)[number]> = [];
for (const fileName of ONLINE_DATA_FILES) {
const sourcePath = join(sourceDir, fileName);
const stats = await lstat(sourcePath).catch(() => null);
if (!stats || !stats.isFile() || stats.size === 0 || stats.size > ONLINE_DATA_MAX_BYTES) continue;
existingFiles.push(fileName);
}
if (existingFiles.length === 0) throw new AppError('save_official_invalid');
await rm(stageDir, { recursive: true, force: true });
await mkdir(stageDir, { recursive: true });
const copied: string[] = [];
for (const fileName of existingFiles) {
const targetPath = join(stageDir, fileName);
await copyFile(join(sourceDir, fileName), targetPath);
copied.push(targetPath);
}
return copied;
}
export async function pickOfficialBackups(window: BrowserWindow | null): Promise<string[]> {
const defaultPath = await resolveDialogDefaultPath('official-backups');
const options = {
properties: ['openFile' as const, 'multiSelections' as const],
filters: [{ name: 'BLK', extensions: ['blk'] }],
...(defaultPath ? { defaultPath } : {}),
};
const options = { properties: ['openFile' as const, 'multiSelections' as const], filters: [{ name: 'BLK', extensions: ['blk'] }] };
const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
if (result.canceled || result.filePaths.length === 0) return [];
if (result.filePaths[0]) await rememberDialogPath('official-backups', result.filePaths[0]);
return result.filePaths;
return result.canceled ? [] : result.filePaths;
}
export async function previewSelectedBackups(
copyId: string, userId: string, paths: readonly string[],
copyId: string, userId: string, paths: readonly string[], includeUsedVehicles: boolean,
): Promise<OfficialPreview> {
const copy = await requireCopy(copyId);
await getSaveDetails(copyId, userId);
const selected = await verifyBackupLocations(copy, paths);
return await run({ operation: 'previewOfficial', ...location(copy), paths: selected }) as OfficialPreview;
return await run({ operation: 'previewOfficial', ...location(copy), paths: selected, includeUsedVehicles }) as OfficialPreview;
}
export async function importSelectedBackups(
@@ -329,18 +174,10 @@ export async function importSelectedBackups(
const copy = await requireCopy(copyId);
await getSaveDetails(copyId, userId);
const selected = await verifyBackupLocations(copy, paths);
const cacheFolders = await offlineClientCacheFolders(userId);
const before = await captureSave(copy, userId);
await saveBackup(copy, userId, 'import');
try {
return await run({
operation: 'importOfficial',
...location(copy),
userId,
paths: selected,
options,
...(cacheFolders.length > 0 ? { offlineClientCacheFolders: cacheFolders } : {}),
}) as OfficialPreview;
return await run({ operation: 'importOfficial', ...location(copy), userId, paths: selected, options }) as OfficialPreview;
} catch (error) {
await restoreDirectory(copy, userId, before);
throw error;
@@ -401,7 +238,12 @@ async function write<T>(operation: () => Promise<T>): Promise<T> {
async function labServerRunning(): Promise<boolean> {
const lab = await readInstalledLab().catch(() => null);
if (!lab) return false;
return localServerReady(lab.port);
try {
const response = await fetch(labStatusUrl(lab.port), { signal: AbortSignal.timeout(600) });
return response.ok && (await response.json() as { app?: string }).app === 'wto-server';
} catch {
return false;
}
}
async function run(task: SaveTask): Promise<SaveResult> {
@@ -178,11 +178,11 @@ export async function backupList(copy: InstallRecord, userId: string): Promise<S
return backups;
}
export async function saveBackup(copy: InstallRecord, userId: string, type: SaveBackup['type'], archive?: SaveArchive): Promise<void> {
export async function saveBackup(copy: InstallRecord, userId: string, type: SaveBackup['type']): Promise<void> {
const root = await backupFolder(copy, userId);
await mkdir(root, { recursive: true });
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
await writeArchive(join(root, `${stamp}.${type}.${randomUUID()}.zip`), archive ?? await captureSave(copy, userId));
await writeArchive(join(root, `${stamp}.${type}.${randomUUID()}.zip`), await captureSave(copy, userId));
if (type === 'launch') {
const older = (await backupList(copy, userId)).filter((backup) => backup.type === 'launch').slice(10);
for (const backup of older) await rm(join(root, backup.name), { force: true });
-171
View File
@@ -1,171 +0,0 @@
import { stat } from 'node:fs/promises';
import { dirname, isAbsolute, join, resolve } from 'node:path';
import { readJsonOr, writeJsonAtomic } from './atomic-json.ts';
/**
* Remembers the last directory chosen in native open/save dialogs, keyed by dialog category,
* persisted to `<userData>/dialog-paths.json`. Read/write errors are swallowed so dialog
* behavior is never disrupted.
*/
export type DialogPathCategory =
| 'folder'
| 'save-archive'
| 'official-backups'
| 'mods-folder'
| 'mod-preset';
export interface DialogPathStore {
resolveDialogDefaultPath(
category: DialogPathCategory,
explicitPath?: string | null,
): Promise<string | undefined>;
rememberDialogPath(category: DialogPathCategory, selectedPath: string): Promise<void>;
}
const DIALOG_PATHS_FILENAME = 'dialog-paths.json';
const LAST_KEY = 'last';
const MAX_ANCESTOR_STEPS = 128;
/**
* Resolve `candidate` to an existing directory:
* - If it is an existing directory, return its normalized path.
* - If it is an existing file or does not exist, walk up to the nearest existing ancestor directory.
* - Return `undefined` when no existing ancestor directory can be reached.
*/
export async function resolveExistingDirectory(candidate: string | null | undefined): Promise<string | undefined> {
if (!candidate) return undefined;
const trimmed = candidate.trim();
if (!trimmed || !isAbsolute(trimmed)) return undefined;
let current = resolve(trimmed);
for (let step = 0; step < MAX_ANCESTOR_STEPS; step++) {
try {
const info = await stat(current);
if (info.isDirectory()) return current;
} catch {
// Missing or inaccessible path; continue walking toward the filesystem root.
}
const parent = dirname(current);
if (parent === current) return undefined;
current = parent;
}
return undefined;
}
/** Create a dialog-path store backed by the JSON file path returned by `resolveStorePath`. */
export function createDialogPathStore(
resolveStorePath: () => Promise<string | null> | string | null,
): DialogPathStore {
let cached: Map<string, string> | null = null;
let loading: Promise<Map<string, string>> | null = null;
let pending: Promise<void> = Promise.resolve();
async function loadMap(): Promise<Map<string, string>> {
if (cached) return cached;
if (loading) return loading;
loading = (async () => {
const map = new Map<string, string>();
const storePath = await resolveStorePath();
if (storePath) {
try {
const raw = await readJsonOr(storePath, null);
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
if (typeof value === 'string' && value.trim().length > 0) {
map.set(key, value);
}
}
}
} catch (error) {
console.warn('[dialog-paths] failed to read dialog paths:', error);
}
}
cached = map;
return map;
})().finally(() => {
loading = null;
});
return loading;
}
return {
async resolveDialogDefaultPath(
category: DialogPathCategory,
explicitPath?: string | null,
): Promise<string | undefined> {
try {
const explicitDir = await resolveExistingDirectory(explicitPath);
if (explicitDir) return explicitDir;
const map = await loadMap();
const categoryPath = map.get(category);
if (categoryPath) {
const resolved = await resolveExistingDirectory(categoryPath);
if (resolved) return resolved;
}
const lastPath = map.get(LAST_KEY);
if (lastPath && lastPath !== categoryPath) {
const resolved = await resolveExistingDirectory(lastPath);
if (resolved) return resolved;
}
} catch (error) {
console.warn('[dialog-paths] failed to resolve default dialog path:', error);
}
return undefined;
},
async rememberDialogPath(category: DialogPathCategory, selectedPath: string): Promise<void> {
const dir = await resolveExistingDirectory(selectedPath);
if (!dir) return;
const operation = pending.then(async () => {
const map = await loadMap();
if (map.get(category) === dir && map.get(LAST_KEY) === dir) return;
map.set(category, dir);
map.set(LAST_KEY, dir);
const storePath = await resolveStorePath();
if (!storePath) return;
try {
await writeJsonAtomic(storePath, Object.fromEntries(map));
} catch (error) {
console.warn('[dialog-paths] failed to save dialog paths:', error);
}
});
pending = operation.then(() => undefined, () => undefined);
await operation;
},
};
}
async function defaultStorePath(): Promise<string | null> {
try {
const mod = await import('electron') as {
readonly app?: { getPath?: (name: 'userData') => string };
readonly default?: { app?: { getPath?: (name: 'userData') => string } };
};
const electronApp = mod.app ?? mod.default?.app;
if (typeof electronApp?.getPath !== 'function') return null;
return join(electronApp.getPath('userData'), DIALOG_PATHS_FILENAME);
} catch {
return null;
}
}
const defaultStore = createDialogPathStore(defaultStorePath);
export function resolveDialogDefaultPath(
category: DialogPathCategory,
explicitPath?: string | null,
): Promise<string | undefined> {
return defaultStore.resolveDialogDefaultPath(category, explicitPath);
}
export function rememberDialogPath(category: DialogPathCategory, selectedPath: string): Promise<void> {
return defaultStore.rememberDialogPath(category, selectedPath);
}
-23
View File
@@ -1,23 +0,0 @@
import * as nodeFs from 'node:fs';
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
let cached: typeof nodeFs | null = null;
/**
* Return Node's unpatched fs module inside Electron.
*
* Electron patches `node:fs` to treat any `.asar` file anywhere on disk as a virtual archive
* directory, which breaks streaming reads, stats and recursive cleanup when copying or managing
* player folders that happen to contain an `.asar` file. Falls back to `node:fs` outside Electron.
*/
export function rawFs(): typeof nodeFs {
if (cached) return cached;
try {
cached = require('original-fs') as typeof nodeFs;
} catch {
cached = nodeFs;
}
return cached;
}
@@ -5,17 +5,10 @@ export interface BuildRequest {
readonly stockPath: string;
readonly copyPath: string;
readonly dataPath: string;
readonly steamLibraryConfirmed: boolean;
readonly port: number;
readonly patches: string;
readonly networkHookLibrary: string;
readonly groundAiScripts: string;
readonly mapNavFolder?: string;
readonly decalCache?: string;
readonly hookLogging: boolean;
readonly acceptedUnavailable: readonly string[];
readonly modsDir?: string;
readonly enabledModIds?: readonly string[];
}
export type BuildCommand = BuildRequest | { readonly kind: 'write' };
+9 -115
View File
@@ -1,114 +1,24 @@
import { readFileSync, realpathSync } from 'node:fs';
import { relative } from 'node:path';
import { readFileSync } from 'node:fs';
import type { MessageEvent } from 'electron';
import { discoverMods, touchedClientPacks, type DiscoveredMod, type ModdableClientPack } from '@wto/mods';
import {
assertWritableCopy,
buildGameCopy,
computeModsBuildFingerprint,
copyPlayerDecalCache,
CORE_BUILD_PACKS,
GAME_PACK_FILE,
isGroundAiActive,
playerDecalCacheProblem,
prepareOptionalStockPacks,
readPlayerDecalIndexFiles,
readStockGameFiles,
syncExternalModFiles,
writeGameCopy,
type GameCopyBuild,
type GameCopyFile,
} from '@wto/patcher';
import { loadGroundAiTuning, multiVehiclePackIds } from '@wto/server';
import { assertWritableCopy, buildGameCopy, readStockGameFiles, writeGameCopy, type GameCopyFile } from '@wto/patcher';
import { multiVehiclePackIds } from '@wto/server';
import type { BuildCommand, BuildReply, BuildRequest } from './build-protocol.ts';
let prepared: {
readonly request: BuildRequest;
readonly files: readonly GameCopyFile[];
readonly decalCache: string | undefined;
readonly enabledMods: readonly DiscoveredMod[];
readonly optionalPacksInBuild: readonly ModdableClientPack[];
readonly fingerprint: string;
} | null = null;
function checkBuildLocation({ stockPath, copyPath, steamLibraryConfirmed }: BuildRequest): void {
if (relative(copyPath, realpathSync(copyPath)) !== '') throw new Error('The copy path changed during the build.');
assertWritableCopy(stockPath, copyPath, { steamLibraryConfirmed });
}
let prepared: { readonly copyPath: string; readonly files: readonly GameCopyFile[] } | null = null;
function send(reply: BuildReply): void {
process.parentPort.postMessage(reply);
}
function importedDecals(path: string | undefined): string | undefined {
if (!path) return undefined;
try {
const imported = realpathSync(path);
if (relative(path, imported) === '' && !playerDecalCacheProblem(imported)) return imported;
} catch (error) {
console.warn('[build] the imported decal cache is unavailable:', error);
}
return undefined;
}
function resolveOrderedMods(modsDir: string | undefined, enabledModIds: readonly string[] | undefined): DiscoveredMod[] {
if (!modsDir || !enabledModIds || enabledModIds.length === 0) return [];
const discovered = discoverMods(modsDir);
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
const ordered: DiscoveredMod[] = [];
for (const id of enabledModIds) {
const mod = byId.get(id);
if (!mod) throw new Error(`enabled mod "${id}" was not found in ${modsDir}`);
ordered.push(mod);
}
return ordered;
}
function logModBuildSummary(result: GameCopyBuild): void {
if (result.gamePack) {
console.info(`[build] injected ${result.gamePack.modules.length} ground AI module(s) into ${result.gamePack.archiveFolder}`);
}
if (result.mods.enabledModIds.length === 0) return;
console.info(
`[build] applied ${result.mods.enabledModIds.length} mod(s): ${result.mods.enabledModIds.join(', ')} ` +
`(pack overlays=${result.mods.packOverlays.length}, addons=${result.mods.addonMounts.length}, ` +
`gui=${result.mods.guiPatches.applied.length} ok/${result.mods.guiPatches.failures.length} failed, ` +
`exe=${result.mods.exePatches.applied.length} ok/${result.mods.exePatches.failures.length} failed)`,
);
for (const failure of [...result.mods.guiPatches.failures, ...result.mods.exePatches.failures]) {
console.warn(`[build] mod "${failure.modId}" patch "${failure.patchId}" skipped: ${failure.reason}`);
}
}
function build(request: BuildRequest): void {
checkBuildLocation(request);
const decalCache = importedDecals(request.decalCache);
const decalIndexFiles = decalCache ? readPlayerDecalIndexFiles(decalCache) : undefined;
const enabledMods = resolveOrderedMods(request.modsDir, request.enabledModIds);
const groundAiConfig = loadGroundAiTuning(request.dataPath, console.info, enabledMods);
const groundAiActive = isGroundAiActive(groundAiConfig);
const touchedSet = new Set<ModdableClientPack>(
touchedClientPacks(enabledMods).filter((pack) => !CORE_BUILD_PACKS.has(pack)),
);
if (groundAiActive) touchedSet.add(GAME_PACK_FILE);
const optionalPacksInBuild = [...touchedSet];
const extraStockPacks = optionalPacksInBuild.length > 0
? prepareOptionalStockPacks(request.copyPath, request.stockPath, optionalPacksInBuild)
: undefined;
assertWritableCopy(request.stockPath, request.copyPath);
const result = buildGameCopy({
stock: readStockGameFiles(request.stockPath),
patches: request.patches,
networkHookLibrary: readFileSync(request.networkHookLibrary),
port: request.port,
multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info, enabledMods),
placeholderDecals: decalCache === undefined,
...(decalIndexFiles ? { decalIndexFiles } : {}),
hookLogging: request.hookLogging,
...(request.mapNavFolder === undefined ? {} : { mapNavFolder: request.mapNavFolder }),
...(enabledMods.length > 0 ? { mods: enabledMods } : {}),
...(extraStockPacks ? { extraStockPacks } : {}),
groundAi: { scriptsFolder: request.groundAiScripts, config: groundAiConfig },
multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info),
placeholderDecals: true,
});
const unavailable = [...result.exePatches.failures, ...result.guiPatches.failures, ...result.nativeModules.failures];
const accepted = new Set(request.acceptedUnavailable);
@@ -117,13 +27,7 @@ function build(request: BuildRequest): void {
send({ kind: 'failed', error: 'launch_build_unavailable' });
return;
}
logModBuildSummary(result);
const fingerprint = computeModsBuildFingerprint(
enabledMods,
request.port,
`${request.patches}|groundAi=${JSON.stringify(groundAiConfig)}`,
);
prepared = { request, files: result.files, decalCache, enabledMods, optionalPacksInBuild, fingerprint };
prepared = { copyPath: request.copyPath, files: result.files };
send({ kind: 'prepared', total: prepared.files.length });
}
@@ -135,22 +39,12 @@ process.parentPort.on('message', (event: MessageEvent) => {
return;
}
if (!prepared) throw new Error('No build is ready to write.');
const { request, files, decalCache, enabledMods, optionalPacksInBuild, fingerprint } = prepared;
const { copyPath, files } = prepared;
prepared = null;
checkBuildLocation(request);
const { copyPath, stockPath } = request;
if (decalCache) copyPlayerDecalCache(decalCache, copyPath);
for (const [index, file] of files.entries()) {
writeGameCopy(copyPath, [file]);
send({ kind: 'progress', written: index + 1, total: files.length, file: file.path });
}
const deployResult = syncExternalModFiles(copyPath, stockPath, enabledMods, optionalPacksInBuild, fingerprint);
for (const warning of deployResult.warnings) {
console.warn(`[mods] skipped "${warning.targetRelPath}" from "${warning.modId}": ${warning.reason}`);
}
if (deployResult.restoredOptionalPacks.length > 0) {
console.info(`[mods] restored stock pack(s): ${deployResult.restoredOptionalPacks.join(', ')}`);
}
send({ kind: 'written' });
} catch (error) {
console.error('[build] preparing the game copy failed:', error);
@@ -1,6 +1,5 @@
import type { AppErrorCode } from '@shared/errors.ts';
import type { SaveCrewEdit, SaveCrewPreview, SaveCrewView } from '@shared/schemas/crew-saves.ts';
import type { AccountEdits, SaveAvatarChoices, CurrencyEdits, OfficialImportOptions, OfficialPreview, ResearchBranch, ResearchOperation, SaveDetails, SaveList, SaveResearch } from '@shared/schemas/saves.ts';
import type { CurrencyEdits, OfficialImportOptions, OfficialPreview, ResearchBranch, ResearchOperation, SaveDetails, SaveList, SaveResearch } from '@shared/schemas/saves.ts';
interface Location {
readonly gameFolder: string;
@@ -10,27 +9,14 @@ interface Location {
export type SaveTask = Location & (
| { readonly operation: 'list' }
| { readonly operation: 'details'; readonly userId: string }
| { readonly operation: 'avatars' }
| { readonly operation: 'avatarPreview'; readonly avatar: string }
| { readonly operation: 'editAccount'; readonly userId: string; readonly edits: AccountEdits }
| { readonly operation: 'edit'; readonly userId: string; readonly values: CurrencyEdits }
| { readonly operation: 'previewOfficial'; readonly paths: readonly string[] }
| {
readonly operation: 'importOfficial';
readonly paths: readonly string[];
readonly userId: string;
readonly options: OfficialImportOptions;
readonly offlineClientCacheFolders?: readonly string[];
}
| { readonly operation: 'previewOfficial'; readonly paths: readonly string[]; readonly includeUsedVehicles: boolean }
| { readonly operation: 'importOfficial'; readonly paths: readonly string[]; readonly userId: string; readonly options: OfficialImportOptions }
| { readonly operation: 'readResearch'; readonly userId: string; readonly branch?: ResearchBranch }
| { readonly operation: 'editResearch'; readonly userId: string; readonly branch: ResearchBranch; readonly action: ResearchOperation }
| { readonly operation: 'readCrews'; readonly userId: string; readonly country: string | undefined }
| { readonly operation: 'previewCrew'; readonly userId: string; readonly country: string; readonly edit: SaveCrewEdit }
| { readonly operation: 'editCrew'; readonly userId: string; readonly country: string; readonly edit: SaveCrewEdit; readonly token: string; readonly cacheFolders: readonly string[] }
| { readonly operation: 'syncRestoredCrewPresets'; readonly userId: string; readonly cacheFolders: readonly string[] }
| { readonly operation: 'remove'; readonly userId: string }
| { readonly operation: 'filter'; readonly profile: Uint8Array; readonly filter: boolean }
| { readonly operation: 'create'; readonly login: string; readonly password: string; readonly nick: string }
);
export type SaveResult = SaveList['saves'] | SaveDetails | OfficialPreview | SaveResearch | SaveCrewView | SaveCrewPreview | { userId: string } | Uint8Array | SaveAvatarChoices | string | null;
export type SaveResult = SaveList['saves'] | SaveDetails | OfficialPreview | SaveResearch | { userId: string } | Uint8Array | null;
export type SaveReply = { ok: true; result: SaveResult } | { ok: false; error: AppErrorCode };
+5 -39
View File
@@ -1,39 +1,22 @@
import type { MessageEvent } from 'electron';
import { AccountStore, editSaveAccount, editSaveCurrencies, editSaveResearch, importOfficialBackup, listSaveAvatars, listSaveSummaries, prepareTransferredProfile, previewOfficialBackup, readSaveAvatar, readSaveDetails, readSaveResearch } from '@wto/server';
import { editSaveCrew, previewSaveCrewEdit, readSaveCrews, syncRestoredCrewPresets } from '@wto/server';
import { AccountStore, editSaveCurrencies, editSaveResearch, importOfficialBackup, listSaveSummaries, prepareTransferredProfile, previewOfficialBackup, readSaveDetails, readSaveResearch } from '@wto/server';
import type { SaveTask, SaveReply } from './save-protocol.ts';
const CREW_ERRORS = {
'not-found': 'save_not_found', invalid: 'save_crew_invalid', 'slot-limit': 'save_crew_slot_limit', stale: 'save_crew_stale',
} as const;
function execute(task: SaveTask): SaveReply {
switch (task.operation) {
case 'list':
return { ok: true, result: listSaveSummaries(task.dataFolder, task.gameFolder) };
return { ok: true, result: listSaveSummaries(task.dataFolder) };
case 'details': {
const result = readSaveDetails(task.dataFolder, task.userId, task.gameFolder);
const result = readSaveDetails(task.dataFolder, task.userId);
return result ? { ok: true, result } : { ok: false, error: 'save_not_found' };
}
case 'avatars':
return { ok: true, result: listSaveAvatars(task) };
case 'avatarPreview':
return { ok: true, result: readSaveAvatar(task, task.avatar) };
case 'editAccount':
switch (editSaveAccount(task, task.userId, task.edits)) {
case 'updated': return { ok: true, result: null };
case 'invalid-nick': return { ok: false, error: 'save_nick_invalid' };
case 'invalid-avatar': return { ok: false, error: 'save_avatar_invalid' };
case 'invalid-level': return { ok: false, error: 'save_level_invalid' };
case 'not-found': return { ok: false, error: 'save_not_found' };
}
case 'edit':
return editSaveCurrencies(task, task.userId, task.values)
? { ok: true, result: null } : { ok: false, error: 'save_not_found' };
case 'previewOfficial':
return { ok: true, result: previewOfficialBackup(task, task.paths) };
return { ok: true, result: previewOfficialBackup(task, task.paths, task.includeUsedVehicles) };
case 'importOfficial':
return { ok: true, result: importOfficialBackup(task, task.userId, task.paths, task.options, task.offlineClientCacheFolders) };
return { ok: true, result: importOfficialBackup(task, task.userId, task.paths, task.options) };
case 'readResearch': {
const result = readSaveResearch(task, task.userId, task.branch);
return result ? { ok: true, result } : { ok: false, error: 'save_not_found' };
@@ -42,23 +25,6 @@ function execute(task: SaveTask): SaveReply {
const result = editSaveResearch(task, task.userId, task.branch, task.action);
return result ? { ok: true, result } : { ok: false, error: 'save_operation_failed' };
}
case 'readCrews': {
const result = readSaveCrews(task, task.userId, task.country);
return result ? { ok: true, result } : { ok: false, error: 'save_not_found' };
}
case 'previewCrew': {
const result = previewSaveCrewEdit(task, task.userId, task.country, task.edit);
if ('preview' in result && result.preview) return { ok: true, result: result.preview };
return { ok: false, error: CREW_ERRORS[result.error ?? 'invalid'] };
}
case 'editCrew': {
const result = editSaveCrew(task, task.userId, task.country, task.edit, task.token, task.cacheFolders);
if ('view' in result && result.view) return { ok: true, result: result.view };
return { ok: false, error: CREW_ERRORS[result.error ?? 'invalid'] };
}
case 'syncRestoredCrewPresets':
syncRestoredCrewPresets(task.dataFolder, task.userId, task.cacheFolders);
return { ok: true, result: null };
case 'remove':
return new AccountStore(task.dataFolder).remove(task.userId)
? { ok: true, result: null } : { ok: false, error: 'save_not_found' };
@@ -1,56 +0,0 @@
import { discoverMods, type DiscoveredMod } from '@wto/mods';
import { startServer } from '@wto/server';
export type ServerWorkerStatus = 'listening' | 'port-busy' | 'failed';
function loadOrderedMods(modsDir: string | undefined, enabledJson: string | undefined): DiscoveredMod[] {
if (!modsDir || !enabledJson) return [];
const ids = JSON.parse(enabledJson) as unknown;
if (!Array.isArray(ids) || ids.length === 0) return [];
const discovered = discoverMods(modsDir);
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
const mods: DiscoveredMod[] = [];
for (const id of ids) {
if (typeof id !== 'string') continue;
const mod = byId.get(id);
if (!mod) throw new Error(`Enabled mod "${id}" not found in ${modsDir}`);
mods.push(mod);
}
return mods;
}
async function serve(): Promise<void> {
const [gameFolder, dataFolder, portText, loggingFlag, modsDir, enabledModIdsJson] = process.argv.slice(2);
const port = Number(portText);
if (!gameFolder || !dataFolder || !Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error('Invalid local server arguments.');
}
const loggingEnabled = loggingFlag !== '0';
const mods = loadOrderedMods(modsDir, enabledModIdsJson);
const server = await startServer({
gameFolder,
dataFolder,
port,
loggingEnabled,
...(mods.length > 0 ? { mods } : {}),
report: console.info,
});
if (server.logFolder) console.info('Traffic log:', server.logFolder);
if (server.loadedModIds.length > 0) console.info('Loaded server script mods:', server.loadedModIds.join(', '));
process.parentPort.once('message', () => {
void server.close().then(() => process.exit(0)).catch((error: unknown) => {
console.error('Could not close the local server:', error);
process.exit(1);
});
});
send('listening');
}
function send(status: ServerWorkerStatus): void {
process.parentPort.postMessage(status);
}
void serve().catch((error: unknown) => {
console.error('Could not start the local server:', error);
send((error as NodeJS.ErrnoException).code === 'EADDRINUSE' ? 'port-busy' : 'failed');
});
+15 -113
View File
@@ -4,13 +4,11 @@ import type { IpcOutput } from '@shared/ipc/contract.ts';
import type { Copies } from '@shared/schemas/install.ts';
import type { LaunchState } from '@shared/schemas/launch.ts';
import type { Settings } from '@shared/schemas/settings.ts';
import { EllipsisTooltipHost } from './components/EllipsisTooltipHost.tsx';
import { Sheet } from './components/Sheet.tsx';
import { applyLanguage, resolveLanguage } from './i18n/index.ts';
import { ipcInvoke, ipcOn } from './ipc.ts';
import { AboutPage } from './pages/about/AboutPage.tsx';
import { CopyMaintenance } from './pages/copies/CopyMaintenance.tsx';
import { useCopyMaintenance } from './pages/copies/useCopyMaintenance.ts';
import { CopyList } from './pages/copies/CopyList.tsx';
import { CopySummary } from './pages/copies/CopySummary.tsx';
import { FeatureStatus } from './pages/copies/FeatureStatus.tsx';
@@ -22,7 +20,6 @@ import { useInstallWizard } from './pages/install/useInstallWizard.ts';
import { WizardMain } from './pages/install/WizardMain.tsx';
import { WizardSide } from './pages/install/WizardSide.tsx';
import { wizardBar } from './pages/install/wizard-bar.ts';
import { ModsPage } from './pages/mods/ModsPage.tsx';
import { TuningPage } from './pages/tuning/TuningPage.tsx';
import { SavesPage } from './pages/saves/SavesPage.tsx';
import { DeveloperSettings } from './pages/settings/DeveloperSettings.tsx';
@@ -33,12 +30,10 @@ import { Background } from './shell/Background.tsx';
import { BottomBar } from './shell/BottomBar.tsx';
import type { BarModel } from './shell/bar-model.ts';
import { Footer } from './shell/Footer.tsx';
import { COPY_SECTIONS, MODS_SECTIONS, navigate, SAVE_SECTIONS, SETTINGS_SECTIONS, START_ROUTE, TUNING_SECTIONS, type Destination, type Route } from './shell/navigation.ts';
import { COPY_SECTIONS, navigate, SAVE_SECTIONS, SETTINGS_SECTIONS, START_ROUTE, TUNING_SECTIONS, type Destination, type Route } from './shell/navigation.ts';
import { SubNav } from './shell/SubNav.tsx';
import { TitleBar } from './shell/TitleBar.tsx';
import { useBackgrounds } from './shell/useBackgrounds.ts';
import { useAppUpdate } from './shell/useAppUpdate.ts';
import { useMapNavPack } from './shell/useMapNavPack.ts';
import { usePatchPack } from './shell/usePatchPack.ts';
import { useErrorMessage } from './useErrorMessage.ts';
@@ -61,8 +56,7 @@ interface View {
*/
export function App({ info, initialSettings, initialCopies }: AppProps) {
const { t } = useTranslation();
const { error, report, clear: clearError } = useErrorMessage();
const [errorPaused, setErrorPaused] = useState(false);
const { message, report } = useErrorMessage();
const [settings, setSettings] = useState(initialSettings);
const [registry, setRegistry] = useState(initialCopies);
const record = registry.copies.find((copy) => copy.id === registry.current) ?? null;
@@ -70,24 +64,14 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
const [route, setRoute] = useState<Route>(START_ROUTE);
// The setting as the window opened: turning it on later does not check right away.
const patchPack = usePatchPack(initialSettings.checkPatchPacksOnStart, report);
const mapNavPack = useMapNavPack(initialSettings.checkPatchPacksOnStart, report);
const appUpdate = useAppUpdate(info.appUpdatesSupported, initialSettings.checkLauncherUpdatesOnStart, report);
const maintenance = useCopyMaintenance(report);
const supported = patchPack.active?.gameVersions ?? info.supportedGameVersions;
const wizard = useInstallWizard({ onInstalled: () => setRoute(START_ROUTE) });
const backgrounds = useBackgrounds(record && !record.folderMissing ? record.copyPath : null, settings, report);
const backgrounds = useBackgrounds(record?.copyPath ?? null, settings, report);
useEffect(() => ipcOn('event:settings-changed', setSettings), []);
useEffect(() => ipcOn('event:copies-changed', setRegistry), []);
useEffect(() => {
const refreshCopies = (): void => {
ipcInvoke('copies:list').then(setRegistry).catch(() => undefined);
};
window.addEventListener('focus', refreshCopies);
return () => window.removeEventListener('focus', refreshCopies);
}, []);
useEffect(() => applyLanguage(resolveLanguage(settings.language, info.systemLocale)), [settings.language, info.systemLocale]);
useEffect(() => {
@@ -103,37 +87,18 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
return () => { mounted = false; dispose(); };
}, [report]);
useEffect(() => {
if (!error || errorPaused) return;
const timer = window.setTimeout(clearError, 6000);
return () => window.clearTimeout(timer);
}, [error, errorPaused, clearError]);
const go = (to: Destination): void => {
clearError();
setRoute((current) => navigate(current, to));
};
const go = (to: Destination): void => setRoute((current) => navigate(current, to));
const selectCopy = (id: string, details = false): void => {
ipcInvoke('copies:setCurrent', { id }).then(() => {
if (details) go({ page: 'copies', section: 'summary' });
}).catch(report);
};
const relocateCopy = (id: string): void => {
clearError();
ipcInvoke('dialog:pickFolder', { title: t('copies.relocateDialogTitle') })
.then(({ path }) => {
if (!path) return;
return ipcInvoke('copies:relocate', { id, path }).then(setRegistry);
})
.catch(report);
};
const perCopyStatus = ['version-changed', 'failed', 'port-busy', 'server-exited', 'game-exited'].includes(launch.phase);
const perCopyStatus = ['version-changed', 'failed', 'port-busy', 'server-exited'].includes(launch.phase);
const launchStatus: LaunchState = perCopyStatus && launch.copyId && launch.copyId !== record?.id ? { phase: 'ready' } : launch;
const home = homeBar(record, launchStatus, t, wizard.start, {
start: () => { ipcInvoke('launch:start').catch(report); },
stop: () => { ipcInvoke('launch:stop').catch(report); },
checkVersion: () => go({ page: 'copies', section: 'features' }),
relocate: () => { if (record) relocateCopy(record.id); },
});
const view = ((): View => {
@@ -154,27 +119,13 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
bar: home,
};
case 'about':
return {
side: homeSide,
main: (
<AboutPage
launcherVersion={info.version}
supportedVersions={supported}
patchPack={patchPack}
mapNavPack={mapNavPack}
appUpdate={appUpdate}
loggingEnabled={settings.loggingEnabled}
onError={report}
/>
),
bar: home,
};
return { side: homeSide, main: <AboutPage launcherVersion={info.version} supportedVersions={supported} patchPack={patchPack} />, bar: home };
case 'settings': {
const sections = SETTINGS_SECTIONS.filter((section) => info.development || section !== 'dev');
const content = {
general: <GeneralSettings settings={settings} appUpdatesSupported={info.appUpdatesSupported} pictures={backgrounds.pictures} onError={report} />,
launch: <LaunchSettings settings={settings} development={info.development} onError={report} />,
diag: <DiagnosticsSettings settings={settings} onError={report} serverRunning={launch.phase === 'running' || launch.phase === 'server-running'} />,
general: <GeneralSettings settings={settings} pictures={backgrounds.pictures} onError={report} />,
launch: <LaunchSettings onError={report} />,
diag: <DiagnosticsSettings onError={report} serverRunning={launch.phase === 'running'} />,
dev: <DeveloperSettings settings={settings} onError={report} />,
};
return {
@@ -187,7 +138,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
return {
side: <SubNav sections={SAVE_SECTIONS} active={route.saves} label={(section) => t(`saves.sections.${section}`)} onSelect={(section) => go({ page: 'saves', section })} />,
main: record
? <SavesPage key={record.id} copy={record} copies={registry.copies} section={route.saves} readOnly={['checking', 'building', 'starting-server', 'starting-game', 'running', 'server-running', 'stopping'].includes(launch.phase)} onError={report} />
? <SavesPage key={record.id} copy={record} copies={registry.copies} section={route.saves} readOnly={['checking', 'building', 'starting-server', 'starting-game', 'running', 'stopping'].includes(launch.phase)} onError={report} />
: <Sheet title={t(`saves.sections.${route.saves}`)}><p className="lead">{t('saves.noCopy')}</p></Sheet>,
bar: home,
};
@@ -199,30 +150,10 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
: <Sheet title={t(`tuning.sections.${route.tuning}`)}><p className="lead">{t('tuning.noCopy')}</p></Sheet>,
bar: home,
};
case 'mods':
return {
side: <SubNav sections={MODS_SECTIONS} active={route.mods} label={(section) => t(`mods.sections.${section}`)} onSelect={(section) => go({ page: 'mods', section })} />,
main: record
? <ModsPage key={record.id} copy={record} section={route.mods} readOnly={['checking', 'building', 'starting-server', 'starting-game', 'running', 'server-running', 'stopping'].includes(launch.phase)} onError={report} />
: <Sheet title={t(`mods.sections.${route.mods}`)}><p className="lead">{t('mods.noCopy')}</p></Sheet>,
bar: home,
};
case 'copies': {
const side = <SubNav sections={COPY_SECTIONS} active={route.copies} label={(section) => t(`copies.sections.${section}`)} onSelect={(section) => go({ page: 'copies', section })} />;
if (route.copies === 'list') {
return {
side,
main: (
<CopyList
registry={registry}
supportedVersions={supported}
onSelect={selectCopy}
onRelocate={relocateCopy}
onAdd={wizard.start}
/>
),
bar: home,
};
return { side, main: <CopyList registry={registry} supportedVersions={supported} onSelect={selectCopy} onAdd={wizard.start} />, bar: home };
}
if (!record) {
return {
@@ -237,19 +168,11 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
};
}
if (route.copies === 'maintain') {
return { side, main: <CopyMaintenance key={record.id} record={record} maintenance={maintenance} onError={report} />, bar: home };
return { side, main: <CopyMaintenance key={record.id} record={record} onError={report} />, bar: home };
}
const main = route.copies === 'features'
? <FeatureStatus record={record} supportedVersions={supported} onError={report} />
: (
<CopySummary
record={record}
supportedVersions={supported}
onShowFeatures={() => go({ page: 'copies', section: 'features' })}
onRelocate={() => relocateCopy(record.id)}
onError={report}
/>
);
: <CopySummary record={record} supportedVersions={supported} onShowFeatures={() => go({ page: 'copies', section: 'features' })} onError={report} />;
return { side, main, bar: home };
}
}
@@ -263,26 +186,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
<aside className="side">{view.side}</aside>
<main className="main">
{view.main}
{error && (
<div
key={error.id}
className="app-error"
role="alert"
onMouseEnter={() => setErrorPaused(true)}
onMouseLeave={() => setErrorPaused(false)}
>
<span className="app-error-text">{error.message}</span>
<button
type="button"
className="app-error-close"
aria-label={t('window.close')}
title={t('window.close')}
onClick={clearError}
>
×
</button>
</div>
)}
{message && <p className="app-error" role="alert">{message}</p>}
</main>
<BottomBar model={view.bar} />
<Footer
@@ -290,10 +194,8 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
gameVersion={record?.gameVersion ?? null}
copyName={record?.name ?? null}
packUpdate={patchPack.check?.status === 'available' ? (patchPack.check.latest?.version ?? null) : null}
appUpdate={appUpdate.check?.status === 'available' ? appUpdate.check.release.version : null}
onOpenUpdates={() => go({ page: 'about' })}
onOpenPackUpdate={() => go({ page: 'about' })}
/>
<EllipsisTooltipHost />
</div>
);
}
@@ -1,110 +0,0 @@
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
interface TooltipState {
readonly text: string;
readonly anchor: DOMRect;
readonly element: HTMLElement;
}
function isTruncated(element: HTMLElement): boolean {
return element.scrollWidth > element.clientWidth + 1 || element.scrollHeight > element.clientHeight + 1;
}
function findTooltipCandidate(start: EventTarget | null): { element: HTMLElement; text: string } | null {
let node = start instanceof Element ? start : null;
while (node && node instanceof HTMLElement) {
const explicit = node.getAttribute('data-ellipsis-tip');
if (explicit !== null) {
const text = explicit.trim();
if (text && (isTruncated(node) || text !== (node.textContent?.trim() ?? ''))) {
return { element: node, text };
}
return null;
}
const style = window.getComputedStyle(node);
if (style.textOverflow === 'ellipsis' && style.overflowX !== 'visible') {
const text = node.textContent?.trim() ?? '';
if (text && isTruncated(node)) {
return { element: node, text };
}
return null;
}
node = node.parentElement;
}
return null;
}
/**
* Window-level tooltip overlay for truncated (ellipsis) text and explicit `data-ellipsis-tip`
* elements. Positioned fixed above the shell so overflow-hidden containers never clip it.
*/
export function EllipsisTooltipHost() {
const [tip, setTip] = useState<TooltipState | null>(null);
const [position, setPosition] = useState<{ left: number; top: number } | null>(null);
const boxRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
const onPointerOver = (event: PointerEvent): void => {
const candidate = findTooltipCandidate(event.target);
if (!candidate) return;
setTip({ text: candidate.text, anchor: candidate.element.getBoundingClientRect(), element: candidate.element });
};
const onPointerOut = (event: PointerEvent): void => {
setTip((current) => {
if (!current) return null;
const related = event.relatedTarget;
if (related instanceof Node && current.element.contains(related)) return current;
return null;
});
};
const clear = (): void => setTip(null);
document.addEventListener('pointerover', onPointerOver, true);
document.addEventListener('pointerout', onPointerOut, true);
document.addEventListener('pointerdown', clear, true);
document.addEventListener('scroll', clear, true);
window.addEventListener('blur', clear);
window.addEventListener('resize', clear);
return () => {
document.removeEventListener('pointerover', onPointerOver, true);
document.removeEventListener('pointerout', onPointerOut, true);
document.removeEventListener('pointerdown', clear, true);
document.removeEventListener('scroll', clear, true);
window.removeEventListener('blur', clear);
window.removeEventListener('resize', clear);
};
}, []);
useLayoutEffect(() => {
if (!tip || !boxRef.current) {
setPosition(null);
return;
}
const margin = 10;
const gap = 8;
const box = boxRef.current.getBoundingClientRect();
const preferredLeft = tip.anchor.left + (tip.anchor.width - box.width) / 2;
const left = Math.max(margin, Math.min(preferredLeft, window.innerWidth - box.width - margin));
const aboveTop = tip.anchor.top - box.height - gap;
const top = aboveTop >= margin
? aboveTop
: Math.min(tip.anchor.bottom + gap, window.innerHeight - box.height - margin);
setPosition({ left, top });
}, [tip]);
if (!tip) return null;
return (
<div
ref={boxRef}
role="tooltip"
className="ellipsis-tooltip"
style={position ? { left: `${position.left}px`, top: `${position.top}px`, visibility: 'visible' } : { left: 0, top: 0, visibility: 'hidden' }}
>
{tip.text}
</div>
);
}
@@ -5,22 +5,16 @@ interface FolderFieldProps {
readonly path: string | null;
/** Title of the folder dialog. */
readonly dialogTitle: string;
/** Optional starting directory when no path is chosen yet. */
readonly defaultPath?: string | null | undefined;
readonly disabled?: boolean;
readonly onChosen: (path: string) => void;
readonly onError: (error: unknown) => void;
}
/** A chosen folder and the button that opens the folder dialog. */
export function FolderField({ path, dialogTitle, defaultPath, disabled = false, onChosen, onError }: FolderFieldProps) {
export function FolderField({ path, dialogTitle, disabled = false, onChosen, onError }: FolderFieldProps) {
const { t } = useTranslation();
const choose = (): void => {
const startPath = path ?? defaultPath;
ipcInvoke('dialog:pickFolder', {
title: dialogTitle,
...(startPath ? { defaultPath: startPath } : {}),
})
ipcInvoke('dialog:pickFolder', { title: dialogTitle })
.then(({ path: chosen }) => {
if (chosen) onChosen(chosen);
})
@@ -1,152 +0,0 @@
import { createElement, Fragment, useMemo, type ReactNode } from 'react';
import { marked, type Token, type Tokens } from 'marked';
const SAFE_EXTERNAL_URL = /^https?:\/\//i;
const HTML_COMMENT = /^<!--[\s\S]*?-->$/;
function isSafeExternalUrl(href: string | undefined): href is string {
return typeof href === 'string' && SAFE_EXTERNAL_URL.test(href.trim());
}
function renderInline(tokens: readonly Token[], keyPrefix: string): ReactNode {
return tokens.map((token, index) => renderInlineToken(token, `${keyPrefix}-${index}`));
}
function renderInlineToken(token: Token, key: string): ReactNode {
switch (token.type) {
case 'text': {
const textToken = token as Tokens.Text;
if (textToken.tokens?.length) return <Fragment key={key}>{renderInline(textToken.tokens, key)}</Fragment>;
return <Fragment key={key}>{textToken.text}</Fragment>;
}
case 'escape':
return <Fragment key={key}>{(token as Tokens.Escape).text}</Fragment>;
case 'strong':
return <strong key={key}>{renderInline((token as Tokens.Strong).tokens, key)}</strong>;
case 'em':
return <em key={key}>{renderInline((token as Tokens.Em).tokens, key)}</em>;
case 'del':
return <del key={key}>{renderInline((token as Tokens.Del).tokens, key)}</del>;
case 'codespan':
return <code key={key}>{(token as Tokens.Codespan).text}</code>;
case 'br':
return <br key={key} />;
case 'link': {
const link = token as Tokens.Link;
const content = link.tokens.length ? renderInline(link.tokens, key) : link.text;
if (!isSafeExternalUrl(link.href)) return <Fragment key={key}>{content}</Fragment>;
return (
<a key={key} href={link.href} title={link.title ?? undefined} target="_blank" rel="noreferrer">
{content}
</a>
);
}
case 'image':
return <Fragment key={key}>{(token as Tokens.Image).text}</Fragment>;
case 'html': {
const raw = (token as Tokens.HTML).text.trim();
if (!raw || HTML_COMMENT.test(raw)) return null;
return <Fragment key={key}>{raw}</Fragment>;
}
default:
return 'raw' in token && typeof token.raw === 'string' ? <Fragment key={key}>{token.raw}</Fragment> : null;
}
}
function renderTable(table: Tokens.Table, key: string): ReactNode {
return (
<div key={key} className="markdown-table-wrap">
<table>
<thead>
<tr>
{table.header.map((cell, column) => (
<th key={`${key}-h-${column}`} style={cell.align ? { textAlign: cell.align } : undefined}>
{renderInline(cell.tokens, `${key}-h-${column}`)}
</th>
))}
</tr>
</thead>
<tbody>
{table.rows.map((row, rowIndex) => (
<tr key={`${key}-r-${rowIndex}`}>
{row.map((cell, column) => (
<td key={`${key}-r-${rowIndex}-${column}`} style={cell.align ? { textAlign: cell.align } : undefined}>
{renderInline(cell.tokens, `${key}-r-${rowIndex}-${column}`)}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
);
}
function renderListItem(item: Tokens.ListItem, key: string): ReactNode {
return (
<li key={key}>
{item.task && <input type="checkbox" checked={Boolean(item.checked)} disabled readOnly className="markdown-task" />}
{renderBlocks(item.tokens, key)}
</li>
);
}
function renderBlock(token: Token, key: string): ReactNode {
switch (token.type) {
case 'space':
case 'def':
case 'checkbox':
return null;
case 'heading': {
const heading = token as Tokens.Heading;
const level = Math.min(6, Math.max(1, heading.depth));
return createElement(`h${level}`, { key }, renderInline(heading.tokens, key));
}
case 'paragraph':
return <p key={key}>{renderInline((token as Tokens.Paragraph).tokens, key)}</p>;
case 'text': {
const textToken = token as Tokens.Text;
if (textToken.tokens?.length) return <Fragment key={key}>{renderInline(textToken.tokens, key)}</Fragment>;
return <Fragment key={key}>{textToken.text}</Fragment>;
}
case 'blockquote':
return <blockquote key={key}>{renderBlocks((token as Tokens.Blockquote).tokens, key)}</blockquote>;
case 'list': {
const list = token as Tokens.List;
const items = list.items.map((item, index) => renderListItem(item, `${key}-i-${index}`));
if (list.ordered) {
return <ol key={key} start={typeof list.start === 'number' && list.start !== 1 ? list.start : undefined}>{items}</ol>;
}
return <ul key={key}>{items}</ul>;
}
case 'code':
return (
<pre key={key}>
<code>{(token as Tokens.Code).text}</code>
</pre>
);
case 'hr':
return <hr key={key} />;
case 'table':
return renderTable(token as Tokens.Table, key);
case 'html': {
const raw = (token as Tokens.HTML).text.trim();
if (!raw || HTML_COMMENT.test(raw)) return null;
return <p key={key}>{raw}</p>;
}
default:
return 'raw' in token && typeof token.raw === 'string' && token.raw.trim()
? <p key={key}>{token.raw}</p>
: null;
}
}
function renderBlocks(tokens: readonly Token[], keyPrefix: string): ReactNode {
return tokens.map((token, index) => renderBlock(token, `${keyPrefix}-${index}`));
}
/** Safe React renderer for GFM Markdown without injecting raw HTML. */
export function MarkdownContent({ markdown }: { readonly markdown: string }) {
const tokens = useMemo(() => marked.lexer(markdown, { gfm: true, breaks: false }), [markdown]);
return <div className="markdown-body">{renderBlocks(tokens, 'md')}</div>;
}
@@ -1,36 +0,0 @@
interface WordmarkProps {
readonly className?: string;
}
/**
* The WTOffline wordmark (from assets/wordmark.svg), rendered with currentColor so it stays
* crisp white over the launcher's dark crimson title bar regardless of OS light/dark mode.
*/
export function Wordmark({ className }: WordmarkProps) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 396 206"
className={className}
role="img"
aria-label="WTOffline"
>
<g fill="currentColor" fillRule="evenodd">
<path d="M62 8H101L112 72L124 24H154L166 72L178 8H214L189 123H153L139 83L124 123H88ZM220 8H337V33L329 42H297V123H251V42H214V15Z" />
<g>
<path d="M13 60H53V68H22ZM31 74H53V82H40Z" />
<path transform="translate(396) scale(-1 1)" d="M13 60H53V68H22ZM31 74H53V82H40Z" />
</g>
<g transform="translate(14 134)">
<path transform="translate(0)" d="M9 0H48L57 9V55L48 64H9L0 55V9ZM17 12L14 15V49L17 52H40L43 49V15L40 12Z" />
<path transform="translate(65)" d="M0 0H50V12H14V27H42V39H14V64H0Z" />
<path transform="translate(123)" d="M0 0H50V12H14V27H42V39H14V64H0Z" />
<path transform="translate(181)" d="M0 0H14V52H45V64H0Z" />
<path transform="translate(234)" d="M0 0H14V64H0Z" />
<path transform="translate(256)" d="M0 0H12L41 39V0H55V64H43L14 25V64H0Z" />
<path transform="translate(319)" d="M0 0H49V12H14V26H43V38H14V52H49V64H0Z" />
</g>
</g>
</svg>
);
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,29 +1,17 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Notice } from '../../components/Notice.tsx';
import { Row } from '../../components/Row.tsx';
import { Sheet } from '../../components/Sheet.tsx';
import { ipcInvoke } from '../../ipc.ts';
import type { AppUpdateState } from '../../shell/useAppUpdate.ts';
import { AppUpdateSection } from './AppUpdateSection.tsx';
import type { PatchPackState } from '../../shell/usePatchPack.ts';
import type { MapNavPackState } from '../../shell/useMapNavPack.ts';
import { MapNavPackSection } from './MapNavPackSection.tsx';
const HOMEPAGE_URL = 'https://wto-project.net';
const DISCORD_INVITE_URL = 'https://discord.gg/P566xWNpEs';
interface AboutPageProps {
readonly launcherVersion: string;
readonly supportedVersions: readonly string[];
readonly patchPack: PatchPackState;
readonly mapNavPack: MapNavPackState;
readonly appUpdate: AppUpdateState;
readonly loggingEnabled: boolean;
readonly onError: (error: unknown) => void;
}
/** The launcher's version, the game versions it supports, updates, community links, log export, and the project statement. */
export function AboutPage({ launcherVersion, supportedVersions, patchPack, mapNavPack, appUpdate, loggingEnabled, onError }: AboutPageProps) {
/** The launcher's version, the game versions it supports, adaptation pack updates, and the project statement. */
export function AboutPage({ launcherVersion, supportedVersions, patchPack }: AboutPageProps) {
const { t } = useTranslation();
return (
<Sheet title={t('nav.about')}>
@@ -35,98 +23,13 @@ export function AboutPage({ launcherVersion, supportedVersions, patchPack, mapNa
{t('about.supported', { versions: supportedVersions.join(', ') })}
</div>
</div>
<div className="about-columns">
<div className="about-column">
<AppUpdateSection state={appUpdate} />
<PatchPackSection state={patchPack} />
<MapNavPackSection state={mapNavPack} />
</div>
<div className="about-column">
<HomepageSection />
<CommunitySection />
<FeedbackLogsSection loggingEnabled={loggingEnabled} onError={onError} />
<section className="about-card">
<h3 className="about-card-title">{t('about.statement')}</h3>
<p className="about-card-meta">{t('about.statementBody')}</p>
</section>
</div>
</div>
<PatchPackSection state={patchPack} />
<h3 className="section-title section-title-spaced">{t('about.statement')}</h3>
<p className="lead">{t('about.statementBody')}</p>
</Sheet>
);
}
function HomepageSection() {
const { t } = useTranslation();
return (
<section className="about-card">
<div className="about-card-head">
<h3 className="about-card-title">{t('about.homepage.title')}</h3>
<div className="about-card-actions">
<a className="button" href={HOMEPAGE_URL} target="_blank" rel="noreferrer">
{t('about.homepage.open')}
</a>
</div>
</div>
<p className="about-card-meta">{t('about.homepage.hint')}</p>
</section>
);
}
function CommunitySection() {
const { t } = useTranslation();
return (
<section className="about-card">
<div className="about-card-head">
<h3 className="about-card-title">{t('about.community.discord')}</h3>
<div className="about-card-actions">
<a className="button" href={DISCORD_INVITE_URL} target="_blank" rel="noreferrer">
{t('about.community.openDiscord')}
</a>
</div>
</div>
<p className="about-card-meta">{t('about.community.discordHint')}</p>
</section>
);
}
function FeedbackLogsSection({ loggingEnabled, onError }: {
readonly loggingEnabled: boolean;
readonly onError: (error: unknown) => void;
}) {
const { t } = useTranslation();
const [exporting, setExporting] = useState(false);
const [savedPath, setSavedPath] = useState<string | null>(null);
async function save(): Promise<void> {
setExporting(true);
setSavedPath(null);
try {
const result = await ipcInvoke('app:exportDiagnostics');
setSavedPath(result.path);
} catch (error) {
onError(error);
} finally {
setExporting(false);
}
}
return (
<section className="about-card">
<div className="about-card-head">
<h3 className="about-card-title">{t('about.feedback.title')}</h3>
<div className="about-card-actions">
<button type="button" className="button" disabled={exporting} onClick={() => { void save(); }}>
{t('about.feedback.exportButton')}
</button>
</div>
</div>
<p className="about-card-meta">{t('about.feedback.exportHint')}</p>
{!loggingEnabled && <p className="small">{t('settings.diagnostics.loggingDisabledNotice')}</p>}
{savedPath && <p className="small" role="status">{t('settings.diagnostics.saved', { path: savedPath })}</p>}
</section>
);
}
function PatchPackSection({ state }: { readonly state: PatchPackState }) {
const { t } = useTranslation();
const { active, check, busy } = state;
@@ -138,30 +41,25 @@ function PatchPackSection({ state }: { readonly state: PatchPackState }) {
? t('about.pack.bundledVersion', { version: active.version })
: t('about.pack.bundled');
return (
<section className="about-card">
<div className="about-card-head">
<h3 className="about-card-title">{t('about.pack.title')}</h3>
<div className="about-card-actions">
<button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}>
{busy === 'checking' ? t('about.pack.checking') : t('about.pack.checkButton')}
<>
<h3 className="section-title">{t('about.pack.title')}</h3>
<Row label={t('about.pack.current')} hint={t('about.pack.currentHint')}>
<span>{current}</span>
{active?.source === 'downloaded' && (
<button type="button" className="button" disabled={busy !== null} onClick={state.useBundled}>
{t('about.pack.useBundled')}
</button>
{active?.source === 'downloaded' && (
<button type="button" className="button" disabled={busy !== null} onClick={state.useBundled}>
{t('about.pack.useBundled')}
</button>
)}
</div>
</div>
<p className="about-card-meta">
<span className="about-card-label">{t('about.pack.current')}</span>
{' · '}
{current}
</p>
<p className="small">{t('about.pack.currentHint')}</p>
)}
</Row>
<Row label={t('about.pack.check')} hint={t('about.pack.checkHint')}>
<button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}>
{busy === 'checking' ? t('about.pack.checking') : t('about.pack.checkButton')}
</button>
</Row>
{busy === 'applying' && <p className="small">{t('about.pack.applying')}</p>}
{state.applyFailure && <Notice tone="error"><p>{t(`about.pack.applyFailed.${state.applyFailure}`)}</p></Notice>}
{check && busy !== 'checking' && <CheckResult state={state} />}
</section>
</>
);
}
@@ -1,72 +0,0 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Notice } from '../../components/Notice.tsx';
import { ProgressBar } from '../../components/ProgressBar.tsx';
import { formatBytes } from '../../format.ts';
import type { AppUpdateState } from '../../shell/useAppUpdate.ts';
import { ReleaseNotesModal } from './ReleaseNotesModal.tsx';
export function AppUpdateSection({ state }: { readonly state: AppUpdateState }) {
const { t } = useTranslation();
const [notesOpen, setNotesOpen] = useState(false);
if (!state.supported) return null;
const { check, busy, progress } = state;
const available = check?.status === 'available' && busy !== 'checking' ? check : null;
const notes = available?.release.notes.trim() ?? '';
return (
<section className="about-card">
<div className="about-card-head">
<h3 className="about-card-title">{t('about.update.title')}</h3>
<div className="about-card-actions">
<button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}>
{t(busy === 'checking' ? 'about.update.checking' : 'about.pack.checkButton')}
</button>
</div>
</div>
<p className="about-card-meta">{t('about.update.check')}</p>
{check?.status === 'current' && busy !== 'checking' && <Notice tone="info"><p>{t('about.update.current')}</p></Notice>}
{check?.status === 'failed' && busy !== 'checking' && <Notice tone="error"><p>{t(`about.update.errors.${check.problem}`)}</p></Notice>}
{available && (
<Notice tone="info">
<p>{t('about.update.available', { version: available.release.version, size: formatBytes(available.release.size) })}</p>
{busy === 'downloading' && (
<>
<p>{t('about.update.downloading')}</p>
<ProgressBar value={progress?.received ?? 0} max={progress?.total ?? null} />
</>
)}
{(busy !== 'downloading' || notes) && (
<div className="update-actions">
{busy !== 'downloading' && (
<button
type="button"
className="button button-primary"
disabled={busy !== null}
onClick={() => {
if (available.ready) state.install(available.release.version);
else state.download(available.release.version);
}}
>
{t(busy === 'installing' ? 'about.update.installing' : available.ready ? 'about.update.install' : 'about.update.download')}
</button>
)}
{notes && (
<button type="button" className="button button-compact" onClick={() => setNotesOpen(true)}>
{t('about.update.viewNotes')}
</button>
)}
</div>
)}
</Notice>
)}
{notesOpen && available && notes && (
<ReleaseNotesModal
version={available.release.version}
notes={notes}
onClose={() => setNotesOpen(false)}
/>
)}
</section>
);
}
@@ -1,66 +0,0 @@
import { useTranslation } from 'react-i18next';
import { Notice } from '../../components/Notice.tsx';
import { ProgressBar } from '../../components/ProgressBar.tsx';
import { formatBytes } from '../../format.ts';
import type { MapNavPackState } from '../../shell/useMapNavPack.ts';
export function MapNavPackSection({ state }: { readonly state: MapNavPackState }) {
const { t } = useTranslation();
const { active, busy, check, progress } = state;
const latest = check?.latest;
return (
<section className="about-card">
<div className="about-card-head">
<h3 className="about-card-title">{t('about.mapNav.title')}</h3>
<div className="about-card-actions">
<button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}>
{t(busy === 'checking' ? 'about.pack.checking' : 'about.pack.checkButton')}
</button>
{active?.source === 'downloaded' && (
<button type="button" className="button" disabled={busy !== null} onClick={state.deactivate}>
{t('about.mapNav.deactivate')}
</button>
)}
</div>
</div>
<p className="about-card-meta">
<span className="about-card-label">{t('about.pack.current')}</span>
{' · '}
{active === undefined ? '…' : active === null ? t('about.mapNav.missing') : [
t('about.mapNav.source.' + active.source), active.version,
t('about.mapNav.mapCount', { count: active.mapCount }),
].filter(Boolean).join(' · ')}
</p>
<p className="small">{t('about.mapNav.hint')}</p>
{busy === 'applying' && (
<div role="status">
<p className="small">
{t(progress?.total && progress.received >= progress.total ? 'about.mapNav.installing' : 'about.mapNav.downloading')}
</p>
<ProgressBar value={progress?.received ?? 0} max={progress?.total ?? null} />
</div>
)}
{state.failure && <Notice tone="error"><p>{t('about.pack.applyFailed.' + state.failure)}</p></Notice>}
{busy !== 'checking' && check?.status === 'failed' && (
<Notice tone="error"><p>{t('about.pack.checkFailed.' + (check.problem ?? 'contents'))}</p></Notice>
)}
{busy !== 'checking' && check?.status === 'up_to_date' && (
<Notice tone="info"><p>{latest ? t('about.mapNav.upToDate', { version: latest.version }) : t('about.mapNav.noneReleased')}</p></Notice>
)}
{busy !== 'checking' && check?.status === 'needs_app_update' && latest && (
<Notice tone="warning"><p>{t('about.pack.needsAppUpdate', { version: latest.version, app: latest.minAppVersion })}</p></Notice>
)}
{busy !== 'checking' && check?.status === 'available' && latest && (
<Notice tone="info">
<p>{t('about.mapNav.available', { version: latest.version, count: latest.mapCount, size: formatBytes(latest.size) })}</p>
<p className="small">{t('about.mapNav.compatible', { versions: latest.gameVersions.join(', ') })}</p>
{busy !== 'applying' && (
<button type="button" className="button button-primary" disabled={busy !== null} onClick={() => state.apply(latest.version)}>
{t('about.pack.apply', { version: latest.version })}
</button>
)}
</Notice>
)}
</section>
);
}
@@ -1,57 +0,0 @@
import { useEffect, useId } from 'react';
import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
import { MarkdownContent } from '../../components/MarkdownContent.tsx';
interface ReleaseNotesModalProps {
readonly version: string;
readonly notes: string;
readonly onClose: () => void;
}
/** Standalone dialog displaying rendered Markdown release notes for an available launcher update. */
export function ReleaseNotesModal({ version, notes, onClose }: ReleaseNotesModalProps) {
const { t } = useTranslation();
const titleId = useId();
useEffect(() => {
const onKeyDown = (event: KeyboardEvent): void => {
if (event.key === 'Escape') onClose();
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
}, [onClose]);
return createPortal(
<div
className="modal-backdrop"
role="presentation"
onClick={(event) => {
if (event.target === event.currentTarget) onClose();
}}
>
<div className="modal-dialog" role="dialog" aria-modal="true" aria-labelledby={titleId}>
<header className="modal-head">
<h3 id={titleId} className="modal-title">{t('about.update.notesTitle', { version })}</h3>
<button
type="button"
className="modal-close"
aria-label={t('about.update.closeNotes')}
onClick={onClose}
>
×
</button>
</header>
<div className="modal-body">
<MarkdownContent markdown={notes} />
</div>
<footer className="modal-foot">
<button type="button" className="button" onClick={onClose}>
{t('about.update.closeNotes')}
</button>
</footer>
</div>
</div>,
document.body,
);
}
@@ -7,11 +7,10 @@ interface CopyListProps {
readonly registry: Copies;
readonly supportedVersions: readonly string[];
readonly onSelect: (id: string, detail?: boolean) => void;
readonly onRelocate: (id: string) => void;
readonly onAdd: () => void;
}
export function CopyList({ registry, supportedVersions, onSelect, onRelocate, onAdd }: CopyListProps) {
export function CopyList({ registry, supportedVersions, onSelect, onAdd }: CopyListProps) {
const { t } = useTranslation();
return (
<Sheet title={t('copies.sections.list')}>
@@ -25,7 +24,6 @@ export function CopyList({ registry, supportedVersions, onSelect, onRelocate, on
<div className="copy-list-heading">
<strong>{copy.name}</strong>
{current && <span className="ok">{t('copies.list.current')}</span>}
{copy.folderMissing && <span className="warn">{t('copies.missingFolder')}</span>}
</div>
<dl className="kv">
<dt>{t('copies.summary.version')}</dt>
@@ -37,17 +35,10 @@ export function CopyList({ registry, supportedVersions, onSelect, onRelocate, on
: <span className="warn">{t('adaptation.unverified')}</span>}
</dd>
<dt>{t('copies.summary.location')}</dt>
<dd className="folder-path" data-ellipsis-tip={copy.copyPath}>{copy.copyPath}</dd>
<dd className="folder-path" title={copy.copyPath}>{copy.copyPath}</dd>
</dl>
<div className="copy-list-actions">
{copy.folderMissing && (
<button type="button" className="button button-primary" onClick={() => onRelocate(copy.id)}>{t('copies.relocate')}</button>
)}
{!current && (
<button type="button" className={copy.folderMissing ? 'button' : 'button button-primary'} onClick={() => onSelect(copy.id)}>
{t('copies.list.select')}
</button>
)}
{!current && <button type="button" className="button button-primary" onClick={() => onSelect(copy.id)}>{t('copies.list.select')}</button>}
<button type="button" className="button" onClick={() => onSelect(copy.id, true)}>{t('side.details')}</button>
</div>
</article>
@@ -1,95 +1,113 @@
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { InstallRecord } from '@shared/schemas/install.ts';
import type { MaintenanceInfo, MaintenanceProgress } from '@shared/schemas/maintenance.ts';
import type { MaintenanceInfo, MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts';
import { ProgressBar } from '../../components/ProgressBar.tsx';
import { Row } from '../../components/Row.tsx';
import { Sheet } from '../../components/Sheet.tsx';
import { formatBytes } from '../../format.ts';
import { ipcInvoke } from '../../ipc.ts';
import { CopyMaintenanceActions, CopyRemoval, type CopyRemovalOptions } from './CopyMaintenanceControls.tsx';
import type { CopyMaintenanceState, MaintenanceOperation, MaintenanceOptions } from './useCopyMaintenance.ts';
import { AppIpcError, ipcInvoke, ipcOn } from '../../ipc.ts';
interface CopyMaintenanceProps {
readonly record: InstallRecord;
readonly maintenance: CopyMaintenanceState;
readonly onError: (error: unknown) => void;
}
export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanceProps) {
const { t } = useTranslation();
const [info, setInfo] = useState<MaintenanceInfo | null>(null);
const [removal, setRemoval] = useState<CopyRemovalOptions | null>(null);
type Operation = MaintenanceRequest['operation'];
useEffect(() => {
setRemoval(null);
}, [record.id]);
export function CopyMaintenance({ record, onError }: CopyMaintenanceProps) {
const { t, i18n } = useTranslation();
const [info, setInfo] = useState<MaintenanceInfo | null>(null);
const [working, setWorking] = useState<Operation | null>(null);
const [progress, setProgress] = useState<MaintenanceProgress | null>(null);
const [confirming, setConfirming] = useState(false);
const [deleteData, setDeleteData] = useState(false);
const [result, setResult] = useState<Operation | 'cancelled' | null>(null);
useEffect(() => {
let mounted = true;
setInfo(null);
ipcInvoke('copies:maintenanceInfo', { id: record.id }).then((value) => {
if (mounted) setInfo(value);
}).catch(onError);
return () => { mounted = false; };
}, [record.id, record.gameVersion, record.sourcePath, record.steamLibraryConfirmation, maintenance.revision, onError]);
}, [record.id, record.gameVersion, onError]);
const run = (operation: MaintenanceOperation, options: MaintenanceOptions = {}): void => {
if (operation === 'delete') setRemoval(null);
maintenance.run(record.id, operation, options);
useEffect(() => ipcOn('event:copy-maintenance', (event) => {
if (event.id === record.id) setProgress(event);
}), [record.id]);
const run = (operation: Operation): void => {
setResult(null);
setWorking(operation);
setProgress(null);
ipcInvoke('copies:maintain', { id: record.id, operation, deleteData: operation === 'delete' && deleteData })
.then(() => {
setResult(operation);
setConfirming(false);
})
.catch((error: unknown) => {
if (error instanceof AppIpcError && error.code === 'maintenance_cancelled') setResult('cancelled');
else onError(error);
})
.finally(() => setWorking(null));
};
const chooseUpdateSource = (): void => {
ipcInvoke('dialog:pickFolder', { title: t('copies.maintenance.chooseSource') }).then(({ path }) => {
if (path) run('set-source', { sourcePath: path });
}).catch(onError);
};
const active = maintenance.active;
const busy = active !== null;
const result = maintenance.lastResult?.copyId === record.id ? maintenance.lastResult.outcome : null;
return (
<Sheet title={t('copies.sections.maintain')} aside={record.name}>
<CopyMaintenanceActions
record={record}
info={info}
busy={busy}
onRun={run}
onChooseSource={chooseUpdateSource}
onConfirmSteam={(steamLocations) => run('confirm-steam', { steamLocations })}
/>
<CopyRemoval
record={record}
info={info}
busy={busy}
options={removal}
onOptionsChange={setRemoval}
onRemove={(options) => run('delete', options)}
onOpenFolder={() => { ipcInvoke('app:openFolder', { path: record.copyPath }).catch(onError); }}
/>
{active && <MaintenanceStatus progress={active} onCancel={maintenance.cancel} />}
<Row label={t('copies.maintenance.update')} hint={info?.sourceVersion
? t(info.updateAvailable ? 'copies.maintenance.newVersion' : 'copies.maintenance.currentVersion', { version: info.sourceVersion })
: t('copies.maintenance.noSource')}>
<button type="button" className={info?.updateAvailable ? 'button button-primary' : 'button'}
disabled={working !== null || !info?.updateAvailable} onClick={() => run('update')}>
{t('copies.maintenance.updateAction')}
</button>
</Row>
<Row label={t('copies.maintenance.check')} hint={record.lastCheckedAt
? t('copies.maintenance.lastCheck', { date: new Date(record.lastCheckedAt).toLocaleString(i18n.language) })
: t('copies.maintenance.checkHint')}>
<button type="button" className="button" disabled={working !== null} onClick={() => run('check')}>
{t('copies.maintenance.check')}
</button>
</Row>
<Row label={t('copies.maintenance.repair')} hint={t('copies.maintenance.repairHint')}>
<button type="button" className="button" disabled={working !== null} onClick={() => run('repair')}>
{t('copies.maintenance.repairAction')}
</button>
</Row>
<Row label={t('copies.maintenance.delete')} hint={t('copies.maintenance.deleteHint')}>
<button type="button" className="button" disabled={working !== null} onClick={() => {
setConfirming(true);
setDeleteData(false);
}}>{t('copies.maintenance.deleteAction')}</button>
</Row>
{confirming && (
<section className="maintenance-confirm" role="group" aria-label={t('copies.maintenance.confirm')}>
<p>{t('copies.maintenance.deleteLocation', { path: record.copyPath })}</p>
<label className="check">
<input type="checkbox" checked={deleteData} disabled={working !== null} onChange={(event) => setDeleteData(event.target.checked)} />
{t('copies.maintenance.deleteData', { path: record.dataPath })}
</label>
<div className="copy-list-actions">
<button type="button" className="button" disabled={working !== null} onClick={() => setConfirming(false)}>{t('wizard.cancel')}</button>
<button type="button" className="button button-primary" disabled={working !== null} onClick={() => run('delete')}>
{t('copies.maintenance.confirm')}
</button>
</div>
</section>
)}
{working && (
<div className="maintenance-progress" role="status">
<p>{t(`copies.maintenance.phase.${progress?.phase ?? 'checking'}`)}</p>
<ProgressBar value={progress?.doneBytes ?? 0} max={progress?.totalBytes || null} />
{progress?.totalBytes ? <p className="small">{formatBytes(progress.doneBytes)} / {formatBytes(progress.totalBytes)}</p> : null}
{working === 'update' && progress?.phase !== 'applying' && (
<button type="button" className="button" onClick={() => ipcInvoke('copies:cancelMaintenance').catch(onError)}>
{t('wizard.cancel')}
</button>
)}
</div>
)}
{result && <p className="small" role="status">{t(`copies.maintenance.result.${result}`)}</p>}
</Sheet>
);
}
interface MaintenanceStatusProps {
readonly progress: MaintenanceProgress;
readonly onCancel: () => void;
}
function MaintenanceStatus({ progress, onCancel }: MaintenanceStatusProps) {
const { t } = useTranslation();
return (
<div className="maintenance-progress" role="status">
<p>{t(`copies.maintenance.phase.${progress.phase}`)}</p>
<ProgressBar value={progress.doneBytes} max={progress.totalBytes || null} />
{progress.totalBytes ? <p className="small">{formatBytes(progress.doneBytes)} / {formatBytes(progress.totalBytes)}</p> : null}
{(progress.operation === 'update' || progress.operation === 'compact') && progress.phase !== 'applying' && (
<button type="button" className="button" onClick={onCancel}>
{t('wizard.cancel')}
</button>
)}
</div>
);
}
@@ -1,185 +0,0 @@
import { useTranslation } from 'react-i18next';
import type { InstallRecord } from '@shared/schemas/install.ts';
import type { MaintenanceInfo, MaintenanceRequest } from '@shared/schemas/maintenance.ts';
import { Notice } from '../../components/Notice.tsx';
import { Row } from '../../components/Row.tsx';
interface CopyMaintenanceControlsProps {
readonly record: InstallRecord;
readonly info: MaintenanceInfo | null;
readonly busy: boolean;
}
interface CopyMaintenanceActionsProps extends CopyMaintenanceControlsProps {
readonly onRun: (operation: 'update' | 'compact' | 'check' | 'repair') => void;
readonly onChooseSource: () => void;
readonly onConfirmSteam: (locations: NonNullable<MaintenanceRequest['steamLocations']>) => void;
}
export function CopyMaintenanceActions({ record, info, busy, onRun, onChooseSource, onConfirmSteam }: CopyMaintenanceActionsProps) {
const { t, i18n } = useTranslation();
const steam = info?.steamLocations;
const updateHint = info?.sourceVersion
? t(info.updateAvailable
? (record.hardlinkedFiles?.length
? (info.updatePreservesSpaceSaving ? 'copies.maintenance.updateKeepsSpaceSaving' : 'copies.maintenance.updateDetaches')
: 'copies.maintenance.newVersion')
: 'copies.maintenance.currentVersion', { version: info.sourceVersion })
: t(record.sourcePath ? (info ? 'copies.maintenance.noSource' : 'copies.maintenance.phase.checking') : 'copies.maintenance.sourceNotSet');
return (
<>
{info?.steamConfirmationRequired && steam && (
<Notice tone="warning">
<p>{t('steam.maintenanceWarning')}</p>
<p className="small">{steam.copyPath}<br />{steam.dataPath}</p>
<button type="button" className="button" disabled={busy}
onClick={() => onConfirmSteam({ copyPath: steam.copyPath, dataPath: steam.dataPath })}>
{t('steam.confirmLocations')}
</button>
</Notice>
)}
<Row label={t('copies.maintenance.update')} hint={record.sourcePath ? <>{record.sourcePath}<br />{updateHint}</> : updateHint}>
<button type="button" className="button" disabled={busy} onClick={onChooseSource}>
{t(record.sourcePath ? 'copies.maintenance.changeSource' : 'copies.maintenance.setSource')}
</button>
<button type="button" className={info?.updateAvailable ? 'button button-primary' : 'button'}
disabled={busy || !info?.updateAvailable} onClick={() => onRun('update')}>
{t('copies.maintenance.updateAction')}
</button>
</Row>
<Row label={t('copies.maintenance.spaceSaving')} hint={info?.spaceSavingAvailable
? t('copies.maintenance.spaceSavingHint') : t('copies.maintenance.spaceSavingUnavailable')}>
<button type="button" className="button" disabled={busy || !info?.spaceSavingAvailable}
onClick={() => onRun('compact')}>{t('copies.maintenance.compactAction')}</button>
</Row>
<Row label={t('copies.maintenance.check')} hint={record.lastCheckedAt
? t('copies.maintenance.lastCheck', { date: new Date(record.lastCheckedAt).toLocaleString(i18n.language) })
: t('copies.maintenance.checkHint')}>
<button type="button" className="button" disabled={busy} onClick={() => onRun('check')}>
{t('copies.maintenance.check')}
</button>
</Row>
<Row label={t('copies.maintenance.repair')} hint={t('copies.maintenance.repairHint')}>
<button type="button" className="button" disabled={busy} onClick={() => onRun('repair')}>
{t('copies.maintenance.repairAction')}
</button>
</Row>
</>
);
}
export interface CopyRemovalOptions {
readonly deleteFiles: boolean;
readonly restoreStock: boolean;
readonly deleteData: boolean;
}
interface CopyRemovalProps extends CopyMaintenanceControlsProps {
readonly options: CopyRemovalOptions | null;
readonly onOptionsChange: (options: CopyRemovalOptions | null) => void;
readonly onRemove: (options: CopyRemovalOptions) => void;
readonly onOpenFolder: () => void;
}
function clientOriginNoteKey(info: MaintenanceInfo): string {
if (info.clientOrigin === 'copy') return 'copies.maintenance.originCopy';
if (info.clientOrigin === 'hardlink') return 'copies.maintenance.originHardlink';
if (info.clientOrigin === 'in-place') return 'copies.maintenance.originInPlace';
return info.hasHardlinkedResources
? 'copies.maintenance.originUnknownHardlinked'
: 'copies.maintenance.originUnknown';
}
export function CopyRemoval({ record, info, busy, options, onOptionsChange, onRemove, onOpenFolder }: CopyRemovalProps) {
const { t } = useTranslation();
const steam = info?.steamLocations;
const copyInSteam = steam?.copyInSteam === true;
const dataInSteam = steam?.dataInSteam === true;
const canDeleteFiles = info?.canDeleteFiles === true;
const isHardlinkCopy = info?.clientOrigin === 'hardlink';
const canRestoreAndRemove = info !== null && !canDeleteFiles && info.canRestoreAndRemove;
const canDeleteData = info !== null && !copyInSteam && !dataInSteam;
const willDeleteFiles = canDeleteFiles && options?.deleteFiles === true;
const willRestoreStock = canRestoreAndRemove && options?.restoreStock === true;
const willDeleteData = canDeleteData && options?.deleteData === true;
const action = t(
willDeleteFiles || willDeleteData
? 'copies.maintenance.confirmDelete'
: willRestoreStock
? 'copies.maintenance.confirmRestore'
: 'copies.maintenance.confirmRemove',
);
const rowHint = copyInSteam
? t('copies.maintenance.removeSteamHint')
: canDeleteFiles
? t('copies.maintenance.removeCopyHint')
: canRestoreAndRemove
? t('copies.maintenance.removeRestoreHint')
: t('copies.maintenance.removeUnlinkHint');
const confirmNotice = copyInSteam
? t('copies.maintenance.removeSteamNotice', { path: steam?.copyPath ?? record.copyPath })
: canDeleteFiles
? t('copies.maintenance.removeCopyNotice', { path: record.copyPath })
: t('copies.maintenance.removeListOnlyNotice', { path: record.copyPath });
return (
<>
<Row label={t('copies.maintenance.remove')} hint={rowHint}>
<button type="button" className="button" disabled={busy}
onClick={() => onOptionsChange({ deleteFiles: false, restoreStock: false, deleteData: false })}>
{t('copies.maintenance.removeAction')}
</button>
</Row>
{options && (
<section className="maintenance-confirm" role="group" aria-label={action}>
<p>{confirmNotice}</p>
{info && <p className="small">{t(clientOriginNoteKey(info))}</p>}
{canDeleteFiles && (
<>
<label className="check">
<input type="checkbox" checked={options.deleteFiles} disabled={busy}
onChange={(event) => onOptionsChange({ ...options, deleteFiles: event.target.checked, restoreStock: false })} />
{t('copies.maintenance.deleteFiles', { path: record.copyPath })}
</label>
{isHardlinkCopy && <p className="small">{t('copies.maintenance.deleteHardlinkHint')}</p>}
</>
)}
{willDeleteFiles && (
<Notice tone="warning">
<p>{t(isHardlinkCopy ? 'copies.maintenance.deleteHardlinkWarning' : 'copies.maintenance.deleteFilesWarning', { path: record.copyPath })}</p>
</Notice>
)}
{canRestoreAndRemove && (
<>
<label className="check">
<input type="checkbox" checked={options.restoreStock} disabled={busy}
onChange={(event) => onOptionsChange({ ...options, restoreStock: event.target.checked, deleteFiles: false })} />
{t('copies.maintenance.restoreStock')}
</label>
<p className="small">{t('copies.maintenance.restoreStockHint')}</p>
</>
)}
{canDeleteData && (
<label className="check">
<input type="checkbox" checked={options.deleteData} disabled={busy}
onChange={(event) => onOptionsChange({ ...options, deleteData: event.target.checked })} />
{t('copies.maintenance.deleteData', { path: record.dataPath })}
</label>
)}
<div className="copy-list-actions">
{!canDeleteFiles && (
<button type="button" className="button" disabled={busy || record.folderMissing === true} onClick={onOpenFolder}>
{t('copies.maintenance.openFolder')}
</button>
)}
<button type="button" className="button" disabled={busy} onClick={() => onOptionsChange(null)}>{t('wizard.cancel')}</button>
<button type="button" className="button button-primary" disabled={busy}
onClick={() => onRemove({ deleteFiles: willDeleteFiles, restoreStock: willRestoreStock, deleteData: willDeleteData })}>
{action}
</button>
</div>
</section>
)}
</>
);
}
Loaded 100 of 687 files, more files were not shown because too many files have changed in this diff. Show more