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