Skip to main content

native_gui_core/
async_ui.rs

1//! Sendable UI-thread command proxy for background work.
2//!
3//! Background threads never borrow or mutate [`crate::Ui`]. Instead they hold
4//! a cloneable, `Send` [`UiProxy`] and post [`TaskCommand`] values into a
5//! bounded channel. The UI thread drains that channel inside its event
6//! functions (`wait_event`, `poll_event`, `dispatch_events`,
7//! `run_until_closed`), applies widget mutations through the same `set_*`
8//! paths as direct calls, and surfaces task lifecycle notifications as
9//! [`crate::UiEvent::Task`] values.
10//!
11//! ```
12//! use native_gui_mock::MockBackend;
13//! use native_gui_core::{Ui, UiEvent, WidgetKind};
14//!
15//! let mut ui = Ui::new(MockBackend::default());
16//! let label = ui.create(WidgetKind::Label, Some("idle"))?;
17//! let proxy = ui.task_proxy();
18//!
19//! let token = proxy.start_task();
20//! let worker_proxy = proxy.clone();
21//! std::thread::spawn(move || {
22//!     // Do the slow work here, then publish the result.
23//!     let _ = worker_proxy.set_text(label, "done");
24//!     let _ = worker_proxy.finish(&token);
25//! });
26//!
27//! // The UI thread applies queued commands while it waits for events.
28//! while let Ok(event) = ui.wait_event() {
29//!     if matches!(event, UiEvent::Task(_)) {
30//!         break;
31//!     }
32//! }
33//! assert_eq!(ui.widget(label).and_then(|spec| spec.text.as_deref()), Some("done"));
34//! # Ok::<(), native_gui_core::GuiError>(())
35//! ```
36//!
37//! Guarantees:
38//! - commands are applied in FIFO post order;
39//! - the queue is bounded (see [`DEFAULT_TASK_QUEUE_CAPACITY`]) and overflow
40//!   is reported as [`TaskSendError::Full`] instead of blocking or growing
41//!   without bound;
42//! - once the owning [`crate::Ui`] is dropped, posts fail with
43//!   [`TaskSendError::Closed`], so stale workers stop deterministically;
44//! - drop contract: dropping a `Ui` (or calling [`crate::Ui::shutdown`])
45//!   closes the channel immediately. Commands already accepted but not yet
46//!   drained are discarded unapplied — a post that returned `Ok(())` before
47//!   teardown is *accepted*, not *applied*; call
48//!   [`crate::Ui::drain_task_commands`] first, and use the count returned by
49//!   [`crate::Ui::shutdown`] to detect lost commits;
50//! - commands that target removed widgets are rejected (counted in
51//!   [`TaskDrainReport::rejected`]) and never panic; every rejected command
52//!   also surfaces as [`TaskEvent::Aborted`], so a teardown race cannot
53//!   swallow a worker's commit silently.
54//!
55//! # Lossy vs. lossless backpressure
56//!
57//! A bounded queue must distinguish what it may drop from what it must not:
58//!
59//! | Class | Examples | Under pressure |
60//! |---|---|---|
61//! | [`TaskClass::Lossy`] — coalescent telemetry | `Progress`, intermediate `SetText`/`SetValue` samples | sent with [`UiProxy::post`]; on [`TaskSendError::Full`] the worker skips the sample (the next one supersedes it) |
62//! | [`TaskClass::Lossless`] — essential lifecycle | `Finished`, `Failed`, and final transactional commits | sent with [`UiProxy::send_lossless`], which blocks (with backoff) until the queue accepts the command, the UI is gone, or the caller's timeout expires |
63//!
64//! Dropping a lossless token strands the UI state machine (a progress bar
65//! that never completes, a worker whose result never lands), so
66//! [`TaskCommand::class`] names the default class of every command and
67//! [`UiProxy::send_lossless`] is the guaranteed path. A lossless send never
68//! waits forever: a worker that cannot make progress reports
69//! [`TaskSendError::Full`] to its caller instead of hanging, and a worker
70//! whose UI is gone stops on [`TaskSendError::Closed`].
71
72use std::fmt;
73use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
74use std::sync::mpsc::{sync_channel, Receiver, SyncSender, TrySendError};
75use std::sync::Arc;
76use std::time::{Duration, Instant};
77
78use crate::error::GuiError;
79use crate::widgets::WidgetId;
80
81/// Default capacity of the UI command channel created by
82/// [`crate::Ui::task_proxy`].
83///
84/// The bound keeps a runaway worker from growing the queue without limit; a
85/// full queue is reported to the worker as [`TaskSendError::Full`] so it can
86/// back off or drop intermediate progress updates.
87pub const DEFAULT_TASK_QUEUE_CAPACITY: usize = 256;
88
89/// Initial retry backoff for [`UiProxy::send_lossless`].
90const LOSSLESS_RETRY_BACKOFF_START: Duration = Duration::from_micros(50);
91
92/// Upper bound for the [`UiProxy::send_lossless`] retry backoff.
93const LOSSLESS_RETRY_BACKOFF_MAX: Duration = Duration::from_millis(2);
94
95/// Identifier for one background operation started through
96/// [`UiProxy::start_task`].
97///
98/// IDs are allocated by the proxy (unique per proxy, starting at 1) and are
99/// stable for the whole operation, matching the "operation IDs" contract
100/// shared across async operations.
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
102pub struct TaskId(pub u64);
103
104impl fmt::Display for TaskId {
105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106        write!(f, "task-{}", self.0)
107    }
108}
109
110/// A command posted from a worker thread to the UI thread.
111///
112/// Widget commands mutate a widget exactly like the matching
113/// `Ui::set_*` call; lifecycle commands produce
114/// [`crate::UiEvent::Task`] notifications instead of touching natives.
115#[derive(Debug, Clone, PartialEq)]
116pub enum TaskCommand {
117    /// Replaces rows in a DataList/ListView widget.
118    SetDataListItems {
119        widget_id: WidgetId,
120        items: Vec<String>,
121    },
122    /// Replaces rows in a DataGrid widget.
123    SetDataGridRows {
124        widget_id: WidgetId,
125        rows: Vec<Vec<String>>,
126    },
127    /// Updates text content for a widget.
128    SetText { widget_id: WidgetId, text: String },
129    /// Sets numeric value for Slider/SpinBox/ProgressBar widgets.
130    SetValue { widget_id: WidgetId, value: i32 },
131    /// Sets checked state for check-capable widgets.
132    SetChecked { widget_id: WidgetId, checked: bool },
133    /// Enables or disables a widget.
134    SetEnabled { widget_id: WidgetId, enabled: bool },
135    /// Shows or hides a widget.
136    SetVisible { widget_id: WidgetId, visible: bool },
137    /// Reports intermediate progress for a task (0.0–100.0 by convention).
138    Progress { task: TaskId, value: f64 },
139    /// Reports that a task finished; posted once per task (duplicates are
140    /// delivered as-is so the UI layer can decide how strict to be).
141    Finished { task: TaskId },
142    /// Reports that a task failed with a human-readable message.
143    Failed { task: TaskId, message: String },
144}
145
146/// Channel class of a [`TaskCommand`] under queue pressure.
147///
148/// The bounded queue (see [`DEFAULT_TASK_QUEUE_CAPACITY`]) rejects posts when
149/// it is full. What the *sender* should do about that depends on the command:
150///
151/// - [`TaskClass::Lossy`] commands are coalescent telemetry. Skipping one is
152///   harmless because the next sample supersedes it, so workers send them
153///   with [`UiProxy::post`] and drop on [`TaskSendError::Full`].
154/// - [`TaskClass::Lossless`] commands are essential lifecycle tokens. Losing
155///   one strands the UI state machine (a task that never completes), so
156///   workers send them with [`UiProxy::send_lossless`], which waits for room
157///   with backoff.
158///
159/// The class is a *default*, not a straitjacket: a widget mutation that
160/// commits a transaction (for example the final result of a search) should
161/// also travel through [`UiProxy::send_lossless`] even though its command
162/// class is [`TaskClass::Lossy`].
163#[derive(Debug, Clone, Copy, PartialEq, Eq)]
164pub enum TaskClass {
165    /// Coalescent telemetry: safe to drop under pressure.
166    Lossy,
167    /// Essential lifecycle: must not be silently dropped.
168    Lossless,
169}
170
171/// The widget-targeting [`TaskCommand`] family.
172///
173/// Carried by [`TaskEvent::Aborted`] as a lightweight name for the command
174/// that did not apply, so applications can tell an aborted intermediate
175/// telemetry sample from an aborted final commit without matching the full
176/// payload.
177#[derive(Debug, Clone, Copy, PartialEq, Eq)]
178pub enum TaskCommandKind {
179    SetDataListItems,
180    SetDataGridRows,
181    SetText,
182    SetValue,
183    SetChecked,
184    SetEnabled,
185    SetVisible,
186}
187
188impl TaskCommand {
189    /// The command's default channel class (see [`TaskClass`]).
190    ///
191    /// `Finished` and `Failed` are lossless because the UI state machine
192    /// depends on them; every other command is coalescent telemetry by
193    /// default (intermediate state publishes that the next sample or the
194    /// final commit supersedes).
195    pub fn class(&self) -> TaskClass {
196        match self {
197            TaskCommand::Finished { .. } | TaskCommand::Failed { .. } => TaskClass::Lossless,
198            TaskCommand::SetDataListItems { .. }
199            | TaskCommand::SetDataGridRows { .. }
200            | TaskCommand::SetText { .. }
201            | TaskCommand::SetValue { .. }
202            | TaskCommand::SetChecked { .. }
203            | TaskCommand::SetEnabled { .. }
204            | TaskCommand::SetVisible { .. }
205            | TaskCommand::Progress { .. } => TaskClass::Lossy,
206        }
207    }
208
209    /// The widget this command mutates, with its kind name; `None` for
210    /// lifecycle commands (`Progress`/`Finished`/`Failed`) that carry no
211    /// widget target.
212    pub fn widget_target(&self) -> Option<(WidgetId, TaskCommandKind)> {
213        match self {
214            TaskCommand::SetDataListItems { widget_id, .. } => {
215                Some((*widget_id, TaskCommandKind::SetDataListItems))
216            }
217            TaskCommand::SetDataGridRows { widget_id, .. } => {
218                Some((*widget_id, TaskCommandKind::SetDataGridRows))
219            }
220            TaskCommand::SetText { widget_id, .. } => Some((*widget_id, TaskCommandKind::SetText)),
221            TaskCommand::SetValue { widget_id, .. } => {
222                Some((*widget_id, TaskCommandKind::SetValue))
223            }
224            TaskCommand::SetChecked { widget_id, .. } => {
225                Some((*widget_id, TaskCommandKind::SetChecked))
226            }
227            TaskCommand::SetEnabled { widget_id, .. } => {
228                Some((*widget_id, TaskCommandKind::SetEnabled))
229            }
230            TaskCommand::SetVisible { widget_id, .. } => {
231                Some((*widget_id, TaskCommandKind::SetVisible))
232            }
233            TaskCommand::Progress { .. }
234            | TaskCommand::Finished { .. }
235            | TaskCommand::Failed { .. } => None,
236        }
237    }
238}
239
240/// Why a queued widget command never reached the shared model.
241///
242/// [`TaskEvent::Aborted`] carries this so a worker that committed through
243/// [`UiProxy::send_lossless`] can distinguish "the widget is gone" from
244/// "the command landed": the dead-letter half of the lossless guarantees.
245#[derive(Debug, Clone, PartialEq, Eq)]
246pub enum TaskAbortReason {
247    /// The target widget had already been removed when the drain ran - the
248    /// teardown race that used to be swallowed by
249    /// [`TaskDrainReport::rejected`].
250    WidgetRemoved,
251    /// The target widget is live but refused the mutation (kind guard,
252    /// validated range, ...); the typed error is preserved for the
253    /// application.
254    Refused(GuiError),
255}
256
257/// Lifecycle notification for one background task, delivered to the UI
258/// thread as [`crate::UiEvent::Task`].
259#[derive(Debug, Clone, PartialEq)]
260pub enum TaskEvent {
261    /// Intermediate progress reported through [`UiProxy::progress`].
262    Progress { task: TaskId, value: f64 },
263    /// The task finished (completed or cancelled — the app decides which).
264    Finished { task: TaskId },
265    /// The task failed; `message` is app-defined (e.g. an I/O error).
266    Failed { task: TaskId, message: String },
267    /// A queued widget command was aborted before it could apply:
268    /// its target was tombstoned by a teardown, or a
269    /// live target refused the mutation.
270    ///
271    /// One event is emitted per aborted command, in drain order, and the
272    /// same commands are counted by [`TaskDrainReport::rejected`]. This is
273    /// the dead-letter notification the lossless guarantees need: a worker
274    /// whose final commit lost its widget learns about it instead of facing
275    /// silence. Treat the first abort for a tombstoned widget as the signal
276    /// to stop that worker.
277    Aborted {
278        /// The widget the aborted command targeted.
279        widget_id: WidgetId,
280        /// Which command was aborted.
281        command: TaskCommandKind,
282        /// Why the command did not apply.
283        reason: TaskAbortReason,
284    },
285}
286
287/// Why a [`UiProxy`] post was not accepted.
288#[derive(Debug, Clone, Copy, PartialEq, Eq)]
289pub enum TaskSendError {
290    /// The bounded queue is full.
291    ///
292    /// [`UiProxy::post`] reports it immediately — the lossy caller drops the
293    /// sample or retries later. [`UiProxy::send_lossless`] reports it only
294    /// after its retry deadline expired, so a lossless caller knows the
295    /// command was **not** queued.
296    Full,
297    /// The owning [`crate::Ui`] is gone; the worker should stop.
298    Closed,
299}
300
301impl fmt::Display for TaskSendError {
302    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
303        match self {
304            TaskSendError::Full => write!(f, "background task queue is full"),
305            TaskSendError::Closed => write!(f, "UI thread command channel is closed"),
306        }
307    }
308}
309
310impl std::error::Error for TaskSendError {}
311
312/// Outcome of one [`crate::Ui::drain_task_commands`] call.
313#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
314pub struct TaskDrainReport {
315    /// Commands applied successfully (including lifecycle notifications).
316    pub applied: usize,
317    /// Commands rejected because their target widget is gone or the backend
318    /// refused the mutation. Rejections never panic and never stop the drain.
319    pub rejected: usize,
320}
321
322impl TaskDrainReport {
323    /// Total number of commands processed by the drain.
324    pub fn total(&self) -> usize {
325        self.applied + self.rejected
326    }
327}
328
329/// Cancellation handle shared between the UI thread and one worker.
330///
331/// The UI thread keeps a clone and calls [`TaskToken::cancel`]; the worker
332/// keeps another clone and polls [`TaskToken::is_cancelled`] between chunks
333/// of work. Cancellation is cooperative: the worker decides where it is safe
334/// to stop and then posts its final [`TaskCommand::Finished`].
335#[derive(Debug, Clone)]
336pub struct TaskToken {
337    id: TaskId,
338    cancelled: Arc<AtomicBool>,
339}
340
341impl TaskToken {
342    /// The identifier of the task this token belongs to.
343    pub fn id(&self) -> TaskId {
344        self.id
345    }
346
347    /// Requests cancellation. Safe to call from any thread; idempotent.
348    pub fn cancel(&self) {
349        self.cancelled.store(true, Ordering::SeqCst);
350    }
351
352    /// Returns `true` once [`TaskToken::cancel`] was called.
353    pub fn is_cancelled(&self) -> bool {
354        self.cancelled.load(Ordering::SeqCst)
355    }
356
357    /// Sleeps for up to `duration`, returning early if cancellation is requested.
358    ///
359    /// Returns `true` if the full `duration` elapsed without cancellation, or `false`
360    /// immediately if cancellation was requested (either prior to this call or during the sleep).
361    /// Polling quantum is bounded (at most 25ms) to guarantee prompt cancellation response
362    /// without CPU spinning.
363    pub fn sleep_or_cancelled(&self, duration: Duration) -> bool {
364        if self.is_cancelled() {
365            return false;
366        }
367        let start = Instant::now();
368        let quantum = Duration::from_millis(25);
369        while start.elapsed() < duration {
370            if self.is_cancelled() {
371                return false;
372            }
373            let remaining = duration.saturating_sub(start.elapsed());
374            let step = remaining.min(quantum);
375            std::thread::sleep(step);
376        }
377        !self.is_cancelled()
378    }
379}
380
381/// Handle returned by [`crate::Ui::spawn_task_with_callback`] representing an active background
382/// task.
383///
384/// Can be retained on the UI thread to query status, obtain the task ID, or cancel the task.
385#[derive(Debug, Clone)]
386pub struct TaskHandle {
387    token: TaskToken,
388    finished: Arc<AtomicBool>,
389}
390
391impl TaskHandle {
392    /// Creates a new task handle wrapping `token`.
393    pub fn new(token: TaskToken) -> Self {
394        Self {
395            token,
396            finished: Arc::new(AtomicBool::new(false)),
397        }
398    }
399
400    /// The identifier of the background operation.
401    pub fn id(&self) -> TaskId {
402        self.token.id()
403    }
404
405    /// Requests cancellation of the background operation.
406    pub fn cancel(&self) {
407        self.token.cancel();
408    }
409
410    /// Returns `true` if cancellation has been requested.
411    pub fn is_cancelled(&self) -> bool {
412        self.token.is_cancelled()
413    }
414
415    /// Returns `true` if the background operation has completed.
416    pub fn is_finished(&self) -> bool {
417        self.finished.load(Ordering::SeqCst)
418    }
419
420    /// Borrows the inner [`TaskToken`].
421    pub fn token(&self) -> &TaskToken {
422        &self.token
423    }
424
425    /// Marks the handle as finished.
426    pub(crate) fn mark_finished(&self) {
427        self.finished.store(true, Ordering::SeqCst);
428    }
429}
430
431/// Cloneable, `Send + Sync` handle used by background threads to post
432/// [`TaskCommand`]s to the UI thread.
433///
434/// Obtained from [`crate::Ui::task_proxy`]. Clones share one bounded queue
435/// and one task-ID counter. Every successful post invokes the backend's wake
436/// hook (when the backend has one) so a blocked `wait_event` returns promptly
437/// and the UI thread can drain the queue.
438#[derive(Clone)]
439pub struct UiProxy {
440    inner: Arc<UiProxyInner>,
441}
442
443struct UiProxyInner {
444    sender: SyncSender<TaskCommand>,
445    wake: Option<Arc<dyn Fn() + Send + Sync>>,
446    next_task: AtomicU64,
447    capacity: usize,
448}
449
450impl fmt::Debug for UiProxy {
451    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
452        f.debug_struct("UiProxy")
453            .field("capacity", &self.inner.capacity)
454            .field("has_wake_hook", &self.inner.wake.is_some())
455            .finish()
456    }
457}
458
459impl UiProxy {
460    /// Creates a proxy plus the receiving end owned by the UI thread.
461    ///
462    /// `wake` is the backend's event-loop wake hook ([`crate::Backend::wake_handle`]);
463    /// `capacity` is clamped to at least 1.
464    pub(crate) fn new(
465        wake: Option<Arc<dyn Fn() + Send + Sync>>,
466        capacity: usize,
467    ) -> (Self, Receiver<TaskCommand>) {
468        let capacity = capacity.max(1);
469        let (sender, receiver) = sync_channel(capacity);
470        let proxy = Self {
471            inner: Arc::new(UiProxyInner {
472                sender,
473                wake,
474                next_task: AtomicU64::new(1),
475                capacity,
476            }),
477        };
478        (proxy, receiver)
479    }
480
481    /// Posts a command to the UI thread (lossy path).
482    ///
483    /// Returns [`TaskSendError::Full`] when the bounded queue is full and
484    /// [`TaskSendError::Closed`] after the owning `Ui` was dropped. This is
485    /// the right path for [`TaskClass::Lossy`] telemetry: on `Full`, skip the
486    /// sample — the next one supersedes it. Essential lifecycle tokens use
487    /// [`UiProxy::send_lossless`] instead.
488    pub fn post(&self, command: TaskCommand) -> Result<(), TaskSendError> {
489        match self.inner.sender.try_send(command) {
490            Ok(()) => {
491                self.wake();
492                Ok(())
493            }
494            Err(TrySendError::Full(_)) => Err(TaskSendError::Full),
495            Err(TrySendError::Disconnected(_)) => Err(TaskSendError::Closed),
496        }
497    }
498
499    /// Posts a command losslessly: waits (with backoff) until the bounded
500    /// queue has room.
501    ///
502    /// This is the guaranteed path for [`TaskClass::Lossless`] commands
503    /// (`Finished`, `Failed`, final transactional commits). [`UiProxy::post`]
504    /// is the lossy counterpart for coalescent telemetry.
505    ///
506    /// The wait is bounded by `timeout`, so a stalled UI thread can never
507    /// hang the worker forever:
508    ///
509    /// - `Ok(())` — the command is queued and will be applied in FIFO order
510    ///   (the backend wake hook is signalled, so a parked `wait_event`
511    ///   returns promptly);
512    /// - `Err(TaskSendError::Closed)` — the owning `Ui` is gone; stop the
513    ///   worker;
514    /// - `Err(TaskSendError::Full)` — `timeout` elapsed while the queue
515    ///   stayed full. The command was **not** queued, so the caller decides
516    ///   what to do (surface the error, retry with a longer timeout, or
517    ///   degrade explicitly); it is never reported as success and never
518    ///   silently dropped.
519    ///
520    /// ```
521    /// use native_gui_mock::MockBackend;
522    /// use native_gui_core::{TaskEvent, Ui, UiEvent};
523    /// use std::time::Duration;
524    ///
525    /// let mut ui = Ui::new(MockBackend::default());
526    /// let proxy = ui.task_proxy();
527    /// let token = proxy.start_task();
528    ///
529    /// let worker_proxy = proxy.clone();
530    /// let worker = std::thread::spawn(move || {
531    ///     // ... do the slow work ...
532    ///     worker_proxy
533    ///         .finish_lossless(&token, Duration::from_secs(5))
534    ///         .expect("the completion token must reach the UI thread");
535    /// });
536    /// worker.join().expect("worker thread");
537    ///
538    /// ui.drain_task_commands();
539    /// let event = ui.poll_event().expect("poll").expect("lifecycle event");
540    /// assert!(matches!(event, UiEvent::Task(TaskEvent::Finished { .. })));
541    /// ```
542    pub fn send_lossless(
543        &self,
544        command: TaskCommand,
545        timeout: Duration,
546    ) -> Result<(), TaskSendError> {
547        let deadline = Instant::now() + timeout;
548        let mut backoff = LOSSLESS_RETRY_BACKOFF_START;
549        let mut pending = command;
550        loop {
551            match self.inner.sender.try_send(pending) {
552                Ok(()) => {
553                    self.wake();
554                    return Ok(());
555                }
556                Err(TrySendError::Full(command)) => {
557                    if Instant::now() >= deadline {
558                        return Err(TaskSendError::Full);
559                    }
560                    pending = command;
561                    std::thread::sleep(backoff);
562                    backoff = (backoff * 2).min(LOSSLESS_RETRY_BACKOFF_MAX);
563                }
564                Err(TrySendError::Disconnected(_)) => return Err(TaskSendError::Closed),
565            }
566        }
567    }
568
569    /// Signals the backend wake hook (when the backend has one) so a parked
570    /// `wait_event` returns promptly and the UI thread drains the queue.
571    fn wake(&self) {
572        if let Some(wake) = &self.inner.wake {
573            wake();
574        }
575    }
576
577    /// Starts a new background operation and returns its cancellation token.
578    ///
579    /// IDs are unique per proxy; clone a token to the worker and keep one
580    /// clone on the UI thread for [`TaskToken::cancel`].
581    pub fn start_task(&self) -> TaskToken {
582        let id = TaskId(self.inner.next_task.fetch_add(1, Ordering::SeqCst));
583        TaskToken {
584            id,
585            cancelled: Arc::new(AtomicBool::new(false)),
586        }
587    }
588
589    /// The bounded capacity of this proxy's command queue.
590    pub fn capacity(&self) -> usize {
591        self.inner.capacity
592    }
593
594    /// Posts [`TaskCommand::SetText`].
595    pub fn set_text(
596        &self,
597        widget_id: WidgetId,
598        text: impl Into<String>,
599    ) -> Result<(), TaskSendError> {
600        self.post(TaskCommand::SetText {
601            widget_id,
602            text: text.into(),
603        })
604    }
605
606    /// Posts a collection replacement for a list widget.
607    pub fn set_data_list_items(
608        &self,
609        widget_id: WidgetId,
610        items: impl IntoIterator<Item = String>,
611    ) -> Result<(), TaskSendError> {
612        self.post(TaskCommand::SetDataListItems {
613            widget_id,
614            items: items.into_iter().collect(),
615        })
616    }
617
618    /// Posts a row-major collection replacement for a data grid.
619    pub fn set_data_grid_rows(
620        &self,
621        widget_id: WidgetId,
622        rows: impl IntoIterator<Item = Vec<String>>,
623    ) -> Result<(), TaskSendError> {
624        self.post(TaskCommand::SetDataGridRows {
625            widget_id,
626            rows: rows.into_iter().collect(),
627        })
628    }
629
630    /// Posts [`TaskCommand::SetValue`].
631    pub fn set_value(&self, widget_id: WidgetId, value: i32) -> Result<(), TaskSendError> {
632        self.post(TaskCommand::SetValue { widget_id, value })
633    }
634
635    /// Posts [`TaskCommand::SetChecked`].
636    pub fn set_checked(&self, widget_id: WidgetId, checked: bool) -> Result<(), TaskSendError> {
637        self.post(TaskCommand::SetChecked { widget_id, checked })
638    }
639
640    /// Posts [`TaskCommand::SetEnabled`].
641    pub fn set_enabled(&self, widget_id: WidgetId, enabled: bool) -> Result<(), TaskSendError> {
642        self.post(TaskCommand::SetEnabled { widget_id, enabled })
643    }
644
645    /// Posts [`TaskCommand::SetVisible`].
646    pub fn set_visible(&self, widget_id: WidgetId, visible: bool) -> Result<(), TaskSendError> {
647        self.post(TaskCommand::SetVisible { widget_id, visible })
648    }
649
650    /// Posts [`TaskCommand::Progress`] for the given task (lossy sample).
651    ///
652    /// Progress is coalescent telemetry: on [`TaskSendError::Full`] skip the
653    /// sample — the next one supersedes it. The completion token still
654    /// arrives through [`UiProxy::finish_lossless`].
655    pub fn progress(&self, token: &TaskToken, value: f64) -> Result<(), TaskSendError> {
656        self.post(TaskCommand::Progress {
657            task: token.id(),
658            value,
659        })
660    }
661
662    /// Posts [`TaskCommand::Finished`] for the given task (lossy path).
663    ///
664    /// Prefer [`UiProxy::finish_lossless`] in real workers: a completion
665    /// token dropped at queue capacity can strand the UI state machine.
666    pub fn finish(&self, token: &TaskToken) -> Result<(), TaskSendError> {
667        self.post(TaskCommand::Finished { task: token.id() })
668    }
669
670    /// Posts [`TaskCommand::Failed`] for the given task (lossy path).
671    ///
672    /// Prefer [`UiProxy::fail_lossless`] in real workers: an error token
673    /// dropped at queue capacity can strand the UI state machine.
674    pub fn fail(&self, token: &TaskToken, message: impl Into<String>) -> Result<(), TaskSendError> {
675        self.post(TaskCommand::Failed {
676            task: token.id(),
677            message: message.into(),
678        })
679    }
680
681    /// Posts [`TaskCommand::Finished`] losslessly (see
682    /// [`UiProxy::send_lossless`]).
683    pub fn finish_lossless(
684        &self,
685        token: &TaskToken,
686        timeout: Duration,
687    ) -> Result<(), TaskSendError> {
688        self.send_lossless(TaskCommand::Finished { task: token.id() }, timeout)
689    }
690
691    /// Posts [`TaskCommand::Failed`] losslessly (see
692    /// [`UiProxy::send_lossless`]).
693    pub fn fail_lossless(
694        &self,
695        token: &TaskToken,
696        message: impl Into<String>,
697        timeout: Duration,
698    ) -> Result<(), TaskSendError> {
699        self.send_lossless(
700            TaskCommand::Failed {
701                task: token.id(),
702                message: message.into(),
703            },
704            timeout,
705        )
706    }
707}
708
709#[cfg(test)]
710mod tests {
711    use super::*;
712
713    fn proxy(capacity: usize) -> (UiProxy, Receiver<TaskCommand>) {
714        UiProxy::new(None, capacity)
715    }
716
717    #[test]
718    fn task_ids_are_unique_and_monotonic() {
719        let (proxy, _receiver) = proxy(4);
720        let first = proxy.start_task();
721        let second = proxy.start_task();
722        let clone = proxy.clone();
723        let third = clone.start_task();
724
725        assert_eq!(first.id(), TaskId(1));
726        assert_eq!(second.id(), TaskId(2));
727        assert_eq!(third.id(), TaskId(3));
728        // Clones share the ID counter.
729        assert_ne!(first.id(), third.id());
730    }
731
732    #[test]
733    fn cancellation_flag_is_visible_across_clones() {
734        let (proxy, _receiver) = proxy(4);
735        let ui_side = proxy.start_task();
736        let worker_side = ui_side.clone();
737
738        assert!(!worker_side.is_cancelled());
739        ui_side.cancel();
740        assert!(worker_side.is_cancelled());
741        // Idempotent.
742        ui_side.cancel();
743        assert!(worker_side.is_cancelled());
744    }
745
746    #[test]
747    fn posts_fail_closed_after_receiver_drops() {
748        let (proxy, receiver) = proxy(4);
749        drop(receiver);
750        assert_eq!(
751            proxy.post(TaskCommand::Finished { task: TaskId(1) }),
752            Err(TaskSendError::Closed)
753        );
754        assert_eq!(
755            proxy.finish(&TaskToken {
756                id: TaskId(1),
757                cancelled: Arc::new(AtomicBool::new(false))
758            }),
759            Err(TaskSendError::Closed)
760        );
761    }
762
763    #[test]
764    fn queue_bound_rejects_then_recovers() {
765        let (proxy, receiver) = proxy(3);
766        assert_eq!(proxy.capacity(), 3);
767
768        for _ in 0..3 {
769            assert_eq!(proxy.set_value(WidgetId(1), 1), Ok(()));
770        }
771        assert_eq!(proxy.set_value(WidgetId(1), 1), Err(TaskSendError::Full));
772
773        // Draining one slot lets the next post through again.
774        let _ = receiver.try_recv().expect("queued command");
775        assert_eq!(proxy.set_value(WidgetId(1), 2), Ok(()));
776    }
777
778    #[test]
779    fn commands_are_received_in_fifo_order() {
780        let (proxy, receiver) = proxy(8);
781        let token = proxy.start_task();
782
783        proxy.set_text(WidgetId(1), "first").expect("post");
784        proxy.progress(&token, 50.0).expect("post");
785        proxy.set_text(WidgetId(1), "second").expect("post");
786
787        assert_eq!(
788            receiver.try_recv().expect("cmd"),
789            TaskCommand::SetText {
790                widget_id: WidgetId(1),
791                text: "first".to_owned()
792            }
793        );
794        assert_eq!(
795            receiver.try_recv().expect("cmd"),
796            TaskCommand::Progress {
797                task: token.id(),
798                value: 50.0
799            }
800        );
801        assert_eq!(
802            receiver.try_recv().expect("cmd"),
803            TaskCommand::SetText {
804                widget_id: WidgetId(1),
805                text: "second".to_owned()
806            }
807        );
808    }
809
810    #[test]
811    fn lifecycle_helpers_carry_the_task_id() {
812        let (proxy, receiver) = proxy(4);
813        let token = proxy.start_task();
814
815        proxy.finish(&token).expect("post");
816        proxy.fail(&token, "boom").expect("post");
817
818        assert_eq!(
819            receiver.try_recv().expect("cmd"),
820            TaskCommand::Finished { task: token.id() }
821        );
822        assert_eq!(
823            receiver.try_recv().expect("cmd"),
824            TaskCommand::Failed {
825                task: token.id(),
826                message: "boom".to_owned()
827            }
828        );
829    }
830
831    #[test]
832    fn proxy_and_token_are_send_and_sync() {
833        fn assert_send_sync<T: Send + Sync>() {}
834        assert_send_sync::<UiProxy>();
835        assert_send_sync::<TaskToken>();
836        assert_send_sync::<TaskSendError>();
837    }
838
839    #[test]
840    fn drain_report_totals_add_up() {
841        let report = TaskDrainReport {
842            applied: 3,
843            rejected: 2,
844        };
845        assert_eq!(report.total(), 5);
846    }
847
848    #[test]
849    fn command_class_taxonomy_matches_the_documented_split() {
850        let task = TaskId(1);
851        let lossless = [
852            TaskCommand::Finished { task },
853            TaskCommand::Failed {
854                task,
855                message: "boom".to_owned(),
856            },
857        ];
858        for command in lossless {
859            assert_eq!(command.class(), TaskClass::Lossless, "{command:?}");
860        }
861
862        let lossy = [
863            TaskCommand::SetDataListItems {
864                widget_id: WidgetId(1),
865                items: vec!["row".to_owned()],
866            },
867            TaskCommand::SetDataGridRows {
868                widget_id: WidgetId(1),
869                rows: vec![vec!["cell".to_owned()]],
870            },
871            TaskCommand::SetText {
872                widget_id: WidgetId(1),
873                text: "text".to_owned(),
874            },
875            TaskCommand::SetValue {
876                widget_id: WidgetId(1),
877                value: 1,
878            },
879            TaskCommand::SetChecked {
880                widget_id: WidgetId(1),
881                checked: true,
882            },
883            TaskCommand::SetEnabled {
884                widget_id: WidgetId(1),
885                enabled: true,
886            },
887            TaskCommand::SetVisible {
888                widget_id: WidgetId(1),
889                visible: false,
890            },
891            TaskCommand::Progress { task, value: 50.0 },
892        ];
893        for command in lossy {
894            assert_eq!(command.class(), TaskClass::Lossy, "{command:?}");
895        }
896    }
897
898    #[test]
899    fn lossless_send_waits_for_capacity_instead_of_dropping() {
900        let (proxy, receiver) = proxy(2);
901        proxy.set_value(WidgetId(1), 1).expect("fills slot 1");
902        proxy.set_value(WidgetId(1), 2).expect("fills slot 2");
903        assert_eq!(proxy.set_value(WidgetId(1), 3), Err(TaskSendError::Full));
904
905        let worker_proxy = proxy.clone();
906        let worker = std::thread::spawn(move || {
907            worker_proxy.send_lossless(
908                TaskCommand::Finished { task: TaskId(9) },
909                Duration::from_secs(5),
910            )
911        });
912
913        // The queue is saturated, so the lossless send must still be waiting.
914        std::thread::sleep(Duration::from_millis(20));
915        let _ = receiver.try_recv().expect("drained slot 1");
916        let _ = receiver.try_recv().expect("drained slot 2");
917        worker
918            .join()
919            .expect("worker thread")
920            .expect("lossless send must succeed once capacity frees up");
921
922        assert_eq!(
923            receiver.try_recv().expect("queued completion"),
924            TaskCommand::Finished { task: TaskId(9) },
925            "the lossless command is queued after the drained samples"
926        );
927    }
928
929    #[test]
930    fn lossless_send_times_out_without_silently_dropping() {
931        let (proxy, receiver) = proxy(1);
932        proxy.set_value(WidgetId(1), 1).expect("fills the queue");
933
934        let error = proxy
935            .send_lossless(TaskCommand::Finished { task: TaskId(9) }, Duration::ZERO)
936            .expect_err("a full queue with no slack must report Full");
937        assert_eq!(error, TaskSendError::Full);
938
939        // The command was not queued behind the blocked sample.
940        assert_eq!(
941            receiver.try_recv().expect("original sample"),
942            TaskCommand::SetValue {
943                widget_id: WidgetId(1),
944                value: 1
945            }
946        );
947        assert!(
948            receiver.try_recv().is_err(),
949            "a timed-out lossless send must not leave a partial post behind"
950        );
951
952        // With capacity, the same call succeeds immediately.
953        proxy
954            .send_lossless(TaskCommand::Finished { task: TaskId(10) }, Duration::ZERO)
955            .expect("zero timeout succeeds when there is room");
956        assert_eq!(
957            receiver.try_recv().expect("queued completion"),
958            TaskCommand::Finished { task: TaskId(10) }
959        );
960    }
961
962    #[test]
963    fn lossless_send_fails_fast_when_the_ui_is_gone() {
964        let (proxy, receiver) = proxy(1);
965        drop(receiver);
966        assert_eq!(
967            proxy.send_lossless(
968                TaskCommand::Finished { task: TaskId(1) },
969                Duration::from_secs(30)
970            ),
971            Err(TaskSendError::Closed),
972            "a closed channel must not wait out the timeout"
973        );
974    }
975
976    #[test]
977    fn task_handle_lifecycle_and_cancellation() {
978        let (proxy, _receiver) = proxy(4);
979        let token = proxy.start_task();
980        let handle = TaskHandle::new(token.clone());
981
982        assert_eq!(handle.id(), token.id());
983        assert!(!handle.is_cancelled());
984        assert!(!handle.is_finished());
985
986        handle.cancel();
987        assert!(handle.is_cancelled());
988        assert!(token.is_cancelled());
989
990        handle.mark_finished();
991        assert!(handle.is_finished());
992    }
993
994    #[test]
995    fn test_b1491_sleep_or_cancelled_completes_when_not_cancelled() {
996        let (proxy, _receiver) = proxy(4);
997        let token = proxy.start_task();
998        let start = Instant::now();
999        let ok = token.sleep_or_cancelled(Duration::from_millis(60));
1000        assert!(ok, "un-cancelled sleep should return true");
1001        assert!(start.elapsed() >= Duration::from_millis(50));
1002    }
1003
1004    #[test]
1005    fn test_b1491_sleep_or_cancelled_returns_immediately_if_already_cancelled() {
1006        let (proxy, _receiver) = proxy(4);
1007        let token = proxy.start_task();
1008        token.cancel();
1009        let start = Instant::now();
1010        let ok = token.sleep_or_cancelled(Duration::from_secs(10));
1011        assert!(!ok, "pre-cancelled sleep should return false");
1012        assert!(
1013            start.elapsed() < Duration::from_secs(1),
1014            "pre-cancelled sleep must return without waiting out the 10s sleep"
1015        );
1016    }
1017
1018    #[test]
1019    fn test_b1491_sleep_or_cancelled_awakens_early_on_cancellation() {
1020        let (proxy, _receiver) = proxy(4);
1021        let token = proxy.start_task();
1022        let cancel_token = token.clone();
1023
1024        let cancel_thread = std::thread::spawn(move || {
1025            std::thread::sleep(Duration::from_millis(40));
1026            cancel_token.cancel();
1027        });
1028
1029        let start = Instant::now();
1030        // Request a 5-second sleep; cancellation at 40ms must cut it short. The
1031        // bound sits well below the full sleep but leaves room for slow, shared
1032        // CI runners, where thread wake-ups can lag by hundreds of milliseconds.
1033        let ok = token.sleep_or_cancelled(Duration::from_secs(5));
1034        assert!(!ok, "sleep interrupted by cancel should return false");
1035        let elapsed = start.elapsed();
1036        assert!(
1037            elapsed < Duration::from_secs(2),
1038            "expected early cancellation awakening, took {elapsed:?}"
1039        );
1040        cancel_thread.join().unwrap();
1041    }
1042}