BREP_app 0.36.1

The next.BREP.io CAD application on the Rust B-rep kernel: an eframe (egui + wgpu) host that draws the brep-render 3D engine into an egui frame, native + wasm from one codebase.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
//! The remote GUI stream — `brep-app --stream ADDR`.
//!
//! The app runs with no window and no display: its egui passes are the ones
//! the desktop loop runs on demand (`on_demand`), on a wgpu device created
//! without a surface, drawn offscreen (`offscreen`) at the size and density
//! the remote page reports. Each drawn frame is cut into tiles; each client
//! is sent the tiles newer than what it holds (`encode`). The page's
//! input becomes the next pass's `RawInput` (`input`), ahead of the MCP
//! virtual pointer's (an agent on `--mcp` drives the same session).
//!
//! Passes run when something asks: input, egui's repaint requests (its
//! animations, `request_repaint_after`), the automation queue, background
//! work landing (the runner's reply waker). Never a fixed-rate spin.
pub mod encode;
pub mod input;
pub mod server;

use crate::app::BrepApp;
use eframe::egui_wgpu;
use std::path::PathBuf;
use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant};

/// The port `--stream` uses when the address names none.
pub const DEFAULT_PORT: u16 = 8770;
/// Passes run at most this often (input arriving faster is batched).
const PACE: Duration = Duration::from_millis(16);
/// The surface before any page has said its size (CSS pixels).
const DEFAULT_SURFACE: (f32, f32, f32) = (1400.0, 900.0, 1.0);

/// What `--stream` was given.
#[derive(Debug, Clone)]
pub struct StreamConfig {
    pub addr: String,
    pub token_file: Option<PathBuf>,
    pub origins: Vec<String>,
}

/// The address with the default host and port filled in.
pub fn resolve_addr(addr: &str) -> String {
    if addr.contains(':') {
        addr.to_string()
    } else if addr.parse::<u16>().is_ok() {
        format!("127.0.0.1:{addr}")
    } else {
        format!("{addr}:{DEFAULT_PORT}")
    }
}

/// Where the token is written unless `--stream-token-file` says.
pub fn default_token_file() -> PathBuf {
    crate::plm::config::app_config_dir().join("brep-stream-token")
}

/// Bind the listener and write the session token; before anything else, so
/// a port in use is a launch error.
pub fn bind(cfg: &StreamConfig) -> Result<(std::net::TcpListener, String, PathBuf), String> {
    let addr = resolve_addr(&cfg.addr);
    let listener = std::net::TcpListener::bind(&addr).map_err(|e| format!("cannot listen on {addr}: {e}"))?;
    let token = format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple());
    let path = cfg.token_file.clone().unwrap_or_else(default_token_file);
    write_private(&path, &token).map_err(|e| format!("token file {}: {e}", path.display()))?;
    Ok((listener, token, path))
}

fn write_private(path: &std::path::Path, text: &str) -> std::io::Result<()> {
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir)?;
    }
    let mut options = std::fs::OpenOptions::new();
    options.write(true).create(true).truncate(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(0o600);
    }
    use std::io::Write;
    options.open(path)?.write_all(text.as_bytes())
}

/// Wakes the host loop: input, a submit, a repaint request with its deadline.
#[derive(Default)]
struct Signal {
    state: Mutex<(bool, Option<Instant>)>,
    cond: Condvar,
}

impl Signal {
    fn wake(&self) {
        self.state.lock().unwrap_or_else(|p| p.into_inner()).0 = true;
        self.cond.notify_one();
    }

    fn repaint_at(&self, at: Instant) {
        let mut s = self.state.lock().unwrap_or_else(|p| p.into_inner());
        s.1 = Some(s.1.map_or(at, |t| t.min(at)));
        self.cond.notify_one();
    }

    /// Wait until woken, a requested repaint is due, or `until`; returns the
    /// repaint deadline taken (if due).
    fn wait(&self, until: Option<Instant>) -> Option<Instant> {
        let mut s = self.state.lock().unwrap_or_else(|p| p.into_inner());
        loop {
            let now = Instant::now();
            let due = [until, s.1].into_iter().flatten().min();
            if s.0 || due.is_some_and(|t| t <= now) {
                break;
            }
            s = match due {
                Some(t) => self.cond.wait_timeout(s, t - now).unwrap_or_else(|p| p.into_inner()).0,
                None => self.cond.wait(s).unwrap_or_else(|p| p.into_inner()),
            };
        }
        s.0 = false;
        s.1.take()
    }
}

/// A wgpu device and egui renderer with no surface.
fn headless_render_state() -> Result<egui_wgpu::RenderState, String> {
    use egui_wgpu::wgpu;
    let mut setup = egui_wgpu::WgpuSetupCreateNew::without_display_handle();
    setup.instance_descriptor.backends.remove(wgpu::Backends::BROWSER_WEBGPU);
    // A real GPU when there is one; a CPU rasteriser otherwise.
    setup.native_adapter_selector = Some(Arc::new(|adapters, _surface| {
        let rank = |a: &&wgpu::Adapter| match a.get_info().device_type {
            wgpu::DeviceType::DiscreteGpu => 0,
            wgpu::DeviceType::IntegratedGpu => 1,
            wgpu::DeviceType::Other | wgpu::DeviceType::VirtualGpu => 2,
            wgpu::DeviceType::Cpu => 3,
        };
        let mut ranked: Vec<&wgpu::Adapter> = adapters.iter().collect();
        ranked.sort_by_key(rank);
        ranked.first().map(|a| (*a).clone()).ok_or_else(|| "no graphics adapter".to_string())
    }));
    let setup = egui_wgpu::WgpuSetup::CreateNew(setup);
    let instance = pollster::block_on(setup.new_instance());
    let config = egui_wgpu::WgpuConfiguration { wgpu_setup: setup, ..Default::default() };
    pollster::block_on(egui_wgpu::RenderState::create(&config, &instance, None, egui_wgpu::RendererOptions::default()))
        .map_err(|e| format!("graphics device: {e}"))
}

/// What [`run`] serves: [`bind`]'s listener and token, and how the session ends.
pub struct Serve {
    pub listener: std::net::TcpListener,
    pub token: String,
    /// Where the token was written (named in the ready line, never the token).
    pub token_file: PathBuf,
    pub origins: Vec<String>,
    /// `--stream-until-stdin-closes`: end the session, as a closed app does,
    /// when standard input reaches its end: the launching program closed it
    /// or exited. A host that embeds the app (`BREP_stream_client`) uses it so
    /// the app never outlives it.
    pub until_stdin_closes: bool,
}

/// The line a launching program waits for on standard output, once the app
/// is built and the server accepts connections: `BREP-STREAM-READY` and a
/// JSON object (`v`, `addr`, `url`, `ws`, `token_file`). One line, flushed.
pub const READY_PREFIX: &str = "BREP-STREAM-READY ";

/// Run the app headless and serve it until it is closed (or, with
/// [`Serve::until_stdin_closes`], until standard input ends).
/// `create` is main.rs's app construction, shared with the desktop loop.
pub fn run(serve: Serve, create: crate::desktop_loop::Create<'_>) -> Result<(), String> {
    let Serve { listener, token, token_file, origins, until_stdin_closes } = serve;
    let addr = listener.local_addr().map_err(|e| format!("listener: {e}"))?;
    let signal = Arc::new(Signal::default());
    let waker: crate::desktop_loop::Waker = {
        let signal = signal.clone();
        Arc::new(move || signal.wake())
    };
    let render = headless_render_state()?;
    let ctx = egui::Context::default();
    {
        let signal = signal.clone();
        ctx.set_request_repaint_callback(move |info| signal.repaint_at(Instant::now() + info.delay));
    }
    brep_render::runner::set_reply_waker(Some(waker.clone()));
    let mut cc = eframe::CreationContext::_new_kittest(ctx.clone());
    cc.wgpu_render_state = Some(render.clone());
    let mut app = create(&cc, waker.clone())?;
    drop(cc);
    let queue = app.automation().clone();
    queue.set_scaled_capture(true);
    app.offer_exports_to_stream();

    let hub = server::Hub::new(token, origins, waker);
    let _server = server::start(listener, hub.clone())?;
    if until_stdin_closes {
        let hub = hub.clone();
        std::thread::Builder::new()
            .name("brep-stream-stdin".into())
            .spawn(move || {
                let _ = std::io::copy(&mut std::io::stdin().lock(), &mut std::io::sink());
                hub.stop();
            })
            .map_err(|e| format!("stdin watch: {e}"))?;
    }
    {
        use std::io::Write;
        let ready = serde_json::json!({
            "v": server::PROTOCOL,
            "addr": addr.to_string(),
            "url": format!("http://{addr}/stream/"),
            "ws": format!("ws://{addr}/stream/ws"),
            "token_file": token_file.display().to_string(),
        });
        let mut out = std::io::stdout().lock();
        let _ = writeln!(out, "{READY_PREFIX}{ready}");
        let _ = out.flush();
    }
    let mut host = Host::new(app_surface(DEFAULT_SURFACE, render.device.limits().max_texture_dimension_2d));
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| host.run(&mut app, &ctx, &render, &hub, &signal)));
    let result = match result {
        Ok(r) => r,
        Err(_) => {
            queue.poison("the app panicked");
            Err("the app panicked".to_string())
        }
    };
    eframe::App::on_exit(&mut app);
    hub.lock().stopping = true;
    result
}

/// `(w, h, dpr)` in CSS pixels, kept positive and within the device's
/// largest texture (`max_side` pixels; the frame is one texture).
fn app_surface((w, h, dpr): (f32, f32, f32), max_side: u32) -> (f32, f32, f32) {
    let dpr = if dpr.is_finite() { dpr.clamp(0.5, 4.0) } else { 1.0 };
    let most = (max_side.min(u32::from(u16::MAX)) as f32 / dpr).max(64.0);
    let side = |v: f32| if v.is_finite() { v.clamp(64.0, most) } else { 800.0 };
    (side(w), side(h), dpr)
}

struct Host {
    started: Instant,
    surface: (f32, f32, f32),
    input: input::InputState,
    /// Events waiting for the next pass (the page's, a capture's).
    events: Vec<egui::Event>,
    last_pass: Option<Instant>,
    /// A pass is owed at this time (a repaint request, pacing).
    next_pass: Option<Instant>,
    busy: bool,
    screen: encode::Screen,
    /// The frame changed since the last send round, or a client is owed one.
    send_owed: bool,
    cursor: Option<egui::CursorIcon>,
    ime_area: Option<egui::Rect>,
    /// The last pass's frame, drawn but not yet read back: it is finished
    /// after the next pass is submitted (so the rasteriser draws one frame
    /// while the host runs the next pass and encodes this one), or when no
    /// pass follows by the pacing deadline.
    pending: Option<Pending>,
    /// What the pages were last told (`doc`, `selection`, `agent`).
    told: Told,
}

/// The session state last sent to the pages, so only changes are sent.
#[derive(Default)]
struct Told {
    doc: Option<(u64, usize, (u64, u64), bool, u64)>,
    selection: Option<serde_json::Value>,
    /// [`crate::automation::queue::AutomationQueue::agent_input_passes`] last seen.
    agent_passes: u64,
    /// When the agent last drove input; the badge shows for [`AGENT_LINGER`] after.
    agent_at: Option<Instant>,
    agent_on: bool,
    /// Passes left in which the selection is rebuilt: input (the page's or
    /// the agent's) may resolve into a pick a pass or two after it lands.
    selection_passes: u8,
}

/// How long the "agent is driving" badge stays after the agent's last input.
const AGENT_LINGER: Duration = Duration::from_millis(1500);

struct Pending {
    drawn: crate::offscreen::Drawn,
    ppp: f32,
    view: Option<egui::Rect>,
    ran: Duration,
    submitted: Instant,
}

impl Host {
    fn new(surface: (f32, f32, f32)) -> Self {
        Host {
            started: Instant::now(),
            surface,
            input: input::InputState { focused: true, ..Default::default() },
            events: Vec::new(),
            last_pass: None,
            next_pass: Some(Instant::now()),
            busy: false,
            screen: encode::Screen::default(),
            send_owed: false,
            cursor: None,
            ime_area: None,
            pending: None,
            told: Told::default(),
        }
    }

    fn run(&mut self, app: &mut BrepApp, ctx: &egui::Context, render: &egui_wgpu::RenderState, hub: &server::Hub, signal: &Signal) -> Result<(), String> {
        let queue = app.automation().clone();
        loop {
            let mut until = self.next_pass;
            if self.busy {
                let paced = Instant::now() + PACE;
                until = Some(until.map_or(paced, |t| t.min(paced)));
            }
            if let Some(off) = self.told.agent_at.filter(|_| self.told.agent_on).map(|t| t + AGENT_LINGER) {
                until = Some(until.map_or(off, |t| t.min(off)));
            }
            if let Some(settle) = self.screen.settles_at().filter(|t| *t > Instant::now()) {
                until = Some(until.map_or(settle, |t| t.min(settle)));
            }
            if let Some(p) = &self.pending {
                // By the time the next pass could run, the frame is shown
                // whether or not one comes.
                let due = p.submitted + PACE;
                until = Some(until.map_or(due, |t| t.min(due)));
            }
            if let Some(due) = signal.wait(until) {
                self.next_pass = Some(self.next_pass.map_or(due, |t| t.min(due)));
            }
            let inbox = {
                let mut inner = hub.lock();
                if inner.stopping {
                    return Ok(());
                }
                std::mem::take(&mut inner.inbox)
            };
            let now = Instant::now();
            if let Some(surface) = inbox.resize {
                let surface = app_surface(surface, render.device.limits().max_texture_dimension_2d);
                if surface != self.surface {
                    self.surface = surface;
                    queue.mark_layout_dirty();
                    self.next_pass = Some(now);
                }
            }
            let zoom = ctx.zoom_factor();
            for msg in &inbox.input {
                self.input.events(msg, zoom, &mut self.events);
            }
            if inbox.joined || inbox.acked {
                self.send_owed = true;
            }
            if inbox.joined {
                // A page that joins is told the state as it is now.
                self.told = Told { agent_passes: self.told.agent_passes, agent_at: self.told.agent_at, ..Told::default() };
            }
            for path in &inbox.uploaded {
                app.open_uploaded_file(path);
                self.next_pass = Some(now);
            }
            let serviced = self.busy || queue.has_frameless_work();
            if serviced {
                self.busy = app.service_automation(ctx);
            }
            let owed = !self.events.is_empty()
                || self.next_pass.is_some_and(|t| t <= now)
                || queue.needs_pass()
                || app.spinning()
                || queue.wants_scaled_capture()
                // A page that joins (or comes back) sees the session as it is
                // now: passes are not drawn while nobody watches, so the last
                // frame may predate what an agent or background work did since.
                || inbox.joined;
            if owed {
                let ready = self.last_pass.is_none_or(|t| t.elapsed() >= PACE);
                if ready {
                    let input = !self.events.is_empty() || serviced;
                    if self.pass(app, ctx, render, hub)? {
                        return Ok(());
                    }
                    self.tell(app, hub, input);
                } else {
                    let at = self.last_pass.map(|t| t + PACE).unwrap_or(now);
                    self.next_pass = Some(self.next_pass.map_or(at, |t| t.min(at)));
                }
            }
            if !owed || self.pending.as_ref().is_some_and(|p| p.submitted.elapsed() >= PACE) {
                if let Some(p) = self.pending.take() {
                    self.finish(p, render, hub);
                }
            }
            if self.send_owed || self.screen.settles_at().is_some_and(|t| t <= Instant::now()) {
                self.send_round(hub);
            }
            self.tell_agent(hub);
        }
    }

    /// After a pass: offer new exports, and tell the pages what changed in
    /// the document and the selection. The document's key is a few integers;
    /// the selection is rebuilt only after a pass with input or automation
    /// work (what can change it), or for a page that just joined.
    fn tell(&mut self, app: &mut BrepApp, hub: &server::Hub, input: bool) {
        for path in app.take_offered_downloads() {
            hub.offer(path);
        }
        let key = app.stream_doc_key();
        let doc_moved = self.told.doc != Some(key);
        if doc_moved {
            self.told.doc = Some(key);
            let mut doc = app.stream_doc();
            doc["t"] = "doc".into();
            hub.to_all(doc);
        }
        let passes = app.automation().agent_input_passes();
        let agent_moved = passes != self.told.agent_passes;
        if agent_moved {
            self.told.agent_passes = passes;
            self.told.agent_at = Some(Instant::now());
        }
        if input || agent_moved || doc_moved {
            self.told.selection_passes = 3;
        }
        if self.told.selection_passes > 0 || self.told.selection.is_none() {
            self.told.selection_passes = self.told.selection_passes.saturating_sub(1);
            let selection = app.stream_selection();
            if self.told.selection.as_ref() != Some(&selection) {
                hub.to_all(serde_json::json!({"t": "selection", "selection": selection}));
                self.told.selection = Some(selection);
            }
        }
    }

    /// The "agent is driving" badge: on while the automation's input moved
    /// within [`AGENT_LINGER`].
    fn tell_agent(&mut self, hub: &server::Hub) {
        let on = self.told.agent_at.is_some_and(|t| t.elapsed() < AGENT_LINGER);
        if on != self.told.agent_on {
            self.told.agent_on = on;
            hub.to_all(serde_json::json!({"t": "agent", "on": on}));
        }
    }

    fn raw_input(&mut self, ctx: &egui::Context, render: &egui_wgpu::RenderState, scale: Option<f32>) -> egui::RawInput {
        let (w, h, dpr) = self.surface;
        let mut raw = egui::RawInput {
            screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(w, h) / ctx.zoom_factor())),
            max_texture_side: Some(render.device.limits().max_texture_dimension_2d as usize),
            time: Some(self.started.elapsed().as_secs_f64()),
            modifiers: self.input.mods,
            events: std::mem::take(&mut self.events),
            focused: self.input.focused,
            ..Default::default()
        };
        let root = raw.viewports.entry(egui::ViewportId::ROOT).or_default();
        root.native_pixels_per_point = Some(dpr * scale.unwrap_or(1.0));
        root.focused = Some(self.input.focused);
        root.inner_rect = raw.screen_rect;
        raw
    }

    /// One pass, its captures and its frame. Returns whether the app closed.
    fn pass(&mut self, app: &mut BrepApp, ctx: &egui::Context, render: &egui_wgpu::RenderState, hub: &server::Hub) -> Result<bool, String> {
        let queue = app.automation().clone();
        let scaled = queue.take_scaled_capture();
        let raw = self.raw_input(ctx, render, scaled.map(|(_, s)| s));
        self.last_pass = Some(Instant::now());
        self.next_pass = None;
        queue.set_pass_scale(scaled.map(|(_, s)| s));
        let started = Instant::now();
        let owned = crate::on_demand::run_owned(app, ctx, Some(render), raw);
        let ran = started.elapsed();
        queue.set_pass_scale(None);
        let crate::on_demand::OwnedPass { mut pass, platform_output, viewport_commands, repaint_delay } = owned;
        if repaint_delay != Duration::MAX {
            let at = Instant::now() + repaint_delay;
            self.next_pass = Some(self.next_pass.map_or(at, |t| t.min(at)));
        }
        let (size_px, clear) = crate::on_demand::capture_target(app, ctx, pass.pixels_per_point);
        let shapes = std::mem::take(&mut pass.shapes);
        if let Some((token, _)) = scaled {
            // Window-density captures asked for in a scaled pass wait for the next.
            for user_data in std::mem::take(&mut pass.captures) {
                ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(user_data));
            }
            match crate::offscreen::capture(render, ctx, shapes, pass.pixels_per_point, size_px, clear) {
                Ok(image) => self.events.extend(crate::on_demand::screenshot_events(vec![egui::UserData::new(token)], image)),
                Err(error) => queue.fail_capture(token, &error),
            }
            // The stream shows the next, unscaled, pass.
            self.next_pass = Some(Instant::now());
        } else {
            let viewers = !hub.lock().clients.is_empty();
            if viewers && pass.captures.is_empty() {
                let drawn = crate::offscreen::draw(render, ctx, shapes, pass.pixels_per_point, size_px, clear);
                let next = Pending { drawn, ppp: pass.pixels_per_point, view: app.view_rect(), ran, submitted: Instant::now() };
                if let Some(previous) = self.pending.replace(next) {
                    self.finish(previous, render, hub);
                }
            } else if viewers || !pass.captures.is_empty() {
                // A capture is drawn and answered now; a frame still in
                // flight is shown first.
                if let Some(previous) = self.pending.take() {
                    self.finish(previous, render, hub);
                }
                match crate::offscreen::capture(render, ctx, shapes, pass.pixels_per_point, size_px, clear) {
                    Ok(image) => {
                        if !pass.captures.is_empty() {
                            self.events.extend(crate::on_demand::screenshot_events(std::mem::take(&mut pass.captures), image.clone()));
                            self.next_pass = Some(Instant::now());
                        }
                        let mut rgba = Vec::with_capacity(image.pixels.len() * 4);
                        for p in &image.pixels {
                            rgba.extend_from_slice(&[p.r(), p.g(), p.b(), 255]);
                        }
                        self.take_frame(image.size[0] as u32, image.size[1] as u32, rgba, app.view_rect(), pass.pixels_per_point, hub);
                    }
                    Err(error) => {
                        log::error!("{error}");
                        queue.fail_captures(&error);
                    }
                }
            }
        }
        crate::offscreen::apply_texture_frees(render, &pass.textures_delta);
        self.platform(platform_output, ctx, hub);
        let mut closed = false;
        for (id, command) in viewport_commands {
            match command {
                egui::ViewportCommand::Close if id == egui::ViewportId::ROOT => closed = true,
                egui::ViewportCommand::Screenshot(user_data) => ctx.send_viewport_cmd_to(id, egui::ViewportCommand::Screenshot(user_data)),
                _ => {}
            }
        }
        Ok(closed)
    }

    /// Read back a drawn frame and take it.
    fn finish(&mut self, p: Pending, render: &egui_wgpu::RenderState, hub: &server::Hub) {
        let in_flight = p.submitted.elapsed();
        let waiting = Instant::now();
        match p.drawn.wait_rgba(render) {
            Ok((w, h, rgba)) => {
                let waited = waiting.elapsed();
                let comparing = Instant::now();
                self.take_frame(w, h, rgba, p.view, p.ppp, hub);
                if trace_on() {
                    eprintln!(
                        "[stream-pass] pass {} ms, drawn {} ms after submit (waited {} ms), read+compare {} ms ({w}x{h})",
                        p.ran.as_millis(),
                        (in_flight + waited).as_millis(),
                        waited.as_millis(),
                        comparing.elapsed().as_millis()
                    );
                }
            }
            Err(error) => log::error!("stream frame: {error}"),
        }
    }

    fn take_frame(&mut self, w: u32, h: u32, rgba: Vec<u8>, view: Option<egui::Rect>, ppp: f32, hub: &server::Hub) {
        let view = view.map(|r| {
            let px = |v: f32, max: u32| ((v * ppp).round().max(0.0) as u32).min(max);
            [px(r.min.x, w), px(r.min.y, h), px(r.max.x, w), px(r.max.y, h)]
        });
        if self.screen.update(w, h, rgba, view, Instant::now()) > 0 {
            self.send_owed = true;
        }
        *hub.surface.lock().unwrap() = (w, h, ppp);
    }

    /// Plan each client's frame, encode the tiles they need (once each,
    /// shared), and hand the frames to the sockets.
    fn send_round(&mut self, hub: &server::Hub) {
        self.send_owed = false;
        if !self.screen.has_frame() {
            return;
        }
        let now = Instant::now();
        let mut plans = Vec::new();
        {
            let mut inner = hub.lock();
            for (id, client) in inner.clients.iter_mut() {
                if !client.can_take_frame() {
                    // Skipped: its ack wakes the loop for the next round.
                    continue;
                }
                let (keyframe, tiles) = client.held.plan(&self.screen, now, client.slow());
                if tiles.is_empty() {
                    continue;
                }
                client.sent_seq = client.sent_seq.wrapping_add(1);
                plans.push((*id, client.sent_seq, keyframe, client.quality(), tiles));
            }
        }
        if plans.is_empty() {
            return;
        }
        let mut wanted: Vec<(usize, u8, u8)> = plans.iter().flat_map(|p| p.4.iter().map(move |(i, c)| (*i, *c, if *c == encode::CODEC_JPEG { p.3 } else { 0 }))).collect();
        wanted.sort_unstable();
        wanted.dedup();
        let planned = now.elapsed();
        let encoded = encode_all(&self.screen, &wanted);
        let encoded_at = now.elapsed();
        let mut inner = hub.lock();
        for (id, seq, keyframe, quality, tiles) in plans {
            let Some(client) = inner.clients.get_mut(&id) else { continue };
            let parts: Vec<(usize, u8, Arc<Vec<u8>>)> = tiles
                .iter()
                .filter_map(|(i, c)| {
                    let q = if *c == encode::CODEC_JPEG { quality } else { 0 };
                    encoded.get(&(*i, *c, q)).map(|b| (*i, *c, b.clone()))
                })
                .collect();
            client.send_frame(encode::frame_message(&self.screen, seq, keyframe, &parts));
        }
        if trace_on() {
            let bytes: usize = encoded.values().map(|b| b.len()).sum();
            eprintln!(
                "[stream] {} tiles, {} bytes; plan {} ms, encode {} ms, total {} ms",
                encoded.len(),
                bytes,
                planned.as_millis(),
                (encoded_at - planned).as_millis(),
                now.elapsed().as_millis()
            );
        }
    }

    fn platform(&mut self, output: egui::PlatformOutput, ctx: &egui::Context, hub: &server::Hub) {
        if self.cursor != Some(output.cursor_icon) {
            self.cursor = Some(output.cursor_icon);
            hub.to_controller(serde_json::json!({"t": "cursor", "css": input::css_cursor(output.cursor_icon)}));
        }
        for command in output.commands {
            match command {
                egui::OutputCommand::CopyText(text) => hub.to_controller(serde_json::json!({"t": "clipboard", "s": text})),
                egui::OutputCommand::OpenUrl(open) => hub.to_controller(serde_json::json!({"t": "open_url", "url": open.url, "new_tab": open.new_tab})),
                egui::OutputCommand::CopyImage(_) => {}
            }
        }
        let area = output.ime.map(|ime| ime.cursor_rect);
        if area != self.ime_area {
            self.ime_area = area;
            let zoom = ctx.zoom_factor();
            let value = match area {
                Some(r) => serde_json::json!({"t": "ime_area", "x": r.min.x * zoom, "y": r.min.y * zoom, "w": r.width() * zoom, "h": r.height() * zoom}),
                None => serde_json::json!({"t": "ime_area"}),
            };
            hub.to_controller(value);
        }
    }
}

/// Encode `wanted` `(tile, codec, quality)` on a few threads.
fn encode_all(screen: &encode::Screen, wanted: &[(usize, u8, u8)]) -> std::collections::HashMap<(usize, u8, u8), Arc<Vec<u8>>> {
    let threads = std::thread::available_parallelism().map_or(2, |n| n.get()).clamp(1, 4);
    let chunk = wanted.len().div_ceil(threads).max(1);
    if trace_on() {
        return encode_all_traced(screen, wanted, chunk);
    }
    std::thread::scope(|scope| {
        let handles: Vec<_> = wanted
            .chunks(chunk)
            .map(|part| scope.spawn(move || part.iter().map(|&(i, c, q)| ((i, c, q), Arc::new(screen.encode(i, c, q)))).collect::<Vec<_>>()))
            .collect();
        handles.into_iter().flat_map(|h| h.join().unwrap_or_default()).collect()
    })
}

/// [`encode_all`] under `BREP_STREAM_TRACE=1`: a round over 100 ms reports,
/// per worker, when it started and finished, its CPU time and run-queue wait
/// (`/proc/thread-self/schedstat`), and its slowest tile; a round over 1 s
/// also writes that tile's RGBA to `BREP_STREAM_TRACE_DIR` (when set).
fn encode_all_traced(screen: &encode::Screen, wanted: &[(usize, u8, u8)], chunk: usize) -> std::collections::HashMap<(usize, u8, u8), Arc<Vec<u8>>> {
    start_heartbeat();
    let spawned = Instant::now();
    std::thread::scope(|scope| {
        let handles: Vec<_> = wanted
            .chunks(chunk)
            .map(|part| {
                scope.spawn(move || {
                    let started = spawned.elapsed();
                    let sched0 = schedstat();
                    let mut slowest = (Duration::ZERO, (0usize, 0u8, 0u8));
                    let out = part
                        .iter()
                        .map(|&(i, c, q)| {
                            let t = Instant::now();
                            let bytes = Arc::new(screen.encode(i, c, q));
                            let took = t.elapsed();
                            if took > slowest.0 {
                                slowest = (took, (i, c, q));
                            }
                            ((i, c, q), bytes)
                        })
                        .collect::<Vec<_>>();
                    let sched1 = schedstat();
                    let cpu_wait = (sched1.0.saturating_sub(sched0.0) / 1_000_000, sched1.1.saturating_sub(sched0.1) / 1_000_000);
                    (out, started, spawned.elapsed(), cpu_wait, slowest)
                })
            })
            .collect();
        let mut all = std::collections::HashMap::new();
        let mut report = Vec::new();
        let mut worst = (Duration::ZERO, (0usize, 0u8, 0u8));
        for h in handles {
            if let Ok((out, started, ended, (cpu, wait), slowest)) = h.join() {
                let (i, c, q) = slowest.1;
                let (_, _, w, h) = screen.rect(i);
                report.push(format!(
                    "{} tiles started {} ms done {} ms cpu {} ms runq {} ms, slowest tile {} {}x{} codec {} q {} {} ms",
                    out.len(),
                    started.as_millis(),
                    ended.as_millis(),
                    cpu,
                    wait,
                    i,
                    w,
                    h,
                    c,
                    q,
                    slowest.0.as_millis()
                ));
                if slowest.0 > worst.0 {
                    worst = slowest;
                }
                all.extend(out);
            }
        }
        let total = spawned.elapsed();
        if total > Duration::from_millis(100) {
            eprintln!("[stream-encode-slow] {} ms, {} tiles over {} threads: {}", total.as_millis(), wanted.len(), report.len(), report.join("; "));
        }
        if total > Duration::from_secs(1) {
            if let Some(dir) = std::env::var_os("BREP_STREAM_TRACE_DIR") {
                let (i, c, q) = worst.1;
                let (x, y, w, h) = screen.rect(i);
                let stride = (screen.w * 4) as usize;
                let mut rgba = Vec::with_capacity((w * h * 4) as usize);
                for row in y..y + h {
                    let a = row as usize * stride + x as usize * 4;
                    rgba.extend_from_slice(&screen.rgba[a..a + w as usize * 4]);
                }
                let name = format!("slow-tile-{}-{w}x{h}-codec{c}-q{q}-{}ms.rgba", std::process::id(), worst.0.as_millis());
                let path = PathBuf::from(dir).join(&name);
                match std::fs::write(&path, &rgba) {
                    Ok(()) => eprintln!("[stream-encode-slow] slowest tile written to {}", path.display()),
                    Err(e) => eprintln!("[stream-encode-slow] could not write {}: {e}", path.display()),
                }
            }
        }
        all
    })
}

/// This thread's (CPU ns, run-queue wait ns); zeros where unreadable.
fn schedstat() -> (u64, u64) {
    let text = std::fs::read_to_string("/proc/thread-self/schedstat").unwrap_or_default();
    let mut it = text.split_whitespace().map(|v| v.parse::<u64>().unwrap_or(0));
    (it.next().unwrap_or(0), it.next().unwrap_or(0))
}

/// Under the trace: a thread that wakes every 10 ms and reports when it woke
/// more than 500 ms late (a whole-process or host stall, not stream code).
fn start_heartbeat() {
    static STARTED: std::sync::Once = std::sync::Once::new();
    STARTED.call_once(|| {
        let _ = std::thread::Builder::new().name("stream-heartbeat".into()).spawn(|| loop {
            let t = Instant::now();
            std::thread::sleep(Duration::from_millis(10));
            let late = t.elapsed().saturating_sub(Duration::from_millis(10));
            if late > Duration::from_millis(500) {
                let unix = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0.0, |d| d.as_secs_f64());
                eprintln!("[stream-heartbeat] woke {} ms late (unix {unix:.1})", late.as_millis());
            }
        });
    });
}

/// `BREP_STREAM_TRACE=1`: report each send round on stderr.
fn trace_on() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| std::env::var_os("BREP_STREAM_TRACE").is_some_and(|v| v == "1"))
}