i18n_ui 0.2.126

Terminal UI for translation progress with interactive concurrent panels and line-by-line fallback
Documentation
//! Handle for a single model-calling task: receives streaming output and reports the result on finish

use std::{
  cell::Cell,
  fmt,
  rc::Rc,
  time::{Duration, Instant},
};

use clean_text::{clean_text as clean, one_line as one_line_cow};
use crossfire::{MTx, mpsc::List};

use crate::{event::Event, i18n::T, text::one_line};
/// Max bytes of retry error summary body (trailing ellipsis counts 3 extra bytes)
const ERR_CAP: usize = 120;

/// Task handle; dropping without calling [`Job::done`] / [`Job::fail`] counts as cancellation
pub struct Job {
  tx: MTx<List<Event>>,
  /// Whether to show streaming reply: non-interactive mode short-circuits the reply callback, saving cleaning and channel overhead
  reply: bool,
  id: u32,
  /// Task start time (when the slot is acquired and the model call is about to begin).
  ///
  /// Uses `std::time::Instant`, a monotonic clock that excludes system sleep
  /// (`CLOCK_UPTIME_RAW` / `mach_absolute_time` on macOS, `CLOCK_MONOTONIC` on Linux),
  /// so a closed lid does not count as model time.
  ///
  /// Do not switch this to `coarsetime`: on macOS it reads `CLOCK_MONOTONIC_RAW_APPROX`,
  /// which keeps ticking while the machine is suspended. One lid close would add hours to a
  /// single `active` duration; because `progbar::Rate` averages the last 32 samples,
  /// that outlier collapses the throughput estimate and makes the ETA jump by orders of
  /// magnitude.
  begin: Instant,
  /// Accumulated retry cooldown for this task, subtracted from effective elapsed time
  waited: Rc<Cell<Duration>>,
  ended: bool,
}

impl Job {
  pub(crate) fn new(tx: MTx<List<Event>>, id: u32, reply: bool) -> Self {
    Self {
      tx,
      reply,
      id,
      begin: Instant::now(),
      waited: Rc::new(Cell::new(Duration::ZERO)),
      ended: false,
    }
  }

  fn end(&mut self, err: Option<String>) {
    self.ended = true;
    // Effective elapsed time is measured on the task thread, unaffected by the render thread's event backlog
    let active = self.begin.elapsed().saturating_sub(self.waited.get());
    let _ = self.tx.send(Event::End {
      id: self.id,
      err,
      active,
    });
  }

  /// Bind or switch the active slot serving this task
  pub fn slot(&mut self, slot: usize) {
    let _ = self.tx.send(Event::JobSlot { id: self.id, slot });
  }

  /// Accumulate tokens consumed by this task
  pub fn tok(&mut self, tok: u32) {
    if tok > 0 {
      let _ = self.tx.send(Event::JobTok { id: self.id, tok });
    }
  }

  /// Reply output callback, sharing this task's panel; a no-op callback in non-interactive mode
  pub fn reply(&self) -> Reply {
    Reply {
      tx: self.reply.then(|| self.tx.clone()),
      id: self.id,
    }
  }

  /// Failure retry callback, sharing this task's panel
  pub fn retry(&self) -> Retry {
    Retry {
      tx: self.tx.clone(),
      id: self.id,
      waited: Rc::clone(&self.waited),
    }
  }

  /// Finish successfully
  pub fn done(mut self) {
    self.end(None);
  }

  /// Push a thinking delta
  pub fn think(&mut self, s: &str) {
    text(&self.tx, self.id, s, false);
  }

  /// Fail
  pub fn fail(mut self, err: &str) {
    self.end(Some(one_line(err)));
  }
}

/// Reply output callback; when `tx` is `None` (non-interactive mode) it passes through and sends nothing
pub struct Reply {
  tx: Option<MTx<List<Event>>>,
  id: u32,
}

/// Failure retry callback
pub struct Retry {
  tx: MTx<List<Event>>,
  id: u32,
  waited: Rc<Cell<Duration>>,
}

/// Clean, collapse whitespace and truncate the error summary at a char boundary, keeping it one compact line
fn brief(raw: &str) -> String {
  let cleaned = clean(raw);
  let mut out = String::with_capacity(cleaned.len().min(ERR_CAP + 4));
  for word in cleaned.split_whitespace() {
    let sep = usize::from(!out.is_empty());
    if out.len() + sep + word.len() > ERR_CAP {
      let end = word.floor_char_boundary(ERR_CAP.saturating_sub(out.len() + sep));
      if end > 0 {
        if sep > 0 {
          out.push(' ');
        }
        out.push_str(&word[..end]);
      }
      out.push('…');
      return out;
    }
    if sep > 0 {
      out.push(' ');
    }
    out.push_str(word);
  }
  out
}

/// Send a chunk of streaming output
fn text(tx: &MTx<List<Event>>, id: u32, s: &str, reply: bool) {
  let cleaned = clean(s);
  if cleaned.is_empty() {
    return;
  }
  let _ = tx.send(Event::Text {
    id,
    text: cleaned.into_owned(),
    reply,
  });
}

impl Reply {
  /// Push a reply delta
  pub fn reply(&mut self, s: &str) {
    if let Some(tx) = &self.tx {
      text(tx, self.id, s, true);
    }
  }
}

impl Retry {
  /// Record the cooldown time and status summary of one failed retry
  pub fn fail(
    &mut self,
    round: usize,
    retry: usize,
    wait: Duration,
    base: &str,
    err: impl fmt::Display,
  ) {
    // After this failure the cooldown always sleeps fully before retrying; if the task is canceled during cooldown its planned unit never counts toward progress
    self.waited.set(self.waited.get().saturating_add(wait));
    let clean_base = one_line_cow(base);
    let trimmed = clean_base.trim();
    let base = if trimmed.len() == clean_base.len() {
      clean_base.into_owned()
    } else {
      trimmed.to_owned()
    };
    let _ = self.tx.send(Event::Retry {
      id: self.id,
      nth: round,
      total: retry,
      wait,
      base,
      err: brief(&err.to_string()),
    });
  }
}

impl Drop for Job {
  fn drop(&mut self) {
    if !self.ended {
      self.end(Some(T.ui.cancel().into()));
    }
  }
}