i18n_ui 0.2.123

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

use std::time::Duration;

use ai_api::{Error, Flow, OnFail, OnReply, OnThink, clean_text as clean};
use crossfire::{MTx, mpsc::List};

use crate::event::Event;

/// 任务未结束就被丢弃时的失败原因
const CANCEL: &str = "已取消";
/// 重试错误摘要最大字节数
const ERR_CAP: usize = 120;

/// 任务句柄;未调用 [`Job::done`] / [`Job::fail`] 就被丢弃视为取消
pub struct Job {
  tx: MTx<List<Event>>,
  /// 是否展示流式正文:非交互模式正文回调短路,省去清洗与通道开销
  reply: bool,
  id: u32,
  ended: bool,
}

impl Job {
  pub(crate) fn new(tx: MTx<List<Event>>, id: u32, reply: bool) -> Self {
    Self {
      tx,
      reply,
      id,
      ended: false,
    }
  }

  fn end(&mut self, err: Option<String>) {
    self.ended = true;
    let _ = self.tx.send(Event::End { id: self.id, err });
  }

  /// 正文输出回调,与本任务共用面板;非交互模式下为空回调
  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,
    }
  }

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

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

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

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

/// 清洗、折叠空白并按字符边界截断错误摘要,保证单行紧凑
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) -> Flow {
  let _ = tx.send(Event::Text {
    id,
    text: clean(s).into_owned(),
    reply,
  });
  Flow::Continue
}

impl OnThink for Job {
  fn think(&mut self, s: &str) -> Flow {
    text(&self.tx, self.id, s, false)
  }
}

impl OnReply for Reply {
  fn reply(&mut self, s: &str) -> Flow {
    if let Some(tx) = &self.tx {
      text(tx, self.id, s, true)
    } else {
      Flow::Continue
    }
  }
}

impl OnFail for Retry {
  fn fail(&mut self, round: usize, retry: usize, wait: Duration, base: &str, err: &Error) {
    let _ = self.tx.send(Event::Retry {
      id: self.id,
      nth: round,
      total: retry,
      wait,
      base: clean(base).trim().to_owned(),
      err: brief(&err.to_string()),
    });
  }
}

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