Skip to main content

i18n_ui/
job.rs

1//! Handle for a single model-calling task: receives streaming output and reports the result on finish
2
3use std::{
4  cell::Cell,
5  fmt,
6  rc::Rc,
7  time::{Duration, Instant},
8};
9
10use clean_text::{clean_text as clean, one_line as one_line_cow};
11use crossfire::{MTx, mpsc::List};
12
13use crate::{event::Event, i18n::T, text::one_line};
14/// Max bytes of retry error summary body (trailing ellipsis counts 3 extra bytes)
15const ERR_CAP: usize = 120;
16
17/// Task handle; dropping without calling [`Job::done`] / [`Job::fail`] counts as cancellation
18pub struct Job {
19  tx: MTx<List<Event>>,
20  /// Whether to show streaming reply: non-interactive mode short-circuits the reply callback, saving cleaning and channel overhead
21  reply: bool,
22  id: u32,
23  /// Task start time (when the slot is acquired and the model call is about to begin).
24  ///
25  /// Uses `std::time::Instant`, a monotonic clock that excludes system sleep
26  /// (`CLOCK_UPTIME_RAW` / `mach_absolute_time` on macOS, `CLOCK_MONOTONIC` on Linux),
27  /// so a closed lid does not count as model time.
28  ///
29  /// Do not switch this to `coarsetime`: on macOS it reads `CLOCK_MONOTONIC_RAW_APPROX`,
30  /// which keeps ticking while the machine is suspended. One lid close would add hours to a
31  /// single `active` duration; because `progbar::Rate` averages the last 32 samples,
32  /// that outlier collapses the throughput estimate and makes the ETA jump by orders of
33  /// magnitude.
34  begin: Instant,
35  /// Accumulated retry cooldown for this task, subtracted from effective elapsed time
36  waited: Rc<Cell<Duration>>,
37  ended: bool,
38}
39
40impl Job {
41  pub(crate) fn new(tx: MTx<List<Event>>, id: u32, reply: bool) -> Self {
42    Self {
43      tx,
44      reply,
45      id,
46      begin: Instant::now(),
47      waited: Rc::new(Cell::new(Duration::ZERO)),
48      ended: false,
49    }
50  }
51
52  fn end(&mut self, err: Option<String>) {
53    self.ended = true;
54    // Effective elapsed time is measured on the task thread, unaffected by the render thread's event backlog
55    let active = self.begin.elapsed().saturating_sub(self.waited.get());
56    let _ = self.tx.send(Event::End {
57      id: self.id,
58      err,
59      active,
60    });
61  }
62
63  /// Bind or switch the active slot serving this task
64  pub fn slot(&mut self, slot: usize) {
65    let _ = self.tx.send(Event::JobSlot { id: self.id, slot });
66  }
67
68  /// Accumulate tokens consumed by this task
69  pub fn tok(&mut self, tok: u32) {
70    if tok > 0 {
71      let _ = self.tx.send(Event::JobTok { id: self.id, tok });
72    }
73  }
74
75  /// Reply output callback, sharing this task's panel; a no-op callback in non-interactive mode
76  pub fn reply(&self) -> Reply {
77    Reply {
78      tx: self.reply.then(|| self.tx.clone()),
79      id: self.id,
80    }
81  }
82
83  /// Failure retry callback, sharing this task's panel
84  pub fn retry(&self) -> Retry {
85    Retry {
86      tx: self.tx.clone(),
87      id: self.id,
88      waited: Rc::clone(&self.waited),
89    }
90  }
91
92  /// Finish successfully
93  pub fn done(mut self) {
94    self.end(None);
95  }
96
97  /// Push a thinking delta
98  pub fn think(&mut self, s: &str) {
99    text(&self.tx, self.id, s, false);
100  }
101
102  /// Fail
103  pub fn fail(mut self, err: &str) {
104    self.end(Some(one_line(err)));
105  }
106}
107
108/// Reply output callback; when `tx` is `None` (non-interactive mode) it passes through and sends nothing
109pub struct Reply {
110  tx: Option<MTx<List<Event>>>,
111  id: u32,
112}
113
114/// Failure retry callback
115pub struct Retry {
116  tx: MTx<List<Event>>,
117  id: u32,
118  waited: Rc<Cell<Duration>>,
119}
120
121/// Clean, collapse whitespace and truncate the error summary at a char boundary, keeping it one compact line
122fn brief(raw: &str) -> String {
123  let cleaned = clean(raw);
124  let mut out = String::with_capacity(cleaned.len().min(ERR_CAP + 4));
125  for word in cleaned.split_whitespace() {
126    let sep = usize::from(!out.is_empty());
127    if out.len() + sep + word.len() > ERR_CAP {
128      let end = word.floor_char_boundary(ERR_CAP.saturating_sub(out.len() + sep));
129      if end > 0 {
130        if sep > 0 {
131          out.push(' ');
132        }
133        out.push_str(&word[..end]);
134      }
135      out.push('…');
136      return out;
137    }
138    if sep > 0 {
139      out.push(' ');
140    }
141    out.push_str(word);
142  }
143  out
144}
145
146/// Send a chunk of streaming output
147fn text(tx: &MTx<List<Event>>, id: u32, s: &str, reply: bool) {
148  let cleaned = clean(s);
149  if cleaned.is_empty() {
150    return;
151  }
152  let _ = tx.send(Event::Text {
153    id,
154    text: cleaned.into_owned(),
155    reply,
156  });
157}
158
159impl Reply {
160  /// Push a reply delta
161  pub fn reply(&mut self, s: &str) {
162    if let Some(tx) = &self.tx {
163      text(tx, self.id, s, true);
164    }
165  }
166}
167
168impl Retry {
169  /// Record the cooldown time and status summary of one failed retry
170  pub fn fail(
171    &mut self,
172    round: usize,
173    retry: usize,
174    wait: Duration,
175    base: &str,
176    err: impl fmt::Display,
177  ) {
178    // After this failure the cooldown always sleeps fully before retrying; if the task is canceled during cooldown its planned unit never counts toward progress
179    self.waited.set(self.waited.get().saturating_add(wait));
180    let clean_base = one_line_cow(base);
181    let trimmed = clean_base.trim();
182    let base = if trimmed.len() == clean_base.len() {
183      clean_base.into_owned()
184    } else {
185      trimmed.to_owned()
186    };
187    let _ = self.tx.send(Event::Retry {
188      id: self.id,
189      nth: round,
190      total: retry,
191      wait,
192      base,
193      err: brief(&err.to_string()),
194    });
195  }
196}
197
198impl Drop for Job {
199  fn drop(&mut self) {
200    if !self.ended {
201      self.end(Some(T.ui.cancel().into()));
202    }
203  }
204}