feat(analysis): what komorebi believed, and what changed

A komorebi `State` is read into monitors, workspaces and windows through each
flavor's rules, and what changed between two states is said in terms a person
would use. `at`, `range`, `summary` and `locate` ask what the recording holds
around a video time, and the other way round, with the text and JSON the later
commands share.
This commit is contained in:
LGUG2Z committed 2026-10-27 22:22:56 -07:00
1 parent af6e332fed
commit 72419d89a2
13 files changed
+2866

No files matched your search

+6
View File
@@ -93,6 +93,12 @@ reactions: a display that is gone has its video finalized at once, one that retu
stream is started afresh after a wake. The capture backend is a trait, so that these policies are tested with a scripted
backend that docks and undocks without hardware.
## Investigating
Reading a session never needs a window: `analysis` answers each question as a plain serializable value, and the command
line and the viewer present the same answers. Every command takes `--json`, which prints an envelope with the data, its
schema, warnings, whether it was truncated and a cursor, and failures exit with a code that says what kind they were.
## Rules and the layer that enforces them
| Rule | Enforced by |
+37
View File
@@ -136,6 +136,14 @@ recorder is built so that **nothing already captured is put at risk by any of it
process. komorebi not running when recording starts is not an error either.
All of this is recorded in `recorder.jsonl`.
It is shown as the `recorder` source, right next to the log lines and trace around it:
```
komorebi-recorder at <session> 12.5 --source recorder
```
`summary` marks a second in which something changed with `recorder=N`, `locate` says which segment of each display covers
a moment (and which displays had no video then), and `frames` extracts from the right segment.
### If the recorder dies
@@ -151,6 +159,35 @@ This closes the segments that were still open (using the video files themselves
the timeline, and marks the session `recovered`. The queries tell you to do this if you point them at an unfinished
session.
## Asking questions of a session
Times are video timecodes: `12.5`, `00:12.500` or `1:02:03`. Video `00:00.000` is the first captured frame.
```
# everything within +-1s of 12.5s, grouped by source
komorebi-recorder at <session> 12.5
# one app's OS trace only, or one source
komorebi-recorder at <session> 12.5 --app Ghostty
komorebi-recorder at <session> 12.5 --source events
# a span, and a per-second digest of the whole recording
komorebi-recorder range <session> 10 15
komorebi-recorder summary <session>
# reverse: where in the video was this?
komorebi-recorder locate <session> --log-line 120
komorebi-recorder locate <session> --event-seq 7
komorebi-recorder locate <session> --utc 2026-10-26T19:43:35.062613Z
# look at the exact frame
komorebi-recorder frames <session> 12.5 14.0
```
Add `--json` to any query for machine-readable output, which is also what makes a session easy to hand to an LLM: the
generated `README.md` in every session directory explains each file and contains these commands with the session path
filled in.
## The session directory
```
+809
View File
@@ -0,0 +1,809 @@
//! The differences between two komorebi states, described the way a person would.
//!
//! A raw JSON diff of komorebi's `State` is mostly noise: a window that moved from the second
//! container to the first is a dozen changed paths. [`diff`] compares two [`Snapshot`]s and reports
//! [`Change`]s instead: a window appeared, went away, moved to another workspace or was really
//! somewhere else on screen; focus moved; a layout or a workspace changed; a monitor came or went.
//! It is a pure function of the two states: nothing is read from a session, so any two snapshots
//! can be compared, from any recording. The `diff` command, `trace` and the viewer all call it.
//!
//! # What counts as a change
//!
//! - **Windows are followed by id.** A window has moved only if its monitor, its workspace or the
//! container it is in changes, or it goes from one kind of place to another (tiled, monocle,
//! maximized, floating). Containers are compared by their id, not their index, so a container
//! that slides from index 1 to index 0 because the one before it closed is not a move, and
//! neither is switching to another tab of the same container. If one id appears in more than one
//! place in a state (see `window-in-two-places` in `crate::analysis::invariants`), the first place
//! found is the one used.
//! - **A rect must move by more than 2 points** in any of left, top, width and height to be a
//! [`Change::WindowRect`]: the accessibility API rounds, and some applications snap to whole
//! points. A window whose rect is missing from either state is never reported as having moved
//! on screen.
//! - **A reorder is one change.** If the same containers are in a different order, the result is a
//! single [`Change::ContainerOrder`] rather than a series of moves.
//! - **Monitors are matched by id** and workspaces by name, within a monitor present in both
//! states. A workspace that exists in only one of the states has no layout or order to compare.
//!
//! # Flavor
//!
//! komorebi for Mac parks a hidden window in a corner of its monitor, so a window's rect shows
//! whether it is hidden. komorebi for Windows cloaks a window where it is, so it does not. The
//! `hidden_before` and `hidden_after` flags of [`Change::WindowRect`] are therefore decided by the
//! rules of the flavor that wrote the state ([`Snapshot::is_hidden_position`]), and are always
//! `false` for a komorebi for Windows state. Nothing else here depends on the flavor.
use super::state::Focus;
use super::state::Location;
use super::state::Monitor;
use super::state::Rect;
use super::state::Snapshot;
use super::state::Window;
use schemars::JsonSchema;
use serde::Serialize;
use std::collections::BTreeMap;
/// A window rect that moved by no more than this is treated as not having moved: the accessibility
/// API rounds, and some applications snap to whole points.
const RECT_TOLERANCE: i64 = 2;
/// A window, named so that a reader can tell which one a [`Change`] is about.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub struct WindowRef {
/// The window's id in komorebi's state: a window id on a Mac, a window handle on Windows.
pub id: u64,
/// The window's title when the state was serialized.
pub title: String,
/// The program the window belongs to, as komorebi names it.
pub exe: String,
}
impl WindowRef {
fn of(window: &Window) -> Self {
Self {
id: window.id,
title: window.title.clone(),
exe: window.exe.clone(),
}
}
/// Returns the window as `exe "title" (window id)`.
#[must_use]
pub fn describe(&self) -> String {
format!("{} \"{}\" (window {})", self.exe, self.title, self.id)
}
}
/// One difference between two states, as [`diff`] reports it.
///
/// In JSON a change is an object with a `kind` field naming the variant in kebab case
/// ([`Change::kind`]) and the variant's fields beside it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum Change {
/// A monitor is in the second state and was not in the first.
MonitorAdded {
/// The display id of the monitor ([`Monitor::id`]).
monitor_id: u64,
/// The monitor's device name.
device: String,
/// The monitor's area, in global display points.
size: Rect,
},
/// A monitor was in the first state and is not in the second.
MonitorRemoved {
/// The display id of the monitor ([`Monitor::id`]).
monitor_id: u64,
/// The monitor's device name.
device: String,
},
/// A monitor is in both states but its area differs (by any amount: there is no tolerance).
MonitorResized {
/// The display id of the monitor ([`Monitor::id`]).
monitor_id: u64,
/// The area in the first state, in global display points.
from: Rect,
/// The area in the second state, in global display points.
to: Rect,
},
/// The workspace showing on a monitor changed.
WorkspaceFocus {
/// The display id of the monitor.
monitor_id: u64,
/// The name of the workspace that was showing; empty if the monitor had none.
from: String,
/// The name of the workspace that is showing; empty if the monitor has none.
to: String,
},
/// The keyboard focus moved (see [`Snapshot::focus`] for what has it).
Focus {
/// The focus before: a monitor, workspace and window; `None` if nothing had it.
from: Option<Focus>,
/// The focus after, in the same terms; `None` if nothing has it.
to: Option<Focus>,
},
/// A workspace's layout changed.
Layout {
/// The display id of the monitor the workspace is on.
monitor_id: u64,
/// The name of the workspace.
workspace: String,
/// The layout's name before, e.g. `Columns` or `BSP`.
from: String,
/// The layout's name after.
to: String,
},
/// The containers of a workspace are in a different order (window ids by container).
ContainerOrder {
/// The display id of the monitor the workspace is on.
monitor_id: u64,
/// The name of the workspace.
workspace: String,
/// The id of the first window of each container, in container order, before.
from: Vec<u64>,
/// The same list after: the same ids in another order.
to: Vec<u64>,
},
/// A window is in the second state and was not in the first.
WindowAdded {
/// The window.
window: WindowRef,
/// Where it is in the second state.
at: Location,
},
/// A window was in the first state and is not in the second.
WindowRemoved {
/// The window.
window: WindowRef,
/// Where it was in the first state.
from: Location,
},
/// Moved to another container, another kind of place, another workspace or another monitor.
WindowMoved {
/// The window.
window: WindowRef,
/// Where it was in the first state.
from: Location,
/// Where it is in the second state.
to: Location,
},
/// Really somewhere else on screen.
WindowRect {
/// The window.
window: WindowRef,
/// Where the window was in the first state, as read live from the OS.
from: Rect,
/// Where the window is in the second state, as read live from the OS.
to: Rect,
/// Whether `from` is where komorebi parks a hidden window. Always `false` for komorebi
/// for Windows, which hides a window without moving it.
hidden_before: bool,
/// Whether `to` is where komorebi parks a hidden window. Always `false` for komorebi for
/// Windows.
hidden_after: bool,
},
/// komorebi was paused or resumed.
Paused {
/// Whether komorebi is paused in the second state.
paused: bool,
},
}
impl Change {
/// Returns the kind name of the change, the same as the `kind` field of its JSON: for example
/// `window-added`.
#[must_use]
pub fn kind(&self) -> &'static str {
match self {
Self::MonitorAdded { .. } => "monitor-added",
Self::MonitorRemoved { .. } => "monitor-removed",
Self::MonitorResized { .. } => "monitor-resized",
Self::WorkspaceFocus { .. } => "workspace-focus",
Self::Focus { .. } => "focus",
Self::Layout { .. } => "layout",
Self::ContainerOrder { .. } => "container-order",
Self::WindowAdded { .. } => "window-added",
Self::WindowRemoved { .. } => "window-removed",
Self::WindowMoved { .. } => "window-moved",
Self::WindowRect { .. } => "window-rect",
Self::Paused { .. } => "paused",
}
}
/// Returns one line a person can read, such as `Safari "window 2" appeared on monitor 1
/// workspace one (container 1)`.
#[must_use]
pub fn describe(&self) -> String {
let focus = |focus: &Option<Focus>| {
focus.as_ref().map_or_else(
|| "nothing".to_string(),
|focus| {
format!(
"window {} on monitor {} workspace {}",
focus
.window_id
.map_or_else(|| "(none)".to_string(), |id| id.to_string()),
focus.monitor_id,
focus.workspace
)
},
)
};
match self {
Self::MonitorAdded {
monitor_id,
device,
size,
} => {
format!(
"monitor {monitor_id} \"{device}\" appeared, {}",
size.describe()
)
}
Self::MonitorRemoved { monitor_id, device } => {
format!("monitor {monitor_id} \"{device}\" went away")
}
Self::MonitorResized {
monitor_id,
from,
to,
} => format!(
"monitor {monitor_id} changed from {} to {}",
from.describe(),
to.describe()
),
Self::WorkspaceFocus {
monitor_id,
from,
to,
} => {
format!("monitor {monitor_id} switched from workspace {from} to {to}")
}
Self::Focus { from, to } => {
format!("focus moved from {} to {}", focus(from), focus(to))
}
Self::Layout {
monitor_id,
workspace,
from,
to,
} => format!(
"monitor {monitor_id} workspace {workspace} layout changed from {from} to {to}"
),
Self::ContainerOrder {
monitor_id,
workspace,
from,
to,
} => format!(
"monitor {monitor_id} workspace {workspace} containers reordered from {from:?} to {to:?}"
),
Self::WindowAdded { window, at } => {
format!("{} appeared on {}", window.describe(), at.describe())
}
Self::WindowRemoved { window, from } => {
format!("{} went away from {}", window.describe(), from.describe())
}
Self::WindowMoved { window, from, to } => format!(
"{} moved from {} to {}",
window.describe(),
from.describe(),
to.describe()
),
Self::WindowRect {
window,
from,
to,
hidden_before,
hidden_after,
} => {
let note = match (hidden_before, hidden_after) {
(false, true) => " (now hidden)",
(true, false) => " (now shown)",
_ => "",
};
format!(
"{} is really at {} instead of {}{note}",
window.describe(),
to.describe(),
from.describe()
)
}
Self::Paused { paused } => {
format!("komorebi {}", if *paused { "paused" } else { "resumed" })
}
}
}
}
/// Where a window sits, coarsely: it only counts as having moved if this changes. Container
/// *indexes* shift whenever a container before it comes or goes, so containers are compared by id.
fn anchor(snapshot: &Snapshot) -> BTreeMap<u64, (u64, String, String, Location, Window)> {
let mut anchors = BTreeMap::new();
for monitor in &snapshot.monitors {
for (index, workspace) in monitor.workspaces.iter().enumerate() {
let visible = index == monitor.focused;
let mut put = |window: &Window, slot: String, place: super::state::Place| {
anchors.entry(window.id).or_insert_with(|| {
(
monitor.id,
workspace.name.clone(),
slot,
Location {
monitor_id: monitor.id,
workspace: workspace.name.clone(),
place,
workspace_visible: visible,
},
window.clone(),
)
});
};
for (container_index, container) in workspace.containers.iter().enumerate() {
for (tab, window) in container.windows.iter().enumerate() {
put(
window,
format!("container {}", container.id),
super::state::Place::Container {
index: container_index,
tab,
},
);
}
}
if let Some(monocle) = &workspace.monocle {
for (tab, window) in monocle.windows.iter().enumerate() {
put(
window,
"monocle".to_string(),
super::state::Place::Monocle { tab },
);
}
}
if let Some(window) = &workspace.maximized {
put(
window,
"maximized".to_string(),
super::state::Place::Maximized,
);
}
for (index, window) in workspace.floating.iter().enumerate() {
put(
window,
"floating".to_string(),
super::state::Place::Floating { index },
);
}
}
}
anchors
}
fn is_hidden(snapshot: &Snapshot, window: &Window) -> bool {
window.rect.as_ref().is_some_and(|rect| {
snapshot
.monitor_under(rect)
.or_else(|| snapshot.monitors.first())
.is_some_and(|monitor| snapshot.is_hidden_position(rect, monitor))
})
}
fn monitor_by_id(snapshot: &Snapshot, id: u64) -> Option<&Monitor> {
snapshot.monitors.iter().find(|monitor| monitor.id == id)
}
/// Returns what changed from the state `before` to the state `after`, empty if nothing did.
///
/// The changes come in a fixed order, which tests and the text output rely on:
///
/// 1. [`Change::Paused`];
/// 2. [`Change::MonitorRemoved`] and [`Change::MonitorResized`], by monitor of `before`, then
/// [`Change::MonitorAdded`];
/// 3. for each monitor in both states, [`Change::WorkspaceFocus`], then for each of its workspaces
/// [`Change::Layout`] and [`Change::ContainerOrder`];
/// 4. [`Change::Focus`];
/// 5. for each window of `after`, in order of window id, [`Change::WindowAdded`], or else
/// [`Change::WindowMoved`] followed by [`Change::WindowRect`];
/// 6. [`Change::WindowRemoved`], for each window of `before` that is not in `after`, in order of
/// window id.
///
/// What counts as a change is described in the [module](self) documentation. The comparison cannot
/// fail and does not panic.
///
/// # Example
///
/// A second window is opened beside the first, so the first is squeezed to half the screen:
///
/// ```rust
/// use komorebi_recorder::analysis::diff::Change;
/// use komorebi_recorder::analysis::diff::diff;
/// use komorebi_recorder::analysis::flavor::Flavor;
/// use komorebi_recorder::analysis::state::Snapshot;
/// use komorebi_recorder::testkit::state_with_windows;
///
/// let before = Snapshot::parse(Flavor::Macos, &state_with_windows(&[(1, "Ghostty")]));
/// let after = Snapshot::parse(
/// Flavor::Macos,
/// &state_with_windows(&[(1, "Ghostty"), (2, "Safari")]),
/// );
///
/// let changes = diff(&before, &after);
/// let kinds: Vec<_> = changes.iter().map(Change::kind).collect();
/// assert_eq!(kinds, ["window-rect", "window-added"]);
/// assert_eq!(
/// changes[0].describe(),
/// "Ghostty \"window 1\" (window 1) is really at 500x800 at (0, 0) instead of 1000x800 at (0, 0)"
/// );
/// assert_eq!(
/// changes[1].describe(),
/// "Safari \"window 2\" (window 2) appeared on monitor 1 workspace one (container 1)"
/// );
///
/// // the same state twice has nothing to report
/// assert!(diff(&after, &after.clone()).is_empty());
/// ```
///
/// Covered in detail by the unit tests of this module, among them
/// `container_indexes_shifting_is_not_a_move`, `reordered_containers_are_one_change` and
/// `rect_jitter_within_the_tolerance_is_not_a_change`.
#[must_use]
pub fn diff(before: &Snapshot, after: &Snapshot) -> Vec<Change> {
let mut changes = Vec::new();
if before.paused != after.paused {
changes.push(Change::Paused {
paused: after.paused,
});
}
for monitor in &before.monitors {
match monitor_by_id(after, monitor.id) {
None => changes.push(Change::MonitorRemoved {
monitor_id: monitor.id,
device: monitor.device.clone(),
}),
Some(now) if now.size != monitor.size => changes.push(Change::MonitorResized {
monitor_id: monitor.id,
from: monitor.size,
to: now.size,
}),
Some(_) => {}
}
}
for monitor in &after.monitors {
if monitor_by_id(before, monitor.id).is_none() {
changes.push(Change::MonitorAdded {
monitor_id: monitor.id,
device: monitor.device.clone(),
size: monitor.size,
});
}
}
for monitor in &after.monitors {
let Some(was) = monitor_by_id(before, monitor.id) else {
continue;
};
let name = |monitor: &Monitor| {
monitor
.focused_workspace()
.map_or_else(String::new, |workspace| workspace.name.clone())
};
if name(was) != name(monitor) {
changes.push(Change::WorkspaceFocus {
monitor_id: monitor.id,
from: name(was),
to: name(monitor),
});
}
for workspace in &monitor.workspaces {
let Some(old) = was.workspaces.iter().find(|old| old.name == workspace.name) else {
continue;
};
if old.layout != workspace.layout {
changes.push(Change::Layout {
monitor_id: monitor.id,
workspace: workspace.name.clone(),
from: old.layout.clone(),
to: workspace.layout.clone(),
});
}
let order = |workspace: &super::state::Workspace| -> Vec<u64> {
workspace
.containers
.iter()
.filter_map(|container| container.windows.first().map(|window| window.id))
.collect()
};
let (old_order, new_order) = (order(old), order(workspace));
let mut old_sorted = old_order.clone();
let mut new_sorted = new_order.clone();
old_sorted.sort_unstable();
new_sorted.sort_unstable();
// the same containers, in another order: a reorder rather than adds and removes
if old_order != new_order && old_sorted == new_sorted {
changes.push(Change::ContainerOrder {
monitor_id: monitor.id,
workspace: workspace.name.clone(),
from: old_order,
to: new_order,
});
}
}
}
let (focus_before, focus_after) = (before.focus(), after.focus());
if focus_before != focus_after {
changes.push(Change::Focus {
from: focus_before,
to: focus_after,
});
}
let (was, now) = (anchor(before), anchor(after));
for (id, (monitor, workspace, slot, location, window)) in &now {
match was.get(id) {
None => changes.push(Change::WindowAdded {
window: WindowRef::of(window),
at: location.clone(),
}),
Some((old_monitor, old_workspace, old_slot, old_location, old_window)) => {
if (old_monitor, old_workspace, old_slot) != (monitor, workspace, slot) {
changes.push(Change::WindowMoved {
window: WindowRef::of(window),
from: old_location.clone(),
to: location.clone(),
});
}
if let (Some(from), Some(to)) = (&old_window.rect, &window.rect)
&& from.max_delta(to) > RECT_TOLERANCE
{
changes.push(Change::WindowRect {
window: WindowRef::of(window),
from: *from,
to: *to,
hidden_before: is_hidden(before, old_window),
hidden_after: is_hidden(after, window),
});
}
}
}
}
for (id, (_, _, _, location, window)) in &was {
if !now.contains_key(id) {
changes.push(Change::WindowRemoved {
window: WindowRef::of(window),
from: location.clone(),
});
}
}
changes
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::Value;
use serde_json::json;
fn window(id: u64, rect: Option<[i64; 4]>) -> Value {
let mut value = json!({"id": id, "details": {"title": format!("w{id}"), "exe": "app"}});
if let Some([left, top, width, height]) = rect {
value["rect"] = json!({"left": left, "top": top, "right": width, "bottom": height});
}
value
}
fn container(id: &str, windows: Vec<Value>) -> Value {
json!({"id": id, "windows": {"elements": windows, "focused": 0}})
}
fn state(workspaces: Vec<(&str, Vec<Value>, usize)>, focused_workspace: usize) -> Snapshot {
let workspaces: Vec<Value> = workspaces
.into_iter()
.map(|(name, containers, focused)| {
json!({"name": name, "layer": "Tiling", "layout": {"Default": "Columns"},
"containers": {"elements": containers, "focused": focused}})
})
.collect();
Snapshot::from_value(&json!({
"monitors": {"elements": [{
"id": 1, "device": "d",
"size": {"left": 0, "top": 0, "right": 1000, "bottom": 800},
"window_hiding_position": "BottomLeft",
"workspaces": {"elements": workspaces, "focused": focused_workspace},
}], "focused": 0}
}))
}
fn kinds(changes: &[Change]) -> Vec<&'static str> {
changes.iter().map(Change::kind).collect()
}
#[test]
fn identical_states_have_no_changes() {
let a = state(
vec![(
"one",
vec![container("a", vec![window(1, Some([0, 0, 500, 800]))])],
0,
)],
0,
);
assert!(diff(&a, &a.clone()).is_empty());
}
#[test]
fn a_window_appearing_and_focus_moving_are_described_as_such() {
let before = state(
vec![("one", vec![container("a", vec![window(1, None)])], 0)],
0,
);
let after = state(
vec![(
"one",
vec![
container("a", vec![window(1, None)]),
container("b", vec![window(2, None)]),
],
1,
)],
0,
);
let changes = diff(&before, &after);
assert_eq!(kinds(&changes), ["focus", "window-added"]);
let Change::WindowAdded { window, at } = &changes[1] else {
panic!("{changes:?}")
};
assert_eq!(window.id, 2);
assert_eq!(at.workspace, "one");
assert!(changes[1].describe().contains("w2"));
}
#[test]
fn a_window_leaving_a_workspace_is_a_move_not_an_add_and_remove() {
let before = state(
vec![
("one", vec![container("a", vec![window(1, None)])], 0),
("two", vec![], 0),
],
0,
);
let after = state(
vec![
("one", vec![], 0),
("two", vec![container("a", vec![window(1, None)])], 0),
],
0,
);
let changes = diff(&before, &after);
assert!(kinds(&changes).contains(&"window-moved"), "{changes:?}");
assert!(!kinds(&changes).contains(&"window-added"));
assert!(!kinds(&changes).contains(&"window-removed"));
}
#[test]
fn container_indexes_shifting_is_not_a_move() {
let before = state(
vec![(
"one",
vec![
container("a", vec![window(1, None)]),
container("b", vec![window(2, None)]),
],
0,
)],
0,
);
// container "a" is closed: "b" moves from index 1 to 0 but is not moved
let after = state(
vec![("one", vec![container("b", vec![window(2, None)])], 0)],
0,
);
assert_eq!(kinds(&diff(&before, &after)), ["focus", "window-removed"]);
}
#[test]
fn reordered_containers_are_one_change() {
let a = container("a", vec![window(1, None)]);
let b = container("b", vec![window(2, None)]);
let before = state(vec![("one", vec![a.clone(), b.clone()], 0)], 0);
let after = state(vec![("one", vec![b, a], 0)], 0);
let changes = diff(&before, &after);
assert!(kinds(&changes).contains(&"container-order"), "{changes:?}");
assert!(!kinds(&changes).contains(&"window-moved"));
}
#[test]
fn a_window_really_moving_on_screen_is_reported_with_hiding() {
let on = window(1, Some([0, 0, 500, 800]));
// hidden at the bottom-left sliver: right edge one point inside the monitor
let hidden = window(1, Some([-499, 790, 500, 800]));
let before = state(vec![("one", vec![container("a", vec![on])], 0)], 0);
let after = state(vec![("one", vec![container("a", vec![hidden])], 0)], 0);
let changes = diff(&before, &after);
let Change::WindowRect {
hidden_before,
hidden_after,
..
} = &changes[0]
else {
panic!("{changes:?}")
};
assert!(!hidden_before && *hidden_after);
assert!(changes[0].describe().contains("now hidden"));
}
#[test]
fn rect_jitter_within_the_tolerance_is_not_a_change() {
let before = state(
vec![(
"one",
vec![container("a", vec![window(1, Some([0, 0, 500, 800]))])],
0,
)],
0,
);
let after = state(
vec![(
"one",
vec![container("a", vec![window(1, Some([1, 0, 499, 800]))])],
0,
)],
0,
);
assert!(diff(&before, &after).is_empty());
}
#[test]
fn workspace_switches_and_monitor_changes_are_reported() {
let before = state(vec![("one", vec![], 0), ("two", vec![], 0)], 0);
let after = state(vec![("one", vec![], 0), ("two", vec![], 0)], 1);
let changes = diff(&before, &after);
assert!(matches!(
&changes[0],
Change::WorkspaceFocus { from, to, .. } if from == "one" && to == "two"
));
let docked = Snapshot::from_value(&json!({
"monitors": {"elements": [
{"id": 1, "device": "a", "size": {"left": 0, "top": 0, "right": 10, "bottom": 10}},
{"id": 2, "device": "b", "size": {"left": 10, "top": 0, "right": 10, "bottom": 10}},
], "focused": 0}
}));
let undocked = Snapshot::from_value(&json!({
"monitors": {"elements": [
{"id": 1, "device": "a", "size": {"left": 0, "top": 0, "right": 20, "bottom": 10}},
], "focused": 0}
}));
let changes = diff(&docked, &undocked);
assert_eq!(kinds(&changes), ["monitor-resized", "monitor-removed"]);
assert_eq!(
kinds(&diff(&undocked, &docked)),
["monitor-resized", "monitor-added"]
);
}
#[test]
fn pausing_is_reported() {
let mut paused = state(vec![], 0);
paused.paused = true;
let changes = diff(&state(vec![], 0), &paused);
assert_eq!(changes, [Change::Paused { paused: true }]);
assert_eq!(changes[0].describe(), "komorebi paused");
}
}
@@ -34,6 +34,8 @@ use crate::analysis::events::EventInfo;
use crate::analysis::events::EventRecord;
use crate::analysis::events::Family;
use crate::analysis::logparse::Line;
use crate::analysis::state::Monitor;
use crate::analysis::state::Rect;
use serde_json::Value;
/// The [`Rules`] of komorebi for Mac: what its events, `State`, log and modules say.
@@ -213,6 +215,20 @@ impl Rules for MacRules {
}
}
/// Whether `rect` is where komorebi parks a window it has hidden on `monitor`: with a
/// one-point sliver still inside the display, so the window stays "on screen" to macOS. The
/// vertical position is not checked, because macOS pulls a window up to keep its title bar
/// reachable.
fn is_hidden_position(&self, rect: &Rect, monitor: &Monitor) -> bool {
let tolerance = 2;
let bottom_right = monitor.hiding_position == "BottomRight";
if bottom_right {
(rect.left - (monitor.size.left + monitor.size.width - 1)).abs() <= tolerance
} else {
(rect.right_edge() - (monitor.size.left + 1)).abs() <= tolerance
}
}
fn block_header(&self, line: &Line, _open: Option<&Block>) -> Option<BlockHeader> {
match line.root_span() {
Some("process_event") if line.message.starts_with(EVENT_HEADER) => {
@@ -40,6 +40,7 @@
//! | [`window_id`](Rules::window_id) | the id a window has in `State` | `Snapshot::parse` | `id` | `hwnd` |
//! | [`window_is_unreadable`](Rules::window_is_unreadable) | whether komorebi failed to read a window | `Snapshot::parse` | the default: never | the title starts with `could not get window` |
//! | [`hides_windows_by_position`](Rules::hides_windows_by_position) | whether a window's position shows that it is hidden | `Snapshot::hides_windows_by_position` | yes: parked at a corner | no: cloaked where it is |
//! | [`is_hidden_position`](Rules::is_hidden_position) | whether a rect is where a hidden window is parked | `Snapshot::is_hidden_position` | a one-point sliver inside the display | never |
//! | [`block_header`](Rules::block_header) | whether a log line starts a handler's block | `blocks::build` | the `processing event:` and `processing command:` lines | the first line of a `process_event{...}` or `process_command{...}` span whose fields differ from the open block's |
//! | [`is_block_end`](Rules::is_block_end) | whether a log line ends a handler's block | `blocks::build` | `processed command: ...`, for commands only | `processed: ...` for events, `processed` for commands |
//! | [`slow_handler_cause`](Rules::slow_handler_cause) | what a slow handler was probably doing | the `overview` and `trace` answers | accessibility calls | Win32 calls |
@@ -78,6 +79,10 @@
//! that komorebi made up ended a real drag.
//! 1. `blocks::build` walks the log: `block_header` for every line, and
//! `is_block_end` for every line inside an open block.
//! 1. `Snapshot::parse` reads each `State`, asking [`window_id`](Rules::window_id) and
//! [`window_is_unreadable`](Rules::window_is_unreadable) for every window. The snapshot keeps
//! its flavor for [`hides_windows_by_position`](Rules::hides_windows_by_position) and
//! `is_hidden_position`.
//!
//! [`MacRules`]: mac::MacRules
//! [`WindowsRules`]: windows::WindowsRules
@@ -94,6 +99,8 @@ use super::classify::Class;
use super::events::EventInfo;
use super::events::EventRecord;
use super::logparse::Line;
use super::state::Monitor;
use super::state::Rect;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
@@ -340,6 +347,7 @@ pub struct BlockHeader {
/// # use komorebi_recorder::analysis::flavor::mac::MacRules;
/// # use komorebi_recorder::analysis::flavor::{BlockHeader, Flavor, Rules};
/// # use komorebi_recorder::analysis::logparse::Line;
/// # use komorebi_recorder::analysis::state::{Monitor, Rect};
/// # use serde_json::Value;
/// struct Unchecked;
///
@@ -353,6 +361,9 @@ pub struct BlockHeader {
/// fn classify_window_manager(&self, event: &EventRecord) -> (Class, &'static str) {
/// MacRules.classify_window_manager(event)
/// }
/// fn is_hidden_position(&self, rect: &Rect, monitor: &Monitor) -> bool {
/// MacRules.is_hidden_position(rect, monitor)
/// }
/// fn block_header(&self, line: &Line, open: Option<&Block>) -> Option<BlockHeader> {
/// MacRules.block_header(line, open)
/// }
@@ -382,6 +393,7 @@ pub struct BlockHeader {
/// # use komorebi_recorder::analysis::flavor::mac::MacRules;
/// # use komorebi_recorder::analysis::flavor::{BlockHeader, Flavor, Rules};
/// # use komorebi_recorder::analysis::logparse::Line;
/// # use komorebi_recorder::analysis::state::{Monitor, Rect};
/// # use serde_json::Value;
/// struct Unchecked;
///
@@ -395,6 +407,9 @@ pub struct BlockHeader {
/// fn classify_window_manager(&self, event: &EventRecord) -> (Class, &'static str) {
/// MacRules.classify_window_manager(event)
/// }
/// fn is_hidden_position(&self, rect: &Rect, monitor: &Monitor) -> bool {
/// MacRules.is_hidden_position(rect, monitor)
/// }
/// fn block_header(&self, line: &Line, open: Option<&Block>) -> Option<BlockHeader> {
/// MacRules.block_header(line, open)
/// }
@@ -515,6 +530,14 @@ pub trait Rules: Sync {
/// komorebi acted, into an echo itself.
fn classify_window_manager(&self, event: &EventRecord) -> (Class, &'static str);
/// Returns whether `rect` is where komorebi parks a window it has hidden on `monitor`.
///
/// `rect` is the window's rect as the `State` has it and `monitor` is the monitor the window is
/// on. komorebi for Mac parks a hidden window with a one-point sliver still inside the
/// display and the rules compare the horizontal position only, within 2 points. komorebi for
/// Windows does not park windows, so its answer is always `false`.
fn is_hidden_position(&self, rect: &Rect, monitor: &Monitor) -> bool;
/// Returns the header of the handler's block that `line` starts, or `None` if `line` does not
/// start one.
///
@@ -35,6 +35,8 @@ use crate::analysis::events::EventInfo;
use crate::analysis::events::EventRecord;
use crate::analysis::events::Family;
use crate::analysis::logparse::Line;
use crate::analysis::state::Monitor;
use crate::analysis::state::Rect;
use serde_json::Value;
/// The [`Rules`] of komorebi for Windows: what its events, `State`, log and modules say.
@@ -244,6 +246,11 @@ impl Rules for WindowsRules {
false
}
fn is_hidden_position(&self, _rect: &Rect, _monitor: &Monitor) -> bool {
// a cloaked window is exactly where it was; nothing in the state says it is hidden
false
}
fn block_header(&self, line: &Line, open: Option<&Block>) -> Option<BlockHeader> {
let kind = match line.root_span()? {
"process_event" => BlockKind::Event,
+123
View File
@@ -0,0 +1,123 @@
//! [`Lookup`] over the files of a session, without opening it for analysis.
//!
//! A `TimeSpec` such as `event:12+1s` or `bug:a-3f9c1e02.end` names a moment by pointing at
//! something the session recorded, and resolving it asks a [`Lookup`] when that thing happened.
//! `Analysis` is one, but opening an `Analysis` refuses a session that is still being recorded
//! and parses the events and the log up front. [`SessionLookup`] reads only the file each question
//! needs, so it works on a session that is still recording: `annotate` uses it to mark a bug region
//! while the recording goes on.
//!
//! It answers differently from `Analysis` about the start of an event: see [`SessionLookup`].
use super::envelope;
use super::timespec::Edge;
use super::timespec::Lookup;
use crate::annotations;
use crate::incidents::INCIDENTS_FILE;
use crate::incidents::Incident;
use crate::session::Manifest;
use crate::session::Session;
use crate::timeline;
use crate::timeline::Locator;
use color_eyre::eyre;
/// A [`Lookup`] that reads the files of a session as they are asked about.
///
/// Every question reads its file again from the start (`events.jsonl`, `komorebi.log`,
/// `recorder.jsonl` or the annotations), which suits resolving the handful of times a command line
/// names, and not resolving many. Every failure to find what is asked for is reported with the
/// not-found exit kind and a message saying what is missing.
///
/// # Difference from `Analysis`
///
/// [`Edge`] is ignored for an event: `event:12` and `event:12.end` both resolve to the moment the
/// notification was received, which is when komorebi had finished handling it. `Analysis`
/// resolves `event:12` (the start edge) to when the handler began, where komorebi's log shows it.
///
///
/// # Example
///
/// ```rust
/// use komorebi_recorder::analysis::lookup::SessionLookup;
/// use komorebi_recorder::analysis::timespec::Edge;
/// use komorebi_recorder::analysis::timespec::Lookup;
/// use komorebi_recorder::analysis::timespec::TimeSpec;
/// use komorebi_recorder::testkit::SessionBuilder;
/// use serde_json::json;
///
/// let (session, manifest) = SessionBuilder::new("doc-session-lookup")
/// .event(2.0, json!({"type": "Retile"}), None)
/// .incident(4.0, "display-disconnected", "display 2")
/// .build();
/// let lookup = SessionLookup::new(&session, &manifest);
///
/// // one second after event 1 was received
/// let moment = "event:1+1s".parse::<TimeSpec>()?.resolve(&manifest, &lookup)?;
/// assert!((moment.video_s - 3.0).abs() < 1e-6);
///
/// // both edges of an event are when it was received
/// assert_eq!(
/// lookup.event_mach_ns(1, Edge::Start)?,
/// lookup.event_mach_ns(1, Edge::End)?
/// );
///
/// // incidents are numbered from 1
/// assert!(lookup.incident_mach_ns(1).is_ok());
/// assert!(lookup.incident_mach_ns(2).is_err());
/// assert!(lookup.event_mach_ns(99, Edge::End).is_err());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// Used end to end, against real files, by
/// `tests/annotate.rs::a_bug_can_be_marked_relative_to_an_event_and_edited_and_deleted` and
/// `tests/annotate.rs::annotating_works_on_a_session_that_is_still_recording`.
pub struct SessionLookup<'a> {
/// The session whose files are read.
pub session: &'a Session,
/// The session's manifest, which maps the master clock to video time.
pub manifest: &'a Manifest,
}
impl<'a> SessionLookup<'a> {
/// Returns a lookup over `session`, whose manifest is `manifest`.
#[must_use]
pub fn new(session: &'a Session, manifest: &'a Manifest) -> Self {
Self { session, manifest }
}
fn located(&self, locator: &Locator) -> eyre::Result<u64> {
timeline::locate(self.session, self.manifest, locator)
.map(|located| located.mach_ns)
.map_err(|error| envelope::not_found(format!("{error:#}")))
}
}
impl Lookup for SessionLookup<'_> {
fn event_mach_ns(&self, seq: u64, _edge: Edge) -> eyre::Result<u64> {
self.located(&Locator::EventSeq(seq))
}
fn log_mach_ns(&self, line: u64) -> eyre::Result<u64> {
self.located(&Locator::LogLine(line))
}
fn incident_mach_ns(&self, number: u64) -> eyre::Result<u64> {
let text = std::fs::read_to_string(self.session.path(INCIDENTS_FILE))
.map_err(|_| envelope::not_found("the session recorded no incidents"))?;
let index = usize::try_from(number.saturating_sub(1)).unwrap_or(usize::MAX);
text.lines()
.nth(index)
.filter(|_| number >= 1)
.and_then(|line| serde_json::from_str::<Incident>(line).ok())
.map(|incident| incident.mach_ns)
.ok_or_else(|| envelope::not_found(format!("there is no incident {number}")))
}
fn annotation_span(&self, id: &str) -> eyre::Result<(u64, Option<u64>)> {
let loaded = annotations::load(&self.session.dir)?;
loaded
.get(id)
.map(|annotation| (annotation.start_mach_ns, annotation.end_mach_ns))
.ok_or_else(|| envelope::not_found(format!("there is no annotation {id}")))
}
}
+3
View File
@@ -8,10 +8,13 @@
pub mod blocks;
pub mod classify;
pub mod diff;
pub mod envelope;
pub mod events;
pub mod flavor;
pub mod guard;
pub mod ids;
pub mod logparse;
pub mod lookup;
pub mod state;
pub mod timespec;
+876
View File
@@ -0,0 +1,876 @@
//! komorebi's `State`, as a model that can be asked questions.
//!
//! Every subscriber notification carries the whole `State` serialized as JSON, and the recorder
//! stores each distinct one. The JSON is read tolerantly into a [`Snapshot`]: unknown fields are
//! ignored and missing ones default, so a komorebi newer than this recorder still reads.
//!
//! Two facts about it that matter when reading it:
//!
//! - A window's `rect` is **not** komorebi's bookkeeping. It is read live from the accessibility
//! API at the moment the state is serialized, so it says where the window *really* was.
//! Comparing it with where komorebi's layout says it should be (`layout_rects`) finds windows
//! that are in the wrong place.
//! - komorebi's `Rect` is `{left, top, right, bottom}` where `right` is the **width** and `bottom`
//! the **height**, in global display points. [`Rect`] uses honest names. komorebi for Windows
//! writes its `Rect` the same way.
//!
//! The two flavors of komorebi do not write a window the same way. A Mac window is keyed by `id`
//! and keeps its title and program under `details`; a Windows window is keyed by its handle,
//! `hwnd`, with its title and program beside it. The flavor's [`Rules`] know which, and
//! [`Snapshot::parse`] asks them, so the rest of the analysis sees one model: a [`Snapshot`] of
//! [`Monitor`]s, [`Workspace`]s, [`Container`]s and [`Window`]s.
//!
//! This module reads and does not judge. Whether the state is consistent (a window in two places, a
//! layout that was not applied) is for the invariant checks of the analysis, which are built on
//! these types.
//!
//! # Example
//!
//! A one-window state as each flavor writes it, read into the same model:
//!
//! ```rust
//! use komorebi_recorder::analysis::flavor::Flavor;
//! use komorebi_recorder::analysis::state::{Place, Rect, Snapshot};
//! use serde_json::json;
//!
//! // a workspace with one container, containing the given window, on monitor 1
//! let state = |window: serde_json::Value| json!({
//! "monitors": {"elements": [{
//! "id": 1,
//! "workspaces": {"elements": [{
//! "name": "one",
//! "containers": {"elements": [
//! {"id": "c", "windows": {"elements": [window], "focused": 0}}
//! ], "focused": 0}
//! }], "focused": 0}
//! }], "focused": 0}
//! });
//!
//! let mac = Snapshot::parse(Flavor::Macos, &state(json!({
//! "id": 59,
//! "details": {"title": "Notes", "exe": "Notes"},
//! "rect": {"left": 10, "top": 10, "right": 1686, "bottom": 1420}
//! })));
//! let (location, window) = mac.find(59).expect("the window");
//! assert_eq!(window.exe, "Notes");
//! // komorebi's `right` and `bottom` are a width and a height
//! assert_eq!(
//! window.rect,
//! Some(Rect { left: 10, top: 10, width: 1686, height: 1420 })
//! );
//! assert_eq!(location.place, Place::Container { index: 0, tab: 0 });
//! assert_eq!(location.describe(), "monitor 1 workspace one (container 0)");
//!
//! let windows = Snapshot::parse(Flavor::Windows, &state(json!({
//! "hwnd": 131072, "title": "Notes", "exe": "notepad.exe",
//! "rect": {"left": 0, "top": 0, "right": 100, "bottom": 100}
//! })));
//! assert_eq!(windows.find(131_072).expect("the window").1.exe, "notepad.exe");
//!
//! // only komorebi for Mac hides windows by position
//! assert!(mac.hides_windows_by_position());
//! assert!(!windows.hides_windows_by_position());
//! ```
use super::flavor::Flavor;
use super::flavor::Rules;
use schemars::JsonSchema;
use serde::Serialize;
use serde_json::Value;
/// A rectangle in komorebi's display coordinates, with names that say what the numbers are.
///
/// komorebi writes a rectangle as `{left, top, right, bottom}`, where `right` and `bottom` are a
/// width and a height. A `Rect` stores those two as [`Rect::width`] and [`Rect::height`], and
/// [`Rect::right_edge`] and [`Rect::bottom_edge`] give the edges.
///
/// A rect is not guaranteed to have a positive size: komorebi for Windows writes zeros for a window
/// it could not read. [`Rect::area`] counts a width or height below 0 as 0.
///
/// # Example
///
/// ```rust
/// use komorebi_recorder::analysis::state::Rect;
///
/// let a = Rect { left: 0, top: 0, width: 10, height: 10 };
/// let b = Rect { left: 5, top: 5, width: 10, height: 10 };
///
/// assert_eq!(a.right_edge(), 10);
/// assert_eq!(a.overlap_area(&b), 25);
/// assert_eq!(a.max_delta(&b), 5);
/// assert_eq!(a.describe(), "10x10 at (0, 0)");
///
/// // rects that only touch share no area
/// let c = Rect { left: 10, top: 0, width: 5, height: 5 };
/// assert_eq!(a.overlap_area(&c), 0);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)]
pub struct Rect {
/// The x coordinate of the left edge.
pub left: i64,
/// The y coordinate of the top edge.
pub top: i64,
/// The width: komorebi's `right`.
pub width: i64,
/// The height: komorebi's `bottom`.
pub height: i64,
}
impl Rect {
/// Returns the x coordinate of the right edge: `left + width`.
#[must_use]
pub fn right_edge(&self) -> i64 {
self.left + self.width
}
/// Returns the y coordinate of the bottom edge: `top + height`.
#[must_use]
pub fn bottom_edge(&self) -> i64 {
self.top + self.height
}
/// Returns the area the two rectangles share, or 0 if they do not overlap (touching edges do
/// not overlap).
#[must_use]
pub fn overlap_area(&self, other: &Rect) -> i64 {
let width = self.right_edge().min(other.right_edge()) - self.left.max(other.left);
let height = self.bottom_edge().min(other.bottom_edge()) - self.top.max(other.top);
if width <= 0 || height <= 0 {
0
} else {
width * height
}
}
/// Returns the rectangle's area. A width or height below 0 counts as 0.
#[must_use]
pub fn area(&self) -> i64 {
self.width.max(0) * self.height.max(0)
}
/// Returns the largest difference in any of the four numbers (`left`, `top`, `width`,
/// `height`) between the two rectangles: 0 if they are equal.
#[must_use]
pub fn max_delta(&self, other: &Rect) -> i64 {
[
(self.left - other.left).abs(),
(self.top - other.top).abs(),
(self.width - other.width).abs(),
(self.height - other.height).abs(),
]
.into_iter()
.max()
.unwrap_or(0)
}
/// Returns the rectangle as text for a reader: `1686x1420 at (10, 10)`, the size and then the
/// position of the top left corner.
#[must_use]
pub fn describe(&self) -> String {
format!(
"{}x{} at ({}, {})",
self.width, self.height, self.left, self.top
)
}
fn from_value(value: &Value) -> Option<Self> {
let number = |key: &str| {
let field = value.get(key)?;
field
.as_i64()
.or_else(|| field.as_f64().map(|float| float.round() as i64))
};
Some(Self {
left: number("left")?,
top: number("top")?,
// komorebi's `right` and `bottom` are a width and a height
width: number("right")?,
height: number("bottom")?,
})
}
}
/// A window that appears in komorebi's state, as the state describes it.
///
/// Fields that the state does not have (a komorebi that does not write them, or one newer than this
/// recorder) are empty text, not an error.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub struct Window {
/// The window's id in the state: a window id on a Mac, a handle on Windows
/// ([`Rules::window_id`]).
pub id: u64,
/// The window's title. Empty if the state has none. For a window komorebi for Windows could not
/// read, it is komorebi's error text (`could not get window title`), not a title.
pub title: String,
/// The program: an application name on a Mac, an executable file name on Windows. Empty if the
/// state has none, and komorebi's error text for a window it could not read.
pub exe: String,
/// Where the window really was when the state was serialized (a live read from the OS, not
/// komorebi's bookkeeping). `None` if the state has no rect for it, or if komorebi could not read
/// the window ([`Rules::window_is_unreadable`]), so that a rect of zeros is not mistaken for a
/// window parked at a corner.
pub rect: Option<Rect>,
}
/// A container: one tile of a workspace, holding one window or a stack of tabbed ones.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub struct Container {
/// komorebi's identifier for the container.
pub id: String,
/// The windows in the container, one tile's worth: more than one when they are tabbed or
/// stacked.
pub windows: Vec<Window>,
/// Which of `windows` is in front: an index into `windows`. 0 if the state does not say.
pub focused: usize,
/// Whether the state has the container as locked (`locked`); `false` if it does not say.
pub locked: bool,
}
impl Container {
/// Returns the window in front, or `None` if `focused` is not an index of `windows` (an empty
/// container, for one).
#[must_use]
pub fn focused_window(&self) -> Option<&Window> {
self.windows.get(self.focused)
}
}
/// A workspace of a monitor: its tiled containers, and its monocle, maximized and floating windows.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub struct Workspace {
/// The workspace's name; empty if it has none.
pub name: String,
/// The tiled containers, in komorebi's order.
pub containers: Vec<Container>,
/// Which of `containers` has focus: an index into `containers`. 0 if the state does not say.
pub focused: usize,
/// A container filling the workspace on its own.
pub monocle: Option<Container>,
/// The window maximized on the workspace, if there is one.
pub maximized: Option<Window>,
/// The windows floating above the tiles.
pub floating: Vec<Window>,
/// Which of `floating` has focus: an index into `floating`. 0 if the state does not say.
pub floating_focused: usize,
/// `Tiling` or `Floating`: which layer has the focus.
pub layer: String,
/// The layout's short name: `Columns`, `BSP`, ... Empty if the state has none.
pub layout: String,
/// Where komorebi's last layout pass put each container, by container index.
pub layout_rects: Vec<Rect>,
/// Whether tiling is on for the workspace. `true` if the state does not say.
pub tiling: bool,
}
/// A monitor and its workspaces.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub struct Monitor {
/// The display id: the same number as the `--display` of the recording.
pub id: u64,
/// The display's name, as komorebi has it (`Built-in Retina Display`).
pub device: String,
/// The monitor's whole area.
pub size: Rect,
/// The monitor's work area, from `work_area_size`.
pub work_area: Rect,
/// The monitor's workspaces, in komorebi's order.
pub workspaces: Vec<Workspace>,
/// Which of `workspaces` is showing: an index into `workspaces`. 0 if the state does not say.
pub focused: usize,
/// `BottomLeft` or `BottomRight`: the corner komorebi hides windows in. Empty if the state does
/// not say.
pub hiding_position: String,
}
impl Monitor {
/// Returns the workspace that is showing, or `None` if `focused` is not an index of
/// `workspaces`.
#[must_use]
pub fn focused_workspace(&self) -> Option<&Workspace> {
self.workspaces.get(self.focused)
}
}
/// Where a window is in the tree: on which monitor and workspace, and in which place on it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub struct Location {
/// The [`Monitor::id`] of the monitor.
pub monitor_id: u64,
/// The name of the workspace.
pub workspace: String,
/// Where on the workspace.
pub place: Place,
/// Whether that workspace is the one showing on its monitor.
pub workspace_visible: bool,
}
/// Where on a workspace a window is.
///
/// Serialized as an object with the kebab-case variant name in `kind`: `{"kind": "container",
/// "index": 2, "tab": 0}`, `{"kind": "maximized"}`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum Place {
/// In a tiled container.
Container {
/// Which of the workspace's containers: an index into [`Workspace::containers`].
index: usize,
/// Which of the container's windows: an index into [`Container::windows`], 0 for the
/// first.
tab: usize,
},
/// In the container that fills the workspace.
Monocle {
/// Which of the container's windows.
tab: usize,
},
/// The window maximized on the workspace.
Maximized,
/// Floating above the tiles.
Floating {
/// Which of the workspace's floating windows: an index into [`Workspace::floating`].
index: usize,
},
}
impl Place {
/// Returns the place as text for a reader: `container 2`, `container 2 tab 1` (the tab only
/// when it is not the first), `monocle`, `maximized` or `floating 0`.
///
/// # Example
///
/// ```rust
/// use komorebi_recorder::analysis::state::Place;
///
/// assert_eq!(Place::Container { index: 2, tab: 0 }.describe(), "container 2");
/// assert_eq!(Place::Container { index: 2, tab: 1 }.describe(), "container 2 tab 1");
/// assert_eq!(Place::Maximized.describe(), "maximized");
/// ```
#[must_use]
pub fn describe(&self) -> String {
match self {
Self::Container { index, tab } if *tab > 0 => format!("container {index} tab {tab}"),
Self::Container { index, .. } => format!("container {index}"),
Self::Monocle { .. } => "monocle".to_string(),
Self::Maximized => "maximized".to_string(),
Self::Floating { index } => format!("floating {index}"),
}
}
}
impl Location {
/// Returns the location as text for a reader: `monitor 3 workspace one (container 0)`.
#[must_use]
pub fn describe(&self) -> String {
format!(
"monitor {} workspace {} ({})",
self.monitor_id,
self.workspace,
self.place.describe()
)
}
}
/// The monitor, workspace and window that have the keyboard focus, as komorebi's state has them.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub struct Focus {
/// The [`Monitor::id`] of the focused monitor.
pub monitor_id: u64,
/// The name of its focused workspace.
pub workspace: String,
/// The focused window's [`Window::id`]; `None` if the workspace has no window to focus.
pub window_id: Option<u64>,
/// Where the focused window is on the workspace; `None` when there is none.
pub place: Option<Place>,
}
/// komorebi's whole `State` at one moment, read into a model.
///
/// A snapshot is built with [`Snapshot::parse`], which never fails: a state with fields missing or
/// unknown reads with what is there, and what is not is empty or a default. It records which
/// [`Flavor`] wrote it, because what a window's position says depends on that (see
/// [`Snapshot::hides_windows_by_position`]); the flavor is not part of the serialized form.
///
/// See the [module documentation](self) for an example.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub struct Snapshot {
/// Which komorebi wrote this state, and so how to read the parts of it that mean different
/// things in each. Not part of the state itself.
#[serde(skip)]
#[schemars(skip)]
pub flavor: Flavor,
/// The monitors, in komorebi's order.
pub monitors: Vec<Monitor>,
/// Which of `monitors` has focus: an index into `monitors`. 0 if the state does not say.
pub focused_monitor: usize,
/// Whether komorebi was paused (`is_paused`); `false` if the state does not say.
pub paused: bool,
}
fn array<'a>(value: &'a Value, key: &str) -> &'a [Value] {
value
.get(key)
.and_then(|ring| ring.get("elements"))
.and_then(Value::as_array)
.map_or(&[], Vec::as_slice)
}
fn focused(value: &Value, key: &str) -> usize {
value
.get(key)
.and_then(|ring| ring.get("focused"))
.and_then(Value::as_u64)
.map_or(0, |index| index as usize)
}
fn text(value: &Value, key: &str) -> String {
value
.get(key)
.and_then(Value::as_str)
.unwrap_or_default()
.to_string()
}
fn window(rules: &dyn Rules, value: &Value) -> Option<Window> {
let id = rules.window_id(value)?;
// a mac window keeps its title and program under `details`, a Windows one beside the rest
let details = value.get("details").unwrap_or(value);
// what komorebi could not read it does not guess: its rect is a zero and its title an error
// message, which would read as a window parked at the corner of the screen
let unreadable = rules.window_is_unreadable(value);
Some(Window {
id,
title: text(details, "title"),
exe: text(details, "exe"),
rect: value
.get("rect")
.and_then(Rect::from_value)
.filter(|_| !unreadable),
})
}
fn container(rules: &dyn Rules, value: &Value) -> Container {
Container {
id: text(value, "id"),
windows: array(value, "windows")
.iter()
.filter_map(|value| window(rules, value))
.collect(),
focused: focused(value, "windows"),
locked: value
.get("locked")
.and_then(Value::as_bool)
.unwrap_or(false),
}
}
/// `{"Default": "Columns"}` or `"BSP"` or `{"Custom": ...}` as a short name.
fn layout_name(value: Option<&Value>) -> String {
match value {
Some(Value::String(name)) => name.clone(),
Some(Value::Object(object)) => {
object
.iter()
.next()
.map_or_else(String::new, |(key, inner)| match inner.as_str() {
Some(name) => name.to_string(),
None => key.clone(),
})
}
_ => String::new(),
}
}
fn workspace(rules: &dyn Rules, value: &Value) -> Workspace {
Workspace {
name: text(value, "name"),
containers: array(value, "containers")
.iter()
.map(|value| container(rules, value))
.collect(),
focused: focused(value, "containers"),
monocle: value
.get("monocle_container")
.filter(|monocle| monocle.is_object())
.map(|monocle| container(rules, monocle)),
maximized: value
.get("maximized_window")
.and_then(|value| window(rules, value)),
floating: array(value, "floating_windows")
.iter()
.filter_map(|value| window(rules, value))
.collect(),
floating_focused: focused(value, "floating_windows"),
layer: text(value, "layer"),
layout: layout_name(value.get("layout")),
layout_rects: value
.get("latest_layout")
.and_then(Value::as_array)
.map(|rects| rects.iter().filter_map(Rect::from_value).collect())
.unwrap_or_default(),
tiling: value.get("tile").and_then(Value::as_bool).unwrap_or(true),
}
}
fn monitor(rules: &dyn Rules, value: &Value) -> Monitor {
let rect = |key: &str| {
value.get(key).and_then(Rect::from_value).unwrap_or(Rect {
left: 0,
top: 0,
width: 0,
height: 0,
})
};
Monitor {
id: value
.get("id")
.and_then(|id| id.as_u64().or_else(|| id.as_i64().map(|id| id as u64)))
.unwrap_or(0),
device: text(value, "device"),
size: rect("size"),
work_area: rect("work_area_size"),
workspaces: array(value, "workspaces")
.iter()
.map(|value| workspace(rules, value))
.collect(),
focused: focused(value, "workspaces"),
hiding_position: text(value, "window_hiding_position"),
}
}
impl Snapshot {
/// Returns the model of a `State` as the komorebi of `flavor` serialized it.
///
/// This never fails. The JSON is read tolerantly: unknown fields are ignored, and a missing one
/// is an empty list, empty text, 0 or `false` (`tiling` is `true`). A window the flavor's
/// [`Rules::window_id`] does not recognize as one is left out. Numbers in a rect may be floats;
/// they are rounded.
///
/// `state` is what komorebi sent in a notification, or what the recorder stored in
/// `states/<id>.json`. See the [module documentation](self) for an example.
#[must_use]
pub fn parse(flavor: Flavor, state: &Value) -> Self {
Self {
flavor,
monitors: array(state, "monitors")
.iter()
.map(|value| monitor(flavor.rules(), value))
.collect(),
focused_monitor: focused(state, "monitors"),
paused: state
.get("is_paused")
.and_then(Value::as_bool)
.unwrap_or(false),
}
}
/// A macOS state, for the tests, whose states all are.
#[cfg(test)]
#[must_use]
pub fn from_value(state: &Value) -> Self {
Self::parse(Flavor::Macos, state)
}
/// Returns every window with where it is, in order: by monitor, then workspace, then the
/// tiled containers (each tab in turn), the monocle container, the maximized window and the
/// floating windows.
///
/// A window that the state lists in two places appears twice.
#[must_use]
pub fn windows(&self) -> Vec<(Location, &Window)> {
let mut found = Vec::new();
for monitor in &self.monitors {
for (index, workspace) in monitor.workspaces.iter().enumerate() {
let visible = index == monitor.focused;
let at = |place: Place| Location {
monitor_id: monitor.id,
workspace: workspace.name.clone(),
place,
workspace_visible: visible,
};
for (container_index, container) in workspace.containers.iter().enumerate() {
for (tab, window) in container.windows.iter().enumerate() {
found.push((
at(Place::Container {
index: container_index,
tab,
}),
window,
));
}
}
if let Some(monocle) = &workspace.monocle {
for (tab, window) in monocle.windows.iter().enumerate() {
found.push((at(Place::Monocle { tab }), window));
}
}
if let Some(window) = &workspace.maximized {
found.push((at(Place::Maximized), window));
}
for (floating_index, window) in workspace.floating.iter().enumerate() {
found.push((
at(Place::Floating {
index: floating_index,
}),
window,
));
}
}
}
found
}
/// Returns the first place a window with this id is, in the order of [`Snapshot::windows`], or
/// `None` if there is none.
#[must_use]
pub fn find(&self, window_id: u64) -> Option<(Location, &Window)> {
self.windows()
.into_iter()
.find(|(_, window)| window.id == window_id)
}
/// Returns what has focus: the focused monitor's focused workspace's focused window, where a
/// floating layer beats the tiled containers and a monocle container beats the rest.
///
/// The layer wins only when the workspace's `layer` is `Floating` and it has floating windows.
/// A `focused_monitor` that is not an index of `monitors` falls back to the first monitor. The
/// result is `None` if there is no monitor or the monitor has no focused workspace; a focused
/// workspace with nothing to focus is a [`Focus`] with no `window_id` and no `place`.
#[must_use]
pub fn focus(&self) -> Option<Focus> {
let monitor = self
.monitors
.get(self.focused_monitor)
.or_else(|| self.monitors.first())?;
let workspace = monitor.focused_workspace()?;
let (window, place) = if workspace.layer == "Floating" && !workspace.floating.is_empty() {
let index = workspace
.floating_focused
.min(workspace.floating.len().saturating_sub(1));
(
workspace.floating.get(index),
Some(Place::Floating { index }),
)
} else if let Some(monocle) = &workspace.monocle {
(
monocle.focused_window(),
Some(Place::Monocle {
tab: monocle.focused,
}),
)
} else if let Some(container) = workspace.containers.get(workspace.focused) {
(
container.focused_window(),
Some(Place::Container {
index: workspace.focused,
tab: container.focused,
}),
)
} else {
(None, None)
};
Some(Focus {
monitor_id: monitor.id,
workspace: workspace.name.clone(),
window_id: window.map(|window| window.id),
place,
})
}
/// Returns whether a window's position says if it is hidden: komorebi for Mac parks a hidden
/// window in a corner, and komorebi for Windows by default cloaks it where it is, so there a
/// hidden window is not told from a visible one by where it is.
///
/// This is [`Rules::hides_windows_by_position`] of the snapshot's flavor. Checks that depend on
/// where hidden windows are skip a snapshot for which it is `false`.
#[must_use]
pub fn hides_windows_by_position(&self) -> bool {
self.flavor.rules().hides_windows_by_position()
}
/// Returns whether `rect` is where komorebi parks a window it has hidden on `monitor`. What that
/// looks like is up to the flavor of komorebi that recorded the state: it is
/// [`Rules::is_hidden_position`] of the snapshot's flavor.
#[must_use]
pub fn is_hidden_position(&self, rect: &Rect, monitor: &Monitor) -> bool {
self.flavor.rules().is_hidden_position(rect, monitor)
}
/// Returns the monitor whose area holds most of `rect`, or `None` if `rect` overlaps none. On a
/// tie, the monitor later in `monitors` is returned.
#[must_use]
pub fn monitor_under(&self, rect: &Rect) -> Option<&Monitor> {
self.monitors
.iter()
.map(|monitor| (monitor.size.overlap_area(rect), monitor))
.filter(|(area, _)| *area > 0)
.max_by_key(|(area, _)| *area)
.map(|(_, monitor)| monitor)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn fixture() -> Snapshot {
let state: Value =
serde_json::from_str(include_str!("../../tests/fixtures/state.json")).expect("fixture");
Snapshot::from_value(&state)
}
#[test]
fn a_real_state_reads_into_monitors_workspaces_and_windows() {
let snapshot = fixture();
assert_eq!(snapshot.monitors.len(), 2);
assert_eq!(snapshot.monitors[0].id, 1);
assert_eq!(snapshot.monitors[0].device, "Built-in Retina Display");
assert_eq!(snapshot.monitors[1].workspaces.len(), 10);
assert!(!snapshot.paused);
let windows = snapshot.windows();
assert!(windows.len() > 15);
let (location, slack) = snapshot.find(59).expect("window 59");
assert_eq!(slack.exe, "Slack");
assert_eq!(slack.title, "window 59");
assert_eq!(location.monitor_id, 3);
assert_eq!(location.workspace, "one");
assert_eq!(location.place, Place::Container { index: 0, tab: 0 });
}
#[test]
fn komorebis_right_and_bottom_are_read_as_width_and_height() {
let snapshot = fixture();
let layout = &snapshot.monitors[1].workspaces[0].layout_rects;
// {"left": 10, "top": 10, "right": 1686, "bottom": 1420}
assert_eq!(
layout[0],
Rect {
left: 10,
top: 10,
width: 1686,
height: 1420
}
);
assert_eq!(layout[0].right_edge(), 1696);
}
#[test]
fn layouts_have_short_names() {
assert_eq!(fixture().monitors[1].workspaces[0].layout, "Columns");
assert_eq!(layout_name(Some(&serde_json::json!("BSP"))), "BSP");
assert_eq!(layout_name(None), "");
}
#[test]
fn hidden_windows_sit_on_the_sliver_and_visible_ones_do_not() {
let snapshot = fixture();
let monitor = &snapshot.monitors[1];
let (_, hidden) = snapshot
.find(59)
.expect("a window on a workspace that is not showing");
assert!(snapshot.is_hidden_position(hidden.rect.as_ref().expect("rect"), monitor));
let visible = Rect {
left: 10,
top: 10,
width: 1686,
height: 1420,
};
assert!(!snapshot.is_hidden_position(&visible, monitor));
}
#[test]
fn focus_follows_the_focused_monitor_workspace_and_container() {
let focus = fixture().focus().expect("focus");
// the second monitor (display 3) is focused, on workspace "ten", at its third container
assert_eq!(focus.monitor_id, 3);
assert_eq!(focus.workspace, "ten");
assert_eq!(focus.window_id, Some(8550));
assert_eq!(focus.place, Some(Place::Container { index: 2, tab: 0 }));
}
fn workspace_state(extra: Value) -> Snapshot {
let mut workspace = serde_json::json!({
"name": "w", "layer": "Tiling",
"containers": {"elements": [
{"id": "a", "windows": {"elements": [{"id": 1, "rect": null}], "focused": 0}},
{"id": "b", "windows": {"elements": [{"id": 2}], "focused": 0}}
], "focused": 1},
"floating_windows": {"elements": [{"id": 3}], "focused": 0},
});
for (key, value) in extra.as_object().expect("object") {
workspace[key] = value.clone();
}
Snapshot::from_value(&serde_json::json!({
"monitors": {"elements": [{"id": 1, "workspaces": {"elements": [workspace], "focused": 0}}], "focused": 0}
}))
}
#[test]
fn a_monocle_container_beats_the_containers_and_a_floating_layer_beats_both() {
let plain = workspace_state(serde_json::json!({}));
assert_eq!(plain.focus().expect("focus").window_id, Some(2));
let monocle = workspace_state(serde_json::json!({
"monocle_container": {"id": "m", "windows": {"elements": [{"id": 9}], "focused": 0}}
}));
assert_eq!(monocle.focus().expect("focus").window_id, Some(9));
let floating = workspace_state(serde_json::json!({
"layer": "Floating",
"monocle_container": {"id": "m", "windows": {"elements": [{"id": 9}], "focused": 0}}
}));
assert_eq!(floating.focus().expect("focus").window_id, Some(3));
}
#[test]
fn missing_and_unknown_fields_do_not_break_reading() {
let snapshot = Snapshot::from_value(&serde_json::json!({"brand_new": 1}));
assert!(snapshot.monitors.is_empty());
assert!(snapshot.focus().is_none());
let odd = Snapshot::from_value(&serde_json::json!({
"monitors": {"elements": [{"id": 1, "future_field": [1, 2], "workspaces": {"elements": [{"name": "x", "monocle_container": null}]}}]}
}));
assert_eq!(odd.monitors[0].workspaces[0].name, "x");
assert!(odd.monitors[0].workspaces[0].monocle.is_none());
}
#[test]
fn a_window_without_a_rect_has_none_and_overlap_is_computed() {
let snapshot = workspace_state(serde_json::json!({}));
assert!(snapshot.find(1).expect("window").1.rect.is_none());
let a = Rect {
left: 0,
top: 0,
width: 10,
height: 10,
};
let b = Rect {
left: 5,
top: 5,
width: 10,
height: 10,
};
assert_eq!(a.overlap_area(&b), 25);
assert_eq!(
a.overlap_area(&Rect {
left: 20,
top: 0,
width: 5,
height: 5
}),
0
);
assert_eq!(a.max_delta(&b), 5);
}
}
+55
View File
@@ -6,8 +6,11 @@
//! `--json` on a command also decides how a failure is reported (see [`Command::wants_json`]).
mod doctor;
mod query;
mod record;
use crate::analysis::envelope::unusable;
use crate::analysis::envelope::with_hint;
use crate::session::Session;
use clap::Args;
use clap::Parser;
@@ -17,6 +20,12 @@ use serde::Serialize;
use std::path::PathBuf;
pub use doctor::DoctorArgs;
pub use query::AtArgs;
pub use query::FilterArgs;
pub use query::FramesArgs;
pub use query::LocateArgs;
pub use query::RangeArgs;
pub use query::SummaryArgs;
pub use record::RecordArgs;
/// The command line of `komorebi-recorder`.
@@ -49,6 +58,16 @@ pub enum Command {
Displays,
/// What this machine can do for a recording, and probes that measure what one leans on
Doctor(DoctorArgs),
/// Everything recorded around a video timecode: komorebi log, events and OS trace
At(AtArgs),
/// Everything recorded between two video timecodes
Range(RangeArgs),
/// A per-bucket digest of the whole recording
Summary(SummaryArgs),
/// Reverse lookup: a UTC time, log line or event number to a video timecode
Locate(LocateArgs),
/// Extract PNG frames at video timecodes (needs ffmpeg)
Frames(FramesArgs),
/// Rebuild a session's timeline from its raw files, recovering it first if the recorder died
Reindex(ReindexArgs),
/// Check the video-to-clock alignment against a rendered on-screen clock
@@ -85,11 +104,20 @@ pub(crate) fn print_json(value: &impl Serialize) -> eyre::Result<()> {
Ok(())
}
pub(crate) fn limit(value: usize) -> Option<usize> {
(value != 0).then_some(value)
}
impl Command {
/// Whether this command was asked for JSON, which also decides how a failure is reported.
#[must_use]
pub fn wants_json(&self) -> bool {
match self {
Self::At(args) => args.filter.json,
Self::Range(args) => args.filter.json,
Self::Summary(args) => args.json,
Self::Locate(args) => args.json,
Self::Frames(args) => args.json,
Self::Doctor(args) => args.json,
_ => false,
}
@@ -130,6 +158,11 @@ pub fn run(command: Command) -> eyre::Result<()> {
Command::Record(args) => record::record(&args),
Command::Displays => record::displays(),
Command::Doctor(args) => doctor::doctor(&args),
Command::At(args) => query::at(&args),
Command::Range(args) => query::range(&args),
Command::Summary(args) => query::summary(&args),
Command::Locate(args) => query::locate(&args),
Command::Frames(args) => query::frames_command(&args),
Command::Reindex(args) => reindex(&args),
Command::Selftest(args) => crate::selftest::run(&args),
Command::SelftestClock => crate::selftest::run_clock(),
@@ -157,6 +190,28 @@ pub fn main() -> eyre::Result<std::process::ExitCode> {
))
}
pub(crate) fn load(session: &std::path::Path) -> eyre::Result<(Session, crate::session::Manifest)> {
let session = Session::open(session)?;
let manifest = session.manifest()?;
if manifest.status == crate::session::STATUS_RECORDING {
let dir = session.dir.display();
return Err(match crate::lock::recorder(&session.dir) {
crate::lock::Recorder::Running(_) => unusable(format!(
"{dir} is still being recorded; stop the recording first"
)),
crate::lock::Recorder::NotRunning | crate::lock::Recorder::Unknown => with_hint(
unusable(format!(
"{dir} was left unfinished: its recorder was killed or crashed"
)),
format!("recover it with `komorebi-recorder reindex {dir}`"),
),
});
}
Ok((session, manifest))
}
fn reindex(args: &ReindexArgs) -> eyre::Result<()> {
let session = Session::open(&args.session)?;
let reindexed = crate::recovery::reindex_session(&session)?;
+330
View File
@@ -0,0 +1,330 @@
//! Reading a session back: `at`, `range`, `summary`, `locate` and `frames`.
//!
//! These read the session's timeline directly (see [`crate::timeline`]), not through an `Analysis`,
//! so they say what was recorded without interpreting it as the output of one komorebi or the
//! other. Times are video timecodes ([`crate::timecode`]).
//!
//! | Command | Asks | Prints |
//! |---|---|---|
//! | `at <time>` | [`timeline::query`] around the time (`--window`, default 1 s, either side) | the records found, a source at a time |
//! | `range <from> <to>` | [`timeline::query`] between two times | the same |
//! | `summary` | [`timeline::summary`] | a line for each bucket of time (`--bucket`) |
//! | `locate` | [`timeline::locate`] | where a UTC time, log line or event falls in video time and in each display's file |
//! | `frames <times>` | [`frames::extract`] | the path of a PNG for each time and display |
//!
//! `--app` and `--source` narrow what `at`, `range` and `summary` read. `--limit` is the most
//! records shown per source in text, and `0` means no limit. A finished session is required: one
//! still being recorded, or whose recorder died, is refused with what to do about it (`reindex`).
//!
//! With `--json` these commands print their data itself (the records, the buckets, the location),
//! not inside the envelope the investigation commands use; a failure is still reported as an
//! envelope.
use super::limit;
use super::load;
use super::print_json;
use crate::frames;
use crate::report;
use crate::timecode;
use crate::timeline;
use crate::timeline::Filter;
use crate::timeline::Locator;
use chrono::DateTime;
use chrono::Utc;
use clap::Args;
use color_eyre::eyre;
use color_eyre::eyre::WrapErr;
use serde::Serialize;
use std::path::PathBuf;
/// The options `at` and `range` share: what to look at, and how to print it.
#[derive(Args, Debug)]
pub struct FilterArgs {
/// Only this application's OS trace (exe name, case-insensitive, or a pid)
#[arg(long, value_name = "EXE|PID")]
pub app: Option<String>,
/// Only these sources: komorebi-log, events, oslog, oslog:komorebi, oslog:system,
/// oslog:app, `oslog:app:<exe>` (repeatable)
#[arg(long = "source", value_name = "SOURCE")]
pub sources: Vec<String>,
/// Machine-readable JSON output
#[arg(long)]
pub json: bool,
/// Most records to print per source in text mode (0 for no limit)
#[arg(long, default_value_t = 100)]
pub limit: usize,
}
impl FilterArgs {
fn filter(&self) -> Filter {
Filter {
app: self.app.clone(),
sources: self.sources.clone(),
}
}
}
/// The arguments of `at`.
#[derive(Args, Debug)]
pub struct AtArgs {
/// Session directory
pub session: PathBuf,
/// Video timecode: 12.5, 00:12.500 or 1:02:03
pub time: String,
/// How far either side of the timecode to look
#[arg(long, default_value = "1s")]
pub window: String,
/// What to look at, and how to print it
#[command(flatten)]
pub filter: FilterArgs,
}
/// The arguments of `range`.
#[derive(Args, Debug)]
pub struct RangeArgs {
/// Session directory
pub session: PathBuf,
/// Start timecode
pub from: String,
/// End timecode
pub to: String,
/// What to look at, and how to print it
#[command(flatten)]
pub filter: FilterArgs,
}
/// The arguments of `summary`.
#[derive(Args, Debug)]
pub struct SummaryArgs {
/// Session directory
pub session: PathBuf,
/// Bucket size
#[arg(long, default_value = "1s")]
pub bucket: String,
/// List every source's count instead of log/events/os totals
#[arg(long)]
pub by_source: bool,
/// Only this application's OS trace
#[arg(long, value_name = "EXE|PID")]
pub app: Option<String>,
/// Only these sources (repeatable)
#[arg(long = "source", value_name = "SOURCE")]
pub sources: Vec<String>,
/// Machine-readable JSON output
#[arg(long)]
pub json: bool,
}
/// The arguments of `locate`: exactly one of `--utc`, `--log-line` and `--event-seq`.
#[derive(Args, Debug)]
#[command(group(clap::ArgGroup::new("what").required(true).multiple(false)))]
pub struct LocateArgs {
/// Session directory
pub session: PathBuf,
/// A UTC time (RFC 3339), e.g. 2026-10-26T19:43:35.062613Z
#[arg(long, group = "what")]
pub utc: Option<String>,
/// A 1-based line number in the session's komorebi.log
#[arg(long, group = "what")]
pub log_line: Option<u64>,
/// A subscriber event sequence number from events.jsonl
#[arg(long, group = "what")]
pub event_seq: Option<u64>,
/// Machine-readable JSON output
#[arg(long)]
pub json: bool,
}
/// The arguments of `frames`.
#[derive(Args, Debug)]
pub struct FramesArgs {
/// Session directory
pub session: PathBuf,
/// Video timecodes to extract
#[arg(required = true)]
pub times: Vec<String>,
/// Only this display
#[arg(long, value_name = "ID")]
pub display: Option<u32>,
/// Machine-readable JSON output
#[arg(long)]
pub json: bool,
}
#[derive(Serialize)]
struct QueryOutput<'a> {
session: String,
from_s: f64,
to_s: f64,
#[serde(skip_serializing_if = "Option::is_none")]
center_s: Option<f64>,
count: usize,
records: &'a [timeline::Record],
}
/// When `--app` matched nothing, say which applications this session does have.
fn hint_unknown_app(manifest: &crate::session::Manifest, filter: &FilterArgs, empty: bool) {
let Some(app) = &filter.app else {
return;
};
let known = timeline::app_names(manifest);
let is_known =
app.parse::<i64>().is_ok() || known.iter().any(|name| name.eq_ignore_ascii_case(app));
if empty && !is_known {
eprintln!(
"note: no application '{app}' was traced in this session; traced: {}",
if known.is_empty() {
"(none)".to_string()
} else {
known.join(", ")
}
);
}
}
pub(super) fn at(args: &AtArgs) -> eyre::Result<()> {
let (session, manifest) = load(&args.session)?;
let center = timecode::parse(&args.time)?;
let window = timecode::parse_span(&args.window)?;
let (from, to) = (center - window, center + window);
let records = timeline::query(&session, &manifest, from, to, &args.filter.filter())?;
if args.filter.json {
return print_json(&QueryOutput {
session: session.dir.display().to_string(),
from_s: from,
to_s: to,
center_s: Some(center),
count: records.len(),
records: &records,
});
}
hint_unknown_app(&manifest, &args.filter, records.is_empty());
let heading = format!(
"{} (window +-{window}s: {} to {})",
timecode::format(center),
timecode::format(from),
timecode::format(to)
);
print!(
"{}",
report::records_text(&heading, &records, Some(center), limit(args.filter.limit))
);
Ok(())
}
pub(super) fn range(args: &RangeArgs) -> eyre::Result<()> {
let (session, manifest) = load(&args.session)?;
let from = timecode::parse(&args.from)?;
let to = timecode::parse(&args.to)?;
if to < from {
eyre::bail!(
"the range end {} is before its start {}",
args.to,
args.from
);
}
let records = timeline::query(&session, &manifest, from, to, &args.filter.filter())?;
if args.filter.json {
return print_json(&QueryOutput {
session: session.dir.display().to_string(),
from_s: from,
to_s: to,
center_s: None,
count: records.len(),
records: &records,
});
}
hint_unknown_app(&manifest, &args.filter, records.is_empty());
let heading = format!("{} to {}", timecode::format(from), timecode::format(to));
print!(
"{}",
report::records_text(&heading, &records, None, limit(args.filter.limit))
);
Ok(())
}
pub(super) fn summary(args: &SummaryArgs) -> eyre::Result<()> {
let (session, manifest) = load(&args.session)?;
let bucket = timecode::parse_span(&args.bucket)?;
let filter = Filter {
app: args.app.clone(),
sources: args.sources.clone(),
};
let buckets = timeline::summary(&session, &manifest, bucket, &filter)?;
if args.json {
return print_json(&buckets);
}
print!("{}", report::summary_text(&buckets, args.by_source));
Ok(())
}
pub(super) fn locate(args: &LocateArgs) -> eyre::Result<()> {
let (session, manifest) = load(&args.session)?;
let locator = if let Some(utc) = &args.utc {
let time: DateTime<Utc> = DateTime::parse_from_rfc3339(utc)
.wrap_err_with(|| {
format!("'{utc}' is not an RFC 3339 time like 2026-10-26T19:43:35.062613Z")
})?
.with_timezone(&Utc);
Locator::Utc(time)
} else if let Some(line) = args.log_line {
Locator::LogLine(line)
} else if let Some(seq) = args.event_seq {
Locator::EventSeq(seq)
} else {
eyre::bail!("one of --utc, --log-line or --event-seq is required");
};
let located = timeline::locate(&session, &manifest, &locator)?;
if args.json {
return print_json(&located);
}
print!("{}", report::locate_text(&located));
Ok(())
}
pub(super) fn frames_command(args: &FramesArgs) -> eyre::Result<()> {
let (session, manifest) = load(&args.session)?;
let times = args
.times
.iter()
.map(|time| timecode::parse(time))
.collect::<eyre::Result<Vec<_>>>()?;
let extraction = frames::extract(&session, &manifest, &times, args.display)?;
if args.json {
return print_json(&extraction);
}
for frame in &extraction.frames {
println!(
"{} display {} {}",
timecode::format(frame.video_s),
frame.display,
frame.path.display()
);
}
for skipped in &extraction.skipped {
eprintln!(
"note: {} display {}: {}",
timecode::format(skipped.video_s),
skipped.display,
skipped.reason
);
}
Ok(())
}
+2
View File
@@ -58,6 +58,7 @@
//! | [`app`] | the recorder window |
//! | [`av`] and [`selftest`] | decoding the recorded video and checking it against the clocks |
//! | [`doctor`] | what a recording leans on, and probes that measure it |
//! | [`report`] | answers as text for a terminal |
//!
//! # What is not supported
//!
@@ -86,6 +87,7 @@ pub mod platform;
pub mod power;
pub mod recorder;
pub mod recovery;
pub mod report;
pub mod selftest;
pub mod session;
pub mod sources;
+579
View File
@@ -0,0 +1,579 @@
//! Human-readable rendering of query results. Everything here is a pure function of its inputs so
//! the output format is unit-testable; `--json` bypasses this module entirely.
//!
//! Each function takes the data an `Analysis` question (or the
//! timeline) answered with, and returns the text the command prints. The text is for a person or an
//! agent reading a terminal: its wording is not a stable interface. A program should ask for
//! `--json`, whose shape is named and versioned by the envelope's `schema`.
//!
//! | Command | Function | Renders |
//! |---|---|---|
//! | `at`, `range` | [`records_text`] (with [`group_by_source`]) | the records of a stretch of the recording, a source at a time |
//! | `summary` | [`summary_text`] | a digest of the recording in buckets of time |
//! | `locate` | [`locate_text`] | where a UTC time, log line or event falls in the video |
//! | `annotate`, `annotations`, and parts of `brief` and `overview` | [`annotation_text`] | a bug region, note or finding |
//! | `state` | `state_text` | `StateData` |
//! | `diff` | `diff_text` | `DiffData` |
//! | `events` | `events_text` | `EventsData` |
//! | `code` | `code_text` | `CodeData` |
//! | `trace` | `trace_text` | `TraceData` |
//! | `window` | `history_text` | `HistoryData` |
//! | `brief` | `brief_text` | `BriefData` |
//! | `overview` | `overview_text` | `OverviewData` |
//! | `search` | `search_text` | `SearchData` |
//! | `changes` | `changes_text` | `ChangesData` |
//! | `sheet` | `sheet_text` | `SheetData` |
//!
//! Times are written as timecodes (`00:12.500`, see [`crate::timecode::format`]) in video time.
use crate::annotations::AnnotationView;
use crate::annotations::Kind;
use crate::timecode;
use crate::timeline::Bucket;
use crate::timeline::Located;
use crate::timeline::Record;
use crate::timeline::SOURCE_EVENTS;
use crate::timeline::SOURCE_KOMOREBI_LOG;
use crate::timeline::SOURCE_RECORDER;
use std::collections::BTreeMap;
use std::fmt::Write;
/// The order sources are listed in: komorebi's own view first, then the OS trace from the
/// daemon outwards to the apps.
fn source_rank(source: &str) -> (u8, String) {
let rank = match source {
// what happened to the recording environment frames everything else
SOURCE_RECORDER => 0,
SOURCE_KOMOREBI_LOG => 1,
SOURCE_EVENTS => 2,
"oslog:komorebi" => 3,
"oslog:system" => 4,
_ if source.starts_with("oslog:app:") => 5,
_ => 6,
};
(rank, source.to_string())
}
/// Groups records by source, in display order.
///
/// The order is the recording environment first (what happened to the machine: displays, sleep),
/// then komorebi's log and events, then the OS trace from the daemon outwards: komorebi's own calls,
/// the system's, then each application's, by name. A source this does not know comes last. The
/// records of a group keep the order they had.
///
/// # Example
///
/// ```rust
/// use komorebi_recorder::report::group_by_source;
/// use komorebi_recorder::timeline::{Record, SOURCE_EVENTS, SOURCE_KOMOREBI_LOG, TimelineEntry};
///
/// let record = |source: &str, text: &str| Record {
/// entry: TimelineEntry {
/// video_s: 1.0,
/// mach_ns: 0,
/// wall_utc: None,
/// source: source.to_string(),
/// pid: None,
/// file: String::new(),
/// offset: 0,
/// len: 0,
/// line: 1,
/// seq: None,
/// },
/// text: text.to_string(),
/// };
///
/// let records = [
/// record("oslog:app:Ghostty", "an app"),
/// record(SOURCE_EVENTS, "an event"),
/// record("oslog:system", "the system"),
/// record(SOURCE_KOMOREBI_LOG, "a log line"),
/// ];
/// let order: Vec<String> = group_by_source(&records)
/// .into_iter()
/// .map(|(source, _)| source)
/// .collect();
/// assert_eq!(order, ["komorebi-log", "events", "oslog:system", "oslog:app:Ghostty"]);
/// ```
#[must_use]
pub fn group_by_source(records: &[Record]) -> Vec<(String, Vec<&Record>)> {
let mut groups: BTreeMap<(u8, String), Vec<&Record>> = BTreeMap::new();
for record in records {
groups
.entry(source_rank(&record.entry.source))
.or_default()
.push(record);
}
groups
.into_iter()
.map(|((_, source), records)| (source, records))
.collect()
}
/// Renders the results of `at` and `range`: a heading with the number of records, then the records
/// a source at a time (in the order of [`group_by_source`]).
///
/// `center_s` is the video time the query was about; if it is given, each record also shows how far
/// from it the record is, as `(+0.100s)`. `limit_per_source` is the most records to show of each
/// source (`None` for all); a source with more reports how many it left out and how to see them.
/// With no records the text says nothing was recorded in the span.
///
/// # Example
///
/// ```rust
/// use komorebi_recorder::report::records_text;
/// use komorebi_recorder::timeline::{Record, SOURCE_KOMOREBI_LOG, TimelineEntry};
///
/// let log_line = |video_s: f64, text: &str| Record {
/// entry: TimelineEntry {
/// video_s,
/// mach_ns: 0,
/// wall_utc: None,
/// source: SOURCE_KOMOREBI_LOG.to_string(),
/// pid: None,
/// file: String::new(),
/// offset: 0,
/// len: 0,
/// line: 1,
/// seq: None,
/// },
/// text: text.to_string(),
/// };
///
/// let records = [log_line(12.4, "line a"), log_line(12.6, "line b")];
/// assert_eq!(
/// records_text("00:12.500 +-1s", &records, Some(12.5), Some(1)),
/// "\
/// 00:12.500 +-1s - 2 records
///
/// == komorebi-log (2) ==
/// 00:12.400 (-0.100s) line a
/// ... 1 more komorebi-log records (raise --limit or narrow with --source/--app)
/// ",
/// );
/// ```
#[must_use]
pub fn records_text(
heading: &str,
records: &[Record],
center_s: Option<f64>,
limit_per_source: Option<usize>,
) -> String {
let mut out = String::new();
let _ = writeln!(out, "{heading} - {} records", records.len());
if records.is_empty() {
let _ = writeln!(out, "(nothing was recorded in this span)");
return out;
}
for (source, group) in group_by_source(records) {
let _ = writeln!(out, "\n== {source} ({}) ==", group.len());
let shown = limit_per_source.map_or(group.len(), |limit| limit.min(group.len()));
for record in group.iter().take(shown) {
let time = timecode::format(record.entry.video_s);
match center_s {
Some(center) => {
let _ = writeln!(
out,
"{time} ({:+.3}s) {}",
record.entry.video_s - center,
record.text
);
}
None => {
let _ = writeln!(out, "{time} {}", record.text);
}
}
}
if shown < group.len() {
let _ = writeln!(
out,
"... {} more {source} records (raise --limit or narrow with --source/--app)",
group.len() - shown
);
}
}
out
}
/// Renders a `summary`: a line for each bucket of time.
///
/// By default a line counts the komorebi log lines (`log=`), the komorebi events (`events=`) and the
/// OS trace records of any application or the system (`os=`), and adds `recorder=` only for a
/// bucket in which something happened to the recording environment, so that it stands out. With
/// `by_source` it lists the count of every source instead. A bucket's first and last log line
/// follow it, the last only if it differs from the first.
///
/// # Example
///
/// ```rust
/// use komorebi_recorder::report::summary_text;
/// use komorebi_recorder::timeline::{Bucket, SOURCE_EVENTS, SOURCE_KOMOREBI_LOG};
/// use std::collections::BTreeMap;
///
/// let bucket = Bucket {
/// start_s: 12.0,
/// end_s: 13.0,
/// counts: BTreeMap::from([
/// (SOURCE_KOMOREBI_LOG.to_string(), 4),
/// (SOURCE_EVENTS.to_string(), 2),
/// ("oslog:app:Ghostty".to_string(), 30),
/// ("oslog:system".to_string(), 5),
/// ]),
/// first_log: Some("retiling".to_string()),
/// last_log: Some("retiling".to_string()),
/// };
///
/// assert_eq!(
/// summary_text(&[bucket], false),
/// "00:12.000 log=4 events=2 os=35\n first: retiling\n",
/// );
/// ```
#[must_use]
pub fn summary_text(buckets: &[Bucket], by_source: bool) -> String {
let mut out = String::new();
if buckets.is_empty() {
out.push_str("(nothing was recorded)\n");
return out;
}
for bucket in buckets {
let _ = write!(out, "{} ", timecode::format(bucket.start_s));
if by_source {
let counts = bucket
.counts
.iter()
.map(|(source, count)| format!("{source}={count}"))
.collect::<Vec<_>>()
.join(" ");
let _ = writeln!(out, "{counts}");
} else {
let sum = |predicate: &dyn Fn(&str) -> bool| -> u64 {
bucket
.counts
.iter()
.filter(|(source, _)| predicate(source))
.map(|(_, count)| *count)
.sum()
};
let _ = write!(
out,
"log={} events={} os={}",
sum(&|source| source == SOURCE_KOMOREBI_LOG),
sum(&|source| source == SOURCE_EVENTS),
sum(&|source| source.starts_with("oslog:")),
);
// something happened to the recording environment in this second: make it stand out
let incidents = sum(&|source| source == SOURCE_RECORDER);
if incidents > 0 {
let _ = write!(out, " recorder={incidents}");
}
let _ = writeln!(out);
}
if let Some(first) = &bucket.first_log {
let _ = writeln!(out, " first: {first}");
}
if let Some(last) = &bucket.last_log
&& bucket.first_log.as_ref() != Some(last)
{
let _ = writeln!(out, " last: {last}");
}
}
out
}
/// Renders a `locate`: what was found, where it falls in video time and UTC, and where in the video
/// file of each display that is.
///
/// A moment outside the recorded video is said to be. A display that was recorded at some point but
/// had no video then is named, with the reasons that can be.
///
/// # Example
///
/// ```rust
/// use komorebi_recorder::report::locate_text;
/// use komorebi_recorder::timeline::Located;
///
/// let located = Located {
/// description: "event #3".to_string(),
/// video_s: 12.5,
/// mach_ns: 17_500_000_000,
/// wall_utc: Some("2026-10-26T19:43:35.062613Z".to_string()),
/// in_video: true,
/// displays: Vec::new(),
/// without_video: vec![2],
/// };
///
/// let text = locate_text(&located);
/// assert!(text.starts_with("event #3\nvideo time: 00:12.500 (12.500s)\n"));
/// assert!(text.contains("utc: 2026-10-26T19:43:35.062613Z"));
/// assert!(text.contains("display 2: no video at this moment"));
/// ```
#[must_use]
pub fn locate_text(located: &Located) -> String {
let mut out = String::new();
let _ = writeln!(out, "{}", located.description);
let _ = writeln!(
out,
"video time: {} ({:.3}s){}",
timecode::format(located.video_s),
located.video_s,
if located.in_video {
""
} else {
" (outside the recorded video)"
}
);
if let Some(wall) = &located.wall_utc {
let _ = writeln!(out, "utc: {wall}");
}
for display in &located.displays {
let _ = writeln!(
out,
" display {}: {} at {} ({:.3}s)",
display.display,
display.file,
timecode::format(display.file_s),
display.file_s
);
}
for display in &located.without_video {
let _ = writeln!(
out,
" display {display}: no video at this moment (unplugged, asleep or its stream had stopped; see the recorder source)"
);
}
out
}
/// Renders one annotation: for a bug, the region and, verbatim, what the user said is wrong.
///
/// The first line says what it is, its id, the span in video time and its length, the displays and
/// the author. The lines after it appear when there is something to say: the title, the text (called
/// "what goes wrong" for a bug), what was expected, that the region is open-ended, that a bug needs
/// a description, what a finding is about and its evidence.
///
/// # Example
///
/// ```rust
/// use komorebi_recorder::annotations::fold;
/// use komorebi_recorder::report::annotation_text;
/// use komorebi_recorder::testkit::{SessionBuilder, mach_ns};
///
/// let (_session, manifest) = SessionBuilder::new("doc-annotation-text").build();
/// let text = format!(
/// r#"{{"v":1,"id":"a-00000001","op":"add","kind":"bug","start_mach_ns":{},"end_mach_ns":{},"text":"the window jumps"}}"#,
/// mach_ns(2.0),
/// mach_ns(5.0),
/// );
/// let bug = fold(&text).annotations.remove(0).view(&manifest);
///
/// assert_eq!(
/// annotation_text(&bug),
/// "bug a-00000001 00:02.000 -> 00:05.000 (3.000s) any display by user\n what goes wrong:\n the window jumps\n",
/// );
/// ```
#[must_use]
pub fn annotation_text(view: &AnnotationView) -> String {
let mut out = String::new();
let displays = if view.displays.is_empty() {
"any display".to_string()
} else {
format!(
"display {}",
view.displays
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(", ")
)
};
let _ = writeln!(
out,
"{} {} {} -> {} ({:.3}s) {displays} by {}",
view.kind,
view.id,
timecode::format(view.start_video_s),
timecode::format(view.end_video_s),
view.end_video_s - view.start_video_s,
view.author
);
let indent = |text: &str| text.lines().collect::<Vec<_>>().join("\n ");
if !view.title.is_empty() {
let _ = writeln!(out, " title: {}", view.title);
}
if !view.text.trim().is_empty() {
let label = match view.kind {
Kind::Bug => "what goes wrong",
Kind::Note => "note",
Kind::Finding => "finding",
};
let _ = writeln!(out, " {label}:\n {}", indent(&view.text));
}
if let Some(expected) = &view.expected {
let _ = writeln!(out, " expected:\n {}", indent(expected));
}
if view.open_ended {
let _ = writeln!(
out,
" open-ended: no end was set, so it runs to the end of the recording"
);
}
if view.needs_description {
let _ = writeln!(
out,
" needs a description: add one with `annotate <session> edit {} --text ...`",
view.id
);
}
if let Some(about) = &view.about {
let _ = writeln!(out, " about: {about}");
}
if !view.refs.is_empty() {
let refs: Vec<String> = view.refs.iter().map(ToString::to_string).collect();
let _ = writeln!(out, " evidence: {}", refs.join(", "));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::timeline::TimelineEntry;
fn record(source: &str, video_s: f64, text: &str) -> Record {
Record {
entry: TimelineEntry {
video_s,
mach_ns: 0,
wall_utc: None,
source: source.to_string(),
pid: None,
file: String::new(),
offset: 0,
len: 0,
line: 1,
seq: None,
},
text: text.to_string(),
}
}
#[test]
fn groups_in_display_order() {
let records = vec![
record("oslog:app:Ghostty", 1.0, "g"),
record("oslog:system", 1.0, "s"),
record(SOURCE_EVENTS, 1.0, "e"),
record("oslog:komorebi", 1.0, "k"),
record(SOURCE_KOMOREBI_LOG, 1.0, "l"),
record("oslog:app:Brave", 1.0, "b"),
record(SOURCE_RECORDER, 1.0, "r"),
];
let order: Vec<String> = group_by_source(&records)
.into_iter()
.map(|(source, _)| source)
.collect();
assert_eq!(
order,
[
SOURCE_RECORDER,
SOURCE_KOMOREBI_LOG,
SOURCE_EVENTS,
"oslog:komorebi",
"oslog:system",
"oslog:app:Brave",
"oslog:app:Ghostty",
]
);
}
#[test]
fn at_output_shows_offsets_and_truncates_per_source() {
let records = vec![
record(SOURCE_KOMOREBI_LOG, 12.4, "line a"),
record(SOURCE_KOMOREBI_LOG, 12.5, "line b"),
record(SOURCE_KOMOREBI_LOG, 12.6, "line c"),
];
let text = records_text("00:12.500 +-1s", &records, Some(12.5), Some(2));
assert!(text.contains("3 records"));
assert!(text.contains("== komorebi-log (3) =="));
assert!(text.contains("00:12.400 (-0.100s) line a"), "{text}");
assert!(text.contains("00:12.600 (+0.100s)") || text.contains("... 1 more"));
assert!(text.contains("... 1 more komorebi-log records"));
assert!(!text.contains("line c"));
}
#[test]
fn empty_results_say_so() {
assert!(records_text("x", &[], None, None).contains("nothing was recorded"));
}
#[test]
fn summary_collapses_oslog_sources_unless_asked() {
let bucket = Bucket {
start_s: 12.0,
end_s: 13.0,
counts: BTreeMap::from([
(SOURCE_KOMOREBI_LOG.to_string(), 4),
(SOURCE_EVENTS.to_string(), 2),
("oslog:app:Ghostty".to_string(), 30),
("oslog:system".to_string(), 5),
]),
first_log: Some("first".to_string()),
last_log: Some("last".to_string()),
};
let collapsed = summary_text(std::slice::from_ref(&bucket), false);
assert!(
collapsed.contains("00:12.000 log=4 events=2 os=35"),
"{collapsed}"
);
assert!(collapsed.contains("first: first"));
assert!(collapsed.contains("last: last"));
assert!(!collapsed.contains("recorder="), "no incidents, no column");
let detailed = summary_text(&[bucket], true);
assert!(detailed.contains("oslog:app:Ghostty=30"));
}
#[test]
fn summary_flags_a_second_in_which_the_environment_changed() {
let bucket = Bucket {
start_s: 40.0,
end_s: 41.0,
counts: BTreeMap::from([
(SOURCE_KOMOREBI_LOG.to_string(), 1),
(SOURCE_RECORDER.to_string(), 2),
]),
first_log: None,
last_log: None,
};
let text = summary_text(&[bucket], false);
assert!(
text.contains("00:40.000 log=1 events=0 os=0 recorder=2"),
"{text}"
);
}
}