Skip to main content

bern_protocol/
session.rs

1//! Framework-provided session and window commands.
2//!
3//! Standard controls are driven through these commands. They are executed
4//! by the UI session that owns the target control, so external entries must
5//! name a live `session_id`; without one the host answers
6//! `requires_ui_session`.
7
8use crate::{
9    CommandPolicy, CommandSpec, EnumDef, ExternalNames, FieldDef, OperationKind, ParamSpec,
10    RecordDef, Retry, Scope, Type, TypeTable, VariantDef,
11};
12
13/// Identifies one framework session command.
14#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
15pub enum SessionCommand {
16    Inspect,
17    Activate,
18    Edit,
19    Submit,
20    SetBool,
21    SetNumber,
22    Select,
23    Back,
24    WindowOpen,
25    WindowClose,
26    WindowActivate,
27    WindowConfirmClose,
28    WindowList,
29    WindowMinimize,
30    WindowRestore,
31    WindowMaximize,
32    WindowMove,
33    WindowResize,
34    Language,
35    SetLanguage,
36    Focus,
37    SetFile,
38    TraceStart,
39    TraceStop,
40    TraceReport,
41    WindowSyncOverlay,
42    WindowScreenshot,
43}
44
45impl SessionCommand {
46    /// Frontends address commands by position: new commands go last.
47    pub const ALL: [SessionCommand; 27] = [
48        SessionCommand::Inspect,
49        SessionCommand::Activate,
50        SessionCommand::Edit,
51        SessionCommand::Submit,
52        SessionCommand::SetBool,
53        SessionCommand::SetNumber,
54        SessionCommand::Select,
55        SessionCommand::Back,
56        SessionCommand::WindowOpen,
57        SessionCommand::WindowClose,
58        SessionCommand::WindowActivate,
59        SessionCommand::WindowConfirmClose,
60        SessionCommand::WindowList,
61        SessionCommand::WindowMinimize,
62        SessionCommand::WindowRestore,
63        SessionCommand::WindowMaximize,
64        SessionCommand::WindowMove,
65        SessionCommand::WindowResize,
66        SessionCommand::Language,
67        SessionCommand::SetLanguage,
68        SessionCommand::Focus,
69        SessionCommand::SetFile,
70        SessionCommand::TraceStart,
71        SessionCommand::TraceStop,
72        SessionCommand::TraceReport,
73        SessionCommand::WindowSyncOverlay,
74        SessionCommand::WindowScreenshot,
75    ];
76
77    pub fn id(self) -> &'static str {
78        match self {
79            SessionCommand::Inspect => "ui.inspect",
80            SessionCommand::Activate => "ui.activate",
81            SessionCommand::Edit => "ui.edit",
82            SessionCommand::Submit => "ui.submit",
83            SessionCommand::SetBool => "ui.set_bool",
84            SessionCommand::SetNumber => "ui.set_number",
85            SessionCommand::Select => "ui.select",
86            SessionCommand::Back => "ui.back",
87            SessionCommand::WindowOpen => "window.open",
88            SessionCommand::WindowClose => "window.close",
89            SessionCommand::WindowActivate => "window.activate",
90            SessionCommand::WindowConfirmClose => "window.confirm_close",
91            SessionCommand::WindowList => "window.list",
92            SessionCommand::WindowMinimize => "window.minimize",
93            SessionCommand::WindowRestore => "window.restore",
94            SessionCommand::WindowMaximize => "window.maximize",
95            SessionCommand::WindowMove => "window.move",
96            SessionCommand::WindowResize => "window.resize",
97            SessionCommand::Language => "ui.language",
98            SessionCommand::SetLanguage => "ui.set_language",
99            SessionCommand::Focus => "ui.focus",
100            SessionCommand::SetFile => "ui.set_file",
101            SessionCommand::TraceStart => "trace.start",
102            SessionCommand::TraceStop => "trace.stop",
103            SessionCommand::TraceReport => "trace.report",
104            SessionCommand::WindowSyncOverlay => "window.sync_overlay",
105            SessionCommand::WindowScreenshot => "window.screenshot",
106        }
107    }
108
109    pub fn from_id(id: &str) -> Option<Self> {
110        Self::ALL.into_iter().find(|command| command.id() == id)
111    }
112
113    /// Commands of the performance trace, which the session runtime
114    /// answers itself; the frontend only records.
115    pub fn is_trace(self) -> bool {
116        matches!(
117            self,
118            SessionCommand::TraceStart | SessionCommand::TraceStop | SessionCommand::TraceReport
119        )
120    }
121
122    /// Commands that act on a window's presentation. The target performs
123    /// them and the session runtime answers with the window's facts.
124    pub fn is_presentation(self) -> bool {
125        matches!(
126            self,
127            SessionCommand::WindowMinimize
128                | SessionCommand::WindowRestore
129                | SessionCommand::WindowMaximize
130                | SessionCommand::WindowMove
131                | SessionCommand::WindowResize
132        )
133    }
134}
135
136fn param(name: &str, ty: Type, doc: &str) -> ParamSpec {
137    ParamSpec {
138        name: name.into(),
139        ty,
140        doc: doc.into(),
141    }
142}
143
144fn spec(
145    command: SessionCommand,
146    kind: OperationKind,
147    doc: &str,
148    params: Vec<ParamSpec>,
149    result: Type,
150    retry: Retry,
151) -> CommandSpec {
152    let (namespace, name) = command.id().split_once('.').expect("namespaced id");
153    CommandSpec {
154        id: command.id().into(),
155        name: name.into(),
156        doc: doc.into(),
157        kind,
158        scope: Scope::Session,
159        params,
160        result,
161        errors: vec![
162            "requires_ui_session".into(),
163            "target_not_found".into(),
164            "target_unavailable".into(),
165            "target_blocked".into(),
166            "stale_window".into(),
167            "stale_confirmation".into(),
168        ],
169        policy: CommandPolicy {
170            retry,
171            ..CommandPolicy::default()
172        },
173        external: ExternalNames::derive(namespace, name),
174        reads: vec![],
175        on: None,
176    }
177}
178
179fn with_errors(mut spec: CommandSpec, errors: &[&str]) -> CommandSpec {
180    spec.errors
181        .extend(errors.iter().map(|error| (*error).to_string()));
182    spec
183}
184
185fn named(name: &str) -> Type {
186    Type::Record { name: name.into() }
187}
188
189fn distribution() -> Type {
190    named("TraceDistribution")
191}
192
193fn segment() -> Type {
194    named("TraceSegment")
195}
196
197fn trace_record(name: &str, fields: &[(&str, Type, &str)]) -> RecordDef {
198    RecordDef {
199        name: name.into(),
200        fields: fields
201            .iter()
202            .map(|(name, ty, doc)| FieldDef {
203                name: (*name).into(),
204                ty: ty.clone(),
205                doc: (*doc).into(),
206                content: false,
207            })
208            .collect(),
209    }
210}
211
212/// Type table and command specs for the framework session catalog.
213pub fn session_catalog() -> (TypeTable, Vec<CommandSpec>) {
214    let control = Type::Record {
215        name: "ControlInfo".into(),
216    };
217    let field = |name: &str, ty: Type, doc: &str| FieldDef {
218        name: name.into(),
219        ty,
220        doc: doc.into(),
221        content: false,
222    };
223    let unit_enum = |name: &str, variants: &[&str]| EnumDef {
224        name: name.into(),
225        variants: variants
226            .iter()
227            .map(|variant| VariantDef {
228                name: (*variant).into(),
229                fields: vec![],
230                label: None,
231            })
232            .collect(),
233    };
234    let decision = || Type::Enum {
235        name: "CloseDecision".into(),
236    };
237    let close_result = Type::Record {
238        name: "CloseResult".into(),
239    };
240    let named_enum = |name: &str| Type::Enum { name: name.into() };
241    let window_info = Type::Record {
242        name: "WindowInfo".into(),
243    };
244    let types = TypeTable {
245        enums: vec![
246            unit_enum(
247                "CloseOutcome",
248                &["Closed", "Rejected", "ConfirmationRequired"],
249            ),
250            unit_enum("CloseDecision", &["Save", "Discard", "Cancel"]),
251            unit_enum("WindowPresentation", &["Native", "Virtual"]),
252            unit_enum("WindowLifecycle", &["Opening", "Open", "Closing"]),
253            unit_enum("WindowVisibility", &["Visible", "Minimized", "Hidden"]),
254            unit_enum("WindowSize", &["Normal", "Maximized", "FullScreen"]),
255            unit_enum(
256                "WindowAction",
257                &[
258                    "Activate", "Close", "Minimize", "Restore", "Maximize", "Move", "Resize",
259                ],
260            ),
261            unit_enum("WindowChangeSource", &["Command", "System"]),
262        ],
263        records: vec![
264            RecordDef {
265                name: "ControlInfo".into(),
266                fields: vec![
267                    field("target", Type::Text, "Stable control identity"),
268                    field("window", Type::Text, "Owning window instance"),
269                    field("role", Type::Text, "Semantic role"),
270                    field("label", Type::Text, "Resolved accessible name"),
271                    field("enabled", Type::Bool, "Whether the control can be operated"),
272                    field(
273                        "value",
274                        Type::optional(Type::Text),
275                        "Current value, when the control has one",
276                    ),
277                    field(
278                        "reason",
279                        Type::optional(Type::Text),
280                        "Why the control cannot be operated: `disabled` or `blocked_by_modal`",
281                    ),
282                ],
283            },
284            RecordDef {
285                name: "CloseResult".into(),
286                fields: vec![
287                    field(
288                        "outcome",
289                        Type::Enum {
290                            name: "CloseOutcome".into(),
291                        },
292                        "Closed, rejected, or waiting for a confirmation decision",
293                    ),
294                    field("window", Type::Text, "Window instance"),
295                    field(
296                        "confirmation",
297                        Type::optional(Type::Text),
298                        "Confirmation to decide with window.confirm_close",
299                    ),
300                    field(
301                        "draft_revision",
302                        Type::Int,
303                        "Draft revision the confirmation is bound to",
304                    ),
305                    field(
306                        "decisions",
307                        Type::list(decision()),
308                        "Decisions the confirmation accepts",
309                    ),
310                    field(
311                        "message",
312                        Type::optional(Type::Text),
313                        "The declared confirmation message, as shown in the dialog",
314                    ),
315                    field(
316                        "reason",
317                        Type::optional(Type::Text),
318                        "Why closing was rejected",
319                    ),
320                ],
321            },
322            RecordDef {
323                name: "WindowFrame".into(),
324                fields: vec![
325                    field(
326                        "x",
327                        Type::Float,
328                        "Left edge in points from the main display's left edge",
329                    ),
330                    field(
331                        "y",
332                        Type::Float,
333                        "Top edge in points below the main display's top edge",
334                    ),
335                    field("width", Type::Float, "Outer width in points"),
336                    field("height", Type::Float, "Outer height in points"),
337                ],
338            },
339            RecordDef {
340                name: "WindowScreenshot".into(),
341                fields: vec![
342                    field("window", Type::Text, "Captured window instance id"),
343                    field("width", Type::Int, "Image width in pixels"),
344                    field("height", Type::Int, "Image height in pixels"),
345                    field("scale", Type::Float, "Backing pixel scale factor"),
346                    field("mime", Type::Text, "Image MIME type, such as `image/png`"),
347                    field(
348                        "path",
349                        Type::optional(Type::Text),
350                        "Output file path written when `--output` was requested",
351                    ),
352                    field(
353                        "data",
354                        Type::optional(Type::Text),
355                        "Base64-encoded PNG bytes, returned when `--output` is omitted",
356                    ),
357                ],
358            },
359            trace_record(
360                "TraceStarted",
361                &[
362                    ("rules", Type::Text, "The rules in their normal spelling"),
363                    (
364                        "file",
365                        Type::optional(Type::Text),
366                        "Where the timeline goes, when it is written to a file",
367                    ),
368                ],
369            ),
370            trace_record(
371                "TraceStopped",
372                &[
373                    (
374                        "files",
375                        Type::list(Type::Text),
376                        "The timeline files written, for ui.perfetto.dev",
377                    ),
378                    ("events", Type::Int, "Records read"),
379                    (
380                        "dropped",
381                        Type::Int,
382                        "Records lost because a ring was full; raise `buffer:`",
383                    ),
384                    (
385                        "timeline",
386                        Type::optional(Type::Text),
387                        "The timeline itself, when asked for",
388                    ),
389                ],
390            ),
391            trace_record(
392                "TraceDistribution",
393                &[
394                    ("count", Type::Int, "Samples in all"),
395                    ("p50", Type::Int, "Median of the recent samples"),
396                    ("p95", Type::Int, "95th percentile of the recent samples"),
397                    ("max", Type::Int, "Largest sample"),
398                ],
399            ),
400            trace_record(
401                "TraceCommand",
402                &[
403                    ("id", Type::Text, "Command id"),
404                    ("entry", Type::Text, "ui, cli, json, web, script or test"),
405                    (
406                        "total_us",
407                        distribution(),
408                        "From dispatch to on screen, or to the engine's answer",
409                    ),
410                    ("queue_us", distribution(), "Waiting for the engine"),
411                    ("exec_us", distribution(), "Running the command"),
412                    (
413                        "publish_us",
414                        distribution(),
415                        "Snapshot, comparison and encoding of the state",
416                    ),
417                    (
418                        "apply_us",
419                        distribution(),
420                        "Decoding and writing the state on the UI thread",
421                    ),
422                    ("bytes", distribution(), "State bytes sent to the UI"),
423                ],
424            ),
425            trace_record(
426                "TraceQuery",
427                &[
428                    ("id", Type::Text, "Query id"),
429                    ("cancelled", Type::Int, "Answers no one waited for any more"),
430                    ("queue_us", distribution(), "Waiting for the engine"),
431                    (
432                        "provider_us",
433                        distribution(),
434                        "From the provider's start to its answer",
435                    ),
436                    (
437                        "round_trip_us",
438                        distribution(),
439                        "From the request to the UI showing the answer",
440                    ),
441                ],
442            ),
443            trace_record(
444                "TraceField",
445                &[
446                    ("name", Type::Text, "State field"),
447                    (
448                        "sent",
449                        Type::Int,
450                        "Times it changed, and was sent to a UI if one runs",
451                    ),
452                    ("bytes_max", Type::Int, "Largest encoding sent"),
453                    (
454                        "items_max",
455                        Type::optional(Type::Int),
456                        "Most items, for a list",
457                    ),
458                    ("snapshot_us", distribution(), "Taking it from the engine"),
459                    (
460                        "compare_us",
461                        distribution(),
462                        "Comparing it with the last state",
463                    ),
464                    ("encode_us", distribution(), "Encoding it for the UI"),
465                    (
466                        "apply_us",
467                        distribution(),
468                        "Decoding and writing it on the UI thread",
469                    ),
470                ],
471            ),
472            trace_record(
473                "TraceSegment",
474                &[
475                    ("name", Type::Text, "Part of the work"),
476                    ("us", Type::Int, "Microseconds"),
477                ],
478            ),
479            trace_record(
480                "TraceInteraction",
481                &[
482                    (
483                        "control",
484                        Type::optional(Type::Text),
485                        "The control operated; absent for commands from other entries",
486                    ),
487                    ("entry", Type::Text, "Where it came from"),
488                    ("commands", Type::list(Type::Text), "Commands it ran"),
489                    ("at_ms", Type::Int, "Milliseconds after tracing started"),
490                    (
491                        "total_us",
492                        Type::Int,
493                        "From the action to the frame showing its result",
494                    ),
495                    (
496                        "revision",
497                        Type::optional(Type::Int),
498                        "The state revision it produced",
499                    ),
500                    ("segments", Type::list(segment()), "Where the time went"),
501                ],
502            ),
503            trace_record(
504                "TraceFrames",
505                &[
506                    ("spacing_us", distribution(), "Time between frame ticks"),
507                    ("long", Type::Int, "Frames over the long-frame threshold"),
508                ],
509            ),
510            trace_record(
511                "TraceFrame",
512                &[
513                    ("at_ms", Type::Int, "Milliseconds after tracing started"),
514                    ("us", Type::Int, "Time since the frame before"),
515                    (
516                        "refresh_us",
517                        Type::Int,
518                        "The display's refresh interval, 0 when unknown",
519                    ),
520                    ("bern_us", Type::Int, "Bern's own work on the UI thread"),
521                    (
522                        "outside_us",
523                        Type::Int,
524                        "The rest: generated views and the platform's layout and drawing",
525                    ),
526                    (
527                        "segments",
528                        Type::list(segment()),
529                        "Bern's longest work on the UI thread",
530                    ),
531                    (
532                        "engine",
533                        Type::list(segment()),
534                        "What the engine did meanwhile",
535                    ),
536                ],
537            ),
538            trace_record(
539                "TraceSpan",
540                &[
541                    ("name", Type::Text, "Span name"),
542                    ("us", distribution(), "Durations"),
543                ],
544            ),
545            trace_record(
546                "TraceReport",
547                &[
548                    ("running", Type::Bool, "Whether tracing is still on"),
549                    ("window_ms", Type::Int, "Milliseconds the statistics cover"),
550                    ("events", Type::Int, "Records read"),
551                    ("dropped", Type::Int, "Records lost because a ring was full"),
552                    (
553                        "commands",
554                        Type::list(named("TraceCommand")),
555                        "Per command, slowest first",
556                    ),
557                    ("queries", Type::list(named("TraceQuery")), "Per query"),
558                    (
559                        "fields",
560                        Type::list(named("TraceField")),
561                        "State fields sent, largest first",
562                    ),
563                    (
564                        "interactions",
565                        Type::list(named("TraceInteraction")),
566                        "The slowest interactions and commands",
567                    ),
568                    ("frames", named("TraceFrames"), "Frame ticks"),
569                    (
570                        "long_frames",
571                        Type::list(named("TraceFrame")),
572                        "The latest long frames",
573                    ),
574                    ("spans", Type::list(named("TraceSpan")), "Spans by name"),
575                ],
576            ),
577            RecordDef {
578                name: "WindowInfo".into(),
579                fields: vec![
580                    field("window", Type::Text, "Window instance"),
581                    field("kind", Type::Text, "Window kind id"),
582                    field(
583                        "presentation",
584                        named_enum("WindowPresentation"),
585                        "Native system window or virtual window",
586                    ),
587                    field(
588                        "lifecycle",
589                        named_enum("WindowLifecycle"),
590                        "Opening until the platform reports it; Closing while a close confirmation waits",
591                    ),
592                    field(
593                        "visibility",
594                        named_enum("WindowVisibility"),
595                        "Visible, minimized or hidden, as the platform reports it",
596                    ),
597                    field(
598                        "size",
599                        named_enum("WindowSize"),
600                        "Normal, maximized or full screen",
601                    ),
602                    field(
603                        "frame",
604                        Type::optional(Type::Record {
605                            name: "WindowFrame".into(),
606                        }),
607                        "Outer frame; absent while opening",
608                    ),
609                    field(
610                        "focused",
611                        Type::Bool,
612                        "Whether the window has keyboard focus",
613                    ),
614                    field(
615                        "actions",
616                        Type::list(named_enum("WindowAction")),
617                        "Window actions available now",
618                    ),
619                    field(
620                        "version",
621                        Type::Int,
622                        "Bumped by every change of this instance's presentation",
623                    ),
624                    field(
625                        "changed_by",
626                        Type::optional(named_enum("WindowChangeSource")),
627                        "Whether the latest change came from a command or from the user and system",
628                    ),
629                ],
630            },
631        ],
632    };
633    let target = || param("target", Type::Text, "Control identity from ui.inspect");
634    let window = || param("window", Type::Text, "Window instance id");
635    let commands = vec![
636        spec(
637            SessionCommand::Inspect,
638            OperationKind::Query,
639            "List the mounted controls of the session",
640            vec![],
641            Type::list(control),
642            Retry::Idempotent,
643        ),
644        spec(
645            SessionCommand::Activate,
646            OperationKind::Command,
647            "Activate a button or link through its real control binding",
648            vec![target()],
649            Type::Unit,
650            Retry::Never,
651        ),
652        spec(
653            SessionCommand::Edit,
654            OperationKind::Command,
655            "Replace the draft text of a text input",
656            vec![target(), param("value", Type::Text, "New text")],
657            Type::Unit,
658            Retry::Idempotent,
659        ),
660        spec(
661            SessionCommand::Submit,
662            OperationKind::Command,
663            "Submit a text input",
664            vec![target()],
665            Type::Unit,
666            Retry::Never,
667        ),
668        spec(
669            SessionCommand::SetBool,
670            OperationKind::Command,
671            "Set a switch or checkbox",
672            vec![target(), param("value", Type::Bool, "New state")],
673            Type::Unit,
674            Retry::Idempotent,
675        ),
676        spec(
677            SessionCommand::SetNumber,
678            OperationKind::Command,
679            "Set and commit a slider",
680            vec![target(), param("value", Type::Float, "New value")],
681            Type::Unit,
682            Retry::Never,
683        ),
684        spec(
685            SessionCommand::Select,
686            OperationKind::Command,
687            "Select an option of a picker, sidebar or tab view by variant name",
688            vec![target(), param("option", Type::Text, "Option name")],
689            Type::Unit,
690            Retry::Idempotent,
691        ),
692        spec(
693            SessionCommand::Back,
694            OperationKind::Command,
695            "Go back one step in a navigation container",
696            vec![target()],
697            Type::Unit,
698            Retry::Never,
699        ),
700        spec(
701            SessionCommand::Focus,
702            OperationKind::Command,
703            "Give a control the keyboard focus, such as a search field, whose results then show",
704            vec![target()],
705            Type::Unit,
706            Retry::Idempotent,
707        ),
708        with_errors(
709            spec(
710                SessionCommand::SetFile,
711                OperationKind::Command,
712                "Give a file to a control that asks for one or takes dropped files, as if the user chose or dropped it; its action then runs",
713                vec![
714                    target(),
715                    param(
716                        "url",
717                        Type::Text,
718                        "A `file://` or http(s) URL; it must be of a kind the control accepts",
719                    ),
720                ],
721                Type::Unit,
722                Retry::Never,
723            ),
724            &["invalid_url", "unsupported_file"],
725        ),
726        spec(
727            SessionCommand::Language,
728            OperationKind::Query,
729            "The session's interface language tag",
730            vec![],
731            Type::Text,
732            Retry::Idempotent,
733        ),
734        with_errors(
735            spec(
736                SessionCommand::SetLanguage,
737                OperationKind::Command,
738                "Switch the interface language; every localized text updates while drafts, navigation and windows stay",
739                vec![param(
740                    "language",
741                    Type::Text,
742                    "A supported language tag, such as `en`",
743                )],
744                Type::Unit,
745                Retry::Idempotent,
746            ),
747            &["unsupported_language"],
748        ),
749        with_errors(
750            spec(
751                SessionCommand::TraceStart,
752                OperationKind::Command,
753                "Start the performance trace with rules such as `engine,ui,slow:16ms` or `command:library.*`; a running trace ends first",
754                vec![param(
755                    "rules",
756                    Type::Text,
757                    "Categories (engine, ui, frame, span, motion, style, all), filters (command:, query:, control:, field:, feature:), slow:, long:, file:, quiet, buffer:",
758                )],
759                named("TraceStarted"),
760                Retry::Idempotent,
761            ),
762            &["invalid_rules"],
763        ),
764        spec(
765            SessionCommand::TraceStop,
766            OperationKind::Command,
767            "Stop the performance trace and write its timeline",
768            vec![param(
769                "timeline",
770                Type::optional(Type::Bool),
771                "Also return the timeline itself, for an app whose files are on another device",
772            )],
773            named("TraceStopped"),
774            Retry::Idempotent,
775        ),
776        spec(
777            SessionCommand::TraceReport,
778            OperationKind::Query,
779            "What the performance trace measured: p50, p95 and maximum per command, the slowest interactions and the long frames",
780            vec![
781                param(
782                    "top",
783                    Type::optional(Type::Int),
784                    "How many of the slowest interactions to list (10)",
785                ),
786                param(
787                    "reset",
788                    Type::optional(Type::Bool),
789                    "Start the statistics over after this report",
790                ),
791            ],
792            named("TraceReport"),
793            Retry::Idempotent,
794        ),
795        spec(
796            SessionCommand::WindowOpen,
797            OperationKind::Command,
798            "Open a window kind or activate its existing instance",
799            vec![param("kind", Type::Text, "Window kind id")],
800            Type::Text,
801            Retry::Idempotent,
802        ),
803        spec(
804            SessionCommand::WindowClose,
805            OperationKind::Command,
806            "Request closing a window instance; its declared close check may ask for a confirmation",
807            vec![window()],
808            close_result.clone(),
809            Retry::Idempotent,
810        ),
811        spec(
812            SessionCommand::WindowActivate,
813            OperationKind::Command,
814            "Bring a window instance to the front",
815            vec![window()],
816            Type::Unit,
817            Retry::Idempotent,
818        ),
819        spec(
820            SessionCommand::WindowConfirmClose,
821            OperationKind::Command,
822            "Decide a pending close confirmation, as its dialog would",
823            vec![
824                window(),
825                param(
826                    "confirmation",
827                    Type::Text,
828                    "Confirmation id from window.close",
829                ),
830                param("decision", decision(), "Save, Discard or Cancel"),
831            ],
832            close_result,
833            Retry::Never,
834        ),
835        spec(
836            SessionCommand::WindowList,
837            OperationKind::Query,
838            "List the open window instances with their actual presentation and available actions",
839            vec![],
840            Type::list(window_info.clone()),
841            Retry::Idempotent,
842        ),
843        spec(
844            SessionCommand::WindowMinimize,
845            OperationKind::Command,
846            "Minimize a window instance; its drafts and navigation stay",
847            vec![window()],
848            window_info.clone(),
849            Retry::Idempotent,
850        ),
851        spec(
852            SessionCommand::WindowRestore,
853            OperationKind::Command,
854            "Undo one step: bring a minimized window back, or leave full screen or the maximized size",
855            vec![window()],
856            window_info.clone(),
857            Retry::Never,
858        ),
859        spec(
860            SessionCommand::WindowMaximize,
861            OperationKind::Command,
862            "Grow a window instance to fill its display, as the platform zooms windows",
863            vec![window()],
864            window_info.clone(),
865            Retry::Idempotent,
866        ),
867        with_errors(
868            spec(
869                SessionCommand::WindowMove,
870                OperationKind::Command,
871                "Move a window instance so its top-left corner is at x, y; its title bar must stay on a display",
872                vec![
873                    window(),
874                    param("x", Type::Float, "Left edge in points"),
875                    param("y", Type::Float, "Top edge in points"),
876                ],
877                window_info.clone(),
878                Retry::Idempotent,
879            ),
880            &["out_of_range"],
881        ),
882        with_errors(
883            spec(
884                SessionCommand::WindowResize,
885                OperationKind::Command,
886                "Resize a window instance, keeping its top-left corner; the size must respect the window's minimum",
887                vec![
888                    window(),
889                    param("width", Type::Float, "Outer width in points"),
890                    param("height", Type::Float, "Outer height in points"),
891                ],
892                window_info,
893                Retry::Idempotent,
894            ),
895            &["out_of_range"],
896        ),
897        spec(
898            SessionCommand::WindowSyncOverlay,
899            OperationKind::Command,
900            "Reposition or close any utility windows anchored to an overlay",
901            vec![param("overlay", Type::Text, "Overlay identifier")],
902            Type::Unit,
903            Retry::Idempotent,
904        ),
905        with_errors(
906            spec(
907                SessionCommand::WindowScreenshot,
908                OperationKind::Query,
909                "Capture an in-process PNG screenshot of an open window without screen recording permission",
910                vec![
911                    param(
912                        "window",
913                        Type::optional(Type::Text),
914                        "Window instance id from window.list; defaults to the focused or primary open window",
915                    ),
916                    param(
917                        "output",
918                        Type::optional(Type::Text),
919                        "Save the PNG to this file path and omit `data` from the JSON reply",
920                    ),
921                ],
922                named("WindowScreenshot"),
923                Retry::Idempotent,
924            ),
925            &["capture_failed"],
926        ),
927    ];
928    (types, commands)
929}
930
931#[cfg(test)]
932mod tests {
933    use super::*;
934    use crate::descriptor::check_external_names;
935
936    #[test]
937    fn session_catalog_is_consistent() {
938        let (types, commands) = session_catalog();
939        types.validate().unwrap();
940        check_external_names(commands.iter()).unwrap();
941        assert_eq!(commands.len(), SessionCommand::ALL.len());
942        for command in SessionCommand::ALL {
943            assert_eq!(SessionCommand::from_id(command.id()), Some(command));
944            assert!(commands.iter().any(|spec| spec.id == command.id()));
945        }
946    }
947}