i18n_ui 0.2.108

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

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

use crate::event::Event;

/// 任务句柄;未调用 [`Job::done`] / [`Job::fail`] 就被丢弃视为取消
pub struct Job {
  tx: MTx<List<Event>>,
  id: u32,
  ended: bool,
}

impl Job {
  pub(crate) fn new(tx: MTx<List<Event>>, id: u32) -> Self {
    Self {
      tx,
      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.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()));
  }
}

/// 正文输出回调
pub struct Reply {
  tx: MTx<List<Event>>,
  id: u32,
}

/// 发送一段流式输出
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 {
    text(&self.tx, self.id, s, true)
  }
}

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