Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

48.1 KB
Raw Blame
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use tauri::Manager;
use tokio::process::Command;

#[cfg(windows)]
const CREATE_NO_WINDOW: u32 = 0x08000000;

const MAX_TIMELAPSE_FRAME_BYTES: usize = 12 * 1024 * 1024; // 12 MB ceiling per keyframe (supports 4K)
const MAX_TIMELAPSE_EXPORT_FRAMES: usize = 100_000;
const MAX_TIMELAPSE_BATCH_FRAMES: usize = 2048;
const MAX_TIMELAPSE_BATCH_BYTES: usize = 64 * 1024 * 1024; // 64 MB ceiling per batch IPC
const MAX_WATERMARK_PNG_BYTES: usize = 8 * 1024 * 1024; // 8 MB ceiling for watermark overlay PNG
const MIN_BATCH_RECORD_BYTES: usize = 4 + 1 + 4; // frame_index(u32) + ext_code(u8) + data_len(u32)

static TMP_META_SEQ: AtomicU64 = AtomicU64::new(1);

fn default_capture_area() -> String {
    "artwork".to_string()
}

fn default_capture_resolution() -> String {
    "1080p".to_string()
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FrameBatchEntry {
    pub frame_index: u32,
    pub ext: &'static str,
    pub data: Vec<u8>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct TimelapseSessionMeta {
    pub recording_id: String,
    #[serde(default)]
    pub document_name: String,
    #[serde(default)]
    pub enabled: bool,
    #[serde(default = "default_capture_area")]
    pub capture_area: String,
    #[serde(default = "default_capture_resolution")]
    pub capture_resolution: String,
    #[serde(default)]
    pub next_index: u32,
    #[serde(default)]
    pub created_at: u64,
    #[serde(default)]
    pub updated_at: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct TimelapseFrameRecord {
    pub index: u32,
    pub timestamp: u64,
    pub width: u32,
    pub height: u32,
    pub mime_type: String,
    pub bytes: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capture_area: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LoadedTimelapseSession {
    pub meta: Option<TimelapseSessionMeta>,
    pub frames: Vec<TimelapseFrameRecord>,
    pub total_bytes: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StoredTimelapseSummary {
    pub recording_id: String,
    pub document_name: String,
    pub enabled: bool,
    pub capture_area: String,
    pub capture_resolution: String,
    pub frame_count: usize,
    pub total_bytes: u64,
    pub created_at: u64,
    pub updated_at: u64,
}

#[derive(Debug, Clone)]
pub struct FrameWriteMeta {
    pub timestamp: u64,
    pub width: u32,
    pub height: u32,
    pub capture_area: Option<String>,
}

#[derive(Debug, Clone)]
pub struct FfmpegExportParams<'a> {
    pub session_id: &'a str,
    pub frame_indices: Vec<u32>,
    pub ext: &'a str,
    pub fps: u32,
    pub width: u32,
    pub height: u32,
    pub bg_color: &'a str,
    pub bg_blur: bool,
    pub quality: &'a str,
    pub watermark_png: Option<&'a [u8]>,
    pub watermark_x: i32,
    pub watermark_y: i32,
}

fn ext_to_code(ext: &str) -> Result<u8, String> {
    match sanitize_ext(ext)? {
        "webp" => Ok(0),
        "jpg" => Ok(1),
        "png" => Ok(2),
        _ => Err("Unsupported timelapse frame extension".to_string()),
    }
}

fn code_to_ext(code: u8) -> Result<&'static str, String> {
    match code {
        0 => Ok("webp"),
        1 => Ok("jpg"),
        2 => Ok("png"),
        _ => Err(format!("Unknown timelapse extension code: {}", code)),
    }
}

fn ext_to_mime(ext: &str) -> &'static str {
    match ext {
        "jpg" | "jpeg" => "image/jpeg",
        "png" => "image/png",
        _ => "image/webp",
    }
}

/// Packs a batch of timelapse frames into a compact binary wire frame:
/// `[count: u32 LE] ([frame_index: u32 LE][ext_code: u8][data_len: u32 LE][data])*`
#[allow(dead_code)]
pub fn pack_frame_batch(entries: &[FrameBatchEntry]) -> Result<Vec<u8>, String> {
    if entries.len() > MAX_TIMELAPSE_BATCH_FRAMES {
        return Err("Timelapse frame batch count exceeds safety ceiling".to_string());
    }
    let mut total: usize = 4;
    for entry in entries {
        if entry.data.len() > MAX_TIMELAPSE_FRAME_BYTES {
            return Err("Timelapse frame exceeds safety size limit".to_string());
        }
        let _ = ext_to_code(entry.ext)?;
        total = total
            .checked_add(MIN_BATCH_RECORD_BYTES)
            .and_then(|n| n.checked_add(entry.data.len()))
            .ok_or_else(|| "Timelapse batch size overflow".to_string())?;
    }
    if total > MAX_TIMELAPSE_BATCH_BYTES {
        return Err("Timelapse frame batch exceeds 64 MB safety limit".to_string());
    }

    let mut out = Vec::with_capacity(total);
    out.extend_from_slice(&(entries.len() as u32).to_le_bytes());
    for entry in entries {
        out.extend_from_slice(&entry.frame_index.to_le_bytes());
        out.push(ext_to_code(entry.ext)?);
        out.extend_from_slice(&(entry.data.len() as u32).to_le_bytes());
        out.extend_from_slice(&entry.data);
    }
    Ok(out)
}

/// Unpacks a binary timelapse frame batch written by the frontend during migration/restore.
pub fn unpack_frame_batch(bytes: &[u8]) -> Result<Vec<FrameBatchEntry>, String> {
    if bytes.len() < 4 {
        return Err("Truncated timelapse frame batch header".to_string());
    }
    if bytes.len() > MAX_TIMELAPSE_BATCH_BYTES {
        return Err("Timelapse frame batch exceeds 64 MB safety limit".to_string());
    }
    let count = u32::from_le_bytes(bytes[0..4].try_into().unwrap()) as usize;
    if count > MAX_TIMELAPSE_BATCH_FRAMES {
        return Err("Timelapse frame batch count exceeds safety ceiling".to_string());
    }
    if count > (bytes.len() - 4) / MIN_BATCH_RECORD_BYTES {
        return Err("Truncated timelapse frame batch payload".to_string());
    }

    let mut offset = 4usize;
    let mut out = Vec::with_capacity(count);
    for _ in 0..count {
        let header_end = offset
            .checked_add(MIN_BATCH_RECORD_BYTES)
            .filter(|&e| e <= bytes.len())
            .ok_or_else(|| "Truncated timelapse batch entry header".to_string())?;
        let frame_index = u32::from_le_bytes(bytes[offset..offset + 4].try_into().unwrap());
        let ext = code_to_ext(bytes[offset + 4])?;
        let data_len = u32::from_le_bytes(bytes[offset + 5..offset + 9].try_into().unwrap()) as usize;
        offset = header_end;

        if data_len == 0 || data_len > MAX_TIMELAPSE_FRAME_BYTES {
            return Err("Invalid timelapse frame size in batch".to_string());
        }
        let data_end = offset
            .checked_add(data_len)
            .filter(|&e| e <= bytes.len())
            .ok_or_else(|| "Truncated timelapse batch entry data".to_string())?;
        out.push(FrameBatchEntry {
            frame_index,
            ext,
            data: bytes[offset..data_end].to_vec(),
        });
        offset = data_end;
    }

    if offset != bytes.len() {
        return Err("Unexpected trailing bytes in timelapse frame batch".to_string());
    }
    Ok(out)
}

/// Unpacks a raw little-endian u32 array of frame indices.
pub fn unpack_frame_indices(bytes: &[u8]) -> Result<Vec<u32>, String> {
    if bytes.len() % 4 != 0 {
        return Err("Invalid frame_indices byte length (must be multiple of 4)".to_string());
    }
    let count = bytes.len() / 4;
    if count > MAX_TIMELAPSE_EXPORT_FRAMES {
        return Err("Timelapse export frame count exceeds safety ceiling".to_string());
    }
    let mut indices = Vec::with_capacity(count);
    for chunk in bytes.chunks_exact(4) {
        indices.push(u32::from_le_bytes(chunk.try_into().unwrap()));
    }
    Ok(indices)
}

fn sanitize_session_id(raw: &str) -> String {
    let s: String = raw
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
                c
            } else {
                '_'
            }
        })
        .collect();
    if s.is_empty() {
        "default".to_string()
    } else {
        s
    }
}

fn sanitize_ext(ext: &str) -> Result<&'static str, String> {
    match ext.to_ascii_lowercase().as_str() {
        "webp" => Ok("webp"),
        "jpg" | "jpeg" => Ok("jpg"),
        "png" => Ok("png"),
        _ => Err("Unsupported timelapse frame extension".to_string()),
    }
}

/// Sanitizes hex color `#RRGGBB` into FFmpeg `0xRRGGBB` notation.
pub fn sanitize_ffmpeg_hex_color(raw: &str) -> String {
    let trimmed = raw.trim().trim_start_matches('#');
    if trimmed.len() == 6 && trimmed.chars().all(|c| c.is_ascii_hexdigit()) {
        format!("0x{}", trimmed.to_ascii_lowercase())
    } else {
        "0xffffff".to_string()
    }
}

/// Maps quality preset string into FFmpeg `(crf, preset)` tuple.
pub fn quality_to_ffmpeg_crf_preset(quality: &str) -> (&'static str, &'static str) {
    match quality.to_ascii_lowercase().as_str() {
        "standard" | "low" => ("26", "veryfast"),
        "ultra" => ("15", "medium"),
        "lossless" | "max" => ("10", "medium"),
        _ => ("20", "fast"), // "high" default
    }
}

/// Builds the FFmpeg `-vf` / `-filter_complex` expression and output map flag.
pub fn build_ffmpeg_filtergraph(
    width: u32,
    height: u32,
    bg_color: &str,
    bg_blur: bool,
    has_watermark: bool,
    watermark_x: i32,
    watermark_y: i32,
) -> (bool, String) {
    let safe_w = width.clamp(64, 3840) & !1;
    let safe_h = height.clamp(64, 3840) & !1;
    let safe_color = sanitize_ffmpeg_hex_color(bg_color);
    let wx = watermark_x.clamp(0, safe_w as i32);
    let wy = watermark_y.clamp(0, safe_h as i32);

    if bg_blur {
        let base_chain = format!(
            "[0:v]split=2[bg][fg];[bg]scale={w}:{h}:force_original_aspect_ratio=increase,crop={w}:{h},boxblur=20:2[bgb];[fg]scale={w}:{h}:force_original_aspect_ratio=decrease[fgs];[bgb][fgs]overlay=(W-w)/2:(H-h)/2,setsar=1[base]",
            w = safe_w,
            h = safe_h
        );
        if has_watermark {
            let full = format!(
                "{};[base][1:v]overlay={}:{}:format=auto[out]",
                base_chain, wx, wy
            );
            (true, full)
        } else {
            let full = base_chain.replace("[base]", "[out]");
            (true, full)
        }
    } else if has_watermark {
        let full = format!(
            "[0:v]scale={w}:{h}:force_original_aspect_ratio=decrease,pad={w}:{h}:(ow-iw)/2:(oh-ih)/2:color={c},setsar=1[base];[base][1:v]overlay={x}:{y}:format=auto[out]",
            w = safe_w,
            h = safe_h,
            c = safe_color,
            x = wx,
            y = wy
        );
        (true, full)
    } else {
        let vf = format!(
            "scale={w}:{h}:force_original_aspect_ratio=decrease,pad={w}:{h}:(ow-iw)/2:(oh-ih)/2:color={c},setsar=1",
            w = safe_w,
            h = safe_h,
            c = safe_color
        );
        (false, vf)
    }
}

/// Persistent root directory for external time-lapse storage (survives app restarts & OS temp cleanup).
pub fn get_timelapse_root(app: Option<&tauri::AppHandle>) -> PathBuf {
    #[cfg(target_os = "windows")]
    {
        if let Ok(local_app_data) = std::env::var("LOCALAPPDATA") {
            return PathBuf::from(local_app_data).join("inkstudio_timelapse");
        }
    }
    if let Some(app_handle) = app {
        if let Ok(dir) = app_handle.path().app_local_data_dir() {
            return dir.join("inkstudio_timelapse");
        }
    }
    std::env::temp_dir().join("inkstudio_timelapse")
}

fn legacy_temp_session_dir(session_id: &str) -> PathBuf {
    std::env::temp_dir()
        .join("inkstudio_timelapse")
        .join(sanitize_session_id(session_id))
}

fn session_dir_in(root: &Path, session_id: &str) -> PathBuf {
    root.join(sanitize_session_id(session_id))
}

fn resolve_existing_session_dir(root: &Path, session_id: &str) -> PathBuf {
    let primary = session_dir_in(root, session_id);
    if primary.exists() {
        return primary;
    }
    let legacy = legacy_temp_session_dir(session_id);
    if legacy != primary && legacy.exists() {
        return legacy;
    }
    primary
}

/// Normalize Windows separators (`\` -> `/`) and escape single quotes (`'` -> `'\''`)
/// per FFmpeg concat demuxer single-quoted token syntax.
fn escape_ffmpeg_concat_path(path: &Path) -> String {
    path.to_string_lossy()
        .replace('\\', "/")
        .replace('\'', "'\\''")
}

fn append_ndjson_records_sync(dir: &Path, records: &[TimelapseFrameRecord]) -> Result<(), String> {
    if records.is_empty() {
        return Ok(());
    }
    let index_path = dir.join("frames.ndjson");
    let mut file = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&index_path)
        .map_err(|e| format!("Failed to open timelapse frame index: {}", e))?;
    for rec in records {
        let line = serde_json::to_string(rec).map_err(|e| e.to_string())?;
        writeln!(file, "{}", line).map_err(|e| e.to_string())?;
    }
    Ok(())
}

fn parse_ndjson_index_sync(dir: &Path) -> HashMap<u32, TimelapseFrameRecord> {
    let mut map = HashMap::new();
    let index_path = dir.join("frames.ndjson");
    let Ok(contents) = std::fs::read_to_string(&index_path) else {
        return map;
    };
    for line in contents.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        if let Ok(rec) = serde_json::from_str::<TimelapseFrameRecord>(trimmed) {
            map.insert(rec.index, rec);
        }
    }
    map
}

fn atomic_write_json_sync(path: &Path, data: &[u8]) -> Result<(), String> {
    let seq = TMP_META_SEQ.fetch_add(1, Ordering::Relaxed);
    let tmp_name = format!(
        ".{}.tmp.{}.{}",
        path.file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("meta.json"),
        std::process::id(),
        seq
    );
    let tmp_path = path.with_file_name(tmp_name);
    std::fs::write(&tmp_path, data).map_err(|e| e.to_string())?;
    if let Err(rename_err) = std::fs::rename(&tmp_path, path) {
        // Windows rename onto an existing destination can fail on some FS drivers; fallback cleanly.
        let _ = std::fs::remove_file(path);
        if std::fs::rename(&tmp_path, path).is_err() {
            let _ = std::fs::remove_file(&tmp_path);
            std::fs::write(path, data)
                .map_err(|e| format!("Failed to save metadata ({}): {}", rename_err, e))?;
        }
    }
    Ok(())
}

pub async fn save_session_meta_in(
    root: PathBuf,
    session_id: &str,
    meta_json: &str,
) -> Result<(), String> {
    let dir = session_dir_in(&root, session_id);
    let parsed: TimelapseSessionMeta = serde_json::from_str(meta_json)
        .map_err(|e| format!("Invalid timelapse session metadata: {}", e))?;
    let serialized = serde_json::to_vec(&parsed).map_err(|e| e.to_string())?;
    tokio::task::spawn_blocking(move || -> Result<(), String> {
        std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
        atomic_write_json_sync(&dir.join("meta.json"), &serialized)
    })
    .await
    .map_err(|e| format!("Timelapse meta save worker failed: {}", e))?
}

pub async fn save_session_meta(
    app: &tauri::AppHandle,
    session_id: &str,
    meta_json: &str,
) -> Result<(), String> {
    save_session_meta_in(get_timelapse_root(Some(app)), session_id, meta_json).await
}

pub async fn write_frame_in(
    root: PathBuf,
    session_id: &str,
    frame_index: u32,
    ext: &str,
    data: Vec<u8>,
    meta: Option<FrameWriteMeta>,
) -> Result<(), String> {
    if data.len() > MAX_TIMELAPSE_FRAME_BYTES {
        return Err("Timelapse frame exceeds 12 MB safety limit".to_string());
    }
    let safe_ext = sanitize_ext(ext)?;
    let dir = session_dir_in(&root, session_id);
    tokio::task::spawn_blocking(move || -> Result<(), String> {
        std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
        let path = dir.join(format!("frame_{:06}.{}", frame_index, safe_ext));
        std::fs::write(&path, &data).map_err(|e| e.to_string())?;
        if let Some(m) = meta {
            let record = TimelapseFrameRecord {
                index: frame_index,
                timestamp: m.timestamp,
                width: m.width.max(2),
                height: m.height.max(2),
                mime_type: ext_to_mime(safe_ext).to_string(),
                bytes: data.len() as u64,
                capture_area: m.capture_area,
            };
            let _ = append_ndjson_records_sync(&dir, &[record]);
        }
        Ok(())
    })
    .await
    .map_err(|e| format!("Timelapse frame write worker failed: {}", e))?
}

pub async fn write_frame(
    app: &tauri::AppHandle,
    session_id: &str,
    frame_index: u32,
    ext: &str,
    data: &[u8],
    meta: Option<FrameWriteMeta>,
) -> Result<(), String> {
    write_frame_in(
        get_timelapse_root(Some(app)),
        session_id,
        frame_index,
        ext,
        data.to_vec(),
        meta,
    )
    .await
}

pub async fn write_frames_batch_in(
    root: PathBuf,
    session_id: &str,
    entries: Vec<FrameBatchEntry>,
    records: Option<Vec<TimelapseFrameRecord>>,
) -> Result<usize, String> {
    if entries.is_empty() {
        return Ok(0);
    }
    let dir = session_dir_in(&root, session_id);
    let count = entries.len();
    tokio::task::spawn_blocking(move || -> Result<usize, String> {
        std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
        let mut fallback_records: Vec<TimelapseFrameRecord> = Vec::new();
        for entry in entries {
            let safe_ext = sanitize_ext(entry.ext)?;
            let path = dir.join(format!("frame_{:06}.{}", entry.frame_index, safe_ext));
            std::fs::write(&path, &entry.data).map_err(|e| e.to_string())?;
            if records.is_none() {
                fallback_records.push(TimelapseFrameRecord {
                    index: entry.frame_index,
                    timestamp: 0,
                    width: 0,
                    height: 0,
                    mime_type: ext_to_mime(safe_ext).to_string(),
                    bytes: entry.data.len() as u64,
                    capture_area: None,
                });
            }
        }
        let to_append = records.as_deref().unwrap_or(&fallback_records);
        let _ = append_ndjson_records_sync(&dir, to_append);
        Ok(count)
    })
    .await
    .map_err(|e| format!("Timelapse batch write worker failed: {}", e))?
}

pub async fn write_frames_batch(
    app: &tauri::AppHandle,
    session_id: &str,
    entries: Vec<FrameBatchEntry>,
) -> Result<usize, String> {
    write_frames_batch_in(get_timelapse_root(Some(app)), session_id, entries, None).await
}

fn scan_disk_frames_sync(dir: &Path) -> Result<Vec<(u32, String, u64)>, String> {
    if !dir.exists() {
        return Ok(Vec::new());
    }
    let mut found: Vec<(u32, String, u64)> = Vec::new();
    let entries = std::fs::read_dir(dir).map_err(|e| e.to_string())?;
    for entry in entries.flatten() {
        let path = entry.path();
        if !path.is_file() {
            continue;
        }
        let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
            continue;
        };
        let Some(num_str) = stem.strip_prefix("frame_") else {
            continue;
        };
        let Ok(idx) = num_str.parse::<u32>() else {
            continue;
        };
        let Some(ext_raw) = path.extension().and_then(|e| e.to_str()) else {
            continue;
        };
        if let Ok(safe_ext) = sanitize_ext(ext_raw) {
            let size = entry.metadata().map(|m| m.len()).unwrap_or(0);
            found.push((idx, safe_ext.to_string(), size));
        }
    }
    found.sort_by_key(|(idx, _, _)| *idx);
    Ok(found)
}

pub async fn list_frames_in(root: PathBuf, session_id: &str) -> Result<Vec<(u32, String)>, String> {
    let dir = resolve_existing_session_dir(&root, session_id);
    tokio::task::spawn_blocking(move || -> Result<Vec<(u32, String)>, String> {
        let scanned = scan_disk_frames_sync(&dir)?;
        Ok(scanned.into_iter().map(|(idx, ext, _)| (idx, ext)).collect())
    })
    .await
    .map_err(|e| format!("Timelapse list worker failed: {}", e))?
}

pub async fn list_frames(
    app: &tauri::AppHandle,
    session_id: &str,
) -> Result<Vec<(u32, String)>, String> {
    list_frames_in(get_timelapse_root(Some(app)), session_id).await
}

pub async fn load_session_in(
    root: PathBuf,
    session_id: &str,
) -> Result<LoadedTimelapseSession, String> {
    let dir = resolve_existing_session_dir(&root, session_id);
    tokio::task::spawn_blocking(move || -> Result<LoadedTimelapseSession, String> {
        if !dir.exists() {
            return Ok(LoadedTimelapseSession {
                meta: None,
                frames: Vec::new(),
                total_bytes: 0,
            });
        }

        let meta = std::fs::read_to_string(dir.join("meta.json"))
            .ok()
            .and_then(|s| serde_json::from_str::<TimelapseSessionMeta>(&s).ok());

        let ndjson_map = parse_ndjson_index_sync(&dir);
        let disk_frames = scan_disk_frames_sync(&dir)?;

        let mut frames = Vec::with_capacity(disk_frames.len());
        let mut total_bytes: u64 = 0;

        for (idx, ext, file_size) in disk_frames {
            total_bytes = total_bytes.saturating_add(file_size);
            if let Some(rec) = ndjson_map.get(&idx) {
                let mut merged = rec.clone();
                merged.bytes = file_size;
                merged.mime_type = ext_to_mime(&ext).to_string();
                frames.push(merged);
            } else {
                frames.push(TimelapseFrameRecord {
                    index: idx,
                    timestamp: 0,
                    width: 0,
                    height: 0,
                    mime_type: ext_to_mime(&ext).to_string(),
                    bytes: file_size,
                    capture_area: None,
                });
            }
        }

        Ok(LoadedTimelapseSession {
            meta,
            frames,
            total_bytes,
        })
    })
    .await
    .map_err(|e| format!("Timelapse load worker failed: {}", e))?
}

pub async fn load_session(
    app: &tauri::AppHandle,
    session_id: &str,
) -> Result<LoadedTimelapseSession, String> {
    load_session_in(get_timelapse_root(Some(app)), session_id).await
}

pub async fn list_sessions_in(root: PathBuf) -> Result<Vec<StoredTimelapseSummary>, String> {
    tokio::task::spawn_blocking(move || -> Result<Vec<StoredTimelapseSummary>, String> {
        if !root.exists() {
            return Ok(Vec::new());
        }
        let mut summaries = Vec::new();
        let entries = std::fs::read_dir(&root).map_err(|e| e.to_string())?;
        for entry in entries.flatten() {
            let dir = entry.path();
            if !dir.is_dir() {
                continue;
            }
            let Some(dir_name) = dir.file_name().and_then(|s| s.to_str()) else {
                continue;
            };
            let meta = std::fs::read_to_string(dir.join("meta.json"))
                .ok()
                .and_then(|s| serde_json::from_str::<TimelapseSessionMeta>(&s).ok());
            let disk_frames = scan_disk_frames_sync(&dir).unwrap_or_default();
            if disk_frames.is_empty() && meta.as_ref().map(|m| !m.enabled).unwrap_or(true) {
                continue;
            }
            let total_bytes: u64 = disk_frames.iter().map(|(_, _, sz)| *sz).sum();
            let dir_mtime = entry
                .metadata()
                .and_then(|m| m.modified())
                .ok()
                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                .map(|d| d.as_millis() as u64)
                .unwrap_or(0);

            if let Some(m) = meta {
                summaries.push(StoredTimelapseSummary {
                    recording_id: if m.recording_id.is_empty() {
                        dir_name.to_string()
                    } else {
                        m.recording_id
                    },
                    document_name: if m.document_name.is_empty() {
                        "Untitled".to_string()
                    } else {
                        m.document_name
                    },
                    enabled: m.enabled,
                    capture_area: m.capture_area,
                    capture_resolution: m.capture_resolution,
                    frame_count: disk_frames.len(),
                    total_bytes,
                    created_at: if m.created_at > 0 { m.created_at } else { dir_mtime },
                    updated_at: if m.updated_at > 0 { m.updated_at } else { dir_mtime },
                });
            } else {
                summaries.push(StoredTimelapseSummary {
                    recording_id: dir_name.to_string(),
                    document_name: "Recovered Recording".to_string(),
                    enabled: false,
                    capture_area: default_capture_area(),
                    capture_resolution: default_capture_resolution(),
                    frame_count: disk_frames.len(),
                    total_bytes,
                    created_at: dir_mtime,
                    updated_at: dir_mtime,
                });
            }
        }
        summaries.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));
        Ok(summaries)
    })
    .await
    .map_err(|e| format!("Timelapse sessions list worker failed: {}", e))?
}

pub async fn list_sessions(app: &tauri::AppHandle) -> Result<Vec<StoredTimelapseSummary>, String> {
    list_sessions_in(get_timelapse_root(Some(app))).await
}

fn resolve_frame_path(dir: &Path, idx: u32, preferred_ext: &str) -> Option<PathBuf> {
    let primary = dir.join(format!("frame_{:06}.{}", idx, preferred_ext));
    if primary.exists() {
        return Some(primary);
    }
    for alt in ["webp", "jpg", "png"] {
        if alt == preferred_ext {
            continue;
        }
        let candidate = dir.join(format!("frame_{:06}.{}", idx, alt));
        if candidate.exists() {
            return Some(candidate);
        }
    }
    None
}

pub async fn read_frame_in(
    root: PathBuf,
    session_id: &str,
    frame_index: u32,
    ext: &str,
) -> Result<Vec<u8>, String> {
    let safe_ext = sanitize_ext(ext)?;
    let dir = resolve_existing_session_dir(&root, session_id);
    let path = resolve_frame_path(&dir, frame_index, safe_ext)
        .unwrap_or_else(|| dir.join(format!("frame_{:06}.{}", frame_index, safe_ext)));
    tokio::fs::read(path).await.map_err(|e| e.to_string())
}

pub async fn read_frame(
    app: &tauri::AppHandle,
    session_id: &str,
    frame_index: u32,
    ext: &str,
) -> Result<Vec<u8>, String> {
    read_frame_in(get_timelapse_root(Some(app)), session_id, frame_index, ext).await
}

pub async fn clear_session_in(root: PathBuf, session_id: &str) -> Result<(), String> {
    let dir = session_dir_in(&root, session_id);
    if dir.exists() {
        let _ = tokio::fs::remove_dir_all(&dir).await;
    }
    let legacy = legacy_temp_session_dir(session_id);
    if legacy != dir && legacy.exists() {
        let _ = tokio::fs::remove_dir_all(&legacy).await;
    }
    Ok(())
}

pub async fn clear_session(app: &tauri::AppHandle, session_id: &str) -> Result<(), String> {
    clear_session_in(get_timelapse_root(Some(app)), session_id).await
}

pub async fn check_ffmpeg() -> bool {
    let mut cmd = Command::new("ffmpeg");
    cmd.arg("-version");
    #[cfg(windows)]
    cmd.creation_flags(CREATE_NO_WINDOW);
    cmd.output()
        .await
        .map(|o| o.status.success())
        .unwrap_or(false)
}

pub async fn export_ffmpeg(
    app: &tauri::AppHandle,
    params: FfmpegExportParams<'_>,
) -> Result<Vec<u8>, String> {
    if params.frame_indices.is_empty() {
        return Err("No frames to export".to_string());
    }
    let safe_ext = sanitize_ext(params.ext)?;
    let safe_fps = params.fps.clamp(1, 60);
    let safe_w = params.width.clamp(64, 3840) & !1;
    let safe_h = params.height.clamp(64, 3840) & !1;
    let root = get_timelapse_root(Some(app));
    let dir = resolve_existing_session_dir(&root, params.session_id);
    let seq = TMP_META_SEQ.fetch_add(1, Ordering::Relaxed);
    let list_path = dir.join(format!("concat_list_{}.txt", seq));
    let out_path = dir.join(format!("timelapse_out_{}.mp4", seq));
    let wm_path = dir.join(format!("watermark_{}.png", seq));

    let mut manifest = String::new();
    let frame_dur = 1.0 / (safe_fps as f64);
    let mut last_escaped: Option<String> = None;
    for idx in &params.frame_indices {
        if let Some(fpath) = resolve_frame_path(&dir, *idx, safe_ext) {
            let escaped = escape_ffmpeg_concat_path(&fpath);
            manifest.push_str(&format!("file '{}'\nduration {:.6}\n", escaped, frame_dur));
            last_escaped = Some(escaped);
        }
    }
    // FFmpeg concat demuxer requires repeating the final file directive so the last frame keeps its duration.
    if let Some(last) = last_escaped {
        manifest.push_str(&format!("file '{}'\n", last));
    }
    if manifest.is_empty() {
        return Err("No readable frames found in local time-lapse storage".to_string());
    }

    tokio::fs::write(&list_path, manifest)
        .await
        .map_err(|e| e.to_string())?;

    let has_watermark = if let Some(wm_bytes) = params.watermark_png {
        if !wm_bytes.is_empty() && wm_bytes.len() <= MAX_WATERMARK_PNG_BYTES {
            tokio::fs::write(&wm_path, wm_bytes)
                .await
                .map_err(|e| e.to_string())?;
            true
        } else {
            false
        }
    } else {
        false
    };

    let (use_complex, filter_expr) = build_ffmpeg_filtergraph(
        safe_w,
        safe_h,
        params.bg_color,
        params.bg_blur,
        has_watermark,
        params.watermark_x,
        params.watermark_y,
    );
    let (crf, preset) = quality_to_ffmpeg_crf_preset(params.quality);

    let mut cmd = Command::new("ffmpeg");
    cmd.args([
        "-y",
        "-f",
        "concat",
        "-safe",
        "0",
        "-i",
        list_path.to_string_lossy().as_ref(),
    ]);
    if has_watermark {
        cmd.args(["-i", wm_path.to_string_lossy().as_ref()]);
    }
    if use_complex {
        cmd.args(["-filter_complex", &filter_expr, "-map", "[out]"]);
    } else {
        cmd.args(["-vf", &filter_expr]);
    }
    cmd.args([
        "-r",
        &safe_fps.to_string(),
        "-c:v",
        "libx264",
        "-preset",
        preset,
        "-crf",
        crf,
        "-pix_fmt",
        "yuv420p",
        "-movflags",
        "+faststart",
        out_path.to_string_lossy().as_ref(),
    ]);
    #[cfg(windows)]
    cmd.creation_flags(CREATE_NO_WINDOW);

    let output = cmd
        .output()
        .await
        .map_err(|e| format!("Failed to launch ffmpeg: {}", e))?;

    let _ = tokio::fs::remove_file(&list_path).await;
    if has_watermark {
        let _ = tokio::fs::remove_file(&wm_path).await;
    }

    if !output.status.success() {
        let _ = tokio::fs::remove_file(&out_path).await;
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(format!("FFmpeg failed: {}", stderr));
    }

    let bytes = tokio::fs::read(&out_path)
        .await
        .map_err(|e| e.to_string())?;
    let _ = tokio::fs::remove_file(&out_path).await;
    Ok(bytes)
}

/// Converts and downscales a top-down 32-bit BGRA buffer to an even-dimension RGBA buffer
/// bounded by `max_dim`, packed with an 8-byte header `[width: u32 LE][height: u32 LE][rgba...]`.
pub fn downscale_bgra_to_packed_rgba(
    bgra: &[u8],
    src_w: u32,
    src_h: u32,
    max_dim: u32,
) -> Result<Vec<u8>, String> {
    let sw = src_w as usize;
    let sh = src_h as usize;
    if sw == 0 || sh == 0 || bgra.len() < sw.saturating_mul(sh).saturating_mul(4) {
        return Err("Invalid source BGRA buffer dimensions".to_string());
    }

    let clamped_max = max_dim.clamp(64, 3840) as f64;
    let longest = (src_w.max(src_h)) as f64;
    let scale = if longest > clamped_max {
        clamped_max / longest
    } else {
        1.0
    };
    let out_w = ((((src_w as f64) * scale).round() as u32).max(2) & !1).max(2) as usize;
    let out_h = ((((src_h as f64) * scale).round() as u32).max(2) & !1).max(2) as usize;

    let mut packed = Vec::with_capacity(8 + out_w * out_h * 4);
    packed.extend_from_slice(&(out_w as u32).to_le_bytes());
    packed.extend_from_slice(&(out_h as u32).to_le_bytes());

    if out_w == sw && out_h == sh {
        for px in bgra[..sw * sh * 4].chunks_exact(4) {
            packed.push(px[2]); // R
            packed.push(px[1]); // G
            packed.push(px[0]); // B
            packed.push(255);   // Opaque window capture
        }
        return Ok(packed);
    }

    // Fast box/bilinear downscaler for crisp UI text & canvas strokes
    let scale_x = (sw as f64) / (out_w as f64);
    let scale_y = (sh as f64) / (out_h as f64);
    for oy in 0..out_h {
        let sy0 = ((oy as f64) * scale_y).floor() as usize;
        let sy1 = ((((oy + 1) as f64) * scale_y).ceil() as usize).clamp(sy0 + 1, sh);
        for ox in 0..out_w {
            let sx0 = ((ox as f64) * scale_x).floor() as usize;
            let sx1 = ((((ox + 1) as f64) * scale_x).ceil() as usize).clamp(sx0 + 1, sw);
            let mut sum_r: u32 = 0;
            let mut sum_g: u32 = 0;
            let mut sum_b: u32 = 0;
            let mut count: u32 = 0;
            for sy in sy0..sy1 {
                let row_off = sy * sw * 4;
                for sx in sx0..sx1 {
                    let off = row_off + sx * 4;
                    sum_b += bgra[off] as u32;
                    sum_g += bgra[off + 1] as u32;
                    sum_r += bgra[off + 2] as u32;
                    count += 1;
                }
            }
            let c = count.max(1);
            packed.push((sum_r / c) as u8);
            packed.push((sum_g / c) as u8);
            packed.push((sum_b / c) as u8);
            packed.push(255);
        }
    }
    Ok(packed)
}

#[cfg(target_os = "windows")]
mod win_capture {
    use super::downscale_bgra_to_packed_rgba;
    use std::ffi::c_void;
    use windows_sys::Win32::Foundation::{HWND, RECT};
    use windows_sys::Win32::Graphics::Gdi::{
        BitBlt, CreateCompatibleDC, CreateDIBSection, DeleteDC, DeleteObject, GetDC, ReleaseDC,
        SelectObject, BITMAPINFO, BITMAPINFOHEADER, BI_RGB, DIB_RGB_COLORS, HDC, HGDIOBJ, SRCCOPY,
    };
    use windows_sys::Win32::UI::WindowsAndMessaging::{GetClientRect, IsIconic};

    const PW_CLIENTONLY: u32 = 0x0000_0001;
    const PW_RENDERFULLCONTENT: u32 = 0x0000_0002;

    extern "system" {
        fn PrintWindow(hwnd: HWND, hdc_blt: HDC, n_flags: u32) -> i32;
    }

    struct WindowDcGuard(HWND, HDC);
    impl Drop for WindowDcGuard {
        fn drop(&mut self) {
            if !self.1.is_null() {
                unsafe {
                    ReleaseDC(self.0, self.1);
                }
            }
        }
    }

    struct MemDcGuard(HDC);
    impl Drop for MemDcGuard {
        fn drop(&mut self) {
            if !self.0.is_null() {
                unsafe {
                    DeleteDC(self.0);
                }
            }
        }
    }

    struct BitmapGuard(HDC, HGDIOBJ, HGDIOBJ);
    impl Drop for BitmapGuard {
        fn drop(&mut self) {
            unsafe {
                if !self.0.is_null() && !self.1.is_null() {
                    SelectObject(self.0, self.1);
                }
                if !self.2.is_null() {
                    DeleteObject(self.2);
                }
            }
        }
    }

    pub fn capture_hwnd_rgba(hwnd_raw: isize, max_dim: u32) -> Result<Vec<u8>, String> {
        let hwnd = hwnd_raw as HWND;
        if hwnd.is_null() {
            return Err("Invalid window handle".to_string());
        }

        unsafe {
            if IsIconic(hwnd) != 0 {
                return Err("App window is minimized".to_string());
            }

            let mut rect = RECT {
                left: 0,
                top: 0,
                right: 0,
                bottom: 0,
            };
            if GetClientRect(hwnd, &mut rect) == 0 {
                return Err("Failed to query app window client rect".to_string());
            }
            let width = rect.right - rect.left;
            let height = rect.bottom - rect.top;
            if width <= 0 || height <= 0 || width > 16384 || height > 16384 {
                return Err("App window has invalid capture dimensions".to_string());
            }

            let win_dc = GetDC(hwnd);
            if win_dc.is_null() {
                return Err("Failed to acquire window DC".to_string());
            }
            let _win_dc_guard = WindowDcGuard(hwnd, win_dc);

            let mem_dc = CreateCompatibleDC(win_dc);
            if mem_dc.is_null() {
                return Err("Failed to create compatible memory DC".to_string());
            }
            let _mem_dc_guard = MemDcGuard(mem_dc);

            let mut bmi: BITMAPINFO = std::mem::zeroed();
            bmi.bmiHeader = BITMAPINFOHEADER {
                biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,
                biWidth: width,
                biHeight: -height, // Top-down DIB
                biPlanes: 1,
                biBitCount: 32,
                biCompression: BI_RGB,
                biSizeImage: 0,
                biXPelsPerMeter: 0,
                biYPelsPerMeter: 0,
                biClrUsed: 0,
                biClrImportant: 0,
            };

            let mut bits_ptr: *mut c_void = std::ptr::null_mut();
            let hbmp = CreateDIBSection(
                win_dc,
                &bmi,
                DIB_RGB_COLORS,
                &mut bits_ptr,
                std::ptr::null_mut(),
                0,
            );
            if hbmp.is_null() || bits_ptr.is_null() {
                return Err("Failed to allocate capture DIB section".to_string());
            }
            let old_obj = SelectObject(mem_dc, hbmp as HGDIOBJ);
            let _bmp_guard = BitmapGuard(mem_dc, old_obj, hbmp as HGDIOBJ);

            let byte_len = (width as usize) * (height as usize) * 4;
            std::ptr::write_bytes(bits_ptr as *mut u8, 0, byte_len);

            let ok_pw = PrintWindow(hwnd, mem_dc, PW_CLIENTONLY | PW_RENDERFULLCONTENT) != 0;
            let pixels = std::slice::from_raw_parts(bits_ptr as *const u8, byte_len);

            // Verify PrintWindow produced non-empty content; otherwise fallback to BitBlt
            let mut has_content = false;
            if ok_pw {
                let stride = (byte_len / 64).max(4) & !3;
                let mut i = 0usize;
                while i + 3 < byte_len {
                    if pixels[i] != 0 || pixels[i + 1] != 0 || pixels[i + 2] != 0 {
                        has_content = true;
                        break;
                    }
                    i += stride;
                }
            }

            if !has_content {
                let _ = BitBlt(mem_dc, 0, 0, width, height, win_dc, 0, 0, SRCCOPY);
            }

            downscale_bgra_to_packed_rgba(pixels, width as u32, height as u32, max_dim)
        }
    }
}

pub async fn capture_app_window(
    app: &tauri::AppHandle,
    max_dim: u32,
) -> Result<Vec<u8>, String> {
    #[cfg(target_os = "windows")]
    {
        let window = app
            .get_webview_window("main")
            .ok_or_else(|| "Main app window not available".to_string())?;
        let hwnd = window
            .hwnd()
            .map_err(|e| format!("Failed to obtain window handle: {}", e))?;
        let hwnd_raw = hwnd.0 as isize;
        tokio::task::spawn_blocking(move || win_capture::capture_hwnd_rgba(hwnd_raw, max_dim))
            .await
            .map_err(|e| format!("App window capture worker failed: {}", e))?
    }
    #[cfg(not(target_os = "windows"))]
    {
        let _ = (app, max_dim);
        Err("Native app window capture is not supported on this platform".to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_test_root(tag: &str) -> PathBuf {
        std::env::temp_dir().join(format!(
            "inkstudio_tl_test_{}_{}",
            tag,
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ))
    }

    #[test]
    fn test_escape_ffmpeg_concat_path_windows_and_quotes() {
        let p = Path::new(
            r"C:\Users\O'Brien\AppData\Local\inkstudio_timelapse\s1\frame_000001.png",
        );
        assert_eq!(
            escape_ffmpeg_concat_path(p),
            "C:/Users/O'\\''Brien/AppData/Local/inkstudio_timelapse/s1/frame_000001.png"
        );
    }

    #[test]
    fn test_unpack_frame_indices() {
        let mut raw = Vec::new();
        for idx in [0u32, 1, 42, 99999] {
            raw.extend_from_slice(&idx.to_le_bytes());
        }
        assert_eq!(unpack_frame_indices(&raw).unwrap(), vec![0, 1, 42, 99999]);
        assert!(unpack_frame_indices(&[1, 2, 3]).is_err());
    }

    #[test]
    fn test_frame_batch_pack_unpack_and_malformed_rejection() {
        let entries = vec![
            FrameBatchEntry {
                frame_index: 0,
                ext: "webp",
                data: vec![0x52, 0x49, 0x46, 0x46, 1, 2, 3],
            },
            FrameBatchEntry {
                frame_index: 5,
                ext: "jpg",
                data: vec![0xff, 0xd8, 0xff, 0xe0, 9, 8],
            },
        ];
        let packed = pack_frame_batch(&entries).expect("pack failed");
        let unpacked = unpack_frame_batch(&packed).expect("unpack failed");
        assert_eq!(unpacked, entries);

        assert!(unpack_frame_batch(&[1, 2]).is_err());
        assert!(unpack_frame_batch(&packed[..packed.len() - 1]).is_err());
        let mut with_trailing = packed.clone();
        with_trailing.push(0x99);
        assert!(unpack_frame_batch(&with_trailing).is_err());
    }

    #[test]
    fn test_ffmpeg_filtergraph_colors_blur_watermark_and_quality() {
        assert_eq!(sanitize_ffmpeg_hex_color("#141414"), "0x141414");
        assert_eq!(sanitize_ffmpeg_hex_color("bad;rm -rf"), "0xffffff");

        assert_eq!(quality_to_ffmpeg_crf_preset("standard"), ("26", "veryfast"));
        assert_eq!(quality_to_ffmpeg_crf_preset("high"), ("20", "fast"));
        assert_eq!(quality_to_ffmpeg_crf_preset("ultra"), ("15", "medium"));
        assert_eq!(quality_to_ffmpeg_crf_preset("lossless"), ("10", "medium"));

        let (complex1, expr1) =
            build_ffmpeg_filtergraph(1920, 1080, "#141414", false, false, 0, 0);
        assert!(!complex1);
        assert!(expr1.contains("color=0x141414"));
        assert!(expr1.contains("setsar=1"));

        let (complex2, expr2) =
            build_ffmpeg_filtergraph(1920, 1080, "#ffffff", false, true, 1600, 960);
        assert!(complex2);
        assert!(expr2.contains("[base][1:v]overlay=1600:960:format=auto[out]"));

        let (complex3, expr3) =
            build_ffmpeg_filtergraph(1080, 1920, "#000000", true, true, 24, 32);
        assert!(complex3);
        assert!(expr3.contains("boxblur=20:2"));
        assert!(expr3.contains("overlay=24:32:format=auto[out]"));
    }

    #[test]
    fn test_downscale_bgra_to_packed_rgba() {
        // 4x4 uniform BGRA=(10, 20, 30, 255) -> RGBA=(30, 20, 10, 255)
        let mut bgra = Vec::with_capacity(4 * 4 * 4);
        for _ in 0..16 {
            bgra.extend_from_slice(&[10, 20, 30, 255]);
        }
        let packed = downscale_bgra_to_packed_rgba(&bgra, 4, 4, 1080).unwrap();
        let w = u32::from_le_bytes(packed[0..4].try_into().unwrap());
        let h = u32::from_le_bytes(packed[4..8].try_into().unwrap());
        assert_eq!((w, h), (4, 4));
        assert_eq!(&packed[8..12], &[30, 20, 10, 255]);

        // Downscaling 200x100 to max_dim=100 -> 100x50
        let mut big = Vec::with_capacity(200 * 100 * 4);
        for _ in 0..(200 * 100) {
            big.extend_from_slice(&[50, 100, 200, 255]);
        }
        let scaled = downscale_bgra_to_packed_rgba(&big, 200, 100, 100).unwrap();
        let sw = u32::from_le_bytes(scaled[0..4].try_into().unwrap());
        let sh = u32::from_le_bytes(scaled[4..8].try_into().unwrap());
        assert_eq!((sw, sh), (100, 50));
        assert_eq!(sw % 2, 0);
        assert_eq!(sh % 2, 0);
        assert_eq!(&scaled[8..12], &[200, 100, 50, 255]);
    }

    #[tokio::test]
    async fn test_persistent_meta_ndjson_load_list_and_self_heal() {
        let root = make_test_root("persist");
        let sid = "rec-persist-1";

        let meta = TimelapseSessionMeta {
            recording_id: sid.to_string(),
            document_name: "Illustration.ink".to_string(),
            enabled: true,
            capture_area: "canvas-view".to_string(),
            capture_resolution: "4k".to_string(),
            next_index: 2,
            created_at: 1000,
            updated_at: 2000,
        };
        save_session_meta_in(root.clone(), sid, &serde_json::to_string(&meta).unwrap())
            .await
            .expect("save meta");

        write_frame_in(
            root.clone(),
            sid,
            0,
            "webp",
            b"webp-frame-0".to_vec(),
            Some(FrameWriteMeta {
                timestamp: 1010,
                width: 1920,
                height: 1080,
                capture_area: Some("canvas-view".to_string()),
            }),
        )
        .await
        .expect("write frame 0");

        write_frame_in(
            root.clone(),
            sid,
            1,
            "jpg",
            b"jpg-frame-1-longer".to_vec(),
            Some(FrameWriteMeta {
                timestamp: 1020,
                width: 1920,
                height: 1080,
                capture_area: Some("artwork".to_string()),
            }),
        )
        .await
        .expect("write frame 1");

        let loaded = load_session_in(root.clone(), sid).await.expect("load");
        assert_eq!(loaded.meta.as_ref(), Some(&meta));
        assert_eq!(loaded.frames.len(), 2);
        assert_eq!(loaded.frames[0].width, 1920);
        assert_eq!(loaded.frames[0].capture_area.as_deref(), Some("canvas-view"));
        assert_eq!(loaded.frames[1].mime_type, "image/jpeg");
        assert_eq!(
            loaded.total_bytes,
            (b"webp-frame-0".len() + b"jpg-frame-1-longer".len()) as u64
        );

        // Mixed-ext read works even if caller passes webp for jpg frame
        assert_eq!(
            read_frame_in(root.clone(), sid, 1, "webp").await.unwrap(),
            b"jpg-frame-1-longer"
        );

        let sessions = list_sessions_in(root.clone()).await.expect("list sessions");
        assert_eq!(sessions.len(), 1);
        assert_eq!(sessions[0].recording_id, sid);
        assert_eq!(sessions[0].frame_count, 2);
        assert_eq!(sessions[0].document_name, "Illustration.ink");

        // Self-heal when frames.ndjson is removed: still discovers both frames on disk!
        let _ = std::fs::remove_file(session_dir_in(&root, sid).join("frames.ndjson"));
        let healed = load_session_in(root.clone(), sid).await.expect("healed load");
        assert_eq!(healed.frames.len(), 2);

        clear_session_in(root.clone(), sid).await.expect("clear");
        assert!(list_frames_in(root.clone(), sid).await.unwrap().is_empty());
        let _ = std::fs::remove_dir_all(&root);
    }

    #[tokio::test]
    async fn test_write_frames_batch_list_and_mixed_ext_resolution() {
        let root = make_test_root("batch");
        let sid = "test_tl_batch";
        let entries = vec![
            FrameBatchEntry {
                frame_index: 0,
                ext: "webp",
                data: b"webp-frame-0".to_vec(),
            },
            FrameBatchEntry {
                frame_index: 1,
                ext: "jpg",
                data: b"jpg-frame-1".to_vec(),
            },
        ];
        let written = write_frames_batch_in(root.clone(), sid, entries, None)
            .await
            .expect("batch write");
        assert_eq!(written, 2);

        let listed = list_frames_in(root.clone(), sid).await.expect("list frames");
        assert_eq!(
            listed,
            vec![(0u32, "webp".to_string()), (1u32, "jpg".to_string())]
        );

        assert_eq!(
            read_frame_in(root.clone(), sid, 0, "webp").await.unwrap(),
            b"webp-frame-0"
        );
        assert_eq!(
            read_frame_in(root.clone(), sid, 1, "jpg").await.unwrap(),
            b"jpg-frame-1"
        );

        let dir = session_dir_in(&root, sid);
        let resolved = resolve_frame_path(&dir, 1, "webp").expect("resolve mixed ext");
        assert!(resolved.to_string_lossy().ends_with("frame_000001.jpg"));

        clear_session_in(root.clone(), sid).await.expect("clear");
        assert!(list_frames_in(root.clone(), sid).await.unwrap().is_empty());
        let _ = std::fs::remove_dir_all(&root);
    }
}