Skip to main content

brep_app/automation/
queue.rs

1//! The command queue: the channel between a host and the app.
2//!
3//! A host calls [`AutomationQueue::submit`] with an [`Envelope`] and gets a
4//! receiver for the [`Reply`]. The app drains the queue at three fixed points
5//! in the frame (§4.4): [`drain_input`](AutomationQueue::drain_input) in
6//! `raw_input_hook`, then [`drain_app`](AutomationQueue::drain_app) for
7//! `Phase::Mutate` at the top of `ui` and for `Phase::Read` at the bottom. A
8//! command waits in the queue until its phase comes round.
9//!
10//! A desktop window is not always drawn: a Wayland compositor sends no frame
11//! callbacks to a window on a hidden workspace, and winit then withholds
12//! `RedrawRequested` indefinitely. So no command waits for one. A submit calls
13//! the [waker](AutomationQueue::set_waker), which wakes the desktop event
14//! loop independently of egui's repaint bookkeeping, and the loop dispatches
15//! the queue's head with [`drain_frameless`](AutomationQueue::drain_frameless)
16//! (`desktop_loop`). What a command needs first is its [`Need`]: app state
17//! (dispatched at once), a current layout (dispatched at once while the last
18//! pass is current, else after one), or a pass of its own (input egui must
19//! apply, a capture of what a pass draws). For the last two the loop runs an
20//! egui pass itself, on demand, without presenting it
21//! ([`needs_pass`](AutomationQueue::needs_pass)); the pass drains the queue
22//! exactly as a drawn frame does, so the queue's order is kept.
23use crate::automation::command::{lookup, Ctx, Envelope, Handler, Notice, NoticeKind, Outcome, Phase, Reply};
24use crate::automation::pointer::Pointer;
25use std::collections::VecDeque;
26use std::sync::mpsc::{channel, Receiver, Sender};
27use std::sync::{Arc, Mutex};
28
29pub struct Pending {
30    pub envelope: Envelope,
31    pub reply: Sender<Reply>,
32    /// `web_time`: `std::time::Instant::now` panics on wasm32 (same type natively).
33    deadline: Option<web_time::Instant>,
34    /// Who sent it ([`AutomationQueue::submit_for`]): the queue keeps each
35    /// client's commands in order, not every client's in one order.
36    client: Option<u64>,
37}
38
39impl Pending {
40    fn expired(&self, frame: u64) -> bool {
41        if self.deadline.is_some_and(|d| web_time::Instant::now() >= d) {
42            let _ = self.reply.send(Reply::err(self.envelope.id, frame,
43                "host_deadline_expired: command expired before dispatch; no effects", vec![]));
44            true
45        } else { false }
46    }
47}
48
49struct Awaiting {
50    token: u64,
51    region: crate::automation::cmd_capture::Region,
52    document: Option<String>,
53    pending: Pending,
54}
55
56struct Polling {
57    pending: Pending,
58    phase: Phase,
59    poller: crate::automation::command::Poller,
60    /// The document handle the command was bound to by its context: the
61    /// eventual reply is tagged with that document's context, as an
62    /// immediate one is.
63    bound: Option<String>,
64}
65
66#[derive(Default)]
67struct Inner {
68    pending: VecDeque<Pending>,
69    awaiting: Vec<Awaiting>,
70    polling: Vec<Polling>,
71    notices: Vec<Notice>,
72    /// How many of `notices` have already ridden out on a command REPLY.
73    /// See [`Inner::reply_notices`].
74    notices_replied: usize,
75    pointer: Pointer,
76    next_token: u64,
77    frame: u64,
78    poisoned: Option<String>,
79    /// The document the last drawn frame showed: `(handle, committed revision)`
80    /// ([`AutomationQueue::publish_view`]), which a capture landing now is of.
81    view: Option<(String, u64)>,
82    /// When the last pass (drawn or on demand) published its layout.
83    layout_at: Option<web_time::Instant>,
84    /// Something may have changed the layout since that pass: a command that
85    /// writes, work that finished, a resize.
86    layout_dirty: bool,
87    /// The pass now running applied input: what the input changed is laid
88    /// out by the pass after it (egui draws once more after input), so this
89    /// pass's layout is not the current one for long.
90    input_this_pass: bool,
91}
92
93impl Inner {
94    /// The last pass's layout still stands ([`Need::Layout`]).
95    fn layout_current(&self) -> bool {
96        !self.layout_dirty && self.layout_at.is_some_and(|at| at.elapsed() < LAYOUT_FRESH)
97    }
98
99    /// What queued command `index` needs.
100    fn need_at(&self, index: usize) -> Need {
101        let p = &self.pending[index];
102        lookup(&p.envelope.cmd).map_or(Need::State, |spec| need(spec, &p.envelope.args))
103    }
104
105    /// Queued command `index` can be dispatched now, without a pass.
106    fn dispatchable(&self, index: usize) -> bool {
107        match self.need_at(index) {
108            Need::State => true,
109            Need::Layout => self.layout_current(),
110            Need::Pass => false,
111        }
112    }
113
114    /// Queued command `index` is next in its client's order: nothing queued
115    /// ahead of it is its own client's, or a client's the queue cannot tell
116    /// apart (`client: None`, ordered against everything). The head always is.
117    fn is_next(&self, index: usize) -> bool {
118        let Some(client) = self.pending[index].client else { return index == 0 };
119        self.pending.iter().take(index).all(|p| p.client.is_some_and(|other| other != client))
120    }
121
122    /// The first queued command that is next in its client's order and can
123    /// be dispatched without a pass: one client's command waiting for a pass
124    /// does not hold up another client's.
125    fn next_dispatchable(&self) -> Option<usize> {
126        (0..self.pending.len()).find(|&i| self.is_next(i) && self.dispatchable(i))
127    }
128
129    /// Some command that is next in its client's order waits for a pass.
130    fn waits_for_pass(&self) -> bool {
131        (0..self.pending.len()).any(|i| self.is_next(i) && !self.dispatchable(i))
132    }
133}
134
135/// Most notices kept. The app pushes one per toast whether or not a host is
136/// listening, so an ordinary session (the `automation` feature is on by
137/// default) must not grow a buffer for a reader that never arrives; the oldest
138/// go first, like the toast overlay's own cap.
139const MAX_NOTICES: usize = 256;
140
141impl Inner {
142    /// The notices a command REPLY carries: the ones that have not gone out on
143    /// an earlier reply.
144    ///
145    /// Two readers share this one buffer, and each must see every notice once.
146    /// A reply piggy-backs the new ones so an agent reads a refusal in the
147    /// answer to the call that caused it; the `notices` COMMAND drains the whole
148    /// buffer on its own cursor, so "every notice since the last drain" stays
149    /// true no matter how many other calls went by in between. Taking the buffer
150    /// for the replies — which is what this used to do — made `notices` report
151    /// whatever happened to arrive after the last call, which for a script that
152    /// waits before reading is nothing at all.
153    fn reply_notices(&mut self) -> Vec<Notice> {
154        let from = self.notices_replied.min(self.notices.len());
155        self.notices_replied = self.notices.len();
156        self.notices[from..].to_vec()
157    }
158}
159
160/// Wakes the thread that owns the app when work is queued.
161pub type Waker = Arc<dyn Fn() + Send + Sync>;
162
163/// What a command needs before it can be dispatched outside a drawn pass.
164#[derive(Debug, Clone, Copy, PartialEq, Eq)]
165pub enum Need {
166    /// Nothing: it reads or writes app state, which a pass has no part in.
167    State,
168    /// A current layout: what only a pass publishes (widget rects, the
169    /// viewport rect, focus, the dock's rendered panes). Dispatched at once
170    /// while the last pass is current ([`LAYOUT_FRESH`], nothing changed
171    /// since), else after one.
172    Layout,
173    /// A pass of its own: input egui must apply in a pass, or a capture of
174    /// what a pass draws.
175    Pass,
176}
177
178/// App commands that need a pass of their own: the captures (the image IS a
179/// pass), the presentation loan a capture series runs under, and `ping`, which
180/// answers from the next pass (the composite tools step the app with it).
181pub const PASS_BOUND: &[&str] = &["screenshot", "illustration_presentation", "ping"];
182
183/// App commands that read the layout a pass publishes. `state_get` and
184/// `state_schema` are here only for a name that is not a plain-state blob
185/// (`automation::state_blobs`): those are built from the app at dispatch.
186pub const LAYOUT_BOUND: &[&str] = &["hit_rects", "state_list", "state_get", "state_schema", "locate", "pick"];
187
188/// How long the last pass's layout stands for a layout read when nothing has
189/// changed since: one frame at 60 Hz, the age a drawn window's layout has.
190/// Older than that, time alone may have moved it (a toast expiring, the
191/// working indicator appearing), so the read gets a pass of its own.
192pub const LAYOUT_FRESH: std::time::Duration = std::time::Duration::from_millis(16);
193
194/// What `spec` called with `args` needs ([`Need`]).
195pub fn need(spec: &crate::automation::command::CommandSpec, args: &serde_json::Value) -> Need {
196    match spec.handler {
197        // A read-only input command (`pointer_state`, which `session_info`
198        // issues) emits no events and only reads the virtual pointer; every
199        // input queued before it has already been applied to that pointer.
200        Handler::Input(_) if spec.phase == Phase::Input && spec.annotations.read_only => Need::State,
201        Handler::Input(_) => Need::Pass,
202        Handler::App(_) if spec.phase == Phase::Input || PASS_BOUND.contains(&spec.name) => Need::Pass,
203        Handler::App(_) if matches!(spec.name, "state_get" | "state_schema") => {
204            let names = args.get("names").and_then(serde_json::Value::as_array);
205            let state = names.is_some_and(|names| {
206                names.iter().all(|n| n.as_str().is_some_and(crate::automation::state_blobs::is_state_blob))
207            });
208            if state { Need::State } else { Need::Layout }
209        }
210        Handler::App(_) if LAYOUT_BOUND.contains(&spec.name) => Need::Layout,
211        Handler::App(_) => Need::State,
212    }
213}
214
215/// What became of a command whose host stopped waiting for it
216/// ([`AutomationQueue::withdraw`]).
217#[derive(Debug, Clone, Copy, PartialEq, Eq)]
218pub enum Withdrawn {
219    /// It was still queued and has been removed: it never ran.
220    NotDispatched,
221    /// A handler accepted it (it is capturing or polling), or it already
222    /// answered: it may have had effects.
223    Accepted,
224}
225
226#[derive(Default)]
227pub struct AutomationQueue {
228    inner: Mutex<Inner>,
229    ctx: Mutex<Option<egui::Context>>,
230    waker: Mutex<Option<Waker>>,
231}
232
233/// Whether a handler's refusal is [`brep_render::engine_state::ASSEMBLY_SESSION_PENDING`].
234fn session_pending(error: &str) -> bool {
235    error.contains(brep_render::engine_state::ASSEMBLY_SESSION_PENDING)
236}
237
238/// How long an assembly action waits for its session copy before it answers
239/// the refusal after all (a runner that never hands one over).
240const SESSION_PENDING_LIMIT: std::time::Duration = std::time::Duration::from_secs(120);
241
242/// [`Outcome::Poll`] that runs `handler` again each frame while it answers
243/// [`session_pending`], and answers with its first other result. Only for a
244/// command bound to no document context (the active tab): a bound one is
245/// answered with the refusal, since its binding is checked once, at dispatch.
246fn retry_while_session_pending(handler: crate::automation::command::AppHandler, args: serde_json::Value) -> Outcome {
247    // web_time: the std clock panics in the browser, where this retry also runs.
248    let start = web_time::Instant::now();
249    Outcome::Poll(Box::new(move |ctx| {
250        let before = refused_counts(&ctx.app.docs);
251        let result = handler(ctx, args.clone());
252        let result = refused_by_lock(&ctx.app.docs, &before, result);
253        match result {
254            Err(error) if session_pending(&error) && start.elapsed() < SESSION_PENDING_LIMIT => None,
255            Ok(Outcome::Poll(_)) => Some(Err("a retried assembly action started polled work".into())),
256            other => Some(other),
257        }
258    }))
259}
260
261impl AutomationQueue {
262    pub fn new() -> Arc<Self> {
263        Arc::new(Self::default())
264    }
265
266    /// Give the queue the egui context so a submit can wake an idle frame loop.
267    pub fn attach(&self, ctx: &egui::Context) {
268        *self.ctx.lock().unwrap() = Some(ctx.clone());
269        if self.has_pending() { ctx.request_repaint(); }
270    }
271
272    /// Install the app thread's waker (the desktop event loop's proxy). Work
273    /// queued before it was installed is not stranded: the waker fires at once.
274    pub fn set_waker(&self, waker: Waker) {
275        *self.waker.lock().unwrap() = Some(waker.clone());
276        if self.has_pending() { waker(); }
277    }
278
279    fn wake(&self) {
280        let waker = self.waker.lock().unwrap().clone();
281        if let Some(waker) = waker { waker(); }
282        if let Some(ctx) = self.ctx.lock().unwrap().as_ref() {
283            ctx.request_repaint();
284        }
285    }
286
287    /// Enqueue a command. The reply arrives on the returned receiver once the
288    /// app has reached the command's phase (or at once, for an unknown command
289    /// or a poisoned session).
290    pub fn submit(&self, envelope: Envelope) -> Receiver<Reply> {
291        self.submit_before(envelope, None)
292    }
293
294    /// A deadline applies before dispatch, never to work already accepted by a handler.
295    pub fn submit_before(&self, envelope: Envelope, deadline: Option<web_time::Instant>) -> Receiver<Reply> {
296        self.submit_for(envelope, deadline, None)
297    }
298
299    /// [`submit_before`](Self::submit_before) for `client` (an MCP host's
300    /// script execution, say). Commands from one client keep their order; a
301    /// command may be dispatched ahead of commands that are queued only by
302    /// OTHER clients, so one client's command waiting for a pass does not
303    /// hold up another's. `None` orders it against every command, as before.
304    pub fn submit_for(&self, envelope: Envelope, deadline: Option<web_time::Instant>, client: Option<u64>) -> Receiver<Reply> {
305        let (tx, rx) = channel();
306        let mut inner = self.inner.lock().unwrap();
307        if let Some(why) = &inner.poisoned {
308            let _ = tx.send(Reply::err(envelope.id, inner.frame, format!("session poisoned: {why}"), vec![]));
309            return rx;
310        }
311        if lookup(&envelope.cmd).is_none() {
312            let _ = tx.send(Reply::err(envelope.id, inner.frame, format!("unknown command `{}`", envelope.cmd), vec![]));
313            return rx;
314        }
315        inner.pending.push_back(Pending { envelope, reply: tx, deadline, client });
316        // Notify only after the command is visible to the app thread: a wake
317        // that arrives first finds it queued.
318        drop(inner);
319        self.wake();
320        rx
321    }
322
323    /// The host stopped waiting for command `id`. A command still queued is
324    /// removed and answered as never dispatched; anything else was accepted.
325    pub fn withdraw(&self, id: u64) -> Withdrawn {
326        let mut inner = self.inner.lock().unwrap();
327        let frame = inner.frame;
328        if let Some(index) = inner.pending.iter().position(|p| p.envelope.id == id) {
329            let p = inner.pending.remove(index).expect("index from position");
330            let _ = p.reply.send(Reply::err(id, frame, "host_deadline_expired: command expired before dispatch; no effects", vec![]));
331            return Withdrawn::NotDispatched;
332        }
333        Withdrawn::Accepted
334    }
335
336    /// Whether [`drain_frameless`](Self::drain_frameless) has anything to do:
337    /// a head it can dispatch without a pass, or polled work.
338    pub fn has_frameless_work(&self) -> bool {
339        let inner = self.inner.lock().unwrap();
340        !inner.polling.is_empty() || inner.next_dispatchable().is_some()
341    }
342
343    /// Whether a command next in its client's order waits for a pass:
344    /// input, a capture, or a layout read with no current layout. The desktop
345    /// loop runs one on demand.
346    pub fn needs_pass(&self) -> bool {
347        self.inner.lock().unwrap().waits_for_pass()
348    }
349
350    /// The layout may have changed outside a command (a resize, finished
351    /// background work): the next layout read gets a pass.
352    pub fn mark_layout_dirty(&self) {
353        self.inner.lock().unwrap().layout_dirty = true;
354    }
355
356    /// A pass (drawn or on demand) has just published its layout and answered
357    /// its reads (`BrepApp::drain_reads`).
358    pub fn note_pass(&self) {
359        let mut inner = self.inner.lock().unwrap();
360        inner.layout_at = Some(web_time::Instant::now());
361        inner.layout_dirty = std::mem::take(&mut inner.input_this_pass);
362    }
363
364    /// Record something the session should know about — a toast the user would
365    /// have seen, a refusal, a panic. The app's own toast lane feeds this every
366    /// frame (`BrepApp::ui`), so `notices` reports what was on screen.
367    pub fn push_notice(&self, kind: NoticeKind, text: impl Into<String>) {
368        let mut inner = self.inner.lock().unwrap();
369        let frame = inner.frame;
370        inner.notices.push(Notice { kind, frame, text: text.into() });
371        let overflow = inner.notices.len().saturating_sub(MAX_NOTICES);
372        if overflow > 0 {
373            inner.notices.drain(0..overflow);
374            inner.notices_replied = inner.notices_replied.saturating_sub(overflow);
375        }
376    }
377
378    /// Drain for the `notices` COMMAND: everything since the last drain. The
379    /// reply cursor goes back to the start with them — the buffer is empty, so
380    /// the reply this drain rides out on carries nothing twice.
381    pub fn take_notices(&self) -> Vec<Notice> {
382        let mut inner = self.inner.lock().unwrap();
383        inner.notices_replied = 0;
384        std::mem::take(&mut inner.notices)
385    }
386
387    pub fn pointer(&self) -> Pointer {
388        self.inner.lock().unwrap().pointer.clone()
389    }
390
391    pub fn frame(&self) -> u64 {
392        self.inner.lock().unwrap().frame
393    }
394
395    pub fn has_pending(&self) -> bool {
396        let inner = self.inner.lock().unwrap();
397        !inner.pending.is_empty() || !inner.awaiting.is_empty() || !inner.polling.is_empty()
398    }
399
400    /// Whether a command has started work the queue is polling (see
401    /// `Outcome::Poll`): a host keeps stepping frames for it past its usual
402    /// frame budget, since the work is advancing, not stuck.
403    pub fn is_polling(&self, id: u64) -> bool {
404        self.inner.lock().unwrap().polling.iter().any(|p| p.pending.envelope.id == id)
405    }
406
407    /// Mark the session unusable (a panic unwound through the app). Every
408    /// pending and future command is answered with the reason.
409    pub fn poison(&self, why: impl Into<String>) {
410        let why = why.into();
411        let mut inner = self.inner.lock().unwrap();
412        inner.poisoned = Some(why.clone());
413        let frame = inner.frame;
414        for p in inner.pending.drain(..) {
415            let _ = p.reply.send(Reply::err(p.envelope.id, frame, format!("session poisoned: {why}"), vec![]));
416        }
417        for a in inner.awaiting.drain(..) {
418            let _ = a.pending.reply.send(Reply::err(a.pending.envelope.id, frame, format!("session poisoned: {why}"), vec![]));
419        }
420    }
421
422    pub fn is_poisoned(&self) -> bool {
423        self.inner.lock().unwrap().poisoned.is_some()
424    }
425
426    /// Phase 1 of the frame: apply input commands as `egui::Event`s and
427    /// complete captures whose `Event::Screenshot` arrived. `view` is the
428    /// viewport rect of the last frame (for `region: viewport` crops).
429    /// `ctx` is the app's: the pointer reads egui's clock from it (the
430    /// headless host leaves `raw.time` unset, and egui adds `predicted_dt`),
431    /// and a `click_gap` resets its click history.
432    pub fn drain_input(&self, raw: &mut egui::RawInput, frame: u64, ppp: f32, view: Option<egui::Rect>, ctx: &egui::Context) {
433        let mut inner = self.inner.lock().unwrap();
434        inner.frame = frame;
435        inner.pointer.now = raw.time.unwrap_or_else(|| ctx.input(|i| i.time) + f64::from(raw.predicted_dt));
436
437        // Screenshots that landed in this frame's input.
438        if !inner.awaiting.is_empty() {
439            let mut done = Vec::new();
440            for event in &raw.events {
441                if let egui::Event::Screenshot { user_data, image, .. } = event {
442                    let token = user_data.data.as_ref().and_then(|d| d.downcast_ref::<u64>()).copied();
443                    if let Some(token) = token {
444                        if let Some(pos) = inner.awaiting.iter().position(|a| a.token == token) {
445                            let a = inner.awaiting.remove(pos);
446                            done.push((a, image.clone()));
447                        }
448                    }
449                }
450            }
451            for (a, image) in done {
452                let notices = inner.reply_notices();
453                let shown = inner.view.clone();
454                // The image is of the frame drawn last: it shows `shown`. A
455                // capture asked for while another document was visible is
456                // refused rather than handed back as that document's picture.
457                let switched = match (&a.document, &shown) {
458                    (Some(asked), Some((drawn, _))) => asked != drawn,
459                    _ => false,
460                };
461                let result = if switched {
462                    Err("document_not_active: the visible document changed between the request and the capture".to_string())
463                } else {
464                    crate::automation::cmd_capture::encode_capture(&image, ppp, view, &a.region).map(|(mut json, png)| {
465                        if let Some((handle, revision)) = &shown {
466                            json["document"] = serde_json::json!({ "documentId": handle, "revision": revision.to_string() });
467                        }
468                        (json, png)
469                    })
470                };
471                let reply = match result {
472                    Ok((json, png)) => {
473                        let mut r = Reply::ok(a.pending.envelope.id, frame, json, notices);
474                        r.blob = Some(png);
475                        r
476                    }
477                    Err(e) => Reply::err(a.pending.envelope.id, frame, e, notices),
478                };
479                let _ = a.pending.reply.send(reply);
480            }
481        }
482
483        // Input-phase commands, in order.
484        let mut keep = VecDeque::new();
485        let mut events = Vec::new();
486        while let Some(p) = inner.pending.pop_front() {
487            if p.expired(frame) { continue; }
488            let Some(spec) = lookup(&p.envelope.cmd) else { continue };
489            match (&spec.handler, spec.phase) {
490                (Handler::Input(f), Phase::Input) => {
491                    let result = f(&mut inner.pointer, p.envelope.args.clone(), &mut events);
492                    let notices = inner.reply_notices();
493                    let reply = match result {
494                        Ok(v) => Reply::ok(p.envelope.id, frame, v, notices),
495                        Err(e) => Reply::err(p.envelope.id, frame, e, notices),
496                    };
497                    let _ = p.reply.send(reply);
498                }
499                _ => keep.push_back(p),
500            }
501        }
502        inner.pending = keep;
503        // A `click_gap` this frame: a fresh `PointerState` before the pass
504        // begins, so egui has no click to count the next one against. The
505        // pass builds on the state this replaces (`InputState::begin_pass`).
506        if std::mem::take(&mut inner.pointer.reset_clicks) {
507            ctx.input_mut(|i| i.pointer = egui::PointerState::default());
508        }
509        // The held modifiers are the SCRIPT's only while a script holds one.
510        // Writing them every pass replaced the user's real Shift/Ctrl/Cmd with
511        // "none" in every build that carries automation (the default native
512        // build and the browser's WebMCP host), so `InputState::modifiers`
513        // never saw a real modifier and Shift+drag box select never started.
514        // A script's release clears what it set, once.
515        let held = inner.pointer.egui_modifiers();
516        if held != egui::Modifiers::NONE {
517            raw.modifiers = held;
518            inner.pointer.modifiers_applied = true;
519        } else if std::mem::take(&mut inner.pointer.modifiers_applied) {
520            raw.modifiers = egui::Modifiers::NONE;
521        }
522        if let Some(platform) = inner.pointer.platform {
523            if ctx.os() != platform.os() {
524                ctx.set_os(platform.os());
525            }
526        }
527        inner.input_this_pass = !events.is_empty();
528        raw.events.extend(events);
529    }
530
531    /// Phases 2 and 3 of the frame. Runs every pending command registered for
532    /// `phase`, in order.
533    pub fn drain_app(&self, phase: Phase, ctx: &mut Ctx<'_>, frame: u64) {
534        let batch: Vec<Pending> = {
535            let mut inner = self.inner.lock().unwrap();
536            inner.frame = frame;
537            let mut keep = VecDeque::new();
538            let mut batch = Vec::new();
539            while let Some(p) = inner.pending.pop_front() {
540                match lookup(&p.envelope.cmd) {
541                    Some(spec) if spec.phase == phase => batch.push(p),
542                    _ => keep.push_back(p),
543                }
544            }
545            inner.pending = keep;
546            batch
547        };
548        for p in batch {
549            self.dispatch(p, phase, ctx, frame);
550        }
551        if self.poll(phase, ctx, frame) {
552            ctx.egui.request_repaint();
553        }
554    }
555
556    /// Dispatch without a pass (the desktop loop's service step): every
557    /// command that is next in its client's order and needs no pass, in
558    /// queue order. A client's commands stop at its first that needs a pass
559    /// ([`needs_pass`](Self::needs_pass), which the loop then runs); other
560    /// clients' go on. Then one poll of the work they started. Returns whether polled work is still
561    /// outstanding. Runs on the app's thread, so mutations stay sequential
562    /// with the UI's own writers.
563    pub fn drain_frameless(&self, ctx: &mut Ctx<'_>) -> bool {
564        let frame = self.frame();
565        loop {
566            let next = {
567                let mut inner = self.inner.lock().unwrap();
568                let ready = inner.next_dispatchable();
569                match ready.and_then(|i| lookup(&inner.pending[i].envelope.cmd).map(|spec| (i, spec))) {
570                    Some((index, spec)) => {
571                        let p = inner.pending.remove(index).expect("index from next_dispatchable");
572                        if let Handler::Input(f) = &spec.handler {
573                            // A read-only input command: answered here, as the
574                            // frame's input phase would answer it.
575                            if !p.expired(frame) {
576                                let mut events = Vec::new();
577                                let result = f(&mut inner.pointer, p.envelope.args.clone(), &mut events);
578                                debug_assert!(events.is_empty(), "{} is read-only but emitted input", spec.name);
579                                let notices = inner.reply_notices();
580                                let reply = match result {
581                                    Ok(v) => Reply::ok(p.envelope.id, frame, v, notices),
582                                    Err(e) => Reply::err(p.envelope.id, frame, e, notices),
583                                };
584                                let _ = p.reply.send(reply);
585                            }
586                            continue;
587                        }
588                        Some((p, spec.phase))
589                    }
590                    _ => None,
591                }
592            };
593            let Some((p, phase)) = next else { break };
594            self.dispatch(p, phase, ctx, frame);
595        }
596        let mutate = self.poll(Phase::Mutate, ctx, frame);
597        let read = self.poll(Phase::Read, ctx, frame);
598        mutate || read
599    }
600
601    /// Run one command's handler and answer (or park) it.
602    fn dispatch(&self, p: Pending, phase: Phase, ctx: &mut Ctx<'_>, frame: u64) {
603        if p.expired(frame) { return; }
604        let spec = lookup(&p.envelope.cmd).expect("checked at submit");
605        let Handler::App(f) = &spec.handler else { return };
606        if !spec.annotations.read_only {
607            // What it writes may move the layout: the next layout read waits
608            // for a pass.
609            self.mark_layout_dirty();
610        }
611        // A document context is checked HERE, on the frame thread, right
612        // before the handler: the only point atomic with the UI's own
613        // writers. It is stripped from the handler's arguments.
614        let (args, bound) = match bind_context(&ctx.app.docs, phase, &p.envelope.cmd, p.envelope.args.clone()) {
615            Ok(bound) => bound,
616            Err(e) => {
617                let mut inner = self.inner.lock().unwrap();
618                let notices = inner.reply_notices();
619                let _ = p.reply.send(Reply::err(p.envelope.id, frame, e, notices));
620                return;
621            }
622        };
623        let before = refused_counts(&ctx.app.docs);
624        let route = bound.as_ref().and_then(|b| b.route).map(|index| ctx.app.docs.route_begin(index));
625        let retry_args = args.clone();
626        let result = f(ctx, args);
627        if let Some(visible) = route {
628            ctx.app.docs.route_end(visible);
629        }
630        // An assembly action that found its main-side session still on the
631        // way from the background runner changed nothing: it is run again on
632        // later frames until the copy has landed, rather than answered with
633        // a refusal a script would have to retry itself.
634        let result = match result {
635            Err(error) if bound.is_none() && session_pending(&error) => Ok(retry_while_session_pending(*f, retry_args)),
636            other => other,
637        };
638        let result = refused_by_lock(&ctx.app.docs, &before, result);
639        let handle = bound.map(|b| b.handle);
640        let result = match &handle {
641            Some(handle) => tag_context(&ctx.app.docs, handle, result),
642            None => result,
643        };
644        let mut inner = self.inner.lock().unwrap();
645        answer(&mut inner, p, phase, frame, result, handle);
646    }
647
648    /// Work started earlier: one poll each, in this phase. Returns whether
649    /// any is still outstanding.
650    fn poll(&self, phase: Phase, ctx: &mut Ctx<'_>, frame: u64) -> bool {
651        let polling: Vec<Polling> = {
652            let mut inner = self.inner.lock().unwrap();
653            let (mine, rest) = std::mem::take(&mut inner.polling).into_iter().partition(|p| p.phase == phase);
654            inner.polling = rest;
655            mine
656        };
657        let mut still = false;
658        for mut entry in polling {
659            match (entry.poller)(ctx) {
660                None => {
661                    still = true;
662                    self.inner.lock().unwrap().polling.push(entry);
663                }
664                Some(result) => {
665                    // Finished work may have changed what a pass would show.
666                    self.mark_layout_dirty();
667                    let result = match &entry.bound {
668                        Some(handle) => tag_context(&ctx.app.docs, handle, result),
669                        None => result,
670                    };
671                    let mut inner = self.inner.lock().unwrap();
672                    answer(&mut inner, entry.pending, phase, frame, result, entry.bound);
673                    still |= !inner.polling.is_empty();
674                }
675            }
676        }
677        still
678    }
679
680    /// Record which document the frame just drawn shows (called at the end of
681    /// every app frame), so a capture is bound to what it pictures.
682    pub fn publish_view(&self, handle: &str, revision: u64) {
683        let mut inner = self.inner.lock().unwrap();
684        if inner.view.as_ref().is_none_or(|(h, r)| h != handle || *r != revision) {
685            inner.view = Some((handle.to_string(), revision));
686        }
687    }
688
689    /// Answer every capture still waiting for its image with `error` (an
690    /// on-demand pass could not draw it).
691    pub fn fail_captures(&self, error: &str) {
692        let mut inner = self.inner.lock().unwrap();
693        let frame = inner.frame;
694        for a in std::mem::take(&mut inner.awaiting) {
695            let notices = inner.reply_notices();
696            let _ = a.pending.reply.send(Reply::err(a.pending.envelope.id, frame, error.to_string(), notices));
697        }
698    }
699
700    /// A fresh token for a screenshot request.
701    pub fn next_token(&self) -> u64 {
702        let mut inner = self.inner.lock().unwrap();
703        inner.next_token += 1;
704        inner.next_token
705    }
706}
707
708/// The root `context` key of a command's arguments: which document the
709/// command is for and the committed revision its writer last saw
710/// (contract §3 `DocumentContext`). Optional — a command without one
711/// acts on the visible document as it always has.
712#[derive(serde::Deserialize)]
713#[serde(deny_unknown_fields, rename_all = "camelCase")]
714struct DocumentContext {
715    document_id: String,
716    expected_revision: String,
717}
718
719/// Commands that read or write only a document's ENGINE — its history, run,
720/// metadata, model and exports — and so may run on a background tab: the
721/// queue routes them there for the one handler call (`Documents::route_begin`)
722/// without touching what the user sees. Every other command acts on the
723/// visible document and refuses a background context (`document_not_active`).
724pub const ENGINE_ONLY: &[&str] = &[
725    "feature_stage",
726    "feature_stage_result",
727    "run_cancel",
728    "history_group_begin",
729    "history_group_end",
730    "feature_add_many",
731    "doc_import",
732    "doc_export",
733    "model_inspect",
734    "mass_properties",
735    "volume",
736    "weld_list",
737    "history_listing",
738    "frame_info",
739    "metadata_set",
740    "metadata_set_many",
741    "metadata_remove",
742];
743
744/// A command bound to a document by its context: the handle it named and,
745/// for an engine-only command addressed to a background tab, that tab.
746#[derive(Debug)]
747struct Bound {
748    handle: String,
749    route: Option<usize>,
750}
751
752/// Take `context` out of `args` and check it against the documents as they
753/// are now. Errors begin with the contract's stable code (`revision_conflict:
754/// …`), so a caller need not parse the prose.
755///
756/// An [`ENGINE_ONLY`] command may name a background tab and is routed there;
757/// any other command must name the visible one (`document_not_active`).
758/// While a Work part is edited in place every context refuses
759/// (`document_busy`): the command would write the hosted part, not the tab
760/// named. A Mutate-phase command requires the expected revision to be the
761/// current one; a Read-phase command only reports the current revision.
762fn bind_context(
763    docs: &crate::document::Documents,
764    phase: Phase,
765    cmd: &str,
766    mut args: serde_json::Value,
767) -> Result<(serde_json::Value, Option<Bound>), String> {
768    let Some(raw) = args.as_object_mut().and_then(|o| o.remove("context")) else {
769        return Ok((args, None));
770    };
771    // A command with no arguments still parses `{}` after the strip.
772    let context: DocumentContext = serde_json::from_value(raw)
773        .map_err(|e| format!("invalid_arguments: context must be {{documentId, expectedRevision}}: {e}"))?;
774    let expected = parse_revision(&context.expected_revision)?;
775    match crate::handles::parse("doc", &context.document_id) {
776        crate::handles::Parsed::Current => {}
777        crate::handles::Parsed::OtherEpoch => {
778            return Err("handle_epoch_mismatch: the document handle is from another run of the app".into())
779        }
780        crate::handles::Parsed::Malformed => return Err("invalid_arguments: documentId is not a document handle".into()),
781    }
782    let Some(index) = docs.index_of_handle(&context.document_id) else {
783        return Err("document_unknown: no open document has that handle (closed, or never opened)".into());
784    };
785    if docs.work_part_in_place() {
786        return Err("document_busy: a Work part is edited in place; a document command would write the part".into());
787    }
788    let route = if index == docs.active_index() {
789        None
790    } else if ENGINE_ONLY.contains(&cmd) {
791        Some(index)
792    } else {
793        return Err("document_not_active: this command acts on the visible document; activate the named one first".into());
794    };
795    let current = docs.get(index).map_or(0, |d| d.committed_revision());
796    if phase == Phase::Mutate && current != expected {
797        return Err(format!(
798            "revision_conflict: the document is at revision {current}, not {expected}; read it again before writing"
799        ));
800    }
801    Ok((args, Some(Bound { handle: context.document_id, route })))
802}
803
804/// A decimal unsigned 64-bit revision, canonical (no sign, no leading zero).
805fn parse_revision(text: &str) -> Result<u64, String> {
806    let canonical = text == "0" || (!text.is_empty() && !text.starts_with('0') && text.bytes().all(|b| b.is_ascii_digit()));
807    text.parse::<u64>()
808        .ok()
809        .filter(|_| canonical)
810        .ok_or_else(|| "invalid_arguments: expectedRevision must be a canonical unsigned decimal string".into())
811}
812
813/// A command that was bound to a document answers with that document's
814/// context as it stands after the handler: `{documentId, expectedRevision}` under the
815/// result's `context` key (an object result), so the writer's next
816/// expectation comes from the answer, not from a guess. A geometry run the
817/// handler started moves the revision again when it lands.
818fn tag_context(
819    docs: &crate::document::Documents,
820    handle: &str,
821    result: Result<Outcome, String>,
822) -> Result<Outcome, String> {
823    let context = docs.index_of_handle(handle).and_then(|i| docs.get(i)).map(|doc| {
824        serde_json::json!({ "documentId": handle, "expectedRevision": doc.committed_revision().to_string() })
825    });
826    let tag = |v: &mut serde_json::Value| {
827        if let (Some(object), Some(context)) = (v.as_object_mut(), context.clone()) {
828            object.insert("context".into(), context);
829        }
830    };
831    match result {
832        Ok(Outcome::Done(mut v)) => {
833            tag(&mut v);
834            Ok(Outcome::Done(v))
835        }
836        Ok(Outcome::Blob { mut json, bytes }) => {
837            tag(&mut json);
838            Ok(Outcome::Blob { json, bytes })
839        }
840        other => other,
841    }
842}
843
844/// Send (or park) one command's reply.
845fn answer(inner: &mut Inner, p: Pending, phase: Phase, frame: u64, result: Result<Outcome, String>, bound: Option<String>) {
846    match result {
847        Ok(Outcome::Done(v)) => {
848            let notices = inner.reply_notices();
849            let _ = p.reply.send(Reply::ok(p.envelope.id, frame, v, notices));
850        }
851        Ok(Outcome::Blob { json, bytes }) => {
852            let notices = inner.reply_notices();
853            let mut r = Reply::ok(p.envelope.id, frame, json, notices);
854            r.blob = Some(bytes);
855            let _ = p.reply.send(r);
856        }
857        // No reply yet — the capture answers when its image arrives, and
858        // takes the notices then (the cursor must not move here).
859        Ok(Outcome::AwaitScreenshot { token, region, document }) => {
860            inner.awaiting.push(Awaiting { token, region, document, pending: p });
861        }
862        Ok(Outcome::Poll(poller)) => inner.polling.push(Polling { pending: p, phase, poller, bound }),
863        Err(e) => {
864            let notices = inner.reply_notices();
865            let _ = p.reply.send(Reply::err(p.envelope.id, frame, e, notices));
866        }
867    }
868}
869
870/// Each open document's refused-edit count ([`crate::document::Document::access`]).
871fn refused_counts(docs: &crate::document::Documents) -> Vec<(u64, u64)> {
872    docs.iter().map(|d| (d.id(), d.engine.history.refused_user_edits())).collect()
873}
874
875/// A command that tried to change a read-only document (a PLM revision this
876/// user has not checked out, or a released one) did not change it — the
877/// document's history refused the write — so its reply is that refusal, not
878/// a success. A command that only reads, moves the camera, opens or closes a
879/// document refuses nothing and answers as it did.
880fn refused_by_lock(
881    docs: &crate::document::Documents,
882    before: &[(u64, u64)],
883    result: Result<Outcome, String>,
884) -> Result<Outcome, String> {
885    if result.is_err() {
886        return result;
887    }
888    for doc in docs.iter() {
889        let was = before.iter().find(|(id, _)| *id == doc.id()).map(|(_, n)| *n);
890        if was.is_some_and(|was| doc.engine.history.refused_user_edits() > was) {
891            if let crate::document::Access::ReadOnly { reason } = doc.access() {
892                return Err(format!("{} is read-only: {reason}", doc.title()));
893            }
894        }
895    }
896    result
897}
898