Release Kaleido Desktop 0.1.0-beta.11

Fix a UI-thread deadlock between the player and window resizes: player_rect
held the video-surface lock while Tauri's hwnd() waited for the UI thread,
and on_resize, running on the UI thread, waited for that lock. Leaving full
screen for the miniplayer could freeze the window while mpv kept playing.
Resize handling now runs off the UI thread, and the Windows surface keeps its
HWND instead of asking the UI thread for it.

Add local diagnostics: a watchdog writes a dump of every thread when the UI
thread stops answering for 5 s, unhandled exceptions write a crash dump and
log the faulting module (Windows), and panics are logged. Windows release
builds keep function names in kaleido.pdb, archived per version in
.tools/symbols/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-04 17:04:07 -07:00
parent 0eb8518927
commit 3de7f83b7f
15 changed files with 362 additions and 10 deletions

View file

@ -1,5 +1,12 @@
# Changelog
## 0.1.0-beta.11
Fixes the app freezing when leaving full screen for the miniplayer, and adds local hang and crash reports.
- Fixed: going back from the full-screen player to the miniplayer (or moving or resizing the miniplayer) could freeze the window — it turned see-through and "Not Responding" while the video kept playing. Two parts of the player were each waiting for the other when the window resized at the wrong moment.
- When the window stops responding for 5 seconds, or the app crashes, Kaleido now saves a report of what each part of the app was doing in its log folder (`%LOCALAPPDATA%\tv.kaleido.desktop\logs`), so a rare problem can be traced the first time it happens. Reports stay on your computer.
## 0.1.0-beta.10
A redesigned player control bar, previous episode, and a movable miniplayer.

View file

@ -47,6 +47,32 @@ Playback tests change real Plex progress; resume an in-progress title near its s
position, or restore it afterwards. Selecting audio or subtitle tracks is saved to Plex
for that file.
## Diagnostics
`src-tauri/src/diagnostics.rs` writes to the app's log folder
(`%LOCALAPPDATA%\tv.kaleido.desktop\logs` on Windows); nothing is uploaded.
- **Hangs**: a watchdog asks the UI thread to answer every second. After 5 seconds of
silence it writes `kaleido-hang-<time>-v<version>.dmp` with every thread's stack (once
per stall) and notes the stall and the recovery in `diagnostics.log`.
- **Crashes** (Windows): an unhandled exception writes `kaleido-crash-…dmp` and logs the
exception and faulting module, e.g. `access violation at libmpv-2.dll+0x1234`.
- **Panics** are logged with a backtrace.
The newest five dumps of each kind are kept. To read one, open it in WinDbg with the
symbols of the exact build that wrote it: `scripts/build.ps1` keeps each release's
`kaleido.exe` and `kaleido.pdb` in `.tools/symbols/<version>/` (release builds keep
function names and line tables in the `.pdb`; the installer doesn't change). In WinDbg:
`.sympath+ <that folder>`, `.reload`, then `~*k` for every thread's stack.
Development builds have two test commands: `debug_freeze_ui` (`{ seconds }`, holds the
UI thread) and `debug_crash` (an access violation); both refuse to run in release builds.
Threading rule learned the hard way: Tauri's window getters (`hwnd()`, sizes…) called
off the UI thread wait for it to answer, so never call one while holding a lock the UI
thread might wait on, and keep window-event handlers from waiting on the player's locks
(they run on the UI thread; `lib.rs` hands resize handling to a background thread).
## App icon
`src-tauri/icons/app-icon.svg` is the source. Render it to a 1024×1024 `app-icon.png`

4
package-lock.json generated
View file

@ -1,12 +1,12 @@
{
"name": "kaleido-desktop",
"version": "0.1.0-beta.10",
"version": "0.1.0-beta.11",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "kaleido-desktop",
"version": "0.1.0-beta.10",
"version": "0.1.0-beta.11",
"dependencies": {
"@fontsource-variable/inter": "^5.3.0",
"@tanstack/react-query": "^5.105.0",

View file

@ -1,7 +1,7 @@
{
"name": "kaleido-desktop",
"private": true,
"version": "0.1.0-beta.10",
"version": "0.1.0-beta.11",
"type": "module",
"scripts": {
"dev": "vite",

View file

@ -21,10 +21,25 @@ if (-not $env:TAURI_SIGNING_PRIVATE_KEY) {
}
if (-not (Test-Path (Join-Path $root "node_modules"))) { npm ci }
# Symbols for reading hang and crash dumps (diagnostics.rs): keep function names
# and line tables in kaleido.pdb. They stay out of the executable.
$env:CARGO_PROFILE_RELEASE_STRIP = "none"
$env:CARGO_PROFILE_RELEASE_DEBUG = "line-tables-only"
$buildArgs = @("tauri", "build")
if ($Debug) { $buildArgs += "--debug" }
npx @buildArgs
if ($LASTEXITCODE -ne 0) { throw "Build failed" }
$profile = if ($Debug) { "debug" } else { "release" }
# Keep this version's executable and symbols: a dump can only be read with the
# exact build that wrote it (.tools/ is ignored).
if (-not $Debug) {
$version = (Get-Content (Join-Path $root "src-tauri\tauri.conf.json") -Raw | ConvertFrom-Json).version
$symbols = Join-Path $root ".tools\symbols\$version"
New-Item -ItemType Directory -Force $symbols | Out-Null
Copy-Item (Join-Path $root "src-tauri\target\release\kaleido.exe"), (Join-Path $root "src-tauri\target\release\kaleido.pdb") $symbols -Force
Write-Host "Symbols kept in $symbols"
}
Get-ChildItem (Join-Path $root "src-tauri\target\$profile\bundle\nsis") | Select-Object Name, Length

2
src-tauri/Cargo.lock generated
View file

@ -2173,7 +2173,7 @@ dependencies = [
[[package]]
name = "kaleido"
version = "0.1.0-beta.10"
version = "0.1.0-beta.11"
dependencies = [
"fs2",
"futures-util",

View file

@ -1,6 +1,6 @@
[package]
name = "kaleido"
version = "0.1.0-beta.10"
version = "0.1.0-beta.11"
description = "Kaleido — a Plex client for Windows"
authors = ["Elijah"]
edition = "2021"
@ -62,6 +62,11 @@ windows = { version = "0.61", features = [
"Win32_Graphics_Direct3D",
"Win32_Graphics_Direct3D11",
"Foundation_Numerics",
# Hang and crash dumps (diagnostics.rs).
"Win32_System_Diagnostics_Debug",
"Win32_System_Kernel",
"Win32_System_Memory",
"Win32_System_Threading",
] }
[profile.release]

View file

@ -0,0 +1,158 @@
//! Diagnostics that stay on this computer, in the app's log folder
//! (`%LOCALAPPDATA%\tv.kaleido.desktop\logs` on Windows):
//!
//! - A watchdog: if the UI thread stops answering for `HANG_AFTER`, it writes
//! a dump of every thread's stack (`kaleido-hang-*.dmp`), once per stall.
//! - Crashes write a dump of the crashing thread and the rest
//! (`kaleido-crash-*.dmp`; Windows only), and panics are logged.
//! - `diagnostics.log` notes each of these with the time.
//!
//! Nothing is uploaded. Dumps need the release's `kaleido.pdb` to read; the
//! build script keeps one per version (docs/development.md → Diagnostics).
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::OnceLock;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use tauri::{AppHandle, Manager, Runtime};
/// How long the UI thread may go without answering before a hang dump.
const HANG_AFTER: Duration = Duration::from_secs(5);
/// Dumps kept of each kind; older ones are removed.
const KEEP_DUMPS: usize = 5;
static DIR: OnceLock<PathBuf> = OnceLock::new();
static ORIGIN: OnceLock<Instant> = OnceLock::new();
/// When the UI thread last answered, in ms since `ORIGIN`.
static BEAT: AtomicU64 = AtomicU64::new(0);
fn now_ms() -> u64 {
ORIGIN.get_or_init(Instant::now).elapsed().as_millis() as u64
}
/// The folder for logs and dumps, once `start` has run.
pub fn dir() -> Option<&'static Path> {
DIR.get().map(PathBuf::as_path)
}
/// UTC date and time, e.g. `2026-11-04 16:43:07` (file names use `-` for `:`).
fn timestamp() -> String {
let secs = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
let (days, rem) = (secs / 86_400, secs % 86_400);
// Civil date from days since 1970-01-01 (Howard Hinnant's algorithm).
let z = days as i64 + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = yoe + era * 400 + i64::from(month <= 2);
format!("{year:04}-{month:02}-{day:02} {:02}:{:02}:{:02}", rem / 3600, rem / 60 % 60, rem % 60)
}
/// Appends a line to `diagnostics.log`.
pub fn log(line: &str) {
let Some(dir) = dir() else { return };
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(dir.join("diagnostics.log")) {
let _ = writeln!(f, "{} UTC {line}", timestamp());
}
}
/// A new dump's path, after removing the oldest of its kind beyond `KEEP_DUMPS`.
pub fn dump_path(kind: &str) -> Option<PathBuf> {
let dir = dir()?;
let prefix = format!("kaleido-{kind}-");
if let Ok(entries) = std::fs::read_dir(dir) {
let mut old: Vec<PathBuf> = entries
.flatten()
.map(|e| e.path())
.filter(|p| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(&prefix) && n.ends_with(".dmp")))
.collect();
old.sort();
while old.len() >= KEEP_DUMPS {
let _ = std::fs::remove_file(old.remove(0));
}
}
let name = format!("{prefix}{}-v{}.dmp", timestamp().replace([' ', ':'], "-"), env!("CARGO_PKG_VERSION"));
Some(dir.join(name))
}
/// Sets up the log folder, crash and panic reporting, and the hang watchdog.
pub fn start<R: Runtime>(app: &AppHandle<R>) {
let Ok(dir) = app.path().app_log_dir() else { return };
if std::fs::create_dir_all(&dir).is_err() || DIR.set(dir).is_err() {
return;
}
crate::platform::install_crash_handler();
let previous = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
let thread = std::thread::current();
log(&format!(
"panic on thread {}: {info}\n{}",
thread.name().unwrap_or("unnamed"),
std::backtrace::Backtrace::force_capture()
));
previous(info);
}));
let app = app.clone();
let _ = std::thread::Builder::new().name("ui-watchdog".into()).spawn(move || watchdog(app));
}
/// Development builds only: holds the UI thread for `seconds`, to test the watchdog.
#[tauri::command]
pub fn debug_freeze_ui<R: Runtime>(app: AppHandle<R>, seconds: u64) -> Result<(), String> {
if !cfg!(debug_assertions) {
return Err("Only available in development builds.".into());
}
app.run_on_main_thread(move || std::thread::sleep(Duration::from_secs(seconds.min(30)))).map_err(|e| e.to_string())
}
/// Development builds only: crashes with an access violation, to test crash dumps.
#[tauri::command]
pub fn debug_crash() -> Result<(), String> {
if !cfg!(debug_assertions) {
return Err("Only available in development builds.".into());
}
let _ = std::thread::Builder::new().name("debug-crash".into()).spawn(|| unsafe {
std::ptr::null_mut::<u8>().write_volatile(1);
});
Ok(())
}
/// Asks the UI thread to note the time every second; if it hasn't for
/// `HANG_AFTER`, the UI thread is stuck: dump every thread's stack.
fn watchdog<R: Runtime>(app: AppHandle<R>) {
BEAT.store(now_ms(), Ordering::Relaxed);
let mut last_tick = now_ms();
let mut stalled_since: Option<u64> = None;
loop {
let _ = app.run_on_main_thread(|| BEAT.store(now_ms(), Ordering::Relaxed));
std::thread::sleep(Duration::from_secs(1));
let now = now_ms();
// This thread was itself held up (the computer slept): not a hang.
if now - last_tick > 3_000 {
BEAT.store(now, Ordering::Relaxed);
}
last_tick = now;
let silent = now.saturating_sub(BEAT.load(Ordering::Relaxed));
if silent >= HANG_AFTER.as_millis() as u64 {
if stalled_since.is_none() {
stalled_since = Some(now - silent);
let written = dump_path("hang").map(|p| (crate::platform::write_dump(&p), p));
match written {
Some((Ok(()), path)) => log(&format!("UI thread stopped answering for {}s; wrote {}", silent / 1000, path.display())),
Some((Err(e), _)) => log(&format!("UI thread stopped answering for {}s; no dump: {e}", silent / 1000)),
None => {}
}
}
} else if let Some(since) = stalled_since.take() {
log(&format!("UI thread answering again after {:.1}s", (now - since) as f64 / 1000.0));
}
}
}

View file

@ -1,3 +1,4 @@
mod diagnostics;
mod downloads;
mod mpv;
mod platform;
@ -26,12 +27,16 @@ pub fn run() {
.manage(downloads::Downloads::default())
.setup(|app| {
let handle = app.handle().clone();
diagnostics::start(&handle);
downloads::restore(&handle);
if let Some(window) = app.get_webview_window("main") {
let w = window.clone();
window.on_window_event(move |event| {
if let WindowEvent::Resized(_) | WindowEvent::ScaleFactorChanged { .. } = event {
player::on_resize(&w);
// Never on the UI thread: the player's locks may be held by a
// command that is itself waiting on the UI thread (see player.rs).
let w = w.clone();
tauri::async_runtime::spawn_blocking(move || player::on_resize(&w));
}
});
}
@ -60,6 +65,8 @@ pub fn run() {
downloads::download_list,
downloads::download_set_dir,
downloads::download_write_meta,
diagnostics::debug_freeze_ui,
diagnostics::debug_crash,
])
.run(tauri::generate_context!())
.expect("error while running Kaleido");

View file

@ -48,3 +48,13 @@ pub fn hold_awake(rx: std::sync::mpsc::Receiver<()>) {
// TODO(Linux): org.freedesktop.ScreenSaver.Inhibit over D-Bus.
let _ = rx.recv();
}
// —— Diagnostics (see diagnostics.rs) ————————————————————————————————————
/// Hang dumps are Windows-only for now; the watchdog still logs the stall.
pub fn write_dump(_: &std::path::Path) -> Result<(), String> {
Err("dumps are not written on this platform".into())
}
/// Crashes are left to the system's crash reporter here.
pub fn install_crash_handler() {}

View file

@ -536,3 +536,13 @@ pub fn hold_awake(rx: Receiver<()>) {
CFRelease(name);
}
}
// —— Diagnostics (see diagnostics.rs) ————————————————————————————————————
/// Hang dumps are Windows-only for now; the watchdog still logs the stall.
pub fn write_dump(_: &std::path::Path) -> Result<(), String> {
Err("dumps are not written on this platform".into())
}
/// Crashes are left to the system's crash reporter here.
pub fn install_crash_handler() {}

View file

@ -9,6 +9,7 @@
//! - `gpu_names`: the graphics adapters, by name.
//! - `device_name`, `os_version`: how the computer identifies itself to Plex.
//! - `set_window_buttons`: shows or hides native window buttons (macOS).
//! - `write_dump`, `install_crash_handler`: hang and crash dumps (Windows).
#[cfg(target_os = "windows")]
mod windows;

View file

@ -10,6 +10,9 @@ use ::windows::Win32::UI::WindowsAndMessaging::GetClientRect;
use crate::mpv::Mpv;
pub struct VideoSurface {
/// The window, kept so fitting needn't ask the UI thread for it (Tauri's
/// `hwnd()` waits on the UI thread when called from elsewhere).
hwnd: HWND,
attached: usize,
device: IDCompositionDevice,
_target: IDCompositionTarget,
@ -46,6 +49,7 @@ impl VideoSurface {
device.Commit().map_err(|e| e.to_string())?;
let _ = &target;
Ok(VideoSurface {
hwnd,
attached: 0,
device,
_target: target,
@ -112,9 +116,8 @@ impl VideoSurface {
/// Matches mpv's composition size and the visual's position to the
/// window's client area, or to the miniplayer rectangle when one is set.
pub fn fit<R: Runtime>(&mut self, window: &WebviewWindow<R>, mpv: Option<&Mpv>) {
let Ok(h) = window.hwnd() else { return };
let (cw, ch) = client_size(HWND(h.0 as _));
pub fn fit<R: Runtime>(&mut self, _: &WebviewWindow<R>, mpv: Option<&Mpv>) {
let (cw, ch) = client_size(self.hwnd);
let (x, y, w, h) = match self.rect {
Some((x, y, w, h)) => (x, y, w.max(16), h.max(16)),
None => (0, 0, cw, ch),
@ -181,6 +184,110 @@ pub fn os_version() -> String {
/// Windows draws its own caption buttons in the page.
pub fn set_window_buttons<R: Runtime>(_: &WebviewWindow<R>, _: bool) {}
// —— Diagnostics (see diagnostics.rs) ————————————————————————————————————
use ::windows::Win32::System::Diagnostics::Debug::{
MiniDumpWithHandleData, MiniDumpWithThreadInfo, MiniDumpWithUnloadedModules, MiniDumpWriteDump, SetUnhandledExceptionFilter,
EXCEPTION_CONTINUE_SEARCH, EXCEPTION_POINTERS, MINIDUMP_EXCEPTION_INFORMATION, MINIDUMP_TYPE,
};
use ::windows::Win32::System::Threading::{GetCurrentProcess, GetCurrentProcessId, GetCurrentThreadId};
use std::os::windows::io::AsRawHandle;
use std::path::Path;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
/// Every thread's stack and state, the loaded and unloaded modules and the
/// open handles: what a hang or crash needs, in a few megabytes.
const DUMP_TYPE: MINIDUMP_TYPE = MINIDUMP_TYPE(MiniDumpWithThreadInfo.0 | MiniDumpWithHandleData.0 | MiniDumpWithUnloadedModules.0);
fn write_dump_with(path: &Path, exception: Option<*const EXCEPTION_POINTERS>) -> Result<(), String> {
let file = std::fs::File::create(path).map_err(|e| e.to_string())?;
let info = exception.map(|pointers| MINIDUMP_EXCEPTION_INFORMATION {
ThreadId: unsafe { GetCurrentThreadId() },
ExceptionPointers: pointers as *mut _,
ClientPointers: false.into(),
});
let file_handle = ::windows::Win32::Foundation::HANDLE(file.as_raw_handle());
unsafe {
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), file_handle, DUMP_TYPE, info.as_ref().map(|i| i as *const _), None, None)
.map_err(|e| e.to_string())
}
}
/// Dumps this process as it is now (the hang watchdog's snapshot).
pub fn write_dump(path: &Path) -> Result<(), String> {
write_dump_with(path, None)
}
/// "access violation at libmpv-2.dll+0x1234 (0xC0000005)", for the log.
unsafe fn describe(pointers: *const EXCEPTION_POINTERS) -> String {
use ::windows::Win32::Foundation::HMODULE;
use ::windows::Win32::System::LibraryLoader::*;
let Some(record) = (*pointers).ExceptionRecord.as_ref() else { return "unknown exception".into() };
let code = record.ExceptionCode.0 as u32;
let address = record.ExceptionAddress as usize;
let mut module = HMODULE::default();
let place = if GetModuleHandleExW(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
::windows::core::PCWSTR(address as *const u16),
&mut module,
)
.is_ok()
{
let mut name = [0u16; 260];
let len = GetModuleFileNameW(Some(module), &mut name) as usize;
let path = String::from_utf16_lossy(&name[..len]);
let file = path.rsplit('\\').next().unwrap_or(&path).to_string();
format!("{file}+{:#x}", address - module.0 as usize)
} else {
format!("{address:#x}")
};
let what = match code {
0xC000_0005 => "access violation",
0xC000_00FD => "stack overflow",
0xC000_0409 => "fail-fast (security check)",
0xC000_001D => "illegal instruction",
0xC000_0094 => "integer division by zero",
_ => "exception",
};
format!("{what} at {place} ({code:#010X})")
}
static PREVIOUS_FILTER: AtomicUsize = AtomicUsize::new(0);
static CRASHED: AtomicBool = AtomicBool::new(false);
unsafe extern "system" fn on_crash(pointers: *const EXCEPTION_POINTERS) -> i32 {
if !CRASHED.swap(true, Ordering::SeqCst) {
let what = describe(pointers);
match crate::diagnostics::dump_path("crash") {
Some(path) => match write_dump_with(&path, Some(pointers)) {
Ok(()) => crate::diagnostics::log(&format!("crash: {what}; wrote {}", path.display())),
Err(e) => crate::diagnostics::log(&format!("crash: {what}; no dump: {e}")),
},
None => crate::diagnostics::log(&format!("crash: {what}")),
}
}
// Then whatever handled it before (Windows Error Reporting by default).
match PREVIOUS_FILTER.load(Ordering::SeqCst) {
0 => EXCEPTION_CONTINUE_SEARCH,
previous => {
let previous: unsafe extern "system" fn(*const EXCEPTION_POINTERS) -> i32 = std::mem::transmute(previous);
previous(pointers)
}
}
}
/// Writes a dump when the process is about to die of an unhandled exception.
/// Called again once libmpv is loaded, in case its runtime replaced it.
pub fn install_crash_handler() {
unsafe {
if let Some(previous) = SetUnhandledExceptionFilter(Some(on_crash)) {
if previous as usize != on_crash as *const () as usize {
PREVIOUS_FILTER.store(previous as usize, Ordering::SeqCst);
}
}
}
}
/// Keeps the display awake until `rx` closes or receives.
pub fn hold_awake(rx: std::sync::mpsc::Receiver<()>) {
use ::windows::Win32::System::Power::*;

View file

@ -14,6 +14,10 @@ use tauri::{AppHandle, Emitter, Manager, Runtime, WebviewWindow};
use crate::mpv::{self, Event, Mpv};
use crate::platform::VideoSurface;
/// Both locks are taken by commands on background threads, and some window
/// calls made while holding them (Tauri's getters, such as `hwnd()`) wait for
/// the UI thread to answer. So the UI thread must never wait on these locks:
/// window events hand their work to a background thread (lib.rs).
#[derive(Default)]
pub struct PlayerState {
mpv: Mutex<Option<Arc<Mpv>>>,
@ -60,6 +64,8 @@ fn emit<R: Runtime>(app: &AppHandle<R>, payload: Value) {
fn create_player<R: Runtime>(app: &AppHandle<R>, window: &WebviewWindow<R>, opts: &InitOptions) -> Result<Arc<Mpv>, String> {
let resource_dir = app.path().resource_dir().ok();
let mpv = Mpv::load(&mpv::library_candidates(resource_dir))?;
// libmpv's runtime may install its own crash filter as it loads; ours goes back on top.
crate::platform::install_crash_handler();
let surface = VideoSurface::create(window)?;
let render_options = surface.mpv_options();
*app.state::<PlayerState>().surface.lock() = Some(surface);

View file

@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Kaleido",
"version": "0.1.0-beta.10",
"version": "0.1.0-beta.11",
"identifier": "tv.kaleido.desktop",
"build": {
"beforeDevCommand": "npm run dev",