i18n_ui 0.2.125

i18n 翻译进度终端界面:交互式并发面板与非交互逐行输出
//! 两种渲染共用的界面状态:进度、运行中任务与计数

use std::{
  mem::take,
  time::{Duration, Instant as WallInstant},
};

use coarsetime::Instant;
use i18n_progress::Progress;

use crate::event::{Event, Name};

/// 思考尾部保留上限(字节),只用于显示最新内容
pub(crate) const TAIL_CAP: usize = 4096;

/// 当前任务的实时重试状态(收到新流式输出后自动清除)
pub(crate) struct RetryState {
  pub(crate) nth: usize,
  pub(crate) total: usize,
  pub(crate) wait: Duration,
  pub(crate) at: WallInstant,
  pub(crate) base: String,
  pub(crate) err: String,
  /// 当前连续重试次数(同一轮切换多 token 时递增)
  pub(crate) streak: usize,
}

impl RetryState {
  /// 距离下次重试的剩余冷却时长
  pub(crate) fn rem(&self, now: WallInstant) -> Duration {
    self
      .wait
      .saturating_sub(now.saturating_duration_since(self.at))
  }
}

/// 运行中的任务
pub(crate) struct Run {
  pub(crate) id: u32,
  pub(crate) name: Name,
  pub(crate) begin: Instant,
  /// 思考:交互模式保留最新尾部;非交互模式暂存尚未成行的部分
  pub(crate) think: String,
  /// 正文最新尾部(仅交互模式)
  pub(crate) reply: String,
  /// 当前重试告警态
  pub(crate) retry: Option<RetryState>,
  /// 本任务累计重试次数
  pub(crate) retry_cnt: usize,
}

impl Run {
  /// 追加流式输出到思考或正文,并裁掉过旧内容
  pub(crate) fn push_tail(&mut self, s: &str, reply: bool) {
    // 已收到模型流式输出,清除重试等待态
    self.retry = None;
    let buf = if reply {
      &mut self.reply
    } else {
      &mut self.think
    };
    buf.push_str(s);
    if let Some(over) = buf.len().checked_sub(TAIL_CAP) {
      buf.drain(..buf.ceil_char_boundary(over));
    }
  }
}

/// 已结束任务
pub(crate) struct Ended {
  pub(crate) name: Name,
  pub(crate) sec: f32,
  pub(crate) retry_cnt: usize,
  pub(crate) err: Option<String>,
  /// 未成行的思考残余:非交互模式在结束时补输出,交互模式忽略
  pub(crate) think: String,
}

pub(crate) struct Board {
  pub(crate) progress: Progress,
  pub(crate) run_li: Vec<Run>,
  pub(crate) hit: usize,
  pub(crate) ok: usize,
  pub(crate) fail: usize,
  pub(crate) retry: usize,
  begin: Instant,
  /// 预检尚未完成时为 `false`,底栏显示扫描状态而不是 100%
  pub(crate) plan_ready: bool,
}

/// 事件应用后的副作用:渲染层据此决定输出,纯状态事件不产生任何输出
pub(crate) enum Act {
  /// 仅更新状态
  None,
  /// 开始任务,携带任务 id 供渲染层读取名称
  Start(u32),
  /// 流式输出
  Text { id: u32, text: String, reply: bool },
  /// 请求重试,携带任务 id
  Retry(u32),
  /// 任务结束
  End(Ended),
  /// 提示信息
  Log(String),
  /// 关闭界面
  Close,
}

impl Board {
  pub(crate) fn new() -> Self {
    Self {
      progress: Progress::new(0),
      run_li: Vec::new(),
      hit: 0,
      ok: 0,
      fail: 0,
      retry: 0,
      begin: Instant::now(),
      plan_ready: false,
    }
  }

  /// 应用事件;状态迁移只在这里发生,两种渲染模式共用
  pub(crate) fn apply(&mut self, event: Event) -> Act {
    match event {
      Event::Plan {
        job,
        concurrency,
        cache,
      } => {
        self.plan(job, concurrency, cache);
        Act::None
      }
      Event::Hit => {
        self.hit();
        Act::None
      }
      Event::Grow => {
        self.grow();
        Act::None
      }
      Event::Skip => {
        self.skip();
        Act::None
      }
      Event::Start { id, name } => {
        self.start(id, name);
        Act::Start(id)
      }
      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, concurrency: u16, cache: usize) {
    self.progress = Progress::new(job).with_concurrency(concurrency);
    self.hit = cache;
    self.plan_ready = true;
  }

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

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

  /// 计划内但本轮未处理的语言:消费一次计划量,不计入缓存命中
  pub(crate) fn skip(&mut self) {
    self.progress.skip();
  }

  pub(crate) fn start(&mut self, id: u32, name: Name) {
    self.run_li.push(Run {
      id,
      name,
      begin: Instant::now(),
      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)
  }

  /// 记录一次请求重试;渲染端经 `run(id)` 重查,无需返回值
  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;
    };
    self.retry += 1;
    run.retry_cnt += 1;
    let streak = run.retry.as_ref().map_or(1, |r| r.streak + 1);
    run.retry = Some(RetryState {
      nth,
      total,
      wait,
      at: WallInstant::now(),
      base,
      err,
      streak,
    });
  }

  /// 结束任务:成功计入进度,失败从总量扣除
  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 mut run = self.run_li.remove(pos);
    if err.is_some() {
      self.fail += 1;
      self.progress.skip();
    } else {
      self.ok += 1;
      self.progress.finish(active);
    }
    let ended = Ended {
      name: Name {
        from: take(&mut run.name.from),
        out: take(&mut run.name.out),
      },
      sec: sec(run.begin),
      retry_cnt: run.retry_cnt,
      err,
      think: take(&mut run.think),
    };
    Some(ended)
  }

  /// 总耗时(秒)
  pub(crate) fn sec(&self) -> f32 {
    sec(self.begin)
  }
}

/// 自 `begin` 起的秒数
pub(crate) fn sec(begin: Instant) -> f32 {
  begin.elapsed().as_f64() as f32
}