i18n_ui 0.2.125

i18n 翻译进度终端界面:交互式并发面板与非交互逐行输出
//! 单个调用模型的任务句柄:接收流式输出,结束时上报结果

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

use clean_text::clean_text as clean;
use coarsetime::Instant;
use crossfire::{MTx, mpsc::List};

use crate::{event::Event, i18n::T, text::one_line};
/// 重试错误摘要正文最大字节数(末尾省略号另计 3 字节)
const ERR_CAP: usize = 120;

/// 任务句柄;未调用 [`Job::done`] / [`Job::fail`] 就被丢弃视为取消
pub struct Job {
  tx: MTx<List<Event>>,
  /// 是否展示流式正文:非交互模式正文回调短路,省去清洗与通道开销
  reply: bool,
  id: u32,
  /// 任务开始时刻(取得并发名额、即将调用模型时)
  begin: Instant,
  /// 本任务重试冷却累计时长,用于从有效耗时中扣除
  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;
    // 有效耗时在任务线程测量,不受渲染线程处理积压事件的影响
    let active = self
      .begin
      .elapsed()
      .saturating_sub(self.waited.get().into())
      .into();
    let _ = self.tx.send(Event::End {
      id: self.id,
      err,
      active,
    });
  }

  /// 正文输出回调,与本任务共用面板;非交互模式下为空回调
  pub fn reply(&self) -> Reply {
    Reply {
      tx: self.reply.then(|| self.tx.clone()),
      id: self.id,
    }
  }

  /// 失败重试回调,与本任务共用面板
  pub fn retry(&self) -> Retry {
    Retry {
      tx: self.tx.clone(),
      id: self.id,
      waited: Rc::clone(&self.waited),
    }
  }

  /// 成功完成
  pub fn done(mut self) {
    self.end(None);
  }

  /// 推送思考增量
  pub fn think(&mut self, s: &str) {
    text(&self.tx, self.id, s, false);
  }

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

/// 正文输出回调;`tx` 为 `None` 时(非交互模式)直通不发送
pub struct Reply {
  tx: Option<MTx<List<Event>>>,
  id: u32,
}

/// 失败重试回调
pub struct Retry {
  tx: MTx<List<Event>>,
  id: u32,
  waited: Rc<Cell<Duration>>,
}

/// 清洗、折叠空白并按字符边界截断错误摘要,保证单行紧凑
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
}

/// 发送一段流式输出
fn text(tx: &MTx<List<Event>>, id: u32, s: &str, reply: bool) {
  let _ = tx.send(Event::Text {
    id,
    text: clean(s).into_owned(),
    reply,
  });
}

impl Reply {
  /// 推送正文增量
  pub fn reply(&mut self, s: &str) {
    if let Some(tx) = &self.tx {
      text(tx, self.id, s, true);
    }
  }
}

impl Retry {
  /// 记录一次失败重试的冷却耗时与状态摘要
  pub fn fail(
    &mut self,
    round: usize,
    retry: usize,
    wait: Duration,
    base: &str,
    err: impl fmt::Display,
  ) {
    // 本次失败后的冷却一定会先睡完再重试;任务若在冷却中被取消,其计划量本就不计入进度
    self.waited.set(self.waited.get().saturating_add(wait));
    let _ = self.tx.send(Event::Retry {
      id: self.id,
      nth: round,
      total: retry,
      wait,
      base: one_line(base).trim().to_owned(),
      err: brief(&err.to_string()),
    });
  }
}

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