From 8c7d4a44a42a154f519e94aa53d45dd632404ba7 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Fri, 4 Dec 2026 09:56:59 +0800 Subject: [PATCH 01/22] docs(release): complete v0.1.4 notes Document the merged ground AI tuning and moving-fire changes, battle reward and backup fixes, and incomplete UHQ pack handling in both languages. --- .github/release-notes/v0.1.4.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/.github/release-notes/v0.1.4.md b/.github/release-notes/v0.1.4.md index 5281575..38af939 100644 --- a/.github/release-notes/v0.1.4.md +++ b/.github/release-notes/v0.1.4.md @@ -12,6 +12,7 @@ - **实验性新版陆战 AI(第一阶段,默认启用)。** - 引入全新的模块化陆战 AI 架构:包含整队指挥层与任务单(按坚守 / 征服 / 制霸模式分配进攻、侧翼、架枪与防空角色,支持分路包抄、集结出发、占点回防与防空阵位)、曝光积分视觉感知与唯一弹道开火许可门(含植被透光、硬遮挡弹道扫掠与友军走廊防误伤)、单车车体状态机(短停射击预算、掩体装填回缩、摆角、僵持换位与受损维修)、本车目击测速提前量与失联守出口,以及按待发架容量配置主/副双弹种出生装弹与局内自动切弹。 - 当前为第一阶段实验版本,默认以完整模式(`full`)运行并持续调优中;若遇到寻路或行为异常,可随时在启动器「数值 → Bot 参数」切回「原版 AI(`stock`)」。 + - 移动射击的车速上限随距离缩短而提高。车辆会主动减速,持续无法开火时可短停争取一炮,瞄准也改为按跟踪目标的误差判断。同步更新了出车权重、感知、占点与车体动作的默认参数。 - **启动器新增「数值 → Bot 参数」页面。** - 统一集中管理陆战 AI 模式切换、AI 坦克 / 飞机重生次数、每类载具候选池上限、**陆战 AI 出车权重**(中坦 / 主战、重坦、坦歼、轻坦、防空车、其他)与出生携弹策略。 - 同时以折叠分组开放全部陆战 AI 进阶参数(指挥配额、占点宏观、状态机、视觉感知、测速偏差、火控开火门、机动寻路、编队避让与地形约束),支持参数校验与一键恢复默认值。 @@ -25,9 +26,14 @@ - 修复空战右下角敌机部件受损播报串台(仅显示本机及观战目标,不再混入 AI 互打记录)以及空战持续命中时重复普通命中丢失的问题; - 修正普通命中与跳弹等引擎判定无效命中的奖励分类,并修正右侧部件受损反馈的攻击者与收件人归属; - 修复机库一键「购买所有已研发改装件」时因前置依赖状态与价格核算不一致报「角色服务器内部错误」的问题。 +- **对局奖励与备用载具** + - 空战街机可因伤害或摧毁敌方小基地获得个人分,摧毁奖励也会列入战后明细。 + - 修复重生界面中已购买的单车备用载具显示。每日免费出击、单车备用和通用备用按实际成功出击结算。 + - 修复部分任务单位击杀被误计为首杀的问题,并加固助攻事件处理。 - **启动器维护、便携版更新与界面**: - 客户端维护页新增「设置 / 更换在线版安装来源」,方便在线版移动目录后继续一键增量更新; - 复制安装与「从在线版更新」自动跳过并保留玩家自定义内容目录(`UserSkins`、`UserSights`、`WarThunderCDK` 与启动器日志),避免更新覆盖自制涂装或瞄具; + - 复制安装与增量更新会跳过下载不完整的超清材质包(UHQ)。已有离线客户端遇到残缺材质包时,启动器会在启动前提示处理。 - 修复便携版原地更新在 Windows 下的文件复制、Electron `.asar` 检查冲突与进程分离重启问题,并防止客户端或数据目录嵌套于启动器安装目录内; - 更新日志改为支持 Markdown 排版的弹窗展示。 @@ -58,6 +64,7 @@ - **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. @@ -71,9 +78,14 @@ - 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. From bc35cc89abe6a0e57d2977cde9b77ab7674067b0 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Fri, 4 Dec 2026 15:20:14 +0800 Subject: [PATCH 02/22] fix(ground-ai): only run custom AI in multiplayer battles --- game-ai/ground/wto_ai_runtime.das | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/game-ai/ground/wto_ai_runtime.das b/game-ai/ground/wto_ai_runtime.das index 775e92b..1171e8a 100644 --- a/game-ai/ground/wto_ai_runtime.das +++ b/game-ai/ground/wto_ai_runtime.das @@ -48,8 +48,12 @@ var private g_last_zone_ver : int = -1 var private g_fire_budget : int = 0 var private g_next_diag_at : float = 0.0 +// Custom ground AI must only run inside a real multiplayer battle. Single-player test +// drives also dispatch tag=server ECS, but their target vehicles must never be taken over. def private wto_any_layer_active() : bool - return WTO_AI_ENABLED && (WTO_AI_LAYER_MACRO || WTO_AI_LAYER_TACTICS || WTO_AI_LAYER_NAVIGATION || WTO_AI_LAYER_FIRE_CONTROL) + if !WTO_AI_ENABLED || !get_app().isMultiplayerGame + return false + return WTO_AI_LAYER_MACRO || WTO_AI_LAYER_TACTICS || WTO_AI_LAYER_NAVIGATION || WTO_AI_LAYER_FIRE_CONTROL [init] def wto_ai_script_init() From f2e73c1cfe3fc36e5d2fb16c140897106a341825 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Fri, 4 Dec 2026 17:15:38 +0800 Subject: [PATCH 03/22] fix(profile): persist vehicle camouflage, loadout, and trim preferences Accept the full client-writable hangar/ field set emitted by AircraftInfo::serialize (mode 0x20/0x80) in cln_update for owned vehicles: lastSkin, lastWeapon, lastBullets0..5 (strings), and aileronTrim/elevatorTrim/rudderTrim (finite reals). Ownership and server-authoritative hangar fields remain untouched, matching the stock chard guard (2.61.0.37 0x938081) and serializer (2.61.0.37 0x940510, 2.61.0.58 0x942f80). Extends the camouflage persistence fix from PR #17 to cover weapon presets, ammo belts, and flight trims reported on the same cln_update path. Verified root and launcher typecheck and SaveStore + clientProfile round-trip persistence. In-game acceptance is pending. Co-authored-by: duduyagame <259639371+duduyagame@users.noreply.github.com> --- .../src/char/actions/client-update-actions.ts | 4 +- .../src/profile/profile-client-settings.ts | 44 ++++++++++++++++++- apps/server/src/profile/profile-hangar.ts | 6 +++ 3 files changed, 52 insertions(+), 2 deletions(-) diff --git a/apps/server/src/char/actions/client-update-actions.ts b/apps/server/src/char/actions/client-update-actions.ts index cb818f4..ed7316d 100644 --- a/apps/server/src/char/actions/client-update-actions.ts +++ b/apps/server/src/char/actions/client-update-actions.ts @@ -2,7 +2,9 @@ * `cln_update` (aces.exe 2.61.0.37 0x29f3ee, job type 3 -> `onUpdateProfile`): * triggered by `save_online_single_job` when the client marks seen user logs as disabled * (`scripts/userLog/userlogUtils.nut` `disableSeenUserlogs`, tag 223) or updates hangar - * auto-repair / auto-refill / auto-buy-modifications and map preferences. On returning from + * auto-repair / auto-refill / auto-buy-modifications, map preferences, and per-vehicle + * preferences (`hangar/` `lastSkin`, `lastWeapon`, `lastBullets0..5`, and flight + * trims `aileronTrim`/`elevatorTrim`/`rudderTrim`). On returning from * a stock training mission, the client also reports completion in `missionAwards` while * `pveProgress` is empty. Answers the whole updated profile. */ diff --git a/apps/server/src/profile/profile-client-settings.ts b/apps/server/src/profile/profile-client-settings.ts index 730e69d..40d4b26 100644 --- a/apps/server/src/profile/profile-client-settings.ts +++ b/apps/server/src/profile/profile-client-settings.ts @@ -5,7 +5,14 @@ * - hangar toggles `autoRefillWeapons:b`, `autoRepairAircrafts:b`, `autoBuyModifications:b` (0x918ef0); * - privacy / save metadata `onlineSaveVersion:i`, `allowToBeAddedToContacts:b`, `allowToBeAddedToLB:b` (0x9179d4..0x917a4c); * - `classinessMarkPriorities:i64` (0x92b2cb); - * - sub-block `mapPreferences` (0x927530 -> 0x9483d0). + * - sub-block `mapPreferences` (0x927530 -> 0x9483d0); + * - per-vehicle `hangar/` client preferences (`AircraftInfo::serialize` mode 0x20/0x80, + * owned vehicles only per the stock chard guard at 0x938081): + * - `lastSkin:t` (2.61.0.37 0x940fbc/0x94111b, 2.61.0.58 0x943a2f/0x943b8e); + * - `lastWeapon:t` (2.61.0.37 0x940ff4/0x941084, 2.61.0.58 0x943a67/0x943af7); + * - `lastBullets0..5:t` (2.61.0.37 0x94078d..0x940914 / 0x940b2c..0x940f8d, 2.61.0.58 0x943200..0x94393e); + * - `aileronTrim:r`, `elevatorTrim:r`, `rudderTrim:r` (2.61.0.37 0x941682..0x941720 / 0x9411e7..0x9412db, + * 2.61.0.58 0x943c7a..0x944119). * * Empty shell blocks that `saveOnline` (mode 0x20) also emits (`entitlementsInfo{}`, * `pveProgress{}`, `weaponPresets{}` — custom weapon presets use `cln_save_weapon_presets`, and @@ -13,6 +20,7 @@ * state is preserved. */ import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk'; +import { updateOwnedVehicle } from './profile-hangar.ts'; import { disableUserLogs } from './profile-trophies-log.ts'; const BOOL_SETTINGS = [ @@ -23,6 +31,23 @@ const BOOL_SETTINGS = [ 'allowToBeAddedToLB', ] as const; +const VEHICLE_STRING_SETTINGS = [ + 'lastSkin', + 'lastWeapon', + 'lastBullets0', + 'lastBullets1', + 'lastBullets2', + 'lastBullets3', + 'lastBullets4', + 'lastBullets5', +] as const; + +const VEHICLE_TRIM_SETTINGS = [ + 'aileronTrim', + 'elevatorTrim', + 'rudderTrim', +] as const; + /** * Whether hangar ammunition/expendable auto-refill is enabled (`EconomicState` +0xe979). * Defaults to `true` when absent from `profile.blk`, matching `aces.exe` 0x90b6a0 and 0x918ef0. @@ -57,6 +82,10 @@ export function applyClientProfileUpdate(profile: BlkBlock, request: BlkBlock): target.blocks = cloned.blocks; } + for (const vehicle of findBlock(request, 'hangar')?.blocks ?? []) { + applyVehicleClientSettings(profile, vehicle); + } + const userlogs = findBlock(request, 'userlogs'); if (userlogs) { const idsToDisable = userlogs.blocks @@ -68,3 +97,16 @@ export function applyClientProfileUpdate(profile: BlkBlock, request: BlkBlock): if (idsToDisable.length > 0) disableUserLogs(profile, idsToDisable); } } + +function applyVehicleClientSettings(profile: BlkBlock, vehicle: BlkBlock): void { + updateOwnedVehicle(profile, vehicle.name, (entry) => { + for (const name of VEHICLE_STRING_SETTINGS) { + const param = findParam(vehicle, name)?.value; + if (param?.type === 'string') setParam(entry, name, param); + } + for (const name of VEHICLE_TRIM_SETTINGS) { + const param = findParam(vehicle, name)?.value; + if (param?.type === 'real' && Number.isFinite(param.value)) setParam(entry, name, param); + } + }); +} diff --git a/apps/server/src/profile/profile-hangar.ts b/apps/server/src/profile/profile-hangar.ts index d569b9a..d983e24 100644 --- a/apps/server/src/profile/profile-hangar.ts +++ b/apps/server/src/profile/profile-hangar.ts @@ -31,6 +31,12 @@ export function addOwnedVehicle(profile: BlkBlock, vehicle: string): void { if (!hangar.blocks.some((owned) => owned.name === vehicle)) hangar.blocks.push({ name: vehicle, params: [], blocks: [] }); } +/** Update an owned vehicle's hangar entry in place; ignores vehicles the player does not own. */ +export function updateOwnedVehicle(profile: BlkBlock, vehicle: string, update: (entry: BlkBlock) => void): void { + const entry = ownedVehicle(profile, vehicle); + if (entry) update(entry); +} + /** The stock client uses the base rank until it has a non-negative selection. */ export function vehicleMrankDelta(profile: BlkBlock, vehicle: string): number { return Math.max(0, intField(ownedVehicle(profile, vehicle), MRANK_DELTA)); From 48f01b533ef8cfe7d048f408f99c488ffd712d53 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Fri, 4 Dec 2026 19:55:03 +0800 Subject: [PATCH 04/22] fix(patcher): strip cross-promo locks so promo gift vehicles can be ordered Strip isCrossPromo and crossPromoBanner from config/shop.blk entries alongside tech-tree hiding flags so cross-promotion gift vehicles (bf-109c_1_promo, us_m4_sherman_promo, jp_destroyer_hatsuzuki) can be ordered directly through their generated local store packs while keeping showOnlyWhenBought intact. --- .../src/tech-tree/reveal-hidden-vehicles.ts | 32 ++++++++++++++++--- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/packages/patcher/src/tech-tree/reveal-hidden-vehicles.ts b/packages/patcher/src/tech-tree/reveal-hidden-vehicles.ts index 8237776..50be1a1 100644 --- a/packages/patcher/src/tech-tree/reveal-hidden-vehicles.ts +++ b/packages/patcher/src/tech-tree/reveal-hidden-vehicles.ts @@ -15,21 +15,45 @@ * not been given them: event and promotion prizes, mission copies of tree vehicles (nt_f_4e, * f_4e_event ...), the drones of the premium columns, the floatplanes that come with ships, * and the launchers of the split air-defence systems (lab round 20, user feedback). + * + * Cross-promotion gift vehicles (e.g. us_m4_sherman_promo, bf-109c_1_promo, + * jp_destroyer_hatsuzuki) also carry `isCrossPromo:b` and `crossPromoBanner:t`. When + * `isCrossPromo` is true, stock client scripts (availabilitybuyonline.nut, unitcontextmenu.nut, + * slotactions.nut) hide the "Order" action and show a cross-promo locked banner instead of + * routing to the local store pack and bundle GUID generated for gift vehicles. Both parameters + * are stripped here so those vehicles can be ordered directly from the tech tree. */ import type { BlkBlock } from '@wto/blk'; export const SHOP_PATH = 'config/shop.blk'; const HIDING_FLAGS = new Set(['showOnlyWhenResearch', 'showOnlyWhenAvailableForPurchase']); +const CROSS_PROMO_PARAMS = new Set(['isCrossPromo', 'crossPromoBanner']); -/** Remove the hiding flags in place; returns how many vehicles were hidden before. */ +/** + * Remove tech-tree hiding flags and cross-promo lock parameters in place. + * Returns how many vehicles had a hiding flag removed (cross-promo unlocks are not counted). + */ export function revealHiddenVehicles(shop: BlkBlock): number { let revealed = 0; for (const entry of shopEntries(shop)) { - const kept = entry.params.filter((param) => !HIDING_FLAGS.has(param.name)); - if (kept.length === entry.params.length) continue; + let wasHidden = false; + let stripped = false; + const kept = entry.params.filter((param) => { + if (HIDING_FLAGS.has(param.name)) { + wasHidden = true; + stripped = true; + return false; + } + if (CROSS_PROMO_PARAMS.has(param.name)) { + stripped = true; + return false; + } + return true; + }); + if (!stripped) continue; entry.params = kept; - revealed++; + if (wasHidden) revealed++; } return revealed; } From 8f1d175d55f9ce929c155c6093adef60fdec72c9 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Fri, 4 Dec 2026 19:55:03 +0800 Subject: [PATCH 05/22] fix(patcher): filter uncached decal and skin entries with placeholder fallback Scan locally cached .ddsx files under cache/content (/.ddsx) when building char.vromfs.bin from player decal snapshots or regional.vromfs.bin. Repair single-LOD cache hits by falling back missing lodN/hdrN pairs to available LODs, fall back uncached stock decals to built-in placeholders, and drop uncached extra decals and incomplete downloadable skins. --- packages/patcher/src/build-game-copy.ts | 6 + packages/patcher/src/char-pack.ts | 96 +++++++- .../patcher/src/decals/offline-decal-index.ts | 90 ++++++- .../patcher/src/decals/player-decal-cache.ts | 230 ++++++++++++++++-- 4 files changed, 383 insertions(+), 39 deletions(-) diff --git a/packages/patcher/src/build-game-copy.ts b/packages/patcher/src/build-game-copy.ts index 2666592..41ec737 100644 --- a/packages/patcher/src/build-game-copy.ts +++ b/packages/patcher/src/build-game-copy.ts @@ -61,6 +61,10 @@ export interface GameCopyInputs { readonly placeholderDecals: boolean; /** Real dldata/downloadable_decals.blk and downloadable_skins.blk extracted from the player's cache. */ readonly decalIndexFiles?: readonly AddedFile[]; + /** Optional player decal cache folder used to filter cached .ddsx textures when embedding indexes. */ + readonly decalCache?: string; + /** Optional pre-scanned set of cached .ddsx relative paths ("/.ddsx", lowercased). */ + readonly cachedDdsx?: ReadonlySet; /** Whether wto_ws.dll writes win64/wto_ws.log; defaults to true. */ readonly hookLogging?: boolean; /** Ordered list of enabled additive mods to overlay onto this build. */ @@ -191,6 +195,8 @@ function buildCorePacks( const { pack: coreCharPack, ...charReport } = rebuildCharPack(inputs.stock.charPack, endpoint, { placeholderDecals: inputs.placeholderDecals, ...(inputs.decalIndexFiles ? { decalIndexFiles: inputs.decalIndexFiles } : {}), + ...(inputs.decalCache ? { decalCache: inputs.decalCache } : {}), + ...(inputs.cachedDdsx ? { cachedDdsx: inputs.cachedDdsx } : {}), localRegistration, }); const charOverlay = applyModPackOverlays(coreCharPack, 'char.vromfs.bin', enabledMods); diff --git a/packages/patcher/src/char-pack.ts b/packages/patcher/src/char-pack.ts index 883f0df..8fe6a40 100644 --- a/packages/patcher/src/char-pack.ts +++ b/packages/patcher/src/char-pack.ts @@ -4,7 +4,19 @@ * tech tree (config/shop.blk), and, unless the player gave a decal source, placeholder decal * and skin indexes (decals/offline-decal-index.ts). */ -import { DECALS_CONFIG_PATH, offlineDecalIndex } from './decals/offline-decal-index.ts'; +import { decodeBlk, emptyBlock, encodeBlk } from '@wto/blk'; +import { + DECALS_CONFIG_PATH, + DECALS_INDEX_PATH, + mergePlayerDecalIndex, + offlineDecalIndex, + SKINS_INDEX_PATH, +} from './decals/offline-decal-index.ts'; +import { + filterPlayerDecalIndexFiles, + readPlayerDecalIndexFiles, + scanCachedDdsxFiles, +} from './decals/player-decal-cache.ts'; import { enableFeaturesForEveryone, GAME_SETTINGS_PATH, OFFLINE_FEATURES } from './features/offline-features.ts'; import type { LocalEndpoint } from './network/local-endpoint.ts'; import { redirectNetworkConfig, type NetworkRedirectReport } from './network/redirect-network-config.ts'; @@ -20,8 +32,12 @@ export interface CharPackResult { readonly features: readonly string[]; /** Vehicles that were hidden from players who had not researched or bought them. */ readonly revealedVehicles: number; - /** Decals in the placeholder index; undefined when the player's own decal cache is used. */ + /** Decals using placeholder textures; undefined when a legacy web cache supplies its own index. */ readonly placeholderDecals: number | undefined; + /** Decals resolved from locally cached .ddsx textures; undefined unless a player index is merged. */ + readonly cachedDecals?: number; + /** Downloadable skins resolved from locally cached .ddsx textures; undefined unless a player index is merged. */ + readonly cachedSkins?: number; } export interface CharPackOptions { @@ -29,22 +45,84 @@ export interface CharPackOptions { readonly placeholderDecals: boolean; /** Real dldata/downloadable_decals.blk and downloadable_skins.blk extracted from the player's cache. */ readonly decalIndexFiles?: readonly AddedFile[]; + /** Optional player decal cache folder (cache/content, cache, or imported snapshot) used to filter cached .ddsx files. */ + readonly decalCache?: string; + /** Optional pre-scanned set of cached .ddsx relative paths ("/.ddsx", lowercased). */ + readonly cachedDdsx?: ReadonlySet; readonly localRegistration: boolean; } +interface DecalOverlay { + readonly files: readonly AddedFile[]; + readonly placeholderDecals: number | undefined; + readonly cachedDecals?: number; + readonly cachedSkins?: number; +} + export function rebuildCharPack(stockPack: Uint8Array, endpoint: LocalEndpoint, options: CharPackOptions): CharPackResult { let network: NetworkRedirectReport | undefined; let features: string[] = []; let revealedVehicles = 0; - const usePlayerIndex = (options.decalIndexFiles?.length ?? 0) > 0; - const decals = !usePlayerIndex && options.placeholderDecals - ? offlineDecalIndex(readPackBlk(stockPack, DECALS_CONFIG_PATH)) - : undefined; - const addedFiles = usePlayerIndex ? options.decalIndexFiles! : (decals?.files ?? []); + const decals = resolveDecalOverlay(stockPack, options); const pack = editPackBlks(stockPack, [ { path: NETWORK_CONFIG_PATH, edit: (root) => { network = redirectNetworkConfig(root, endpoint, options.localRegistration); } }, { path: GAME_SETTINGS_PATH, edit: (root) => { features = enableFeaturesForEveryone(root, OFFLINE_FEATURES); } }, { path: SHOP_PATH, edit: (root) => { revealedVehicles = revealHiddenVehicles(root); } }, - ], addedFiles); - return { pack, network: network!, features, revealedVehicles, placeholderDecals: decals?.decals }; + ], decals.files); + return { + pack, + network: network!, + features, + revealedVehicles, + placeholderDecals: decals.placeholderDecals, + ...(decals.cachedDecals !== undefined ? { cachedDecals: decals.cachedDecals } : {}), + ...(decals.cachedSkins !== undefined ? { cachedSkins: decals.cachedSkins } : {}), + }; +} + +function resolveDecalOverlay(stockPack: Uint8Array, options: CharPackOptions): DecalOverlay { + const playerIndexFiles = resolvePlayerIndexFiles(options); + if (playerIndexFiles !== undefined && playerIndexFiles.length > 0) { + const decalsConfig = readPackBlk(stockPack, DECALS_CONFIG_PATH); + const decalsFile = playerIndexFiles.find((file) => file.path === DECALS_INDEX_PATH); + const skinsFile = playerIndexFiles.find((file) => file.path === SKINS_INDEX_PATH); + const otherFiles = playerIndexFiles.filter((file) => file.path !== DECALS_INDEX_PATH && file.path !== SKINS_INDEX_PATH); + const merged = mergePlayerDecalIndex( + decalsConfig, + decalsFile ? decodeBlk(decalsFile.content) : emptyBlock(), + ); + const skinsContent = skinsFile ? skinsFile.content : encodeBlk(emptyBlock()); + const cachedSkins = skinsFile ? decodeBlk(skinsFile.content).blocks.length : 0; + return { + files: [ + { path: SKINS_INDEX_PATH, content: skinsContent }, + { path: DECALS_INDEX_PATH, content: merged.content }, + ...otherFiles, + ], + placeholderDecals: merged.placeholderDecals, + cachedDecals: merged.cachedDecals, + cachedSkins, + }; + } + if (options.placeholderDecals) { + const offline = offlineDecalIndex(readPackBlk(stockPack, DECALS_CONFIG_PATH)); + return { files: offline.files, placeholderDecals: offline.decals }; + } + return { files: [], placeholderDecals: undefined }; +} + +function resolvePlayerIndexFiles(options: CharPackOptions): readonly AddedFile[] | undefined { + if (options.decalIndexFiles !== undefined) { + if (options.cachedDdsx !== undefined) { + return filterPlayerDecalIndexFiles(options.decalIndexFiles, options.cachedDdsx); + } + if (options.decalCache !== undefined) { + return filterPlayerDecalIndexFiles(options.decalIndexFiles, scanCachedDdsxFiles(options.decalCache)); + } + return options.decalIndexFiles; + } + if (options.decalCache !== undefined) { + return readPlayerDecalIndexFiles(options.decalCache); + } + return undefined; } diff --git a/packages/patcher/src/decals/offline-decal-index.ts b/packages/patcher/src/decals/offline-decal-index.ts index bd88c4b..3ece545 100644 --- a/packages/patcher/src/decals/offline-decal-index.ts +++ b/packages/patcher/src/decals/offline-decal-index.ts @@ -58,17 +58,35 @@ export interface OfflineDecalIndex { readonly decals: number; } +export interface MergedDecalIndex { + readonly index: BlkBlock; + readonly content: Uint8Array; + /** Total decals backed by locally cached .ddsx textures (stock + extra). */ + readonly cachedDecals: number; + /** Stock config/decals.blk entries resolved from cached .ddsx textures. */ + readonly cachedStockDecals: number; + /** Extra entries outside config/decals.blk kept because their .ddsx textures are cached. */ + readonly cachedExtraDecals: number; + /** Stock config/decals.blk entries that fell back to built-in placeholder textures. */ + readonly placeholderDecals: number; +} + +const SQUARE_PARAMS = textureParams(SQUARE_PLACEHOLDER); +const WIDE_PARAMS = textureParams(WIDE_PLACEHOLDER); + +export function placeholderDecalBlock(decal: BlkBlock): BlkBlock { + return { + name: decal.name, + params: aspectRatio(decal) >= WIDE_ASPECT_RATIO ? WIDE_PARAMS : SQUARE_PARAMS, + blocks: [], + }; +} + export function offlineDecalIndex(decalsConfig: BlkBlock): OfflineDecalIndex { - const square = textureParams(SQUARE_PLACEHOLDER); - const wide = textureParams(WIDE_PLACEHOLDER); const index: BlkBlock = { name: '', params: [], - blocks: decalsConfig.blocks.map((decal) => ({ - name: decal.name, - params: aspectRatio(decal) >= WIDE_ASPECT_RATIO ? wide : square, - blocks: [], - })), + blocks: decalsConfig.blocks.map(placeholderDecalBlock), }; return { files: [ @@ -79,6 +97,64 @@ export function offlineDecalIndex(decalsConfig: BlkBlock): OfflineDecalIndex { }; } +/** + * Merge a filtered player downloadable_decals.blk (containing only decals with locally cached + * .ddsx textures) with stock config/decals.blk: + * - Every stock decal present in cachedPlayerDecals keeps its real entry. + * - Every stock decal missing from cachedPlayerDecals falls back to a built-in placeholder + * texture (star/panther) so it never fails to load offline. + * - Extra decals outside config/decals.blk that survived cache filtering are appended. + */ +export function mergePlayerDecalIndex( + decalsConfig: BlkBlock, + cachedPlayerDecals: BlkBlock, +): MergedDecalIndex { + const cachedByName = new Map(); + for (const block of cachedPlayerDecals.blocks) { + cachedByName.set(block.name, block); + } + + const stockNames = new Set(); + const blocks: BlkBlock[] = []; + let cachedStockDecals = 0; + let placeholderDecals = 0; + + for (const decal of decalsConfig.blocks) { + stockNames.add(decal.name); + const cached = cachedByName.get(decal.name); + if (cached !== undefined) { + blocks.push(cached); + cachedStockDecals += 1; + } else { + blocks.push(placeholderDecalBlock(decal)); + placeholderDecals += 1; + } + } + + const emittedExtra = new Set(); + let cachedExtraDecals = 0; + for (const block of cachedPlayerDecals.blocks) { + if (stockNames.has(block.name) || emittedExtra.has(block.name)) continue; + emittedExtra.add(block.name); + blocks.push(block); + cachedExtraDecals += 1; + } + + const index: BlkBlock = { + name: '', + params: cachedPlayerDecals.params, + blocks, + }; + return { + index, + content: encodeBlk(index), + cachedDecals: cachedStockDecals + cachedExtraDecals, + cachedStockDecals, + cachedExtraDecals, + placeholderDecals, + }; +} + function aspectRatio(decal: BlkBlock): number { const value = decal.params.find((param) => param.name === 'aspect_ratio')?.value; return value?.type === 'real' && Number.isFinite(value.value) && value.value > 0 ? value.value : 1; diff --git a/packages/patcher/src/decals/player-decal-cache.ts b/packages/patcher/src/decals/player-decal-cache.ts index 8d1d50d..d98cb75 100644 --- a/packages/patcher/src/decals/player-decal-cache.ts +++ b/packages/patcher/src/decals/player-decal-cache.ts @@ -6,20 +6,23 @@ * * Two layouts exist across War Thunder builds (verified on 2.61.0.37 and 2.61.0.58): * 1. Modern vromfs-indexed cache (2.61+): cache/content/ holds dldata_s.info and the downloaded - * /.ddsx textures, while the decal and skin indexes (dldata/downloadable_decals.blk - * and dldata/downloadable_skins.blk) ship inside sibling cache/binary./regional.vromfs.bin - * (mounted by webdlcontent::on_regional_vrom_remounted, 0xd3cf95 -> 0xd3d066). Because the client - * reads the vromfs index first, it never writes downloadable_decals..blk into cache/content/. - * We extract both index BLKs into a self-contained snapshot (.wto-index/) on import and embed - * them into char.vromfs.bin during build so webdlcontent::init mounts cache/content/ (0xd3ca11) - * and loads the real hashes from vromfs without signature checks (0xd3cb6b). + * /.ddsx textures (where the first 2 characters of each base32 hash form the + * bucket directory and the remaining characters plus ".ddsx" form the filename), while the + * decal and skin indexes (dldata/downloadable_decals.blk and dldata/downloadable_skins.blk) + * ship inside sibling cache/binary./regional.vromfs.bin (mounted by + * webdlcontent::on_regional_vrom_remounted, 0xd3cf95 -> 0xd3d066). Because the client reads + * the vromfs index first, it never writes downloadable_decals..blk into cache/content/. + * We extract both raw index BLKs into a self-contained snapshot (.wto-index/) on import; when + * building char.vromfs.bin, we filter both indexes against the .ddsx files actually present + * in the cache (backfilling missing single-LOD references from the cached LOD) so uncached + * entries do not fail to load offline. * 2. Legacy webcache-indexed cache: cache/content/ holds dldata_s.info and signed * downloadable_decals..blk directly; char.vromfs.bin omits dldata/ so the client reads * the cached index from cache/content/. */ import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs'; import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path'; -import { decodeBlk, emptyBlock, encodeBlk, parseSharedNameMap } from '@wto/blk'; +import { decodeBlk, emptyBlock, encodeBlk, parseSharedNameMap, type BlkBlock, type BlkParam } from '@wto/blk'; import { getFile, NAME_MAP_PATH, readArchive } from '@wto/vromfs'; import type { AddedFile } from '../pack-edit.ts'; import { compareVersions } from '../version-record.ts'; @@ -33,6 +36,9 @@ const REGIONAL_PACK_NAME = 'regional.vromfs.bin'; const SNAPSHOT_INDEX_DIR = '.wto-index'; const SNAPSHOT_DECALS_FILE = 'downloadable_decals.blk'; const SNAPSHOT_SKINS_FILE = 'downloadable_skins.blk'; +const DDSX_EXTENSION = '.ddsx'; +const LOD_PARAM = /^lod(\d+)$/; +const HDR_PARAM = /^hdr(\d+)$/; export interface PlayerDecalCache { readonly copiedTo: string; @@ -60,27 +66,133 @@ export function playerDecalCacheProblem(source: string): string | undefined { } /** - * Read real dldata/downloadable_decals.blk and dldata/downloadable_skins.blk for embedding into - * char.vromfs.bin when the cache uses either an imported snapshot index or a sibling - * binary./regional.vromfs.bin. Returns undefined for legacy downloadable_decals..blk - * caches, which supply their index directly inside cache/content/. + * Map a downloadable texture hash (e.g. "nhy6...cyii") to its cache-relative .ddsx path + * ("nh/y6...cyii.ddsx", lowercased). Returns undefined for non-hash values. */ -export function readPlayerDecalIndexFiles(source: string): readonly AddedFile[] | undefined { - const folder = resolvePlayerDecalCacheFolder(source); - const snapshot = readSnapshotIndexFiles(folder); - if (snapshot) return snapshot; - if (decalIndexes(folder).length > 0) return undefined; - const regional = findRegionalPack(folder); - if (!regional) return undefined; - return extractRegionalIndexFiles(regional); +export function ddsxPathForHash(hash: string): string | undefined { + const normalized = hash.trim().toLowerCase(); + if (normalized.length < 3 || normalized.includes('/') || normalized.includes('\\')) return undefined; + return `${normalized.slice(0, 2)}/${normalized.slice(2)}${DDSX_EXTENSION}`; } /** - * Persist extracted vromfs decal/skin indexes into an imported cache snapshot so subsequent + * Scan a player decal cache folder (cache/content, its parent cache folder, or an imported + * snapshot) and collect the normalized relative paths ("/.ddsx", lowercased) of + * all cached .ddsx files, skipping .wto-index. + */ +export function scanCachedDdsxFiles(source: string): ReadonlySet { + const folder = resolvePlayerDecalCacheFolder(source); + const cached = new Set(); + if (!existsSync(folder) || !statSync(folder).isDirectory()) return cached; + for (const entry of readdirSync(folder, { withFileTypes: true })) { + if (!entry.isDirectory() || entry.name === SNAPSHOT_INDEX_DIR) continue; + const bucket = entry.name.toLowerCase(); + if (bucket.length !== 2) continue; + const sub = join(folder, entry.name); + for (const child of readdirSync(sub, { withFileTypes: true })) { + if (!child.isFile()) continue; + const name = child.name.toLowerCase(); + if (name.endsWith(DDSX_EXTENSION)) cached.add(`${bucket}/${name}`); + } + } + return cached; +} + +/** + * Filter a downloadable_decals.blk root block to only decals with at least one cached LOD + * texture in cachedDdsx, backfilling any missing lodN/hdrN from the best cached LOD. + */ +export function filterDownloadableDecalsBlock( + decalsBlk: BlkBlock, + cachedDdsx: ReadonlySet, +): BlkBlock { + const blocks: BlkBlock[] = []; + for (const decal of decalsBlk.blocks) { + const normalized = normalizeTextureBlockLods(decal, cachedDdsx); + if (normalized !== undefined) blocks.push(normalized); + } + return { name: decalsBlk.name, params: decalsBlk.params, blocks }; +} + +/** + * Filter a downloadable_skins.blk root block to only skins whose texture entries all have at + * least one cached LOD texture in cachedDdsx, backfilling missing lodN (and hdrN if present) + * from the best cached LOD. + */ +export function filterDownloadableSkinsBlock( + skinsBlk: BlkBlock, + cachedDdsx: ReadonlySet, +): BlkBlock { + const blocks: BlkBlock[] = []; + for (const skin of skinsBlk.blocks) { + if (skin.blocks.length > 0) { + const nextChildren: BlkBlock[] = []; + let allCached = true; + let hasTextureChild = false; + for (const child of skin.blocks) { + if (hasLodParams(child)) { + hasTextureChild = true; + const normalized = normalizeTextureBlockLods(child, cachedDdsx); + if (normalized === undefined) { + allCached = false; + break; + } + nextChildren.push(normalized); + } else { + nextChildren.push(child); + } + } + if (allCached && hasTextureChild) { + blocks.push({ name: skin.name, params: skin.params, blocks: nextChildren }); + } + } else { + const normalized = normalizeTextureBlockLods(skin, cachedDdsx); + if (normalized !== undefined) blocks.push(normalized); + } + } + return { name: skinsBlk.name, params: skinsBlk.params, blocks }; +} + +/** + * Filter encoded dldata/downloadable_decals.blk and dldata/downloadable_skins.blk entries + * against the set of locally cached .ddsx relative paths. + */ +export function filterPlayerDecalIndexFiles( + files: readonly AddedFile[], + cachedDdsx: ReadonlySet, +): readonly AddedFile[] { + return files.map((file) => { + if (file.path === DECALS_INDEX_PATH) { + return { path: file.path, content: encodeBlk(filterDownloadableDecalsBlock(decodeBlk(file.content), cachedDdsx)) }; + } + if (file.path === SKINS_INDEX_PATH) { + return { path: file.path, content: encodeBlk(filterDownloadableSkinsBlock(decodeBlk(file.content), cachedDdsx)) }; + } + return file; + }); +} + +/** + * Read dldata/downloadable_decals.blk and dldata/downloadable_skins.blk for embedding into + * char.vromfs.bin when the cache uses either an imported snapshot index or a sibling + * binary./regional.vromfs.bin, filtered to entries whose .ddsx textures actually exist in + * the cache folder (with single-LOD fallback). Returns undefined for legacy + * downloadable_decals..blk caches, which supply their index directly inside cache/content/. + */ +export function readPlayerDecalIndexFiles(source: string): readonly AddedFile[] | undefined { + const folder = resolvePlayerDecalCacheFolder(source); + const raw = readRawPlayerDecalIndexFiles(folder); + if (!raw) return undefined; + return filterPlayerDecalIndexFiles(raw, scanCachedDdsxFiles(folder)); +} + +/** + * Persist raw extracted vromfs decal/skin indexes into an imported cache snapshot so subsequent * launches are completely self-contained and never touch the online client directory. */ export function writeDecalCacheIndexSnapshot(source: string, target: string): void { - const files = readPlayerDecalIndexFiles(source); + const folder = resolvePlayerDecalCacheFolder(source); + const files = readRawPlayerDecalIndexFiles(folder); if (!files) return; const indexDir = join(target, SNAPSHOT_INDEX_DIR); mkdirSync(indexDir, { recursive: true }); @@ -140,6 +252,78 @@ function directDecalCacheProblem(folder: string): string | undefined { return `${folder} has no downloadable_decals..blk and no sibling binary.*/${REGIONAL_PACK_NAME}`; } +function readRawPlayerDecalIndexFiles(folder: string): readonly AddedFile[] | undefined { + const snapshot = readSnapshotIndexFiles(folder); + if (snapshot) return snapshot; + if (decalIndexes(folder).length > 0) return undefined; + const regional = findRegionalPack(folder); + if (!regional) return undefined; + return extractRegionalIndexFiles(regional); +} + +function hasLodParams(block: BlkBlock): boolean { + return block.params.some((param) => param.value.type === 'string' && LOD_PARAM.test(param.name)); +} + +function normalizeTextureBlockLods( + block: BlkBlock, + cachedDdsx: ReadonlySet, +): BlkBlock | undefined { + const lods: Array<{ readonly index: number; readonly value: string; readonly cached: boolean }> = []; + const hdrs = new Map(); + for (const param of block.params) { + if (param.value.type !== 'string') continue; + const lodMatch = LOD_PARAM.exec(param.name); + if (lodMatch) { + const rel = ddsxPathForHash(param.value.value); + lods.push({ + index: Number(lodMatch[1]), + value: param.value.value, + cached: rel !== undefined && cachedDdsx.has(rel), + }); + continue; + } + const hdrMatch = HDR_PARAM.exec(param.name); + if (hdrMatch) { + hdrs.set(Number(hdrMatch[1]), param.value.value); + } + } + if (lods.length === 0) return undefined; + lods.sort((a, b) => a.index - b.index); + const best = lods.find((entry) => entry.cached); + if (!best) return undefined; + if (lods.every((entry) => entry.cached)) return block; + + const missingIndices = new Set(lods.filter((entry) => !entry.cached).map((entry) => entry.index)); + const bestHdr = hdrs.get(best.index); + const nextParams: BlkParam[] = []; + for (const param of block.params) { + if (param.value.type === 'string') { + const hdrMatch = HDR_PARAM.exec(param.name); + if (hdrMatch) { + const idx = Number(hdrMatch[1]); + if (missingIndices.has(idx) && bestHdr !== undefined) { + nextParams.push({ name: param.name, value: { type: 'string', value: bestHdr } }); + continue; + } + } + const lodMatch = LOD_PARAM.exec(param.name); + if (lodMatch) { + const idx = Number(lodMatch[1]); + if (missingIndices.has(idx)) { + if (bestHdr !== undefined && !hdrs.has(idx)) { + nextParams.push({ name: `hdr${idx}`, value: { type: 'string', value: bestHdr } }); + } + nextParams.push({ name: param.name, value: { type: 'string', value: best.value } }); + continue; + } + } + } + nextParams.push(param); + } + return { name: block.name, params: nextParams, blocks: block.blocks }; +} + function readSnapshotIndexFiles(folder: string): readonly AddedFile[] | undefined { const decalsPath = join(folder, SNAPSHOT_INDEX_DIR, SNAPSHOT_DECALS_FILE); if (!statSync(decalsPath, { throwIfNoEntry: false })?.isFile()) return undefined; @@ -158,7 +342,7 @@ function hasCachedDdsxTextures(folder: string): boolean { if (!entry.isDirectory() || entry.name === SNAPSHOT_INDEX_DIR) continue; const sub = join(folder, entry.name); for (const child of readdirSync(sub, { withFileTypes: true })) { - if (child.isFile() && child.name.endsWith('.ddsx')) return true; + if (child.isFile() && child.name.toLowerCase().endsWith(DDSX_EXTENSION)) return true; } } return false; From b3211b89cd164b636251629cf39ff98fdb7b274b Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Fri, 4 Dec 2026 19:55:04 +0800 Subject: [PATCH 06/22] feat(launcher): remember last selected directory in file and folder pickers Persist per-category dialog directories under userData/dialog-paths.json and resolve existing parent fallbacks for folder pickers, save archive import/export, online backup selection, and mod preset/folder dialogs. --- apps/launcher/src/main/ipc/handlers.ts | 14 +- .../src/main/services/mods/mods-service.ts | 10 +- .../src/main/services/saves/manage-saves.ts | 31 +++- apps/launcher/src/main/util/dialog-paths.ts | 171 ++++++++++++++++++ .../renderer/src/components/FolderField.tsx | 5 +- apps/launcher/src/shared/ipc/contract.ts | 7 +- 6 files changed, 226 insertions(+), 12 deletions(-) create mode 100644 apps/launcher/src/main/util/dialog-paths.ts diff --git a/apps/launcher/src/main/ipc/handlers.ts b/apps/launcher/src/main/ipc/handlers.ts index f08af21..440393d 100644 --- a/apps/launcher/src/main/ipc/handlers.ts +++ b/apps/launcher/src/main/ipc/handlers.ts @@ -32,6 +32,7 @@ import { } from '../services/mods/mods-service.ts'; import { resourcePaths } from '../services/resources/resource-paths.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 { broadcast, handle } from './register.ts'; /** Registers the handler of every contract channel. One line per channel; the work is in services/. */ @@ -68,11 +69,18 @@ export function registerIpcHandlers(): void { BrowserWindow.fromWebContents(sender)?.close(); }); - handle('dialog:pickFolder', async ({ title }, sender) => { + handle('dialog:pickFolder', async ({ title, defaultPath }, sender) => { const window = BrowserWindow.fromWebContents(sender); - const options = { properties: ['openDirectory', 'createDirectory'] as Array<'openDirectory' | 'createDirectory'>, ...(title ? { title } : {}) }; + const resolvedDefaultPath = await resolveDialogDefaultPath('folder', defaultPath); + const options = { + properties: ['openDirectory', 'createDirectory'] as Array<'openDirectory' | 'createDirectory'>, + ...(title ? { title } : {}), + ...(resolvedDefaultPath ? { defaultPath: resolvedDefaultPath } : {}), + }; const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options); - return { path: result.canceled ? null : (result.filePaths[0] ?? null) }; + const chosen = result.canceled ? null : (result.filePaths[0] ?? null); + if (chosen) await rememberDialogPath('folder', chosen); + return { path: chosen }; }); handle('install:prepareCopy', () => createCopyDraft()); diff --git a/apps/launcher/src/main/services/mods/mods-service.ts b/apps/launcher/src/main/services/mods/mods-service.ts index 46dc6af..e722056 100644 --- a/apps/launcher/src/main/services/mods/mods-service.ts +++ b/apps/launcher/src/main/services/mods/mods-service.ts @@ -17,6 +17,7 @@ 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'; @@ -236,8 +237,10 @@ export async function exportModPreset( 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: `${safeName}.wto-mods-preset.json`, + defaultPath: defaultDir ? join(defaultDir, fileName) : fileName, filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }], }; const choice = window @@ -252,6 +255,7 @@ export async function exportModPreset( enabled: { ...preset.enabled }, }; await writeFile(choice.filePath, JSON.stringify(payload, null, 2) + '\n', 'utf8'); + await rememberDialogPath('mod-preset', choice.filePath); return { path: choice.filePath }; } @@ -260,9 +264,11 @@ export async function importModPreset( 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) @@ -270,6 +276,7 @@ export async function importModPreset( if (choice.canceled || !choice.filePaths[0]) { return { imported: false, state: await buildModsStateView(copy) }; } + await rememberDialogPath('mod-preset', choice.filePaths[0]); let parsedRaw: unknown; try { @@ -309,6 +316,7 @@ export async function setModsFolder(copyId: string, folderPath: string | null): } } await updateSettings({ modsFolder: folderPath }); + if (folderPath !== null) await rememberDialogPath('mods-folder', folderPath); const copy = await requireCopy(copyId); return buildModsStateView(copy); } diff --git a/apps/launcher/src/main/services/saves/manage-saves.ts b/apps/launcher/src/main/services/saves/manage-saves.ts index c505131..c3a6831 100644 --- a/apps/launcher/src/main/services/saves/manage-saves.ts +++ b/apps/launcher/src/main/services/saves/manage-saves.ts @@ -6,6 +6,7 @@ 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 { 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'; @@ -95,15 +96,27 @@ export async function setSaveCurrencies(copyId: string, userId: string, values: } export async function pickSaveArchive(window: BrowserWindow | null): Promise<{ path: string | null }> { - const options = { properties: ['openFile' as const], filters: [{ name: 'ZIP', extensions: ['zip'] }] }; + const defaultPath = await resolveDialogDefaultPath('save-archive'); + const options = { + properties: ['openFile' as const], + filters: [{ name: 'ZIP', extensions: ['zip'] }], + ...(defaultPath ? { defaultPath } : {}), + }; const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options); - return { path: result.canceled ? null : result.filePaths[0] ?? null }; + const chosen = result.canceled ? null : (result.filePaths[0] ?? null); + if (chosen) await rememberDialogPath('save-archive', chosen); + return { path: chosen }; } 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 options = { defaultPath: `WTOffline-save-${userId}.zip`, filters: [{ name: 'ZIP', extensions: ['zip'] }] }; + 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 result = window ? await dialog.showSaveDialog(window, options) : await dialog.showSaveDialog(options); if (result.canceled || !result.filePath) return { path: null }; try { @@ -113,6 +126,7 @@ 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 }; } @@ -275,9 +289,16 @@ export async function copyOnlineData(copyId: string, userId: string, accountId: } export async function pickOfficialBackups(window: BrowserWindow | null): Promise { - const options = { properties: ['openFile' as const, 'multiSelections' as const], filters: [{ name: 'BLK', extensions: ['blk'] }] }; + const defaultPath = await resolveDialogDefaultPath('official-backups'); + const options = { + properties: ['openFile' as const, 'multiSelections' as const], + filters: [{ name: 'BLK', extensions: ['blk'] }], + ...(defaultPath ? { defaultPath } : {}), + }; const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options); - return result.canceled ? [] : result.filePaths; + if (result.canceled || result.filePaths.length === 0) return []; + if (result.filePaths[0]) await rememberDialogPath('official-backups', result.filePaths[0]); + return result.filePaths; } export async function previewSelectedBackups( diff --git a/apps/launcher/src/main/util/dialog-paths.ts b/apps/launcher/src/main/util/dialog-paths.ts new file mode 100644 index 0000000..ef8fd3a --- /dev/null +++ b/apps/launcher/src/main/util/dialog-paths.ts @@ -0,0 +1,171 @@ +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 `/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; + rememberDialogPath(category: DialogPathCategory, selectedPath: string): Promise; +} + +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 { + 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, +): DialogPathStore { + let cached: Map | null = null; + let loading: Promise> | null = null; + let pending: Promise = Promise.resolve(); + + async function loadMap(): Promise> { + if (cached) return cached; + if (loading) return loading; + + loading = (async () => { + const map = new Map(); + 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)) { + 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 { + 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 { + 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 { + 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 { + return defaultStore.resolveDialogDefaultPath(category, explicitPath); +} + +export function rememberDialogPath(category: DialogPathCategory, selectedPath: string): Promise { + return defaultStore.rememberDialogPath(category, selectedPath); +} diff --git a/apps/launcher/src/renderer/src/components/FolderField.tsx b/apps/launcher/src/renderer/src/components/FolderField.tsx index fa85583..0a6d63e 100644 --- a/apps/launcher/src/renderer/src/components/FolderField.tsx +++ b/apps/launcher/src/renderer/src/components/FolderField.tsx @@ -14,7 +14,10 @@ interface FolderFieldProps { export function FolderField({ path, dialogTitle, disabled = false, onChosen, onError }: FolderFieldProps) { const { t } = useTranslation(); const choose = (): void => { - ipcInvoke('dialog:pickFolder', { title: dialogTitle }) + ipcInvoke('dialog:pickFolder', { + title: dialogTitle, + ...(path ? { defaultPath: path } : {}), + }) .then(({ path: chosen }) => { if (chosen) onChosen(chosen); }) diff --git a/apps/launcher/src/shared/ipc/contract.ts b/apps/launcher/src/shared/ipc/contract.ts index d87aa0f..980c419 100644 --- a/apps/launcher/src/shared/ipc/contract.ts +++ b/apps/launcher/src/shared/ipc/contract.ts @@ -65,8 +65,11 @@ export const ipcContract = { output: z.object({ path: z.string().nullable() }), }, 'dialog:pickFolder': { - /** The dialog title, already translated by the window. */ - input: z.object({ title: z.string().optional() }), + /** The dialog title, already translated by the window, and an optional starting path. */ + input: z.object({ + title: z.string().optional(), + defaultPath: z.string().optional(), + }), /** The chosen folder, or null when the player cancelled. */ output: z.object({ path: z.string().nullable() }), }, From 429c5eec120088e3949d397a65a26e75b612e30f Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Fri, 4 Dec 2026 19:55:04 +0800 Subject: [PATCH 07/22] fix(clans): fix squadron timestamps, 20k RP cap, and configurable initial RP Fix two 1970 squadron timestamps by sending nextRewardDayId as a 64-bit Unix timestamp in seconds and emitting dynamic bi-monthly season fields (clanDuelNextReward, clanSeasonStart, clanSeasonOrdinal, clanSeasonInYear) in clientProfile. Backfill preset normal squadrons to 58-60 deterministic NPC members so the client activity reward cap reaches 20,000, default startingPeriods and startingActivity to 0 in tuning/clans.jsonc, remove the hardcoded 20,000 empty-history fallback, and wire battle RP into squadron activity accumulation and period settlement. --- apps/server/src/battle/battle-settlement.ts | 7 +- .../server/src/char/actions/battle-actions.ts | 12 +- apps/server/src/clans/clan-blk.ts | 16 +- apps/server/src/clans/clan-membership.ts | 6 +- apps/server/src/clans/clan-season.ts | 75 ++++++ apps/server/src/clans/clan-seeds.ts | 131 ++++++++++- apps/server/src/clans/clan-store.ts | 214 +++++++++++++++--- apps/server/src/clans/clan-tuning.ts | 47 +++- apps/server/src/clans/clan-types.ts | 2 + apps/server/src/profile/client-profile.ts | 21 +- apps/server/tuning/clans.jsonc | 57 ++++- 11 files changed, 528 insertions(+), 60 deletions(-) create mode 100644 apps/server/src/clans/clan-season.ts diff --git a/apps/server/src/battle/battle-settlement.ts b/apps/server/src/battle/battle-settlement.ts index dd99412..258d490 100644 --- a/apps/server/src/battle/battle-settlement.ts +++ b/apps/server/src/battle/battle-settlement.ts @@ -53,6 +53,8 @@ export interface BattleSettlementDeps { readonly streaks: BattleStreaks; readonly items: ItemCatalogue; readonly repair: RepairRules; + /** Optional hook receiving total base (unboosted) vehicle RP earned in the battle. */ + readonly onBattleRpEarned?: ((baseVehicleRp: number, nowSec: number) => void) | undefined; } const REPAIR_MODE: Readonly> = { arcade: 'Arcade', realistic: 'Historical', simulator: 'Simulation' }; @@ -87,12 +89,15 @@ export function settleBattle(profile: BlkBlock, report: BattleReport, session: B if (crew && vehicle.expTotal > 0) addEarnedSkillPoints(crew, vehicle.expTotal * crewExpMul); } const weaponRefillSl = refillOwnedEquipment(profile, deps.equipment); - const research = investBattleRp(profile, rewards.vehicles.map(vehicleRpOf), { + const vehicleRps = rewards.vehicles.map(vehicleRpOf); + const research = investBattleRp(profile, vehicleRps, { country: session.country, requiredClass: session.requiredClass, difficulty, nowUnixSec: log.timeSec, }, deps); + const baseVehicleRp = vehicleRps.reduce((sum, vehicle) => sum + Math.max(0, vehicle.noBonusExp), 0); + if (baseVehicleRp > 0) deps.onBattleRpEarned?.(baseVehicleRp, log.timeSec); recordBoosterUses(profile, boosters.uses, log); const wager = activeWager(profile, deps.items); const wagerOutcome = wager && wagerBattle(wager.wager, wager.state, { diff --git a/apps/server/src/char/actions/battle-actions.ts b/apps/server/src/char/actions/battle-actions.ts index c99ab72..0be7ecb 100644 --- a/apps/server/src/char/actions/battle-actions.ts +++ b/apps/server/src/char/actions/battle-actions.ts @@ -13,6 +13,7 @@ import type { BattleEconomy } from '../../battle/battle-economy.ts'; import type { BattleStreaks } from '../../battle/battle-streaks.ts'; import { withoutSupportPlanes } from '../../battle/battle-support-planes.ts'; import type { CrewSkillCatalogue } from '../../crew/crew-skill-rules.ts'; +import type { ClanStore } from '../../clans/clan-store.ts'; import type { ItemCatalogue } from '../../items/item-catalogue.ts'; import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts'; import { clientProfile } from '../../profile/client-profile.ts'; @@ -41,6 +42,7 @@ export interface FinishBattleContext { readonly crew: CrewSkillCatalogue; readonly items: ItemCatalogue; readonly repair: RepairRules; + readonly clans?: { readonly store: ClanStore } | undefined; } export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActionDependencies): CharActionHandler { @@ -67,7 +69,15 @@ export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActio // The result log and expenses are written together. A retry can arrive after the profile // was saved but before the session was marked settled. if (hasBattleResultLog(profile, session.roomId)) return false; - settleBattle(profile, report, session, settlementDeps); + settleBattle(profile, report, session, { + ...settlementDeps, + onBattleRpEarned: ctx.clans + ? (baseVehicleRp, nowSec) => { + ctx.clans!.store.recordBattleActivity(account.userId, baseVehicleRp, nowSec); + ctx.clans!.store.syncProfile(profile, account, nowSec); + } + : undefined, + }); battle.onAfterSettle?.({ userId: account.userId, roomId: session.sessionId, diff --git a/apps/server/src/clans/clan-blk.ts b/apps/server/src/clans/clan-blk.ts index aa78a01..c79e100 100644 --- a/apps/server/src/clans/clan-blk.ts +++ b/apps/server/src/clans/clan-blk.ts @@ -31,6 +31,14 @@ const OPTIONAL_LOG_STRING_KEYS: ReadonlyArray todayDay ? candidateNextDay : todayDay + rewardPeriodDays; + const nextRewardSec = nextRewardDay * 86400; return { name: '', params: [ @@ -57,7 +65,7 @@ export function toClanInfoBlk(clan: ClanRecord, tuning: ClanTuning, nowSec = Mat int('rewardPeriodDays', rewardPeriodDays), bool('expRewardEnabled', true), int('historyDepth', historyDepthDays), - int('nextRewardDayId', todayDay + rewardPeriodDays), + int64('nextRewardDayId', BigInt(nextRewardSec)), ], blocks: [ buildAstatBlock(clan, tuning), @@ -215,7 +223,7 @@ function statParams(stats: ClanStats): BlkParam[] { function buildMemberActivityBlock(member: ClanMemberRecord, todayDay: number): BlkBlock { const periods = member.periods.length > 0 ? member.periods - : [{ day: todayDay, activity: member.curActivity, exp: 20000 }]; + : (member.curActivity > 0 ? [{ day: todayDay, activity: member.curActivity, exp: 0 }] : []); return { name: member.uid, @@ -248,6 +256,10 @@ function int(name: string, value: number): BlkParam { return { name, value: { type: 'int', value: Math.trunc(value) } }; } +function int64(name: string, value: bigint): BlkParam { + return { name, value: { type: 'int64', value } }; +} + function bool(name: string, value: boolean): BlkParam { return { name, value: { type: 'bool', value } }; } diff --git a/apps/server/src/clans/clan-membership.ts b/apps/server/src/clans/clan-membership.ts index 0abd231..287cdc6 100644 --- a/apps/server/src/clans/clan-membership.ts +++ b/apps/server/src/clans/clan-membership.ts @@ -54,13 +54,15 @@ export function addMemberToClan( ): void { if (clan.members.some((m) => m.uid === uid)) return; const periods = buildDefaultPeriods(Math.floor(nowSec / 86400), tuning); + const curActivity = Math.min(tuning.activity.maxPerPeriod, tuning.activity.startingActivity); + const periodActivitySum = periods.reduce((s, p) => s + p.activity, 0); clan.members.push({ uid, nick, role, joinDateSec: nowSec, - curActivity: tuning.activity.maxPerPeriod, - totalActivity: periods.reduce((s, p) => s + p.activity, 0), + curActivity, + totalActivity: periods.length > 0 ? periodActivitySum : curActivity, earnedSquadronExp: periods.reduce((s, p) => s + p.exp, 0), ratingArc: tuning.playerRating.joiner.arc, ratingHist: tuning.playerRating.joiner.hist, diff --git a/apps/server/src/clans/clan-season.ts b/apps/server/src/clans/clan-season.ts new file mode 100644 index 0000000..113079b --- /dev/null +++ b/apps/server/src/clans/clan-season.ts @@ -0,0 +1,75 @@ +/** + * Squadron (clan) battle season schedule matching `char.vromfs.bin` `config/clan_rewards.blk` + * (`seasons{}`): six bi-monthly UTC seasons per year starting on the 1st of Jan, Mar, May, + * Jul, Sep, and Nov at 00:00:00 UTC. + * + * Wire contract verified in stock `aces.exe` (2.61.0.58): + * - `GameSaveData::onAsyncEconTransComplete` (`0xebc33c..0xebc7b4`) reads four top-level + * profile parameters on every profile-returning char transaction: + * - `clanDuelNextReward:i64` (`0xebc731..0xebc745`, `DataBlock::getInt64`) -> `rewardDay` + * - `clanSeasonStart:i64` (`0xebc755..0xebc769`, `DataBlock::getInt64`) -> `startDay` + * - `clanSeasonOrdinal:i` (`0xebc778..0xebc78c`, `DataBlock::getInt`) -> `ordinalNumber` + * - `clanSeasonInYear:i` (`0xebc79a..0xebc7ae`, `DataBlock::getInt`) -> `numberInYear` + * - `clan_get_current_season_info` (`0x178aff0..0x178b227`) exposes those four fields verbatim. + * - `gui.vromfs.bin` `scripts/clans/clanseasons.nut:45-54` formats the title using + * `unixtime_to_utc_timetbl(info.startDay).year` and `info.numberInYear + 1` + * (`CLAN_SEASON_NUM_IN_YEAR_SHIFT = 1`, yielding Roman numerals `I`..`VI`), and formats the + * end time with `time.buildDateTimeStr(info.rewardDay, false, false)`. + */ + +export interface ClanSeasonInfo { + /** UTC 00:00:00 start of the active season as Unix seconds. */ + readonly startDaySec: number; + /** UTC 00:00:00 end/reward timestamp of the active season (start of next season) as Unix seconds. */ + readonly rewardDaySec: number; + /** Zero-based season index within the UTC year (`0..5`, displayed as `I..VI`). */ + readonly numberInYear: number; + /** Monotonic positive ordinal season number across years. */ + readonly ordinalNumber: number; +} + +/** Season start month/day pairs from `char.vromfs.bin` `config/clan_rewards.blk` `seasons{}`. */ +export const CLAN_SEASON_STARTS: ReadonlyArray<{ readonly month: number; readonly day: number }> = [ + { month: 1, day: 1 }, + { month: 3, day: 1 }, + { month: 5, day: 1 }, + { month: 7, day: 1 }, + { month: 9, day: 1 }, + { month: 11, day: 1 }, +]; + +const SEASON_ORDINAL_BASE_YEAR = 2016; + +/** Compute the active squadron battle season for a given Unix timestamp in seconds. */ +export function currentClanSeason(nowSec = Math.floor(Date.now() / 1000)): ClanSeasonInfo { + const now = new Date(Math.trunc(nowSec) * 1000); + const year = now.getUTCFullYear(); + const seasonCount = CLAN_SEASON_STARTS.length; + + let activeIndex = 0; + let startSec = Date.UTC(year, CLAN_SEASON_STARTS[0]!.month - 1, CLAN_SEASON_STARTS[0]!.day) / 1000; + + for (let i = seasonCount - 1; i >= 0; i--) { + const entry = CLAN_SEASON_STARTS[i]!; + const candidateSec = Date.UTC(year, entry.month - 1, entry.day) / 1000; + if (nowSec >= candidateSec) { + activeIndex = i; + startSec = candidateSec; + break; + } + } + + const nextIndex = (activeIndex + 1) % seasonCount; + const nextYear = activeIndex + 1 >= seasonCount ? year + 1 : year; + const nextEntry = CLAN_SEASON_STARTS[nextIndex]!; + const rewardSec = Date.UTC(nextYear, nextEntry.month - 1, nextEntry.day) / 1000; + + const ordinalNumber = Math.max(1, (year - SEASON_ORDINAL_BASE_YEAR) * seasonCount + activeIndex + 1); + + return { + startDaySec: startSec, + rewardDaySec: rewardSec, + numberInYear: activeIndex, + ordinalNumber, + }; +} diff --git a/apps/server/src/clans/clan-seeds.ts b/apps/server/src/clans/clan-seeds.ts index f37e4ae..72f0f1b 100644 --- a/apps/server/src/clans/clan-seeds.ts +++ b/apps/server/src/clans/clan-seeds.ts @@ -3,25 +3,75 @@ * The directory is written when the server first creates `/clans.json`. */ import type { ClanTuning, PresetClan, PresetMember } from './clan-tuning.ts'; -import type { ClanActivityPeriodEntry, ClanMemberRecord, ClanRecord } from './clan-types.ts'; +import { ClanRole, type ClanActivityPeriodEntry, type ClanMemberRecord, type ClanRecord } from './clan-types.ts'; const SECONDS_PER_DAY = 86400; export function createDefaultClans(tuning: ClanTuning, nowSec = Math.floor(Date.now() / 1000)): ClanRecord[] { const todayDay = Math.floor(nowSec / SECONDS_PER_DAY); const createdBase = nowSec - tuning.presetClans.createdDaysAgo * SECONDS_PER_DAY; - return tuning.presetClans.clans.map((spec) => buildSeededClan(spec, createdBase + spec.createdAfterDays * SECONDS_PER_DAY, todayDay, tuning)); + return tuning.presetClans.clans.map((spec, specIndex) => + buildSeededClan(spec, specIndex, createdBase + spec.createdAfterDays * SECONDS_PER_DAY, todayDay, tuning)); } -/** The activity periods a member starts with: startingPeriods periods, each with the given activity and the squadron RP it earns. */ -export function buildDefaultPeriods(todayDay: number, tuning: ClanTuning, periodActivity = tuning.activity.maxPerPeriod): ClanActivityPeriodEntry[] { - const { maxPerPeriod, squadronRpPerFullPeriod, rewardPeriodDays, startingPeriods } = tuning.activity; +/** + * The activity periods a member starts with: `periodCount` periods (defaulting to + * `activity.startingPeriods`), each with the given activity and the squadron RP it earns. + */ +export function buildDefaultPeriods( + todayDay: number, + tuning: ClanTuning, + periodActivity = tuning.activity.maxPerPeriod, + periodCount = tuning.activity.startingPeriods, +): ClanActivityPeriodEntry[] { + if (periodCount <= 0) return []; + const { maxPerPeriod, squadronRpPerFullPeriod, rewardPeriodDays } = tuning.activity; const exp = Math.round((periodActivity / maxPerPeriod) * squadronRpPerFullPeriod); - return Array.from({ length: startingPeriods }, (_, idx) => ({ day: todayDay - idx * rewardPeriodDays, activity: periodActivity, exp })); + return Array.from({ length: periodCount }, (_, idx) => ({ day: todayDay - idx * rewardPeriodDays, activity: periodActivity, exp })); } -function buildSeededClan(spec: PresetClan, cdateSec: number, todayDay: number, tuning: ClanTuning): ClanRecord { - const members = spec.members.map((npc, idx) => buildSeededMember(spec, npc, idx, cdateSec, todayDay, tuning)); +/** + * Idempotently appends deterministic filler NPCs to an existing preset clan whose + * persisted roster is smaller than its configured `targetMemberCount`, without altering + * any existing player or NPC members. + */ +export function backfillPresetClanMembers( + clan: ClanRecord, + spec: PresetClan, + specIndex: number, + todayDay: number, + tuning: ClanTuning, +): boolean { + const targetCount = Math.min(clan.mlimit, spec.targetMemberCount); + if (clan.members.length >= targetCount) return false; + + const existingUids = new Set(clan.members.map((m) => m.uid)); + const fillerSpecs = buildPresetFillerSpecs(spec, specIndex, tuning); + let added = false; + for (let i = 0; i < fillerSpecs.length && clan.members.length < targetCount; i++) { + const npc = fillerSpecs[i]!; + if (existingUids.has(npc.uid)) continue; + existingUids.add(npc.uid); + const memberIdx = spec.members.length + i; + clan.members.push(buildSeededMember(spec, npc, memberIdx, clan.cdateSec, todayDay, tuning)); + added = true; + } + return added; +} + +function buildSeededClan( + spec: PresetClan, + specIndex: number, + cdateSec: number, + todayDay: number, + tuning: ClanTuning, +): ClanRecord { + const mlimit = spec.type === 'battalion' ? tuning.memberLimits.battalionInitial : tuning.memberLimits.normal; + const allSpecs: PresetMember[] = [ + ...spec.members, + ...buildPresetFillerSpecs(spec, specIndex, tuning), + ].slice(0, mlimit); + const members = allSpecs.map((npc, idx) => buildSeededMember(spec, npc, idx, cdateSec, todayDay, tuning)); const leader = spec.members[0]!; return { id: spec.id, @@ -35,13 +85,14 @@ function buildSeededClan(spec: PresetClan, cdateSec: number, todayDay: number, t region: spec.region, status: 'open', autoaccept: spec.autoAccept, - mlimit: spec.type === 'battalion' ? tuning.memberLimits.battalionInitial : tuning.memberLimits.normal, + mlimit, mspent: 0, cdateSec, changedByUid: leader.uid, changedByNick: leader.nick, changedTimeSec: cdateSec, regionLastUpdatedSec: 0, + lastRewardDay: todayDay, stats: { dr_era5_arc: spec.rating.arc, dr_era5_hist: spec.rating.hist, dr_era5_sim: spec.rating.sim, ...tuning.presetClans.stats }, members, candidates: [], @@ -55,8 +106,64 @@ function buildSeededClan(spec: PresetClan, cdateSec: number, todayDay: number, t }; } -function buildSeededMember(spec: PresetClan, npc: PresetMember, idx: number, cdateSec: number, todayDay: number, tuning: ClanTuning): ClanMemberRecord { - const periods = buildDefaultPeriods(todayDay, tuning, npc.activity); +function buildPresetFillerSpecs(spec: PresetClan, specIndex: number, tuning: ClanTuning): PresetMember[] { + const mlimit = spec.type === 'battalion' ? tuning.memberLimits.battalionInitial : tuning.memberLimits.normal; + const targetCount = Math.min(mlimit, Math.max(spec.members.length, spec.targetMemberCount)); + const needed = targetCount - spec.members.length; + if (needed <= 0) return []; + + const filler = tuning.presetClans.fillerMembers; + const clanSlot = presetClanSlot(spec.id, specIndex); + const usedUids = new Set(spec.members.map((m) => m.uid)); + const span = Math.max(0, filler.activityMax - filler.activityMin); + const result: PresetMember[] = []; + + let ordinal = spec.members.length + 1; + while (result.length < needed) { + const uid = String(filler.uidBase + clanSlot * filler.uidStride + ordinal); + if (usedUids.has(uid)) { + ordinal++; + continue; + } + usedUids.add(uid); + const callsign = filler.callsigns[(clanSlot * 7 + ordinal) % filler.callsigns.length]!; + const title = filler.titles[(clanSlot * 3 + ordinal) % filler.titles.length]!; + const icon = filler.icons[(clanSlot * 5 + ordinal) % filler.icons.length]!; + const unit = filler.units[(clanSlot * 11 + ordinal) % filler.units.length]!; + const activityOffset = span > 0 ? (clanSlot * 13 + ordinal * 17) % (span + 1) : 0; + const activity = Math.min(tuning.activity.maxPerPeriod, filler.activityMin + activityOffset); + result.push({ + uid, + nick: `${callsign}_${clanSlot}${String(ordinal).padStart(2, '0')}`, + role: ClanRole.REGULAR, + title, + icon, + unit, + activity, + }); + ordinal++; + } + return result; +} + +function presetClanSlot(clanId: string, specIndex: number): number { + const parsed = Number(clanId); + if (Number.isSafeInteger(parsed) && parsed > 0) { + const remainder = parsed % 1000; + if (remainder > 0) return remainder; + } + return specIndex + 1; +} + +function buildSeededMember( + spec: PresetClan, + npc: PresetMember, + idx: number, + cdateSec: number, + todayDay: number, + tuning: ClanTuning, +): ClanMemberRecord { + const periods = buildDefaultPeriods(todayDay, tuning, npc.activity, tuning.presetClans.npcHistoryPeriods); const { step, floor } = tuning.presetClans.memberRating; return { uid: npc.uid, @@ -69,7 +176,7 @@ function buildSeededMember(spec: PresetClan, npc: PresetMember, idx: number, cda npcFrame: '', npcShowcaseUnit: npc.unit, curActivity: npc.activity, - totalActivity: periods.reduce((sum, p) => sum + p.activity, 0), + totalActivity: periods.length > 0 ? periods.reduce((sum, p) => sum + p.activity, 0) : npc.activity, earnedSquadronExp: periods.reduce((sum, p) => sum + p.exp, 0), ratingArc: Math.max(floor.arc, spec.rating.arc - idx * step.arc), ratingHist: Math.max(floor.hist, spec.rating.hist - idx * step.hist), diff --git a/apps/server/src/clans/clan-store.ts b/apps/server/src/clans/clan-store.ts index 032b26a..5104585 100644 --- a/apps/server/src/clans/clan-store.ts +++ b/apps/server/src/clans/clan-store.ts @@ -39,10 +39,12 @@ import { type MembershipRequestQuery, } from './clan-membership.ts'; import { findClanInList, queryClanLeaderboard, type LeaderboardQuery } from './clan-queries.ts'; -import { createDefaultClans } from './clan-seeds.ts'; +import { backfillPresetClanMembers, createDefaultClans } from './clan-seeds.ts'; import type { ClanTuning } from './clan-tuning.ts'; import type { ClanBestReward, ClanMemberRecord, ClanRecord } from './clan-types.ts'; +const SECONDS_PER_DAY = 86400; + export type { LeaderboardQuery }; export class ClanStore { @@ -51,18 +53,36 @@ export class ClanStore { readonly tuning: ClanTuning; #state: StoredClansState; - constructor(dataFolder: string, tuning: ClanTuning) { + constructor(dataFolder: string, tuning: ClanTuning, nowSec = nowSeconds()) { this.#filePath = join(dataFolder, 'clans.json'); this.tuning = tuning; - this.#state = this.#loadOrSeed(); + this.#state = this.#loadOrSeed(nowSec); } - #loadOrSeed(): StoredClansState { + #loadOrSeed(nowSec: number): StoredClansState { + const todayDay = Math.floor(nowSec / SECONDS_PER_DAY); if (existsSync(this.#filePath)) { const parsed = JSON.parse(readFileSync(this.#filePath, 'utf8')) as StoredClansState; - if (Array.isArray(parsed.clans) && typeof parsed.nextClanId === 'number') return parsed; + if (Array.isArray(parsed.clans) && typeof parsed.nextClanId === 'number') { + let mutated = false; + for (let i = 0; i < this.tuning.presetClans.clans.length; i++) { + const spec = this.tuning.presetClans.clans[i]!; + const existing = parsed.clans.find((c) => c.id === spec.id); + if (existing && backfillPresetClanMembers(existing, spec, i, todayDay, this.tuning)) { + mutated = true; + } + } + for (const clan of parsed.clans) { + if (clan.lastRewardDay === undefined) { + clan.lastRewardDay = todayDay; + mutated = true; + } + } + if (mutated) this.#save(parsed); + return parsed; + } } - const seeded: StoredClansState = { nextClanId: this.tuning.firstNewClanId, clans: createDefaultClans(this.tuning) }; + const seeded: StoredClansState = { nextClanId: this.tuning.firstNewClanId, clans: createDefaultClans(this.tuning, nowSec) }; this.#save(seeded); return seeded; } @@ -71,19 +91,7 @@ export class ClanStore { writeFileAtomic(this.#filePath, JSON.stringify(state, null, 2)); } - #resolveClan(clanId: string | undefined, userId: string): ClanRecord | undefined { - return clanId && clanId !== '-1' ? this.byId(clanId) : this.clanOfUser(userId)?.clan; - } - - byId(clanId: string): ClanRecord | undefined { - return this.#state.clans.find((c) => c.id === clanId); - } - - findClan(query: { readonly clanId?: string | undefined; readonly clanName?: string | undefined; readonly clanTag?: string | undefined }): ClanRecord | undefined { - return findClanInList(this.#state.clans, query); - } - - clanOfUser(userId: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined { + #findUserClan(userId: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined { for (const clan of this.#state.clans) { const member = clan.members.find((m) => m.uid === userId); if (member) return { clan, member }; @@ -91,12 +99,147 @@ export class ClanStore { return undefined; } + #resolveClan(clanId: string | undefined, userId: string): ClanRecord | undefined { + return clanId && clanId !== '-1' + ? this.#state.clans.find((c) => c.id === clanId) + : this.#findUserClan(userId)?.clan; + } + + /** + * Lazily settles expired activity reward periods for all squadrons using the stock + * client formula (`clanAverageActivityModal.nut:44-54`): + * `myExp = min(min(1, myPercent / clanPercent) * clanActivity, maxClanActivity)` + * Player members' current-period activity resets to 0 for the new period while NPC + * members keep their active roster contribution. + */ + settleExpiredPeriods(nowSec = nowSeconds()): boolean { + const todayDay = Math.floor(nowSec / SECONDS_PER_DAY); + const { + maxPerPeriod, + squadronRpPerFullPeriod: maxClanActivity, + rewardPeriodDays, + historyDepthDays, + } = this.tuning.activity; + + let mutated = false; + for (const clan of this.#state.clans) { + if (clan.lastRewardDay === undefined) { + clan.lastRewardDay = todayDay; + mutated = true; + continue; + } + const elapsedDays = todayDay - clan.lastRewardDay; + if (elapsedDays < rewardPeriodDays) continue; + + const anchorDay = clan.lastRewardDay; + const periodsPassed = Math.floor(elapsedDays / rewardPeriodDays); + const settlementDay = anchorDay + rewardPeriodDays; + const nextAnchorDay = anchorDay + periodsPassed * rewardPeriodDays; + const clanActivity = clan.members.reduce((sum, m) => sum + Math.max(0, m.curActivity), 0); + const maxActivity = maxPerPeriod * clan.members.length; + const clanPercent = maxActivity > 0 ? clanActivity / maxActivity : 0; + const minKeptDay = settlementDay - historyDepthDays; + + clan.members = clan.members.map((member) => { + const myActivity = Math.max(0, member.curActivity); + const myPercent = maxPerPeriod > 0 ? myActivity / maxPerPeriod : 0; + const myExp = (myPercent > 0 && clanPercent > 0) + ? Math.min(maxClanActivity, Math.round(Math.min(1, myPercent / clanPercent) * clanActivity)) + : 0; + const pastSettled = member.periods.filter((p) => !(p.exp === 0 && p.day >= anchorDay && p.day <= settlementDay)); + const settledEntry = (myActivity > 0 || myExp > 0) + ? [{ day: settlementDay, activity: myActivity, exp: myExp }] + : []; + const nextPeriods = [...settledEntry, ...pastSettled].filter((p) => p.day >= minKeptDay); + if (member.isNpc) { + return { + ...member, + totalActivity: member.totalActivity + myActivity, + earnedSquadronExp: member.earnedSquadronExp + myExp, + periods: nextPeriods, + }; + } + return { + ...member, + curActivity: 0, + earnedSquadronExp: member.earnedSquadronExp + myExp, + periods: nextPeriods, + }; + }); + + clan.lastRewardDay = nextAnchorDay; + mutated = true; + } + + if (mutated) this.#save(); + return mutated; + } + + /** + * Accumulates current-period squadron activity from battle base vehicle RP + * (`floor(baseVehicleRp / rpPerActivityPoint)`, capped at `maxPerPeriod`). + * Returns the activity points actually added. + */ + recordBattleActivity(userId: string, baseVehicleRp: number, nowSec = nowSeconds()): number { + this.settleExpiredPeriods(nowSec); + if (!Number.isFinite(baseVehicleRp) || baseVehicleRp <= 0) return 0; + const found = this.#findUserClan(userId); + if (!found) return 0; + + const { maxPerPeriod, rpPerActivityPoint } = this.tuning.activity; + const rawGain = Math.floor(baseVehicleRp / rpPerActivityPoint); + if (rawGain <= 0) return 0; + + const { clan, member } = found; + const remaining = Math.max(0, maxPerPeriod - member.curActivity); + const added = Math.min(rawGain, remaining); + if (added <= 0) return 0; + + const todayDay = Math.floor(nowSec / SECONDS_PER_DAY); + const periodStartDay = clan.lastRewardDay ?? todayDay; + const nextCurActivity = member.curActivity + added; + const nextTotalActivity = member.totalActivity + added; + const existingInProgressIdx = member.periods.findIndex((p) => p.exp === 0 && p.day >= periodStartDay); + const nextPeriods = existingInProgressIdx >= 0 + ? member.periods.map((p, idx) => (idx === existingInProgressIdx ? { day: todayDay, activity: nextCurActivity, exp: 0 } : p)) + : [{ day: todayDay, activity: nextCurActivity, exp: 0 }, ...member.periods]; + + const memberIdx = clan.members.findIndex((m) => m.uid === userId); + if (memberIdx < 0) return 0; + clan.members[memberIdx] = { + ...member, + curActivity: nextCurActivity, + totalActivity: nextTotalActivity, + periods: nextPeriods, + }; + this.#save(); + return added; + } + + byId(clanId: string, nowSec = nowSeconds()): ClanRecord | undefined { + this.settleExpiredPeriods(nowSec); + return this.#state.clans.find((c) => c.id === clanId); + } + + findClan( + query: { readonly clanId?: string | undefined; readonly clanName?: string | undefined; readonly clanTag?: string | undefined }, + nowSec = nowSeconds(), + ): ClanRecord | undefined { + this.settleExpiredPeriods(nowSec); + return findClanInList(this.#state.clans, query); + } + + clanOfUser(userId: string, nowSec = nowSeconds()): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined { + this.settleExpiredPeriods(nowSec); + return this.#findUserClan(userId); + } + pendingRequestOfUser(userId: string): ClanRecord | undefined { return this.#state.clans.find((c) => c.candidates.some((cand) => cand.uid === userId)); } - earnedSquadronExpOf(userId: string): number { - return this.clanOfUser(userId)?.member.earnedSquadronExp ?? 0; + earnedSquadronExpOf(userId: string, nowSec = nowSeconds()): number { + return this.clanOfUser(userId, nowSec)?.member.earnedSquadronExp ?? 0; } npcMemberByUid(uid: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined { @@ -107,8 +250,8 @@ export class ClanStore { return undefined; } - syncProfile(profile: BlkBlock, account: Account): void { - const found = this.clanOfUser(account.userId); + syncProfile(profile: BlkBlock, account: Account, nowSec = nowSeconds()): void { + const found = this.clanOfUser(account.userId, nowSec); if (found) { const { clan, member } = found; if (member.nick !== account.nick) { @@ -131,15 +274,31 @@ export class ClanStore { } } - queryLeaderboard(query: LeaderboardQuery): ReadonlyArray<{ readonly clan: ClanRecord; readonly pos: number }> { + queryLeaderboard(query: LeaderboardQuery, nowSec = nowSeconds()): ReadonlyArray<{ readonly clan: ClanRecord; readonly pos: number }> { + this.settleExpiredPeriods(nowSec); return queryClanLeaderboard(this.#state.clans, query, this.tuning); } createClan(profile: BlkBlock, account: Account, economy: ClanEconomy, input: CreateClanInput, nowSec = nowSeconds()): RuleOutcome { + this.settleExpiredPeriods(nowSec); const outcome = createClanInState(this.#state, profile, account, economy, this.tuning, input, nowSec); if (outcome.ok) { + const created = this.#state.clans[0]; + if (created) { + created.lastRewardDay = Math.floor(nowSec / SECONDS_PER_DAY); + const founder = created.members[0]; + if (founder && founder.uid === account.userId) { + const curActivity = Math.min(this.tuning.activity.maxPerPeriod, this.tuning.activity.startingActivity); + const periodActivitySum = founder.periods.reduce((s, p) => s + p.activity, 0); + created.members[0] = { + ...founder, + curActivity, + totalActivity: founder.periods.length > 0 ? periodActivitySum : curActivity, + }; + } + } this.#save(); - this.syncProfile(profile, account); + this.syncProfile(profile, account, nowSec); } return outcome; } @@ -189,10 +348,11 @@ export class ClanStore { } requestOrCancelMembership(profile: BlkBlock, account: Account, query: MembershipRequestQuery, nowSec = nowSeconds()): RuleOutcome { - const res = requestOrCancelMembershipInState(this.#state.clans, this.findClan(query), Boolean(this.clanOfUser(account.userId)), account, query, nowSec, this.tuning); + this.settleExpiredPeriods(nowSec); + const res = requestOrCancelMembershipInState(this.#state.clans, findClanInList(this.#state.clans, query), Boolean(this.#findUserClan(account.userId)), account, query, nowSec, this.tuning); if (res.mutated) { this.#save(); - this.syncProfile(profile, account); + this.syncProfile(profile, account, nowSec); } return res.outcome; } diff --git a/apps/server/src/clans/clan-tuning.ts b/apps/server/src/clans/clan-tuning.ts index 8a2e063..cd7b521 100644 --- a/apps/server/src/clans/clan-tuning.ts +++ b/apps/server/src/clans/clan-tuning.ts @@ -26,6 +26,17 @@ export interface PresetMember { readonly activity: number; } +export interface PresetFillerMembers { + readonly activityMin: number; + readonly activityMax: number; + readonly uidBase: number; + readonly uidStride: number; + readonly callsigns: readonly string[]; + readonly titles: readonly string[]; + readonly icons: readonly string[]; + readonly units: readonly string[]; +} + export interface PresetClan { readonly id: string; readonly tag: string; @@ -37,6 +48,7 @@ export interface PresetClan { readonly region: string; readonly autoAccept: boolean; readonly createdAfterDays: number; + readonly targetMemberCount: number; readonly rating: ModeTriple; readonly members: readonly PresetMember[]; } @@ -47,6 +59,8 @@ export interface ClanTuning { readonly squadronRpPerFullPeriod: number; readonly rewardPeriodDays: number; readonly historyDepthDays: number; + readonly rpPerActivityPoint: number; + readonly startingActivity: number; readonly startingPeriods: number; }; readonly memberLimits: { readonly normal: number; readonly battalionInitial: number }; @@ -56,6 +70,8 @@ export interface ClanTuning { readonly presetClans: { readonly createdDaysAgo: number; readonly memberJoinSpacingMinutes: number; + readonly npcHistoryPeriods: number; + readonly fillerMembers: PresetFillerMembers; readonly stats: PresetClanStats; readonly memberRating: { readonly step: ModeTriple; readonly floor: ModeTriple }; readonly clans: readonly PresetClan[]; @@ -64,6 +80,7 @@ export interface ClanTuning { export function readClanTuning(file: TuningReader): ClanTuning { const activity = file.object('activity'); + const maxPerPeriod = activity.int('maxPerPeriod', { min: 1 }); const limits = file.object('memberLimits'); const leaderboard = file.object('leaderboard'); const preset = file.object('presetClans'); @@ -71,10 +88,12 @@ export function readClanTuning(file: TuningReader): ClanTuning { const rating = preset.object('memberRating'); return { activity: { - maxPerPeriod: activity.int('maxPerPeriod', { min: 1 }), + maxPerPeriod, squadronRpPerFullPeriod: activity.int('squadronRpPerFullPeriod', { min: 0 }), rewardPeriodDays: activity.int('rewardPeriodDays', { min: 1 }), historyDepthDays: activity.int('historyDepthDays', { min: 1 }), + rpPerActivityPoint: activity.int('rpPerActivityPoint', { min: 1 }), + startingActivity: activity.int('startingActivity', { min: 0, max: maxPerPeriod }), startingPeriods: activity.int('startingPeriods', { min: 0 }), }, memberLimits: { normal: limits.int('normal', { min: 1 }), battalionInitial: limits.int('battalionInitial', { min: 1 }) }, @@ -84,6 +103,8 @@ export function readClanTuning(file: TuningReader): ClanTuning { presetClans: { createdDaysAgo: preset.int('createdDaysAgo', { min: 0 }), memberJoinSpacingMinutes: preset.int('memberJoinSpacingMinutes', { min: 0 }), + npcHistoryPeriods: preset.int('npcHistoryPeriods', { min: 0 }), + fillerMembers: readFillerMembers(preset.object('fillerMembers'), maxPerPeriod), stats: Object.fromEntries(STAT_KEYS.map((key) => [key, stats.int(key, { min: 0 })])) as unknown as PresetClanStats, memberRating: { step: triple(rating.object('step')), floor: triple(rating.object('floor')) }, clans: preset.list('clans', readPresetClan), @@ -91,11 +112,34 @@ export function readClanTuning(file: TuningReader): ClanTuning { }; } +function readFillerMembers(entry: TuningReader, maxPerPeriod: number): PresetFillerMembers { + const activityMin = entry.int('activityMin', { min: 0, max: maxPerPeriod }); + const activityMax = entry.int('activityMax', { min: activityMin, max: maxPerPeriod }); + const callsigns = entry.stringList('callsigns'); + const titles = entry.stringList('titles'); + const icons = entry.stringList('icons'); + const units = entry.stringList('units'); + if (callsigns.length === 0 || titles.length === 0 || icons.length === 0 || units.length === 0) { + throw new TuningError('tuning file clans.jsonc: presetClans.fillerMembers callsigns, titles, icons, and units must be non-empty'); + } + return { + activityMin, + activityMax, + uidBase: entry.int('uidBase', { min: 1 }), + uidStride: entry.int('uidStride', { min: 1 }), + callsigns, + titles, + icons, + units, + }; +} + function readPresetClan(entry: TuningReader): PresetClan { const type = entry.string('type'); if (type !== 'normal' && type !== 'battalion') throw new TuningError(`tuning file clans.jsonc: clan type must be normal or battalion (found "${type}")`); const members = entry.list('members', readPresetMember); if (members.length === 0) throw new TuningError(`tuning file clans.jsonc: preset clan ${entry.string('id')} needs at least one member (the first is its leader)`); + const rawTarget = entry.has('targetMemberCount') ? entry.int('targetMemberCount', { min: 1 }) : members.length; return { id: entry.string('id'), tag: entry.string('tag'), @@ -107,6 +151,7 @@ function readPresetClan(entry: TuningReader): PresetClan { region: entry.string('region'), autoAccept: entry.bool('autoAccept'), createdAfterDays: entry.int('createdAfterDays', { min: 0 }), + targetMemberCount: Math.max(members.length, rawTarget), rating: triple(entry.object('rating')), members, }; diff --git a/apps/server/src/clans/clan-types.ts b/apps/server/src/clans/clan-types.ts index c07ad84..9024419 100644 --- a/apps/server/src/clans/clan-types.ts +++ b/apps/server/src/clans/clan-types.ts @@ -171,6 +171,8 @@ export interface ClanRecord { changedByNick: string; changedTimeSec: number; regionLastUpdatedSec: number; + /** UTC day index (floor(unixSec / 86400)) when the current activity reward period started. */ + lastRewardDay?: number; stats: ClanStats; members: ClanMemberRecord[]; candidates: ClanCandidateRecord[]; diff --git a/apps/server/src/profile/client-profile.ts b/apps/server/src/profile/client-profile.ts index da812bc..9a39f34 100644 --- a/apps/server/src/profile/client-profile.ts +++ b/apps/server/src/profile/client-profile.ts @@ -1,22 +1,30 @@ /** * The profile as the char service hands it to the client: the saved profile plus the - * account data and server clock the char server attaches on the wire. + * account data, server clock, and active squadron season metadata the char server attaches + * on the wire. * * charDrivenNick: the client reads the player's nick from this top-level string when it * loads a profile (name looked up at aces.exe 2.61.0.37 0x8fe0aa, value stored at 0x91874d). * * serverTime:i64: the char server's clock; without it the client * takes the server time as 0 and every expiry and time limit is wrong. + * + * clanDuelNextReward:i64, clanSeasonStart:i64, clanSeasonOrdinal:i, clanSeasonInYear:i: + * parsed by GameSaveData::onAsyncEconTransComplete (aces.exe 2.61.0.58 0xebc728..0xebc7b4) + * on every profile-returning char response and exposed by clan_get_current_season_info + * (0x178aff0..0x178b227). Without them all fields default to 0, causing the squadron + * leaderboard to display "1970-I" and "1970-01-01". */ import { setParam, type BlkBlock } from '@wto/blk'; import type { Account } from '../accounts/account-store.ts'; +import { currentClanSeason } from '../clans/clan-season.ts'; import { appearance, DEFAULT_PILOT_ICON } from './profile-appearance.ts'; import { DAILY_SPARES_BLOCK } from './profile-daily-spares.ts'; import { clearStoreCart } from './profile-store-cart.ts'; import { clientHangarSpares } from './profile-vehicle-state.ts'; -import { serverTimeNow } from './server-time.ts'; +import { serverTimeFromUnixMs } from './server-time.ts'; -export function clientProfile(saved: BlkBlock, account: Account): BlkBlock { +export function clientProfile(saved: BlkBlock, account: Account, nowMs = Date.now()): BlkBlock { // Clone the hangar entries whose spare count has a different wire representation. const profile: BlkBlock = { name: saved.name, @@ -26,8 +34,13 @@ export function clientProfile(saved: BlkBlock, account: Account): BlkBlock { }; clearStoreCart(profile); const pilotIcon = appearance(profile).pilotIcon || DEFAULT_PILOT_ICON; + const season = currentClanSeason(Math.floor(nowMs / 1000)); setParam(profile, 'pilotIcon', { type: 'string', value: pilotIcon }); setParam(profile, 'charDrivenNick', { type: 'string', value: account.nick }); - setParam(profile, 'serverTime', { type: 'int64', value: serverTimeNow() }); + setParam(profile, 'serverTime', { type: 'int64', value: serverTimeFromUnixMs(nowMs) }); + setParam(profile, 'clanDuelNextReward', { type: 'int64', value: BigInt(season.rewardDaySec) }); + setParam(profile, 'clanSeasonStart', { type: 'int64', value: BigInt(season.startDaySec) }); + setParam(profile, 'clanSeasonOrdinal', { type: 'int', value: season.ordinalNumber }); + setParam(profile, 'clanSeasonInYear', { type: 'int', value: season.numberInYear }); return profile; } diff --git a/apps/server/tuning/clans.jsonc b/apps/server/tuning/clans.jsonc index d84dae5..a80b239 100644 --- a/apps/server/tuning/clans.jsonc +++ b/apps/server/tuning/clans.jsonc @@ -2,19 +2,25 @@ { // Set activity and squadron RP. The service reports maxActivityPerPeriod, maxClanActivity, rewardPeriodDays, and historyDepth in squadron replies. "activity": { - "maxPerPeriod": 360, // Activity cap per reward period. + "maxPerPeriod": 360, // Activity cap per reward period. "squadronRpPerFullPeriod": 20000, // Squadron RP awarded for a full activity period. "rewardPeriodDays": 3, // Reward period in days. "historyDepthDays": 14, // Activity history displayed by the client, in days. - // Seed full periods on creation or joining so squadron research can start immediately. - "startingPeriods": 3 + // Base vehicle RP from battles required for 1 squadron activity point (stock rule: 200 RP = 1 point). + "rpPerActivityPoint": 200, + // Starting current-period activity for a player creating or joining a squadron (0..maxPerPeriod). + // Set to 360 together with startingPeriods > 0 in /tuning/clans.jsonc to start at full activity immediately. + "startingActivity": 0, + // Full past activity periods granted on creation or joining (default 0: earn activity through battles). + // Increase (e.g. 1 or 3) in /tuning/clans.jsonc to grant immediate squadron RP on joining. + "startingPeriods": 0 }, // Set the full squadron cap and initial battalion cap. Expansion cost and step size are read from warpoints.blk. "memberLimits": { "normal": 128, "battalionInitial": 10 }, - // Displayed leaderboard activity is min(maxActivity, summed member activity * activityMultiplier), so small NPC rosters can represent full squadrons. - "leaderboard": { "activityMultiplier": 10, "maxActivity": 100000 }, + // Displayed leaderboard activity is min(maxActivity, summed member activity * activityMultiplier). + "leaderboard": { "activityMultiplier": 1, "maxActivity": 100000 }, // Starting ID for player-created squadrons. "firstNewClanId": 600001, @@ -29,6 +35,37 @@ "presetClans": { "createdDaysAgo": 180, // Age of the first seeded squadron before applying each squadron's createdAfterDays offset. "memberJoinSpacingMinutes": 60, + "npcHistoryPeriods": 3, // Past activity periods seeded for preset NPC members. + // Deterministic filler NPC pool used when a preset clan's targetMemberCount exceeds its named roster. + "fillerMembers": { + "activityMin": 340, + "activityMax": 360, + "uidBase": 900000000, + "uidStride": 1000, + "callsigns": [ + "Vanguard", "Falcon", "Striker", "Sentinel", "Raptor", "Valkyrie", + "Tempest", "Bastion", "Corsair", "Drago", "Harrier", "Kestrel", + "Lancer", "Mirage", "Nomad", "Osprey", "Paladin", "Reaper", + "Sabre", "Talon", "Vector", "Warden", "Zephyr", "Aegis", + "Cobra", "Hornet", "Jaguar", "Lynx", "Mantis", "Puma" + ], + "titles": [ + "title_pilot", "title_tankman", "title_ace", "title_sniper", + "title_scout", "title_eagle", "title_tank_destroyer", "title_jet_powered" + ], + "icons": [ + "cardicon_03", "cardicon_05", "cardicon_07", "cardicon_08", + "cardicon_09", "cardicon_11", "cardicon_12", "cardicon_14", + "cardicon_15", "cardicon_16", "cardicon_18", "cardicon_19", + "cardicon_20", "cardicon_22", "cardicon_25", "cardicon_28" + ], + "units": [ + "cn_ztz_99a", "su_27sm", "germ_leopard_2a7v", "f_14b", + "jp_destroyer_shimakaze", "sw_strv_122b_plus", "j_11a", "jh_7a", + "cn_vt_4a1", "f_15j_kai", "ussr_t_90m", "us_m1a2_sep2_abrams", + "uk_challenger_2_black_night", "us_hstvl", "it_centauro_rgo_120" + ] + }, // Lifetime stats displayed for each seeded squadron. "stats": { "akills_arc": 4280, "akills_hist": 6150, "akills_sim": 1420, @@ -45,7 +82,7 @@ "slogan": "离线天空与钢铁防线 · 自由研发全部联队载具", "desc": "War Thunder Offline 官方预置主力联队。开启自动审批,加入即可获得完整联队活跃度与联队研发点支持。", "announcement": "欢迎加入 [WTOF]!可在联队页面右上角点击「联队载具」或「活跃度」查看研发进度。", - "region": "CN / Global", "autoAccept": true, "createdAfterDays": 0, + "region": "CN / Global", "autoAccept": true, "createdAfterDays": 0, "targetMemberCount": 60, "rating": { "arc": 1840, "hist": 2150, "sim": 1620 }, "members": [ { "uid": "900001001", "nick": "Lin_Wei", "role": "LEADER", "title": "title_marshall", "icon": "cardicon_28", "unit": "cn_ztz_99a", "activity": 360 }, @@ -61,7 +98,7 @@ "slogan": "鹰击长空 · 现代喷气空战与陆空协同联队", "desc": "专注于高阶喷气机与现代主战坦克联合作战的离线联队,支持自动入队与高活跃度加成。", "announcement": "本期联队研发推荐:F-16A OCU、苏-33、豹 2PL、M1A1 AIM。", - "region": "Asia", "autoAccept": true, "createdAfterDays": 12, + "region": "Asia", "autoAccept": true, "createdAfterDays": 12, "targetMemberCount": 60, "rating": { "arc": 1690, "hist": 2040, "sim": 1780 }, "members": [ { "uid": "900002001", "nick": "SkyDragon_J20", "role": "LEADER", "title": "title_ace", "icon": "cardicon_25", "unit": "j_11a", "activity": 360 }, @@ -75,7 +112,7 @@ "slogan": "Steel & Fire — Heavy Armor Historical Squadron", "desc": "Classic and modern armored warfare squadron. Open auto-accept recruitment for all tank commanders.", "announcement": "Squadron vehicles ready for research at full 20,000 RP per period.", - "region": "EU / Global", "autoAccept": true, "createdAfterDays": 24, + "region": "EU / Global", "autoAccept": true, "createdAfterDays": 24, "targetMemberCount": 60, "rating": { "arc": 1920, "hist": 1980, "sim": 1510 }, "members": [ { "uid": "900003001", "nick": "Kommissar_KVs", "role": "LEADER", "title": "title_hero", "icon": "cardicon_22", "unit": "ussr_t_90m", "activity": 360 }, @@ -88,7 +125,7 @@ "slogan": "All The Way — Air, Ground & Naval Task Force", "desc": "需要审批模式的示例联队(用于测试发送与撤回入队申请流程)。若想立即加入联队,请选择 [WTOF]、=PLAF= 或 -1STG-。", "announcement": "Manual application review enabled for testing request/cancel workflow.", - "region": "NA", "autoAccept": false, "createdAfterDays": 35, + "region": "NA", "autoAccept": false, "createdAfterDays": 35, "targetMemberCount": 58, "rating": { "arc": 1550, "hist": 1760, "sim": 1490 }, "members": [ { "uid": "900004001", "nick": "Major_Winters", "role": "LEADER", "title": "title_brother_in_arms", "icon": "cardicon_03", "unit": "us_m1a2_sep2_abrams", "activity": 360 }, @@ -100,7 +137,7 @@ "slogan": "轻量级战术分队 · 侦察与快速反应", "desc": "战斗群(Battalion)类型预置联队,开启自动加入,支持体验战斗群架构与联队扩编。", "announcement": "轻装侦察分队常驻开放。", - "region": "Global", "autoAccept": true, "createdAfterDays": 48, + "region": "Global", "autoAccept": true, "createdAfterDays": 48, "targetMemberCount": 2, "rating": { "arc": 1410, "hist": 1610, "sim": 1320 }, "members": [ { "uid": "900005001", "nick": "Ghost_Scout", "role": "LEADER", "title": "title_scout", "icon": "cardicon_15", "unit": "us_hstvl", "activity": 360 }, From 12a573a333a3720bd76963b7b364be876a1c7527 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Fri, 4 Dec 2026 19:55:04 +0800 Subject: [PATCH 08/22] feat(store): default free offline payment label to Direct Claim and make it tunable Add tuning/store.jsonc freePaymentLabel (default Direct Claim in Chinese and English) and apply it consistently across the local web store, local marketplace, and the in-game payment dialog via cln_get_entitlements_price_ex top-level metadata. --- apps/server/src/char/actions/store-actions.ts | 19 ++++++-- .../src/inventory/marketplace-service.ts | 30 ++++++++++--- apps/server/src/inventory/web/app.js | 12 +++-- apps/server/src/server.ts | 7 ++- apps/server/src/store/store-tuning.ts | 43 ++++++++++++++++++ apps/server/src/store/store-web-api.ts | 45 ++++++++++++++----- apps/server/src/store/web/app.js | 12 +++-- apps/server/tuning/store.jsonc | 4 ++ .../free-offline-payment-method/patch.jsonc | 2 +- .../free-offline-payment-method/replace.nut | 9 +++- 10 files changed, 154 insertions(+), 29 deletions(-) diff --git a/apps/server/src/char/actions/store-actions.ts b/apps/server/src/char/actions/store-actions.ts index 1a2b2ba..59dc2bd 100644 --- a/apps/server/src/char/actions/store-actions.ts +++ b/apps/server/src/char/actions/store-actions.ts @@ -8,18 +8,24 @@ */ import { appendParam, emptyBlock, setParam, type BlkBlock } from '@wto/blk'; import type { AccountStore } from '../../accounts/account-store.ts'; +import type { LocalizedText } from '../../game-data/datasets/unit-names.ts'; import { clientProfile } from '../../profile/client-profile.ts'; import type { PlayerProfiles } from '../../profile/player-profiles.ts'; import { serverTimeNow } from '../../profile/server-time.ts'; import type { RuleOutcome } from '../../research/rule-outcome.ts'; import type { StoreCatalogue, StoreProduct } from '../../store/store-catalogue.ts'; import { buyGoldEntitlement } from '../../store/store-purchase.ts'; +import { freePaymentLabelForStore } from '../../store/store-tuning.ts'; import type { CharActionHandler } from '../char-action.ts'; import { withAccount } from './account-context.ts'; import { headerOrPayloadInt, headerOrPayloadString } from './payload-params.ts'; -export function entitlementsPriceEx(store: StoreCatalogue): CharActionHandler { - const table = buildEntitlementsPriceBlk(store.allProducts()); +export function entitlementsPriceEx( + store: StoreCatalogue, + freePaymentLabel?: LocalizedText, +): CharActionHandler { + const label = freePaymentLabel ?? freePaymentLabelForStore(store); + const table = buildEntitlementsPriceBlk(store.allProducts(), label); return () => ({ kind: 'data', blk: table }); } @@ -42,8 +48,15 @@ export function buyEntitlementAction(profiles: PlayerProfiles, accounts: Account }); } -function buildEntitlementsPriceBlk(products: readonly StoreProduct[]): BlkBlock { +function buildEntitlementsPriceBlk( + products: readonly StoreProduct[], + freePaymentLabel: LocalizedText, +): BlkBlock { const root = emptyBlock(); + // Top-level string params are ignored by stock blockCount() enumeration and read by the + // free-offline-payment-method GUI patch to localize the no-GJN payment option. + setParam(root, 'wtoFreePaymentLabelZh', { type: 'string', value: freePaymentLabel.zh }); + setParam(root, 'wtoFreePaymentLabelEn', { type: 'string', value: freePaymentLabel.en }); for (const product of products) { const block = emptyBlock(product.id); setParam(block, 'chapter', { type: 'string', value: product.chapter }); diff --git a/apps/server/src/inventory/marketplace-service.ts b/apps/server/src/inventory/marketplace-service.ts index 4ce1904..92cb5be 100644 --- a/apps/server/src/inventory/marketplace-service.ts +++ b/apps/server/src/inventory/marketplace-service.ts @@ -4,8 +4,10 @@ * `extInventory` and pushing `mrpc.generic_notify` (`inventory.changed`) to active game clients. */ import { gjnText } from '../store/redeem-codes.ts'; +import { DEFAULT_FREE_PAYMENT_LABEL } from '../store/store-tuning.ts'; import type { BlkBlock } from '@wto/blk'; import type { AccountStore } from '../accounts/account-store.ts'; +import type { LocalizedText } from '../game-data/datasets/unit-names.ts'; import type { PlayerProfiles } from '../profile/player-profiles.ts'; import { balanceOf } from '../profile/profile-currency.ts'; import { externalInventoryItems } from '../profile/profile-external-inventory.ts'; @@ -36,6 +38,7 @@ export class MarketplaceService implements Service { readonly #notifyInventoryChanged: () => void; readonly #maxPerPurchase: number; readonly #sellFeeRate: number; + readonly #freePaymentLabel: LocalizedText; constructor( accounts: AccountStore, @@ -43,6 +46,7 @@ export class MarketplaceService implements Service { catalogue: InventoryCatalogue, notifyInventoryChanged: () => void, tuning: Pick, + freePaymentLabel: LocalizedText = DEFAULT_FREE_PAYMENT_LABEL, ) { this.#accounts = accounts; this.#profiles = profiles; @@ -50,6 +54,7 @@ export class MarketplaceService implements Service { this.#notifyInventoryChanged = notifyInventoryChanged; this.#maxPerPurchase = tuning.maxPerPurchase; this.#sellFeeRate = tuning.sellFeeRate; + this.#freePaymentLabel = freePaymentLabel; } accepts(request: ServiceRequest): boolean { @@ -96,6 +101,7 @@ export class MarketplaceService implements Service { currentUserId: account?.userId ?? '', balance, sellFeeRate: this.#sellFeeRate, + freePaymentLabel: this.#freePaymentLabel, listings, }, `marketplace state (${account?.userId ?? 'no-account'})`); } @@ -158,7 +164,13 @@ export class MarketplaceService implements Service { }); if (errorReason === 'NOT_ENOUGH_GJN') { - return jsonResponse({ ok: false, message: { zh: 'GJN 不够。可直接点「老福爷付过了」,或在商店的"兑换码"页用 GJN 充值码补充。', en: 'Not enough GJN. Use "老福爷付过了" or a GJN code on the Redeem tab of the store.' } }, `marketplace buy ${itemdefId}: NOMONEY`); + return jsonResponse({ + ok: false, + message: { + zh: `GJN 不够。可直接点「${this.#freePaymentLabel.zh}」,或在商店的"兑换码"页用 GJN 充值码补充。`, + en: `Not enough GJN. Use "${this.#freePaymentLabel.en}" or a GJN code on the Redeem tab of the store.`, + }, + }, `marketplace buy ${itemdefId}: NOMONEY`); } if (errorReason) { return jsonResponse({ ok: false, message: { zh: '购买失败。', en: 'Purchase failed.' } }, `marketplace buy ${itemdefId}: ${errorReason}`); @@ -166,15 +178,23 @@ export class MarketplaceService implements Service { this.#notifyInventoryChanged(); const costSummary = isFree ? 'free' : `${gjnText(listing.gjnCostCents * quantity)} GJN`; - return jsonResponse({ ok: true, message: buySuccessMessage(listing, quantity, isFree) }, `marketplace buy ${itemdefId} x${quantity} (${costSummary})`); + return jsonResponse( + { ok: true, message: buySuccessMessage(listing, quantity, isFree, this.#freePaymentLabel) }, + `marketplace buy ${itemdefId} x${quantity} (${costSummary})`, + ); } } -function buySuccessMessage(listing: MarketplaceListing, quantity: number, isFree: boolean): { zh: string; en: string } { +function buySuccessMessage( + listing: MarketplaceListing, + quantity: number, + isFree: boolean, + freePaymentLabel: LocalizedText, +): LocalizedText { return isFree ? { - zh: `老福爷付过了!「${listing.title.zh}」兑换券 ×${quantity} 已放进游戏库存,可在机库的"道具 → 库存"里使用。`, - en: `Paid by 老福爷! ${quantity} × "${listing.title.en}" coupon is in your inventory (Items → Inventory in the hangar).`, + zh: `已通过「${freePaymentLabel.zh}」获得「${listing.title.zh}」兑换券 ×${quantity},已放进游戏库存,可在机库的"道具 → 库存"里使用。`, + en: `Claimed ${quantity} × "${listing.title.en}" coupon via "${freePaymentLabel.en}". It is in your inventory (Items → Inventory in the hangar).`, } : { zh: `已购买「${listing.title.zh}」兑换券 ×${quantity},已放进游戏库存,可在机库的"道具 → 库存"里使用。`, diff --git a/apps/server/src/inventory/web/app.js b/apps/server/src/inventory/web/app.js index b1e1b0d..c88eb9f 100644 --- a/apps/server/src/inventory/web/app.js +++ b/apps/server/src/inventory/web/app.js @@ -9,7 +9,7 @@ const T = { heldOnly: '只看我的库存', search: '搜索', sortPopular: '人气', sortName: '名称(从 A 到 Z)', sortPriceAsc: '价格(从低到高)', sortPriceDesc: '价格(从高到低)', catVehicle: '载具', catSkin: '涂装', catAttachable: '装饰挂件', catDecal: '贴花', catUnlock: '头像', allCountries: '全部国家', allClasses: '全部', rank: '{rank} 级', from: '从', held: '库存 ×{n}', owned: '已拥有', - buy: '购买', freeBuy: '老福爷付过了', sell: '出售', pickAccount: '请先在右上角选择账号', empty: '没有符合条件的物品', + buy: '购买', freeBuy: '直接获取', sell: '出售', pickAccount: '请先在右上角选择账号', empty: '没有符合条件的物品', buyPrice: '系统售价:{price} GJN', sellPrice: '卖给系统:{price} GJN(扣 {fee}% 手续费)', youHave: '你拥有:{n}', tradeUnconfirmed: '无法确认交易结果,请先查看余额和库存。', tagType: '物品类型', tagRarity: '稀有度', tagCountry: '国家', ticker: '离线交易所:按固定价格与系统交易,价格取自官方交易所快照。', @@ -19,7 +19,7 @@ const T = { heldOnly: 'Only my inventory', search: 'Search', sortPopular: 'Popular', sortName: 'Name (A to Z)', sortPriceAsc: 'Price (low to high)', sortPriceDesc: 'Price (high to low)', catVehicle: 'Vehicles', catSkin: 'Camouflages', catAttachable: 'Decorations', catDecal: 'Decals', catUnlock: 'Avatars', allCountries: 'All countries', allClasses: 'All', rank: 'Rank {rank}', from: 'from', held: 'Owned ×{n}', owned: 'Owned', - buy: 'Buy', freeBuy: '老福爷付过了', sell: 'Sell', pickAccount: 'Pick an account at the top right', empty: 'Nothing matches the filters', + buy: 'Buy', freeBuy: 'Direct Claim', sell: 'Sell', pickAccount: 'Pick an account at the top right', empty: 'Nothing matches the filters', buyPrice: 'System price: {price} GJN', sellPrice: 'Sell to system: {price} GJN ({fee}% fee)', youHave: 'You own: {n}', tradeUnconfirmed: 'Could not confirm the trade. Check your balance and inventory.', tagType: 'Item type', tagRarity: 'Rarity', tagCountry: 'Country', ticker: 'Offline market: fixed-price trades with the system, prices from an official market snapshot.', @@ -33,7 +33,11 @@ const t = (key, params) => WtoUi.tr(T, key, params); const $ = (id) => document.getElementById(id); const wantedItem = WtoUi.query.get('n') || ''; -let state = { accounts: [], currentUserId: '', balance: { gjnCents: 0, goldenEagles: 0 }, listings: [] }; +let state = { accounts: [], currentUserId: '', balance: { gjnCents: 0, goldenEagles: 0 }, listings: [], freePaymentLabel: null }; + +function freePaymentLabel() { + return WtoUi.text(state.freePaymentLabel) || t('freeBuy'); +} const activeCats = new Set(); let openedWanted = false; let tradeNoticeId = 0; @@ -173,7 +177,7 @@ function fillOrderColumns(detail, listing) { sellCol.append(sellBtn, html('totals', t('sellPrice', { price: WtoUi.gjn(listing.sellCents), fee })), html('totals', t('youHave', { n: listing.couponCount || 0 }))); const buyBtn = Object.assign(document.createElement('button'), { className: 'big buy', textContent: noAccount ? t('pickAccount') : t('buy'), disabled: noAccount }); buyBtn.onclick = () => trade('/trade.gaijin.net/api/buy', { itemdefId: listing.itemdefId, quantity: 1, payMethod: 'gjn' }, listing); - const freeBtn = Object.assign(document.createElement('button'), { className: 'big free', textContent: t('freeBuy'), disabled: noAccount }); + const freeBtn = Object.assign(document.createElement('button'), { className: 'big free', textContent: freePaymentLabel(), disabled: noAccount }); freeBtn.onclick = () => trade('/trade.gaijin.net/api/buy', { itemdefId: listing.itemdefId, quantity: 1, payMethod: 'free' }, listing); buyCol.append(buyBtn, freeBtn, html('totals', t('buyPrice', { price: WtoUi.gjn(listing.gjnCostCents) }))); } diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index b58597d..848e2f1 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -60,6 +60,7 @@ import { Router } from './transport/router.ts'; import { loadOrCreateCredentials } from './transport/tls/tls-certificate.ts'; import { StoreCatalogue } from './store/store-catalogue.ts'; import { StoreService } from './store/store-service.ts'; +import { bindStoreFreePaymentLabel } from './store/store-tuning.ts'; import { TrainingCatalogue } from './training/training-completion.ts'; import { TrafficLog } from './traffic-log/traffic-log.ts'; import { loadTuning, type Tuning } from './tuning/tuning.ts'; @@ -235,7 +236,7 @@ export async function startServer(options: ServerOptions): Promise(); + +/** Associate a configured free payment label with a StoreCatalogue instance. */ +export function bindStoreFreePaymentLabel(store: object, label: LocalizedText): void { + freePaymentLabelsByStore.set(store, label); +} + +/** Return the configured free payment label for a StoreCatalogue instance, falling back to the default. */ +export function freePaymentLabelForStore(store: object): LocalizedText { + return freePaymentLabelsByStore.get(store) ?? DEFAULT_FREE_PAYMENT_LABEL; +} + export interface StoreTuning { + /** Localized label for the no-GJN offline payment button in the game dialog, local store, and marketplace. */ + readonly freePaymentLabel: LocalizedText; readonly goldenEaglePacks: readonly GoldenEaglePack[]; readonly silverLionPacks: readonly SilverLionPack[]; readonly premiumForGoldenEagles: readonly PremiumTier[]; @@ -53,6 +73,7 @@ export interface StoreTuning { } export function readStoreTuning(file: TuningReader): StoreTuning { + const freePaymentLabel = readFreePaymentLabel(file); const packs = file.object('vehiclePacks'); const byRank = packs.list('byRank', (entry) => ({ upToRank: entry.int('upToRank', { min: 1 }), ...packContent(entry) })) .sort((a, b) => a.upToRank - b.upToRank); @@ -66,6 +87,7 @@ export function readStoreTuning(file: TuningReader): StoreTuning { validateStoreUniqueness(goldenEaglePacks, silverLionPacks, premiumForGoldenEagles, premiumForGjn, multiVehiclePacks); return { + freePaymentLabel, goldenEaglePacks, silverLionPacks, premiumForGoldenEagles, @@ -76,6 +98,27 @@ export function readStoreTuning(file: TuningReader): StoreTuning { }; } +function readFreePaymentLabel(file: TuningReader): LocalizedText { + const labelObj = file.object('freePaymentLabel'); + return { + zh: readFreePaymentLabelPart(labelObj, 'zh'), + en: readFreePaymentLabelPart(labelObj, 'en'), + }; +} + +function readFreePaymentLabelPart(entry: TuningReader, key: 'zh' | 'en'): string { + const trimmed = entry.string(key).trim(); + if (trimmed === '') { + throw new TuningError(`tuning file store.jsonc: freePaymentLabel.${key} must not be blank`); + } + if (trimmed.length > MAX_FREE_PAYMENT_LABEL_LENGTH) { + throw new TuningError( + `tuning file store.jsonc: freePaymentLabel.${key} must be at most ${MAX_FREE_PAYMENT_LABEL_LENGTH} characters`, + ); + } + return trimmed; +} + /** The pack content for a vehicle: its own entry over the first rank tier that covers its rank (the last tier above the highest). */ export function vehiclePackContent(tuning: StoreTuning, vehicle: string, rank: number): VehiclePackContent { const tier = tuning.vehiclePacksByRank.find((entry) => rank <= entry.upToRank) ?? tuning.vehiclePacksByRank[tuning.vehiclePacksByRank.length - 1]!; diff --git a/apps/server/src/store/store-web-api.ts b/apps/server/src/store/store-web-api.ts index eadec17..02a2929 100644 --- a/apps/server/src/store/store-web-api.ts +++ b/apps/server/src/store/store-web-api.ts @@ -20,6 +20,7 @@ import { describeRedeemCodes, gjnText, redeemStoreCode, type RedeemOutcome } fro import type { RedeemTuning } from './redeem-tuning.ts'; import type { StoreCatalogue, StoreProduct } from './store-catalogue.ts'; import { buyFreeStoreProduct, buyGjnProduct, buyStoreCart, canBuyGjnProduct, type GjnPurchaseOutcome, type StoreCheckoutOutcome } from './store-purchase.ts'; +import { freePaymentLabelForStore } from './store-tuning.ts'; const NO_ACCOUNT: LocalizedText = { zh: '没有找到这个账号,请先在右上角选择账号。', en: 'Account not found. Pick an account at the top right first.' }; @@ -31,12 +32,20 @@ export class StoreWebApi { readonly #profiles: PlayerProfiles; readonly #catalogue: StoreCatalogue; readonly #redeemCodes: RedeemTuning; + readonly #freePaymentLabel: LocalizedText; - constructor(accounts: AccountStore, profiles: PlayerProfiles, catalogue: StoreCatalogue, redeemCodes: RedeemTuning) { + constructor( + accounts: AccountStore, + profiles: PlayerProfiles, + catalogue: StoreCatalogue, + redeemCodes: RedeemTuning, + freePaymentLabel?: LocalizedText, + ) { this.#accounts = accounts; this.#profiles = profiles; this.#catalogue = catalogue; this.#redeemCodes = redeemCodes; + this.#freePaymentLabel = freePaymentLabel ?? freePaymentLabelForStore(catalogue); } /** The answer for /store/api/, or undefined when it is not an API request. */ @@ -64,6 +73,7 @@ export class StoreWebApi { products, cartProductIds: profile ? storeCartIds(profile) : [], redeemHelp: describeRedeemCodes(this.#redeemCodes), + freePaymentLabel: this.#freePaymentLabel, }, `store web state (${account?.userId ?? 'no account'})`); } @@ -94,7 +104,10 @@ export class StoreWebApi { return true; }); const modeTag = isFree ? 'free' : 'gjn'; - return jsonResponse({ ok: outcome.ok, cartProductIds, message: purchaseMessage(outcome, product, isFree) }, `store web buy ${product.id} (${modeTag}): ${outcome.ok ? 'OK' : outcome.reason}`); + return jsonResponse( + { ok: outcome.ok, cartProductIds, message: purchaseMessage(outcome, product, isFree, this.#freePaymentLabel) }, + `store web buy ${product.id} (${modeTag}): ${outcome.ok ? 'OK' : outcome.reason}`, + ); } #cart(request: ServiceRequest): ServiceResponse { @@ -153,7 +166,7 @@ export class StoreWebApi { return false; } const outcome = buyStoreCart(profile, products, payMethod, now); - message = checkoutMessage(outcome, products, payMethod); + message = checkoutMessage(outcome, products, payMethod, this.#freePaymentLabel); if (!outcome.ok) return false; clearStoreCart(profile); cartProductIds = []; @@ -177,13 +190,18 @@ export class StoreWebApi { } } -function purchaseMessage(outcome: GjnPurchaseOutcome, product: StoreProduct, isFree: boolean): LocalizedText { +function purchaseMessage( + outcome: GjnPurchaseOutcome, + product: StoreProduct, + isFree: boolean, + freePaymentLabel: LocalizedText, +): LocalizedText { const cost = gjnText(product.gjnCostCents ?? 0); if (outcome.ok) { return isFree ? { - zh: `老福爷付过了!已直接获得「${product.title.zh}」。关闭商店窗口后机库会自动刷新。`, - en: `Paid by 老福爷! Claimed "${product.title.en}". Close the store window to refresh the hangar.`, + zh: `已通过「${freePaymentLabel.zh}」获得「${product.title.zh}」。关闭商店窗口后机库会自动刷新。`, + en: `Claimed "${product.title.en}" via "${freePaymentLabel.en}". Close the store window to refresh the hangar.`, } : { zh: `已购买「${product.title.zh}」,花费 ${cost} GJN。关闭商店窗口后机库会自动刷新。`, @@ -191,7 +209,10 @@ function purchaseMessage(outcome: GjnPurchaseOutcome, product: StoreProduct, isF }; } if (outcome.reason === 'NOT_ENOUGH_GJN') { - return { zh: `GJN 不够:需要 ${cost} GJN。可直接点「老福爷付过了」,或在"兑换码"页用 GJN 充值码补充。`, en: `Not enough GJN: ${cost} GJN needed. Use "老福爷付过了" or a GJN code on the Redeem tab.` }; + return { + zh: `GJN 不够:需要 ${cost} GJN。可直接点「${freePaymentLabel.zh}」,或在"兑换码"页用 GJN 充值码补充。`, + en: `Not enough GJN: ${cost} GJN needed. Use "${freePaymentLabel.en}" or a GJN code on the Redeem tab.`, + }; } if (outcome.reason === 'ALREADY_BOUGHT') return alreadyBoughtMessage(product); return { zh: '这个商品现在买不了。', en: 'This product cannot be bought right now.' }; @@ -208,19 +229,23 @@ function checkoutMessage( outcome: StoreCheckoutOutcome, products: readonly StoreProduct[], payMethod: 'gjn' | 'free', + freePaymentLabel: LocalizedText, ): LocalizedText { if (outcome.ok) { const count = products.length; const cost = gjnText(outcome.costCents); return payMethod === 'free' - ? { zh: `老福爷付过了!已领取 ${count} 件商品。关闭商城窗口后机库会自动刷新。`, - en: `Paid by 老福爷! Claimed ${count} items. Close the store to refresh the hangar.` } + ? { zh: `已通过「${freePaymentLabel.zh}」领取 ${count} 件商品。关闭商城窗口后机库会自动刷新。`, + en: `Claimed ${count} items via "${freePaymentLabel.en}". Close the store to refresh the hangar.` } : { zh: `已购买 ${count} 件商品,花费 ${cost} GJN。关闭商城窗口后机库会自动刷新。`, en: `Bought ${count} items for ${cost} GJN. Close the store to refresh the hangar.` }; } if (outcome.reason === 'NOT_ENOUGH_GJN') { const cost = gjnText(outcome.costCents); - return { zh: `购物车共需 ${cost} GJN,当前余额不足。`, en: `Your cart costs ${cost} GJN. Your balance is too low.` }; + return { + zh: `购物车共需 ${cost} GJN,当前余额不足。可直接点「${freePaymentLabel.zh}」。`, + en: `Your cart costs ${cost} GJN. Your balance is too low. Use "${freePaymentLabel.en}" instead.`, + }; } const product = products.find((item) => item.id === outcome.productId); return outcome.reason === 'ALREADY_BOUGHT' && product ? alreadyBoughtMessage(product) : NO_PRODUCT; diff --git a/apps/server/src/store/web/app.js b/apps/server/src/store/web/app.js index e52699f..9a57e3d 100644 --- a/apps/server/src/store/web/app.js +++ b/apps/server/src/store/web/app.js @@ -9,7 +9,7 @@ const T = { search: '搜索礼包或载具', allCountries: '所有国家', allRanks: '所有等级', rank: '{rank} 级', sort: '商品排序', sortBest: '最畅销', sortNewest: '最新上架', sortPriceAsc: '价格从低到高', sortPriceDesc: '价格从高到低', containsEagles: '{n} 金鹰', containsSilver: '{n} 银狮', containsPremium: '{days} 天高级账户', - buy: '购买', freeBuy: '老福爷付过了', owned: '已拥有', pickAccount: '请先选择账号', + buy: '购买', freeBuy: '直接获取', owned: '已拥有', pickAccount: '请先选择账号', redeem: '兑换', codePlaceholder: '输入兑换码', empty: '没有符合条件的商品', featured: '推荐礼包', bestSeller: '畅销', viewPack: '查看礼包', related: '更多推荐', packPrice: '礼包价格', includes: '礼包内容', back: '返回目录', bonusTitle: '高级载具权益', @@ -31,7 +31,7 @@ const T = { search: 'Search packs or vehicles', allCountries: 'All nations', allRanks: 'All ranks', rank: 'Rank {rank}', sort: 'Sort products', sortBest: 'Top sellers', sortNewest: 'Newest', sortPriceAsc: 'Price: low to high', sortPriceDesc: 'Price: high to low', containsEagles: '{n} Golden Eagles', containsSilver: '{n} Silver Lions', containsPremium: '{days} days of Premium Account', - buy: 'Buy', freeBuy: '老福爷付过了', owned: 'Owned', pickAccount: 'Pick an account first', + buy: 'Buy', freeBuy: 'Direct Claim', owned: 'Owned', pickAccount: 'Pick an account first', redeem: 'Redeem', codePlaceholder: 'Enter a code', empty: 'Nothing matches the filters', featured: 'Featured packs', bestSeller: 'Top seller', viewPack: 'View pack', related: 'Explore other packs', packPrice: 'Pack price', includes: 'Pack contents', back: 'Back to catalog', bonusTitle: 'Premium bonuses', @@ -53,7 +53,7 @@ const t = (key, params) => WtoUi.tr(T, key, params); const $ = (id) => document.getElementById(id); let initialGuid = (WtoUi.query.get('item') || '').toUpperCase(); -let state = { accounts: [], activeUserId: '', balance: { gjnCents: 0 }, products: [], cartProductIds: [], redeemHelp: [] }; +let state = { accounts: [], activeUserId: '', balance: { gjnCents: 0 }, products: [], cartProductIds: [], redeemHelp: [], freePaymentLabel: null }; let currentTab = 'vehicle-pack'; let detailId = ''; let catalogScroll = 0; @@ -61,9 +61,14 @@ let loadVersion = 0; let loading = true; const checkout = createStoreCheckout(loadState); +function freePaymentLabel() { + return WtoUi.text(state.freePaymentLabel) || t('freeBuy'); +} + function applyStaticTexts() { for (const el of document.querySelectorAll('[data-t]')) el.textContent = t(el.dataset.t); for (const el of document.querySelectorAll('[data-label]')) el.setAttribute('aria-label', t(el.dataset.label)); + $('payFree').textContent = freePaymentLabel(); $('searchInput').placeholder = t('search'); $('codeInput').placeholder = t('codePlaceholder'); $('marketLink').href = WtoUi.pageLink('/trade.gaijin.net/'); @@ -88,6 +93,7 @@ async function loadState(userId) { return await loadState(''); } state = next; + $('payFree').textContent = freePaymentLabel(); WtoUi.fillAccountSelect($('accountSelect'), state.accounts, state.activeUserId); $('gjnVal').textContent = WtoUi.gjn(state.balance.gjnCents); $('goldVal').textContent = WtoUi.num(state.balance.goldenEagles); diff --git a/apps/server/tuning/store.jsonc b/apps/server/tuning/store.jsonc index e620eb5..5bc9e7e 100644 --- a/apps/server/tuning/store.jsonc +++ b/apps/server/tuning/store.jsonc @@ -1,6 +1,10 @@ // Local store products and prices. // The client receives these prices from the local server. { + // Button label for the no-GJN offline payment method shown in the in-game payment dialog, + // local web store, and local marketplace. Players can override it in /tuning/store.jsonc. + "freePaymentLabel": { "zh": "直接获取", "en": "Direct Claim" }, + // GJN prices use the official USD prices at 1 GJN per USD. // Golden Eagle packs use GJN in both the in-game payment dialog and the local web store. diff --git a/patches/gui/online-shop/free-offline-payment-method/patch.jsonc b/patches/gui/online-shop/free-offline-payment-method/patch.jsonc index daac78f..9ef33f9 100644 --- a/patches/gui/online-shop/free-offline-payment-method/patch.jsonc +++ b/patches/gui/online-shop/free-offline-payment-method/patch.jsonc @@ -3,7 +3,7 @@ // Without it: the in-game payment window offers no free offline purchase. { "id": "online-shop/free-offline-payment-method", - "title": "游戏内支付方式窗口增加「老福爷付过了」免 GJN 直接购买选项", + "title": "Add a no-GJN direct claim option to the in-game payment dialog", "features": [ "G-Currencies", "G-Premium account", diff --git a/patches/gui/online-shop/free-offline-payment-method/replace.nut b/patches/gui/online-shop/free-offline-payment-method/replace.nut index e1fd249..4e14406 100644 --- a/patches/gui/online-shop/free-offline-payment-method/replace.nut +++ b/patches/gui/online-shop/free-offline-payment-method/replace.nut @@ -1,4 +1,11 @@ - let freePayName = "老福爷付过了" + let { isChineseVersion, isChineseHarmonized } = require("%scripts/langUtils/language.nut") + let { getShopPriceBlk } = require("%scripts/onlineShop/onlineShopState.nut") + let isChinese = isChineseVersion() || isChineseHarmonized() + let priceBlk = getShopPriceBlk() + let customFreePayName = isChinese ? priceBlk?.wtoFreePaymentLabelZh : priceBlk?.wtoFreePaymentLabelEn + let freePayName = (type(customFreePayName) == "string" && customFreePayName != "") + ? customFreePayName + : (isChinese ? "直接获取" : "Direct Claim") items.append({ name = freePayName icon = "" From 9e6e13895e8f8d8803b855705cc959dffa0d76b8 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Fri, 4 Dec 2026 19:55:05 +0800 Subject: [PATCH 09/22] fix(launcher): separate client removal from deleting disk files Split deleteFiles from deleteData in copy maintenance requests with safe false defaults. Block disk deletion for non-copy (in-place/existing) and Steam-library clients on both main and renderer sides, and allow pure list removal to bypass stockBackup/root checks so missing or damaged client entries can always be removed. --- .../main/services/copies/copy-maintenance.ts | 88 +++++++++++++++---- .../src/renderer/src/i18n/locales/en.json | 25 +++--- .../src/renderer/src/i18n/locales/zh-CN.json | 25 +++--- .../src/pages/copies/CopyMaintenance.tsx | 6 +- .../pages/copies/CopyMaintenanceControls.tsx | 52 ++++++++--- .../src/pages/copies/useCopyMaintenance.ts | 2 +- .../src/shared/schemas/maintenance.ts | 1 + 7 files changed, 146 insertions(+), 53 deletions(-) diff --git a/apps/launcher/src/main/services/copies/copy-maintenance.ts b/apps/launcher/src/main/services/copies/copy-maintenance.ts index db6521d..ec8e00d 100644 --- a/apps/launcher/src/main/services/copies/copy-maintenance.ts +++ b/apps/launcher/src/main/services/copies/copy-maintenance.ts @@ -1,5 +1,5 @@ import { readdir, rm } from 'node:fs/promises'; -import { isAbsolute, join, parse, relative } from 'node:path'; +import { isAbsolute, join, parse, relative, resolve } from 'node:path'; import { app } from 'electron'; import { isInSteamLibrary } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; @@ -90,10 +90,18 @@ export async function maintainCopy( } } +/** Only launcher-created copies outside any Steam library may have their game folder deleted on disk. */ +export function canDeleteCopyFiles(record: InstallRecord, root: string): boolean { + return record.method === 'copy' && !isInSteamLibrary(record.copyPath) && !isInSteamLibrary(root); +} + async function performMaintenance(request: MaintenanceRequest, signal: AbortSignal, report: Report): Promise { const { id, operation, steamLocations } = request; const record = await requireCopy(id); if (operation === 'set-source') return setCopySource(record, request.sourcePath); + if (operation === 'delete') { + return remove(record, request.deleteFiles === true, request.deleteData === true, signal, report); + } const root = await checkedRoot(record); const dataPath = await canonicalCopyPath(record.dataPath); @@ -101,7 +109,7 @@ async function performMaintenance(request: MaintenanceRequest, signal: AbortSign if (await gameProcessRunning(signal) || await labServerUses(root)) throw new AppError('maintenance_busy'); signal.throwIfAborted(); - if (operation !== 'confirm-steam' && operation !== 'delete' && needsConfirmation) { + if (operation !== 'confirm-steam' && needsConfirmation) { throw new AppError('launch_steam_confirmation_required'); } @@ -123,9 +131,6 @@ async function performMaintenance(request: MaintenanceRequest, signal: AbortSign return updateFromSource(record, root, signal, report); case 'compact': return compactCopy(record, root, signal, report); - case 'delete': - report('applying'); - return remove(record, root, request.deleteData); } } @@ -184,24 +189,73 @@ async function recordCheck(record: InstallRecord, folder: string): Promise { - if (isInSteamLibrary(record.copyPath) || isInSteamLibrary(root)) { - if (deleteData) failLocation('delete_data_blocked_in_steam', { copyPath: record.copyPath, root }); +async function remove( + record: InstallRecord, + deleteFiles: boolean, + deleteData: boolean, + signal: AbortSignal, + report: Report, +): Promise { + 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) { + report('applying'); return removeCopyRecord(record.id); } - const data = deleteData ? await safeFolder(record.dataPath) : await canonicalCopyPath(record.dataPath); + const copyInSteam = isInSteamLibrary(record.copyPath) || isInSteamLibrary(canonicalRoot); + if (copyInSteam) { + failLocation(deleteFiles ? 'delete_files_blocked_in_steam' : 'delete_data_blocked_in_steam', { + method: record.method, + copyPath: record.copyPath, + root: canonicalRoot, + }); + } + + if (deleteFiles && !canDeleteCopyFiles(record, canonicalRoot)) { + failLocation('delete_files_blocked_for_method', { + method: record.method, + copyPath: record.copyPath, + root: canonicalRoot, + }); + } + + const root = deleteFiles ? await checkedRoot(record) : canonicalRoot; + if (deleteFiles && !canDeleteCopyFiles(record, root)) { + failLocation('delete_files_blocked', { method: record.method, copyPath: record.copyPath, root }); + } + + const data = deleteData ? await safeFolder(record.dataPath, false) : 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)))) { - failLocation('delete_data_overlaps_source_or_copy', { root, data, source }); + const stockBackup = await canonicalCopyPath(record.stockBackupPath); + if (deleteData) { + const rawRoot = resolve(record.copyPath); + const overlapsSource = source !== null && (copyPathContains(data, source) || copyPathContains(source, data)); + 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 }); + } } - if (!deleteData && copyPathContains(root, data)) { - await removeExcept(root, data); - } else { - await rm(root, { recursive: true, force: true }); + + report('applying'); + if (deleteFiles) { + if (!deleteData && copyPathContains(root, data)) { + await removeExcept(root, data); + } else { + await rm(root, { recursive: true, force: true }); + } + } + if (deleteData && (!deleteFiles || !copyPathContains(root, data))) { + await rm(data, { recursive: true, force: true }); } - if (deleteData && !copyPathContains(root, data)) await rm(data, { recursive: true, force: true }); return removeCopyRecord(record.id); } diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index 13e0c5e..fd5e504 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -258,16 +258,19 @@ "repair": "Repair client", "repairAction": "Repair", "repairHint": "Restore the original files from the backup. Game files will be generated again at launch.", - "delete": "Delete client", - "deleteAction": "Delete…", - "deleteHint": "The data folder is kept by default.", - "unlink": "Remove registration", - "unlinkAction": "Remove…", - "unlinkHint": "The launcher keeps the Steam game files and data folder in place.", - "unlinkLocation": "Remove the launcher's registration for {{path}}? Steam game files and data will stay in place.", - "deleteLocation": "Delete the offline client at {{path}}?", - "deleteData": "Also delete the data folder at {{path}}", - "confirm": "Confirm deletion", + "remove": "Remove client", + "removeAction": "Remove…", + "removeCopyHint": "Removes from the launcher list by default without deleting files on disk.", + "removeUnlinkHint": "Removes only from the launcher list without deleting game files on disk.", + "removeSteamHint": "Removes only from the launcher list. Steam game files and the data folder stay in place.", + "removeCopyNotice": "Removes {{path}} from the launcher list. All game files and data on disk are kept by default.", + "removeListOnlyNotice": "Removes {{path}} from the launcher list only. Game files on disk will not be deleted.", + "removeSteamNotice": "Removes {{path}} from the launcher list only. Steam game files and data on disk will not be deleted.", + "deleteFiles": "Also delete the client folder at {{path}}", + "deleteFilesWarning": "This will permanently delete all files in the copied client folder at {{path}}. This action cannot be undone.", + "deleteData": "Also delete the data folder at {{path}} (contains saves, settings, and logs)", + "confirmRemove": "Remove from list", + "confirmDelete": "Confirm deletion", "phase": { "checking": "Checking the client", "copying": "Copying changed files", @@ -280,7 +283,7 @@ "repair": "Original files restored.", "update": "Client updated.", "compact": "Space-saving conversion complete.", - "delete": "Client deleted.", + "delete": "Client removed.", "cancelled": "Maintenance cancelled." } }, diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index 8f515b8..34cb6c3 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -258,16 +258,19 @@ "repair": "修复客户端", "repairAction": "修复", "repairHint": "从原版文件备份还原文件。下次启动时重新生成游戏文件。", - "delete": "删除客户端", - "deleteAction": "删除…", - "deleteHint": "默认保留数据目录。", - "unlink": "解除登记", - "unlinkAction": "解除登记…", - "unlinkHint": "Steam 游戏文件和数据目录将留在原处。", - "unlinkLocation": "从启动器中解除 {{path}} 的登记?Steam 游戏文件和数据将留在原处。", - "deleteLocation": "确认删除 {{path}} 中的离线客户端?", - "deleteData": "同时删除 {{path}} 中的数据", - "confirm": "确认删除", + "remove": "移除客户端", + "removeAction": "移除…", + "removeCopyHint": "默认仅从启动器列表移除,不会删除磁盘文件。", + "removeUnlinkHint": "仅从启动器列表移除,不会删除磁盘上的游戏文件。", + "removeSteamHint": "仅从启动器列表移除,Steam 游戏文件和数据目录将留在原处。", + "removeCopyNotice": "将从启动器列表移除 {{path}}。默认保留磁盘上的所有游戏文件和数据。", + "removeListOnlyNotice": "将仅从启动器列表移除 {{path}},不会删除磁盘上的游戏文件。", + "removeSteamNotice": "将仅从启动器列表移除 {{path}},不会删除磁盘上的 Steam 游戏文件和数据目录。", + "deleteFiles": "同时删除客户端文件夹 {{path}}", + "deleteFilesWarning": "将永久删除客户端副本文件夹 {{path}} 中的全部文件,此操作无法撤销。", + "deleteData": "同时删除数据文件夹 {{path}}(包含存档、配置与日志)", + "confirmRemove": "从列表移除", + "confirmDelete": "确认删除", "phase": { "checking": "正在检查客户端", "copying": "正在复制有变化的文件", @@ -280,7 +283,7 @@ "repair": "原版文件已还原。", "update": "客户端已更新。", "compact": "省空间转换已完成。", - "delete": "客户端已删除。", + "delete": "客户端已移除。", "cancelled": "维护已取消。" } }, diff --git a/apps/launcher/src/renderer/src/pages/copies/CopyMaintenance.tsx b/apps/launcher/src/renderer/src/pages/copies/CopyMaintenance.tsx index 5bb637a..5e352dc 100644 --- a/apps/launcher/src/renderer/src/pages/copies/CopyMaintenance.tsx +++ b/apps/launcher/src/renderer/src/pages/copies/CopyMaintenance.tsx @@ -20,6 +20,10 @@ export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanc const [info, setInfo] = useState(null); const [removal, setRemoval] = useState(null); + useEffect(() => { + setRemoval(null); + }, [record.id]); + useEffect(() => { let mounted = true; setInfo(null); @@ -60,7 +64,7 @@ export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanc busy={busy} options={removal} onOptionsChange={setRemoval} - onRemove={(deleteData) => run('delete', { deleteData })} + onRemove={(options) => run('delete', options)} /> {active && } {result &&

{t(`copies.maintenance.result.${result}`)}

} diff --git a/apps/launcher/src/renderer/src/pages/copies/CopyMaintenanceControls.tsx b/apps/launcher/src/renderer/src/pages/copies/CopyMaintenanceControls.tsx index f66cd7d..65cb9be 100644 --- a/apps/launcher/src/renderer/src/pages/copies/CopyMaintenanceControls.tsx +++ b/apps/launcher/src/renderer/src/pages/copies/CopyMaintenanceControls.tsx @@ -69,44 +69,72 @@ export function CopyMaintenanceActions({ record, info, busy, onRun, onChooseSour } export interface CopyRemovalOptions { + readonly deleteFiles: boolean; readonly deleteData: boolean; } interface CopyRemovalProps extends CopyMaintenanceControlsProps { readonly options: CopyRemovalOptions | null; readonly onOptionsChange: (options: CopyRemovalOptions | null) => void; - readonly onRemove: (deleteData: boolean) => void; + readonly onRemove: (options: CopyRemovalOptions) => void; } export function CopyRemoval({ record, info, busy, options, onOptionsChange, onRemove }: CopyRemovalProps) { const { t } = useTranslation(); const steam = info?.steamLocations; - const unlinkOnly = steam?.copyInSteam === true; - const canDeleteData = !unlinkOnly && !steam?.dataInSteam; - const action = t(unlinkOnly ? 'copies.maintenance.unlink' : 'copies.maintenance.confirm'); + const copyInSteam = steam?.copyInSteam === true; + const dataInSteam = steam?.dataInSteam === true; + const canDeleteFiles = info !== null && record.method === 'copy' && !copyInSteam; + const canDeleteData = info !== null && !copyInSteam && !dataInSteam; + const willDeleteFiles = canDeleteFiles && options?.deleteFiles === true; + const willDeleteData = canDeleteData && options?.deleteData === true; + const willDeleteAny = willDeleteFiles || willDeleteData; + const action = t(willDeleteAny ? 'copies.maintenance.confirmDelete' : 'copies.maintenance.confirmRemove'); + const rowHint = copyInSteam + ? t('copies.maintenance.removeSteamHint') + : record.method === 'copy' + ? t('copies.maintenance.removeCopyHint') + : 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 ( <> - - {options && (
-

{t(unlinkOnly ? 'copies.maintenance.unlinkLocation' : 'copies.maintenance.deleteLocation', { path: steam?.copyPath ?? record.copyPath })}

+

{confirmNotice}

+ {canDeleteFiles && ( + + )} + {willDeleteFiles && ( + +

{t('copies.maintenance.deleteFilesWarning', { path: record.copyPath })}

+
+ )} {canDeleteData && ( )}
-
diff --git a/apps/launcher/src/renderer/src/pages/copies/useCopyMaintenance.ts b/apps/launcher/src/renderer/src/pages/copies/useCopyMaintenance.ts index 4ed7b99..b6b9910 100644 --- a/apps/launcher/src/renderer/src/pages/copies/useCopyMaintenance.ts +++ b/apps/launcher/src/renderer/src/pages/copies/useCopyMaintenance.ts @@ -4,7 +4,7 @@ import type { MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/ma import { AppIpcError, ipcInvoke, ipcOn } from '../../ipc.ts'; export type MaintenanceOperation = MaintenanceRequest['operation']; -export type MaintenanceOptions = Pick, 'deleteData' | 'steamLocations' | 'sourcePath'>; +export type MaintenanceOptions = Pick, 'deleteFiles' | 'deleteData' | 'steamLocations' | 'sourcePath'>; export interface MaintenanceOutcome { readonly copyId: string; diff --git a/apps/launcher/src/shared/schemas/maintenance.ts b/apps/launcher/src/shared/schemas/maintenance.ts index 7e06f85..437daf4 100644 --- a/apps/launcher/src/shared/schemas/maintenance.ts +++ b/apps/launcher/src/shared/schemas/maintenance.ts @@ -5,6 +5,7 @@ export const MaintenanceOperationSchema = z.enum(['check', 'repair', 'update', ' export const MaintenanceRequestSchema = z.object({ id: CopyIdSchema, operation: MaintenanceOperationSchema, + deleteFiles: z.boolean().default(false), deleteData: z.boolean().default(false), sourcePath: z.string().min(1).optional(), steamLocations: z.object({ From 29736870acad28ced8d7676c7fc372725d1583b8 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Fri, 4 Dec 2026 19:55:05 +0800 Subject: [PATCH 10/22] fix(launcher): split copied and hardlinked bytes in space-saving install progress Report actual disk-copied bytes separately from NTFS hardlinked asset bytes during space-saving installation, display both counts clearly in the installer progress view, and note that Windows Explorer folder properties double-count hardlinked space. --- .../src/main/services/install/copy-game.ts | 24 ++++++-- .../src/main/services/install/install-game.ts | 27 +++++++-- .../src/renderer/src/i18n/locales/en.json | 5 +- .../src/renderer/src/i18n/locales/zh-CN.json | 5 +- .../renderer/src/pages/install/MethodStep.tsx | 8 +++ .../src/pages/install/ProgressStep.tsx | 58 ++++++++++++++++--- apps/launcher/src/shared/schemas/install.ts | 12 ++++ 7 files changed, 119 insertions(+), 20 deletions(-) diff --git a/apps/launcher/src/main/services/install/copy-game.ts b/apps/launcher/src/main/services/install/copy-game.ts index fd46653..9c75fd5 100644 --- a/apps/launcher/src/main/services/install/copy-game.ts +++ b/apps/launcher/src/main/services/install/copy-game.ts @@ -68,6 +68,12 @@ 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. */ @@ -129,12 +135,19 @@ export async function copyPlannedFiles( for (const folder of plan.folders) await fsPromises.mkdir(join(target, folder), { recursive: true }); const linkedTargets = hardlinks ? new Map() : undefined; let next = 0; - let doneBytes = 0; + let copiedBytes = 0; + let linkedBytes = 0; + let linkedFiles = 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) { - doneBytes += chunk.length; - onProgress({ doneBytes, doneFiles }); + copiedBytes += chunk.length; + emitProgress(); callback(null, chunk); }, }); @@ -155,7 +168,8 @@ export async function copyPlannedFiles( if (verified) { const linked = await linkVerifiedResource(from, to, verified); linkedTargets?.set(to, linked); - doneBytes += file.bytes; + linkedBytes += file.bytes; + linkedFiles += 1; } else { await pipeline( fs.createReadStream(from), @@ -168,7 +182,7 @@ export async function copyPlannedFiles( await fsPromises.utimes(to, modified, modified); } doneFiles += 1; - onProgress({ doneBytes, doneFiles }); + emitProgress(); } } catch (error) { if (!hasError && !stop.signal.aborted && !signal.aborted) { diff --git a/apps/launcher/src/main/services/install/install-game.ts b/apps/launcher/src/main/services/install/install-game.ts index ea86232..8e686f4 100644 --- a/apps/launcher/src/main/services/install/install-game.ts +++ b/apps/launcher/src/main/services/install/install-game.ts @@ -219,8 +219,10 @@ async function copyGame( 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 linkedBytes = hardlinks ? [...hardlinks.values()].reduce((total, file) => total + Number(file.size), 0) : 0; - const neededBytes = plan.totalBytes - linkedBytes + SPARE_BYTES; + 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'); } @@ -229,11 +231,26 @@ async function copyGame( throw new AppError('not_enough_space', { neededGb: gigabytes(neededBytes), freeGb: gigabytes(available) }); } const targetExisted = await exists(target); - const totals = { totalBytes: plan.totalBytes, totalFiles: plan.files.length }; - report({ phase: 'copying', doneBytes: 0, doneFiles: 0, ...totals }); + // 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 })); try { await copyPlannedFiles(source, target, plan, signal, - (done) => report({ phase: 'copying', ...done, ...totals }), hardlinks); + (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), diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index fd5e504..66c69ba 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -158,7 +158,8 @@ "copy": "Copy installation (recommended)", "copyBody": "Copies the game to a new folder. Requires about {{size}} of free space.", "spaceSaving": "Space-saving copy", - "spaceSavingBody": "Shares read-only resource archives on the same volume. Estimated space required is {{size}}. An in-place update to the source client can change shared files in this client.", + "spaceSavingBody": "Resource packs are shared with the online client via same-volume hard links, requiring only about {{size}} of additional copying. Windows Explorer Properties counts shared files toward both folders, but only the newly copied files use extra disk space. An in-place update to the online client can change shared files.", + "spaceSavingBreakdown": "Estimated copy: about {{copy}} · Shared via hard links: about {{shared}} (no extra disk space)", "spaceSavingPending": "Calculating how much space can be saved.", "spaceSavingUnavailable": "This installation has no read-only resource archives eligible for space-saving copying.", "sameVolumeRequired": "Select a destination on the same volume as the original installation.", @@ -214,6 +215,8 @@ "recording": "Finishing installation" }, "copied": "Copied {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files", + "copiedActual": "Copied to disk: {{copied}} / {{copyTotal}} ({{copiedFiles}} / {{copyTotalFiles}} files)", + "linkedShared": "Shared via hard links (no extra space): {{linked}} / {{linkTotal}} ({{linkedFiles}} / {{linkTotalFiles}} resource packs)", "verified": "Verified {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files", "prepared": "Prepared {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files", "cancelHint": "Can be cancelled at any time; copied files will be deleted", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index 34cb6c3..10ebcad 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -158,7 +158,8 @@ "copy": "复制安装(推荐)", "copyBody": "将游戏复制到新文件夹。需要约 {{size}} 的可用空间。", "spaceSaving": "节省空间的复制", - "spaceSavingBody": "与同一磁盘卷上的原版共用只读资源包,预计需要 {{size}}。原版就地更新可能改变客户端中的共享文件。", + "spaceSavingBody": "资源包通过同盘硬链接与在线版共享,仅需额外复制约 {{size}};Windows 资源管理器「属性」会重复统计共享文件大小,实际只占新增复制的磁盘空间。原版就地更新可能改变共享文件。", + "spaceSavingBreakdown": "预计实际复制约 {{copy}} · 硬链接共享约 {{shared}}(不额外占用磁盘空间)", "spaceSavingPending": "正在估算可节省的空间。", "spaceSavingUnavailable": "该安装目录没有可用于省空间复制的只读资源包。", "sameVolumeRequired": "请选择与原版位于同一磁盘卷的目标文件夹。", @@ -214,6 +215,8 @@ "recording": "完成安装" }, "copied": "已复制 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件", + "copiedActual": "实际复制:已复制 {{copied}} / {{copyTotal}}({{copiedFiles}} / {{copyTotalFiles}} 个文件)", + "linkedShared": "硬链接共享(不额外占空间):已链接共享 {{linked}} / {{linkTotal}}({{linkedFiles}} / {{linkTotalFiles}} 个资源包)", "verified": "已核对 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件", "prepared": "已处理 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件", "cancelHint": "可随时取消,已复制的文件将被删除", diff --git a/apps/launcher/src/renderer/src/pages/install/MethodStep.tsx b/apps/launcher/src/renderer/src/pages/install/MethodStep.tsx index f92ce7d..fff0d8c 100644 --- a/apps/launcher/src/renderer/src/pages/install/MethodStep.tsx +++ b/apps/launcher/src/renderer/src/pages/install/MethodStep.tsx @@ -89,6 +89,14 @@ export function MethodStep({ source, sourceSize, choice, onChoice, onError }: Me : t('method.spaceSavingPending')} onSelect={() => choose('hardlink')} > + {sourceSize && savingAvailable && ( +

+ {t('method.spaceSavingBreakdown', { + copy: formatBytes(bytesToCopy(sourceSize, 'hardlink')), + shared: formatBytes(sourceSize.linkableBytes ?? 0), + })} +

+ )} {targetPicker} 0 + ? { + copiedBytes: progress.copiedBytes, + copyTotalBytes: progress.copyTotalBytes, + linkedBytes: progress.linkedBytes, + linkTotalBytes: progress.linkTotalBytes, + linkedFiles: progress.linkedFiles, + linkTotalFiles: progress.linkTotalFiles, + copiedFiles: Math.max(0, progress.doneFiles - progress.linkedFiles), + copyTotalFiles: Math.max(0, progress.totalFiles - progress.linkTotalFiles), + } + : null; return ( <> {phases.map((name, position) => { @@ -32,14 +53,35 @@ export function ProgressStep({ progress, useHardLinks, importDecals }: { })} {tracking && ( -
- {t(caption, { - done: formatBytes(progress.doneBytes), - total: formatBytes(progress.totalBytes), - doneFiles: progress.doneFiles.toLocaleString(), - totalFiles: progress.totalFiles.toLocaleString(), - })} -
+ hardlinkStats ? ( + <> +
+ {t('progress.copiedActual', { + copied: formatBytes(hardlinkStats.copiedBytes), + copyTotal: formatBytes(hardlinkStats.copyTotalBytes), + copiedFiles: hardlinkStats.copiedFiles.toLocaleString(), + copyTotalFiles: hardlinkStats.copyTotalFiles.toLocaleString(), + })} +
+
+ {t('progress.linkedShared', { + linked: formatBytes(hardlinkStats.linkedBytes), + linkTotal: formatBytes(hardlinkStats.linkTotalBytes), + linkedFiles: hardlinkStats.linkedFiles.toLocaleString(), + linkTotalFiles: hardlinkStats.linkTotalFiles.toLocaleString(), + })} +
+ + ) : ( +
+ {t(caption, { + done: formatBytes(progress.doneBytes), + total: formatBytes(progress.totalBytes), + doneFiles: progress.doneFiles.toLocaleString(), + totalFiles: progress.totalFiles.toLocaleString(), + })} +
+ ) )} ); diff --git a/apps/launcher/src/shared/schemas/install.ts b/apps/launcher/src/shared/schemas/install.ts index 3981ff7..0460de0 100644 --- a/apps/launcher/src/shared/schemas/install.ts +++ b/apps/launcher/src/shared/schemas/install.ts @@ -143,6 +143,18 @@ export const InstallProgressSchema = z.object({ totalBytes: z.number(), doneFiles: z.number(), totalFiles: z.number(), + /** Actual bytes written to disk during copying (excludes hard-linked files). */ + copiedBytes: z.number().nonnegative().optional(), + /** Total bytes planned to be written to disk during copying (excludes hard-linked files). */ + copyTotalBytes: z.number().nonnegative().optional(), + /** Bytes shared via hard links so far (occupies no extra disk space). */ + linkedBytes: z.number().nonnegative().optional(), + /** Total bytes planned to be shared via hard links. */ + linkTotalBytes: z.number().nonnegative().optional(), + /** Number of hard-linked files created so far. */ + linkedFiles: z.number().nonnegative().optional(), + /** Total number of files planned to be shared via hard links. */ + linkTotalFiles: z.number().nonnegative().optional(), }); export type InstallProgress = z.output; From 49264b03261726d11cfe7aac17efb32d95ea91cf Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Fri, 4 Dec 2026 20:38:08 +0800 Subject: [PATCH 11/22] feat(launcher): add client origin marker and stock restore removal flow Write a self-describing wtoffline/client.json origin marker (copy, hardlink, or in-place) on install, space-saving compaction, and hardlink-detaching updates, and read it with lightweight hardlink nlink sampling when inspecting existing folders. Allow deleting existing folders only when backed by a valid copy/hardlink marker outside Steam and disjoint from all registered source paths, and add an atomic restore-stock-and-remove option that restores the four stock core files and removes only wto_ws.{dll,cfg,log} and wtoffline/. --- .../services/copies/copy-file-maintenance.ts | 14 +- .../main/services/copies/copy-maintenance.ts | 181 +++--------- .../src/main/services/copies/copy-removal.ts | 272 ++++++++++++++++++ .../game-folder/inspect-game-folder.ts | 7 + .../main/services/install/client-marker.ts | 114 ++++++++ .../main/services/install/data-location.ts | 27 +- .../main/services/install/hardlink-files.ts | 28 ++ .../src/main/services/install/install-game.ts | 74 ++--- .../src/renderer/src/i18n/locales/en.json | 12 + .../src/renderer/src/i18n/locales/zh-CN.json | 12 + .../src/pages/copies/CopyMaintenance.tsx | 1 + .../pages/copies/CopyMaintenanceControls.tsx | 68 ++++- .../src/pages/copies/useCopyMaintenance.ts | 5 +- apps/launcher/src/shared/schemas/install.ts | 11 + .../src/shared/schemas/maintenance.ts | 7 +- 15 files changed, 626 insertions(+), 207 deletions(-) create mode 100644 apps/launcher/src/main/services/copies/copy-removal.ts create mode 100644 apps/launcher/src/main/services/install/client-marker.ts diff --git a/apps/launcher/src/main/services/copies/copy-file-maintenance.ts b/apps/launcher/src/main/services/copies/copy-file-maintenance.ts index 6744074..ffa511f 100644 --- a/apps/launcher/src/main/services/copies/copy-file-maintenance.ts +++ b/apps/launcher/src/main/services/copies/copy-file-maintenance.ts @@ -7,6 +7,7 @@ import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schema 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, @@ -69,7 +70,7 @@ export async function updateFromSource(record: InstallRecord, root: string, sign signal.throwIfAborted(); const check = await checkPatches(game.path, record.dataPath); signal.throwIfAborted(); - return changeCopyFiles(root, async (incoming) => { + const updated = await changeCopyFiles(root, async (incoming) => { report('copying', 0, copy.totalBytes); let lastReport = 0; await copyPlannedFiles(game.path, incoming, copy, signal, ({ doneBytes }) => { @@ -104,6 +105,13 @@ export async function updateFromSource(record: InstallRecord, root: string, sign 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 { @@ -188,7 +196,7 @@ export async function compactCopy(record: InstallRecord, root: string, signal: A 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])); - return changeCopyFiles(root, async (incoming) => { + const updated = await changeCopyFiles(root, async (incoming) => { const replacements: string[] = []; const unchanged = new Map(); let checked = 0; @@ -225,6 +233,8 @@ export async function compactCopy(record: InstallRecord, root: string, signal: A 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 { diff --git a/apps/launcher/src/main/services/copies/copy-maintenance.ts b/apps/launcher/src/main/services/copies/copy-maintenance.ts index ec8e00d..0323406 100644 --- a/apps/launcher/src/main/services/copies/copy-maintenance.ts +++ b/apps/launcher/src/main/services/copies/copy-maintenance.ts @@ -1,21 +1,29 @@ -import { readdir, rm } from 'node:fs/promises'; -import { isAbsolute, join, parse, relative, resolve } from 'node:path'; -import { app } from 'electron'; +import { isAbsolute, relative } from 'node:path'; import { isInSteamLibrary } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; import type { Copies, 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 { installationInProgress } from '../install/install-game.ts'; -import { canonicalCopyPath, copyPathContains, listCopies, removeCopyRecord, steamLibraryNeedsConfirmation, updateCopyRecord } from '../install/install-record.ts'; +import { canonicalCopyPath, listCopies, steamLibraryNeedsConfirmation, 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 { fileInfo } from './change-copy-files.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'; +export { canDeleteCopyFiles, canRestoreStock, resolveClientOrigin } from './copy-removal.ts'; + let current: { stop: AbortController; interruptible: boolean; @@ -35,9 +43,23 @@ export function cancelMaintenance(): void { } export async function maintenanceInfo(id: string): Promise { - const record = await requireCopy(id); - const source = await readSource(record); - const [copyPath, dataPath] = await Promise.all([canonicalCopyPath(record.copyPath), canonicalCopyPath(record.dataPath)]); + 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 { @@ -47,6 +69,10 @@ export async function maintenanceInfo(id: string): Promise { 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, }; } @@ -90,17 +116,22 @@ export async function maintainCopy( } } -/** Only launcher-created copies outside any Steam library may have their game folder deleted on disk. */ -export function canDeleteCopyFiles(record: InstallRecord, root: string): boolean { - return record.method === 'copy' && !isInSteamLibrary(record.copyPath) && !isInSteamLibrary(root); -} - async function performMaintenance(request: MaintenanceRequest, signal: AbortSignal, report: Report): Promise { const { id, operation, steamLocations } = request; const record = await requireCopy(id); if (operation === 'set-source') return setCopySource(record, request.sourcePath); if (operation === 'delete') { - return remove(record, request.deleteFiles === true, request.deleteData === true, signal, report); + return removeCopy( + record, + { + deleteFiles: request.deleteFiles === true, + restoreStock: request.restoreStock === true, + deleteData: request.deleteData === true, + }, + signal, + report, + labServerUses, + ); } const root = await checkedRoot(record); @@ -140,42 +171,6 @@ async function requireCopy(id: string): Promise { return record; } -function failLocation(reason: string, details: Record): never { - console.warn('[copies] maintenance_location:', reason, details); - throw new AppError('maintenance_location'); -} - -async function checkedRoot(record: InstallRecord): Promise { - 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 (copyPathContains(source, root) || copyPathContains(root, source)) { - failLocation('copy_overlaps_source', { root, source, sourcePath: record.sourcePath }); - } - } - return root; -} - -async function safeFolder(path: string, steamAllowed = false): Promise { - 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; -} - async function labServerUses(root: string): Promise { const lab = await readInstalledLab().catch(() => null); if (!lab || relative(lab.copyPath, root) !== '') return false; @@ -188,87 +183,3 @@ async function recordCheck(record: InstallRecord, folder: string): Promise { - 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) { - report('applying'); - return removeCopyRecord(record.id); - } - - const copyInSteam = isInSteamLibrary(record.copyPath) || isInSteamLibrary(canonicalRoot); - if (copyInSteam) { - failLocation(deleteFiles ? 'delete_files_blocked_in_steam' : 'delete_data_blocked_in_steam', { - method: record.method, - copyPath: record.copyPath, - root: canonicalRoot, - }); - } - - if (deleteFiles && !canDeleteCopyFiles(record, canonicalRoot)) { - failLocation('delete_files_blocked_for_method', { - method: record.method, - copyPath: record.copyPath, - root: canonicalRoot, - }); - } - - const root = deleteFiles ? await checkedRoot(record) : canonicalRoot; - if (deleteFiles && !canDeleteCopyFiles(record, root)) { - failLocation('delete_files_blocked', { method: record.method, copyPath: record.copyPath, root }); - } - - 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 && (copyPathContains(data, source) || copyPathContains(source, data)); - 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 }); - } - } - - report('applying'); - if (deleteFiles) { - if (!deleteData && copyPathContains(root, data)) { - await removeExcept(root, data); - } else { - await rm(root, { recursive: true, force: true }); - } - } - if (deleteData && (!deleteFiles || !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 { - 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()) failLocation('kept_data_ancestor_not_directory', { folder, kept, path }); - await removeExcept(path, kept); - } else { - await rm(path, { recursive: true, force: true }); - } - } -} diff --git a/apps/launcher/src/main/services/copies/copy-removal.ts b/apps/launcher/src/main/services/copies/copy-removal.ts new file mode 100644 index 0000000..a900b86 --- /dev/null +++ b/apps/launcher/src/main/services/copies/copy-removal.ts @@ -0,0 +1,272 @@ +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): 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 { + 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 { + return Promise.all(copies.map(async (copy) => ( + copy.sourcePath ? { ...copy, sourcePath: await canonicalCopyPath(copy.sourcePath) } : copy + ))); +} + +export async function checkedRoot(record: InstallRecord): Promise { + 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 { + 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, +): Promise { + 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 { + 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 { + 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 }); + } + } +} diff --git a/apps/launcher/src/main/services/game-folder/inspect-game-folder.ts b/apps/launcher/src/main/services/game-folder/inspect-game-folder.ts index d1aa5dd..0567d14 100644 --- a/apps/launcher/src/main/services/game-folder/inspect-game-folder.ts +++ b/apps/launcher/src/main/services/game-folder/inspect-game-folder.ts @@ -3,6 +3,7 @@ import { dirname, 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'; @@ -61,6 +62,10 @@ export async function inspectGameFolder(path: string): Promise; + +/** 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 `/wtoffline/client.json`. + * Returns `null` when missing, unreadable, malformed, or schema-invalid without throwing. + */ +export async function readClientMarker(copyFolder: string): Promise { + 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 `/wtoffline/client.json`. + * Preserves `createdAt` and records `updatedAt` when updating an existing valid marker. + */ +export async function writeClientMarker(copyFolder: string, origin: ClientOrigin): Promise { + 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 { + 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; +} diff --git a/apps/launcher/src/main/services/install/data-location.ts b/apps/launcher/src/main/services/install/data-location.ts index b4a00d1..defa9a5 100644 --- a/apps/launcher/src/main/services/install/data-location.ts +++ b/apps/launcher/src/main/services/install/data-location.ts @@ -1,6 +1,31 @@ import { readdir } from 'node:fs/promises'; -import { join } from 'node:path'; +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 { diff --git a/apps/launcher/src/main/services/install/hardlink-files.ts b/apps/launcher/src/main/services/install/hardlink-files.ts index b3199d7..0d0c424 100644 --- a/apps/launcher/src/main/services/install/hardlink-files.ts +++ b/apps/launcher/src/main/services/install/hardlink-files.ts @@ -1,7 +1,11 @@ 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 } @@ -83,3 +87,27 @@ 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> { + 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(); + 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; +} diff --git a/apps/launcher/src/main/services/install/install-game.ts b/apps/launcher/src/main/services/install/install-game.ts index 8e686f4..2255285 100644 --- a/apps/launcher/src/main/services/install/install-game.ts +++ b/apps/launcher/src/main/services/install/install-game.ts @@ -1,19 +1,21 @@ -import type { BigIntStats } from 'node:fs'; import { access, mkdir } from 'node:fs/promises'; -import { dirname, isAbsolute, join, relative } from 'node:path'; +import { dirname, isAbsolute, relative } from 'node:path'; import { app } from 'electron'; -import { isHardlinkableResource, isInSteamLibrary } from '@wto/patcher'; +import { isInSteamLibrary } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; -import type { DataFolderProblem, InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts'; +import type { ClientOrigin, 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 { copyPlannedFiles, planCopy, removeInterruptedCopy, type CopyPlan } from './copy-game.ts'; -import { requireUnredirectedData } from './data-location.ts'; +import { readClientMarker, writeClientMarker } from './client-marker.ts'; +import { copyPlannedFiles, planCopy, removeInterruptedCopy } from './copy-game.ts'; +import { dataFolderProblem, requireUnredirectedData } from './data-location.ts'; import { discardDecalCache, importDecalCache } from './decals.ts'; -import { statHardlinkResource } from './hardlink-files.ts'; +import { prepareHardlinks } from './hardlink-files.ts'; import { canonicalCopyPath, copyPathContains, requireAvailableCopy, writeInstallRecord } from './install-record.ts'; import { checkPatches } from './patch-check.ts'; -import { backUpStockFiles, installStockSource, refreshStockBackup, refreshStockBackupFrom, requireStockBackupLocation, STOCK_BACKUP_FOLDER } from './stock-backup.ts'; +import { backUpStockFiles, installStockSource, refreshStockBackup, refreshStockBackupFrom, requireStockBackupLocation } from './stock-backup.ts'; + +export { dataFolderProblem } from './data-location.ts'; /** * Install the offline version: check the patches against the player's game, @@ -101,6 +103,16 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr ? await refreshStockBackup(copyPath) : 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, @@ -116,6 +128,7 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr installedAt: new Date().toISOString(), lastCheckedAt: new Date().toISOString(), ...(decalCacheId ? { decalCacheId } : {}), + ...(detectedOrigin ? { detectedOrigin } : {}), ...copied, }; await writeInstallRecord(record); @@ -176,28 +189,6 @@ async function inspectInstallation(request: InstallRequest) { return { version: game.version, requestedCopyPath, copyPath, dataPath, sourcePath, externalStockPath, target, useHardLinks, copyInSteam, dataInSteam }; } -/** - * 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; -} - async function resolveExternalStockSource(stockSourcePath: string, expectedVersion: string | null) { const stockGame = await requireGameFolder(stockSourcePath); if (stockGame.needsStockSource) throw new AppError('stock_source_invalid'); @@ -265,29 +256,6 @@ async function copyGame( } } -async function prepareHardlinks( - source: string, - plan: CopyPlan, - signal: AbortSignal, - report: (progress: InstallProgress) => void, -): Promise> { - 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(); - 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; -} - async function requireGameFolder(path: string) { const game = await inspectGameFolder(path); if (game.missingFiles.length) throw new AppError('not_a_game_folder', { path }); diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index 66c69ba..00849ed 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -264,15 +264,27 @@ "remove": "Remove client", "removeAction": "Remove…", "removeCopyHint": "Removes from the launcher list by default without deleting files on disk.", + "removeRestoreHint": "Removes from the launcher list by default; optionally restores original files and removes offline patch files while keeping the base game.", "removeUnlinkHint": "Removes only from the launcher list without deleting game files on disk.", "removeSteamHint": "Removes only from the launcher list. Steam game files and the data folder stay in place.", "removeCopyNotice": "Removes {{path}} from the launcher list. All game files and data on disk are kept by default.", "removeListOnlyNotice": "Removes {{path}} from the launcher list only. Game files on disk will not be deleted.", "removeSteamNotice": "Removes {{path}} from the launcher list only. Steam game files and data on disk will not be deleted.", + "originCopy": "Detected client type: full copy (created as an independent copy by the launcher).", + "originHardlink": "Detected client type: space-saving hard-linked copy (read-only resource packs are shared; deleting this copy does not affect the original game folder).", + "originInPlace": "Detected client type: in-place installation (full folder deletion is disabled to protect the base game).", + "originUnknown": "Detected client type: existing folder of unknown origin (no client identity marker found; full folder deletion is disabled for safety).", + "originUnknownHardlinked": "Detected client type: existing folder of unknown origin (hard-linked resources were detected without a client identity marker; full folder deletion is disabled for safety).", "deleteFiles": "Also delete the client folder at {{path}}", + "deleteHardlinkHint": "Note: This client shares read-only resource packs via hard links; deleting the copy folder will not affect the original game folder.", "deleteFilesWarning": "This will permanently delete all files in the copied client folder at {{path}}. This action cannot be undone.", + "deleteHardlinkWarning": "This will permanently delete all files in the hard-linked copy folder at {{path}} (the original game folder is unaffected). This action cannot be undone.", + "restoreStock": "Restore original files and remove offline patch files (keep base game)", + "restoreStockHint": "Restores the 4 original core files from wtoffline\\stock and removes wtoffline\\ along with network hook files (wto_ws.dll / wto_ws.cfg / wto_ws.log). No base game files are deleted.", "deleteData": "Also delete the data folder at {{path}} (contains saves, settings, and logs)", + "openFolder": "Open folder", "confirmRemove": "Remove from list", + "confirmRestore": "Restore and remove", "confirmDelete": "Confirm deletion", "phase": { "checking": "Checking the client", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index 10ebcad..bf83c00 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -264,15 +264,27 @@ "remove": "移除客户端", "removeAction": "移除…", "removeCopyHint": "默认仅从启动器列表移除,不会删除磁盘文件。", + "removeRestoreHint": "默认仅从启动器列表移除;也可选还原为原版并清理离线补丁文件(保留游戏本体)。", "removeUnlinkHint": "仅从启动器列表移除,不会删除磁盘上的游戏文件。", "removeSteamHint": "仅从启动器列表移除,Steam 游戏文件和数据目录将留在原处。", "removeCopyNotice": "将从启动器列表移除 {{path}}。默认保留磁盘上的所有游戏文件和数据。", "removeListOnlyNotice": "将仅从启动器列表移除 {{path}},不会删除磁盘上的游戏文件。", "removeSteamNotice": "将仅从启动器列表移除 {{path}},不会删除磁盘上的 Steam 游戏文件和数据目录。", + "originCopy": "识别结果:完整复制副本(由启动器独立复制创建)。", + "originHardlink": "识别结果:省空间硬链接副本(只读资源包与原版共享,删除副本不会影响原版游戏目录)。", + "originInPlace": "识别结果:原位安装目录(为保护原版游戏本体,不支持直接删除整个文件夹)。", + "originUnknown": "识别结果:未知来源的已有目录(缺少客户端身份标记,为保护游戏文件不支持直接删除整个文件夹)。", + "originUnknownHardlinked": "识别结果:未知来源的已有目录(检测到硬链接资源包,但缺少客户端身份标记;为保护原版目录不支持直接删除整个文件夹)。", "deleteFiles": "同时删除客户端文件夹 {{path}}", + "deleteHardlinkHint": "提示:此客户端使用同盘硬链接共享资源包,删除副本文件夹不会影响原版游戏目录。", "deleteFilesWarning": "将永久删除客户端副本文件夹 {{path}} 中的全部文件,此操作无法撤销。", + "deleteHardlinkWarning": "将永久删除硬链接副本文件夹 {{path}} 中的全部文件(不会影响原版游戏目录),此操作无法撤销。", + "restoreStock": "还原为原版并清理离线补丁文件(保留游戏本体)", + "restoreStockHint": "将从 wtoffline\\stock 恢复原版 4 个核心文件,并删除 wtoffline\\ 目录与网络钩子文件(wto_ws.dll / wto_ws.cfg / wto_ws.log),绝不删除其他游戏本体文件。", "deleteData": "同时删除数据文件夹 {{path}}(包含存档、配置与日志)", + "openFolder": "打开所在文件夹", "confirmRemove": "从列表移除", + "confirmRestore": "还原并移除", "confirmDelete": "确认删除", "phase": { "checking": "正在检查客户端", diff --git a/apps/launcher/src/renderer/src/pages/copies/CopyMaintenance.tsx b/apps/launcher/src/renderer/src/pages/copies/CopyMaintenance.tsx index 5e352dc..48634c3 100644 --- a/apps/launcher/src/renderer/src/pages/copies/CopyMaintenance.tsx +++ b/apps/launcher/src/renderer/src/pages/copies/CopyMaintenance.tsx @@ -65,6 +65,7 @@ export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanc options={removal} onOptionsChange={setRemoval} onRemove={(options) => run('delete', options)} + onOpenFolder={() => { ipcInvoke('app:openFolder', { path: record.copyPath }).catch(onError); }} /> {active && } {result &&

{t(`copies.maintenance.result.${result}`)}

} diff --git a/apps/launcher/src/renderer/src/pages/copies/CopyMaintenanceControls.tsx b/apps/launcher/src/renderer/src/pages/copies/CopyMaintenanceControls.tsx index 65cb9be..f8c7a7f 100644 --- a/apps/launcher/src/renderer/src/pages/copies/CopyMaintenanceControls.tsx +++ b/apps/launcher/src/renderer/src/pages/copies/CopyMaintenanceControls.tsx @@ -70,6 +70,7 @@ export function CopyMaintenanceActions({ record, info, busy, onRun, onChooseSour export interface CopyRemovalOptions { readonly deleteFiles: boolean; + readonly restoreStock: boolean; readonly deleteData: boolean; } @@ -77,24 +78,44 @@ interface CopyRemovalProps extends CopyMaintenanceControlsProps { readonly options: CopyRemovalOptions | null; readonly onOptionsChange: (options: CopyRemovalOptions | null) => void; readonly onRemove: (options: CopyRemovalOptions) => void; + readonly onOpenFolder: () => void; } -export function CopyRemoval({ record, info, busy, options, onOptionsChange, onRemove }: CopyRemovalProps) { +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 !== null && record.method === 'copy' && !copyInSteam; + 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 willDeleteAny = willDeleteFiles || willDeleteData; - const action = t(willDeleteAny ? 'copies.maintenance.confirmDelete' : 'copies.maintenance.confirmRemove'); + const action = t( + willDeleteFiles || willDeleteData + ? 'copies.maintenance.confirmDelete' + : willRestoreStock + ? 'copies.maintenance.confirmRestore' + : 'copies.maintenance.confirmRemove', + ); const rowHint = copyInSteam ? t('copies.maintenance.removeSteamHint') - : record.method === 'copy' + : canDeleteFiles ? t('copies.maintenance.removeCopyHint') - : t('copies.maintenance.removeUnlinkHint'); + : canRestoreAndRemove + ? t('copies.maintenance.removeRestoreHint') + : t('copies.maintenance.removeUnlinkHint'); const confirmNotice = copyInSteam ? t('copies.maintenance.removeSteamNotice', { path: steam?.copyPath ?? record.copyPath }) : canDeleteFiles @@ -105,25 +126,39 @@ export function CopyRemoval({ record, info, busy, options, onOptionsChange, onRe <> {options && (

{confirmNotice}

+ {info &&

{t(clientOriginNoteKey(info))}

} {canDeleteFiles && ( - + <> + + {isHardlinkCopy &&

{t('copies.maintenance.deleteHardlinkHint')}

} + )} {willDeleteFiles && ( -

{t('copies.maintenance.deleteFilesWarning', { path: record.copyPath })}

+

{t(isHardlinkCopy ? 'copies.maintenance.deleteHardlinkWarning' : 'copies.maintenance.deleteFilesWarning', { path: record.copyPath })}

)} + {canRestoreAndRemove && ( + <> + +

{t('copies.maintenance.restoreStockHint')}

+ + )} {canDeleteData && (