From 8dbd5e2310e4952eebec0626f6f48af5c833d54a Mon Sep 17 00:00:00 2001 From: Shaydera Date: Thu, 19 Nov 2026 23:18:42 +0100 Subject: [PATCH 1/3] List normal dungeon visits as runs A visit to a dungeon difficulty becomes a run like a Mythic+ key, with its boss and combat pulls inside. A later visit of the same instance copy, read from the NPC GUIDs, continues it together with the fights outside in between; a visit without a pull is not listed. While a log is followed, the open run and a run just left are listed as provisional entries. Index format 16. --- crates/openlogs-analysis/src/run_result.rs | 20 +- crates/openlogs-analysis/tests/run_result.rs | 30 ++ crates/openlogs-cli/src/format.rs | 74 +++- crates/openlogs-cli/src/main.rs | 2 +- crates/openlogs-index/src/builder.rs | 278 ++++++++++----- crates/openlogs-index/src/lib.rs | 1 + crates/openlogs-index/src/model.rs | 74 +++- crates/openlogs-index/src/runs.rs | 111 ++++++ crates/openlogs-index/src/scan.rs | 4 +- crates/openlogs-index/tests/combat_pulls.rs | 29 +- crates/openlogs-index/tests/common/mod.rs | 121 +++++++ crates/openlogs-index/tests/dungeon_runs.rs | 354 +++++++++++++++++++ crates/openlogs-index/tests/index_runs.rs | 6 +- crates/openlogs-index/tests/live.rs | 67 +++- crates/openlogs-index/tests/run_semantics.rs | 8 +- crates/openlogs-service/src/log_dto.rs | 51 ++- crates/openlogs-wasm/src/engine.rs | 3 +- crates/openlogs-wasm/tests/engine.rs | 62 +++- 18 files changed, 1082 insertions(+), 213 deletions(-) create mode 100644 crates/openlogs-index/src/runs.rs create mode 100644 crates/openlogs-index/tests/common/mod.rs create mode 100644 crates/openlogs-index/tests/dungeon_runs.rs diff --git a/crates/openlogs-analysis/src/run_result.rs b/crates/openlogs-analysis/src/run_result.rs index a31f2df..cffde52 100644 --- a/crates/openlogs-analysis/src/run_result.rs +++ b/crates/openlogs-analysis/src/run_result.rs @@ -1,7 +1,5 @@ -//! The result of a Mythic+ run decided with the game's dungeon data. Without that data the -//! index's result stands. - -use std::collections::HashSet; +//! The result of a run. A Mythic+ run's is decided with the game's dungeon data; without +//! that data, and for a dungeon visit, the index's result stands. use openlogs_gamedata::{DungeonTable, KeyTimer}; use openlogs_index::{FightSummary, Outcome}; @@ -21,9 +19,11 @@ pub struct RunResult { pub bosses: Option, /// Only for a run completed by the boss list with a logged time. pub timer: Option, + /// Bosses with a killed boss pull in the run, each counted once. + pub killed_bosses: u32, } -/// The result of `run` (an entry with `challenge`) among the index's `fights`. +/// The result of `run` (a run entry) among the index's `fights`. /// /// With a boss list for the key: completed exactly when every boss of the dungeon has a /// killed boss pull in the run and the logged time is not 0; otherwise not completed with @@ -35,12 +35,14 @@ pub fn run_result( fights: &[FightSummary], dungeons: Option<&DungeonTable>, ) -> RunResult { + let kills = run.killed_encounters(fights); let index_result = RunResult { outcome: run.outcome, bosses: None, timer: None, + killed_bosses: kills.len() as u32, }; - let Some(challenge) = &run.challenge else { + let Some(challenge) = run.keystone() else { return index_result; }; let Some(dungeon) = dungeons.and_then(|table| table.dungeon(challenge.challenge_mode_id)) @@ -50,11 +52,6 @@ pub fn run_result( let Some(bosses) = &dungeon.bosses else { return index_result; }; - let kills: HashSet = fights - .iter() - .filter(|fight| fight.run_index == Some(run.index) && fight.outcome == Outcome::Kill) - .map(|fight| fight.encounter_id) - .collect(); let killed = bosses .iter() .filter(|boss| kills.contains(&boss.encounter_id)) @@ -75,5 +72,6 @@ pub fn run_result( outcome, bosses: Some(BossProgress { killed, total }), timer, + ..index_result } } diff --git a/crates/openlogs-analysis/tests/run_result.rs b/crates/openlogs-analysis/tests/run_result.rs index 2b0ab5a..826ea56 100644 --- a/crates/openlogs-analysis/tests/run_result.rs +++ b/crates/openlogs-analysis/tests/run_result.rs @@ -76,6 +76,7 @@ fn a_key_ended_after_a_mid_dungeon_kill_is_not_completed() { outcome: Outcome::Wipe, bosses: bosses(2), timer: None, + killed_bosses: 2, } ); } @@ -98,6 +99,7 @@ fn a_key_with_every_boss_killed_is_completed_with_its_timer() { outcome: Outcome::Kill, bosses: bosses(3), timer: Some(timer), + killed_bosses: 3, }, "{total_ms} ms" ); @@ -116,6 +118,7 @@ fn a_logged_time_of_zero_is_not_completed_even_with_every_boss_killed() { outcome: Outcome::Wipe, bosses: bosses(3), timer: None, + killed_bosses: 3, } ); } @@ -127,6 +130,7 @@ fn without_a_boss_list_the_index_result_stays() { outcome: Outcome::Kill, bosses: None, timer: None, + killed_bosses: 2, }; let index = log_with(|_| {}); assert_eq!(result(&index, None), unchanged, "no dungeon data"); @@ -139,3 +143,29 @@ fn without_a_boss_list_the_index_result_stays() { assert_eq!(result(&index, Some(&table)), unchanged, "key {key}"); } } + +#[test] +fn a_run_counts_each_killed_boss_once() { + let log = [ + "11/17/2026 20:00:00.0000 ZONE_CHANGE,230,\"Blackrock Depths\",1", + "11/17/2026 20:00:10.0000 ENCOUNTER_START,227,\"High Interrogator Gerstahn\",1,5,230", + "11/17/2026 20:00:20.0000 ENCOUNTER_END,227,\"High Interrogator Gerstahn\",1,5,1,10000", + "11/17/2026 20:01:10.0000 ENCOUNTER_START,227,\"High Interrogator Gerstahn\",1,5,230", + "11/17/2026 20:01:20.0000 ENCOUNTER_END,227,\"High Interrogator Gerstahn\",1,5,1,10000", + "11/17/2026 20:02:10.0000 ENCOUNTER_START,228,\"Lord Roccor\",1,5,230", + "11/17/2026 20:02:20.0000 ENCOUNTER_END,228,\"Lord Roccor\",1,5,0,10000", + "11/17/2026 20:03:00.0000 ZONE_CHANGE,0,\"Searing Gorge\",0", + ] + .map(|line| format!("{line}\n")) + .concat(); + let index = index_bytes(log.as_bytes()); + assert_eq!( + result(&index, Some(&table())), + RunResult { + outcome: Outcome::Ended, + bosses: None, + timer: None, + killed_bosses: 1, + } + ); +} diff --git a/crates/openlogs-cli/src/format.rs b/crates/openlogs-cli/src/format.rs index 9492c23..300ef08 100644 --- a/crates/openlogs-cli/src/format.rs +++ b/crates/openlogs-cli/src/format.rs @@ -2,9 +2,7 @@ use std::fmt::Write; use std::path::Path; use std::time::Duration; -use openlogs_index::{ - CacheStatus, ChallengeMode, FightSummary, GameFlavor, LogIndex, Outcome, difficulty_label, -}; +use openlogs_index::{CacheStatus, FightSummary, GameFlavor, LogIndex, Outcome, difficulty_label}; /// Human-readable fight table for `openlogs-cli dump-fights`. pub fn report( @@ -67,11 +65,12 @@ pub fn report( let runs: Vec = index .fights .iter() - .filter_map(|fight| Some(run_line(fight, fight.challenge.as_ref()?, &index.fights))) + .filter(|fight| fight.is_run()) + .map(|run| run_line(run, &index.fights)) .collect(); if !runs.is_empty() { let _ = writeln!(out); - let _ = writeln!(out, "Mythic+ runs"); + let _ = writeln!(out, "Runs"); for line in runs { let _ = writeln!(out, "{line}"); } @@ -80,15 +79,14 @@ pub fn report( } fn fight_row(fight: &FightSummary) -> String { - let (difficulty, result) = match &fight.challenge { + let (difficulty, result) = match fight.keystone() { Some(challenge) => ( format!("+{}", challenge.keystone_level), run_result(fight.outcome), ), None if fight.is_combat() => ("Combat".to_string(), pull_result(fight.outcome)), None => ( - difficulty_label(fight.difficulty) - .map_or_else(|| fight.difficulty.to_string(), str::to_string), + difficulty_name(fight.difficulty), pull_result(fight.outcome), ), }; @@ -96,7 +94,7 @@ fn fight_row(fight: &FightSummary) -> String { Some(combat) if combat.enemy_count > 1 => format!(" +{}", combat.enemy_count - 1), _ => String::new(), }; - // Pulls of a Mythic+ run sit indented under their run. + // Pulls of a run sit indented under their run. let name = match fight.run_index { Some(_) => format!(" {}{enemies}", fight.name), None => format!("{}{enemies}", fight.name), @@ -126,7 +124,11 @@ fn pull_result(outcome: Outcome) -> &'static str { } } -/// A run's result as the index reads it from the log (see `FightSummary::outcome`). +fn difficulty_name(difficulty: u32) -> String { + difficulty_label(difficulty).map_or_else(|| difficulty.to_string(), str::to_string) +} + +/// A key's result as the index reads it from the log (see `FightSummary::outcome`). fn run_result(outcome: Outcome) -> &'static str { match outcome { Outcome::Kill => "Completed", @@ -136,8 +138,9 @@ fn run_result(outcome: Outcome) -> &'static str { } /// E.g. ` #1 Priory of the Sacred Flame +12: Completed in 10:00.0 (logged 10:00.0), -/// affixes 10, 147, 9, boss pulls 2, 3, 4`. -fn run_line(run: &FightSummary, challenge: &ChallengeMode, fights: &[FightSummary]) -> String { +/// affixes 10, 147, 9, boss pulls 2, 3, 4`, or ` #1 Blackrock Depths Normal: Ended in +/// 70:00.0, bosses killed 3, boss pulls 3, 5, 7`. +fn run_line(run: &FightSummary, fights: &[FightSummary]) -> String { let list = |items: Vec| { if items.is_empty() { "none".to_string() @@ -145,10 +148,6 @@ fn run_line(run: &FightSummary, challenge: &ChallengeMode, fights: &[FightSummar items.join(", ") } }; - let logged = challenge - .total_time_ms - .map_or_else(String::new, |ms| format!(" (logged {})", duration(ms))); - let affixes = list(challenge.affix_ids.iter().map(u32::to_string).collect()); let pulls = list( fights .iter() @@ -156,6 +155,21 @@ fn run_line(run: &FightSummary, challenge: &ChallengeMode, fights: &[FightSummar .map(|fight| fight.index.to_string()) .collect(), ); + let Some(challenge) = run.keystone() else { + return format!( + " #{} {} {}: {} in {}, bosses killed {}, boss pulls {pulls}", + run.index, + run.name, + difficulty_name(run.difficulty), + pull_result(run.outcome), + duration(run.duration_ms), + run.killed_encounters(fights).len() + ); + }; + let logged = challenge + .total_time_ms + .map_or_else(String::new, |ms| format!(" (logged {})", duration(ms))); + let affixes = list(challenge.affix_ids.iter().map(u32::to_string).collect()); format!( " #{} {} +{}: {} in {}{logged}, affixes {affixes}, boss pulls {pulls}", run.index, @@ -259,6 +273,34 @@ mod tests { ); } + #[test] + fn report_lists_dungeon_runs_with_their_killed_bosses() { + let log = [ + "11/17/2026 20:00:00.0000 ZONE_CHANGE,230,\"Blackrock Depths\",1", + "11/17/2026 20:00:10.0000 ENCOUNTER_START,227,\"High Interrogator Gerstahn\",1,5,230", + "11/17/2026 20:00:20.0000 ENCOUNTER_END,227,\"High Interrogator Gerstahn\",1,5,1,10000", + "11/17/2026 20:01:10.0000 ENCOUNTER_START,228,\"Lord Roccor\",1,5,230", + "11/17/2026 20:01:20.0000 ENCOUNTER_END,228,\"Lord Roccor\",1,5,0,10000", + "11/17/2026 20:02:00.0000 ZONE_CHANGE,0,\"Searing Gorge\",0", + ] + .map(|line| format!("{line}\n")) + .concat(); + let index = index_bytes(log.as_bytes()); + let text = report( + Path::new("Logs/brd.txt"), + 8192, + &index, + Duration::from_millis(3), + None, + ); + assert!( + text.contains( + "#1 Blackrock Depths Normal: Ended in 1:20.0, bosses killed 1, boss pulls 2, 3" + ), + "{text}" + ); + } + #[test] fn report_marks_combat_pulls() { let index = index_bytes( diff --git a/crates/openlogs-cli/src/main.rs b/crates/openlogs-cli/src/main.rs index 6fbb726..526eb2c 100644 --- a/crates/openlogs-cli/src/main.rs +++ b/crates/openlogs-cli/src/main.rs @@ -23,7 +23,7 @@ struct Cli { #[derive(Subcommand)] enum Command { - /// List the fights (boss pulls and Mythic+ runs) in a combat log. + /// List the fights (pulls and runs) in a combat log. DumpFights { /// Path to a WoWCombatLog-*.txt file. file: PathBuf, diff --git a/crates/openlogs-index/src/builder.rs b/crates/openlogs-index/src/builder.rs index d7e2cc1..bc51fb1 100644 --- a/crates/openlogs-index/src/builder.rs +++ b/crates/openlogs-index/src/builder.rs @@ -8,10 +8,12 @@ use openlogs_parser::{ use crate::combat::{DeadEnemies, Exchange, OpenCombat, counted_damage, exchange}; use crate::markers::MarkerState; use crate::model::{ - BOSS_TAIL_MICROS, ChallengeMode, END_GRACE_LINES, END_GRACE_MICROS, FightSummary, GameFlavor, - LEAD_MAX_MICROS, LogIndex, MYTHIC_KEYSTONE_DIFFICULTY, MapBounds, Outcome, PRELUDE_MICROS, - RESUME_MAX_GAP_MICROS, RosterEntry, SUPPORTED_LOG_VERSION, WorldMarker, + BOSS_TAIL_MICROS, ChallengeMode, DUNGEON_DIFFICULTIES, END_GRACE_LINES, END_GRACE_MICROS, + FightSummary, GameFlavor, LEAD_MAX_MICROS, LogIndex, MYTHIC_KEYSTONE_DIFFICULTY, MapBounds, + Outcome, PRELUDE_MICROS, RESUME_MAX_GAP_MICROS, RosterEntry, RunKind, SUPPORTED_LOG_VERSION, + WorldMarker, }; +use crate::runs::{OpenRun, run_outcome}; /// Byte range of one line in the log file. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -27,13 +29,16 @@ pub struct IndexBuilder { open: Option, /// The combat pull in progress; never open together with a boss pull. combat: Option, - /// The Mythic+ run in progress; boss pulls opened meanwhile belong to it. + /// The Mythic+ run or dungeon visit in progress; pulls opened meanwhile belong to it. run: Option, + /// The dungeon run last left, which a later visit of the same instance copy continues. + /// Listed once another instance or a key is entered, or another copy is fought in. + left_run: Option, /// The run's `CHALLENGE_MODE_END`, held while its open boss pull may still end. held_end: Option, /// Lines of the last [`PRELUDE_MICROS`], oldest first, as (timestamp, offset). recent: VecDeque<(Timestamp, u64)>, - /// `end_offset` of the last closed boss pull or run; preludes never reach back past it. + /// `end_offset` of the last closed boss pull or key; preludes never reach back past it. /// Combat pulls leave it alone, so a boss pull keeps the trash before it in its prelude. last_fight_end: u64, /// `end_offset` of the last closed combat pull; combat pull preludes never reach back @@ -69,6 +74,7 @@ impl IndexBuilder { open: None, combat: None, run: None, + left_run: None, held_end: None, recent: VecDeque::new(), last_fight_end: 0, @@ -178,6 +184,9 @@ impl IndexBuilder { } } Event::Combat(event) => { + if let Some(run) = &mut self.run { + run.learn_copy(event); + } if let CombatKind::UnitDied { unconscious: false } = event.kind && event.target.is_enemy_npc() { @@ -243,6 +252,7 @@ impl IndexBuilder { self.zone = Some((*name).to_string()); self.zone_instance_id = *zone_id; self.zone_difficulty = *difficulty; + self.enter_zone(span, line.timestamp, *zone_id, name, *difficulty); } } } @@ -257,23 +267,22 @@ impl IndexBuilder { self.close_combat(Outcome::Incomplete); self.close_open(Outcome::Incomplete); self.close_run(Outcome::Incomplete); + self.list_left_run(); // A run closes after its boss pulls but is numbered before them. self.index.fights.sort_by_key(|fight| fight.index); self.index } - /// The closed entries that no later line can change, as an index. With `settle_ms`, only - /// those with a line more than `settle_ms` past their end, which the analysis may still read; - /// measured as it does, in whole ms from their start against `duration_ms`. Boss and combat - /// pulls of the open run wait for it. + /// The closed pulls, as an index, with the open run and the left run as of now. With + /// `settle_ms`, only pulls with a line more than `settle_ms` past their end, which the + /// analysis may still read; measured as it does, in whole ms from their start against + /// `duration_ms`. No later line changes an entry unless it is listed in `provisional`. pub fn settled(&self, settle_ms: Option) -> LogIndex { - let open_run = self.run.as_ref().map(|run| run.summary.index); let latest = self.recent.back().map(|&(timestamp, _)| timestamp); let mut fights: Vec = self .index .fights .iter() - .filter(|fight| fight.run_index.is_none() || fight.run_index != open_run) .filter(|fight| match (settle_ms, latest) { (None, _) => true, (Some(settle), Some(latest)) => { @@ -284,6 +293,20 @@ impl IndexBuilder { }) .cloned() .collect(); + let mut provisional = Vec::new(); + if let Some(left) = &self.left_run { + let may_join = |fight: &&FightSummary| { + fight.index > left.summary.index && fight.run_index.is_none() && !fight.is_run() + }; + provisional.extend(fights.iter().filter(may_join).map(|fight| fight.index)); + provisional.push(left.summary.index); + fights.push(left.clone().finish(Outcome::Ended)); + } + if let Some(run) = self.run.as_ref().filter(|run| run.numbered) { + provisional.push(run.summary.index); + fights.push(run.clone().finish(Outcome::Incomplete)); + } + provisional.sort_unstable(); fights.sort_by_key(|fight| fight.index); LogIndex { format_version: self.index.format_version, @@ -297,6 +320,7 @@ impl IndexBuilder { unhandled_in_fights: self.index.unhandled_in_fights.clone(), warnings: self.index.warnings.clone(), fights, + provisional, } } @@ -335,12 +359,18 @@ impl IndexBuilder { .as_ref() .is_some_and(|run| run.summary.instance_id != *zone_id) { - self.close_run(Outcome::Incomplete); + self.leave_run(); } } Event::ChallengeModeStart(start) if !self.is_same_key(start, line.timestamp) => { self.close_open(Outcome::Incomplete); - self.close_run(Outcome::Incomplete); + let dungeon = self.run.as_ref().is_some_and(OpenRun::is_dungeon); + self.close_run(if dungeon { + Outcome::Ended + } else { + Outcome::Incomplete + }); + self.list_left_run(); } Event::ChallengeModeEnd(end) if self.is_open_run(end.instance_id) => { self.hold_end(span, line.timestamp, end); @@ -476,7 +506,7 @@ impl IndexBuilder { fn is_open_run(&self, instance_id: u32) -> bool { self.run .as_ref() - .is_some_and(|run| run.summary.instance_id == instance_id) + .is_some_and(|run| !run.is_dungeon() && run.summary.instance_id == instance_id) } /// Whether `start`, logged at `timestamp`, repeats the key of the open run: same @@ -485,7 +515,7 @@ impl IndexBuilder { self.run.as_ref().is_some_and(|run| { run.summary.instance_id == start.instance_id && timestamp.0 - run.summary.end.0 <= RESUME_MAX_GAP_MICROS - && run.summary.challenge.as_ref().is_some_and(|key| { + && run.summary.keystone().is_some_and(|key| { key.challenge_mode_id == start.challenge_mode_id && key.keystone_level == start.keystone_level }) @@ -500,6 +530,7 @@ impl IndexBuilder { lead: Option, ) { self.close_open(Outcome::Incomplete); + let run_index = self.number_run(); let index = match &lead { Some(lead) => lead.pull.index, None => self.next_index(), @@ -524,8 +555,8 @@ impl IndexBuilder { boss_hp_percent: None, roster: Vec::new(), broken_lines: 0, - challenge: None, - run_index: self.run.as_ref().map(|run| run.summary.index), + run: None, + run_index, world_markers: self.markers.active(), map_bounds: self.map_bounds.values().copied().collect(), combat: None, @@ -561,41 +592,128 @@ impl IndexBuilder { /// Opens a run; [`Self::close_before`] has already ended what was open. fn open_run(&mut self, span: LineSpan, timestamp: Timestamp, start: &ChallengeModeStart<'_>) { - let index = self.next_index(); - let prelude_offset = self.prelude_offset(span, self.last_fight_end); - self.run = Some(OpenRun { - summary: FightSummary { - index, - encounter_id: 0, - name: start.zone_name.to_string(), - difficulty: MYTHIC_KEYSTONE_DIFFICULTY, - group_size: 0, - instance_id: start.instance_id, - zone: Some(start.zone_name.to_string()), - outcome: Outcome::Incomplete, - start: timestamp, - end: timestamp, - duration_ms: 0, - prelude_offset, - start_offset: span.offset, - end_offset: span.next_offset, - boss_hp_percent: None, - roster: Vec::new(), - broken_lines: 0, - challenge: Some(ChallengeMode { - challenge_mode_id: start.challenge_mode_id, - keystone_level: start.keystone_level, - affix_ids: start.affix_ids(), - total_time_ms: None, - }), - run_index: None, - world_markers: Vec::new(), - map_bounds: Vec::new(), - combat: None, - }, - player_names: HashMap::new(), - last_pull: None, - }); + let mut summary = self.run_summary( + span, + timestamp, + start.zone_name, + start.instance_id, + MYTHIC_KEYSTONE_DIFFICULTY, + RunKind::Keystone(ChallengeMode { + challenge_mode_id: start.challenge_mode_id, + keystone_level: start.keystone_level, + affix_ids: start.affix_ids(), + total_time_ms: None, + }), + ); + summary.index = self.next_index(); + self.run = Some(OpenRun::new(summary)); + } + + /// A `ZONE_CHANGE` into a dungeon difficulty opens a visit, numbered by its first pull. + /// Entering another instance or difficulty than the left run's lists that run; the open + /// world (difficulty 0) keeps it waiting. + fn enter_zone( + &mut self, + span: LineSpan, + timestamp: Timestamp, + zone_id: u32, + name: &str, + difficulty: u32, + ) { + if difficulty != 0 + && self.left_run.as_ref().is_some_and(|left| { + (left.summary.instance_id, left.summary.difficulty) != (zone_id, difficulty) + }) + { + self.list_left_run(); + } + if self.run.is_none() && DUNGEON_DIFFICULTIES.contains(&difficulty) { + let summary = + self.run_summary(span, timestamp, name, zone_id, difficulty, RunKind::Dungeon); + self.run = Some(OpenRun::new(summary)); + } + } + + /// A run starting at this line, not numbered yet. + fn run_summary( + &self, + span: LineSpan, + timestamp: Timestamp, + name: &str, + instance_id: u32, + difficulty: u32, + kind: RunKind, + ) -> FightSummary { + FightSummary { + index: 0, + encounter_id: 0, + name: name.to_string(), + difficulty, + group_size: 0, + instance_id, + zone: Some(name.to_string()), + outcome: Outcome::Incomplete, + start: timestamp, + end: timestamp, + duration_ms: 0, + prelude_offset: self.prelude_offset(span, self.last_fight_end), + start_offset: span.offset, + end_offset: span.next_offset, + boss_hp_percent: None, + roster: Vec::new(), + broken_lines: 0, + run: Some(kind), + run_index: None, + world_markers: Vec::new(), + map_bounds: Vec::new(), + combat: None, + } + } + + /// `index` of the open run for a pull opening now. A dungeon visit's first pull numbers + /// it, unless the visit continues the left run: then the pulls listed since that run + /// was left join it. + fn number_run(&mut self) -> Option { + if let Some(mut visit) = self.run.take_if(|run| !run.numbered) { + match self.left_run.take_if(|left| left.continued_by(&visit)) { + Some(mut left) => { + let index = left.summary.index; + for fight in &mut self.index.fights { + if fight.index > index && fight.run_index.is_none() && !fight.is_run() { + fight.run_index = Some(index); + } + } + left.absorb(visit); + self.run = Some(left); + } + None => { + self.list_left_run(); + visit.summary.index = self.next_index(); + visit.numbered = true; + self.run = Some(visit); + } + } + } + self.run.as_ref().map(|run| run.summary.index) + } + + /// Leaving the instance closes a key's run. A dungeon visit with a pull becomes the left + /// run, which a later visit may continue; one without is dropped. + fn leave_run(&mut self) { + if !self.run.as_ref().is_some_and(OpenRun::is_dungeon) { + self.close_run(Outcome::Incomplete); + return; + } + if let Some(run) = self.run.take().filter(|run| run.numbered) { + self.list_left_run(); + self.left_run = Some(run); + } + } + + fn list_left_run(&mut self) { + if let Some(left) = self.left_run.take() { + self.index.fights.push(left.finish(Outcome::Ended)); + } } /// An end for another instance leaves the open run alone, and a held end waits for @@ -609,8 +727,8 @@ impl IndexBuilder { /// Closes the open run at its `CHALLENGE_MODE_END`, with the result the log shows. fn close_run_at_end(&mut self, end: &ChallengeModeEnd) { let Some(run) = &mut self.run else { return }; - if let Some(challenge) = &mut run.summary.challenge { - challenge.total_time_ms = Some(end.total_time_ms); + if let Some(RunKind::Keystone(key)) = &mut run.summary.run { + key.total_time_ms = Some(end.total_time_ms); } let outcome = run_outcome(end, run.last_pull); self.close_run(outcome); @@ -654,9 +772,13 @@ impl IndexBuilder { } } + /// Closes the open run; a dungeon visit without a pull is dropped. A dungeon visit, unlike + /// a key, leaves preludes alone: a key started right after it keeps its lookback. fn close_run(&mut self, outcome: Outcome) { - if let Some(run) = self.run.take() { - self.last_fight_end = self.last_fight_end.max(run.summary.end_offset); + if let Some(run) = self.run.take().filter(|run| run.numbered) { + if !run.is_dungeon() { + self.last_fight_end = self.last_fight_end.max(run.summary.end_offset); + } self.index.fights.push(run.finish(outcome)); } } @@ -686,6 +808,7 @@ impl IndexBuilder { } fn open_combat(&mut self, span: LineSpan, timestamp: Timestamp) { + let run_index = self.number_run(); let index = self.next_index(); let prelude_offset = self.prelude_offset(span, self.last_fight_end.max(self.last_combat_end)); @@ -707,8 +830,8 @@ impl IndexBuilder { boss_hp_percent: None, roster: Vec::new(), broken_lines: 0, - challenge: None, - run_index: self.run.as_ref().map(|run| run.summary.index), + run: None, + run_index, world_markers: self.markers.active(), map_bounds: self.map_bounds.values().copied().collect(), combat: None, @@ -915,45 +1038,6 @@ struct HeldEnd { run_end_offset: u64, } -#[derive(Clone)] -struct OpenRun { - summary: FightSummary, - /// Player names seen in the run's boss pulls. - player_names: HashMap, - /// Outcome of the run's latest boss pull so far. - last_pull: Option, -} - -/// `success` may mean "in time" or only "finished", so a completed key is told by its last -/// boss pull being a kill; the flag decides only when no pull tells. -fn run_outcome(end: &ChallengeModeEnd, last_pull: Option) -> Outcome { - let completed = match last_pull { - _ if end.total_time_ms == 0 => false, - Some(Outcome::Kill) => true, - Some(Outcome::Wipe) => false, - Some(Outcome::Incomplete | Outcome::Ended) | None => end.success, - }; - if completed { - Outcome::Kill - } else { - Outcome::Wipe - } -} - -impl OpenRun { - /// A run lasts from its start line to its last line, `CHALLENGE_MODE_END` included. - fn finish(mut self, outcome: Outcome) -> FightSummary { - let summary = &mut self.summary; - summary.outcome = outcome; - summary.duration_ms = u64::try_from(summary.end.millis_since(summary.start)).unwrap_or(0); - summary.group_size = summary.roster.len() as u32; - for entry in &mut summary.roster { - entry.name = self.player_names.get(&entry.guid).cloned(); - } - self.summary - } -} - /// Bosses are the units with at least a fifth of the top damage taken and a quarter of the /// top max HP, so councils count every boss but idle encounter NPCs and adds do not. fn boss_hp_percent(units: &HashMap) -> Option { diff --git a/crates/openlogs-index/src/lib.rs b/crates/openlogs-index/src/lib.rs index 3e03bf5..7bf1180 100644 --- a/crates/openlogs-index/src/lib.rs +++ b/crates/openlogs-index/src/lib.rs @@ -5,6 +5,7 @@ mod cache; mod combat; mod markers; mod model; +mod runs; mod scan; pub use builder::{IndexBuilder, LineSpan}; diff --git a/crates/openlogs-index/src/model.rs b/crates/openlogs-index/src/model.rs index d286f36..0d6710e 100644 --- a/crates/openlogs-index/src/model.rs +++ b/crates/openlogs-index/src/model.rs @@ -1,10 +1,10 @@ -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use openlogs_parser::Timestamp; use serde::{Deserialize, Serialize}; /// Bumped whenever the index layout or its rules change; invalidates cached indexes. -pub const INDEX_FORMAT_VERSION: u32 = 15; +pub const INDEX_FORMAT_VERSION: u32 = 16; /// The combat log format this tool is built and tested against. pub const SUPPORTED_LOG_VERSION: u32 = 22; /// Lookback before `ENCOUNTER_START` that belongs to a fight (pre-pots, pre-casts). @@ -67,6 +67,8 @@ impl GameFlavor { /// Difficulty ID of Mythic+ (Mythic Keystone) dungeons; run entries carry it too. pub const MYTHIC_KEYSTONE_DIFFICULTY: u32 = 8; +/// Difficulties whose visit is a dungeon run: Normal, Heroic, Mythic, Timewalking, Follower. +pub const DUNGEON_DIFFICULTIES: [u32; 5] = [1, 2, 23, 24, 205]; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct LogIndex { @@ -86,8 +88,12 @@ pub struct LogIndex { /// Lines inside fights whose event the parser does not model, by event name. pub unhandled_in_fights: BTreeMap, pub warnings: Vec, - /// Boss pulls, combat pulls and Mythic+ runs, in the order of their start lines. + /// Boss pulls, combat pulls and runs, in the order of their start lines. pub fights: Vec, + /// `index` of the entries a later line may still change; only in a settled index of a log + /// still being written: the open run, a left run and the entries after it that may join it. + #[serde(default)] + pub provisional: Vec, } impl LogIndex { @@ -104,16 +110,22 @@ impl LogIndex { unhandled_in_fights: BTreeMap::new(), warnings: Vec::new(), fights: Vec::new(), + provisional: Vec::new(), } } } -/// One boss pull, a combat pull when `combat` is set, or a whole Mythic+ run when `challenge` -/// is set. A run spans `CHALLENGE_MODE_START` to `CHALLENGE_MODE_END`; it has encounter ID 0, +/// One boss pull, a combat pull when `combat` is set, or a whole run when `run` is set. +/// A Mythic+ run spans `CHALLENGE_MODE_START` to `CHALLENGE_MODE_END`; it has encounter ID 0, /// the dungeon as `name` and `zone`, difficulty [`MYTHIC_KEYSTONE_DIFFICULTY`], its roster size /// as `group_size` and no boss HP. Its boss and combat pulls are entries of their own with /// `run_index`. /// +/// A dungeon run is a visit of a dungeon difficulty ([`DUNGEON_DIFFICULTIES`]) with at least one +/// pull, from its `ZONE_CHANGE` to the last line before leaving. A later visit of the same +/// instance copy continues it, together with the pulls outside in between. It has the zone's +/// difficulty and is numbered by its first pull's start. +/// /// A combat pull is a fight outside boss encounters, from the first exchange of damage between /// the group and an enemy NPC. It has encounter ID 0, the enemy that took the most damage from /// the group as `name`, difficulty and instance of the latest `ZONE_CHANGE`, the number of the @@ -130,9 +142,10 @@ pub struct FightSummary { pub instance_id: u32, /// Zone of the last `ZONE_CHANGE` before the start line, if any; a run's dungeon. pub zone: Option, - /// For a run: `Kill` = completed (`CHALLENGE_MODE_END` after a killed last boss pull), - /// `Wipe` = not completed (any other end, or a logged time of 0), `Incomplete` = no - /// end. The `success` flag decides only when no boss pull tells. + /// For a Mythic+ run: `Kill` = completed (`CHALLENGE_MODE_END` after a killed last boss + /// pull), `Wipe` = not completed (any other end, or a logged time of 0), `Incomplete` = no + /// end. The `success` flag decides only when no boss pull tells. For a dungeon run: `Ended` + /// once left or ended by a key's start, `Incomplete` when the log ends inside. pub outcome: Outcome, pub start: Timestamp, pub end: Timestamp, @@ -147,9 +160,9 @@ pub struct FightSummary { pub boss_hp_percent: Option, pub roster: Vec, pub broken_lines: u64, - /// Key details when this entry is a whole Mythic+ run. - pub challenge: Option, - /// `index` of the Mythic+ run this boss or combat pull belongs to. + /// Set when this entry is a whole run: a Mythic+ key or a dungeon visit. + pub run: Option, + /// `index` of the run this boss or combat pull belongs to. pub run_index: Option, /// World markers active at the start line, sorted by marker; empty for runs. #[serde(default)] @@ -186,9 +199,30 @@ pub struct MapBounds { } impl FightSummary { - /// Whether this entry is a whole Mythic+ run rather than a boss pull. + /// Whether this entry is a whole run rather than a pull. pub fn is_run(&self) -> bool { - self.challenge.is_some() + self.run.is_some() + } + + /// Encounter IDs of the boss pulls killed in this run, among the index's `fights`. + pub fn killed_encounters(&self, fights: &[FightSummary]) -> BTreeSet { + fights + .iter() + .filter(|fight| { + fight.run_index == Some(self.index) + && !fight.is_combat() + && fight.outcome == Outcome::Kill + }) + .map(|fight| fight.encounter_id) + .collect() + } + + /// Key details when this entry is a Mythic+ run. + pub fn keystone(&self) -> Option<&ChallengeMode> { + match &self.run { + Some(RunKind::Keystone(key)) => Some(key), + _ => None, + } } /// Whether this entry is a combat pull outside boss encounters. @@ -197,6 +231,12 @@ impl FightSummary { } } +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum RunKind { + Keystone(ChallengeMode), + Dungeon, +} + /// Key details of a Mythic+ run from `CHALLENGE_MODE_START` and `CHALLENGE_MODE_END`. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ChallengeMode { @@ -230,10 +270,12 @@ pub struct RosterEntry { pub fn difficulty_label(id: u32) -> Option<&'static str> { match id { MYTHIC_KEYSTONE_DIFFICULTY => Some("Mythic+"), - 14 => Some("Normal"), - 15 => Some("Heroic"), + 1 | 14 => Some("Normal"), + 2 | 15 => Some("Heroic"), // 233: Mythic with a flexible raid size, logged by Nymrissa Wavecaller. - 16 | 233 => Some("Mythic"), + 16 | 23 | 233 => Some("Mythic"), + 24 => Some("Timewalking"), + 205 => Some("Follower"), 17 => Some("LFR"), _ => None, } diff --git a/crates/openlogs-index/src/runs.rs b/crates/openlogs-index/src/runs.rs new file mode 100644 index 0000000..31d1be4 --- /dev/null +++ b/crates/openlogs-index/src/runs.rs @@ -0,0 +1,111 @@ +use std::collections::HashMap; + +use openlogs_parser::{ChallengeModeEnd, CombatEvent}; + +use crate::model::{FightSummary, Outcome, RunKind}; + +#[derive(Clone)] +pub(crate) struct OpenRun { + pub(crate) summary: FightSummary, + /// Player names seen in the run's boss pulls. + pub(crate) player_names: HashMap, + /// Outcome of the run's latest boss pull so far. + pub(crate) last_pull: Option, + /// Instance copy of a dungeon run, once an NPC of its instance was seen. + pub(crate) copy: Option, + /// Whether `summary.index` is set. A dungeon visit gets its number with its first pull, + /// so a visit without a fight is never listed. + pub(crate) numbered: bool, +} + +impl OpenRun { + pub(crate) fn new(summary: FightSummary) -> Self { + let numbered = !matches!(summary.run, Some(RunKind::Dungeon)); + Self { + summary, + player_names: HashMap::new(), + last_pull: None, + copy: None, + numbered, + } + } + + pub(crate) fn is_dungeon(&self) -> bool { + matches!(self.summary.run, Some(RunKind::Dungeon)) + } + + pub(crate) fn learn_copy(&mut self, event: &CombatEvent<'_>) { + if !self.is_dungeon() || self.copy.is_some() { + return; + } + self.copy = [event.source.guid, event.target.guid] + .into_iter() + .find_map(|guid| instance_copy(guid, self.summary.instance_id)) + .map(str::to_string); + } + + /// Whether `visit` is in the same instance copy, which only an NPC seen in both proves. + pub(crate) fn continued_by(&self, visit: &OpenRun) -> bool { + self.summary.instance_id == visit.summary.instance_id + && self.summary.difficulty == visit.summary.difficulty + && self.copy.is_some() + && self.copy == visit.copy + } + + /// Extends this run, left earlier, by a later visit of the same copy. + pub(crate) fn absorb(&mut self, visit: OpenRun) { + let summary = &mut self.summary; + summary.end = summary.end.max(visit.summary.end); + summary.end_offset = visit.summary.end_offset; + summary.broken_lines += visit.summary.broken_lines; + for entry in visit.summary.roster { + if summary.roster.iter().all(|known| known.guid != entry.guid) { + summary.roster.push(entry); + } + } + for (guid, name) in visit.player_names { + self.player_names.entry(guid).or_insert(name); + } + } + + /// A run lasts from its start line to its last line, `CHALLENGE_MODE_END` included. + pub(crate) fn finish(mut self, outcome: Outcome) -> FightSummary { + let summary = &mut self.summary; + summary.outcome = outcome; + summary.duration_ms = u64::try_from(summary.end.millis_since(summary.start)).unwrap_or(0); + summary.group_size = summary.roster.len() as u32; + for entry in &mut summary.roster { + entry.name = self.player_names.get(&entry.guid).cloned(); + } + self.summary + } +} + +/// The instance copy (zone UID) of an NPC GUID `Creature-0-----` +/// of map `instance_id`; NPCs of other maps also show up inside dungeons. +pub(crate) fn instance_copy(guid: &str, instance_id: u32) -> Option<&str> { + let mut fields = guid.split('-'); + let kind = fields.next()?; + if kind != "Creature" && kind != "Vehicle" { + return None; + } + let map = fields.nth(2)?; + let copy = fields.next()?; + (map.parse() == Ok(instance_id)).then_some(copy) +} + +/// `success` may mean "in time" or only "finished", so a completed key is told by its last +/// boss pull being a kill; the flag decides only when no pull tells. +pub(crate) fn run_outcome(end: &ChallengeModeEnd, last_pull: Option) -> Outcome { + let completed = match last_pull { + _ if end.total_time_ms == 0 => false, + Some(Outcome::Kill) => true, + Some(Outcome::Wipe) => false, + Some(Outcome::Incomplete | Outcome::Ended) | None => end.success, + }; + if completed { + Outcome::Kill + } else { + Outcome::Wipe + } +} diff --git a/crates/openlogs-index/src/scan.rs b/crates/openlogs-index/src/scan.rs index 5d59735..7b9ffa1 100644 --- a/crates/openlogs-index/src/scan.rs +++ b/crates/openlogs-index/src/scan.rs @@ -92,8 +92,8 @@ impl Indexer { self.clone().finish() } - /// The closed pulls and runs of everything fed so far that no later line can change; see - /// [`IndexBuilder::settled`]. A trailing partial line is ignored. + /// The closed pulls of everything fed so far, with the open and the left run as provisional + /// entries; see [`IndexBuilder::settled`]. A trailing partial line is ignored. pub fn settled_index(&self, settle_ms: Option) -> LogIndex { self.builder.settled(settle_ms) } diff --git a/crates/openlogs-index/tests/combat_pulls.rs b/crates/openlogs-index/tests/combat_pulls.rs index 9f2792a..fcf7105 100644 --- a/crates/openlogs-index/tests/combat_pulls.rs +++ b/crates/openlogs-index/tests/combat_pulls.rs @@ -1,5 +1,7 @@ +mod common; + +use common::{Unit, died, hit, ts}; use openlogs_index::{CombatPull, FightSummary, Indexer, Outcome, index_bytes}; -use openlogs_parser::Timestamp; /// Open world in Tirisfal Glades: the logging rogue kills one Vile Fin Minor Oracle while /// players outside the group fight Puddlejumpers and Mongrels around them. @@ -43,27 +45,6 @@ const WOLF: Unit = Unit { flags: "0x1111", }; -struct Unit { - guid: &'static str, - name: &'static str, - flags: &'static str, -} - -fn hit(ts: &str, source: &Unit, target: &Unit, amount: u64) -> String { - let (s, t) = (source, target); - format!( - "{ts} SPELL_DAMAGE,{},\"{}\",{},0x80000000,{},\"{}\",{},0x80000000,44425,\"Arcane Barrage\",0x40,{},0000000000000000,1000,50000000,0,0,0,0,0,0,1,0,0,0,1590.00,-3.00,2308,1.0000,80,{amount},{amount},-1,64,0,0,0,nil,nil,nil,ST\n", - s.guid, s.name, s.flags, t.guid, t.name, t.flags, t.guid - ) -} - -fn died(ts: &str, unit: &Unit) -> String { - format!( - "{ts} UNIT_DIED,0000000000000000,nil,0x80000000,0x80000000,{},\"{}\",{},0x80000000,0\n", - unit.guid, unit.name, unit.flags - ) -} - fn buff(ts: &str) -> String { format!( "{ts} SPELL_AURA_APPLIED,{},\"{}\",{},0x80000000,{},\"{}\",{},0x80000000,774,\"Rejuvenation\",0x8,BUFF\n", @@ -71,10 +52,6 @@ fn buff(ts: &str) -> String { ) } -fn ts(text: &str) -> Timestamp { - Timestamp::parse(text).unwrap() -} - fn combat_pulls(fights: &[FightSummary]) -> Vec<&FightSummary> { fights.iter().filter(|fight| fight.is_combat()).collect() } diff --git a/crates/openlogs-index/tests/common/mod.rs b/crates/openlogs-index/tests/common/mod.rs new file mode 100644 index 0000000..bc15d68 --- /dev/null +++ b/crates/openlogs-index/tests/common/mod.rs @@ -0,0 +1,121 @@ +#![allow(dead_code)] + +use openlogs_parser::Timestamp; + +pub struct Unit { + pub guid: &'static str, + pub name: &'static str, + pub flags: &'static str, +} + +pub const RAVEL: Unit = Unit { + guid: "Player-6949-0066C9DA", + name: "Ravel-Ashwood-Normal-EU", + flags: "0x511", +}; +/// Blackrock Depths (230), instance copy 110435. +pub const GUARDSMAN: Unit = Unit { + guid: "Creature-0-5250-230-110435-8901-000016ABCD", + name: "Anvilrage Guardsman", + flags: "0xa48", +}; +pub const WARDEN: Unit = Unit { + guid: "Creature-0-5250-230-110435-8890-000016ABCE", + name: "Anvilrage Warden", + flags: "0xa48", +}; +/// Blackrock Depths (230), instance copy 54287. +pub const OTHER_COPY_GUARDSMAN: Unit = Unit { + guid: "Creature-0-5250-230-54287-8901-000016BBCD", + name: "Anvilrage Guardsman", + flags: "0xa48", +}; +/// Searing Gorge, outside the dungeon. +pub const BASILISK: Unit = Unit { + guid: "Creature-0-5250-0-29-5990-000016AAAA", + name: "Redstone Basilisk", + flags: "0xa48", +}; + +pub const BRD: u32 = 230; +pub const BRD_NAME: &str = "Blackrock Depths"; + +pub fn hit(ts: &str, source: &Unit, target: &Unit, amount: u64) -> String { + let (s, t) = (source, target); + format!( + "{ts} SPELL_DAMAGE,{},\"{}\",{},0x80000000,{},\"{}\",{},0x80000000,44425,\"Arcane Barrage\",0x40,{},0000000000000000,1000,50000000,0,0,0,0,0,0,1,0,0,0,1590.00,-3.00,2308,1.0000,80,{amount},{amount},-1,64,0,0,0,nil,nil,nil,ST\n", + s.guid, s.name, s.flags, t.guid, t.name, t.flags, t.guid + ) +} + +pub fn died(ts: &str, unit: &Unit) -> String { + format!( + "{ts} UNIT_DIED,0000000000000000,nil,0x80000000,0x80000000,{},\"{}\",{},0x80000000,0\n", + unit.guid, unit.name, unit.flags + ) +} + +pub fn zone(ts: &str, id: u32, name: &str, difficulty: u32) -> String { + format!("{ts} ZONE_CHANGE,{id},\"{name}\",{difficulty}\n") +} + +pub fn outside(ts: &str) -> String { + zone(ts, 0, "Searing Gorge", 0) +} + +pub fn boss_start(ts: &str, id: u32, name: &str, instance: u32) -> String { + format!("{ts} ENCOUNTER_START,{id},\"{name}\",1,5,{instance}\n") +} + +pub fn boss_end(ts: &str, id: u32, name: &str, success: bool) -> String { + format!( + "{ts} ENCOUNTER_END,{id},\"{name}\",1,5,{},1000\n", + u8::from(success) + ) +} + +/// A trash pack of one enemy that dies two seconds after the first hit, at `minute`. +pub fn pack(minute: u32, enemy: &Unit) -> String { + [ + hit( + &format!("11/17/2026 20:{minute:02}:10.0000"), + &RAVEL, + enemy, + 100, + ), + died(&format!("11/17/2026 20:{minute:02}:12.0000"), enemy), + ] + .concat() +} + +pub fn enter_brd(minute: u32) -> String { + zone( + &format!("11/17/2026 20:{minute:02}:00.0000"), + BRD, + BRD_NAME, + 1, + ) +} + +pub fn leave(minute: u32) -> String { + outside(&format!("11/17/2026 20:{minute:02}:00.0000")) +} + +/// Two visits of the same Blackrock Depths copy, each with one trash pack, and a fight +/// outside in between: run 1, its pack 2, the outside pull 3 and the second pack 4. +pub fn dungeon_log() -> String { + [ + enter_brd(0), + pack(0, &GUARDSMAN), + leave(1), + pack(1, &BASILISK), + enter_brd(2), + pack(2, &WARDEN), + leave(3), + ] + .concat() +} + +pub fn ts(text: &str) -> Timestamp { + Timestamp::parse(text).unwrap() +} diff --git a/crates/openlogs-index/tests/dungeon_runs.rs b/crates/openlogs-index/tests/dungeon_runs.rs new file mode 100644 index 0000000..6f9be6a --- /dev/null +++ b/crates/openlogs-index/tests/dungeon_runs.rs @@ -0,0 +1,354 @@ +mod common; + +use common::{ + BASILISK, BRD, BRD_NAME, GUARDSMAN, OTHER_COPY_GUARDSMAN, RAVEL, Unit, WARDEN, boss_end, + boss_start, died, dungeon_log, enter_brd, hit, leave, pack, ts, zone, +}; +use openlogs_index::{FightSummary, Outcome, RunKind, difficulty_label, index_bytes}; + +const MYTHIC_PLUS: &str = include_str!("fixtures/mythic_plus.txt"); + +const OTHER_MAP_CRITTER: Unit = Unit { + guid: "Creature-0-5250-1-67303-4075-000016CCCC", + name: "Rat", + flags: "0xa28", +}; + +fn entries(fights: &[FightSummary]) -> Vec<(u32, bool, Option)> { + fights + .iter() + .map(|fight| (fight.index, fight.is_run(), fight.run_index)) + .collect() +} + +fn runs(fights: &[FightSummary]) -> Vec<&FightSummary> { + fights.iter().filter(|fight| fight.is_run()).collect() +} + +fn gerstahn(minute: u32, success: bool) -> String { + [ + boss_start( + &format!("11/17/2026 20:{minute:02}:30.0000"), + 227, + "High Interrogator Gerstahn", + BRD, + ), + hit( + &format!("11/17/2026 20:{minute:02}:31.0000"), + &RAVEL, + &GUARDSMAN, + 100, + ), + boss_end( + &format!("11/17/2026 20:{minute:02}:40.0000"), + 227, + "High Interrogator Gerstahn", + success, + ), + ] + .concat() +} + +#[test] +fn a_dungeon_visit_becomes_a_run_with_its_pulls() { + let log = [ + enter_brd(0), + pack(0, &GUARDSMAN), + gerstahn(0, true), + leave(1), + ] + .concat(); + let index = index_bytes(log.as_bytes()); + assert_eq!( + entries(&index.fights), + [(1, true, None), (2, false, Some(1)), (3, false, Some(1))] + ); + let run = &index.fights[0]; + assert_eq!( + ( + run.name.as_str(), + run.difficulty, + run.instance_id, + &run.run, + run.outcome + ), + (BRD_NAME, 1, BRD, &Some(RunKind::Dungeon), Outcome::Ended) + ); + assert_eq!(index.fights[2].outcome, Outcome::Kill); + assert_eq!(run.start, ts("11/17/2026 20:00:00.0000")); + assert_eq!(run.duration_ms, 40_000); +} + +#[test] +fn the_next_visit_of_the_same_copy_continues_the_run() { + let log = [ + enter_brd(0), + pack(0, &GUARDSMAN), + leave(1), + enter_brd(2), + pack(2, &WARDEN), + leave(3), + ] + .concat(); + let index = index_bytes(log.as_bytes()); + assert_eq!( + entries(&index.fights), + [(1, true, None), (2, false, Some(1)), (3, false, Some(1))] + ); + assert_eq!(index.fights[0].duration_ms, 132_000); +} + +#[test] +fn a_visit_of_another_copy_starts_a_new_run() { + let log = [ + enter_brd(0), + pack(0, &GUARDSMAN), + leave(1), + enter_brd(2), + pack(2, &OTHER_COPY_GUARDSMAN), + leave(3), + ] + .concat(); + let index = index_bytes(log.as_bytes()); + assert_eq!( + entries(&index.fights), + [ + (1, true, None), + (2, false, Some(1)), + (3, true, None), + (4, false, Some(3)) + ] + ); +} + +#[test] +fn a_visit_without_a_fight_between_two_visits_of_the_same_copy_keeps_one_run() { + let log = [ + enter_brd(0), + pack(0, &GUARDSMAN), + leave(1), + enter_brd(2), + leave(3), + enter_brd(4), + pack(4, &WARDEN), + leave(5), + ] + .concat(); + let index = index_bytes(log.as_bytes()); + assert_eq!( + entries(&index.fights), + [(1, true, None), (2, false, Some(1)), (3, false, Some(1))] + ); +} + +#[test] +fn a_pull_outside_between_two_visits_of_the_same_copy_joins_the_run() { + let index = index_bytes(dungeon_log().as_bytes()); + assert_eq!( + entries(&index.fights), + [ + (1, true, None), + (2, false, Some(1)), + (3, false, Some(1)), + (4, false, Some(1)) + ] + ); + assert_eq!(index.fights[2].name, BASILISK.name); +} + +#[test] +fn a_pull_outside_stays_outside_when_the_next_visit_is_another_copy() { + let log = [ + enter_brd(0), + pack(0, &GUARDSMAN), + leave(1), + pack(1, &BASILISK), + enter_brd(2), + pack(2, &OTHER_COPY_GUARDSMAN), + leave(3), + ] + .concat(); + let index = index_bytes(log.as_bytes()); + assert_eq!( + entries(&index.fights), + [ + (1, true, None), + (2, false, Some(1)), + (3, false, None), + (4, true, None), + (5, false, Some(4)) + ] + ); +} + +#[test] +fn a_visit_without_a_pull_is_not_listed() { + let log = [enter_brd(0), leave(1), pack(1, &BASILISK)].concat(); + let index = index_bytes(log.as_bytes()); + assert_eq!(entries(&index.fights), [(1, false, None)]); +} + +#[test] +fn a_revisit_starting_with_a_boss_pull_starts_a_new_run() { + let log = [ + enter_brd(0), + pack(0, &GUARDSMAN), + leave(1), + enter_brd(2), + gerstahn(2, true), + leave(3), + ] + .concat(); + let index = index_bytes(log.as_bytes()); + assert_eq!( + entries(&index.fights), + [ + (1, true, None), + (2, false, Some(1)), + (3, true, None), + (4, false, Some(3)) + ] + ); +} + +#[test] +fn an_npc_of_another_map_never_decides_the_copy() { + let log = [ + enter_brd(0), + pack(0, &GUARDSMAN), + leave(1), + enter_brd(2), + died("11/17/2026 20:02:05.0000", &OTHER_MAP_CRITTER), + pack(2, &WARDEN), + leave(3), + ] + .concat(); + let index = index_bytes(log.as_bytes()); + assert_eq!(runs(&index.fights).len(), 1, "{:?}", entries(&index.fights)); +} + +/// Retail logs a key's entry as Mythic, then `CHALLENGE_MODE_START`, then Mythic+. +fn with_mythic_entry(extra_before_start: &str) -> String { + let start = MYTHIC_PLUS + .find("10/8/2026 20:00:00.0000 CHALLENGE_MODE_START") + .unwrap(); + let after_start = start + MYTHIC_PLUS[start..].find('\n').unwrap() + 1; + [ + MYTHIC_PLUS[..start].replace( + r#""Priory of the Sacred Flame",8"#, + r#""Priory of the Sacred Flame",23"#, + ), + extra_before_start.to_string(), + MYTHIC_PLUS[start..after_start].to_string(), + zone( + "10/8/2026 20:00:00.0000", + 2649, + "Priory of the Sacred Flame", + 8, + ), + MYTHIC_PLUS[after_start..].to_string(), + ] + .concat() +} + +fn without_offsets(fights: &[FightSummary]) -> Vec { + fights + .iter() + .cloned() + .map(|mut fight| { + (fight.prelude_offset, fight.start_offset, fight.end_offset) = (0, 0, 0); + fight + }) + .collect() +} + +#[test] +fn a_mythic_zero_entry_before_a_key_changes_nothing() { + let plain = index_bytes(MYTHIC_PLUS.as_bytes()); + let entered = index_bytes(with_mythic_entry("").as_bytes()); + assert_eq!( + without_offsets(&entered.fights), + without_offsets(&plain.fights) + ); +} + +#[test] +fn a_pull_before_a_key_start_gets_a_mythic_run_that_ends_at_the_start() { + const FAELAN: Unit = Unit { + guid: "Player-4101-8E8C0182", + name: "Faelan-Emberfall-EU", + flags: "0x512", + }; + const KNIGHT: Unit = Unit { + guid: "Creature-0-3892-2649-1387-206698-0000468009", + name: "Arathi Knight", + flags: "0xa48", + }; + let trash = [ + hit("10/8/2026 19:59:51.0000", &FAELAN, &KNIGHT, 100), + died("10/8/2026 19:59:53.0000", &KNIGHT), + ] + .concat(); + let index = index_bytes(with_mythic_entry(&trash).as_bytes()); + let runs = runs(&index.fights); + assert_eq!(runs.len(), 2, "{:?}", entries(&index.fights)); + let (mythic, key) = (runs[0], runs[1]); + assert_eq!( + (&mythic.run, mythic.difficulty, mythic.outcome), + (&Some(RunKind::Dungeon), 23, Outcome::Ended) + ); + assert!(key.keystone().is_some()); + assert!(mythic.end < key.start, "{:?} {:?}", mythic.end, key.start); + assert!( + key.prelude_offset < mythic.end_offset, + "the key keeps the lines before its start in its prelude" + ); +} + +#[test] +fn a_log_ending_inside_the_dungeon_leaves_the_run_incomplete() { + let log = [enter_brd(0), pack(0, &GUARDSMAN)].concat(); + let index = index_bytes(log.as_bytes()); + assert_eq!(index.fights[0].outcome, Outcome::Incomplete); +} + +#[test] +fn only_dungeon_difficulties_open_a_run() { + for difficulty in [1, 2, 23, 24, 205] { + let log = [ + zone("11/17/2026 20:00:00.0000", BRD, BRD_NAME, difficulty), + pack(0, &GUARDSMAN), + ] + .concat(); + let index = index_bytes(log.as_bytes()); + assert_eq!( + entries(&index.fights), + [(1, true, None), (2, false, Some(1))], + "difficulty {difficulty}" + ); + } + let raid = [ + zone("11/17/2026 20:00:00.0000", 2810, "Manaforge Omega", 14), + pack(0, &GUARDSMAN), + ] + .concat(); + assert_eq!( + entries(&index_bytes(raid.as_bytes()).fights), + [(1, false, None)] + ); +} + +#[test] +fn dungeon_difficulties_have_labels() { + let labels: Vec<_> = [1, 2, 23, 24, 205].map(difficulty_label).into(); + assert_eq!( + labels, + [ + Some("Normal"), + Some("Heroic"), + Some("Mythic"), + Some("Timewalking"), + Some("Follower") + ] + ); +} diff --git a/crates/openlogs-index/tests/index_runs.rs b/crates/openlogs-index/tests/index_runs.rs index 58b670d..a84c23a 100644 --- a/crates/openlogs-index/tests/index_runs.rs +++ b/crates/openlogs-index/tests/index_runs.rs @@ -70,7 +70,7 @@ fn a_run_is_indexed_with_its_key_its_roster_and_its_prelude() { ) ); assert_eq!( - run.challenge, + run.keystone().cloned(), Some(ChallengeMode { challenge_mode_id: 499, keystone_level: 12, @@ -182,7 +182,7 @@ fn a_run_without_end_lasts_to_the_end_of_the_file() { (run.outcome, run.duration_ms, run.end_offset), (Outcome::Incomplete, 300_000, data.len() as u64) ); - assert_eq!(run.challenge.as_ref().unwrap().total_time_ms, None); + assert_eq!(run.keystone().unwrap().total_time_ms, None); assert_eq!(index.fights[1].run_index, Some(1)); } @@ -230,7 +230,7 @@ fn an_end_for_another_dungeon_does_not_close_the_run() { (run.outcome, run.end), (Outcome::Incomplete, ts("10/8/2026 20:12:00.0000")) ); - assert_eq!(run.challenge.as_ref().unwrap().total_time_ms, None); + assert_eq!(run.keystone().unwrap().total_time_ms, None); } #[test] diff --git a/crates/openlogs-index/tests/live.rs b/crates/openlogs-index/tests/live.rs index 24a7ca5..05899cc 100644 --- a/crates/openlogs-index/tests/live.rs +++ b/crates/openlogs-index/tests/live.rs @@ -1,3 +1,6 @@ +mod common; + +use common::{BASILISK, GUARDSMAN, dungeon_log, enter_brd, leave, pack, zone}; use openlogs_index::{Indexer, LogIndex, Outcome, index_bytes}; use openlogs_parser::Timestamp; @@ -70,12 +73,17 @@ fn a_snapshot_after_every_chunk_equals_indexing_the_bytes_so_far() { #[test] fn settled_entries_never_change_as_the_log_grows() { - for log in FIXTURES { + let dungeon = dungeon_log(); + for log in FIXTURES.into_iter().chain([dungeon.as_str()]) { let whole = index_bytes(log.as_bytes()); let mut indexer = Indexer::new(); for chunk in log.as_bytes().chunks(97) { indexer.feed(chunk); - for fight in indexer.settled_index(Some(SETTLE_MS)).fights { + let settled = indexer.settled_index(Some(SETTLE_MS)); + for fight in settled.fights { + if settled.provisional.contains(&fight.index) { + continue; + } assert_eq!( Some(&fight), whole.fights.iter().find(|f| f.index == fight.index) @@ -115,18 +123,53 @@ fn a_pull_settles_only_after_a_line_more_than_a_second_past_its_end() { } #[test] -fn boss_pulls_of_a_running_key_wait_for_the_key_to_end() { +fn a_running_key_is_listed_with_its_finished_boss_pulls() { let log = FIXTURES[1]; let (_, after_settling) = cuts_after_encounter_end(log, 0); - let running = indexer_after(log, after_settling); - assert!(running.settled_index(None).fights.is_empty()); + let settled = indexer_after(log, after_settling).settled_index(None); + let run = settled.fights.iter().find(|fight| fight.is_run()).unwrap(); + assert_eq!(run.outcome, Outcome::Incomplete); + assert!(settled.fights.iter().any(|fight| { + fight.run_index == Some(run.index) + && fight.encounter_id != 0 + && fight.outcome == Outcome::Kill + })); + assert_eq!(settled.provisional, [run.index]); +} + +#[test] +fn a_left_run_is_provisional_until_another_dungeon_is_entered() { + let left = dungeon_log(); + let settled = indexer_after(&left, left.len()).settled_index(None); + assert_eq!( + (settled.fights[0].outcome, settled.provisional.contains(&1)), + (Outcome::Ended, true) + ); + + let elsewhere = left + &zone("11/17/2026 20:04:00.0000", 229, "Blackrock Spire", 1); + let settled = indexer_after(&elsewhere, elsewhere.len()).settled_index(None); + assert!(settled.provisional.is_empty(), "{:?}", settled.provisional); + assert_eq!( + settled.fights[0], + index_bytes(elsewhere.as_bytes()).fights[0] + ); +} + +#[test] +fn pulls_outside_after_a_left_run_are_provisional() { + let log = [ + enter_brd(0), + pack(0, &GUARDSMAN), + leave(1), + pack(1, &BASILISK), + ] + .concat(); + let settled = indexer_after(&log, log.len()).settled_index(None); + assert_eq!(settled.provisional, [1, 3]); +} - let whole = index_bytes(log.as_bytes()); - let mut finished = Indexer::new(); - finished.feed(log.as_bytes()); - let settled = finished.settled_index(None); - assert!(settled.fights.iter().any(|fight| fight.is_run())); - assert!(settled.fights.iter().any(|fight| fight.run_index.is_some())); - assert_eq!(settled.fights, whole.fights); +#[test] +fn a_finished_index_has_no_provisional_entries() { + assert!(index_bytes(dungeon_log().as_bytes()).provisional.is_empty()); } diff --git a/crates/openlogs-index/tests/run_semantics.rs b/crates/openlogs-index/tests/run_semantics.rs index dea96a4..3fa46a7 100644 --- a/crates/openlogs-index/tests/run_semantics.rs +++ b/crates/openlogs-index/tests/run_semantics.rs @@ -191,7 +191,7 @@ fn a_run_result_follows_its_logged_time_then_its_last_boss_pull_then_its_success assert_eq!( ( run.outcome, - run.challenge.as_ref().unwrap().total_time_ms, + run.keystone().unwrap().total_time_ms, run.duration_ms ), (outcome, Some(total_ms), 600_000), @@ -212,8 +212,8 @@ fn a_repeated_start_of_the_same_key_continues_the_run_and_its_open_pull() { (before.start, before.end, before.duration_ms) ); assert_eq!( - (&run.challenge, &run.roster), - (&before.challenge, &before.roster) + (run.keystone(), &run.roster), + (before.keystone(), &before.roster) ); let offset = |prefix: &str| RECONNECT.find(prefix).unwrap() as u64; assert_eq!( @@ -312,7 +312,7 @@ fn the_last_pull_keeps_its_kill_when_its_end_follows_the_run_end_in_the_same_mom ( run.end, run.duration_ms, - run.challenge.as_ref().unwrap().total_time_ms + run.keystone().unwrap().total_time_ms ), (ts("10/8/2026 20:07:00.0000"), 420_000, Some(420_000)) ); diff --git a/crates/openlogs-service/src/log_dto.rs b/crates/openlogs-service/src/log_dto.rs index ee3d23a..0196c0f 100644 --- a/crates/openlogs-service/src/log_dto.rs +++ b/crates/openlogs-service/src/log_dto.rs @@ -87,10 +87,26 @@ impl From for GameDto { } } -/// Key details of a Mythic+ run row. +/// A run row: a Mythic+ key or a dungeon visit. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct RunDto { + /// Set for a Mythic+ run. + pub key: Option, + pub instance_id: u32, + /// Bosses with a killed boss pull in the run, each counted once. + pub killed_bosses: u32, + /// The log is still being written inside the run, so the row changes as it grows. + pub running: bool, + /// A later line may still change the row: the run is running, or was left and a later + /// visit may continue it. + pub provisional: bool, +} + +/// Key details of a Mythic+ run row. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct KeyDto { pub challenge_mode_id: u32, pub keystone_level: u32, /// Raw IDs until curated affix names exist. @@ -110,7 +126,7 @@ pub struct CombatDto { pub enemy_count: u32, } -/// A boss pull, a combat pull or a whole Mythic+ run; all open the same way by `index`. +/// A boss pull, a combat pull or a whole run; all open the same way by `index`. #[derive(Debug, Clone, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct FightRow { @@ -125,7 +141,7 @@ pub struct FightRow { pub player_count: u32, pub start_unix_ms: i64, pub zone: Option, - /// Set when the row is a whole Mythic+ run; its boss pulls are rows of their own. + /// Set when the row is a whole run; its pulls are rows of their own. pub run: Option, /// `index` of the run this boss or combat pull belongs to. pub run_index: Option, @@ -158,14 +174,15 @@ pub fn unix_ms(timestamp: Timestamp) -> i64 { timestamp.0.div_euclid(1_000) } -/// A row of the pull list. A run's result comes from the dungeon data when `dungeons` +/// A row of the pull list. A key's result comes from the dungeon data when `dungeons` /// knows its boss list, otherwise from the index. pub fn fight_row( fight: &FightSummary, - fights: &[FightSummary], + index: &LogIndex, dungeons: Option<&DungeonTable>, ) -> FightRow { - let result = run_result(fight, fights, dungeons); + let result = run_result(fight, &index.fights, dungeons); + let provisional = index.provisional.contains(&fight.index); FightRow { index: fight.index, encounter_id: fight.encounter_id, @@ -178,13 +195,19 @@ pub fn fight_row( player_count: fight.roster.len() as u32, start_unix_ms: unix_ms(fight.start), zone: fight.zone.clone(), - run: fight.challenge.as_ref().map(|challenge| RunDto { - challenge_mode_id: challenge.challenge_mode_id, - keystone_level: challenge.keystone_level, - affix_ids: challenge.affix_ids.clone(), - total_time_ms: challenge.total_time_ms, - bosses: result.bosses.map(Into::into), - timer: result.timer.map(Into::into), + run: fight.is_run().then(|| RunDto { + key: fight.keystone().map(|challenge| KeyDto { + challenge_mode_id: challenge.challenge_mode_id, + keystone_level: challenge.keystone_level, + affix_ids: challenge.affix_ids.clone(), + total_time_ms: challenge.total_time_ms, + bosses: result.bosses.map(Into::into), + timer: result.timer.map(Into::into), + }), + instance_id: fight.instance_id, + killed_bosses: result.killed_bosses, + running: provisional && fight.outcome == Outcome::Incomplete, + provisional, }), run_index: fight.run_index, combat: fight.combat.as_ref().map(|combat| CombatDto { @@ -225,7 +248,7 @@ pub fn log_view( fights: index .fights .iter() - .map(|fight| fight_row(fight, &index.fights, dungeons)) + .map(|fight| fight_row(fight, index, dungeons)) .collect(), } } diff --git a/crates/openlogs-wasm/src/engine.rs b/crates/openlogs-wasm/src/engine.rs index 2e3db09..13a7dab 100644 --- a/crates/openlogs-wasm/src/engine.rs +++ b/crates/openlogs-wasm/src/engine.rs @@ -88,7 +88,8 @@ impl Engine { } /// Re-lists the pulls of a log that grew, keeping only pulls whose end has settled; with - /// `settle_all` every closed pull counts. Loaded pulls that no longer match the log are dropped. + /// `settle_all` every closed pull counts. The open and the left run are listed as they are + /// now. Loaded pulls and runs that no longer match the log are dropped. pub fn refresh_index( &mut self, log_id: &str, diff --git a/crates/openlogs-wasm/tests/engine.rs b/crates/openlogs-wasm/tests/engine.rs index e7f2574..cdd1eff 100644 --- a/crates/openlogs-wasm/tests/engine.rs +++ b/crates/openlogs-wasm/tests/engine.rs @@ -704,12 +704,18 @@ fn opening_a_mythic_plus_log_lists_the_run_and_its_boss_pulls() { assert_eq!( run["run"], json!({ - "challengeModeId": 499, - "keystoneLevel": 12, - "affixIds": [10, 147, 9], - "totalTimeMs": 600_000, - "bosses": null, - "timer": null, + "key": { + "challengeModeId": 499, + "keystoneLevel": 12, + "affixIds": [10, 147, 9], + "totalTimeMs": 600_000, + "bosses": null, + "timer": null, + }, + "instanceId": 2649, + "killedBosses": 2, + "running": false, + "provisional": false, }) ); assert_eq!( @@ -725,6 +731,36 @@ fn opening_a_mythic_plus_log_lists_the_run_and_its_boss_pulls() { assert_eq!(view["zone"], "Priory of the Sacred Flame"); } +/// A Blackrock Depths visit: a trash pack, then High Interrogator Gerstahn killed. +const DUNGEON_VISIT: &str = "11/17/2026 20:00:00.0000 ZONE_CHANGE,230,\"Blackrock Depths\",1 +11/17/2026 20:00:10.0000 SPELL_DAMAGE,Player-6949-0066C9DA,\"Ravel-Ashwood-Normal-EU\",0x511,0x80000000,Creature-0-5250-230-110435-8901-000016ABCD,\"Anvilrage Guardsman\",0xa48,0x80000000,44425,\"Arcane Barrage\",0x40,Creature-0-5250-230-110435-8901-000016ABCD,0000000000000000,1000,50000000,0,0,0,0,0,0,1,0,0,0,1590.00,-3.00,2308,1.0000,80,100,100,-1,64,0,0,0,nil,nil,nil,ST +11/17/2026 20:00:12.0000 UNIT_DIED,0000000000000000,nil,0x80000000,0x80000000,Creature-0-5250-230-110435-8901-000016ABCD,\"Anvilrage Guardsman\",0xa48,0x80000000,0 +11/17/2026 20:00:30.0000 ENCOUNTER_START,227,\"High Interrogator Gerstahn\",1,5,230 +11/17/2026 20:00:40.0000 ENCOUNTER_END,227,\"High Interrogator Gerstahn\",1,5,1,10000 +11/17/2026 20:00:45.0000 ZONE_CHANGE,230,\"Blackrock Depths\",1 +"; + +#[test] +fn a_refresh_inside_a_dungeon_marks_the_run_running() { + let (mut engine, _) = open(""); + engine.index_feed(DUNGEON_VISIT.as_bytes()); + let view: Value = serde_json::from_str(&engine.refresh_index( + "log-1", + "WoWCombatLog-111726_200000.txt", + DUNGEON_VISIT.len() as u64, + true, + )) + .unwrap(); + let run = &view["fights"][0]; + assert_eq!( + (&run["outcome"], &run["run"]), + ( + &json!("incomplete"), + &json!({ "key": null, "instanceId": 230, "killedBosses": 1, "running": true, "provisional": true }) + ) + ); +} + /// Priory: three bosses, 1950/1560/1170 s. fn with_dungeons() -> Engine { let table = DungeonTable::from_csv( @@ -763,8 +799,11 @@ fn dungeon_data_decides_the_result_of_a_run() { let (_, view) = open_with(with_dungeons(), MYTHIC_PLUS); let run = &view["fights"][0]; assert_eq!(run["outcome"], "wipe", "Prioress Murrpray lives"); - assert_eq!(run["run"]["bosses"], json!({ "killed": 2, "total": 3 })); - assert_eq!(run["run"]["timer"], Value::Null); + assert_eq!( + run["run"]["key"]["bosses"], + json!({ "killed": 2, "total": 3 }) + ); + assert_eq!(run["run"]["key"]["timer"], Value::Null); let outcomes: Vec<_> = runs_and_boss_pulls(&view)[1..] .iter() .map(|f| f["outcome"].clone()) @@ -782,10 +821,13 @@ fn dungeon_data_decides_the_result_of_a_run() { let (_, view) = open_with(with_dungeons(), &every_boss_killed(total_ms)); assert_eq!(view["fights"][0]["outcome"], "kill"); assert_eq!( - view["fights"][0]["run"]["bosses"], + view["fights"][0]["run"]["key"]["bosses"], json!({ "killed": 3, "total": 3 }) ); - assert_eq!(view["fights"][0]["run"]["timer"], timer, "{total_ms} ms"); + assert_eq!( + view["fights"][0]["run"]["key"]["timer"], timer, + "{total_ms} ms" + ); } } From d2435eaa3550fa241ea12fced6edd67fce931a2f Mon Sep 17 00:00:00 2001 From: Shaydera Date: Fri, 20 Nov 2026 00:41:07 +0100 Subject: [PATCH 2/3] Show dungeon runs as run cards A dungeon run card shows its difficulty where a key shows its level, and its killed bosses and time. A running run is never a jump target: following stays with its pulls through a ghost run, and a shown running run is read again in place when one of its pulls arrives. --- ui/src/api/types.ts | 21 +++- ui/src/components/BossTile.tsx | 2 +- ui/src/components/PullList.tsx | 17 +++- ui/src/components/chrome/FightHeader.tsx | 6 +- ui/src/components/chrome/LiveNotice.tsx | 8 +- ui/src/components/chrome/ReportToolbar.tsx | 2 +- ui/src/components/chrome/TabBar.tsx | 2 +- ui/src/components/chrome/crumbs.ts | 6 +- ui/src/components/chrome/fightMeta.test.ts | 9 +- ui/src/components/chrome/fightMeta.ts | 14 +-- ui/src/components/overview/Timeline.tsx | 2 +- ui/src/i18n/en.ts | 8 +- ui/src/pulls/follow.test.ts | 53 +++++++++- ui/src/pulls/follow.ts | 29 ++++-- ui/src/pulls/groupPulls.test.ts | 70 ++++++++++--- ui/src/pulls/groupPulls.ts | 110 +++++++++++++-------- ui/src/store.test.ts | 24 +++++ ui/src/store.ts | 21 +++- ui/src/styles/runs.css | 6 +- ui/src/test/runFixture.ts | 40 ++++++-- 20 files changed, 339 insertions(+), 111 deletions(-) diff --git a/ui/src/api/types.ts b/ui/src/api/types.ts index 1b5eaca..61453bb 100644 --- a/ui/src/api/types.ts +++ b/ui/src/api/types.ts @@ -15,8 +15,21 @@ export type Game = { kind: 'retail' } | { kind: 'classicEra' } | { kind: 'foreve /** A completed key against its time limits (mirrors `TimerDto`). */ export type KeyTimer = { kind: 'inTime'; upgrades: number } | { kind: 'overTime' }; -/** Mythic+ details of a run row (mirrors `RunDto`). */ +/** A whole run (mirrors `RunDto`): a Mythic+ key or a dungeon visit. */ export interface RunInfo { + /** Set for a Mythic+ run. */ + key: KeyInfo | null; + instanceId: number; + /** Bosses with a killed boss pull in the run, each counted once. */ + killedBosses: number; + /** The log is still being written inside the run, so the row changes as it grows. */ + running: boolean; + /** A later line may still change the row: the run is running, or was left and a later visit may continue it. */ + provisional: boolean; +} + +/** Mythic+ details of a run row (mirrors `KeyDto`). */ +export interface KeyInfo { challengeModeId: number; keystoneLevel: number; /** Affix IDs as logged; shown raw until curated names exist. */ @@ -35,7 +48,7 @@ export interface CombatInfo { enemyCount: number; } -/** A boss pull, a combat pull when `combat` is set, or a whole Mythic+ run when `run` is set; all open by `index`. */ +/** A boss pull, a combat pull when `combat` is set, or a whole run when `run` is set; all open by `index`. */ export interface FightRow { index: number; encounterId: number; @@ -49,7 +62,7 @@ export interface FightRow { playerCount: number; startUnixMs: number; zone: string | null; - /** Set when this row is a whole Mythic+ run; its boss pulls are rows of their own. */ + /** Set when this row is a whole run; its pulls are rows of their own. */ run: RunInfo | null; /** Log index of the run this boss or combat pull belongs to. */ runIndex: number | null; @@ -105,7 +118,7 @@ export interface Kpis { } export interface Phase { - /** `trash`: time between the boss pulls of a Mythic+ run. */ + /** `trash`: time between the boss pulls of a run. */ kind: 'boss' | 'intermission' | 'trash'; number: number; startMs: number; diff --git a/ui/src/components/BossTile.tsx b/ui/src/components/BossTile.tsx index 5d086f4..95e6cde 100644 --- a/ui/src/components/BossTile.tsx +++ b/ui/src/components/BossTile.tsx @@ -4,7 +4,7 @@ import { bossMonogram } from '../monogram'; /** * The boss's Encounter Journal portrait, else a monogram tile — also for - * Mythic+ runs, whose rows have no encounter (0). `large` is the Overview header's portrait. + * runs, whose rows have no encounter (0). `large` is the Overview header's portrait. */ export function BossTile({ encounterId, name, large = false }: { encounterId: number; name: string; large?: boolean }) { const src = useIconSrc(encounterId > 0 ? bossIcon(encounterId) : null); diff --git a/ui/src/components/PullList.tsx b/ui/src/components/PullList.tsx index aa4ac4d..68b0012 100644 --- a/ui/src/components/PullList.tsx +++ b/ui/src/components/PullList.tsx @@ -1,6 +1,6 @@ import { useId, useState } from 'react'; import type { PullSet } from '../api/types'; -import { formatClock, formatDuration, formatInteger, formatKeystoneLevel, formatPercent } from '../i18n/format'; +import { formatClock, formatDuration, formatInteger, formatPercent } from '../i18n/format'; import { t } from '../i18n/i18n'; import { type BossGroup, @@ -189,9 +189,16 @@ export function CombatPullList({ pulls, onOpen }: { pulls: CombatPullView[]; onO ); } -/** Bosses killed of the dungeon's list as a bar and `3/3`; empty and `—` without dungeon data. */ +/** Bosses killed of the dungeon's list as a bar and `3/3`; empty and `—` without dungeon data. A dungeon visit has no boss list: `2 bosses killed`. */ function RunProgress({ run }: { run: RunView }) { - const bosses = run.bosses; + if (run.key === null) { + return ( + + {t('runs.bossesKilled', { count: run.killedBosses })} + + ); + } + const bosses = run.key.bosses; const width = bosses !== null && bosses.total > 0 ? (bosses.killed / bosses.total) * 100 : 0; const fill = bosses === null ? 'fill-abort' : run.status === 'completed' ? 'fill-kill' : 'fill-wipe'; return ( @@ -263,12 +270,12 @@ interface RunProps { onOpen: (fightIndex: number) => void; } -/** One card per Mythic+ run, built like a boss card: the first row opens the whole run, the boss pulls and the folded combat pulls follow. */ +/** One card per run, built like a boss card: the first row opens the whole run, the boss pulls and the folded combat pulls follow. */ export function RunCards({ runs, onOpen }: RunProps) { return ( <> {runs.map((run) => { - const level = formatKeystoneLevel(run.keystoneLevel); + const level = run.badge; return (
diff --git a/ui/src/components/chrome/FightHeader.tsx b/ui/src/components/chrome/FightHeader.tsx index a432df6..6adadce 100644 --- a/ui/src/components/chrome/FightHeader.tsx +++ b/ui/src/components/chrome/FightHeader.tsx @@ -1,8 +1,8 @@ import { Fragment, type RefObject } from 'react'; import type { FightRow, LogView, PullSet } from '../../api/types'; -import { formatDuration, formatKeystoneLevel } from '../../i18n/format'; +import { formatDuration } from '../../i18n/format'; import { t } from '../../i18n/i18n'; -import { PULL_CHIP, RUN_CHIP, isCombatPull, moreEnemies, pullStatus, runStatus } from '../../pulls/groupPulls'; +import { PULL_CHIP, RUN_CHIP, isCombatPull, moreEnemies, pullStatus, runBadge, runStatus } from '../../pulls/groupPulls'; import { BossTile } from '../BossTile'; import { CombatName } from '../CombatName'; import { Kpi, KpiStrip } from '../Kpi'; @@ -17,7 +17,7 @@ import type { HeaderTile } from './headerTiles'; function fightIdentity(row: FightRow): Pick { const run = row.run; const status = pullStatus(row); - const title = run ? t('runs.heading', { dungeon: row.name, level: formatKeystoneLevel(run.keystoneLevel) }) : row.name; + const title = run ? t('runs.heading', { dungeon: row.name, level: runBadge({ ...row, run }) }) : row.name; const chip = run ? { className: RUN_CHIP[runStatus(row)], label: t(`runs.status.${runStatus(row)}`) } : { className: PULL_CHIP[status], label: t(`status.${status}`) }; diff --git a/ui/src/components/chrome/LiveNotice.tsx b/ui/src/components/chrome/LiveNotice.tsx index 50c006f..fa90c7e 100644 --- a/ui/src/components/chrome/LiveNotice.tsx +++ b/ui/src/components/chrome/LiveNotice.tsx @@ -1,5 +1,5 @@ import { useEffect } from 'react'; -import { formatInteger, formatShare } from '../../i18n/format'; +import { formatShare } from '../../i18n/format'; import { t } from '../../i18n/i18n'; import type { LiveNotice as Notice } from '../../pulls/follow'; import { spokenCombatName } from '../../pulls/groupPulls'; @@ -9,11 +9,7 @@ const NOTICE_MS = 4000; function message(notice: Notice): string { if (notice.kind === 'run') { - return t('live.runLoaded', { - dungeon: notice.dungeon, - level: formatInteger(notice.keystoneLevel), - result: t(`runs.status.${notice.status}`), - }); + return t('live.runLoaded', { run: notice.heading, result: t(`runs.status.${notice.status}`) }); } const label = t(`status.${notice.status}`); if (notice.kind === 'combat') return t('live.combatLoaded', { pull: spokenCombatName(notice.name, notice.moreEnemies), result: label }); diff --git a/ui/src/components/chrome/ReportToolbar.tsx b/ui/src/components/chrome/ReportToolbar.tsx index b073183..f7aa3f1 100644 --- a/ui/src/components/chrome/ReportToolbar.tsx +++ b/ui/src/components/chrome/ReportToolbar.tsx @@ -5,7 +5,7 @@ import { DeathCutoffChip } from './DeathCutoffChip'; import { OptionsMenu } from './OptionsMenu'; import { ViewSwitch } from './ViewSwitch'; -/** The row under the tabs: whose view and which source at the start, the options menu, view switch and replay toggle at the end; the replay has none of them, a whole Mythic+ run no replay. */ +/** The row under the tabs: whose view and which source at the start, the options menu, view switch and replay toggle at the end; the replay has none of them, a whole run no replay. */ export function ReportToolbar() { const tab = useApp((s) => s.tab); const withReplay = useApp(replayOffered); diff --git a/ui/src/components/chrome/TabBar.tsx b/ui/src/components/chrome/TabBar.tsx index f4c5b4e..5540f44 100644 --- a/ui/src/components/chrome/TabBar.tsx +++ b/ui/src/components/chrome/TabBar.tsx @@ -26,7 +26,7 @@ const replayIcon = ( ); /** - * The fight's tab row: `lead` at its start, then the tabs with the Replay tab last; a whole Mythic+ run + * The fight's tab row: `lead` at its start, then the tabs with the Replay tab last; a whole run * has no replay. A pull set keeps the tabs it has not visible and focusable, disabled with the reason. */ export function TabBar({ lead }: { lead?: ReactNode }) { diff --git a/ui/src/components/chrome/crumbs.ts b/ui/src/components/chrome/crumbs.ts index ab2cd1a..123171f 100644 --- a/ui/src/components/chrome/crumbs.ts +++ b/ui/src/components/chrome/crumbs.ts @@ -1,7 +1,7 @@ import type { Detail, FightRow, LogView, PlayerRef, PullSet, QuickOverview } from '../../api/types'; -import { formatDuration, formatKeystoneLevel } from '../../i18n/format'; +import { formatDuration } from '../../i18n/format'; import { t } from '../../i18n/i18n'; -import { combatName, isCombatPull, moreEnemies, pullNumber, pullStatus, runStatus } from '../../pulls/groupPulls'; +import { combatName, isCombatPull, moreEnemies, pullNumber, pullStatus, runBadge, runStatus } from '../../pulls/groupPulls'; import type { FightTab, ReportData } from '../../store'; import { playerIndex, shortName, spellName } from '../overview/players'; import { setIdentity } from './fightMeta'; @@ -38,7 +38,7 @@ type Level = Omit; /** `Ula'tek · Pull #1`, a run's `Priory of the Sacred Flame +12`, a combat pull's `Venomfang Juggernaut +10`. */ function pullLabel(fights: FightRow[], row: FightRow): string { - if (row.run) return t('runs.heading', { dungeon: row.name, level: formatKeystoneLevel(row.run.keystoneLevel) }); + if (row.run) return t('runs.heading', { dungeon: row.name, level: runBadge({ ...row, run: row.run }) }); if (isCombatPull(row)) return combatName(row.name, moreEnemies(row.combat)); const n = pullNumber(fights, row); return n === null ? row.name : t('crumb.pull', { boss: row.name, n }); diff --git a/ui/src/components/chrome/fightMeta.test.ts b/ui/src/components/chrome/fightMeta.test.ts index 7f75649..8649ccf 100644 --- a/ui/src/components/chrome/fightMeta.test.ts +++ b/ui/src/components/chrome/fightMeta.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; import type { FightRow } from '../../api/types'; import { compareLogFixture } from '../../test/compareFixture'; -import { runLogFixture } from '../../test/runFixture'; +import { dungeonRunFixture, runLogFixture } from '../../test/runFixture'; import { type MetaItem, fightMeta, setIdentity, setMeta } from './fightMeta'; /** The items as text, mono ones in brackets. */ @@ -20,10 +20,15 @@ describe('fight meta line', () => { it('claims nothing a run did not log or the dungeon data does not know', () => { const run = runLogFixture.fights[0]; - const bare: FightRow = { ...run, outcome: 'incomplete', run: { ...run.run!, totalTimeMs: null, affixIds: [], bosses: null, timer: null } }; + const key = { ...run.run!.key!, totalTimeMs: null, affixIds: [], bosses: null, timer: null }; + const bare: FightRow = { ...run, outcome: 'incomplete', run: { ...run.run!, key } }; expect(read(bare)).toEqual(['[31:00]', '5 players', 'Oct 8, 2026 · 20:01']); }); + it('a dungeon run lists players, date and killed bosses', () => { + expect(read(dungeonRunFixture.fights[0])).toEqual(['[31:00]', '5 players', 'Oct 8, 2026 · 20:01', '2 bosses killed']); + }); + it('set_meta_counts_wipes_and_kills_and_sums_the_duration', () => { const set = { kind: 'all' as const, encounterId: 3492, difficulty: 15, fights: [1, 3] }; const identity = setIdentity(compareLogFixture, set); diff --git a/ui/src/components/chrome/fightMeta.ts b/ui/src/components/chrome/fightMeta.ts index 68b28c5..36ecbe7 100644 --- a/ui/src/components/chrome/fightMeta.ts +++ b/ui/src/components/chrome/fightMeta.ts @@ -36,15 +36,17 @@ export function fightMeta(row: FightRow): MetaItem[] { return items.filter((item): item is MetaItem => item !== null); } -/** A Mythic+ run: timer and bosses only from the dungeon data, never from the log alone. */ +/** A Mythic+ run: timer and bosses only from the dungeon data, never from the log alone. A dungeon visit: its killed bosses. */ function runFacts(row: FightRow, run: RunInfo): (MetaItem | null)[] { + const common = [fact(t('fight.players', { count: row.playerCount })), fact(formatDateTime(row.startUnixMs))]; + const key = run.key; + if (key === null) return [...common, fact(t('runs.bossesKilled', { count: run.killedBosses }))]; return [ - fact(t('fight.players', { count: row.playerCount })), - fact(formatDateTime(row.startUnixMs)), + ...common, // An abandoned key logs 0; that is no time worth showing. - run.totalTimeMs ? fact(t('runs.loggedTime', { time: formatDuration(run.totalTimeMs) })) : null, - ...runProgress(run).map((part) => fact(part)), - run.affixIds.length > 0 ? fact(t('runs.affixes', { ids: run.affixIds.join(', ') })) : null, + key.totalTimeMs ? fact(t('runs.loggedTime', { time: formatDuration(key.totalTimeMs) })) : null, + ...runProgress(key).map((part) => fact(part)), + key.affixIds.length > 0 ? fact(t('runs.affixes', { ids: key.affixIds.join(', ') })) : null, ]; } diff --git a/ui/src/components/overview/Timeline.tsx b/ui/src/components/overview/Timeline.tsx index 67d7f11..b198383 100644 --- a/ui/src/components/overview/Timeline.tsx +++ b/ui/src/components/overview/Timeline.tsx @@ -13,7 +13,7 @@ import { TIMELINE_VIEW_BOX, percentOf, timelineGeometry, timelineSummary } from /** * The Overview's timeline and its range brush: drag to select, click a phase (or its * label) to select it, the accent handles are sliders for the keyboard. It always draws the whole pull; - * the range filters what lies below. `run`: a whole Mythic+ run, which has no boss HP line; its boss + * the range filters what lies below. `run`: a whole run, which has no boss HP line; its boss * pulls are the named phases. */ export function Timeline({ overview, run = false }: { overview: QuickOverview; run?: boolean }) { diff --git a/ui/src/i18n/en.ts b/ui/src/i18n/en.ts index f2262d6..1e3cfe0 100644 --- a/ui/src/i18n/en.ts +++ b/ui/src/i18n/en.ts @@ -68,7 +68,7 @@ export const en = { 'combat.moreTitle': { one: '{count} more enemy fought', other: '{count} more enemies fought' }, 'combat.named': '{name} {more}', 'combat.open': 'Open combat pull {pull}, {result} after {duration}, started {start}', - 'runs.title': 'Mythic+ runs', + 'runs.title': 'Dungeon runs', 'runs.run': 'Run', 'runs.chipInTime': 'In time +{upgrades} · {duration}', 'runs.chipOverTime': 'Over time · {duration}', @@ -79,6 +79,8 @@ export const en = { 'runs.status.completed': 'Completed', 'runs.status.notCompleted': 'Not completed', 'runs.status.incomplete': 'Incomplete', + 'runs.status.ended': 'Ended', + 'runs.status.running': 'Running', 'runs.bossPulls': { one: '{count} boss pull', other: '{count} boss pulls' }, 'runs.combatPulls': { one: '{count} combat pull', other: '{count} combat pulls' }, 'runs.open': 'Open run {dungeon} {level}', @@ -89,6 +91,8 @@ export const en = { 'runs.inTime': 'In time +{upgrades}', 'runs.overTime': 'Over time', 'runs.bosses': { one: '{killed}/{count} boss', other: '{killed}/{count} bosses' }, + 'runs.bossesKilled': { one: '{count} boss killed', other: '{count} bosses killed' }, + 'runs.chipDungeon': '{status} · {duration}', 'status.kill': 'Kill', 'status.wipe': 'Wipe', 'status.aborted': 'Aborted', @@ -657,7 +661,7 @@ export const en = { 'options.liveRefreshUnavailable': 'This log cannot be followed here. Open it again, or use Chrome, Edge or the desktop app.', 'live.pullLoaded': 'Pull {n} loaded · {result}', 'live.combatLoaded': '{pull} loaded · {result}', - 'live.runLoaded': '{dungeon} +{level} loaded · {result}', + 'live.runLoaded': '{run} loaded · {result}', 'options.deathCutoff': 'Stop at player death', 'options.deathCutoffOff': 'off', 'options.deathCutoffHint': 'Every view ends at the {nth} death ({time}), as if the pull ended there. Empty = whole pull.', diff --git a/ui/src/pulls/follow.test.ts b/ui/src/pulls/follow.test.ts index 6d536e5..895db4a 100644 --- a/ui/src/pulls/follow.test.ts +++ b/ui/src/pulls/follow.test.ts @@ -23,7 +23,14 @@ function fight(index: number, outcome: FightRow['outcome'], durationMs: number, }; } -const RUN: RunInfo = { challengeModeId: 505, keystoneLevel: 12, affixIds: [10, 9], totalTimeMs: 0, bosses: null, timer: null }; +const RUN: RunInfo = { + key: { challengeModeId: 505, keystoneLevel: 12, affixIds: [10, 9], totalTimeMs: 0, bosses: null, timer: null }, + instanceId: 2287, + killedBosses: 0, + running: false, + provisional: false, +}; +const DUNGEON: RunInfo = { key: null, instanceId: 230, killedBosses: 2, running: false, provisional: false }; const wipe = (index: number) => fight(index, 'wipe', 120_000); const kill = (index: number) => fight(index, 'kill', 300_000); @@ -82,7 +89,41 @@ describe('followUpdate shown pull', () => { it('flags a shown pull that is no longer listed', () => { const before = [wipe(10), wipe(20)]; const update = followUpdate(before, [wipe(10)], shown(20), true, false); - expect(update).toEqual({ jumpTo: null, set: null, shownVanished: true }); + expect(update).toEqual({ jumpTo: null, set: null, shownVanished: true, reload: false }); + }); +}); + +describe('followUpdate running run', () => { + /** Running inside, left but possibly going on after a ghost run, or final. */ + const brd = (durationMs: number, state: 'running' | 'left' | 'final') => + fight(1, state === 'running' ? 'incomplete' : 'ended', durationMs, { + run: { ...DUNGEON, running: state === 'running', provisional: state !== 'final' }, + name: 'Blackrock Depths', + encounterId: 0, + }); + const gerstahn = fight(2, 'wipe', 12_000, { runIndex: 1, encounterId: 227 }); + const roccor = fight(3, 'kill', 40_000, { runIndex: 1, encounterId: 228 }); + + it('a running run is never a jump target', () => { + const update = followUpdate([brd(100_000, 'running'), gerstahn], [brd(200_000, 'running'), gerstahn], shown(2), true, false); + expect([update.jumpTo, update.reload]).toEqual([null, false]); + }); + + it('stays on a shown running run and reloads it when one of its pulls arrives', () => { + const before = [brd(100_000, 'running'), gerstahn]; + expect(followUpdate(before, [brd(200_000, 'running'), gerstahn, roccor], shown(1), true, false)).toMatchObject({ jumpTo: null, reload: true }); + expect(followUpdate(before, [brd(200_000, 'running'), gerstahn], shown(1), true, false)).toMatchObject({ jumpTo: null, reload: false }); + }); + + it('stays on the newest pull through a ghost run and follows the next boss pull of the run', () => { + const left = followUpdate([brd(100_000, 'running'), gerstahn], [brd(110_000, 'left'), gerstahn], shown(2), true, false); + expect(left.jumpTo).toBeNull(); + const back = followUpdate([brd(110_000, 'left'), gerstahn], [brd(300_000, 'running'), gerstahn, roccor], shown(2), true, false); + expect(back.jumpTo).toBe(3); + }); + + it('jumps to a dungeon run once it is final', () => { + expect(followUpdate([brd(100_000, 'left'), gerstahn], [brd(100_000, 'final'), gerstahn], shown(2), true, false).jumpTo).toBe(1); }); }); @@ -122,7 +163,13 @@ describe('liveNoticeOf', () => { it('describes a run', () => { const fights = [fight(5, 'incomplete', 600_000, { run: RUN, name: 'Halls of Atonement' })]; - expect(liveNoticeOf(fights, 5)).toEqual({ kind: 'run', dungeon: 'Halls of Atonement', keystoneLevel: 12, status: 'incomplete' }); + expect(liveNoticeOf(fights, 5)).toEqual({ kind: 'run', heading: 'Halls of Atonement +12', status: 'incomplete' }); + }); + + it('describes a dungeon run', () => { + const brd = { run: DUNGEON, name: 'Blackrock Depths', difficulty: 1, difficultyLabel: 'Normal' }; + const fights = [fight(5, 'ended', 600_000, brd)]; + expect(liveNoticeOf(fights, 5)).toEqual({ kind: 'run', heading: 'Blackrock Depths Normal', status: 'ended' }); }); it('names a combat pull after its enemies', () => { diff --git a/ui/src/pulls/follow.ts b/ui/src/pulls/follow.ts index 4e3534d..3e21820 100644 --- a/ui/src/pulls/follow.ts +++ b/ui/src/pulls/follow.ts @@ -1,6 +1,7 @@ import type { FightRow, PullSet } from '../api/types'; import type { View } from '../store'; -import { isAborted, isCombatPull, isGroupedBossPull, moreEnemies, pullNumber, pullStatus, runStatus, type PullStatus, type RunStatus } from './groupPulls'; +import { t } from '../i18n/i18n'; +import { isAborted, isCombatPull, isGroupedBossPull, moreEnemies, pullNumber, pullStatus, runBadge, runStatus, type PullStatus, type RunStatus } from './groupPulls'; export interface FollowUpdate { /** Pull or run the view moves to; `null` = stay. */ @@ -9,25 +10,36 @@ export interface FollowUpdate { set: PullSet | null; /** The shown pull is no longer listed (an in-progress pull hidden once the log grows). */ shownVanished: boolean; + /** The shown run is still running and one of its pulls arrived: read it again where it is. */ + reload: boolean; } export type LiveNotice = | { kind: 'pull'; n: number; status: PullStatus; bossHpPercent: number | null } | { kind: 'combat'; name: string; moreEnemies: number; status: PullStatus } - | { kind: 'run'; dungeon: string; keystoneLevel: number; status: RunStatus }; + | { kind: 'run'; heading: string; status: RunStatus }; -/** Follows only to rows of the kind shown, or to any while the shown row is unknown: reading a boss pull, new trash never pulls the view away. */ +/** + * Follows only to rows of the kind shown, or to any while the shown row is unknown: reading a boss pull, new trash never pulls the view away. + * A run arrives only once it is final: a left one may go on after a ghost run, so following stays with its pulls. + */ export function followUpdate(before: FightRow[], after: FightRow[], view: View, hideAborted: boolean, comparing: boolean): FollowUpdate { const known = new Map(before.map((fight) => [fight.index, fight])); const isNew = (fight: FightRow) => { const old = known.get(fight.index); - return old === undefined || old.outcome !== fight.outcome || old.durationMs !== fight.durationMs; + return ( + old === undefined || old.outcome !== fight.outcome || old.durationMs !== fight.durationMs || old.run?.provisional !== fight.run?.provisional + ); }; const isVisible = (fight: FightRow) => fight.run !== null || !(hideAborted && isAborted(fight)); - const arrived = after.filter((fight) => isNew(fight) && isVisible(fight)); + const arrived = after.filter((fight) => isNew(fight) && isVisible(fight) && !fight.run?.provisional); let jumpTo: number | null = null; - if (view.kind === 'fight' && !comparing) { + let reload = false; + const shownRunning = view.kind === 'fight' && after.some((fight) => fight.index === view.fightIndex && fight.run?.running); + if (view.kind === 'fight' && shownRunning) { + reload = arrived.some((fight) => fight.runIndex === view.fightIndex); + } else if (view.kind === 'fight' && !comparing) { const shownRow = known.get(view.fightIndex); const combatShown = shownRow !== undefined && isCombatPull(shownRow); const ofShownKind = (fight: FightRow) => isCombatPull(fight) === combatShown; @@ -45,7 +57,7 @@ export function followUpdate(before: FightRow[], after: FightRow[], view: View, const shownVanished = view.kind === 'fight' && jumpTo === null && known.has(view.fightIndex) && !present.has(view.fightIndex); const unchanged = new Set(after.filter((fight) => !isNew(fight)).map((fight) => fight.index)); - return { jumpTo, set: view.kind === 'set' ? grownSet(view.set, unchanged, arrived) : null, shownVanished }; + return { jumpTo, set: view.kind === 'set' ? grownSet(view.set, unchanged, arrived) : null, shownVanished, reload }; } function newest(fights: FightRow[]): FightRow | null { @@ -72,7 +84,8 @@ export function liveNoticeOf(fights: FightRow[], index: number): LiveNotice { const fight = fights.find((candidate) => candidate.index === index); if (!fight) throw new Error(`No pull with index ${index}`); if (fight.run !== null) { - return { kind: 'run', dungeon: fight.name, keystoneLevel: fight.run.keystoneLevel, status: runStatus(fight) }; + const heading = t('runs.heading', { dungeon: fight.name, level: runBadge({ ...fight, run: fight.run }) }); + return { kind: 'run', heading, status: runStatus(fight) }; } if (isCombatPull(fight)) return { kind: 'combat', name: fight.name, moreEnemies: moreEnemies(fight.combat), status: pullStatus(fight) }; return { kind: 'pull', n: pullNumber(fights, fight)!, status: pullStatus(fight), bossHpPercent: fight.bossHpPercent }; diff --git a/ui/src/pulls/groupPulls.test.ts b/ui/src/pulls/groupPulls.test.ts index f87d401..030391e 100644 --- a/ui/src/pulls/groupPulls.test.ts +++ b/ui/src/pulls/groupPulls.test.ts @@ -7,13 +7,14 @@ import { pullStatus, pullView, rangeKey, + runBadge, runChipLabel, runProgress, runStatus, runSubtitle, type RunView, } from './groupPulls'; -import { runLogFixture } from '../test/runFixture'; +import { dungeonRunFixture, runLogFixture } from '../test/runFixture'; let next = 1; function fight( @@ -177,7 +178,7 @@ describe('combat pulls', () => { it('run card lists trash between boss pulls and still counts only boss pulls', () => { const MPLUS = { difficulty: 8, difficultyLabel: 'Mythic+', playerCount: 5 }; - const info: RunInfo = { challengeModeId: 499, keystoneLevel: 12, affixIds: [], totalTimeMs: 600_000, bosses: null, timer: null }; + const info = keyRun({ affixIds: [] }); const run = fight('Priory of the Sacred Flame', 0, 'kill', 600_000, null, { ...MPLUS, run: info }); const inRun = { ...MPLUS, runIndex: run.index }; const log = [ @@ -218,7 +219,7 @@ describe('comparable pulls', () => { }); describe('Mythic+ runs', () => { - const RUN: RunInfo = { challengeModeId: 499, keystoneLevel: 12, affixIds: [10, 147, 9], totalTimeMs: 600_000, bosses: null, timer: null }; + const RUN = keyRun(); const MPLUS = { difficulty: 8, difficultyLabel: 'Mythic+', playerCount: 5 }; const RUN_LOG = [ fight("Ula'tek", 3492, 'kill', 478_610, 0, { index: 101 }), @@ -230,18 +231,18 @@ describe('Mythic+ runs', () => { fight('Priory of the Sacred Flame', 0, 'incomplete', 90_000, null, { ...MPLUS, index: 107, - run: { ...RUN, keystoneLevel: 13, totalTimeMs: null }, + run: keyRun({ keystoneLevel: 13, totalTimeMs: null }), }), fight('Captain Dailcry', 2847, 'wipe', 45_000, 40, { ...MPLUS, index: 108, runIndex: 107 }), ]; it('lists each run with its boss pulls numbered within the run and its dungeon data', () => { const runs = groupRuns(RUN_LOG, true); - expect(runs.map((run) => [run.index, run.dungeon, run.keystoneLevel, run.status, run.pullCount, run.bosses, run.timer])).toEqual([ - [102, 'Priory of the Sacred Flame', 12, 'completed', 4, null, null], - [107, 'Priory of the Sacred Flame', 13, 'incomplete', 1, null, null], + expect(runs.map((run) => [run.index, run.dungeon, run.badge, run.status, run.pullCount, run.key?.bosses, run.key?.timer])).toEqual([ + [102, 'Priory of the Sacred Flame', '+12', 'completed', 4, null, null], + [107, 'Priory of the Sacred Flame', '+13', 'incomplete', 1, null, null], ]); - expect(runs[0].affixIds).toEqual([10, 147, 9]); + expect(runs[0].key?.affixIds).toEqual([10, 147, 9]); const bossPulls = (run: RunView) => run.entries.flatMap((entry) => (entry.kind === 'boss' ? [entry.pull] : [])); expect(bossPulls(runs[0]).map((pull) => [pull.index, pull.n, pull.name, pull.status])).toEqual([ [103, 1, 'Captain Dailcry', 'kill'], @@ -251,9 +252,9 @@ describe('Mythic+ runs', () => { expect(bossPulls(groupRuns(RUN_LOG, false)[0]).map((pull) => pull.n)).toEqual([1, 2, 3, 4]); expect(groupRuns(LOG, false)).toEqual([]); - const known: RunInfo = { ...RUN, bosses: { killed: 3, total: 3 }, timer: { kind: 'inTime', upgrades: 2 } }; + const known = keyRun({ bosses: { killed: 3, total: 3 }, timer: { kind: 'inTime', upgrades: 2 } }); const [run] = groupRuns([{ ...RUN_LOG[1], run: known }], false); - expect([run.bosses, run.timer]).toEqual([{ killed: 3, total: 3 }, { kind: 'inTime', upgrades: 2 }]); + expect([run.key?.bosses, run.key?.timer]).toEqual([{ killed: 3, total: 3 }, { kind: 'inTime', upgrades: 2 }]); }); it('keeps runs and their boss pulls out of the boss groups and comparisons, with saved ranges per dungeon', () => { @@ -276,13 +277,52 @@ describe('Mythic+ runs', () => { describe('run cards', () => { it("shows the logged key time, not an abandoned key's 0, with the result and the dungeon data", () => { const [run] = groupRuns(runLogFixture.fights, true); - expect(run.loggedMs).toBe(1_859_624); - const abandoned = { ...runLogFixture.fights[0], run: { ...runLogFixture.fights[0].run!, totalTimeMs: 0 } }; - expect(groupRuns([abandoned], true)[0].loggedMs).toBeNull(); + const key = run.key!; + expect(key.loggedMs).toBe(1_859_624); + const abandoned = { ...runLogFixture.fights[0], run: keyRun({ totalTimeMs: 0 }) }; + expect(groupRuns([abandoned], true)[0].key?.loggedMs).toBeNull(); expect(runSubtitle(run)).toBe('3/3 bosses · 5 boss pulls · Affixes 10, 147, 9'); - expect(runSubtitle({ ...run, bosses: null, affixIds: [] })).toBe('5 boss pulls'); - const chips = [run, { ...run, timer: { kind: 'overTime' as const } }, { ...run, timer: null, loggedMs: null }, { ...run, status: 'notCompleted' as const }]; + expect(runSubtitle({ ...run, key: { ...key, bosses: null, affixIds: [] } })).toBe('5 boss pulls'); + const chips = [ + run, + { ...run, key: { ...key, timer: { kind: 'overTime' as const } } }, + { ...run, key: { ...key, timer: null, loggedMs: null } }, + { ...run, status: 'notCompleted' as const }, + ]; expect(chips.map(runChipLabel)).toEqual(['In time +1 · 30:59', 'Over time · 30:59', 'Completed · 31:00', 'Not completed']); }); }); + +describe('dungeon runs', () => { + it('groups a dungeon run with its pulls and counts its killed bosses', () => { + const [run] = groupRuns(dungeonRunFixture.fights, false); + expect([run.dungeon, run.badge, run.key, run.killedBosses, run.status]).toEqual(['Blackrock Depths', 'Normal', null, 2, 'ended']); + expect(run.entries.map((entry) => (entry.kind === 'boss' ? entry.pull.index : entry.pulls.map((pull) => pull.index)))).toEqual([[2], 3, 4]); + expect(runSubtitle(run)).toBe('2 bosses killed · 2 boss pulls'); + expect(runChipLabel(run)).toBe('Ended · 31:00'); + }); + + it('a running run has the running status', () => { + const [row] = dungeonRunFixture.fights; + const running = { ...row, outcome: 'incomplete' as const, run: { ...row.run!, running: true, provisional: true } }; + expect(runStatus(running)).toBe('running'); + expect(runChipLabel(groupRuns([running], false)[0])).toBe('Running'); + }); + + it('a dungeon run keeps its saved range per dungeon and difficulty', () => { + const [row] = dungeonRunFixture.fights; + expect(rangeKey(row)).toBe('dungeon:230:1'); + expect(runBadge({ ...row, run: row.run! })).toBe('Normal'); + }); +}); + +function keyRun(key: Partial> = {}): RunInfo { + return { + key: { challengeModeId: 499, keystoneLevel: 12, affixIds: [10, 147, 9], totalTimeMs: 600_000, bosses: null, timer: null, ...key }, + instanceId: 2649, + killedBosses: 0, + running: false, + provisional: false, + }; +} diff --git a/ui/src/pulls/groupPulls.ts b/ui/src/pulls/groupPulls.ts index fdd4b0b..408f5c7 100644 --- a/ui/src/pulls/groupPulls.ts +++ b/ui/src/pulls/groupPulls.ts @@ -1,5 +1,5 @@ -import type { BossProgress, CombatInfo, FightRow, KeyTimer, PullSet, PullSetKind, RunInfo } from '../api/types'; -import { formatDuration, formatInteger, formatSeconds } from '../i18n/format'; +import type { BossProgress, CombatInfo, FightRow, KeyInfo, KeyTimer, PullSet, PullSetKind, RunInfo } from '../api/types'; +import { formatDuration, formatInteger, formatKeystoneLevel, formatSeconds } from '../i18n/format'; import { t } from '../i18n/i18n'; /** Non-kills shorter than this are "aborted" and can be hidden. */ @@ -7,11 +7,14 @@ const ABORT_THRESHOLD_MS = 10_000; export type PullStatus = 'kill' | 'wipe' | 'ended' | 'aborted' | 'incomplete'; -/** A run's result: completed, ended without completion, or no end in the log. */ -export type RunStatus = 'completed' | 'notCompleted' | 'incomplete'; +/** + * A run's result: a key completed or not, a dungeon visit left (`ended`), the log still being + * written inside the run (`running`), or no end in the log. + */ +export type RunStatus = 'completed' | 'notCompleted' | 'ended' | 'running' | 'incomplete'; /** Chip style of a run result: completed like a kill, not completed like a wipe, no end neutral. */ -export const RUN_CHIP: Record = { completed: 'kill', notCompleted: 'wipe', incomplete: 'abort' }; +export const RUN_CHIP: Record = { completed: 'kill', notCompleted: 'wipe', ended: 'ended', running: 'abort', incomplete: 'abort' }; export const PULL_CHIP: Record = { kill: 'kill', wipe: 'wipe', incomplete: 'wipe', ended: 'ended', aborted: 'abort' }; @@ -48,7 +51,7 @@ export interface PullSetView { durationMs: number; } -/** A boss pull inside a Mythic+ run; `n` counts within the run, hidden pulls included. */ +/** A boss pull inside a run; `n` counts within the run, hidden pulls included. */ export interface RunPullView extends PullView { name: string; } @@ -71,18 +74,26 @@ export interface CombatPullView { /** A boss pull of a run card, or the combat pulls between two of them; `after` is the index of the boss pull before them, or of the run. */ export type RunEntry = { kind: 'boss'; pull: RunPullView } | { kind: 'trash'; after: number; pulls: CombatPullView[] }; -/** A Mythic+ run with its boss and combat pulls. */ -export interface RunView { - index: number; - dungeon: string; - keystoneLevel: number; +/** What a run card shows of a key besides its level. */ +export interface KeyView { affixIds: number[]; - status: RunStatus; /** From the dungeon data; `null` without it. */ bosses: BossProgress | null; timer: KeyTimer | null; /** Logged key time (`CHALLENGE_MODE_END`, penalties included); `null` without an end or for an abandoned key's 0. */ loggedMs: number | null; +} + +/** A Mythic+ run or a dungeon visit with its boss and combat pulls. */ +export interface RunView { + index: number; + dungeon: string; + /** A key's level, a dungeon visit's difficulty. */ + badge: string; + status: RunStatus; + /** `null` for a dungeon visit. */ + key: KeyView | null; + killedBosses: number; durationMs: number; playerCount: number; startUnixMs: number; @@ -134,14 +145,21 @@ export function pullViewTime(pull: PullView, durationMs = pull.durationMs): stri } export function runStatus(fight: FightRow): RunStatus { + if (fight.run?.running) return 'running'; if (fight.outcome === 'kill') return 'completed'; - return fight.outcome === 'wipe' ? 'notCompleted' : 'incomplete'; + if (fight.outcome === 'wipe') return 'notCompleted'; + return fight.outcome === 'ended' ? 'ended' : 'incomplete'; +} + +/** `+12` for a key, `Normal` for a dungeon visit: what follows the dungeon in a run's heading. */ +export function runBadge(row: FightRow & { run: RunInfo }): string { + return row.run.key ? formatKeystoneLevel(row.run.key.keystoneLevel) : difficultyName(row); } /** Difficulty ID of Mythic+ keystone dungeons. */ const MYTHIC_PLUS_DIFFICULTY = 8; -/** What boss groups, sets and comparisons are made of: boss pulls outside Mythic+ runs. */ +/** What boss groups, sets and comparisons are made of: boss pulls outside runs. */ export function isGroupedBossPull(fight: FightRow): boolean { return fight.run === null && fight.runIndex === null && !isCombatPull(fight); } @@ -150,7 +168,7 @@ export function difficultyName(fight: Pick(); for (const fight of fights) { @@ -200,16 +218,17 @@ function pullSets(boss: Pick, pulls: Pul })); } -/** Combat pulls outside Mythic+ runs in log order; `groupRuns` lists those inside a run. */ +/** Combat pulls outside runs in log order; `groupRuns` lists those inside a run. */ export function combatPulls(fights: FightRow[], hideAborted: boolean): CombatPullView[] { return fights.filter(isCombatPull).filter((fight) => fight.runIndex === null && !(hideAborted && isAborted(fight))).map(toCombatView); } -/** Mythic+ runs in log order, each with its boss pulls numbered within the run and the combat pulls between them. */ +/** Runs in log order, each with its boss pulls numbered within the run and the combat pulls between them. */ export function groupRuns(fights: FightRow[], hideAborted: boolean): RunView[] { return fights.flatMap((fight) => { const run = fight.run; if (run === null) return []; + const key = run.key; const numbered = runBossPulls(fights, fight.index); const entries: RunEntry[] = []; for (const pull of fights) { @@ -223,12 +242,10 @@ export function groupRuns(fights: FightRow[], hideAborted: boolean): RunView[] { { index: fight.index, dungeon: fight.name, - keystoneLevel: run.keystoneLevel, - affixIds: run.affixIds, + badge: runBadge({ ...fight, run }), status: runStatus(fight), - bosses: run.bosses, - timer: run.timer, - loggedMs: run.totalTimeMs || null, + key: key && { affixIds: key.affixIds, bosses: key.bosses, timer: key.timer, loggedMs: key.totalTimeMs || null }, + killedBosses: run.killedBosses, durationMs: fight.durationMs, playerCount: fight.playerCount, startUnixMs: fight.startUnixMs, @@ -243,7 +260,7 @@ export function groupRuns(fights: FightRow[], hideAborted: boolean): RunView[] { * What the dungeon data tells about a run, e.g. `In time +2` and `3/3 bosses`; nothing * without it, so no time is ever claimed from the log alone. */ -export function runProgress(run: Pick): string[] { +export function runProgress(run: Pick): string[] { const timer = run.timer === null ? null @@ -254,34 +271,41 @@ export function runProgress(run: Pick): string[] { return [timer, bosses].filter((part): part is string => part !== null); } -/** Subtitle of a run card, e.g. `3/3 bosses · 5 boss pulls · Affixes 10, 147, 9`; affix IDs stay raw until curated names exist. */ +/** + * Subtitle of a run card, e.g. `3/3 bosses · 5 boss pulls · Affixes 10, 147, 9`, a dungeon visit's + * `2 bosses killed · 3 boss pulls`; affix IDs stay raw until curated names exist. + */ export function runSubtitle(run: RunView): string { + const key = run.key; + if (key === null) return [t('runs.bossesKilled', { count: run.killedBosses }), t('runs.bossPulls', { count: run.pullCount })].join(' · '); return [ - run.bosses === null ? null : t('runs.bosses', { killed: formatInteger(run.bosses.killed), count: run.bosses.total }), + key.bosses === null ? null : t('runs.bosses', { killed: formatInteger(key.bosses.killed), count: key.bosses.total }), t('runs.bossPulls', { count: run.pullCount }), - run.affixIds.length > 0 ? t('runs.affixes', { ids: run.affixIds.join(', ') }) : null, + key.affixIds.length > 0 ? t('runs.affixes', { ids: key.affixIds.join(', ') }) : null, ] .filter((part): part is string => part !== null) .join(' · '); } -/** The one time a run card shows: the logged key time when the log has one, else the fight's length. */ -export function runTimeMs(run: Pick): number { - return run.loggedMs ?? run.durationMs; +/** The one time a run card shows: the logged key time when the log has one, else the run's length. */ +export function runTimeMs(run: Pick): number { + return run.key?.loggedMs ?? run.durationMs; } /** * Result chip of a run card, like a boss card's "Kill 6:05": `In time +1 · 30:59`, `Over time · 34:10`, - * `Completed · 31:00` (no dungeon data), else the status alone. The time is the logged key time when - * the log has one. + * `Completed · 31:00` (no dungeon data), a left dungeon visit's `Ended · 31:00`, else the status + * alone. The time is the logged key time when the log has one. */ -export function runChipLabel(run: Pick): string { - if (run.status !== 'completed') return t(`runs.status.${run.status}`); +export function runChipLabel(run: Pick): string { const duration = formatDuration(runTimeMs(run)); - if (run.timer === null) return t('runs.chipCompleted', { duration }); - return run.timer.kind === 'inTime' - ? t('runs.chipInTime', { upgrades: formatInteger(run.timer.upgrades), duration }) - : t('runs.chipOverTime', { duration }); + if (run.key === null && run.status === 'ended') { + return t('runs.chipDungeon', { status: t('runs.status.ended'), duration }); + } + if (run.status !== 'completed') return t(`runs.status.${run.status}`); + const timer = run.key?.timer ?? null; + if (timer === null) return t('runs.chipCompleted', { duration }); + return timer.kind === 'inTime' ? t('runs.chipInTime', { upgrades: formatInteger(timer.upgrades), duration }) : t('runs.chipOverTime', { duration }); } function toView(fight: FightRow, n: number): PullView { @@ -313,12 +337,16 @@ function toCombatView(fight: FightRow & { combat: CombatInfo }): CombatPullView }; } -/** Key of saved ranges: per boss and difficulty, per dungeon for a Mythic+ run; `null` for a combat pull, which keeps none. */ +/** + * Key of saved ranges: per boss and difficulty, per key dungeon for a Mythic+ run, per dungeon and + * difficulty for a dungeon visit; `null` for a combat pull, which keeps none. + */ export function rangeKey(fight: FightRow): string | null { if (isCombatPull(fight)) return null; - return fight.run ? `run:${fight.run.challengeModeId}` : `${fight.encounterId}:${fight.difficulty}`; + if (fight.run === null) return `${fight.encounterId}:${fight.difficulty}`; + return fight.run.key ? `run:${fight.run.key.challengeModeId}` : `dungeon:${fight.run.instanceId}:${fight.difficulty}`; } -/** Pulls of one boss and difficulty outside Mythic+, numbered as in the pull list (hidden pulls count). */ +/** Pulls of one boss and difficulty outside runs, numbered as in the pull list (hidden pulls count). */ function bossPulls(fights: FightRow[], boss: Pick): PullView[] { return fights .filter((fight) => isGroupedBossPull(fight) && fight.encounterId === boss.encounterId && fight.difficulty === boss.difficulty) @@ -346,7 +374,7 @@ export function pullView(fights: FightRow[], index: number): PullView | null { /** * Pulls `current` can be compared with: same boss and difficulty, not aborted, not itself. - * Comparison stays with boss pulls outside Mythic+, so runs, their boss pulls and combat pulls get none. + * Comparison stays with boss pulls outside runs, so runs, their boss pulls and combat pulls get none. */ export function comparablePulls(fights: FightRow[], current: FightRow): PullView[] { // Mythic+ boss pulls stay out, also when their run is missing (logging started mid-key). diff --git a/ui/src/store.test.ts b/ui/src/store.test.ts index ba1da0c..3a2276e 100644 --- a/ui/src/store.test.ts +++ b/ui/src/store.test.ts @@ -1661,6 +1661,30 @@ describe('live refresh', () => { expect(s).toMatchObject({ overview: overviewFixture, overviewCutoff: 3, report: { tab: 'deaths', data: deathsReportFixture }, timeline: timelineFixture }); }); + it('reads a shown running run again where it is when one of its pulls arrives', async () => { + const run = (durationMs: number): FightRow => ({ + ...wipe(1), + name: 'Blackrock Depths', + encounterId: 0, + outcome: 'incomplete', + durationMs, + run: { key: null, instanceId: 230, killedBosses: 0, running: true, provisional: true }, + }); + const inRun = (index: number): FightRow => ({ ...wipe(index), runIndex: 1 }); + const RUNNING: LogView = { ...LOG, fights: [run(600_000), inRun(2)] }; + vi.mocked(api.openLog).mockResolvedValue(RUNNING); + await useApp.getState().openLog(chosen(RUNNING)); + await useApp.getState().openFight(1); + await useApp.getState().setRange({ startMs: 0, endMs: 60_000 }); + vi.mocked(api.quickOverview).mockClear(); + vi.mocked(api.followLog).mockResolvedValueOnce({ ...RUNNING, fights: [run(900_000), inRun(2), inRun(3)] }); + await vi.advanceTimersByTimeAsync(2000); + const s = useApp.getState(); + expect([s.view, s.range, s.liveNotice]).toEqual([{ kind: 'fight', fightIndex: 1 }, { startMs: 0, endMs: 60_000 }, null]); + expect(api.quickOverview).toHaveBeenCalledWith(RUNNING.id, 1, WHOLE_PULL); + expect(s.overview).toEqual(overviewFixture); + }); + it('leaves a viewer of an older pull where they are', async () => { await useApp.getState().openLog(chosen(LIVE)); await useApp.getState().openFight(1); diff --git a/ui/src/store.ts b/ui/src/store.ts index dbf9820..ba3c939 100644 --- a/ui/src/store.ts +++ b/ui/src/store.ts @@ -121,12 +121,12 @@ function showsWholeRun({ log, view }: Pick): boolean { return log?.fights.find((fight) => fight.index === fightIndex)?.run != null; } -/** Whole Mythic+ runs and pull sets have no replay; the boss pulls inside runs have one. */ +/** Whole runs and pull sets have no replay; the boss pulls inside runs have one. */ export function replayOffered(s: Pick): boolean { return s.view.kind !== 'set' && !showsWholeRun(s); } -/** Whole Mythic+ runs have no death cutoff; a set cuts each of its pulls at its own death. */ +/** Whole runs have no death cutoff; a set cuts each of its pulls at its own death. */ export function cutoffOffered(s: Pick): boolean { return !showsWholeRun(s); } @@ -1154,6 +1154,7 @@ function showGrownLog(get: () => Store, set: SetState, grown: LogView) { const update = followUpdate(log.fights, grown.fights, view, hideAborted, comparison !== null); set({ log: grown }); if (update.jumpTo !== null) void followToFight(get, set, update.jumpTo); + else if (update.reload && view.kind === 'fight') void rereadShownFight(get, set, view.fightIndex); else if (update.set) void followSet(get, set, update.set); else if (update.shownVanished) get().backToPulls(); } @@ -1186,6 +1187,22 @@ async function followToFight(get: () => Store, set: SetState, fightIndex: number if (request === fightRequest && get().overview) await loadReport(get, set); } +/** Reads the shown run again as the log grew, leaving tab, range, filters and detail pages where they are. */ +async function rereadShownFight(get: () => Store, set: SetState, fightIndex: number) { + const { log } = get(); + if (!log) return; + const request = fightRequest; + const filter = reportFilter({ ...get(), range: null }); + try { + const overview = await api.quickOverview(log.id, fightIndex, filter); + if (request !== fightRequest) return; + set({ overview, overviewCutoff: filter.deathCutoff }); + await loadReport(get, set); + } catch { + // The next arriving pull reads it again; what is shown stays. + } +} + /** Shows the open set with its changed pulls; its figures are read again, overview included. */ async function followSet(get: () => Store, set: SetState, grown: PullSet) { set({ view: { kind: 'set', set: grown } }); diff --git a/ui/src/styles/runs.css b/ui/src/styles/runs.css index fa58403..ef614d0 100644 --- a/ui/src/styles/runs.css +++ b/ui/src/styles/runs.css @@ -1,4 +1,4 @@ -/* Mythic+ runs: boss-style cards; the grid's first row opens the whole run. */ +/* Runs: boss-style cards; the grid's first row opens the whole run. */ /* "Not completed" (about 105px) needs a wider Result column than the boss cards' 92px. */ .run-card .pull { grid-template-columns: 44px 120px 64px minmax(120px, 1fr) 70px 64px 20px; @@ -46,3 +46,7 @@ .pull-fold .chevron.chevron-open { transform: rotate(90deg); } +.run-killed { + font-size: 13px; + color: var(--text-soft); +} diff --git a/ui/src/test/runFixture.ts b/ui/src/test/runFixture.ts index 37ca6e1..1512e5b 100644 --- a/ui/src/test/runFixture.ts +++ b/ui/src/test/runFixture.ts @@ -2,12 +2,18 @@ import type { FightRow, LogView, RunInfo } from '../api/types'; /** 30:59.6 against the real limits 32:30 / 26:00 / 19:30: in time +1. */ const PRIORY: RunInfo = { - challengeModeId: 499, - keystoneLevel: 12, - affixIds: [10, 147, 9], - totalTimeMs: 1_859_624, - bosses: { killed: 3, total: 3 }, - timer: { kind: 'inTime', upgrades: 1 }, + key: { + challengeModeId: 499, + keystoneLevel: 12, + affixIds: [10, 147, 9], + totalTimeMs: 1_859_624, + bosses: { killed: 3, total: 3 }, + timer: { kind: 'inTime', upgrades: 1 }, + }, + instanceId: 2649, + killedBosses: 3, + running: false, + provisional: false, }; function row( @@ -72,3 +78,25 @@ export const runLogFixture: LogView = { }), ], }; + +const BRD = { difficulty: 1, difficultyLabel: 'Normal', zone: 'Blackrock Depths' }; + +/** A Blackrock Depths Normal visit (log index 1), left after a combat pull and two boss kills. */ +export const dungeonRunFixture: LogView = { + ...runLogFixture, + id: 'WoWCombatLog-111726_200000.txt', + fileName: 'WoWCombatLog-111726_200000.txt', + game: { kind: 'forever' }, + zone: 'Blackrock Depths', + startUnixMs: Date.UTC(2026, 9, 8, 20, 1), + fights: [ + row(1, 'Blackrock Depths', 0, 'ended', 1_860_000, null, { + ...BRD, + run: { key: null, instanceId: 230, killedBosses: 2, running: false, provisional: false }, + runIndex: null, + }), + row(2, 'Anvilrage Guardsman', 0, 'kill', 12_000, null, { ...BRD, combat: { enemyCount: 2 } }), + row(3, 'High Interrogator Gerstahn', 227, 'kill', 12_000, 0, BRD), + row(4, 'Lord Roccor', 228, 'kill', 40_000, 0, BRD), + ], +}; From c5f5aa44ae6ba098a307f4c232d4e7424096f293 Mon Sep 17 00:00:00 2001 From: Shaydera Date: Fri, 20 Nov 2026 00:58:31 +0100 Subject: [PATCH 3/3] Space the timeline ticks of long runs --- ui/src/components/overview/timelineGeometry.test.ts | 7 +++++++ ui/src/components/overview/timelineGeometry.ts | 12 ++++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/ui/src/components/overview/timelineGeometry.test.ts b/ui/src/components/overview/timelineGeometry.test.ts index 0012161..a233107 100644 --- a/ui/src/components/overview/timelineGeometry.test.ts +++ b/ui/src/components/overview/timelineGeometry.test.ts @@ -38,6 +38,13 @@ describe('timelineGeometry', () => { ]); }); + it('spaces the ticks of a long run so their labels never crowd', () => { + const labels = (durationMs: number) => timelineGeometry(base, durationMs).ticks.map((tick) => tick.label); + expect(labels(40 * 60_000)).toHaveLength(40); + expect(labels(125 * 60_000).slice(0, 3)).toEqual(['0:00', '5:00', '10:00']); + expect(labels(125 * 60_000).length).toBeLessThanOrEqual(40); + }); + it('numbers a boss pulled twice in a run but leaves repeated raid phase names plain', () => { const run: Phase[] = [ { kind: 'trash', number: 1, startMs: 0, endMs: 60_000, name: null }, diff --git a/ui/src/components/overview/timelineGeometry.ts b/ui/src/components/overview/timelineGeometry.ts index 11fc71b..8220f19 100644 --- a/ui/src/components/overview/timelineGeometry.ts +++ b/ui/src/components/overview/timelineGeometry.ts @@ -114,10 +114,18 @@ export function dpsAreaPath( return [`M ${first} ${scale.height}`, ...line.map(([px, py]) => `L ${px} ${py}`), `L ${last} ${scale.height}`, 'Z'].join(' '); } -/** A tick on every full minute of the axis but its very end, where the label would hang past the plot. */ +const TICK_STEPS_MINUTES = [1, 2, 5, 10, 15, 30, 60]; +const MAX_TICKS = 40; + +/** + * A tick on every full minute of the axis but its very end, where the label would hang past the plot; + * a long run gets every 2nd, 5th, … minute so it keeps at most 40 labels. + */ export function minuteTicks(axisMs: number): { leftPct: number; label: string }[] { + const stepMs = + 60_000 * (TICK_STEPS_MINUTES.find((minutes) => Math.ceil(axisMs / (minutes * 60_000)) <= MAX_TICKS) ?? TICK_STEPS_MINUTES.at(-1)!); const ticks: { leftPct: number; label: string }[] = []; - for (let ms = 0; ms === 0 || ms < axisMs; ms += 60_000) { + for (let ms = 0; ms === 0 || ms < axisMs; ms += stepMs) { ticks.push({ leftPct: percentOf(ms, axisMs), label: formatDuration(ms) }); } return ticks;