i18n_ui 0.2.126

Terminal UI for translation progress with interactive concurrent panels and line-by-line fallback
Documentation
//! UI state shared by both renderers: slot pool, running tasks and progress

mod item;
mod slot;

use std::{
  borrow::Cow,
  time::{Duration, Instant},
};

pub(crate) use item::{Ended, RetryState, Run, TAIL_CAP};
use progbar::Progress;
pub(crate) use slot::SlotEntry;

use crate::{
  event::{Event, Name, PoolStat},
  i18n::T,
  text::{dur, fmt_tok},
};

pub(crate) struct Board {
  pub(crate) progress: Progress,
  /// Source files discovered by the directory walk (inline scan stage)
  pub(crate) scan_found: usize,
  /// Source files whose cache state is checked (inline scan stage)
  pub(crate) scan_checked: usize,
  /// Cache hits confirmed by the preflight scan (inline scan stage)
  pub(crate) scan_cache: usize,
  pub(crate) slot_li: Vec<SlotEntry>,
  pub(crate) pool_stat: PoolStat,
  pub(crate) run_li: Vec<Run>,
  pub(crate) hit: usize,
  pub(crate) ok: usize,
  pub(crate) fail: usize,
  pub(crate) retry: usize,
  /// Whether `plan()` was called this session (`--purge` / early setup errors never call `plan`)
  planned: bool,
  /// Whether non-model disk writes, manual-edit syncs, or orphan deletions occurred
  changed: bool,
  /// Fallback token accumulator when tasks report tokens directly without pool snapshots
  job_tok_sum: u64,
  /// Session anchor for the summary elapsed time. Suspend-excluding, matching task timings.
  begin: Instant,
}

/// Side effect after applying an event: the renderer decides output from it; pure state events produce no output
pub(crate) enum Act {
  /// Update state only
  None,
  /// Preflight finished: the scan stage gives way to the live board, `job` is the planned model task count
  Plan { job: usize },
  /// Start a task, carrying the task id so the renderer can read its name
  Start(u32),
  /// Streaming output
  Text { id: u32, text: String, reply: bool },
  /// Request retry, carrying the task id
  Retry(u32),
  /// Task finished
  End(Ended),
  /// Informational message
  Log(String),
  /// Close the UI
  Close,
}

impl Board {
  pub(crate) fn new() -> Self {
    Self {
      progress: Progress::new(0),
      scan_found: 0,
      scan_checked: 0,
      scan_cache: 0,
      slot_li: Vec::new(),
      pool_stat: PoolStat::default(),
      run_li: Vec::new(),
      hit: 0,
      ok: 0,
      fail: 0,
      retry: 0,
      planned: false,
      changed: false,
      job_tok_sum: 0,
      begin: Instant::now(),
    }
  }

  /// Apply an event; state transitions happen only here and are shared by both render modes
  pub(crate) fn apply(&mut self, event: Event) -> Act {
    match event {
      Event::ScanFound(found) => {
        self.scan_found = found;
        Act::None
      }
      Event::ScanChecked { checked, cache } => {
        self.scan_checked = checked;
        self.scan_cache = cache;
        Act::None
      }
      Event::Plan { job, cache } => {
        self.plan(job, cache);
        Act::Plan { job }
      }
      Event::Pool(meta_li) => {
        self.init_pool(meta_li);
        Act::None
      }
      Event::Slot { row, stat } => {
        self.on_slot(row, stat);
        Act::None
      }
      Event::Hit => {
        self.hit();
        Act::None
      }
      Event::Grow => {
        self.grow();
        Act::None
      }
      Event::Skip => {
        self.skip();
        Act::None
      }
      Event::Fail => {
        self.fail += 1;
        Act::None
      }
      Event::Change => {
        self.changed = true;
        Act::None
      }
      Event::Start { id, name } => {
        self.start(id, name);
        Act::Start(id)
      }
      Event::JobSlot { id, slot } => {
        if let Some(run) = self.run(id) {
          run.slot = Some(slot);
        }
        Act::None
      }
      Event::JobTok { id, tok } => {
        self.job_tok_sum = self.job_tok_sum.saturating_add(u64::from(tok));
        if let Some(run) = self.run(id) {
          run.tok = run.tok.saturating_add(u64::from(tok));
        }
        Act::None
      }
      Event::Text { id, text, reply } => Act::Text { id, text, reply },
      Event::Retry {
        id,
        nth,
        total,
        wait,
        base,
        err,
      } => {
        self.on_retry(id, nth, total, wait, base, err);
        Act::Retry(id)
      }
      Event::End { id, err, active } => match self.end(id, err, active) {
        Some(ended) => Act::End(ended),
        None => Act::None,
      },
      Event::Log(text) => Act::Log(text),
      Event::Close => Act::Close,
    }
  }

  pub(crate) fn plan(&mut self, job: usize, cache: usize) {
    let cap = self.pool_stat.cap.max(1);
    self.progress = Progress::new(job).with_concurrency(cap);
    self.hit = cache;
    self.planned = true;
  }

  pub(crate) fn hit(&mut self) {
    self.hit += 1;
    self.progress.hit();
  }

  pub(crate) fn grow(&mut self) {
    self.progress.grow();
  }

  /// Languages planned but unprocessed this round: consume one planned unit, not counted as cache hits
  pub(crate) fn skip(&mut self) {
    self.progress.skip();
  }

  pub(crate) fn start(&mut self, id: u32, name: Name) {
    let now = Instant::now();
    self.run_li.push(Run {
      id,
      name,
      begin: now,
      at: now,
      slot: None,
      tok: 0,
      think: String::new(),
      reply: String::new(),
      retry: None,
      retry_cnt: 0,
    });
  }

  pub(crate) fn run(&mut self, id: u32) -> Option<&mut Run> {
    self.run_li.iter_mut().find(|run| run.id == id)
  }

  /// Total consumed tokens across pool telemetry and task-level reports
  pub(crate) fn total_tok(&self) -> u64 {
    self.pool_stat.tok.max(self.job_tok_sum)
  }

  /// Active concurrency count for UI footer display
  pub(crate) fn active_conc(&self) -> usize {
    usize::from(self.pool_stat.in_flight).max(self.run_li.len())
  }

  /// Record one request retry; the renderer re-queries via `run(id)`, so no return value is needed
  pub(crate) fn on_retry(
    &mut self,
    id: u32,
    nth: usize,
    total: usize,
    wait: Duration,
    base: String,
    err: String,
  ) {
    let Some(run) = self.run_li.iter_mut().find(|run| run.id == id) else {
      return;
    };
    run.retry_cnt += 1;
    run.think.clear();
    run.reply.clear();
    let streak = run.retry.as_ref().map_or(1, |r| r.streak + 1);
    run.retry = Some(RetryState {
      nth,
      total,
      wait,
      at: Instant::now(),
      base,
      err,
      streak,
    });
    self.retry += 1;
  }

  /// Finish a task: success counts toward progress, failure is subtracted from the total
  pub(crate) fn end(&mut self, id: u32, err: Option<String>, active: Duration) -> Option<Ended> {
    let pos = self.run_li.iter().position(|run| run.id == id)?;
    let run = self.run_li.swap_remove(pos);
    if err.is_some() {
      self.fail += 1;
      self.progress.skip();
    } else {
      self.ok += 1;
      self.progress.finish(active);
    }
    let slot_label = self.slot(run.slot).map(|s| s.label.clone());
    Some(Ended {
      name: run.name,
      slot: run.slot,
      slot_label,
      tok: run.tok,
      sec: sec(run.begin),
      retry_cnt: run.retry_cnt,
      err,
      think: run.think,
    })
  }

  /// Total elapsed time (seconds)
  pub(crate) fn sec(&self) -> f32 {
    sec(self.begin)
  }

  /// Summary block for stderr on exit, `None` when the run ended before planning with no activity, or a one-line no-change notice when all tasks hit cache cleanly
  pub(crate) fn summary(&self) -> Option<Cow<'static, str>> {
    if !self.planned && self.ok == 0 && self.fail == 0 && self.hit == 0 && !self.changed {
      return None;
    }
    let tok = self.total_tok();
    if self.ok == 0 && self.fail == 0 && tok == 0 && !self.changed {
      return Some(Cow::Borrowed(T.ui.no_change()));
    }
    Some(
      T.ui
        .summary(self.ok, self.hit, self.fail, fmt_tok(tok), dur(self.sec())),
    )
  }
}

/// Seconds elapsed since `begin`
///
/// `std::time::Instant` excludes system sleep on macOS (`CLOCK_UPTIME_RAW`) and Linux
/// (`CLOCK_MONOTONIC`), so a closed lid does not inflate task durations.
pub(crate) fn sec(begin: Instant) -> f32 {
  begin.elapsed().as_secs_f32()
}