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