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