Game client: download and update through the Manager

PLAY turns into UPDATE CLIENT when a tracked client is outdated; with no client linked
it offers choosing an existing folder or downloading from the community launcher servers
(resumable, hash-verified, free-space checked, progress and stop). Files the player changed
are kept on request or moved aside, never silently replaced. Existing clients can be adopted
from Settings. Fresh downloads get a realmlist for each installed locale.

Fixes zero-length files in the downloader (found by the live probe).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
ДмитрийandClaude Sonnet 5.5 committed 2026-10-01 07:52:58 +05:00
1 parent 7d447b490f
commit 615b3e938d
21 files changed
+1632 -27

No files matched your search

+16 -1
View File
@@ -36,7 +36,22 @@ export {};
if(cmd==="get_population"){if(!running) return null;let b=(window as any).__bots??85;const t=(window as any).__target??0;if(t>b){b=Math.min(t,b+25);(window as any).__bots=b;}return {online_total:b,bots_online:Math.max(0,b-7),players_online:0,bots_total:b};}
if(cmd==="get_performance") return running?{mean_ms:14,median_ms:15,p95_ms:24,p99_ms:30,max_ms:61,ticks_per_sec:71.4}:null;
if(cmd==="run_diagnostics") return {problems:2,checks:[{id:"files",title:"Server files",level:"ok",detail:"All expected server parts were found."},{id:"world",title:"World server",level:"warn",detail:"Not running."},{id:"disk",title:"Free disk space",level:"warn",detail:"Only 3 GB free; backups and updates need room."},{id:"exposure",title:"Private services",level:"ok",detail:"Database and server console are not reachable from the network."}]};
if(cmd==="plugin:event|listen") return 1;
if(cmd.startsWith("client_")){
const w=window as any;
const emit=(payload: any)=>(w.__handlers?.["client-progress"]??[]).forEach((h: any)=>h({event:"client-progress",id:1,payload}));
const sleep=(ms: number)=>new Promise((r: any)=>setTimeout(r,ms));
const total=46404000000;
const run=async(phase: string,n: number,speed: number)=>{for(let i=1;i<=n;i++){if(w.__stop){w.__stop=false;throw {human:{code:"unknown",title:"",message:"",actions:[]},technical:"Download cancelled."};}emit({phase,done:Math.round(total*i/n),total,bytes_per_sec:speed,file:phase==="scan"?"Data/patch-"+i+".MPQ":"Data/patch-O.MPQ"});await sleep(120);}};
if(cmd==="client_status"){const c=w.__client??"none";return {linked:c!=="none",managed:c==="old"||c==="new",installed_version:c==="old"?"2026-09-20-01":c==="new"?"2026-09-29-01":null,latest_version:"2026-09-29-01",latest_bytes:total,update_available:c==="old"};}
if(cmd==="client_download_check") return {needed_bytes:total,free_bytes:args.parent.startsWith("C")?210e9:20e9,version:"2026-09-29-01",dest:args.parent+"\\CoA Client"};
if(cmd==="client_plan"){await run("scan",12,0);return {version:"2026-09-29-01",items:[{path:"Data/patch-O.MPQ",size:2814983707,kind:"changed"},{path:"Data/patch-WB1.MPQ",size:2001890268,kind:"missing"},...(w.__modified?[{path:"d3d9.dll",size:4284430,kind:"modified"},{path:"Ascension.exe",size:7694848,kind:"modified"}]:[])],download_bytes:4829000000,total_files:200,up_to_date_files:196,kept_files:0};}
if(cmd==="client_sync"){await run("download",25,41e6);w.__client="new";return null;}
if(cmd==="client_download"){await run("scan",4,0);await run("download",40,41e6);w.__client="new";return {path:args.parent+"\\CoA Client",executable:"Ascension.exe",realmlists:[{path:"x",host:"127.0.0.1"}],addon:{installed:true,version:"1",up_to_date:true},other_addons:0};}
if(cmd==="client_cancel"){w.__stop=true;return null;}
}
if(cmd==="client_info"){const c=(window as any).__client??"none";return c==="none"?null:{path:"C:\\games\\CoA Client",executable:"Ascension.exe",realmlists:[{path:"x",host:"127.0.0.1"}],addon:{installed:true,version:"1",up_to_date:true},other_addons:2};}
if(cmd==="set_client"){(window as any).__client="foreign";return {path:args.path,executable:"Ascension.exe",realmlists:[],addon:{installed:false,version:null,up_to_date:null},other_addons:0};}
if(cmd==="plugin:event|listen"){const w=window as any;(w.__handlers??={})[args.event]=[...(w.__handlers[args.event]??[]),args.handler];return 1;}
if(cmd==="plugin:event|unlisten") return null;
throw new Error("unmocked "+cmd);
}
+50
View File
@@ -578,6 +578,56 @@ const de: Partial<Record<keyof typeof en, string>> = {
"overview.openUpdates": "Updates öffnen",
"overview.updatingNote": "Update läuft: Der Server wird gestoppt, gesichert, aktualisiert und zur Prüfung erneut gestartet.",
"nav.updateDot": "Update verfügbar",
// Game client download and update
"btn.close": "Schließen",
"btn.setupClient": "Spielclient einrichten",
"btn.updateClient": "CLIENT AKTUALISIEREN",
"client.setup.title": "Spielclient einrichten",
"client.setup.intro": "Zum Spielen brauchst du den Spielclient. Nutze einen vorhandenen oder lass ihn vom Manager herunterladen.",
"client.setup.have": "Ich habe bereits einen Client",
"client.setup.haveHint": "Wähle den Ordner mit Data und der Spieldatei. Darin wird nichts verändert.",
"client.setup.download": "Client herunterladen",
"client.setup.downloadHint": "Etwa 43 GB von den Servern des Community-Launchers. Jede Datei wird vor der Nutzung geprüft; ein unterbrochener Download wird fortgesetzt.",
"client.dl.pickParent": "Wähle, wohin der Spielclient soll",
"client.dl.confirmText": "Version {v}, {size}. Er wird in diesem Ordner gespeichert:",
"client.dl.free": "Freier Platz auf diesem Laufwerk: {free}.",
"client.dl.notEnough": "Nicht genug freier Platz: {need} nötig, {free} verfügbar. Wähle ein anderes Laufwerk.",
"client.dl.otherFolder": "Anderer Ordner …",
"client.dl.start": "Herunterladen",
"client.dl.back": "Zurück",
"client.dl.retry": "Erneut versuchen",
"client.dl.resume": "Fortsetzen",
"client.dl.cancel": "Anhalten",
"client.dl.cancelled": "Angehalten. Alles bereits Heruntergeladene bleibt erhalten; du kannst jederzeit fortsetzen.",
"client.dl.scanning": "Dateien werden verglichen …",
"client.dl.downloading": "Wird heruntergeladen",
"client.dl.progress": "{done} von {total}",
"client.dl.speed": "{speed}/s",
"client.dl.done": "Der Spielclient ist bereit",
"client.dl.doneText": "Er ist mit diesem Server verknüpft. Du kannst auf PLAY drücken.",
"client.upd.title": "Client-Update",
"client.upd.available": "Ein neuerer Spielclient ist verfügbar: {v}.",
"client.upd.summary": "{n} Datei(en) zum Herunterladen, insgesamt {size}.",
"client.upd.upToDate": "Dein Client entspricht bereits Version {v}.",
"client.upd.modifiedTitle": "{n} Datei(en) hast du geändert",
"client.upd.modifiedText": "Zum Beispiel eine eigene d3d9.dll oder eine gepatchte Programmdatei. Behalte sie oder ersetze sie durch die offiziellen Versionen; deine werden dann im Ordner .coa-manager des Clients gesichert.",
"client.upd.keep": "Von mir geänderte Dateien behalten",
"client.upd.more": "… und {n} weitere",
"client.upd.start": "Client aktualisieren",
"client.upd.later": "Jetzt nicht",
"client.upd.playAnyway": "Ohne Update spielen",
"client.upd.done": "Der Spielclient ist aktuell",
"client.upd.doneText": "Der Manager sagt dir Bescheid, wenn eine neuere Version erscheint.",
"client.track.title": "Client aktuell halten",
"client.track.text": "Der Manager vergleicht deinen Client einmal mit dem offiziellen und prüft danach auf neue Versionen, wie beim Server. Von dir geänderte Dateien werden nur ersetzt, wenn du es willst.",
"client.track.start": "Aktuell halten",
"client.track.startUpdate": "Aktualisieren und aktuell halten",
"client.track.button": "Diesen Client aktuell halten …",
"client.version": "Client-Version",
"client.versionUntracked": "vom Manager nicht verfolgt",
"client.versionUnfinished": "Download nicht abgeschlossen",
"client.downloadInstead": "Client herunterladen …",
};
export default de;
+50
View File
@@ -578,6 +578,56 @@ const en = {
"overview.openUpdates": "Open updates",
"overview.updatingNote": "Updating: the server is stopped, backed up, updated and started again to check that it works.",
"nav.updateDot": "Update available",
// Game client download and update
"btn.close": "Close",
"btn.setupClient": "Set up game client",
"btn.updateClient": "UPDATE CLIENT",
"client.setup.title": "Set up the game client",
"client.setup.intro": "To play you need the game client. Use one you already have, or let the Manager download it.",
"client.setup.have": "I already have a client",
"client.setup.haveHint": "Choose the folder that contains Data and the game executable. Nothing in it is changed.",
"client.setup.download": "Download the client",
"client.setup.downloadHint": "About 43 GB from the community launcher servers. Every file is verified before it is used, and an interrupted download continues where it stopped.",
"client.dl.pickParent": "Choose where to put the game client",
"client.dl.confirmText": "Version {v}, {size}. It will be saved in this folder:",
"client.dl.free": "Free space on that drive: {free}.",
"client.dl.notEnough": "Not enough free space: {need} needed, {free} available. Choose another drive.",
"client.dl.otherFolder": "Other folder…",
"client.dl.start": "Download",
"client.dl.back": "Back",
"client.dl.retry": "Try again",
"client.dl.resume": "Continue",
"client.dl.cancel": "Stop",
"client.dl.cancelled": "Stopped. Everything already downloaded is kept; continue whenever you like.",
"client.dl.scanning": "Comparing files…",
"client.dl.downloading": "Downloading",
"client.dl.progress": "{done} of {total}",
"client.dl.speed": "{speed}/s",
"client.dl.done": "The game client is ready",
"client.dl.doneText": "It is linked to this server. You can press PLAY.",
"client.upd.title": "Client update",
"client.upd.available": "A newer game client is available: {v}.",
"client.upd.summary": "{n} file(s) to download, {size} in total.",
"client.upd.upToDate": "Your client already matches version {v}.",
"client.upd.modifiedTitle": "{n} file(s) were changed by you",
"client.upd.modifiedText": "For example a custom d3d9.dll or a patched executable. Keep them, or replace them with the official versions; yours are then saved in the client’s .coa-manager folder.",
"client.upd.keep": "Keep the files I changed",
"client.upd.more": "… and {n} more",
"client.upd.start": "Update client",
"client.upd.later": "Not now",
"client.upd.playAnyway": "Play without updating",
"client.upd.done": "The game client is up to date",
"client.upd.doneText": "The Manager will tell you when a newer one is published.",
"client.track.title": "Keep the client up to date",
"client.track.text": "The Manager compares your client with the official one once, then checks for new versions like it does for the server. Files you changed are never replaced unless you say so.",
"client.track.start": "Keep up to date",
"client.track.startUpdate": "Update and keep up to date",
"client.track.button": "Keep this client up to date…",
"client.version": "Client version",
"client.versionUntracked": "not tracked by the Manager",
"client.versionUnfinished": "download not finished",
"client.downloadInstead": "Download a client…",
} as const;
export default en;
+50
View File
@@ -578,6 +578,56 @@ const es: Partial<Record<keyof typeof en, string>> = {
"overview.openUpdates": "Abrir actualizaciones",
"overview.updatingNote": "Actualizando: el servidor se detiene, se respalda, se actualiza y se inicia de nuevo para comprobar que funciona.",
"nav.updateDot": "Actualización disponible",
// Game client download and update
"btn.close": "Cerrar",
"btn.setupClient": "Configurar el cliente del juego",
"btn.updateClient": "ACTUALIZAR CLIENTE",
"client.setup.title": "Configurar el cliente del juego",
"client.setup.intro": "Para jugar necesitas el cliente del juego. Usa uno que ya tengas o deja que el Manager lo descargue.",
"client.setup.have": "Ya tengo un cliente",
"client.setup.haveHint": "Elige la carpeta que contiene Data y el ejecutable del juego. No se cambia nada en ella.",
"client.setup.download": "Descargar el cliente",
"client.setup.downloadHint": "Unos 43 GB desde los servidores del lanzador de la comunidad. Cada archivo se verifica antes de usarse y una descarga interrumpida continúa donde se detuvo.",
"client.dl.pickParent": "Elige dónde guardar el cliente del juego",
"client.dl.confirmText": "Versión {v}, {size}. Se guardará en esta carpeta:",
"client.dl.free": "Espacio libre en esa unidad: {free}.",
"client.dl.notEnough": "No hay espacio suficiente: se necesitan {need} y hay {free}. Elige otra unidad.",
"client.dl.otherFolder": "Otra carpeta…",
"client.dl.start": "Descargar",
"client.dl.back": "Atrás",
"client.dl.retry": "Reintentar",
"client.dl.resume": "Continuar",
"client.dl.cancel": "Detener",
"client.dl.cancelled": "Detenido. Todo lo ya descargado se conserva; puedes continuar cuando quieras.",
"client.dl.scanning": "Comparando archivos…",
"client.dl.downloading": "Descargando",
"client.dl.progress": "{done} de {total}",
"client.dl.speed": "{speed}/s",
"client.dl.done": "El cliente del juego está listo",
"client.dl.doneText": "Está vinculado a este servidor. Puedes pulsar PLAY.",
"client.upd.title": "Actualización del cliente",
"client.upd.available": "Hay un cliente del juego más reciente: {v}.",
"client.upd.summary": "{n} archivo(s) por descargar, {size} en total.",
"client.upd.upToDate": "Tu cliente ya coincide con la versión {v}.",
"client.upd.modifiedTitle": "{n} archivo(s) cambiado(s) por ti",
"client.upd.modifiedText": "Por ejemplo un d3d9.dll personalizado o un ejecutable modificado. Consérvalos o reemplázalos por las versiones oficiales; los tuyos se guardan entonces en la carpeta .coa-manager del cliente.",
"client.upd.keep": "Conservar los archivos que cambié",
"client.upd.more": "… y {n} más",
"client.upd.start": "Actualizar cliente",
"client.upd.later": "Ahora no",
"client.upd.playAnyway": "Jugar sin actualizar",
"client.upd.done": "El cliente del juego está actualizado",
"client.upd.doneText": "El Manager te avisará cuando se publique una más reciente.",
"client.track.title": "Mantener el cliente actualizado",
"client.track.text": "El Manager compara una vez tu cliente con el oficial y luego busca versiones nuevas como hace con el servidor. Los archivos que cambiaste solo se reemplazan si tú lo decides.",
"client.track.start": "Mantener actualizado",
"client.track.startUpdate": "Actualizar y mantener actualizado",
"client.track.button": "Mantener este cliente actualizado…",
"client.version": "Versión del cliente",
"client.versionUntracked": "el Manager no la sigue",
"client.versionUnfinished": "descarga sin terminar",
"client.downloadInstead": "Descargar un cliente…",
};
export default es;
+50
View File
@@ -578,6 +578,56 @@ const fr: Partial<Record<keyof typeof en, string>> = {
"overview.openUpdates": "Ouvrir les mises à jour",
"overview.updatingNote": "Mise à jour : le serveur est arrêté, sauvegardé, mis à jour puis relancé pour vérifier qu’il fonctionne.",
"nav.updateDot": "Mise à jour disponible",
// Game client download and update
"btn.close": "Fermer",
"btn.setupClient": "Configurer le client du jeu",
"btn.updateClient": "METTRE À JOUR LE CLIENT",
"client.setup.title": "Configurer le client du jeu",
"client.setup.intro": "Pour jouer, il faut le client du jeu. Utilisez-en un existant ou laissez le Manager le télécharger.",
"client.setup.have": "J’ai déjà un client",
"client.setup.haveHint": "Choisissez le dossier qui contient Data et l’exécutable du jeu. Rien n’y est modifié.",
"client.setup.download": "Télécharger le client",
"client.setup.downloadHint": "Environ 43 Go depuis les serveurs du lanceur communautaire. Chaque fichier est vérifié avant utilisation et un téléchargement interrompu reprend là où il s’est arrêté.",
"client.dl.pickParent": "Choisissez où placer le client du jeu",
"client.dl.confirmText": "Version {v}, {size}. Il sera enregistré dans ce dossier :",
"client.dl.free": "Espace libre sur ce disque : {free}.",
"client.dl.notEnough": "Espace libre insuffisant : {need} nécessaires, {free} disponibles. Choisissez un autre disque.",
"client.dl.otherFolder": "Autre dossier…",
"client.dl.start": "Télécharger",
"client.dl.back": "Retour",
"client.dl.retry": "Réessayer",
"client.dl.resume": "Continuer",
"client.dl.cancel": "Arrêter",
"client.dl.cancelled": "Arrêté. Tout ce qui est déjà téléchargé est conservé ; vous pouvez reprendre à tout moment.",
"client.dl.scanning": "Comparaison des fichiers…",
"client.dl.downloading": "Téléchargement",
"client.dl.progress": "{done} sur {total}",
"client.dl.speed": "{speed}/s",
"client.dl.done": "Le client du jeu est prêt",
"client.dl.doneText": "Il est lié à ce serveur. Vous pouvez appuyer sur PLAY.",
"client.upd.title": "Mise à jour du client",
"client.upd.available": "Un client de jeu plus récent est disponible : {v}.",
"client.upd.summary": "{n} fichier(s) à télécharger, {size} au total.",
"client.upd.upToDate": "Votre client correspond déjà à la version {v}.",
"client.upd.modifiedTitle": "{n} fichier(s) modifié(s) par vous",
"client.upd.modifiedText": "Par exemple un d3d9.dll personnalisé ou un exécutable modifié. Conservez-les ou remplacez-les par les versions officielles ; les vôtres sont alors sauvegardées dans le dossier .coa-manager du client.",
"client.upd.keep": "Conserver les fichiers que j’ai modifiés",
"client.upd.more": "… et {n} de plus",
"client.upd.start": "Mettre à jour le client",
"client.upd.later": "Pas maintenant",
"client.upd.playAnyway": "Jouer sans mettre à jour",
"client.upd.done": "Le client du jeu est à jour",
"client.upd.doneText": "Le Manager vous préviendra quand une version plus récente sera publiée.",
"client.track.title": "Garder le client à jour",
"client.track.text": "Le Manager compare une fois votre client avec l’officiel, puis cherche les nouvelles versions comme pour le serveur. Les fichiers que vous avez modifiés ne sont remplacés que si vous le décidez.",
"client.track.start": "Garder à jour",
"client.track.startUpdate": "Mettre à jour et garder à jour",
"client.track.button": "Garder ce client à jour…",
"client.version": "Version du client",
"client.versionUntracked": "non suivi par le Manager",
"client.versionUnfinished": "téléchargement inachevé",
"client.downloadInstead": "Télécharger un client…",
};
export default fr;
+50
View File
@@ -578,6 +578,56 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"overview.openUpdates": "Открыть обновления",
"overview.updatingNote": "Идёт обновление: сервер останавливается, сохраняется резервная копия, затем он обновляется и запускается снова для проверки.",
"nav.updateDot": "Есть обновление",
// Game client download and update
"btn.close": "Закрыть",
"btn.setupClient": "Настроить клиент игры",
"btn.updateClient": "ОБНОВИТЬ КЛИЕНТ",
"client.setup.title": "Настройка клиента игры",
"client.setup.intro": "Чтобы играть, нужен клиент игры. Выберите уже имеющийся или позвольте менеджеру скачать его.",
"client.setup.have": "У меня уже есть клиент",
"client.setup.haveHint": "Выберите папку, где лежат Data и исполняемый файл игры. Ничего в ней не меняется.",
"client.setup.download": "Скачать клиент",
"client.setup.downloadHint": "Около 43 ГБ с серверов лаунчера сообщества. Каждый файл проверяется перед использованием, прерванная загрузка продолжится с того же места.",
"client.dl.pickParent": "Выберите, куда поместить клиент игры",
"client.dl.confirmText": "Версия {v}, {size}. Клиент будет сохранён в эту папку:",
"client.dl.free": "Свободно на этом диске: {free}.",
"client.dl.notEnough": "Недостаточно места: нужно {need}, доступно {free}. Выберите другой диск.",
"client.dl.otherFolder": "Другая папка…",
"client.dl.start": "Скачать",
"client.dl.back": "Назад",
"client.dl.retry": "Повторить",
"client.dl.resume": "Продолжить",
"client.dl.cancel": "Остановить",
"client.dl.cancelled": "Остановлено. Всё уже скачанное сохранено, можно продолжить в любой момент.",
"client.dl.scanning": "Сравниваю файлы…",
"client.dl.downloading": "Загрузка",
"client.dl.progress": "{done} из {total}",
"client.dl.speed": "{speed}/с",
"client.dl.done": "Клиент игры готов",
"client.dl.doneText": "Он привязан к этому серверу. Можно нажимать PLAY.",
"client.upd.title": "Обновление клиента",
"client.upd.available": "Доступна новая версия клиента игры: {v}.",
"client.upd.summary": "Файлов к загрузке: {n}, всего {size}.",
"client.upd.upToDate": "Ваш клиент уже соответствует версии {v}.",
"client.upd.modifiedTitle": "Файлов, изменённых вами: {n}",
"client.upd.modifiedText": "Например, свой d3d9.dll или изменённый exe. Оставьте их или замените официальными версиями; ваши тогда сохранятся в папке .coa-manager внутри клиента.",
"client.upd.keep": "Оставить файлы, которые я менял",
"client.upd.more": "… и ещё {n}",
"client.upd.start": "Обновить клиент",
"client.upd.later": "Не сейчас",
"client.upd.playAnyway": "Играть без обновления",
"client.upd.done": "Клиент игры обновлён",
"client.upd.doneText": "Менеджер сообщит, когда выйдет новая версия.",
"client.track.title": "Обновление клиента через менеджер",
"client.track.text": "Менеджер один раз сравнит ваш клиент с официальным, а потом будет проверять новые версии, как для сервера. Файлы, которые вы меняли, не заменяются без вашего согласия.",
"client.track.start": "Следить за обновлениями",
"client.track.startUpdate": "Обновить и следить за обновлениями",
"client.track.button": "Обновлять этот клиент через менеджер…",
"client.version": "Версия клиента",
"client.versionUntracked": "менеджер не отслеживает",
"client.versionUnfinished": "загрузка не завершена",
"client.downloadInstead": "Скачать клиент…",
};
export default ru;
+39
View File
@@ -226,6 +226,39 @@ export interface ClientInfo {
other_addons: number;
}
export interface ClientStatus {
linked: boolean;
managed: boolean;
installed_version: string | null;
latest_version: string | null;
latest_bytes: number | null;
update_available: boolean;
}
export interface ClientPlan {
version: string;
items: { path: string; size: number; kind: "missing" | "changed" | "modified" }[];
download_bytes: number;
total_files: number;
up_to_date_files: number;
kept_files: number;
}
export interface ClientStep {
phase: "scan" | "download" | "finish";
done: number;
total: number;
bytes_per_sec: number;
file: string | null;
}
export interface ClientDownloadCheck {
needed_bytes: number;
free_bytes: number;
version: string;
dest: string;
}
export type FriendsMode = "local" | "lan" | "direct" | "private";
export interface FriendsStatus {
@@ -301,6 +334,12 @@ export const api = {
setClient: (id: string, path: string) => invoke<ClientInfo>("set_client", { id, path }),
setRealmlist: (id: string, host: string) => invoke<string[]>("client_realmlist", { id, host }),
installAddon: (id: string) => invoke<void>("client_install_addon", { id }),
clientStatus: (id: string) => invoke<ClientStatus>("client_status", { id }),
clientDownloadCheck: (parent: string) => invoke<ClientDownloadCheck>("client_download_check", { parent }),
clientPlan: (id: string) => invoke<ClientPlan>("client_plan", { id }),
clientSync: (id: string, keepModified: boolean) => invoke<void>("client_sync", { id, keepModified }),
clientDownload: (id: string, parent: string) => invoke<ClientInfo>("client_download", { id, parent }),
clientCancel: () => invoke<void>("client_cancel"),
play: (id: string) => invoke<DriverOutcome>("play", { id }),
friendsStatus: (id: string) => invoke<FriendsStatus>("friends_status", { id }),
friendsCheckInternet: () => invoke<InternetCheck>("friends_check_internet"),
+51
View File
@@ -0,0 +1,51 @@
import { useSyncExternalStore } from "react";
import { api, type ClientStatus } from "@/lib/api";
/**
* Game client status for the main screen: which client is linked and, for a client the Manager keeps up to date,
* whether a newer one has been published. Checked at start and every five minutes (one small request; no game file is read).
*/
interface State {
status: ClientStatus | null;
checking: boolean;
}
const EMPTY: State = { status: null, checking: false };
const states = new Map<string, State>();
const listeners = new Set<() => void>();
const CHECK_EVERY_MS = 5 * 60 * 1000;
const get = (id: string) => states.get(id) ?? EMPTY;
function set(id: string, next: Partial<State>) {
states.set(id, { ...get(id), ...next });
listeners.forEach((l) => l());
}
export async function checkClient(id: string): Promise<void> {
if (get(id).checking) return;
set(id, { checking: true });
try {
set(id, { status: await api.clientStatus(id) });
} catch {
// offline: keep what we knew
} finally {
set(id, { checking: false });
}
}
/** Check now and then every five minutes. Returns the function that stops it. */
export function startClientPolling(id: string): () => void {
void checkClient(id);
const t = setInterval(() => void checkClient(id), CHECK_EVERY_MS);
return () => clearInterval(t);
}
export function useClientStatus(id: string): State {
return useSyncExternalStore(
(l) => {
listeners.add(l);
return () => listeners.delete(l);
},
() => get(id),
);
}
+12
View File
@@ -5,6 +5,18 @@ export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
/** 1536 -> "1.5 KB"; 43.2e9 -> "40.2 GB" (binary units, as drive sizes are shown). */
export function formatBytes(n: number): string {
const units = ["B", "KB", "MB", "GB", "TB"];
let v = Math.max(0, n);
let i = 0;
while (v >= 1024 && i < units.length - 1) {
v /= 1024;
i++;
}
return `${i === 0 || v >= 100 ? Math.round(v) : v.toFixed(1)} ${units[i]}`;
}
export function formatUptime(secs: number | null | undefined): string {
if (secs == null) return "—";
const d = Math.floor(secs / 86400);
+35 -3
View File
@@ -1,6 +1,8 @@
import { useEffect, useState } from "react";
import { open } from "@tauri-apps/plugin-dialog";
import { api, asUiError, type ClientInfo, type UiError } from "@/lib/api";
import { api, asUiError, type ClientInfo, type ClientStatus, type UiError } from "@/lib/api";
import { checkClient } from "@/lib/clientUpdate";
import { ClientDialog, type ClientDialogMode } from "@/screens/ClientDialog";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { useHuman, useT } from "@/i18n";
@@ -12,8 +14,13 @@ export function ClientCard({ serverId }: { serverId: string }) {
const [error, setError] = useState<UiError | null>(null);
const [note, setNote] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [status, setStatus] = useState<ClientStatus | null>(null);
const [dialog, setDialog] = useState<ClientDialogMode | null>(null);
const refresh = () => api.clientInfo(serverId).then(setInfo).catch((e) => setError(asUiError(e)));
const refresh = () => {
void api.clientStatus(serverId).then(setStatus).catch(() => setStatus(null));
return api.clientInfo(serverId).then(setInfo).catch((e) => setError(asUiError(e)));
};
useEffect(() => {
void refresh();
}, [serverId]); // eslint-disable-line react-hooks/exhaustive-deps
@@ -48,7 +55,7 @@ export function ClientCard({ serverId }: { serverId: string }) {
{info === null && (
<>
<p className="mt-1 text-sm text-muted">{t("client.intro")}</p>
<Button className="mt-4" onClick={() => void choose()} disabled={busy}>{t("client.chooseFolder")}</Button>
<Button className="mt-4" onClick={() => setDialog("setup")} disabled={busy}>{t("btn.setupClient")}</Button>
</>
)}
{info && (
@@ -60,6 +67,13 @@ export function ClientCard({ serverId }: { serverId: string }) {
{hosts.length ? hosts.filter(Boolean).join(", ") : "—"}
{pointsLocal ? <span className="ml-2 text-ok">{t("client.thisComputer")}</span> : <span className="ml-2 text-warn">{t("client.notThisServer")}</span>}
</dd>
<dt className="text-muted">{t("client.version")}</dt>
<dd>
{status?.managed
? status.installed_version ?? t("client.versionUnfinished")
: t("client.versionUntracked")}
{status?.update_available && <span className="ml-2 text-warn">{t("client.updateAvailable")}</span>}
</dd>
<dt className="text-muted">{t("client.addon")}</dt>
<dd>
{info.addon.installed ? (info.addon.version ? t("client.installedVersion", { v: info.addon.version }) : t("client.installed")) : t("client.addonNotInstalled")}
@@ -79,12 +93,30 @@ export function ClientCard({ serverId }: { serverId: string }) {
{info.addon.installed ? t("client.updateAddon") : t("client.installAddon")}
</Button>
)}
{status?.update_available && (
<Button size="sm" variant="primary" disabled={busy} onClick={() => setDialog("update")}>{t("client.upd.start")}</Button>
)}
{status && !status.managed && (
<Button size="sm" disabled={busy} onClick={() => setDialog("track")}>{t("client.track.button")}</Button>
)}
<Button size="sm" variant="ghost" disabled={busy} onClick={() => void choose()}>{t("client.changeFolder")}</Button>
<Button size="sm" variant="ghost" disabled={busy} onClick={() => setDialog("setup")}>{t("client.downloadInstead")}</Button>
</div>
</>
)}
{note && <p className="mt-3 text-sm text-ok" role="status">{note}</p>}
{error && <p className="mt-3 text-sm text-bad" role="alert">{error.human.code === "unknown" ? error.technical : human(error.human).message}</p>}
{dialog && (
<ClientDialog
serverId={serverId}
mode={dialog}
onClose={() => setDialog(null)}
onChanged={() => {
void refresh();
void checkClient(serverId);
}}
/>
)}
</Card>
);
}
+300
View File
@@ -0,0 +1,300 @@
import { useEffect, useRef, useState } from "react";
import { open } from "@tauri-apps/plugin-dialog";
import { listen } from "@tauri-apps/api/event";
import { Check, Loader2 } from "lucide-react";
import { api, asUiError, type ClientDownloadCheck, type ClientPlan, type ClientStep, type UiError } from "@/lib/api";
import { formatBytes } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { useHuman, useT } from "@/i18n";
/**
* - setup: no client linked yet: pick an existing folder or download the client.
* - update: a client the Manager keeps up to date has a newer version.
* - track: an existing client the Manager has not looked at yet: compare it once, then keep it up to date.
*/
export type ClientDialogMode = "setup" | "update" | "track";
type Phase = "choose" | "confirm" | "scanning" | "preview" | "working" | "done" | "stopped" | "failed";
export function ClientDialog(props: {
serverId: string;
mode: ClientDialogMode;
onClose: () => void;
/** The linked client or its version changed; the caller refreshes what it shows. */
onChanged: () => void;
/** Update mode only: start the game without updating. */
onPlayAnyway?: () => void;
}) {
const t = useT();
const human = useHuman();
const { serverId, mode } = props;
const [phase, setPhase] = useState<Phase>(mode === "setup" ? "choose" : "scanning");
const [step, setStep] = useState<ClientStep | null>(null);
const [parent, setParent] = useState<string | null>(null);
const [check, setCheck] = useState<ClientDownloadCheck | null>(null);
const [plan, setPlan] = useState<ClientPlan | null>(null);
const [keep, setKeep] = useState(true);
const [error, setError] = useState<UiError | null>(null);
const cancelled = useRef(false);
const working = phase === "scanning" || phase === "working";
useEffect(() => {
let un: (() => void) | undefined;
let gone = false;
listen<ClientStep>("client-progress", (e) => setStep(e.payload))
.then((u) => (gone ? u() : (un = u)))
.catch(() => undefined);
return () => {
gone = true;
un?.();
};
}, []);
useEffect(() => {
if (mode !== "setup") void startPlan();
}, []); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape" && !working) close();
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
});
function close() {
props.onChanged();
props.onClose();
}
function fail(e: unknown) {
if (cancelled.current) {
setPhase("stopped");
} else {
setError(asUiError(e));
setPhase("failed");
}
}
async function useExisting() {
const picked = await open({ directory: true, multiple: false, title: t("client.dialogTitle") });
if (typeof picked !== "string") return;
setError(null);
try {
await api.setClient(serverId, picked);
setPhase("done");
} catch (e) {
setError(asUiError(e));
setPhase("failed");
}
}
async function pickParent() {
const picked = await open({ directory: true, multiple: false, title: t("client.dl.pickParent") });
if (typeof picked !== "string") return;
setError(null);
try {
setCheck(await api.clientDownloadCheck(picked));
setParent(picked);
setPhase("confirm");
} catch (e) {
setError(asUiError(e));
setPhase("failed");
}
}
async function startDownload() {
if (!parent) return;
cancelled.current = false;
setStep(null);
setPhase("working");
try {
await api.clientDownload(serverId, parent);
setPhase("done");
} catch (e) {
fail(e);
}
}
async function startPlan() {
cancelled.current = false;
setStep(null);
setError(null);
setPhase("scanning");
try {
const p = await api.clientPlan(serverId);
setPlan(p);
setKeep(p.items.some((i) => i.kind === "modified"));
setPhase("preview");
} catch (e) {
fail(e);
}
}
async function startSync() {
cancelled.current = false;
setStep(null);
setPhase("working");
try {
await api.clientSync(serverId, keep);
setPhase("done");
} catch (e) {
fail(e);
}
}
function stop() {
cancelled.current = true;
void api.clientCancel();
}
const modified = plan?.items.filter((i) => i.kind === "modified") ?? [];
const pct = step && step.total > 0 ? Math.min(100, Math.floor((step.done / step.total) * 100)) : 0;
const title = mode === "setup" ? t("client.setup.title") : mode === "update" ? t("client.upd.title") : t("client.track.title");
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-6" role="presentation">
<Card className="max-h-full w-full max-w-lg overflow-y-auto p-6 shadow-2xl" role="dialog" aria-modal="true" aria-label={title}>
<h2 className="text-lg font-semibold">{title}</h2>
{phase === "choose" && (
<>
<p className="mt-1 text-sm text-muted">{t("client.setup.intro")}</p>
<div className="mt-4 grid gap-3">
<button type="button" onClick={() => void useExisting()} className="cursor-pointer rounded-md border border-line bg-card-2 p-4 text-left transition-colors hover:border-gold/50">
<span className="block font-medium">{t("client.setup.have")}</span>
<span className="mt-1 block text-sm text-muted">{t("client.setup.haveHint")}</span>
</button>
<button type="button" onClick={() => void pickParent()} className="cursor-pointer rounded-md border border-line bg-card-2 p-4 text-left transition-colors hover:border-gold/50">
<span className="block font-medium">{t("client.setup.download")}</span>
<span className="mt-1 block text-sm text-muted">{t("client.setup.downloadHint")}</span>
</button>
</div>
<div className="mt-5 flex justify-end">
<Button variant="ghost" onClick={close}>{t("btn.close")}</Button>
</div>
</>
)}
{phase === "confirm" && check && (
<>
<p className="mt-1 text-sm text-muted">{t("client.dl.confirmText", { v: check.version, size: formatBytes(check.needed_bytes) })}</p>
<p className="selectable mt-3 break-all rounded-md bg-black/30 px-3 py-2 text-sm">{check.dest}</p>
<p className={check.free_bytes < check.needed_bytes + 512 * 1024 * 1024 ? "mt-3 text-sm text-bad" : "mt-3 text-sm text-muted"}>
{check.free_bytes < check.needed_bytes + 512 * 1024 * 1024
? t("client.dl.notEnough", { need: formatBytes(check.needed_bytes), free: formatBytes(check.free_bytes) })
: t("client.dl.free", { free: formatBytes(check.free_bytes) })}
</p>
<div className="mt-5 flex justify-end gap-2">
<Button variant="ghost" onClick={() => void pickParent()}>{t("client.dl.otherFolder")}</Button>
<Button variant="primary" disabled={check.free_bytes < check.needed_bytes + 512 * 1024 * 1024} onClick={() => void startDownload()}>
{t("client.dl.start")}
</Button>
</div>
</>
)}
{(phase === "scanning" || phase === "working") && (
<div className="mt-4" role="status">
<div className="flex items-center gap-2 text-sm">
<Loader2 className="h-4 w-4 animate-spin text-gold" aria-hidden />
<span>{phase === "scanning" || step?.phase === "scan" ? t("client.dl.scanning") : t("client.dl.downloading")}</span>
<span className="ml-auto text-muted">{pct}%</span>
</div>
<div className="mt-2 h-2 overflow-hidden rounded-full bg-white/10" role="progressbar" aria-valuenow={pct} aria-valuemin={0} aria-valuemax={100}>
<div className="h-full rounded-full bg-gold transition-[width] duration-300" style={{ width: `${pct}%` }} />
</div>
<div className="mt-2 flex justify-between gap-4 text-xs text-muted">
<span className="min-w-0 truncate">{step?.file ?? ""}</span>
<span className="shrink-0">
{step ? t("client.dl.progress", { done: formatBytes(step.done), total: formatBytes(step.total) }) : ""}
{step && step.phase === "download" && step.bytes_per_sec > 0 ? ` · ${t("client.dl.speed", { speed: formatBytes(step.bytes_per_sec) })}` : ""}
</span>
</div>
<div className="mt-5 flex justify-end">
<Button variant="ghost" onClick={stop}>{t("client.dl.cancel")}</Button>
</div>
</div>
)}
{phase === "preview" && plan && (
<>
{plan.items.length === 0 ? (
<p className="mt-2 text-sm">{t("client.upd.upToDate", { v: plan.version })}</p>
) : (
<>
{mode === "update" && <p className="mt-2 text-sm">{t("client.upd.available", { v: plan.version })}</p>}
<p className="mt-1 text-sm text-muted">{t("client.upd.summary", { n: plan.items.length, size: formatBytes(plan.download_bytes) })}</p>
</>
)}
{mode === "track" && <p className="mt-3 text-sm text-muted">{t("client.track.text")}</p>}
{modified.length > 0 && (
<div className="mt-4 rounded-md border border-warn/40 bg-warn/5 p-3 text-sm">
<p className="font-medium">{t("client.upd.modifiedTitle", { n: modified.length })}</p>
<p className="mt-1 text-muted">{t("client.upd.modifiedText")}</p>
<ul className="selectable mt-2 space-y-0.5 text-xs text-muted">
{modified.slice(0, 8).map((i) => (
<li key={i.path} className="truncate">{i.path}</li>
))}
{modified.length > 8 && <li>{t("client.upd.more", { n: modified.length - 8 })}</li>}
</ul>
<label className="mt-3 flex cursor-pointer items-center gap-2">
<input type="checkbox" checked={keep} onChange={(e) => setKeep(e.target.checked)} className="h-4 w-4 accent-[#c9a24a]" />
<span>{t("client.upd.keep")}</span>
</label>
</div>
)}
<div className="mt-5 flex flex-wrap justify-end gap-2">
{mode === "update" && props.onPlayAnyway && (
<Button variant="ghost" onClick={() => { close(); props.onPlayAnyway?.(); }}>{t("client.upd.playAnyway")}</Button>
)}
<Button variant="ghost" onClick={close}>{t("client.upd.later")}</Button>
<Button variant="primary" onClick={() => void startSync()}>
{mode === "track" ? (plan.items.length === 0 ? t("client.track.start") : t("client.track.startUpdate")) : t("client.upd.start")}
</Button>
</div>
</>
)}
{phase === "done" && (
<>
<div className="mt-4 flex items-center gap-3">
<span className="flex h-9 w-9 items-center justify-center rounded-full bg-ok/15 text-ok"><Check className="h-5 w-5" aria-hidden /></span>
<div>
<p className="font-medium">{mode === "setup" ? t("client.dl.done") : t("client.upd.done")}</p>
<p className="text-sm text-muted">{mode === "setup" ? t("client.dl.doneText") : t("client.upd.doneText")}</p>
</div>
</div>
<div className="mt-5 flex justify-end">
<Button variant="primary" onClick={close}>{t("btn.close")}</Button>
</div>
</>
)}
{phase === "stopped" && (
<>
<p className="mt-3 text-sm text-muted">{t("client.dl.cancelled")}</p>
<div className="mt-5 flex justify-end gap-2">
<Button variant="ghost" onClick={close}>{t("btn.close")}</Button>
{mode === "setup" ? (
parent && <Button variant="primary" onClick={() => void startDownload()}>{t("client.dl.resume")}</Button>
) : (
<Button variant="primary" onClick={() => void startPlan()}>{t("client.dl.resume")}</Button>
)}
</div>
</>
)}
{phase === "failed" && error && (
<>
<p className="mt-3 text-sm text-bad" role="alert">{error.human.code === "unknown" ? error.technical : human(error.human).message}</p>
<div className="mt-5 flex justify-end gap-2">
<Button variant="ghost" onClick={close}>{t("btn.close")}</Button>
{mode === "setup" ? <Button onClick={() => { setError(null); setPhase("choose"); }}>{t("client.dl.back")}</Button> : <Button onClick={() => void startPlan()}>{t("client.dl.retry")}</Button>}
</div>
</>
)}
</Card>
</div>
);
}
+28 -3
View File
@@ -4,6 +4,8 @@ import { api, asUiError, type ClientInfo, type Human, type Performance, type Pop
import { cn, formatUptime } from "@/lib/utils";
import { useHuman, useT } from "@/i18n";
import { applyServerUpdate, useServerUpdate } from "@/lib/serverUpdate";
import { checkClient, useClientStatus } from "@/lib/clientUpdate";
import { ClientDialog, type ClientDialogMode } from "@/screens/ClientDialog";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
@@ -67,7 +69,9 @@ export function Overview({ server, onForget, onOpenUpdates }: { server: ServerSu
const [failure, setFailure] = useState<Failure | null>(null);
const [showDetails, setShowDetails] = useState(false);
const [pop, setPop] = useState<Population | null>(null);
const [client, setClient] = useState<ClientInfo | null>(null);
const [client, setClient] = useState<ClientInfo | null | undefined>(undefined);
const [dialog, setDialog] = useState<ClientDialogMode | null>(null);
const clientStatus = useClientStatus(server.id).status;
const [playing, setPlaying] = useState(false);
const [perf, setPerf] = useState<Performance | null>(null);
const upd = useServerUpdate(server.id);
@@ -272,12 +276,20 @@ export function Overview({ server, onForget, onOpenUpdates }: { server: ServerSu
{t("btn.stopSmall")}
</Button>
)}
{client && (
{client && clientStatus?.update_available ? (
<Button variant="primary" size="xl" disabled={playing} onClick={() => setDialog("update")} className="ml-auto min-w-40">
{t("btn.updateClient")}
</Button>
) : client ? (
<Button variant={running ? "primary" : "secondary"} size="xl" disabled={transitioning || playing} onClick={() => void play()} className="ml-auto min-w-40">
{playing && <Loader2 className="h-5 w-5 animate-spin" aria-hidden />}
{running ? t("btn.play") : t("btn.startPlay")}
</Button>
)}
) : client === null ? (
<Button variant="secondary" size="xl" onClick={() => setDialog("setup")} className="ml-auto min-w-40">
{t("btn.setupClient")}
</Button>
) : null}
</div>
{anyUp && !running && !transitioning && (
<p className="mt-3 text-sm text-muted">{t("overview.partial")}</p>
@@ -330,6 +342,19 @@ export function Overview({ server, onForget, onOpenUpdates }: { server: ServerSu
)}
</Card>
)}
{dialog && (
<ClientDialog
serverId={server.id}
mode={dialog}
onClose={() => setDialog(null)}
onChanged={() => {
void api.clientInfo(server.id).then(setClient).catch(() => setClient(null));
void checkClient(server.id);
}}
onPlayAnyway={() => void play()}
/>
)}
</div>
);
}
+10 -2
View File
@@ -14,6 +14,7 @@ import { FriendsPage } from "@/screens/FriendsPage";
import { ConsolePage } from "@/screens/ConsolePage";
import { Button } from "@/components/ui/button";
import { startServerUpdatePolling, useServerUpdate } from "@/lib/serverUpdate";
import { startClientPolling } from "@/lib/clientUpdate";
type Page = "overview" | "bots" | "server" | "players" | "friends" | "backups" | "console" | "settings";
@@ -41,8 +42,15 @@ export function Shell(props: {
const current = NAV.find((n) => n.id === page)!;
const update = useServerUpdate(props.activeId);
// Look for a server update when the app starts and then every five minutes.
useEffect(() => startServerUpdatePolling(props.activeId), [props.activeId]);
// Look for a server and a game client update when the app starts and then every five minutes.
useEffect(() => {
const stopServer = startServerUpdatePolling(props.activeId);
const stopClient = startClientPolling(props.activeId);
return () => {
stopServer();
stopClient();
};
}, [props.activeId]);
return (
<div className="flex h-full">