plushie 0.7.0

Desktop GUI framework for Rust
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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
//! Side effects returned from [`App::update`](crate::App::update).
//!
//! Commands are data, not closures (except `Async` and `Stream`).
//! This makes them testable: you can assert which commands an
//! update call returns without executing them.
//!
//! Operation types ([`WindowOp`], [`ImageOp`], [`EffectRequest`], etc.)
//! are defined in [`plushie_core::ops`] and re-exported here.

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;

use parking_lot::Mutex;
use serde_json::Value;

use crate::event::Event;

// Re-export all operation types from plushie-core.
pub use plushie_core::ops::*;

/// A boxed async closure that produces a result.
///
/// The closure is called once to produce a future. The future resolves
/// to `Ok(value)` or `Err(value)`, delivered as
/// [`AsyncEvent`](crate::event::AsyncEvent).
pub type AsyncTaskFn =
    Box<dyn FnOnce() -> Pin<Box<dyn Future<Output = Result<Value, Value>> + Send>> + Send>;

/// A boxed streaming async closure. Receives a [`StreamEmitter`] to push
/// intermediate values as [`StreamEvent`](crate::event::StreamEvent)s;
/// returns a final [`AsyncEvent`](crate::event::AsyncEvent) when the
/// future resolves.
pub type StreamTaskFn = Box<
    dyn FnOnce(StreamEmitter) -> Pin<Box<dyn Future<Output = Result<Value, Value>> + Send>> + Send,
>;

/// A cloneable sink for pushing values from a streaming task.
///
/// Runtime-specific sinks are installed when the command begins
/// executing. Until then (and in test mode), emits are buffered
/// locally and drained by the runner.
///
/// The sink closure runs outside the internal lock, so panicking
/// in the closure does not poison the emitter. A consequence is
/// that if a sink closure invokes `emit` reentrantly (directly or
/// indirectly through another clone of this emitter on the same
/// thread), the reentrant call sees a placeholder no-op closure
/// and silently drops the value. Sinks should not call `emit` on
/// the same emitter while delivering a value.
#[derive(Clone)]
pub struct StreamEmitter {
    tag: String,
    inner: Arc<Mutex<StreamEmitterInner>>,
}

enum StreamEmitterInner {
    /// Values accumulated before a runtime sink is attached.
    Buffer(Vec<Value>),
    /// Values routed through the runtime sink.
    Sink(Box<dyn FnMut(String, Value) + Send>),
}

impl StreamEmitter {
    /// Create an emitter backed by an in-memory buffer. Used by test
    /// runners and as the default until a runtime installs a sink.
    pub fn buffered(tag: &str) -> Self {
        Self {
            tag: tag.to_string(),
            inner: Arc::new(Mutex::new(StreamEmitterInner::Buffer(Vec::new()))),
        }
    }

    /// Replace the underlying delivery mechanism with a sink closure.
    /// Any buffered values are flushed through the new sink in order.
    pub fn attach_sink(&self, mut sink: Box<dyn FnMut(String, Value) + Send>) {
        // Take ownership of the buffered values without holding the
        // lock during user code. Drain-then-call: a panic in the
        // sink closure cannot poison the lock (parking_lot has no
        // poison surface) or strand other clones of the emitter.
        let buffered: Vec<Value> = {
            let mut guard = self.inner.lock();
            match &mut *guard {
                StreamEmitterInner::Buffer(values) => std::mem::take(values),
                StreamEmitterInner::Sink(_) => Vec::new(),
            }
        };
        for v in buffered {
            sink(self.tag.clone(), v);
        }
        let mut guard = self.inner.lock();
        *guard = StreamEmitterInner::Sink(sink);
    }

    /// Drain buffered values. Only meaningful when the emitter is
    /// still in buffer mode; returns empty otherwise.
    pub fn drain_buffer(&self) -> Vec<Value> {
        let mut guard = self.inner.lock();
        match &mut *guard {
            StreamEmitterInner::Buffer(v) => std::mem::take(v),
            StreamEmitterInner::Sink(_) => Vec::new(),
        }
    }

    /// The tag this emitter is bound to.
    pub fn tag(&self) -> &str {
        &self.tag
    }

    /// Emit an intermediate value to the runtime. Delivered as
    /// [`StreamEvent`](crate::event::StreamEvent) with this emitter's
    /// tag.
    pub fn emit(&self, value: impl Into<Value>) {
        let value = value.into();
        // Buffer mode: push under the lock and return.
        // Sink mode: swap the sink out, release the lock, invoke,
        // then put it back. Drain-then-call keeps the sink call out
        // of the critical section: a panic in the sink unwinds past
        // the (already released) lock instead of poisoning it, and
        // re-entrant emits from clones don't deadlock.
        let sink = {
            let mut guard = self.inner.lock();
            match &mut *guard {
                StreamEmitterInner::Buffer(buf) => {
                    buf.push(value);
                    return;
                }
                StreamEmitterInner::Sink(_) => {
                    let placeholder: Box<dyn FnMut(String, Value) + Send> = Box::new(|_, _| {});
                    match std::mem::replace(&mut *guard, StreamEmitterInner::Sink(placeholder)) {
                        StreamEmitterInner::Sink(s) => s,
                        StreamEmitterInner::Buffer(_) => unreachable!(),
                    }
                }
            }
        };

        // Carry the sink through a Drop guard so an unwind through
        // the sink call still reinstalls it for cloned emitters.
        // Without this the placeholder above would silently swallow
        // future values from any other clone.
        struct Restore<'a> {
            inner: &'a Mutex<StreamEmitterInner>,
            sink: Option<Box<dyn FnMut(String, Value) + Send>>,
        }
        impl Drop for Restore<'_> {
            fn drop(&mut self) {
                if let Some(sink) = self.sink.take() {
                    let mut guard = self.inner.lock();
                    *guard = StreamEmitterInner::Sink(sink);
                }
            }
        }

        let mut restore = Restore {
            inner: &self.inner,
            sink: Some(sink),
        };
        // Call through the option. On panic, Drop sees Some(sink)
        // and reinstalls it. The explicit Drop at end of scope
        // performs the same reinstall on the success path.
        if let Some(sink) = restore.sink.as_mut() {
            sink(self.tag.clone(), value);
        }
    }

    /// Emit a typed widget event, encoding it to the wire format first.
    /// The tag used is the emitter's tag; the event's family is not
    /// inspected.
    pub fn emit_event(&self, event: impl plushie_core::types::WidgetEventEncode) {
        let (_family, value) = event.to_wire();
        self.emit(Value::from(value));
    }
}

impl std::fmt::Debug for StreamEmitter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StreamEmitter")
            .field("tag", &self.tag)
            .finish()
    }
}

// ---------------------------------------------------------------------------
// Command
// ---------------------------------------------------------------------------

/// A side effect returned from the update function.
///
/// Every operation has a builder method for ergonomic construction
/// (focus, scroll, window ops/queries, effects, images, pane grid,
/// system, async tasks, etc.).
///
/// Commands that go to the renderer are wrapped in
/// [`Command::Renderer`]. SDK-local commands (async tasks, timers)
/// are handled in-process and never reach the renderer.
#[non_exhaustive]
pub enum Command {
    /// No side effect.
    None,
    /// Execute multiple commands.
    Batch(Vec<Command>),
    /// Exit the application.
    Exit,

    // -- SDK-local (never sent to renderer) --
    /// Run an async task. Result delivered as
    /// [`AsyncEvent`](crate::event::AsyncEvent).
    Async {
        /// Tag correlating the delivered result with this command.
        tag: String,
        /// Boxed future factory that produces the task output.
        task: AsyncTaskFn,
    },
    /// Run a streaming async task. Intermediate emits deliver as
    /// [`StreamEvent`](crate::event::StreamEvent); the final result
    /// delivers as [`AsyncEvent`](crate::event::AsyncEvent).
    Stream {
        /// Tag correlating stream emits and the final result.
        tag: String,
        /// Boxed stream factory.
        task: StreamTaskFn,
    },
    /// Cancel a running async task or stream by tag.
    Cancel {
        /// Tag of the task or stream to cancel.
        tag: String,
    },
    /// Deliver an event after a delay.
    SendAfter {
        /// Delay before the event is dispatched.
        delay: Duration,
        /// Event to dispatch.
        event: Box<Event>,
    },

    // -- Renderer operations (typed, zero-overhead in direct mode) --
    /// An operation for the renderer to execute.
    Renderer(RendererOp),
}

impl std::fmt::Debug for Command {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::None => write!(f, "None"),
            Self::Batch(cmds) => f.debug_tuple("Batch").field(cmds).finish(),
            Self::Exit => write!(f, "Exit"),
            Self::Async { tag, .. } => f.debug_struct("Async").field("tag", tag).finish(),
            Self::Stream { tag, .. } => f.debug_struct("Stream").field("tag", tag).finish(),
            Self::Cancel { tag } => f.debug_struct("Cancel").field("tag", tag).finish(),
            Self::SendAfter { delay, .. } => {
                f.debug_struct("SendAfter").field("delay", delay).finish()
            }
            Self::Renderer(op) => f.debug_tuple("Renderer").field(op).finish(),
        }
    }
}

// ---------------------------------------------------------------------------
// Builder helpers
// ---------------------------------------------------------------------------

/// Panic if a raw RGBA pixel buffer does not match `width * height * 4`.
///
/// Mirrors the pixel-buffer precondition enforced by the other host
/// SDKs (Python's `ValueError`, Ruby's `ArgumentError`). The renderer
/// would otherwise interpret out-of-range bytes as image content,
/// producing garbled output with no clear error origin.
fn assert_pixel_buffer_size(handle: &str, width: u32, height: u32, actual: usize) {
    let expected = (width as usize)
        .checked_mul(height as usize)
        .and_then(|n| n.checked_mul(4))
        .unwrap_or(usize::MAX);
    assert!(
        actual == expected,
        "create_image_rgba / update_image_rgba: pixel buffer for {handle:?} has {actual} bytes, \
         expected {expected} (width={width} height={height} channels=4)",
    );
}

// ---------------------------------------------------------------------------
// Builder methods
// ---------------------------------------------------------------------------

impl Command {
    /// A no-op command.
    pub fn none() -> Self {
        Self::None
    }

    /// Execute multiple commands together.
    pub fn batch(cmds: impl IntoIterator<Item = Command>) -> Self {
        Self::Batch(cmds.into_iter().collect())
    }

    /// Exit the application.
    pub fn exit() -> Self {
        Self::Exit
    }

    /// Deliver an event after a delay.
    pub fn send_after(delay: Duration, event: Event) -> Self {
        Self::SendAfter {
            delay,
            event: Box::new(event),
        }
    }

    /// Deliver an event through the normal update pipeline as soon
    /// as possible. Equivalent to
    /// [`send_after`](Self::send_after) with a zero delay, but named
    /// to make the intent clear at the call site.
    ///
    /// Useful for lifting a locally-derived value back into the MVU
    /// loop, e.g. kicking off a follow-up update after computing a
    /// value in the current `update`:
    ///
    /// ```no_run
    /// use plushie::prelude::*;
    /// use plushie::event::WidgetEvent;
    /// use serde_json::Value;
    ///
    /// let _ = Command::dispatch(Event::Widget(WidgetEvent {
    ///     event_type: EventType::Click,
    ///     scoped_id: ScopedId::new("next", vec![], None),
    ///     value: Value::Null,
    /// }));
    /// ```
    pub fn dispatch(event: Event) -> Self {
        Self::send_after(Duration::ZERO, event)
    }

    /// Run an async task. The result is delivered as
    /// [`AsyncEvent`](crate::event::AsyncEvent).
    ///
    /// ```no_run
    /// use plushie::command::Command;
    /// use serde_json::{json, Value};
    ///
    /// async fn fetch_text(_url: &str) -> Result<String, String> { Ok(String::new()) }
    ///
    /// let _ = Command::task("fetch", || async {
    ///     let data: Result<Value, Value> = fetch_text("https://api.example.com/data")
    ///         .await
    ///         .map(|t| json!(t))
    ///         .map_err(|e| json!(e));
    ///     data
    /// });
    /// ```
    ///
    /// # Delivery contract
    ///
    /// For every `task` the MVU loop sees exactly one of:
    ///
    /// - `AsyncEvent(Ok(value))` when the future resolves successfully.
    /// - `AsyncEvent(Err(value))` when the future resolves to `Err`,
    ///   or when it panics (the runner and
    ///   [`TestSession`](crate::test::TestSession) wrap the future
    ///   in a panic guard that converts panics to
    ///   `Err(json!({"error": "panic", "message": ...}))` instead of
    ///   unwinding).
    /// - Nothing at all if the task is cancelled via
    ///   [`Command::cancel`] with the same `tag` before it completes.
    ///
    /// # Errors
    ///
    /// Errors are not returned from this constructor; they are
    /// delivered asynchronously as `AsyncEvent(Err(value))` via the
    /// MVU loop. The inner future's `Err` payload becomes the event's
    /// error value verbatim. Panics inside the future are converted
    /// into an error event with the shape
    /// `{"error": "panic", "message": ...}` rather than unwinding the
    /// runtime.
    pub fn task<F, Fut>(tag: &str, f: F) -> Self
    where
        F: FnOnce() -> Fut + Send + 'static,
        Fut: Future<Output = Result<Value, Value>> + Send + 'static,
    {
        Self::Async {
            tag: tag.to_string(),
            task: Box::new(move || Box::pin(f())),
        }
    }

    /// Cancel a running async task or stream by tag.
    ///
    /// # Semantics
    ///
    /// Cancellation is best-effort:
    ///
    /// - If a task with `tag` is still queued (has not started
    ///   running), it is dropped without running and no
    ///   `AsyncEvent`/`StreamEvent` is delivered.
    /// - If a task with `tag` is already in flight, the runner
    ///   aborts it where possible. The task's result is discarded
    ///   and no `AsyncEvent` is delivered. A panic racing
    ///   cancellation is swallowed.
    /// - If no task with `tag` exists, the command is a no-op.
    ///
    /// Tags are how `Command::task`, `Command::stream`, and
    /// `Command::cancel` rendezvous. Reusing a tag while an earlier
    /// task is still in flight replaces the earlier task (the
    /// runner cancels it on the author's behalf).
    ///
    /// # Mode-specific notes
    ///
    /// - **Direct mode** calls `iced::task::Handle::abort`. iced
    ///   *detaches* the future from the executor rather than
    ///   force-dropping it; a future awaiting a non-cancelable
    ///   inner future may continue to run to completion with its
    ///   result discarded. No `AsyncEvent` is delivered regardless.
    /// - **Wire mode** calls `tokio::task::JoinHandle::abort`,
    ///   which schedules a cancellation at the next await point;
    ///   the result is discarded when the task eventually yields.
    /// - **TestSession** runs async tasks inline on a fresh
    ///   current-thread runtime, so cancellation during dispatch is
    ///   a no-op unless the task has yielded back to the scheduler.
    pub fn cancel(tag: &str) -> Self {
        Self::Cancel {
            tag: tag.to_string(),
        }
    }

    /// Run a streaming async task. Intermediate emits deliver as
    /// [`StreamEvent`](crate::event::StreamEvent)s; the final future
    /// result delivers as [`AsyncEvent`](crate::event::AsyncEvent).
    ///
    /// The task receives a cloneable [`StreamEmitter`] it can pass
    /// around to produce values over time:
    ///
    /// ```no_run
    /// use plushie::command::Command;
    /// use serde_json::{json, Value};
    ///
    /// async fn fetch_lines() -> Result<Vec<Value>, Value> { Ok(vec![]) }
    ///
    /// let _ = Command::stream("import", |emitter| async move {
    ///     for line in fetch_lines().await? {
    ///         emitter.emit(line);
    ///     }
    ///     Ok::<_, Value>(json!({"done": true}))
    /// });
    /// ```
    ///
    /// Cancel via [`Command::cancel`] with the same tag.
    pub fn stream<F, Fut>(tag: &str, f: F) -> Self
    where
        F: FnOnce(StreamEmitter) -> Fut + Send + 'static,
        Fut: Future<Output = Result<Value, Value>> + Send + 'static,
    {
        Self::Stream {
            tag: tag.to_string(),
            task: Box::new(move |emitter| Box::pin(f(emitter))),
        }
    }

    // -- Focus --

    /// Move keyboard focus to the widget with the given ID.
    pub fn focus(id: &str) -> Self {
        Self::Renderer(RendererOp::Command {
            id: id.to_string(),
            family: "focus".to_string(),
            value: Value::Null,
        })
    }

    /// Move keyboard focus to the next focusable widget.
    pub fn focus_next() -> Self {
        Self::Renderer(RendererOp::FocusNext)
    }

    /// Move keyboard focus to the previous focusable widget.
    pub fn focus_previous() -> Self {
        Self::Renderer(RendererOp::FocusPrevious)
    }

    /// Move keyboard focus to the next focusable widget within the
    /// subtree rooted at the given widget ID. Focus wraps within the
    /// scope rather than walking out into siblings.
    ///
    /// Use this for scoped keyboard navigation: a menu, a pane grid,
    /// or anywhere you need a contained Tab cycle. For modal focus
    /// traps, set `a11y.modal = true` on the container; the fork
    /// auto-traps focus at modal boundaries without needing this
    /// command.
    pub fn focus_next_within(scope: &str) -> Self {
        Self::Renderer(RendererOp::FocusNextWithin {
            scope: scope.to_string(),
        })
    }

    /// Move keyboard focus to the previous focusable widget within
    /// the given scope. See [`focus_next_within`](Command::focus_next_within).
    pub fn focus_previous_within(scope: &str) -> Self {
        Self::Renderer(RendererOp::FocusPreviousWithin {
            scope: scope.to_string(),
        })
    }

    // -- Text cursor --

    /// Select all text in a text input or editor.
    pub fn select_all(target: &str) -> Self {
        Self::Renderer(RendererOp::Command {
            id: target.to_string(),
            family: "select_all".to_string(),
            value: Value::Null,
        })
    }

    /// Move the cursor to the front of a text input or editor.
    pub fn move_cursor_to_front(target: &str) -> Self {
        Self::Renderer(RendererOp::Command {
            id: target.to_string(),
            family: "move_cursor_to_front".to_string(),
            value: Value::Null,
        })
    }

    /// Move the cursor to the end of a text input or editor.
    pub fn move_cursor_to_end(target: &str) -> Self {
        Self::Renderer(RendererOp::Command {
            id: target.to_string(),
            family: "move_cursor_to_end".to_string(),
            value: Value::Null,
        })
    }

    /// Move the cursor to a specific position in a text input.
    pub fn move_cursor_to(target: &str, position: usize) -> Self {
        Self::Renderer(RendererOp::Command {
            id: target.to_string(),
            family: "move_cursor_to".to_string(),
            value: serde_json::json!({"position": position}),
        })
    }

    /// Select a range of text in a text input.
    pub fn select_range(target: &str, start: usize, end: usize) -> Self {
        Self::Renderer(RendererOp::Command {
            id: target.to_string(),
            family: "select_range".to_string(),
            value: serde_json::json!({"start": start, "end": end}),
        })
    }

    // -- Scroll --

    /// Scroll a scrollable widget to an absolute position.
    pub fn scroll_to(target: &str, x: f32, y: f32) -> Self {
        Self::Renderer(RendererOp::Command {
            id: target.to_string(),
            family: "scroll_to".to_string(),
            value: serde_json::json!({"x": x, "y": y}),
        })
    }

    /// Scroll a scrollable widget by a relative offset.
    pub fn scroll_by(target: &str, x: f32, y: f32) -> Self {
        Self::Renderer(RendererOp::Command {
            id: target.to_string(),
            family: "scroll_by".to_string(),
            value: serde_json::json!({"x": x, "y": y}),
        })
    }

    /// Snap a scrollable widget to a position (no animation).
    pub fn snap_to(target: &str, x: f32, y: f32) -> Self {
        Self::Renderer(RendererOp::Command {
            id: target.to_string(),
            family: "snap_to".to_string(),
            value: serde_json::json!({"x": x, "y": y}),
        })
    }

    /// Snap a scrollable widget to the end of its content.
    pub fn snap_to_end(target: &str) -> Self {
        Self::Renderer(RendererOp::Command {
            id: target.to_string(),
            family: "snap_to_end".to_string(),
            value: Value::Null,
        })
    }

    // -- Window --

    /// Close the window with the given ID.
    pub fn close_window(id: &str) -> Self {
        Self::Renderer(RendererOp::Window(WindowOp::Close(id.to_string())))
    }

    /// Resize a window to the given dimensions in logical pixels.
    pub fn resize_window(id: &str, width: f32, height: f32) -> Self {
        Self::Renderer(RendererOp::Window(WindowOp::Resize {
            window_id: id.to_string(),
            width,
            height,
        }))
    }

    /// Move a window to the given position in logical pixels.
    pub fn move_window(id: &str, x: f32, y: f32) -> Self {
        Self::Renderer(RendererOp::Window(WindowOp::Move {
            window_id: id.to_string(),
            x,
            y,
        }))
    }

    /// Maximize a window.
    pub fn maximize_window(id: &str) -> Self {
        Self::Renderer(RendererOp::Window(WindowOp::Maximize {
            window_id: id.to_string(),
            maximized: true,
        }))
    }

    /// Restore a window from maximized to its previous size.
    pub fn unmaximize_window(id: &str) -> Self {
        Self::Renderer(RendererOp::Window(WindowOp::Maximize {
            window_id: id.to_string(),
            maximized: false,
        }))
    }

    /// Minimize a window.
    pub fn minimize_window(id: &str) -> Self {
        Self::Renderer(RendererOp::Window(WindowOp::Minimize {
            window_id: id.to_string(),
            minimized: true,
        }))
    }

    /// Restore a minimized window.
    pub fn unminimize_window(id: &str) -> Self {
        Self::Renderer(RendererOp::Window(WindowOp::Minimize {
            window_id: id.to_string(),
            minimized: false,
        }))
    }

    /// Set the window display mode.
    pub fn set_window_mode(id: &str, mode: WindowMode) -> Self {
        Self::Renderer(RendererOp::Window(WindowOp::SetMode {
            window_id: id.to_string(),
            mode,
        }))
    }

    /// Toggle a window between maximized and restored states.
    pub fn toggle_maximize(id: &str) -> Self {
        Self::Renderer(RendererOp::Window(WindowOp::ToggleMaximize(id.to_string())))
    }

    /// Toggle window decorations (title bar, borders).
    pub fn toggle_decorations(id: &str) -> Self {
        Self::Renderer(RendererOp::Window(WindowOp::ToggleDecorations(
            id.to_string(),
        )))
    }

    /// Bring a window to the front and give it input focus.
    pub fn focus_window(id: &str) -> Self {
        Self::Renderer(RendererOp::Window(WindowOp::FocusWindow(id.to_string())))
    }

    /// Set the window stacking level.
    pub fn set_window_level(id: &str, level: WindowLevel) -> Self {
        Self::Renderer(RendererOp::Window(WindowOp::SetLevel {
            window_id: id.to_string(),
            level,
        }))
    }

    /// Begin an interactive window drag.
    pub fn drag_window(id: &str) -> Self {
        Self::Renderer(RendererOp::Window(WindowOp::DragWindow(id.to_string())))
    }

    /// Begin an interactive window resize from the given direction.
    pub fn drag_resize_window(id: &str, direction: &str) -> Self {
        Self::Renderer(RendererOp::Window(WindowOp::DragResize {
            window_id: id.to_string(),
            direction: direction.to_string(),
        }))
    }

    /// Request user attention (taskbar flash or similar).
    pub fn request_attention(id: &str, urgency: Option<NotificationUrgency>) -> Self {
        Self::Renderer(RendererOp::Window(WindowOp::RequestAttention {
            window_id: id.to_string(),
            urgency,
        }))
    }

    /// Take a screenshot of a window. Result delivered as a system event.
    pub fn screenshot(window_id: &str, tag: &str) -> Self {
        Self::Renderer(RendererOp::Window(WindowOp::Screenshot {
            window_id: window_id.to_string(),
            tag: tag.to_string(),
        }))
    }

    /// Set whether a window is user-resizable.
    pub fn set_resizable(id: &str, resizable: bool) -> Self {
        Self::Renderer(RendererOp::Window(WindowOp::SetResizable {
            window_id: id.to_string(),
            resizable,
        }))
    }

    /// Set the minimum window size.
    pub fn set_min_size(id: &str, width: f32, height: f32) -> Self {
        Self::Renderer(RendererOp::Window(WindowOp::SetMinSize {
            window_id: id.to_string(),
            width,
            height,
        }))
    }

    /// Set the maximum window size.
    pub fn set_max_size(id: &str, width: f32, height: f32) -> Self {
        Self::Renderer(RendererOp::Window(WindowOp::SetMaxSize {
            window_id: id.to_string(),
            width,
            height,
        }))
    }

    /// Allow mouse events to pass through a window.
    pub fn enable_mouse_passthrough(id: &str) -> Self {
        Self::Renderer(RendererOp::Window(WindowOp::EnableMousePassthrough(
            id.to_string(),
        )))
    }

    /// Stop mouse events from passing through a window.
    pub fn disable_mouse_passthrough(id: &str) -> Self {
        Self::Renderer(RendererOp::Window(WindowOp::DisableMousePassthrough(
            id.to_string(),
        )))
    }

    /// Show the native system menu for a window.
    pub fn show_system_menu(id: &str) -> Self {
        Self::Renderer(RendererOp::Window(WindowOp::ShowSystemMenu(id.to_string())))
    }

    /// Set the window icon from raw RGBA pixel data.
    pub fn set_icon(id: &str, rgba_data: Vec<u8>, width: u32, height: u32) -> Self {
        Self::Renderer(RendererOp::Window(WindowOp::SetIcon {
            window_id: id.to_string(),
            data: rgba_data,
            width,
            height,
        }))
    }

    /// Set window resize increment constraints.
    pub fn set_resize_increments(id: &str, width: f32, height: f32) -> Self {
        Self::Renderer(RendererOp::Window(WindowOp::SetResizeIncrements {
            window_id: id.to_string(),
            width,
            height,
        }))
    }

    // -- Window queries --
    //
    // Results are delivered as `Event::System(SystemEvent)` with the
    // tag you provide, allowing correlation in your update function.

    /// Query the size of a window.
    pub fn window_size(window_id: &str, tag: &str) -> Self {
        Self::Renderer(RendererOp::WindowQuery(WindowQuery::GetSize {
            window_id: window_id.to_string(),
            tag: tag.to_string(),
        }))
    }

    /// Query the position of a window.
    pub fn window_position(window_id: &str, tag: &str) -> Self {
        Self::Renderer(RendererOp::WindowQuery(WindowQuery::GetPosition {
            window_id: window_id.to_string(),
            tag: tag.to_string(),
        }))
    }

    /// Query whether a window is maximized.
    pub fn is_maximized(window_id: &str, tag: &str) -> Self {
        Self::Renderer(RendererOp::WindowQuery(WindowQuery::IsMaximized {
            window_id: window_id.to_string(),
            tag: tag.to_string(),
        }))
    }

    /// Query whether a window is minimized.
    pub fn is_minimized(window_id: &str, tag: &str) -> Self {
        Self::Renderer(RendererOp::WindowQuery(WindowQuery::IsMinimized {
            window_id: window_id.to_string(),
            tag: tag.to_string(),
        }))
    }

    /// Query the display mode of a window.
    pub fn window_mode(window_id: &str, tag: &str) -> Self {
        Self::Renderer(RendererOp::WindowQuery(WindowQuery::GetMode {
            window_id: window_id.to_string(),
            tag: tag.to_string(),
        }))
    }

    /// Query the scale factor of a window.
    pub fn scale_factor(window_id: &str, tag: &str) -> Self {
        Self::Renderer(RendererOp::WindowQuery(WindowQuery::GetScaleFactor {
            window_id: window_id.to_string(),
            tag: tag.to_string(),
        }))
    }

    /// Query the monitor size for a window.
    pub fn monitor_size(window_id: &str, tag: &str) -> Self {
        Self::Renderer(RendererOp::WindowQuery(WindowQuery::MonitorSize {
            window_id: window_id.to_string(),
            tag: tag.to_string(),
        }))
    }

    /// Query the raw platform window ID.
    pub fn raw_id(window_id: &str, tag: &str) -> Self {
        Self::Renderer(RendererOp::WindowQuery(WindowQuery::RawId {
            window_id: window_id.to_string(),
            tag: tag.to_string(),
        }))
    }

    // -- System --

    /// Enable or disable automatic window tabbing (macOS).
    pub fn allow_automatic_tabbing(enabled: bool) -> Self {
        Self::Renderer(RendererOp::SystemOp(SystemOp::AllowAutomaticTabbing(
            enabled,
        )))
    }

    /// Query the current OS theme (light/dark).
    pub fn system_theme(tag: &str) -> Self {
        Self::Renderer(RendererOp::SystemQuery(SystemQuery::GetTheme {
            tag: tag.to_string(),
        }))
    }

    /// Query system information (OS, renderer version, etc.).
    pub fn system_info(tag: &str) -> Self {
        Self::Renderer(RendererOp::SystemQuery(SystemQuery::GetInfo {
            tag: tag.to_string(),
        }))
    }

    // -- Images --

    /// Create an image from encoded bytes (PNG, JPEG, etc.).
    pub fn create_image(handle: &str, data: Vec<u8>) -> Self {
        Self::Renderer(RendererOp::Image(ImageOp::Create {
            handle: handle.to_string(),
            data,
        }))
    }

    /// Create an image from raw RGBA pixel data.
    ///
    /// # Panics
    ///
    /// Panics if `pixels.len()` is not exactly `width * height * 4`.
    /// RGBA requires four bytes per pixel; a buffer of any other size
    /// is always a programmer error and would corrupt the renderer's
    /// image registry.
    pub fn create_image_rgba(handle: &str, width: u32, height: u32, pixels: Vec<u8>) -> Self {
        assert_pixel_buffer_size(handle, width, height, pixels.len());
        Self::Renderer(RendererOp::Image(ImageOp::CreateRaw {
            handle: handle.to_string(),
            width,
            height,
            pixels,
        }))
    }

    /// Replace an existing image with new encoded bytes.
    pub fn update_image(handle: &str, data: Vec<u8>) -> Self {
        Self::Renderer(RendererOp::Image(ImageOp::Update {
            handle: handle.to_string(),
            data,
        }))
    }

    /// Replace an existing image with new raw RGBA pixel data.
    ///
    /// # Panics
    ///
    /// Panics if `pixels.len()` is not exactly `width * height * 4`.
    /// RGBA requires four bytes per pixel; a buffer of any other size
    /// is always a programmer error and would corrupt the renderer's
    /// image registry.
    pub fn update_image_rgba(handle: &str, width: u32, height: u32, pixels: Vec<u8>) -> Self {
        assert_pixel_buffer_size(handle, width, height, pixels.len());
        Self::Renderer(RendererOp::Image(ImageOp::UpdateRaw {
            handle: handle.to_string(),
            width,
            height,
            pixels,
        }))
    }

    /// Delete an image by handle.
    pub fn delete_image(handle: &str) -> Self {
        Self::Renderer(RendererOp::Image(ImageOp::Delete(handle.to_string())))
    }

    /// List all loaded image handles.
    pub fn list_images(tag: &str) -> Self {
        Self::Renderer(RendererOp::Image(ImageOp::List {
            tag: tag.to_string(),
        }))
    }

    /// Delete all loaded images.
    pub fn clear_images() -> Self {
        Self::Renderer(RendererOp::Image(ImageOp::Clear))
    }

    // -- Pane grid --

    /// Split a pane in a pane grid along the given axis.
    pub fn pane_split(target: &str, pane: &str, axis: &str, new_pane_id: &str) -> Self {
        Self::Renderer(RendererOp::Command {
            id: target.to_string(),
            family: "pane_split".to_string(),
            value: serde_json::json!({
                "pane": pane,
                "axis": axis,
                "new_pane_id": new_pane_id,
            }),
        })
    }

    /// Close a pane in a pane grid.
    pub fn pane_close(target: &str, pane: &str) -> Self {
        Self::Renderer(RendererOp::Command {
            id: target.to_string(),
            family: "pane_close".to_string(),
            value: serde_json::json!({"pane": pane}),
        })
    }

    /// Swap two panes in a pane grid.
    pub fn pane_swap(target: &str, a: &str, b: &str) -> Self {
        Self::Renderer(RendererOp::Command {
            id: target.to_string(),
            family: "pane_swap".to_string(),
            value: serde_json::json!({"a": a, "b": b}),
        })
    }

    /// Maximize a pane in a pane grid.
    pub fn pane_maximize(target: &str, pane: &str) -> Self {
        Self::Renderer(RendererOp::Command {
            id: target.to_string(),
            family: "pane_maximize".to_string(),
            value: serde_json::json!({"pane": pane}),
        })
    }

    /// Restore all panes in a pane grid from a maximized state.
    pub fn pane_restore(target: &str) -> Self {
        Self::Renderer(RendererOp::Command {
            id: target.to_string(),
            family: "pane_restore".to_string(),
            value: Value::Null,
        })
    }

    // -- Misc --

    /// Announce text to screen readers at the given politeness.
    ///
    /// `politeness`:
    /// - [`Live::Polite`] queues after any ongoing speech; correct
    ///   for status messages, toast feedback, and confirmations.
    /// - [`Live::Assertive`] interrupts ongoing speech; reserved
    ///   for urgent announcements the user must hear immediately.
    ///
    /// [`Live::Polite`]: plushie_core::types::Live::Polite
    /// [`Live::Assertive`]: plushie_core::types::Live::Assertive
    pub fn announce(text: &str, politeness: plushie_core::types::Live) -> Self {
        Self::Renderer(RendererOp::Announce {
            text: text.to_string(),
            politeness,
        })
    }

    /// Announce text politely to screen readers. Shorthand for
    /// [`Command::announce(text, Live::Polite)`](Command::announce).
    pub fn announce_text(text: &str) -> Self {
        Self::announce(text, plushie_core::types::Live::Polite)
    }

    /// Load a font from raw byte data.
    ///
    /// `family` is the name the app will reference this font by, e.g.
    /// `"Inter"`. It flows into the renderer's loaded-font registry so
    /// subsequent `default_font.family` settings and widget `font.family`
    /// props can resolve to this font without parsing its metadata.
    pub fn load_font(family: impl Into<String>, bytes: Vec<u8>) -> Self {
        Self::Renderer(RendererOp::LoadFont {
            family: family.into(),
            bytes,
        })
    }

    /// Request a hash of the current widget tree.
    pub fn tree_hash(tag: &str) -> Self {
        Self::Renderer(RendererOp::TreeHash {
            tag: tag.to_string(),
        })
    }

    /// Query which widget currently has keyboard focus.
    pub fn find_focused(tag: &str) -> Self {
        Self::Renderer(RendererOp::FindFocused {
            tag: tag.to_string(),
        })
    }

    /// Advance renderer-side animation to the given timestamp in
    /// headless/mock wire testing.
    ///
    /// Windowed daemon mode is driven by iced frame ticks instead; the
    /// renderer ignores this command there and logs a warning.
    pub fn advance_frame(timestamp: u64) -> Self {
        Self::Renderer(RendererOp::AdvanceFrame { timestamp })
    }

    // -- Effects --
    //
    // File-dialog paths have a TOCTOU (time-of-check, time-of-use)
    // boundary: the returned path reflects the user's selection at
    // the moment the dialog closed, not the filesystem state at the
    // moment the host reads or writes through it. Hosts that open,
    // execute, or otherwise trust a dialog-returned path should
    // re-verify existence, type, symlink target, and permissions
    // before acting on it.

    /// Open a file-open dialog.
    ///
    /// See the module header for the TOCTOU note that applies to
    /// every file-dialog result.
    pub fn file_open(tag: &str) -> Self {
        Self::Renderer(RendererOp::Effect {
            tag: tag.to_string(),
            timeout: None,
            request: EffectRequest::FileOpen(Default::default()),
        })
    }

    /// Open a file-open dialog with options.
    pub fn file_open_with(tag: &str, opts: FileDialogOpts) -> Self {
        Self::Renderer(RendererOp::Effect {
            tag: tag.to_string(),
            timeout: None,
            request: EffectRequest::FileOpen(opts),
        })
    }

    /// Open a multi-file selection dialog.
    pub fn file_open_multiple(tag: &str) -> Self {
        Self::Renderer(RendererOp::Effect {
            tag: tag.to_string(),
            timeout: None,
            request: EffectRequest::FileOpenMultiple(Default::default()),
        })
    }

    /// Open a multi-file selection dialog with options.
    pub fn file_open_multiple_with(tag: &str, opts: FileDialogOpts) -> Self {
        Self::Renderer(RendererOp::Effect {
            tag: tag.to_string(),
            timeout: None,
            request: EffectRequest::FileOpenMultiple(opts),
        })
    }

    /// Open a file-save dialog.
    ///
    /// Subject to the same TOCTOU boundary as `file_open`: re-verify
    /// the chosen path before writing.
    pub fn file_save(tag: &str) -> Self {
        Self::Renderer(RendererOp::Effect {
            tag: tag.to_string(),
            timeout: None,
            request: EffectRequest::FileSave(Default::default()),
        })
    }

    /// Open a file-save dialog with options.
    pub fn file_save_with(tag: &str, opts: FileDialogOpts) -> Self {
        Self::Renderer(RendererOp::Effect {
            tag: tag.to_string(),
            timeout: None,
            request: EffectRequest::FileSave(opts),
        })
    }

    /// Open a single-directory selection dialog.
    ///
    /// Subject to the same TOCTOU boundary as `file_open`.
    pub fn directory_select(tag: &str) -> Self {
        Self::Renderer(RendererOp::Effect {
            tag: tag.to_string(),
            timeout: None,
            request: EffectRequest::DirectorySelect(Default::default()),
        })
    }

    /// Open a single-directory selection dialog with options.
    pub fn directory_select_with(tag: &str, opts: FileDialogOpts) -> Self {
        Self::Renderer(RendererOp::Effect {
            tag: tag.to_string(),
            timeout: None,
            request: EffectRequest::DirectorySelect(opts),
        })
    }

    /// Open a multi-directory selection dialog.
    pub fn directory_select_multiple(tag: &str) -> Self {
        Self::Renderer(RendererOp::Effect {
            tag: tag.to_string(),
            timeout: None,
            request: EffectRequest::DirectorySelectMultiple(Default::default()),
        })
    }

    /// Open a multi-directory selection dialog with options.
    pub fn directory_select_multiple_with(tag: &str, opts: FileDialogOpts) -> Self {
        Self::Renderer(RendererOp::Effect {
            tag: tag.to_string(),
            timeout: None,
            request: EffectRequest::DirectorySelectMultiple(opts),
        })
    }

    /// Read text from the system clipboard.
    pub fn clipboard_read(tag: &str) -> Self {
        Self::Renderer(RendererOp::Effect {
            tag: tag.to_string(),
            timeout: None,
            request: EffectRequest::ClipboardRead,
        })
    }

    /// Write text to the system clipboard.
    pub fn clipboard_write(tag: &str, text: &str) -> Self {
        Self::Renderer(RendererOp::Effect {
            tag: tag.to_string(),
            timeout: None,
            request: EffectRequest::ClipboardWrite(text.to_string()),
        })
    }

    /// Read HTML content from the system clipboard.
    pub fn clipboard_read_html(tag: &str) -> Self {
        Self::Renderer(RendererOp::Effect {
            tag: tag.to_string(),
            timeout: None,
            request: EffectRequest::ClipboardReadHtml,
        })
    }

    /// Write HTML content to the system clipboard.
    ///
    /// The HTML is written verbatim; the renderer does not
    /// sanitise it. Callers that accept user-supplied HTML and
    /// forward it to this effect must sanitise before calling.
    /// Receiving applications decide how to render the payload and
    /// may execute embedded scripts or load external resources.
    /// `alt_text` is stored as the plain-text fallback for
    /// clipboards that refuse HTML.
    pub fn clipboard_write_html(tag: &str, html: &str, alt_text: Option<&str>) -> Self {
        Self::Renderer(RendererOp::Effect {
            tag: tag.to_string(),
            timeout: None,
            request: EffectRequest::ClipboardWriteHtml {
                html: html.to_string(),
                alt_text: alt_text.map(|s| s.to_string()),
            },
        })
    }

    /// Clear the system clipboard.
    pub fn clipboard_clear(tag: &str) -> Self {
        Self::Renderer(RendererOp::Effect {
            tag: tag.to_string(),
            timeout: None,
            request: EffectRequest::ClipboardClear,
        })
    }

    /// Read text from the primary selection (X11/Wayland).
    pub fn clipboard_read_primary(tag: &str) -> Self {
        Self::Renderer(RendererOp::Effect {
            tag: tag.to_string(),
            timeout: None,
            request: EffectRequest::ClipboardReadPrimary,
        })
    }

    /// Write text to the primary selection (X11/Wayland).
    pub fn clipboard_write_primary(tag: &str, text: &str) -> Self {
        Self::Renderer(RendererOp::Effect {
            tag: tag.to_string(),
            timeout: None,
            request: EffectRequest::ClipboardWritePrimary(text.to_string()),
        })
    }

    /// Show a desktop notification.
    ///
    /// On macOS, notifications may require the app to be bundled
    /// (.app) or have notification entitlements to display.
    ///
    /// `title`, `body`, `icon`, and `sound` are forwarded to the
    /// platform notification daemon verbatim. Different daemons
    /// interpret the fields differently; some historical
    /// freedesktop daemons interpret markup in `body`, icon names
    /// starting with `/` are treated as file paths, and sound
    /// names are resolved against the active sound theme. Callers
    /// that surface untrusted strings in these fields should
    /// sanitise before calling this effect.
    pub fn notification(tag: &str, title: &str, body: &str) -> Self {
        Self::Renderer(RendererOp::Effect {
            tag: tag.to_string(),
            timeout: None,
            request: EffectRequest::Notification {
                title: title.to_string(),
                body: body.to_string(),
                opts: Default::default(),
            },
        })
    }

    /// Show a desktop notification with options.
    pub fn notification_with(tag: &str, title: &str, body: &str, opts: NotificationOpts) -> Self {
        Self::Renderer(RendererOp::Effect {
            tag: tag.to_string(),
            timeout: None,
            request: EffectRequest::Notification {
                title: title.to_string(),
                body: body.to_string(),
                opts,
            },
        })
    }

    // -- Widget commands --

    /// Send a typed command to a widget.
    ///
    /// Uses a `#[derive(WidgetCommand)]` enum for type-safe command
    /// construction. The derive macro generates `to_wire()` which
    /// provides the family string and encoded value.
    ///
    /// ```no_run
    /// use plushie::command::Command;
    /// use plushie::WidgetCommand;
    ///
    /// #[derive(WidgetCommand)]
    /// enum GaugeCommand {
    ///     SetValue(f32),
    ///     Reset,
    ///     SetRange { min: f32, max: f32 },
    /// }
    ///
    /// let _ = Command::widget("temp-gauge", GaugeCommand::SetValue(72.0));
    /// ```
    pub fn widget<C: plushie_core::WidgetCommandEncode>(id: &str, cmd: C) -> Self {
        let wc = plushie_core::ops::WidgetCommand::new(id, cmd);
        Self::Renderer(RendererOp::Command {
            id: wc.id,
            family: wc.family,
            value: wc.value,
        })
    }

    /// Send a command to a widget by ID with raw family and value.
    ///
    /// Low-level generic builder. Prefer `Command::widget()` with a
    /// typed command enum derived via `#[derive(WidgetCommand)]`.
    pub fn send(id: &str, family: &str, value: Value) -> Self {
        let wc = plushie_core::ops::WidgetCommand::raw(id, family, value);
        Self::Renderer(RendererOp::Command {
            id: wc.id,
            family: wc.family,
            value: wc.value,
        })
    }

    /// Apply a batch of widget commands atomically.
    ///
    /// Unlike [`Command::batch`], which dispatches each command
    /// independently, `widget_batch` buffers intermediate events so
    /// observers only see a single consistent state after all
    /// commands commit. Build items with
    /// [`WidgetCommand::new`](plushie_core::ops::WidgetCommand::new)
    /// for typed commands and
    /// [`WidgetCommand::raw`](plushie_core::ops::WidgetCommand::raw)
    /// for ad-hoc ones:
    ///
    /// ```no_run
    /// use plushie::command::{Command, WidgetCommand};
    /// use plushie::WidgetCommand as WidgetCommandDerive;
    /// use serde_json::Value;
    ///
    /// #[derive(WidgetCommandDerive)]
    /// enum PaneCommand { SelectPane(u32) }
    ///
    /// let _ = Command::widget_batch(vec![
    ///     WidgetCommand::new("pane", PaneCommand::SelectPane(1)),
    ///     WidgetCommand::raw("footer", "refresh", Value::Null),
    /// ]);
    /// ```
    pub fn widget_batch(cmds: impl IntoIterator<Item = plushie_core::ops::WidgetCommand>) -> Self {
        Self::Renderer(RendererOp::Commands(cmds.into_iter().collect()))
    }
}