Skip to main content

arin_protocol/
client.rs

1//! Client to daemon messages.
2
3use crate::anchor::Anchor;
4use crate::geom::{DisplayId, LogicalPoint, LogicalRect};
5use crate::ids::AnnotationId;
6use crate::position::Position;
7use crate::validate::{Validate, ValidationError};
8use serde::{Deserialize, Serialize};
9
10fn is_false(b: &bool) -> bool {
11    !*b
12}
13
14/// Check a time to live, which every drawing message carries in the same form.
15///
16/// Milliseconds rather than seconds so the wire never has to carry a fraction, and an
17/// integer so it never has to carry a NaN. Absent means the mark lives until it is
18/// cleared or invalidated, which is what the daemon does by default.
19fn validate_ttl(ttl_ms: Option<u64>) -> Result<(), ValidationError> {
20    match ttl_ms {
21        Some(0) => Err(ValidationError::ZeroTtl),
22        _ => Ok(()),
23    }
24}
25
26/// Anything a client can send.
27#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
28#[serde(tag = "type", rename_all = "snake_case")]
29pub enum ClientMessage {
30    /// Open a session. The daemon replies with a session id.
31    SessionStart(SessionStart),
32    /// Put the orb on a target.
33    Point(Point),
34    /// Outline a region.
35    Highlight(Highlight),
36    /// Place a text box. Display only, never an input widget.
37    Textbox(Textbox),
38    /// Draw a freehand path.
39    Draw(Draw),
40    /// Remove annotations owned by this session.
41    Clear(Clear),
42    /// Bring an application's windows to the front.
43    Focus(Focus),
44    /// Wait until an application's window is showing.
45    AwaitWindow(AwaitWindow),
46    /// Close the session. Annotations fade shortly after.
47    SessionEnd,
48}
49
50impl Validate for ClientMessage {
51    fn validate(&self) -> Result<(), ValidationError> {
52        match self {
53            Self::SessionStart(m) => m.validate(),
54            Self::Point(m) => m.validate(),
55            Self::Highlight(m) => m.validate(),
56            Self::Textbox(m) => m.validate(),
57            Self::Draw(m) => m.validate(),
58            Self::Clear(m) => m.validate(),
59            Self::Focus(m) => m.validate(),
60            Self::AwaitWindow(m) => m.validate(),
61            Self::SessionEnd => Ok(()),
62        }
63    }
64}
65
66/// Bring an application's windows to the front.
67///
68/// The one message that changes what is on the user's screen rather than what is drawn over
69/// it, and the only one a daemon may refuse for being switched off rather than malformed.
70///
71/// Arin can only mark the visible desktop, since every desktop on a display shares one set
72/// of coordinates, so a target the user has swiped away from has nowhere to be marked. This
73/// is the ask to switch, carried out.
74///
75/// It names an application rather than a window: a window has no name a client could know,
76/// and choosing between an application's windows needs Accessibility.
77#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
78pub struct Focus {
79    /// The application to bring forward, by visible name or bundle identifier.
80    ///
81    /// `"Slack"` and `"com.tinyspeck.slackmacgap"` both work. Matched against the
82    /// applications that own windows the capture backend can see, so this never reaches an
83    /// application the user does not have open, and never reads a window title to decide.
84    pub app: String,
85}
86
87impl Validate for Focus {
88    fn validate(&self) -> Result<(), ValidationError> {
89        if self.app.trim().is_empty() {
90            return Err(ValidationError::Empty { field: "app" });
91        }
92        Ok(())
93    }
94}
95
96/// Wait until an application's window is showing, or give up.
97///
98/// The other half of guiding somebody somewhere Arin cannot take them. A mark can say
99/// "switch desktops", and without this nothing knows whether they did, so an agent draws an
100/// instruction and carries on as though it were followed.
101///
102/// A request rather than a pushed event because MCP has no way for a server to interrupt a
103/// model: a client driven by one could not act on an event until its next call anyway.
104///
105/// It never moves anything. The acting half of the handoff is the user's.
106#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
107pub struct AwaitWindow {
108    /// The application to wait for, matched exactly as [`Focus::app`] is.
109    pub app: String,
110    /// How long to wait before giving up, in milliseconds.
111    ///
112    /// Absent leaves it to the daemon, which is what a client that has no opinion should
113    /// send: the useful bound is "about as long as a person takes to find a window", and the
114    /// daemon is better placed to know that than a client is.
115    #[serde(default, skip_serializing_if = "Option::is_none")]
116    pub timeout_ms: Option<u64>,
117}
118
119impl Validate for AwaitWindow {
120    fn validate(&self) -> Result<(), ValidationError> {
121        if self.app.trim().is_empty() {
122            return Err(ValidationError::Empty { field: "app" });
123        }
124        // A wait of no time is a question, not a wait, and answering it as though somebody
125        // had waited would report "they never arrived" the instant they were asked to move.
126        if self.timeout_ms == Some(0) {
127            return Err(ValidationError::ZeroTtl);
128        }
129        Ok(())
130    }
131}
132
133/// Open a session.
134#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
135pub struct SessionStart {
136    /// Free-form client identifier, for example `"claude-code"`. Shown in diagnostics.
137    pub client_name: String,
138}
139
140impl Validate for SessionStart {
141    fn validate(&self) -> Result<(), ValidationError> {
142        if self.client_name.trim().is_empty() {
143            return Err(ValidationError::Empty {
144                field: "client_name",
145            });
146        }
147        Ok(())
148    }
149}
150
151/// Put the orb on a target.
152///
153/// Two forms. Clients that ground coordinates themselves send `x` and `y`. Clients that
154/// cannot send `query` instead, which needs a configured resolver.
155#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
156pub struct Point {
157    /// Horizontal position in logical points. Paired with `y`.
158    #[serde(default, skip_serializing_if = "Option::is_none")]
159    pub x: Option<f64>,
160    /// Vertical position in logical points. Paired with `x`.
161    #[serde(default, skip_serializing_if = "Option::is_none")]
162    pub y: Option<f64>,
163    /// A position named relative to the display, such as `top-left` or `50%,30%`.
164    ///
165    /// For clients that have not measured the screen and so cannot name a coordinate.
166    /// Resolved by the daemon, which is the only party that knows the geometry.
167    #[serde(default, skip_serializing_if = "Option::is_none")]
168    pub at: Option<String>,
169    /// Natural language description of the target, resolved by the daemon.
170    #[serde(default, skip_serializing_if = "Option::is_none")]
171    pub query: Option<String>,
172    /// The display the coordinates, position, or query apply to.
173    pub display_id: DisplayId,
174    /// Short caption rendered next to the orb.
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub label: Option<String>,
177    /// How long the mark should live, in milliseconds.
178    ///
179    /// Omit to draw until cleared, invalidated, or the session ends.
180    #[serde(default, skip_serializing_if = "Option::is_none")]
181    pub ttl_ms: Option<u64>,
182}
183
184/// Which form of [`Point`] a client sent.
185#[derive(Debug, Clone, Copy, PartialEq)]
186pub enum PointTarget<'a> {
187    /// The client did its own grounding.
188    Coords(LogicalPoint),
189    /// A position relative to the display, which only the daemon can turn into a point.
190    Named(Position),
191    /// The daemon must resolve this.
192    Query(&'a str),
193}
194
195impl Point {
196    /// At explicit coordinates.
197    pub const fn at(x: f64, y: f64, display_id: DisplayId) -> Self {
198        Self {
199            x: Some(x),
200            y: Some(y),
201            at: None,
202            query: None,
203            display_id,
204            label: None,
205            ttl_ms: None,
206        }
207    }
208
209    /// From a natural language description. Requires a resolver.
210    pub fn query(query: impl Into<String>, display_id: DisplayId) -> Self {
211        Self {
212            x: None,
213            y: None,
214            at: None,
215            query: Some(query.into()),
216            display_id,
217            label: None,
218            ttl_ms: None,
219        }
220    }
221
222    /// At a position named relative to the display, such as `top-left` or `50%,30%`.
223    pub fn named(at: impl Into<String>, display_id: DisplayId) -> Self {
224        Self {
225            x: None,
226            y: None,
227            at: Some(at.into()),
228            query: None,
229            display_id,
230            label: None,
231            ttl_ms: None,
232        }
233    }
234
235    /// Attach a caption.
236    #[must_use]
237    pub fn with_label(mut self, label: impl Into<String>) -> Self {
238        self.label = Some(label.into());
239        self
240    }
241
242    /// Set how long the mark lives, in milliseconds.
243    #[must_use]
244    pub fn with_ttl_ms(mut self, ttl_ms: Option<u64>) -> Self {
245        self.ttl_ms = ttl_ms;
246        self
247    }
248
249    /// Which form was sent.
250    ///
251    /// Exactly one of the three. Half a coordinate pair, or two forms at once, is an
252    /// error rather than a guess: every one of those is a client bug, and drawing
253    /// somewhere plausible would hide it.
254    pub fn target(&self) -> Result<PointTarget<'_>, ValidationError> {
255        const EXPECTED: &str = "x and y, or at, or query";
256
257        let coords = self.x.is_some() || self.y.is_some();
258        let named = self.at.is_some();
259        let queried = self.query.is_some();
260
261        match (coords, named, queried) {
262            (false, false, false) => {
263                return Err(ValidationError::MissingTarget {
264                    message: "point",
265                    expected: EXPECTED,
266                });
267            }
268            // More than one form supplied.
269            (true, true, _) | (true, _, true) | (_, true, true) => {
270                return Err(ValidationError::AmbiguousTarget {
271                    message: "point",
272                    expected: EXPECTED,
273                });
274            }
275            _ => {}
276        }
277
278        if let Some(at) = self.at.as_deref() {
279            return Position::parse(at).map(PointTarget::Named);
280        }
281
282        if let Some(query) = self.query.as_deref() {
283            return if query.trim().is_empty() {
284                Err(ValidationError::Empty { field: "query" })
285            } else {
286                Ok(PointTarget::Query(query))
287            };
288        }
289
290        match (self.x, self.y) {
291            (Some(x), Some(y)) => {
292                let p = LogicalPoint::new(x, y);
293                if !p.is_finite() {
294                    return Err(ValidationError::NonFiniteCoordinate { field: "x, y" });
295                }
296                Ok(PointTarget::Coords(p))
297            }
298            // Half a pair. Guessing the other half would put the mark somewhere the
299            // client never asked for.
300            _ => Err(ValidationError::AmbiguousTarget {
301                message: "point",
302                expected: EXPECTED,
303            }),
304        }
305    }
306}
307
308impl Validate for Point {
309    fn validate(&self) -> Result<(), ValidationError> {
310        validate_ttl(self.ttl_ms)?;
311        self.target().map(|_| ())
312    }
313}
314
315/// Outline a region.
316#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
317pub struct Highlight {
318    /// The region in logical points, as `[x, y, width, height]`.
319    #[serde(default, skip_serializing_if = "Option::is_none")]
320    pub rect: Option<LogicalRect>,
321    /// Natural language description of the region, resolved by the daemon.
322    #[serde(default, skip_serializing_if = "Option::is_none")]
323    pub query: Option<String>,
324    /// The display the rect or query applies to.
325    pub display_id: DisplayId,
326    /// Short caption rendered against the region.
327    #[serde(default, skip_serializing_if = "Option::is_none")]
328    pub label: Option<String>,
329    /// How long the mark should live, in milliseconds.
330    ///
331    /// Omit to draw until cleared, invalidated, or the session ends.
332    #[serde(default, skip_serializing_if = "Option::is_none")]
333    pub ttl_ms: Option<u64>,
334}
335
336/// Which form of [`Highlight`] a client sent.
337#[derive(Debug, Clone, Copy, PartialEq)]
338pub enum HighlightTarget<'a> {
339    /// The client did its own grounding.
340    Rect(LogicalRect),
341    /// The daemon must resolve this.
342    Query(&'a str),
343}
344
345impl Highlight {
346    /// Over an explicit rect.
347    pub const fn over(rect: LogicalRect, display_id: DisplayId) -> Self {
348        Self {
349            rect: Some(rect),
350            query: None,
351            display_id,
352            label: None,
353            ttl_ms: None,
354        }
355    }
356
357    /// From a natural language description. Requires a resolver.
358    pub fn query(query: impl Into<String>, display_id: DisplayId) -> Self {
359        Self {
360            rect: None,
361            query: Some(query.into()),
362            display_id,
363            label: None,
364            ttl_ms: None,
365        }
366    }
367
368    /// Attach a caption.
369    #[must_use]
370    pub fn with_label(mut self, label: impl Into<String>) -> Self {
371        self.label = Some(label.into());
372        self
373    }
374
375    /// Set how long the mark lives, in milliseconds.
376    #[must_use]
377    pub fn with_ttl_ms(mut self, ttl_ms: Option<u64>) -> Self {
378        self.ttl_ms = ttl_ms;
379        self
380    }
381
382    /// Which form was sent.
383    pub fn target(&self) -> Result<HighlightTarget<'_>, ValidationError> {
384        const EXPECTED: &str = "rect or query";
385        match (self.rect, self.query.as_deref()) {
386            (Some(rect), None) => {
387                if !rect.is_valid() {
388                    return Err(ValidationError::InvalidRect { field: "rect" });
389                }
390                Ok(HighlightTarget::Rect(rect))
391            }
392            (None, Some(q)) if !q.trim().is_empty() => Ok(HighlightTarget::Query(q)),
393            (None, Some(_)) => Err(ValidationError::Empty { field: "query" }),
394            (None, None) => Err(ValidationError::MissingTarget {
395                message: "highlight",
396                expected: EXPECTED,
397            }),
398            (Some(_), Some(_)) => Err(ValidationError::AmbiguousTarget {
399                message: "highlight",
400                expected: EXPECTED,
401            }),
402        }
403    }
404}
405
406impl Validate for Highlight {
407    fn validate(&self) -> Result<(), ValidationError> {
408        validate_ttl(self.ttl_ms)?;
409        self.target().map(|_| ())
410    }
411}
412
413/// Place a text box.
414///
415/// Display only. Arin never renders an editable input, and the overlay is fully click
416/// through. This is not negotiable within 0.x.
417#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
418pub struct Textbox {
419    /// Where to pin the box. Preferred form.
420    #[serde(default, skip_serializing_if = "Option::is_none")]
421    pub anchor: Option<Anchor>,
422    /// Shorthand for an anchor, used with `display_id`.
423    #[serde(default, skip_serializing_if = "Option::is_none")]
424    pub rect: Option<LogicalRect>,
425    /// Required when `rect` is used instead of `anchor`.
426    #[serde(default, skip_serializing_if = "Option::is_none")]
427    pub display_id: Option<DisplayId>,
428    /// The text to render.
429    pub text: String,
430    /// How long the box should live, in milliseconds.
431    ///
432    /// Omit to draw until cleared, invalidated, or the session ends.
433    #[serde(default, skip_serializing_if = "Option::is_none")]
434    pub ttl_ms: Option<u64>,
435}
436
437impl Textbox {
438    /// Pin text to a region.
439    pub fn new(anchor: Anchor, text: impl Into<String>) -> Self {
440        Self {
441            anchor: Some(anchor),
442            rect: None,
443            display_id: None,
444            text: text.into(),
445            ttl_ms: None,
446        }
447    }
448
449    /// Set how long the box lives, in milliseconds.
450    #[must_use]
451    pub fn with_ttl_ms(mut self, ttl_ms: Option<u64>) -> Self {
452        self.ttl_ms = ttl_ms;
453        self
454    }
455
456    /// The anchor, whichever form was sent.
457    pub fn resolved_anchor(&self) -> Result<Anchor, ValidationError> {
458        const EXPECTED: &str = "anchor, or rect with display_id";
459        match (&self.anchor, self.rect, self.display_id) {
460            (Some(anchor), None, None) => {
461                if !anchor.screen_rect.is_valid() {
462                    return Err(ValidationError::InvalidRect {
463                        field: "anchor.screen_rect",
464                    });
465                }
466                Ok(anchor.clone())
467            }
468            (None, Some(rect), Some(display_id)) => {
469                if !rect.is_valid() {
470                    return Err(ValidationError::InvalidRect { field: "rect" });
471                }
472                Ok(Anchor::new(rect, display_id))
473            }
474            (None, None, _) => Err(ValidationError::MissingTarget {
475                message: "textbox",
476                expected: EXPECTED,
477            }),
478            _ => Err(ValidationError::AmbiguousTarget {
479                message: "textbox",
480                expected: EXPECTED,
481            }),
482        }
483    }
484}
485
486impl Validate for Textbox {
487    fn validate(&self) -> Result<(), ValidationError> {
488        validate_ttl(self.ttl_ms)?;
489        if self.text.trim().is_empty() {
490            return Err(ValidationError::Empty { field: "text" });
491        }
492        self.resolved_anchor().map(|_| ())
493    }
494}
495
496/// Draw a freehand path.
497#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
498pub struct Draw {
499    /// The display the path is drawn on.
500    pub display_id: DisplayId,
501    /// Ordered vertices in logical points, each as `[x, y]`.
502    pub path: Vec<[f64; 2]>,
503    /// Stroke appearance. Daemon defaults apply when absent.
504    #[serde(default, skip_serializing_if = "Option::is_none")]
505    pub style: Option<StrokeStyle>,
506    /// How long the path should live, in milliseconds.
507    ///
508    /// Omit to draw until cleared, invalidated, or the session ends.
509    #[serde(default, skip_serializing_if = "Option::is_none")]
510    pub ttl_ms: Option<u64>,
511}
512
513impl Draw {
514    /// A path on a display.
515    pub fn new(display_id: DisplayId, path: Vec<[f64; 2]>) -> Self {
516        Self {
517            display_id,
518            path,
519            style: None,
520            ttl_ms: None,
521        }
522    }
523
524    /// Set how long the path lives, in milliseconds.
525    #[must_use]
526    pub fn with_ttl_ms(mut self, ttl_ms: Option<u64>) -> Self {
527        self.ttl_ms = ttl_ms;
528        self
529    }
530
531    /// The path as logical points.
532    pub fn points(&self) -> impl Iterator<Item = LogicalPoint> + '_ {
533        self.path.iter().map(|&[x, y]| LogicalPoint::new(x, y))
534    }
535}
536
537impl Validate for Draw {
538    fn validate(&self) -> Result<(), ValidationError> {
539        validate_ttl(self.ttl_ms)?;
540        if self.path.len() < 2 {
541            return Err(ValidationError::PathTooShort {
542                got: self.path.len(),
543            });
544        }
545        if !self.points().all(|p| p.is_finite()) {
546            return Err(ValidationError::NonFiniteCoordinate { field: "path" });
547        }
548        Ok(())
549    }
550}
551
552/// Stroke appearance for a freehand path.
553#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
554pub struct StrokeStyle {
555    /// Stroke width in logical points.
556    #[serde(default, skip_serializing_if = "Option::is_none")]
557    pub width: Option<f64>,
558    /// Stroke colour as `#RRGGBB`.
559    ///
560    /// Omit to let the contrast picker choose against the target region. Blue is
561    /// reserved for the orb and is excluded from automatic selection.
562    #[serde(default, skip_serializing_if = "Option::is_none")]
563    pub color: Option<String>,
564}
565
566/// Remove annotations. Only ever affects the calling session's own annotations.
567#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
568pub struct Clear {
569    /// Clear one annotation.
570    #[serde(default, skip_serializing_if = "Option::is_none")]
571    pub annotation_id: Option<AnnotationId>,
572    /// Clear every annotation in this session.
573    #[serde(default, skip_serializing_if = "is_false")]
574    pub all: bool,
575}
576
577impl Clear {
578    /// Clear every annotation in the session.
579    pub const fn all() -> Self {
580        Self {
581            annotation_id: None,
582            all: true,
583        }
584    }
585
586    /// Clear one annotation.
587    pub const fn one(annotation_id: AnnotationId) -> Self {
588        Self {
589            annotation_id: Some(annotation_id),
590            all: false,
591        }
592    }
593}
594
595impl Validate for Clear {
596    fn validate(&self) -> Result<(), ValidationError> {
597        const EXPECTED: &str = "annotation_id or all";
598        match (&self.annotation_id, self.all) {
599            (Some(_), false) | (None, true) => Ok(()),
600            (None, false) => Err(ValidationError::MissingTarget {
601                message: "clear",
602                expected: EXPECTED,
603            }),
604            (Some(_), true) => Err(ValidationError::AmbiguousTarget {
605                message: "clear",
606                expected: EXPECTED,
607            }),
608        }
609    }
610}