diff --git a/crates/coa-core/src/portable/service/engine.rs b/crates/coa-core/src/portable/service/engine.rs index 1c95a6d..a17a5ca 100644 --- a/crates/coa-core/src/portable/service/engine.rs +++ b/crates/coa-core/src/portable/service/engine.rs @@ -36,7 +36,7 @@ use super::super::compat::{self, CompatibilityReport, Inputs, Operation, Outcome use super::super::error::PortableError; use super::super::extension::ExtensionRegistry; use super::super::ids::{CharacterId, SessionId}; -use super::super::projection::{Decision, Oracle, SuppliedDecision}; +use super::super::projection::{Decision, Oracle, ProgressionPin, SuppliedDecision}; use super::super::realm::knowledge::RealmKnowledge; use super::super::realm::online::import_character_online_on; use super::super::realm::profile::{probe_capabilities, with_remembered_progression}; @@ -441,7 +441,7 @@ impl PortableService { // ---- views -------------------------------------------------------------------------------------------------------------------- - fn realm_view(&self, id: &str) -> Res { + pub fn realm_view(&self, id: &str) -> Res { let a = self.access(id)?; let o = self.obs.get(id); let caps = o.and_then(|o| o.caps.as_ref()); @@ -494,7 +494,7 @@ impl PortableService { } } else if behind || stale { PlayStatus::UpdateRequired - } else if let Some(Verdict::Degraded) = self.verdicts.get(&(character, realm_id.to_string())) { + } else if projected.is_some() || self.verdicts.get(&(character, realm_id.to_string())) == Some(&Verdict::Degraded) { PlayStatus::CompatWarning } else { PlayStatus::Ready @@ -510,7 +510,7 @@ impl PortableService { for m in self.host.server_mappings(c.character_id).unwrap_or_default() { let Some(realm) = self.realms.iter().find(|r| r.id == m.server_id) else { continue }; let (status, behind, projected_level, rev, at) = self.copy_status(c.character_id, c.revision, &m.server_id); - let degraded = self.verdicts.get(&(c.character_id, m.server_id.clone())) == Some(&Verdict::Degraded); + let degraded = projected_level.is_some() || self.verdicts.get(&(c.character_id, m.server_id.clone())) == Some(&Verdict::Degraded); copies.push(CopyView { realm_id: m.server_id.clone(), realm_name: realm.name.clone(), status, synced_revision: rev, behind, projected_level, degraded, updated_at: at }); } let active = copies.iter().find(|x| matches!(x.status, PlayStatus::Playing | PlayStatus::Saving | PlayStatus::WaitingLogin | PlayStatus::Syncing)).cloned(); @@ -900,6 +900,13 @@ impl PortableService { let _ = self.host.detach_realm_copy(made.character_id, realm_id); return Err(e.into()); } + if let Ok(mut ra) = access.ra() { + if let Ok(caps) = self.capabilities(&access, &db, &mut ra, true) { + if let Some(p) = &caps.progression { + let _ = self.host.set_mapping_pin(made.character_id, realm_id, Some(&ProgressionPin::native(p, &caps.content_profile_hash))); + } + } + } self.publish(); self.state().characters.into_iter().find(|c| c.id == made.character_id.to_string()).ok_or_else(|| fail("other", "The character was not registered.")) } @@ -954,7 +961,7 @@ impl PortableService { .owner .list_revisions(cid)? .into_iter() - .map(|r| HistoryEntry { revision: r.revision, at: r.created_at, source_realm: names.get(r.source_server_id.as_str()).map(|n| n.to_string()).unwrap_or(r.source_server_id), note: r.note }) + .map(|r| HistoryEntry { revision: r.revision, at: r.created_at, source_realm: names.get(r.source_server_id.as_str()).map(|n| n.to_string()).unwrap_or(r.source_server_id), kind: HistoryKind::of(r.note.as_deref()) }) .collect(); out.sort_by(|a, b| b.revision.cmp(&a.revision)); Ok(out) @@ -1003,6 +1010,12 @@ impl PortableService { DiagnosticsReport { generated_at: now_text(), manager_version: env!("CARGO_PKG_VERSION").to_string(), realms, characters, errors: self.errors.iter().cloned().collect() } } + /// What the interface needs to start the game for a realm: the installation id (when this Manager runs the server) and the address. + pub fn realm_launch_info(&self, realm_id: &str) -> Res<(Option, String)> { + let a = self.access(realm_id)?; + Ok((a.install_id.clone(), a.address.clone())) + } + pub fn saved(&self, character: &str, realm_id: &str) -> Option<(u64, String)> { let cid: CharacterId = character.parse().ok()?; self.saved.get(&(cid, realm_id.to_string())).map(|s| (s.revision, s.at.clone())) diff --git a/crates/coa-core/src/portable/service/live_service.rs b/crates/coa-core/src/portable/service/live_service.rs index ffa67eb..f6d62d3 100644 --- a/crates/coa-core/src/portable/service/live_service.rs +++ b/crates/coa-core/src/portable/service/live_service.rs @@ -166,6 +166,30 @@ fn one_click_play_of_a_level_eighty_on_a_cap_sixty_realm_survives_navigation_a_r let _ = (name, server); } +#[test] +#[ignore] +fn a_character_made_portable_on_a_running_realm_is_armed_on_it_without_a_restart() { + let (Some(r), Some(sp), Some(jobs)) = (realms(), spec(), job_dir()) else { return }; + reset_b(&r.b); + std::fs::create_dir_all(&jobs).unwrap(); + let dir = tempfile::tempdir().unwrap(); + let file = descriptor(dir.path()); + let mut svc = PortableService::open(&dir.path().join("portable"), vec![]).unwrap(); + svc.add_prepared_realm(&file).unwrap(); + let server = Server::start(sp); + svc.tick(); + svc.tick(); + + let local = svc.local_characters(REALM).unwrap(); + let pick = local.iter().find(|c| c.eligible).expect("an eligible character on the realm"); + let made = svc.make_portable(REALM, pick.token).unwrap(); + let pre = svc.preflight(&made.id, REALM).unwrap(); + assert_eq!(pre.step, Step::Arm, "the realm's own character is current: nothing to update, nothing to restart; {:?}", pre.notes); + svc.play(&made.id, REALM, None).unwrap(); + assert_eq!(status(&svc), PlayStatus::WaitingLogin); + drop(server); +} + fn name_of_account(db: &crate::db::Db, id: u32) -> String { sql(db, &format!("SELECT username FROM acore_auth.account WHERE id = {id}")).trim().to_string() } diff --git a/crates/coa-core/src/portable/service/view.rs b/crates/coa-core/src/portable/service/view.rs index 9a1538b..0d433dc 100644 --- a/crates/coa-core/src/portable/service/view.rs +++ b/crates/coa-core/src/portable/service/view.rs @@ -149,7 +149,41 @@ pub struct HistoryEntry { pub revision: u64, pub at: String, pub source_realm: String, - pub note: Option, + pub kind: HistoryKind, +} + +/// What a saved version came from, in words a player understands; internal session and checkpoint identifiers never leave the service. +#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum HistoryKind { + Created, + Play, + Other, +} + +impl HistoryKind { + pub fn of(note: Option<&str>) -> Self { + match note { + Some("created") => Self::Created, + Some(n) if n.starts_with("session ") => Self::Play, + _ => Self::Other, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn history_notes_become_kinds_without_identifiers() { + assert_eq!(HistoryKind::of(Some("created")), HistoryKind::Created); + assert_eq!(HistoryKind::of(Some("session 01a11638-9ccf-7111-b5e9-124d1ecf84bb checkpoint 3")), HistoryKind::Play); + assert_eq!(HistoryKind::of(Some("re-export")), HistoryKind::Other); + assert_eq!(HistoryKind::of(None), HistoryKind::Other); + let json = serde_json::to_string(&HistoryEntry { revision: 2, at: "t".into(), source_realm: "r".into(), kind: HistoryKind::of(Some("session 01a11638-9ccf-7111-b5e9-124d1ecf84bb checkpoint 3")) }).unwrap(); + assert!(!json.contains("01a1") && !json.contains("checkpoint"), "{json}"); + } } #[derive(Debug, Clone, Serialize, PartialEq, Eq)] diff --git a/docs/PORTABLE_PLAYER_MODE.md b/docs/PORTABLE_PLAYER_MODE.md new file mode 100644 index 0000000..ba94818 --- /dev/null +++ b/docs/PORTABLE_PLAYER_MODE.md @@ -0,0 +1,106 @@ +# Portable characters in the Manager (Phase 9): Player Mode flow, service, runtime, diagnostics + +Integrates the proven engines (store, import/update/reconcile, sessions, level-cap projection) into the application without changing them. Local machine / LAN only: no +Registry, Relay or public browsing, no Wildcard, no personal bank or equipment sets. Rust is authoritative; the screen observes state and asks for high-level operations. + +## 1. What the player does + +Welcome -> *Connect to another server* -> **Characters**. Nothing here needs a local server. + +1. **Realms** lists the realms the Manager knows: the servers it installed itself (*installed*) and realms added from a descriptor file (*prepared*, section 4). +2. **Make an existing character portable** reads a character that is *not in the game* from a realm's database and registers it. The Manager keeps a trusted copy + (the *canonical* character) and remembers which realm it came from. The realm's own character is not touched. +3. **Play on realm...** shows the compatibility check first (section 3), then **Play**. One click prepares everything: the character is put on the realm if it is not there + (an update if it is behind), the session is armed, and the screen says *Ready. Start the game and log in with this character*. **Start the game** launches the linked client. +4. While playing, the Manager checkpoints in the background; on logout it saves the final state. The card shows the resulting saved version and when it was saved. +5. **Saved versions** lists the canonical history in words ("Progress saved while playing on ", "Saved from "). + +The player never sees a local GUID, a character or session UUID, a projection manifest, a progression pin, an RA command, a job file, a baseline command or a checkpoint number. +Technical detail is available under *Technical details* of an error and in the diagnostics report. + +### States + +| State | Meaning | +|---|---| +| Ready | The realm's copy is current; nothing is running | +| Preparing character | Play was pressed; the import / update / arm is in progress | +| Waiting for game login | The session is armed; the next login with this character is tracked | +| Playing / Syncing | A session is open; Syncing while checkpoints are in flight | +| Saving progress | The character left the game; the final state is being saved | +| Offline | The realm (or its database) is not reachable | +| Compatibility warning | The realm plays the character with limits (see section 3) | +| Update required | The realm's copy is behind and the realm has to be stopped to be updated | +| Conflict requires action | The realm's copy and the saved character both changed (section 5) | +| Incompatible | The realm cannot take the character; nothing was changed | + +## 2. Layers + +``` +React (PortablePage, usePortable) observes PortableState every ~1.2 s, calls portable_* commands +Tauri commands (src-tauri/src/lib.rs) portable_state / preflight / play / make / resolve / history / add_realm / remove_realm / diagnostics / launch +PortableRuntime (service/runtime.rs) worker thread; 1 s tick; installs refreshed every 5 s; publishes a state snapshot; call() runs one action on the thread +PortableService (service/engine.rs) synchronous orchestration over Owner store, Host store, realm access, ServerControl +service/access.rs RealmAccess: how to reach a realm (installed from the registry, prepared from a descriptor) +service/view.rs everything the UI sees; no identifiers of the engines +engines unchanged: store, realm::{import,update,reconcile,project}, session::{Owner,Host,LiveBridge}, projection +``` + +* The runtime is started with the application (`start_portable`) and stopped on `RunEvent::Exit`; it is independent of the screen, so navigating away changes nothing. +* The Owner and Host stores live under `/portable/{owner,host}`. A restart resumes sessions, the outbox and the progression pins from them; `HostMemory` keeps the + Host's in-memory throttling between ticks. The first tick after a restart checkpoints at once. +* One operation at a time (`busy`); status derivation is a pure function of stores + observations (`copy_status`). +* `COA_MANAGER_DATA_DIR` overrides the data folder (development and tests only). + +## 3. Compatibility before anything is written + +`preflight(character, realm)` reads the realm (capabilities, cap, running state) and evaluates the Phase 7 report for the operations that Play would do. It writes nothing. + +| Verdict | Play | Shown | +|---|---|---| +| Compatible | yes | "The character is already on this realm and up to date" / "The Manager will put the character on this realm" | +| Degraded | yes | what stays safely in the canonical character; for a level cap: "This realm has level cap 60. Your level-80 character will play here as level 60. Your full level-80 progression is preserved." | +| Incompatible | no, refused before any mutation | the reasons | + +The next step is `Prepare` (not on the realm), `Arm` (on the realm and current), `Resume` (a session is already armed or open), `Restart` (behind, or the realm's progression +changed: the realm has to be stopped), `Resolve` (conflict), `Offline`, `Blocked`. The projection itself is decided by the core and applied by the Manager exactly as in Phase 8; +there is no manual projection step. After `make portable` the Manager records the realm's *native* progression pin for the copy, so the realm's own character is current +and Play needs no restart. + +## 4. Realms + +* **Installed** (a server this Manager runs): derived from the registry/repack settings; id `srv-`; the Manager can stop and start it, so an *update* of the + realm's copy is done automatically (`ServerControl`: stop, database up, update with the next session armed in the same transaction, start). +* **Prepared** (somebody else's / a development realm): a JSON descriptor, schema 1, `deny_unknown_fields`, in `/portable/realms/.json` (added with *Add realm file...*). + +```json +{ "schema": 1, "id": "friends-realm", "name": "Friends' realm", "address": "192.168.1.20", + "mysql_bin": "C:/path/to/mysql/bin", "db_port": 3306, "db_user": "...", "db_password": "...", + "ra_port": 3443, "ra_user": "...", "ra_password": "...", + "job_dir": "C:/path/to/realm/job-dir", "data_dir": "C:/path/to/realm/Data", "game_server_users": ["acore"] } +``` + +The descriptor holds credentials; it is trusted-local (same machine / LAN) material, never printed (`Redacted`), never part of diagnostics. An *update* of a prepared realm's copy is +not automated (the Manager cannot stop it): Play says *Update required* and the realm's owner restarts it. + +## 5. Conflicts + +If the realm's copy changed outside the Manager while the saved character also moved, `preview_update` reports the conflicting fields and the card shows *Conflict requires action*. +There is no automatic merge. Allowed answers: **Use the saved character** (installed realms; the realm's copy is overwritten with the canonical one, in a stopped-realm update), +**Detach the realm copy** (the Manager stops managing it; the realm's character is left exactly as it is), **Cancel**. + +## 6. Diagnostics + +*Copy diagnostics* produces a redacted JSON report: Manager version, per realm: id, kind, online, capability profile hash, core commit, level cap, progression signature, session +protocol; per character: id, canonical revision; per copy: realm, synced revision, session id and state, last checkpoint, progression pin, projected flag, compatibility result; +the recent errors. No credentials, no snapshots, no inventory. + +## 7. Verification + +* Unit tests: descriptor round trip / refusals / secrets never printed, installed realm derivation, history notes never expose identifiers. +* Live (`#[ignore]`d, real worldserver, real disposable databases, a bot standing in for the game client): + `service::live_service::one_click_play_of_a_level_eighty_on_a_cap_sixty_realm_survives_navigation_a_restart_and_the_logout` (offline refusal, preflight, one-click Play with + projection 80 -> 60, Host restart mid-session, final sync, history, diagnostics redaction, incompatible realm blocked with nothing written) and + `a_character_made_portable_on_a_running_realm_is_armed_on_it_without_a_restart`. +* The Tauri window was driven over WebView2's DevTools protocol on a fresh data folder: add descriptors, make portable, preflight with the projection warning, Play, status chips, + navigation away and back, a Manager restart in the middle of a session, logout and the saved version, history wording. +* Not covered by automation: the real game client (needs the owner's run, see the report). diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 874169e..d17defa 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -3,7 +3,7 @@ use std::collections::HashSet; use std::path::PathBuf; -use std::sync::Mutex; +use std::sync::{Arc, Mutex}; use coa_core::backup::{self, Kind, RecoveryPoint, Trigger, VerifyReport}; use coa_core::config::{self, Scope, SettingsView}; @@ -15,12 +15,13 @@ use coa_core::update::{self, Resolution}; use coa_core::error::UiError; use coa_core::layout::{self, Classification, ScanReport}; use coa_core::process::{self, Observed}; +use coa_core::portable::service::{self as portable_service, PortableRuntime, ServiceError}; use coa_core::registry::{metadata_dir_for, InstallKind, InstallMeta, MetaDir, Registry}; use coa_core::{Error, Result}; use serde::Serialize; use serde_json::Value; use std::collections::BTreeMap; -use tauri::{AppHandle, Emitter, State}; +use tauri::{AppHandle, Emitter, Manager, State}; struct AppState { registry: Registry, @@ -30,8 +31,113 @@ struct AppState { install_cancel: Mutex>, /// Cancel handle of the game-client check or download currently running, if any. client_cancel: Mutex>, + /// The portable play runtime (the Host loop): started with the application, stopped with it. + portable: Option>, } +/// Starting and stopping the servers this Manager installed, for the portable runtime. +struct InstallControl { + registry: Registry, +} + +impl InstallControl { + fn run(&self, install_id: &str, verb: Verb) -> Result<()> { + let root = self.registry.list()?.into_iter().find(|(i, _)| i == install_id).map(|(_, p)| p).ok_or_else(|| Error::UnknownInstallation(install_id.to_string()))?; + let out = driver::run(&root, verb)?; + if out.ok { Ok(()) } else { Err(Error::Invalid(out.output.lines().last().unwrap_or("The server did not answer.").to_string())) } + } +} + +impl portable_service::ServerControl for InstallControl { + fn stop_all(&self, install_id: &str) -> Result<()> { self.run(install_id, Verb::StopAll) } + fn start_database(&self, install_id: &str) -> Result<()> { self.run(install_id, Verb::StartMysql) } + fn start_all(&self, install_id: &str) -> Result<()> { self.run(install_id, Verb::StartAll) } +} + +fn runtime(state: &State<'_, AppState>) -> std::result::Result, ServiceError> { + state.portable.clone().ok_or_else(|| ServiceError { code: "stopped".into(), message: "The portable play service could not start; see the Manager's log.".into(), notes: vec![] }) +} + +/// Run one action of the portable play service on its own thread without blocking the interface. +async fn portable_call(state: &State<'_, AppState>, f: impl FnOnce(&mut portable_service::PortableService) -> std::result::Result + Send + 'static) -> std::result::Result { + let rt = runtime(state)?; + tauri::async_runtime::spawn_blocking(move || rt.call(f)) + .await + .map_err(|e| ServiceError { code: "other".into(), message: e.to_string(), notes: vec![] })? + .and_then(|r| r) +} + +#[tauri::command] +fn portable_state(state: State<'_, AppState>) -> portable_service::PortableState { + state.portable.as_ref().map(|r| r.state()).unwrap_or_default() +} + +#[tauri::command] +async fn portable_preflight(state: State<'_, AppState>, character: String, realm: String) -> std::result::Result { + portable_call(&state, move |s| s.preflight(&character, &realm)).await +} + +#[tauri::command] +async fn portable_play(state: State<'_, AppState>, character: String, realm: String, account: Option) -> std::result::Result { + portable_call(&state, move |s| s.play(&character, &realm, account.as_deref())).await +} + +#[tauri::command] +async fn portable_local_characters(state: State<'_, AppState>, realm: String) -> std::result::Result, ServiceError> { + portable_call(&state, move |s| s.local_characters(&realm)).await +} + +#[tauri::command] +async fn portable_make(state: State<'_, AppState>, realm: String, token: u32) -> std::result::Result { + portable_call(&state, move |s| s.make_portable(&realm, token)).await +} + +#[tauri::command] +async fn portable_resolve(state: State<'_, AppState>, character: String, realm: String, action: portable_service::Resolve) -> std::result::Result<(), ServiceError> { + portable_call(&state, move |s| s.resolve(&character, &realm, action)).await +} + +#[tauri::command] +async fn portable_history(state: State<'_, AppState>, character: String) -> std::result::Result, ServiceError> { + portable_call(&state, move |s| s.history(&character)).await +} + +#[tauri::command] +async fn portable_add_realm(state: State<'_, AppState>, path: String) -> std::result::Result { + portable_call(&state, move |s| s.add_prepared_realm(std::path::Path::new(&path))).await +} + +#[tauri::command] +async fn portable_remove_realm(state: State<'_, AppState>, realm: String) -> std::result::Result<(), ServiceError> { + portable_call(&state, move |s| s.remove_prepared_realm(&realm)).await +} + +#[tauri::command] +async fn portable_diagnostics(state: State<'_, AppState>) -> std::result::Result { + portable_call(&state, |s| Ok(s.diagnostics())).await +} + +/// Start the game for a realm that is ready: an installed server uses its own client, any other realm the Player Mode client pointed at +/// the realm's address. +#[tauri::command] +async fn portable_launch(state: State<'_, AppState>, realm: String) -> std::result::Result<(), ServiceError> { + let (install, address) = portable_call(&state, move |s| s.realm_launch_info(&realm)).await?; + let other = |e: UiError| ServiceError { code: "launch".into(), message: e.technical, notes: vec![] }; + match install { + Some(id) => play(state, id).await.map(|_| ()).map_err(other), + None => { + { + let dir = remote_dir(); + let mut profile = coa_core::remote_client::load(&dir).map_err(|e| other(e.into()))?; + profile.host = address; + coa_core::remote_client::save(&dir, &profile).map_err(|e| other(e.into()))?; + } + play(state, REMOTE_CLIENT_ID.to_string()).await.map(|_| ()).map_err(other) + } + } +} + + /// Where official server packages are published (created by the release pipeline, Phase 6). /// Where signed update packages are published; override with COA_UPDATE_SOURCE (URL or local package folder). const DEFAULT_UPDATE_URL: &str = "https://github.com/Corfirean/coa-server-build/releases/download/stable"; @@ -72,6 +178,10 @@ struct StatusView { /// Where the Manager keeps its own state (server list, logs). `%LOCALAPPDATA%` on Windows, the XDG data folder elsewhere. fn data_dir() -> PathBuf { + // a separate data folder for tests and diagnostics, so that a development build never reads or writes the installed Manager's own state + if let Some(dir) = std::env::var_os("COA_MANAGER_DATA_DIR").map(PathBuf::from).filter(|p| p.is_absolute()) { + return dir; + } #[cfg(windows)] let base = std::env::var_os("LOCALAPPDATA").map(PathBuf::from).unwrap_or_else(std::env::temp_dir); #[cfg(not(windows))] @@ -1519,7 +1629,7 @@ pub fn run() { .plugin(tauri_plugin_dialog::init()) .plugin(tauri_plugin_updater::Builder::new().build()) .plugin(tauri_plugin_process::init()) - .manage(AppState { registry: Registry::at(dir.join("installs.json")), busy: Mutex::new(HashSet::new()), install_cancel: Mutex::new(None), client_cancel: Mutex::new(None) }) + .manage(AppState { registry: Registry::at(dir.join("installs.json")), busy: Mutex::new(HashSet::new()), install_cancel: Mutex::new(None), client_cancel: Mutex::new(None), portable: start_portable(&dir) }) .invoke_handler(tauri::generate_handler![ default_install_dir, scan_server, @@ -1603,10 +1713,42 @@ pub fn run() { export_diagnostics, console_tail, console_risk, - console_command + console_command, + portable_state, + portable_preflight, + portable_play, + portable_local_characters, + portable_make, + portable_resolve, + portable_history, + portable_add_realm, + portable_remove_realm, + portable_diagnostics, + portable_launch ]) - .run(tauri::generate_context!()) - .expect("error while running CoA Server Manager"); + .build(tauri::generate_context!()) + .expect("error while building CoA Server Manager") + .run(|app, event| { + // the Host loop stops with the application: what it is doing is finished first, the stores keep every session + if let tauri::RunEvent::Exit = event { + if let Some(rt) = app.state::().portable.clone() { + rt.shutdown(); + } + } + }); +} + +fn start_portable(dir: &std::path::Path) -> Option> { + let registry = Registry::at(dir.join("installs.json")); + let control = InstallControl { registry: Registry::at(dir.join("installs.json")) }; + let installs: portable_service::runtime::Installs = Box::new(move || registry.list().unwrap_or_default()); + match PortableRuntime::start(&dir.join("portable"), installs, Some(Box::new(control))) { + Ok(rt) => Some(Arc::new(rt)), + Err(e) => { + tracing::error!(error = %e, "the portable play service did not start"); + None + } + } } #[cfg(all(test, not(windows)))] diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index fe566ef..f5e15bd 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -836,6 +836,132 @@ const en = { "upd.current": "You are up to date (version {v}).", "client.job.checking": "Checking the client…", "client.job.updating": "Updating the client", + "nav.characters": "Characters", + "q.characters": "Which of my characters can play where?", + "portable.title": "Characters", + "portable.intro": "Your characters are kept safe by the Manager. Pick a realm and press Play: the Manager prepares the character there and saves your progress when you log out.", + "portable.runtime.stopped": "The part of the Manager that follows your game is not running. Restart the Manager.", + "portable.realms.title": "Realms", + "portable.realms.none": "No realm yet. Add a realm file you were given by the person who runs the server.", + "portable.realm.online": "Running", + "portable.realm.stopped": "Not running", + "portable.realm.unreachable": "Cannot be reached", + "portable.realm.cap": "level cap {cap}", + "portable.realm.setup": "needs a setting before it can follow your game", + "portable.realm.installed": "your server", + "portable.realm.prepared": "added from a file", + "portable.realm.remove": "Remove this realm", + "portable.realm.add": "Add a realm file…", + "portable.realm.fileType": "Realm file", + "portable.characters.title": "Your characters", + "portable.characters.none": "No characters yet. Use “Make an existing character portable” to bring one in from a realm.", + "portable.level": "level {level}", + "portable.revision": "saved version {n}", + "portable.lastSync": "Last saved {when}", + "portable.activeOn": "playing on {realm}", + "portable.copy.projected": "plays here as level {level}", + "portable.copy.synced": "version {n} on this realm", + "portable.play.button": "Play on a realm…", + "portable.play.title": "Play {name}", + "portable.play.realm": "Realm", + "portable.play.checking": "Checking the realm…", + "portable.play.account": "Your game account on this realm", + "portable.play.accountHint": "The account name you log in with. The Manager remembers it.", + "portable.play.go": "Play", + "portable.play.ready": "Ready. Start the game and log in with this character.", + "portable.play.next": "Connect the game to {address}.", + "portable.play.launch": "Launch the game", + "portable.history.button": "Saved versions", + "portable.history.created": "Saved from {realm}", + "portable.history.play": "Progress saved while playing on {realm}", + "portable.history.other": "Saved from {realm}", + "portable.history.title": "Saved versions of {name}", + "portable.make.button": "Make an existing character portable", + "portable.make.title": "Make a character portable", + "portable.make.text": "Pick a character that already exists on a realm. The Manager keeps a safe copy that can play on other realms. The character must be logged out.", + "portable.make.noRealm": "None of your realms can be reached right now.", + "portable.make.loading": "Looking at the realm’s characters…", + "portable.make.none": "Every character of this realm is already portable.", + "portable.make.do": "Make portable", + "portable.make.done": "{name} is now portable.", + "portable.blocker.online": "is logged in", + "portable.blocker.deleted": "is deleted", + "portable.blocker.bot_account": "belongs to a bot account", + "portable.blocker.active_challenge": "a challenge is in progress", + "portable.blocker.active_game_mode": "a game mode such as hardcore is active", + "portable.blocker.active_custom_trial": "a trial is in progress", + "portable.blocker.pending_manastorm_caches": "rewards are waiting to be delivered", + "portable.blocker.unclassified_state": "has data the Manager does not know yet", + "portable.cancel": "Cancel", + "portable.close": "Close", + "portable.details": "Technical details", + "portable.status.ready": "Ready", + "portable.status.syncing": "Syncing", + "portable.status.preparing": "Preparing character", + "portable.status.waiting_login": "Waiting for game login", + "portable.status.playing": "Playing", + "portable.status.saving": "Saving progress", + "portable.status.offline": "Offline", + "portable.status.compat_warning": "Compatibility warning", + "portable.status.update_required": "Update required", + "portable.status.conflict": "Conflict requires action", + "portable.status.incompatible": "Not compatible", + "portable.status.error": "Problem", + "portable.verdict.compatible": "This realm takes your character completely.", + "portable.verdict.degraded": "This realm takes your character with a limit.", + "portable.verdict.incompatible": "This realm cannot take this character.", + "portable.degraded.text": "You can play. What this realm cannot show stays safely stored with your character and comes back on a realm that can.", + "portable.projection.title": "This realm has level cap {cap}.", + "portable.projection.text": "Your level-{from} character will play here as level {to}.", + "portable.projection.safe": "Your full level-{from} progression is preserved.", + "portable.step.prepare": "The Manager will put your character on this realm.", + "portable.step.arm": "Your character is on this realm and up to date.", + "portable.step.resume": "Your character is already prepared on this realm.", + "portable.step.restart": "This realm has to be restarted to receive your latest progress. The Manager does it for you when it runs the server.", + "portable.step.resolve": "The copy on this realm and your saved character both changed. Choose what to keep.", + "portable.step.blocked": "Nothing was changed.", + "portable.step.offline": "The realm is not running. Start it, then try again.", + "portable.resolve.canonical": "Use my saved character", + "portable.resolve.detach": "Detach the realm’s copy", + "portable.resolve.help": "“Use my saved character” replaces the realm’s copy with your saved one. “Detach” leaves the realm’s copy as an ordinary character that the Manager no longer follows.", + "portable.note.held_wardrobe": "{held} appearance(s) this realm cannot show stay stored with your character.", + "portable.note.held_collection": "Some collected items this realm does not know stay stored with your account.", + "portable.note.held_extension": "Data of a module this realm does not have ({namespace}) stays stored with your character.", + "portable.note.unsupported_wardrobe": "This realm cannot show selected appearances; they stay stored.", + "portable.note.unsupported_collection": "This realm does not keep this kind of collection; it stays stored.", + "portable.note.unsupported_extension": "A module’s data cannot be used here; it stays stored.", + "portable.note.blocked_ruleset": "This character is for another kind of realm.", + "portable.note.blocked_format": "This realm reads another version of the character format. Update the Manager or the realm.", + "portable.note.blocked_online_import": "This realm cannot take characters while it runs. Update the realm.", + "portable.note.blocked_sessions": "This realm cannot follow a game session. Ask its owner to enable portable play.", + "portable.note.blocked_client_data": "The game data the Manager sees is not the data the realm loaded.", + "portable.note.blocked_progression": "The realm’s level cap is not known yet or cannot be handled. Start the realm and try again.", + "portable.note.realm_offline": "The realm cannot be reached.", + "portable.note.realm_unknown": "The Manager has not seen this realm running yet.", + "portable.note.conflict": "Both the realm’s copy and your saved character changed.", + "portable.note.unreadable": "The realm’s copy could not be read.", + "portable.note.generic": "{detail}", + "portable.err.realm_offline": "The realm is not running or cannot be reached.", + "portable.err.realm_missing": "That realm is not known.", + "portable.err.character_missing": "That character is not known.", + "portable.err.incompatible": "This realm cannot take this character. Nothing was changed.", + "portable.err.conflict": "The realm’s copy and your saved character both changed.", + "portable.err.update_required": "The realm has to be restarted before it can take your latest progress.", + "portable.err.needs_account": "Enter your game account on this realm.", + "portable.err.account_missing": "The realm has no game account with that name.", + "portable.err.busy": "Another character is being prepared. Wait a moment.", + "portable.err.storage": "The Manager could not use its own storage.", + "portable.err.stopped": "The part of the Manager that follows your game is not running.", + "portable.err.already_on_realm": "This character is already on that realm.", + "portable.err.session_open": "This character is in play on that realm.", + "portable.err.realm_unreadable": "The realm answered in a way the Manager does not understand.", + "portable.err.not_prepared": "Only a realm added from a file can be removed here.", + "portable.err.launch": "The game could not be started. Check the client in Settings.", + "portable.err.other": "Something went wrong. Nothing was lost.", + "portable.diag.title": "Diagnostics", + "portable.diag.text": "A report for a bug report: realms, versions, sessions and recent problems. No passwords and no character data.", + "portable.diag.copy": "Copy diagnostics", + "portable.diag.copied": "Copied.", } as const; export default en; diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts index 5c8b38e..e784be2 100644 --- a/src/i18n/locales/ru.ts +++ b/src/i18n/locales/ru.ts @@ -834,6 +834,132 @@ const ru: Partial> = { "upd.current": "У вас последняя версия ({v}).", "client.job.checking": "Проверка клиента…", "client.job.updating": "Обновление клиента", + "nav.characters": "Персонажи", + "q.characters": "Какие мои персонажи где могут играть?", + "portable.title": "Персонажи", + "portable.intro": "Менеджер хранит ваших персонажей в безопасности. Выберите реалм и нажмите «Играть»: Менеджер сам подготовит персонажа и сохранит прогресс, когда вы выйдете из игры.", + "portable.runtime.stopped": "Часть Менеджера, которая следит за игрой, не работает. Перезапустите Менеджер.", + "portable.realms.title": "Реалмы", + "portable.realms.none": "Реалмов пока нет. Добавьте файл реалма, который вам дал тот, кто держит сервер.", + "portable.realm.online": "Работает", + "portable.realm.stopped": "Не запущен", + "portable.realm.unreachable": "Недоступен", + "portable.realm.cap": "предел уровня {cap}", + "portable.realm.setup": "нужна настройка, чтобы следить за игрой", + "portable.realm.installed": "ваш сервер", + "portable.realm.prepared": "добавлен из файла", + "portable.realm.remove": "Убрать этот реалм", + "portable.realm.add": "Добавить файл реалма…", + "portable.realm.fileType": "Файл реалма", + "portable.characters.title": "Ваши персонажи", + "portable.characters.none": "Персонажей пока нет. Нажмите «Сделать существующего персонажа переносимым», чтобы взять одного с реалма.", + "portable.level": "{level} уровень", + "portable.revision": "сохранённая версия {n}", + "portable.lastSync": "Последнее сохранение: {when}", + "portable.activeOn": "играет на {realm}", + "portable.copy.projected": "здесь играет как {level} уровень", + "portable.copy.synced": "на реалме версия {n}", + "portable.play.button": "Играть на реалме…", + "portable.play.title": "Играть: {name}", + "portable.play.realm": "Реалм", + "portable.play.checking": "Проверяю реалм…", + "portable.play.account": "Ваш игровой аккаунт на этом реалме", + "portable.play.accountHint": "Имя аккаунта, под которым вы входите в игру. Менеджер его запомнит.", + "portable.play.go": "Играть", + "portable.play.ready": "Готово. Запустите игру и войдите этим персонажем.", + "portable.play.next": "Подключите игру к {address}.", + "portable.play.launch": "Запустить игру", + "portable.history.button": "Сохранённые версии", + "portable.history.created": "Сохранён с реалма {realm}", + "portable.history.play": "Прогресс сохранён во время игры на реалме {realm}", + "portable.history.other": "Сохранён с реалма {realm}", + "portable.history.title": "Сохранённые версии: {name}", + "portable.make.button": "Сделать существующего персонажа переносимым", + "portable.make.title": "Сделать персонажа переносимым", + "portable.make.text": "Выберите персонажа, который уже есть на реалме. Менеджер сохранит надёжную копию, которая сможет играть на других реалмах. Персонаж должен быть не в игре.", + "portable.make.noRealm": "Сейчас ни один ваш реалм недоступен.", + "portable.make.loading": "Смотрю персонажей реалма…", + "portable.make.none": "Все персонажи этого реалма уже переносимые.", + "portable.make.do": "Сделать переносимым", + "portable.make.done": "{name} теперь переносимый.", + "portable.blocker.online": "сейчас в игре", + "portable.blocker.deleted": "удалён", + "portable.blocker.bot_account": "принадлежит аккаунту бота", + "portable.blocker.active_challenge": "идёт испытание", + "portable.blocker.active_game_mode": "включён режим вроде хардкора", + "portable.blocker.active_custom_trial": "идёт испытание", + "portable.blocker.pending_manastorm_caches": "ждут доставки награды", + "portable.blocker.unclassified_state": "есть данные, которых Менеджер ещё не знает", + "portable.cancel": "Отмена", + "portable.close": "Закрыть", + "portable.details": "Технические подробности", + "portable.status.ready": "Готов", + "portable.status.syncing": "Синхронизация", + "portable.status.preparing": "Готовлю персонажа", + "portable.status.waiting_login": "Жду входа в игру", + "portable.status.playing": "В игре", + "portable.status.saving": "Сохраняю прогресс", + "portable.status.offline": "Недоступен", + "portable.status.compat_warning": "Есть ограничения", + "portable.status.update_required": "Нужно обновление", + "portable.status.conflict": "Нужно ваше решение", + "portable.status.incompatible": "Не подходит", + "portable.status.error": "Проблема", + "portable.verdict.compatible": "Этот реалм принимает персонажа полностью.", + "portable.verdict.degraded": "Этот реалм принимает персонажа с ограничением.", + "portable.verdict.incompatible": "Этот реалм не может принять этого персонажа.", + "portable.degraded.text": "Играть можно. То, что реалм не может показать, остаётся в сохранности у персонажа и вернётся на реалме, который это умеет.", + "portable.projection.title": "На этом реалме предел уровня — {cap}.", + "portable.projection.text": "Ваш персонаж {from} уровня будет играть здесь как {to} уровня.", + "portable.projection.safe": "Весь прогресс {from} уровня сохраняется.", + "portable.step.prepare": "Менеджер сам поставит персонажа на этот реалм.", + "portable.step.arm": "Персонаж уже на этом реалме и актуален.", + "portable.step.resume": "Персонаж уже подготовлен на этом реалме.", + "portable.step.restart": "Реалм нужно перезапустить, чтобы он получил ваш последний прогресс. Менеджер сделает это сам, если держит этот сервер.", + "portable.step.resolve": "И копия на реалме, и ваш сохранённый персонаж изменились. Выберите, что оставить.", + "portable.step.blocked": "Ничего не изменено.", + "portable.step.offline": "Реалм не запущен. Запустите его и попробуйте снова.", + "portable.resolve.canonical": "Взять мой сохранённый", + "portable.resolve.detach": "Отвязать копию на реалме", + "portable.resolve.help": "«Взять мой сохранённый» заменит копию на реалме вашим сохранённым персонажем. «Отвязать» оставит копию на реалме обычным персонажем, за которым Менеджер больше не следит.", + "portable.note.held_wardrobe": "{held} внешн. вид(ов), которые реалм не умеет показывать, остаются у персонажа.", + "portable.note.held_collection": "Часть коллекций, которых реалм не знает, остаётся у вашего аккаунта.", + "portable.note.held_extension": "Данные модуля, которого нет на реалме ({namespace}), остаются у персонажа.", + "portable.note.unsupported_wardrobe": "Этот реалм не показывает выбранный внешний вид; он остаётся сохранённым.", + "portable.note.unsupported_collection": "Этот реалм не хранит такую коллекцию; она остаётся сохранённой.", + "portable.note.unsupported_extension": "Данные модуля здесь не используются; они остаются сохранёнными.", + "portable.note.blocked_ruleset": "Этот персонаж — для реалма другого типа.", + "portable.note.blocked_format": "Реалм читает другую версию формата персонажа. Обновите Менеджер или реалм.", + "portable.note.blocked_online_import": "Этот реалм не принимает персонажей, пока работает. Обновите реалм.", + "portable.note.blocked_sessions": "Этот реалм не может следить за игровой сессией. Попросите владельца включить переносимую игру.", + "portable.note.blocked_client_data": "Игровые данные, которые видит Менеджер, не те, что загрузил реалм.", + "portable.note.blocked_progression": "Предел уровня реалма пока неизвестен или не поддерживается. Запустите реалм и попробуйте снова.", + "portable.note.realm_offline": "Реалм недоступен.", + "portable.note.realm_unknown": "Менеджер ещё не видел этот реалм запущенным.", + "portable.note.conflict": "Изменились и копия на реалме, и ваш сохранённый персонаж.", + "portable.note.unreadable": "Копию на реалме не удалось прочитать.", + "portable.note.generic": "{detail}", + "portable.err.realm_offline": "Реалм не запущен или недоступен.", + "portable.err.realm_missing": "Такой реалм неизвестен.", + "portable.err.character_missing": "Такой персонаж неизвестен.", + "portable.err.incompatible": "Этот реалм не может принять этого персонажа. Ничего не изменено.", + "portable.err.conflict": "И копия на реалме, и ваш сохранённый персонаж изменились.", + "portable.err.update_required": "Реалм нужно перезапустить, чтобы он принял ваш последний прогресс.", + "portable.err.needs_account": "Введите ваш игровой аккаунт на этом реалме.", + "portable.err.account_missing": "На реалме нет игрового аккаунта с таким именем.", + "portable.err.busy": "Сейчас готовится другой персонаж. Подождите немного.", + "portable.err.storage": "Менеджер не смог использовать собственное хранилище.", + "portable.err.stopped": "Часть Менеджера, которая следит за игрой, не работает.", + "portable.err.already_on_realm": "Этот персонаж уже есть на том реалме.", + "portable.err.session_open": "Этот персонаж сейчас в игре на том реалме.", + "portable.err.realm_unreadable": "Реалм ответил так, что Менеджер не понимает.", + "portable.err.not_prepared": "Здесь можно убрать только реалм, добавленный из файла.", + "portable.err.launch": "Не удалось запустить игру. Проверьте клиент в настройках.", + "portable.err.other": "Что-то пошло не так. Ничего не потеряно.", + "portable.diag.title": "Диагностика", + "portable.diag.text": "Отчёт для сообщения об ошибке: реалмы, версии, сессии и недавние проблемы. Без паролей и без данных персонажей.", + "portable.diag.copy": "Скопировать диагностику", + "portable.diag.copied": "Скопировано.", }; export default ru; diff --git a/src/lib/portable.ts b/src/lib/portable.ts new file mode 100644 index 0000000..e7f7c85 --- /dev/null +++ b/src/lib/portable.ts @@ -0,0 +1,123 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import { invoke } from "@tauri-apps/api/core"; + +export type PlayStatus = + | "ready" | "syncing" | "preparing" | "waiting_login" | "playing" | "saving" | "offline" + | "compat_warning" | "update_required" | "conflict" | "incompatible" | "error"; + +export interface CopyView { + realm_id: string; + realm_name: string; + status: PlayStatus; + synced_revision: number; + behind: boolean; + projected_level: number | null; + degraded: boolean; + updated_at: string; +} + +export interface CharacterView { + id: string; + name: string; + class_name: string; + race: string; + level: number; + revision: number; + updated_at: string; + active_realm: string | null; + status: PlayStatus; + copies: CopyView[]; +} + +export interface RealmView { + id: string; + name: string; + kind: "installed" | "prepared"; + address: string; + online: boolean; + database_ok: boolean; + level_cap: number | null; + portable: "ready" | "setup" | "unknown"; + game_account: string | null; + installed_id: string | null; +} + +export interface Note { code: string; params: Record; detail: string } +export type Verdict = "compatible" | "degraded" | "incompatible"; +export type Step = "prepare" | "arm" | "resume" | "restart" | "resolve" | "blocked" | "offline"; + +export interface PreflightView { + verdict: Verdict; + step: Step; + projection: [number, number] | null; + notes: Note[]; + needs_account: boolean; +} + +export interface PlayView { + status: PlayStatus; + projection: [number, number] | null; + notes: Note[]; + realm_address: string; + realm_id: string; +} + +export interface LocalCharacterView { + token: number; + name: string; + class_name: string; + level: number; + account: string; + eligible: boolean; + reasons: string[]; +} + +export interface HistoryEntry { revision: number; at: string; source_realm: string; kind: "created" | "play" | "other" } +export interface ErrorEntry { at: string; realm: string | null; message: string } + +export interface PortableState { + characters: CharacterView[]; + realms: RealmView[]; + operation: { character_id: string; realm_id: string; status: PlayStatus } | null; + runtime: { running: boolean; last_tick_secs: number | null; sessions_open: number; errors: ErrorEntry[] }; +} + +export interface PortableError { code: string; message: string; notes: Note[] } + +export function asPortableError(e: unknown): PortableError { + if (e && typeof e === "object" && "code" in e && "message" in e) return e as PortableError; + return { code: "other", message: String(e), notes: [] }; +} + +export type Resolve = "use_canonical" | "detach"; + +export const portable = { + state: () => invoke("portable_state"), + preflight: (character: string, realm: string) => invoke("portable_preflight", { character, realm }), + play: (character: string, realm: string, account?: string) => invoke("portable_play", { character, realm, account: account ?? null }), + localCharacters: (realm: string) => invoke("portable_local_characters", { realm }), + make: (realm: string, token: number) => invoke("portable_make", { realm, token }), + resolve: (character: string, realm: string, action: Resolve) => invoke("portable_resolve", { character, realm, action }), + history: (character: string) => invoke("portable_history", { character }), + addRealm: (path: string) => invoke("portable_add_realm", { path }), + removeRealm: (realm: string) => invoke("portable_remove_realm", { realm }), + diagnostics: () => invoke("portable_diagnostics"), + launch: (realm: string) => invoke("portable_launch", { realm }), +}; + +/** The state of portable play, refreshed every second or so for as long as a screen shows it. The service itself runs without the screen. */ +export function usePortable(everyMs = 1200): { state: PortableState | null; refresh: () => Promise } { + const [state, setState] = useState(null); + const busy = useRef(false); + const refresh = useCallback(async () => { + if (busy.current) return; + busy.current = true; + try { setState(await portable.state()); } catch { /* the service is not available; the screen says so */ } finally { busy.current = false; } + }, []); + useEffect(() => { + void refresh(); + const timer = setInterval(() => void refresh(), everyMs); + return () => clearInterval(timer); + }, [refresh, everyMs]); + return { state, refresh }; +} diff --git a/src/screens/PortablePage.tsx b/src/screens/PortablePage.tsx new file mode 100644 index 0000000..3ac5a23 --- /dev/null +++ b/src/screens/PortablePage.tsx @@ -0,0 +1,336 @@ +import { useEffect, useMemo, useState } from "react"; +import { open } from "@tauri-apps/plugin-dialog"; +import { AlertTriangle, CheckCircle2, History, Loader2, Plus, ShieldAlert, Swords, Trash2, X } from "lucide-react"; +import { useT, type Key } from "@/i18n"; +import { Button } from "@/components/ui/button"; +import { Card } from "@/components/ui/card"; +import { cn } from "@/lib/utils"; +import { + asPortableError, portable, usePortable, + type CharacterView, type HistoryEntry, type LocalCharacterView, type Note, type PlayStatus, + type PlayView, type PortableError, type PreflightView, type RealmView, +} from "@/lib/portable"; + +const WORKING: PlayStatus[] = ["preparing", "syncing", "saving"]; +const LIVE: PlayStatus[] = ["playing", "waiting_login", "preparing", "syncing", "saving"]; + +function when(iso: string): string { + const d = new Date(iso); + return Number.isNaN(d.getTime()) ? iso : d.toLocaleString(); +} + +function StatusChip({ status, degraded }: { status: PlayStatus; degraded?: boolean }) { + const t = useT(); + const tone = status === "playing" ? "bg-ok/15 text-ok" + : status === "conflict" || status === "incompatible" || status === "error" ? "bg-bad/15 text-bad" + : status === "update_required" || status === "compat_warning" || status === "offline" ? "bg-warn/15 text-warn" + : WORKING.includes(status) || status === "waiting_login" ? "bg-gold/15 text-gold" + : "bg-white/5 text-muted"; + return + + {WORKING.includes(status) && } + {t(`portable.status.${status}` as Key)} + + {degraded && {t("portable.status.compat_warning")}} + ; +} + +/** The words of one line of the compatibility check. */ +function noteText(t: ReturnType, n: Note): string { + const key = `portable.note.${n.code}` as Key; + const text = t(key, { ...n.params }); + return text === key ? t("portable.note.generic", { detail: n.detail }) : text; +} + +function Notes({ notes }: { notes: Note[] }) { + const t = useT(); + const shown = notes.filter((n) => n.code !== "projection"); + if (!shown.length) return null; + return
    {shown.map((n, i) =>
  • {noteText(t, n)}
  • )}
; +} + +function Projection({ from, to, cap }: { from: number; to: number; cap?: number | null }) { + const t = useT(); + return
+

{t("portable.projection.title", { cap: cap ?? to })}

+

{t("portable.projection.text", { from, to })}

+

{t("portable.projection.safe", { from })}

+
; +} + +function ErrorLine({ error }: { error: PortableError }) { + const t = useT(); + const key = `portable.err.${error.code}` as Key; + const text = t(key); + return
+

{text === key ? t("portable.err.other") : text}

+
{t("portable.details")}

{error.message}

+ +
; +} + +// ---- Play -------------------------------------------------------------------------------------------------------------------- + +function PlayDialog({ character, realms, initial, onClose, onChanged }: { character: CharacterView; realms: RealmView[]; initial: string; onClose: () => void; onChanged: () => void }) { + const t = useT(); + const [realmId, setRealmId] = useState(initial); + const realm = realms.find((r) => r.id === realmId)!; + const [pre, setPre] = useState(null); + const [account, setAccount] = useState(realm.game_account ?? ""); + const [busy, setBusy] = useState(false); + const [done, setDone] = useState(null); + const [error, setError] = useState(null); + const [launching, setLaunching] = useState(false); + + useEffect(() => { + let alive = true; + setPre(null); setError(null); setDone(null); setAccount(realm.game_account ?? ""); + void portable.preflight(character.id, realmId).then((p) => { if (alive) setPre(p); }).catch((e) => { if (alive) setError(asPortableError(e)); }); + return () => { alive = false; }; + }, [character.id, realmId]); // eslint-disable-line react-hooks/exhaustive-deps + + async function play() { + setBusy(true); setError(null); + try { setDone(await portable.play(character.id, realmId, account.trim() || undefined)); onChanged(); } + catch (e) { setError(asPortableError(e)); } + finally { setBusy(false); } + } + async function launch() { + setLaunching(true); setError(null); + try { await portable.launch(realmId); } catch (e) { setError(asPortableError(e)); } finally { setLaunching(false); } + } + async function resolve(action: "use_canonical" | "detach") { + setBusy(true); setError(null); + try { await portable.resolve(character.id, realmId, action); onChanged(); setPre(await portable.preflight(character.id, realmId)); } + catch (e) { setError(asPortableError(e)); } + finally { setBusy(false); } + } + + const blocked = !pre || pre.step === "blocked" || pre.step === "offline" || pre.step === "resolve" || busy; + return
+ +
+

{t("portable.play.title", { name: character.name })}

+ +
+ + + + {!pre && !error &&

{t("portable.play.checking")}

} + {pre && !done && <> +

+ {pre.verdict === "compatible" ? : } + {t(`portable.verdict.${pre.verdict}` as Key)} +

+ {pre.projection && } + {pre.verdict === "degraded" &&

{t("portable.degraded.text")}

} + +

{t(`portable.step.${pre.step}` as Key)}

+ {pre.step === "resolve" &&
+ + + +
} + {pre.step === "resolve" &&

{t("portable.resolve.help")}

} + {(pre.needs_account || realm.game_account === null) && pre.step === "prepare" &&
+ +

{t("portable.play.accountHint")}

+ setAccount(e.target.value)} disabled={busy} className="mt-1 w-full rounded-md border border-line bg-card px-3 py-2" autoComplete="off" /> +
} + } + {done &&
+

{t("portable.play.ready")}

+ {done.projection && } + +

{t("portable.play.next", { address: done.realm_address })}

+
} + {error && } +
+ + {!done && } + {done && } +
+
+
; +} + +// ---- Make portable ------------------------------------------------------------------------------------------------------------ + +function MakeDialog({ realms, onClose, onChanged }: { realms: RealmView[]; onClose: () => void; onChanged: () => void }) { + const t = useT(); + const usable = realms.filter((r) => r.database_ok); + const [realmId, setRealmId] = useState(usable[0]?.id ?? ""); + const [list, setList] = useState(null); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(null); + const [made, setMade] = useState(null); + useEffect(() => { + if (!realmId) return; + let alive = true; + setList(null); setError(null); + void portable.localCharacters(realmId).then((l) => { if (alive) setList(l); }).catch((e) => { if (alive) setError(asPortableError(e)); }); + return () => { alive = false; }; + }, [realmId]); + async function make(c: LocalCharacterView) { + setBusy(c.token); setError(null); + try { const v = await portable.make(realmId, c.token); setMade(v.name); onChanged(); setList((l) => l?.filter((x) => x.token !== c.token) ?? null); } + catch (e) { setError(asPortableError(e)); } finally { setBusy(null); } + } + return
+ +
+

{t("portable.make.title")}

+ +
+

{t("portable.make.text")}

+ {usable.length === 0 ?

{t("portable.make.noRealm")}

: <> + + + {!list && !error &&

{t("portable.make.loading")}

} + {list && list.length === 0 &&

{t("portable.make.none")}

} + {list && list.length > 0 &&
    + {list.map((c) =>
  • +

    {c.name}

    {c.class_name} · {t("portable.level", { level: c.level })}{c.account ? ` · ${c.account}` : ""}

    + {!c.eligible &&

    {c.reasons.map((r) => t(`portable.blocker.${r}` as Key)).join(", ")}

    }
    + +
  • )} +
} + } + {made &&

{t("portable.make.done", { name: made })}

} + {error && } +
+
; +} + +// ---- History ------------------------------------------------------------------------------------------------------------------ + +function HistoryDialog({ character, onClose }: { character: CharacterView; onClose: () => void }) { + const t = useT(); + const [list, setList] = useState(null); + const [error, setError] = useState(null); + useEffect(() => { void portable.history(character.id).then(setList).catch((e) => setError(asPortableError(e))); }, [character.id]); + return
+ +
+

{t("portable.history.title", { name: character.name })}

+ +
+ {!list && !error && } + {list &&
    + {list.map((h) =>
  • #{h.revision}{when(h.at)} · {t(`portable.history.${h.kind}` as Key, { realm: h.source_realm })}
  • )} +
} + {error && } +
+
; +} + +// ---- the page ---------------------------------------------------------------------------------------------------------------- + +export function PortablePage({ onOpenSettings }: { onOpenSettings?: () => void }) { + const t = useT(); + const { state, refresh } = usePortable(); + const [playing, setPlaying] = useState<{ character: CharacterView; realm: string } | null>(null); + const [history, setHistory] = useState(null); + const [making, setMaking] = useState(false); + const [error, setError] = useState(null); + const [copied, setCopied] = useState(false); + const realms = state?.realms ?? []; + const characters = state?.characters ?? []; + const usable = useMemo(() => realms, [realms]); + + async function addRealm() { + setError(null); + try { + const file = await open({ multiple: false, filters: [{ name: t("portable.realm.fileType"), extensions: ["json"] }] }); + if (typeof file === "string") { await portable.addRealm(file); await refresh(); } + } catch (e) { setError(asPortableError(e)); } + } + async function removeRealm(id: string) { + setError(null); + try { await portable.removeRealm(id); await refresh(); } catch (e) { setError(asPortableError(e)); } + } + async function copyDiagnostics() { + try { + const json = JSON.stringify(await portable.diagnostics(), null, 2); + await navigator.clipboard.writeText(json); + setCopied(true); setTimeout(() => setCopied(false), 2500); + } catch (e) { setError(asPortableError(e)); } + } + + return
+
+

{t("portable.title")}

+
+ +
+
+

{t("portable.intro")}

+ {state && !state.runtime.running &&

{t("portable.runtime.stopped")}

} + {error && } + +

{t("portable.realms.title")}

+ + {usable.length === 0 &&

{t("portable.realms.none")}

} + {usable.map((r) =>
+ +
+

{r.name}

+

+ {t(r.online ? "portable.realm.online" : r.database_ok ? "portable.realm.stopped" : "portable.realm.unreachable")} + {r.level_cap ? ` · ${t("portable.realm.cap", { cap: r.level_cap })}` : ""} + {r.portable === "setup" ? ` · ${t("portable.realm.setup")}` : ""} + {` · ${t(r.kind === "installed" ? "portable.realm.installed" : "portable.realm.prepared")}`} +

+
+ {r.kind === "prepared" && } +
)} +
+
+ +

{t("portable.characters.title")}

+ {characters.length === 0 && {t("portable.characters.none")}} +
+ {characters.map((c) => +
+ +
+

{c.name}

+

{c.class_name} · {t("portable.level", { level: c.level })} · {t("portable.revision", { n: c.revision })}

+

{t("portable.lastSync", { when: when(c.updated_at) })}{c.active_realm ? ` · ${t("portable.activeOn", { realm: c.active_realm })}` : ""}

+
+ +
+ {c.copies.length > 0 &&
    + {c.copies.map((x) =>
  • + {x.realm_name} + {x.projected_level && {t("portable.copy.projected", { level: x.projected_level })}} + {t("portable.copy.synced", { n: x.synced_revision })} + +
  • )} +
} +
+ + +
+
)} +
+ +

{t("portable.diag.title")}

+ +

{t("portable.diag.text")}

+ {state && state.runtime.errors.length > 0 &&
    {state.runtime.errors.slice(-5).map((e, i) =>
  • {when(e.at)} · {e.message}
  • )}
} +
{copied && {t("portable.diag.copied")}}
+
+ + {playing && setPlaying(null)} onChanged={() => void refresh()} />} + {making && setMaking(false)} onChanged={() => void refresh()} />} + {history && setHistory(null)} />} + {onOpenSettings && null} +
; +} diff --git a/src/screens/RemoteClient.tsx b/src/screens/RemoteClient.tsx index 0ad2300..807e475 100644 --- a/src/screens/RemoteClient.tsx +++ b/src/screens/RemoteClient.tsx @@ -1,10 +1,11 @@ import { useEffect, useState } from "react"; -import { Gauge, Settings } from "lucide-react"; +import { Gauge, Settings, Swords } from "lucide-react"; import { api, asUiError, REMOTE_CLIENT_ID } from "@/lib/api"; import { checkClient, startClientPolling, useClientStatus } from "@/lib/clientUpdate"; import { ClientCard } from "@/screens/ClientCard"; import { ClientDialog, type ClientDialogMode } from "@/screens/ClientDialog"; import { AboutCard } from "@/screens/AboutCard"; +import { PortablePage } from "@/screens/PortablePage"; import { LanguagePicker } from "@/components/LanguagePicker"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; @@ -15,7 +16,7 @@ import logo from "@/assets/logo.png"; export function RemoteClient({ onHost }: { onHost: () => void }) { const t = useT(); const human = useHuman(); - const [page, setPage] = useState<"overview" | "settings">("overview"); + const [page, setPage] = useState<"overview" | "characters" | "settings">("overview"); const [host, setHost] = useState(""); const [savedHost, setSavedHost] = useState(""); const [loading, setLoading] = useState(true); @@ -56,14 +57,14 @@ export function RemoteClient({ onHost }: { onHost: () => void }) {
- {page === "settings" ? <>

{t("nav.settings")}

: <> + {page === "characters" ? : page === "settings" ? <>

{t("nav.settings")}

: <>

{t("welcome.connect.title")}

{t("remote.intro")}

diff --git a/src/screens/Shell.tsx b/src/screens/Shell.tsx index ff81391..374cfd0 100644 --- a/src/screens/Shell.tsx +++ b/src/screens/Shell.tsx @@ -1,5 +1,5 @@ import { useCallback, useEffect, useState } from "react"; -import { Archive, Bot, Bug, Gauge, Globe, Puzzle, Server, Settings, Terminal, Users, type LucideIcon } from "lucide-react"; +import { Archive, Bot, Bug, Gauge, Globe, Puzzle, Server, Settings, Swords, Terminal, Users, type LucideIcon } from "lucide-react"; import { api, type ServerSummary } from "@/lib/api"; import { useT, type Key } from "@/i18n"; import logo from "@/assets/logo.png"; @@ -14,11 +14,12 @@ import { FriendsPage } from "@/screens/FriendsPage"; import { ReportPage } from "@/screens/ReportPage"; import { ModulesPage } from "@/screens/ModulesPage"; import { ConsolePage } from "@/screens/ConsolePage"; +import { PortablePage } from "@/screens/PortablePage"; import { Button } from "@/components/ui/button"; import { startServerUpdatePolling, useServerUpdate } from "@/lib/serverUpdate"; import { startClientPolling } from "@/lib/clientUpdate"; -type Page = "overview" | "bots" | "server" | "modules" | "players" | "friends" | "backups" | "console" | "report" | "settings"; +type Page = "overview" | "bots" | "server" | "modules" | "players" | "characters" | "friends" | "backups" | "console" | "report" | "settings"; const NAV: { id: Page; label: Key; icon: LucideIcon; question: Key }[] = [ { id: "overview", label: "nav.overview", icon: Gauge, question: "q.overview" }, @@ -26,6 +27,7 @@ const NAV: { id: Page; label: Key; icon: LucideIcon; question: Key }[] = [ { id: "server", label: "nav.server", icon: Server, question: "q.server" }, { id: "modules", label: "nav.modules", icon: Puzzle, question: "q.modules" }, { id: "players", label: "nav.players", icon: Users, question: "q.players" }, + { id: "characters", label: "nav.characters", icon: Swords, question: "q.characters" }, { id: "friends", label: "nav.friends", icon: Globe, question: "q.friends" }, { id: "backups", label: "nav.backups", icon: Archive, question: "q.backups" }, { id: "console", label: "nav.console", icon: Terminal, question: "q.console" }, @@ -140,6 +142,8 @@ export function Shell(props: { ) : page === "settings" ? ( + ) : page === "characters" ? ( + ) : page === "players" ? ( ) : page === "backups" ? (