hex/src/meeting/retention.rs
Dax 72ac81ad61
fix(meetings): finish recordings across quits and update restarts (#1900)
* fix(meetings): recover recordings lost to a quit or update restart

Rune ends a quitting app with `_exit` unless it is told the app has work
after its loop, so every in-app quit (Quit Hex, `hex quit`, Restart to
update) skipped Hex's drain since the Nov 14 Rune bump. A meeting
recording was killed mid-write: zeroed WAV headers, no `final.pending`,
and nothing to recover at the next launch.

- `rune::orderly_exit()` in the macOS, Windows, and Linux app loops, so
  the existing teardown runs on every quit; the AppKit terminate path
  still drains from its will-terminate notification.
- macOS joins the meeting controller before installing a staged update
  and before the other workers, and a recording gets 30 s to finalise
  rather than 5.
- `meeting::recording()` is a process-wide flag the updater reads.
  Restart to update refuses with a reason, re-checks before swapping,
  and keeps the release staged.
- Launch recovery selects every unlocked unfinished meeting, not just
  `final.pending`; repairs zeroed or wrong WAV RIFF/data sizes from the
  file length, fills sample counts and duration from the audio, and runs
  the existing final pass so the transcript, Markdown export, and notes
  are written. Failed and completed meetings are untouched.

Checks: `a_zeroed_wav_header_is_repaired_from_its_file_length`,
`a_stranded_recording_is_selected_for_recovery`,
`recovery_fills_the_manifest_from_the_repaired_audio`,
`the_flag_holds_until_the_recorder_drops_it`,
`restart_to_update_waits_while_a_meeting_records`.

* fix(meetings): settle recovery attempts and keep retention honest

Reviews of #1900:
- a recovery that dies during the final pass leaves recovery.attempt;
  the next launch marks the meeting Interrupted ("recovery did not
  finish") and never retries that audio. final.pending folders that
  already have a transcript are finished too.
- a repaired, unfinalised track overwrites list_all's relabel with the
  audio's real duration and ended_at.
- retention only waits for stranded meetings while recovery can run
  (Meetings on, model installed); the MCP query uses the same rule.
- repair only rewrites a zero or overlong data chunk, so a trailing
  chunk or pad byte is never read as audio.
- the macOS status item dims Restart to update while a meeting records.
- finish_restart keeps Ready only when an update is staged.
- macOS installs a staged update before joining the controller when
  nothing records; Windows arms a 20 s teardown deadline; Linux writes
  its reopen marker only after a restart is accepted.
- the recording flag is a counter, tested without assuming idleness.

* fix(meetings): bound recovery retries and harden quits

- recovery.attempt now counts attempts: a pass that dies is retried once,
  then the meeting is marked Interrupted ("recovery did not finish") and
  that audio is never handed to Hex again. The pass holds the meeting
  busy flag, so the quit deadline and Restart to update wait for it.
- a finished meeting with a stale attempt marker keeps its final.pending,
  which the ordinary final pass then exports; settling no longer deletes
  it.
- pending recoveries stop between meetings when a recording starts and
  are offered again once Hex is idle.
- an empty finalised track is not "unfinalised"; the audio's duration
  wins whenever repair changed the manifest's track counts.
- can_recover reads meetings.enabled and the model from settings.json in
  readers (`hex mcp`, `hex meetings`), matching the app.
- updater: State::Applied is never overwritten by a later check, and a
  restart check that races a quit never swaps a second time.
- macOS installs the staged bundle before joining the meeting
  controller, marks quitting before any drain, and extends the 5 s exit
  deadline to 30 s from the quit's start while meeting audio is in
  flight. `meeting::record` refuses once quitting.
- Windows marks quitting after the loop, bounds teardown at 20 s (30 s
  while meeting audio is in flight) and exits 1 when the window failed;
  Linux marks quitting before joining meetings and removes a reopen
  marker when a restart is refused.

* fix(updater): keep the staged update installable when a late download is dropped

- check() now returns the state the locks actually show when it discards a
  release during a quit: Applied only if one was installed, else Ready while
  an older update is staged, else Current. install_on_quit therefore still
  installs the staged update a plain quit is about to apply.
- after waiting for meeting audio, the macOS exit deadline gives the rest of
  the drain up to 5 s more, inside the 30 s bound from the quit's start.
  Windows polls meeting audio to 30 s instead of choosing a bound once.
- the Restart to update refusal reads "Hex is finishing a meeting; restart to
  update when it's done", true for a recording and a launch recovery.
- a recording refused because Hex is quitting removes the empty folder it
  created (and only when it holds nothing but the lock file).
- docs: the macOS drain installs before joining the controller, and the
  deadline/discarded-release wording matches the code.
2026-11-16 12:30:57 -05:00

262 lines
8.9 KiB
Rust

//! Meeting retention: how long finished meetings, and separately their WAV
//! tracks, are kept before moving to the Trash.
use std::path::Path;
use color_eyre::eyre::{Result, eyre};
use super::{
FINAL_PENDING_FILE, MeetingManifest, MeetingStatus, exported_markdown, file_sha256, list_all,
meeting_is_active, notes_in_progress, now_ms, os, pending_final_transcripts, read_manifest,
root, write_manifest,
};
use crate::app_settings::MeetingRetention;
/// Every meeting whose final transcript is still owed: one with a
/// `final.pending` marker, or one the launch recovery will finish while it
/// can actually run. With Meetings off or no installed model, unfinished
/// meetings expire like any other.
fn awaiting_final_transcript(meetings: &[MeetingManifest]) -> Vec<String> {
let mut ids = pending_final_transcripts();
if super::recovery::can_recover() {
ids.extend(super::recovery::stranded_among(meetings));
}
ids.sort();
ids.dedup();
ids
}
/// User-facing readers omit expired meetings even before the Trash sweep.
pub fn list() -> Result<Vec<MeetingManifest>> {
let chosen = crate::app_settings::meeting_retention();
let now = now_ms();
let meetings = list_all()?;
let pending = awaiting_final_transcript(&meetings);
Ok(meetings
.into_iter()
.filter(|meeting| {
readable(
meeting,
meeting.status,
pending.contains(&meeting.id),
chosen,
now,
)
})
.collect())
}
/// How long `manifest` is kept: the retention the user chose, else
/// [`MeetingRetention::DEFAULT`] for meetings recorded since it began, and
/// older meetings for good.
pub fn retention_for(
manifest: &MeetingManifest,
chosen: Option<MeetingRetention>,
) -> MeetingRetention {
chosen.unwrap_or(if manifest.retention_applies {
MeetingRetention::DEFAULT
} else {
MeetingRetention::Forever
})
}
/// Read admission and retention share the same pending-final exception.
/// A retained draft must remain readable while its final pass waits or fails.
pub(super) fn readable(
manifest: &MeetingManifest,
status: MeetingStatus,
pending_final: bool,
chosen: Option<MeetingRetention>,
now_ms: u64,
) -> bool {
pending_final
|| status.is_active()
|| retention_for(manifest, chosen)
.max_age_ms()
.is_none_or(|max_age_ms| {
let ended = manifest.ended_at_ms.unwrap_or(manifest.created_at_ms);
now_ms.saturating_sub(ended) <= max_age_ms
})
}
/// Moves every expired meeting to the Trash: its folder, and its exported
/// Markdown while that is still the copy Hex wrote. One that is recording,
/// transcribing, writing notes, or waiting for its final transcript stays
/// for a later pass. Returns how many moved.
pub fn expire(chosen: Option<MeetingRetention>) -> Result<usize> {
let meetings = list_all()?;
let pending = awaiting_final_transcript(&meetings);
let root = root()?;
let mut moved = 0;
for id in expired_meetings(&meetings, chosen, &pending, now_ms()) {
match trash_expired(&root.join(id), os::move_to_trash) {
Ok(()) => {
moved += 1;
tracing::info!(meeting = id, "moved an expired meeting to the Trash");
}
Err(error) => {
tracing::info!(%error, meeting = id, "kept an expired meeting for now");
}
}
}
Ok(moved)
}
/// The expired meetings in `meetings`, leaving out `pending` ones.
pub(super) fn expired_meetings<'a>(
meetings: &'a [MeetingManifest],
chosen: Option<MeetingRetention>,
pending: &[String],
now_ms: u64,
) -> Vec<&'a str> {
meetings
.iter()
.filter(|meeting| {
!readable(
meeting,
meeting.status,
pending.contains(&meeting.id),
chosen,
now_ms,
)
})
.map(|meeting| meeting.id.as_str())
.collect()
}
/// [`super::trash_meeting`] for expiry: an exported Markdown the user changed
/// is left where it is.
pub(super) fn trash_expired(
directory: &Path,
mut move_to_trash: impl FnMut(&Path) -> Result<()>,
) -> Result<()> {
let manifest = read_manifest(directory)?;
if meeting_is_active(directory) != Some(false) {
return Err(eyre!("the meeting is recording"));
}
if notes_in_progress(&manifest.id) {
return Err(eyre!("its notes are being written"));
}
if let Some(path) = exported_markdown(&manifest) {
if manifest.export_sha256.is_some() && file_sha256(&path) == manifest.export_sha256 {
move_to_trash(&path)?;
} else {
tracing::info!(
meeting = manifest.id,
"kept the meeting's Markdown, which changed since Hex wrote it"
);
}
}
if let Some(path) = super::notes_file::tracked(&manifest) {
if manifest.notes_export_sha256.is_some()
&& file_sha256(&path) == manifest.notes_export_sha256
{
move_to_trash(&path)?;
} else {
tracing::info!(
meeting = manifest.id,
"kept the meeting's notes file, which changed since Hex wrote it"
);
}
}
move_to_trash(directory)
}
/// Whether a finished meeting's audio outlived a separate audio retention,
/// counted from when it ended (or, with no end, started). Only a Complete
/// meeting with its final transcript published and no audio removed yet can.
pub fn audio_expired(
manifest: &MeetingManifest,
status: MeetingStatus,
chosen: Option<MeetingRetention>,
now_ms: u64,
) -> bool {
status == MeetingStatus::Complete
&& manifest.audio_removed_at_ms.is_none()
&& chosen
.and_then(MeetingRetention::max_age_ms)
.is_some_and(|max_age_ms| {
let ended = manifest.ended_at_ms.unwrap_or(manifest.created_at_ms);
now_ms.saturating_sub(ended) > max_age_ms
})
}
/// Moves the WAV tracks of meetings past a separate audio retention to the
/// Trash, keeping their transcripts, notes, summary, and exported Markdown.
/// One that is not Complete, has a pending final transcript, is recording,
/// or is writing notes stays for a later pass. Returns how many lost audio.
pub fn expire_audio(chosen: Option<MeetingRetention>) -> Result<usize> {
let Some(chosen) = chosen else {
return Ok(0);
};
let meetings = list_all()?;
let pending = awaiting_final_transcript(&meetings);
let root = root()?;
let mut removed = 0;
for id in audio_expired_meetings(&meetings, chosen, &pending, now_ms()) {
match trash_audio_tracks(&root.join(id), notes_in_progress, os::move_to_trash) {
Ok(()) => {
removed += 1;
tracing::info!(
meeting = id,
"moved an expired meeting's audio to the Trash"
);
}
Err(error) => {
tracing::info!(%error, meeting = id, "kept an expired meeting's audio for now");
}
}
}
Ok(removed)
}
/// The meetings in `meetings` whose audio outlived `chosen`, leaving out
/// `pending` ones.
pub(super) fn audio_expired_meetings<'a>(
meetings: &'a [MeetingManifest],
chosen: MeetingRetention,
pending: &[String],
now_ms: u64,
) -> Vec<&'a str> {
meetings
.iter()
.filter(|meeting| !pending.contains(&meeting.id))
.filter(|meeting| audio_expired(meeting, meeting.status, Some(chosen), now_ms))
.map(|meeting| meeting.id.as_str())
.collect()
}
/// Moves only a finished meeting's WAV tracks to the Trash and records it in
/// the manifest; its text and Markdown stay.
pub(super) fn trash_audio_tracks(
directory: &Path,
notes_busy: impl Fn(&str) -> bool,
mut move_to_trash: impl FnMut(&Path) -> Result<()>,
) -> Result<()> {
let manifest = read_manifest(directory)?;
if manifest.status != MeetingStatus::Complete {
return Err(eyre!("the meeting is not finished"));
}
if directory.join(FINAL_PENDING_FILE).exists() {
return Err(eyre!("its final transcript is still pending"));
}
if meeting_is_active(directory) != Some(false) {
return Err(eyre!("the meeting is recording"));
}
if notes_busy(&manifest.id) {
return Err(eyre!("its notes are being written"));
}
if manifest.audio_removed_at_ms.is_some() {
return Ok(());
}
for file in [&manifest.system.file, &manifest.microphone.file] {
let path = directory.join(file);
if path.exists() {
move_to_trash(&path)?;
}
}
// Re-read so concurrent manifest updates are not lost.
let mut manifest = read_manifest(directory)?;
manifest.audio_removed_at_ms = Some(now_ms());
write_manifest(directory, &manifest)
}