Skip to main content

arin_protocol/
daemon.rs

1//! Daemon to client messages.
2
3use crate::geom::{DisplayInfo, LogicalPoint};
4use crate::ids::{AnnotationId, SessionId};
5use serde::{Deserialize, Serialize};
6
7/// Anything the daemon can send.
8#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
9#[serde(tag = "type", rename_all = "snake_case")]
10pub enum DaemonMessage {
11    /// A client message was accepted.
12    Ack(Ack),
13    /// An annotation is no longer valid.
14    Invalidated(Invalidated),
15    /// A client message was rejected.
16    Error(ProtocolError),
17}
18
19/// A client message was accepted.
20///
21/// A session start acks with `session_id` and no annotation. Everything else acks with
22/// `annotation_id`. Resolver-backed requests additionally carry what was resolved and
23/// how confident the resolver was.
24#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
25pub struct Ack {
26    /// Present on the ack for a session start.
27    #[serde(default, skip_serializing_if = "Option::is_none")]
28    pub session_id: Option<SessionId>,
29    /// Present on the ack for an annotation.
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub annotation_id: Option<AnnotationId>,
32    /// Where a query landed. Only for query-form requests.
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub resolved_coords: Option<LogicalPoint>,
35    /// How sure the resolver was, in `0.0..=1.0`. Only for query-form requests.
36    ///
37    /// The daemon, not the client, decides what to draw from this. It is reported so
38    /// clients can phrase themselves honestly, not so they can pick a rendering.
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    pub confidence: Option<f64>,
41    /// Scale and size of the display involved, so clients can convert screenshot pixels.
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    pub display: Option<DisplayInfo>,
44    /// What was brought forward. Only for a focus request.
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub activated: Option<Activated>,
47    /// Whether the window turned up. Only for an `await_window` request.
48    ///
49    /// `false` is an answer rather than a failure: the user was asked to go somewhere and
50    /// has not, which is a thing a client should handle rather than an error it should
51    /// report. Waiting longer, asking again, or giving up are all reasonable, and only the
52    /// client knows which.
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub appeared: Option<bool>,
55}
56
57/// The application a focus request brought forward.
58///
59/// Reported back because a client names an application loosely and the daemon resolves it,
60/// so the only way to know what actually came forward is to be told. An agent that asked
61/// for `"slack"` and reads `"Slack"` back can say what it did with some confidence.
62#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
63pub struct Activated {
64    /// The application's own name for itself, as the system reports it.
65    pub app: String,
66    /// Its bundle identifier, when it has one.
67    #[serde(default, skip_serializing_if = "Option::is_none")]
68    pub bundle_id: Option<String>,
69    /// Which browser profile window holds the target, when that is how it was found.
70    ///
71    /// Present only when the match came from a browser's open tabs rather than from a
72    /// window, which is the case where raising the application is not enough on its own: a
73    /// browser is one application holding many profile windows, and activation cannot
74    /// choose between them. So this is the difference between "Chrome is in front of you"
75    /// and "it is in the window called Your Chrome", and the second is the one a user can
76    /// act on.
77    ///
78    /// It is the profile's display name, the label in the browser's own profile switcher.
79    /// Nothing else read from the tab index ever reaches a client: not a title, not a URL,
80    /// not how many matched.
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    pub profile: Option<String>,
83}
84
85impl Ack {
86    /// Ack a session start.
87    pub fn session(session_id: SessionId) -> Self {
88        Self {
89            session_id: Some(session_id),
90            ..Self::default()
91        }
92    }
93
94    /// Ack an annotation.
95    pub fn annotation(annotation_id: AnnotationId) -> Self {
96        Self {
97            annotation_id: Some(annotation_id),
98            ..Self::default()
99        }
100    }
101
102    /// Attach display metadata.
103    #[must_use]
104    pub fn with_display(mut self, display: DisplayInfo) -> Self {
105        self.display = Some(display);
106        self
107    }
108
109    /// Attach what a resolver produced.
110    #[must_use]
111    pub fn with_resolution(mut self, coords: LogicalPoint, confidence: f64) -> Self {
112        self.resolved_coords = Some(coords);
113        self.confidence = Some(confidence);
114        self
115    }
116
117    /// Ack a wait with whether the window turned up.
118    pub fn appeared(appeared: bool) -> Self {
119        Self {
120            appeared: Some(appeared),
121            ..Self::default()
122        }
123    }
124
125    /// Ack a focus request with what came forward.
126    ///
127    /// Carries no annotation id, because nothing was drawn. This is the one ack that
128    /// reports a change to the user's screen rather than to what is over it.
129    pub fn activated(app: Activated) -> Self {
130        Self {
131            activated: Some(app),
132            ..Self::default()
133        }
134    }
135}
136
137/// An annotation is no longer valid and has been removed.
138#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
139pub struct Invalidated {
140    /// The annotation that went away. Absent when a whole display was invalidated.
141    #[serde(default, skip_serializing_if = "Option::is_none")]
142    pub annotation_id: Option<AnnotationId>,
143    /// Why.
144    pub reason: InvalidationReason,
145}
146
147impl Invalidated {
148    /// One annotation went away.
149    pub fn one(annotation_id: AnnotationId, reason: InvalidationReason) -> Self {
150        Self {
151            annotation_id: Some(annotation_id),
152            reason,
153        }
154    }
155}
156
157/// Why an annotation was invalidated.
158#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
159#[serde(rename_all = "snake_case")]
160pub enum InvalidationReason {
161    /// Content moved under the annotation.
162    ///
163    /// In 0.1 a scroll invalidates every annotation on that display. Later versions
164    /// translate annotations with the scroll and only invalidate when they cannot.
165    Scroll,
166    /// A display was added, removed, or reconfigured.
167    DisplayChange,
168    /// The owning session ended, or its socket disconnected.
169    SessionEnd,
170    /// The annotation's time to live expired.
171    Ttl,
172    /// The user cleared it, from the menu bar or the global hotkey.
173    ///
174    /// Distinct from `session_end` because the client did not ask for it and may want to
175    /// say so. The clear affordance belongs to the user, not to the agent driving.
176    Cleared,
177    /// A reason introduced by a newer daemon than this build knows about.
178    #[serde(untagged)]
179    Unknown(String),
180}
181
182/// A client message was rejected.
183#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
184pub struct ProtocolError {
185    /// Machine-readable cause.
186    pub code: ErrorCode,
187    /// Human-readable detail. Never load bearing, so do not parse it.
188    pub msg: String,
189}
190
191impl ProtocolError {
192    /// Build an error.
193    pub fn new(code: ErrorCode, msg: impl Into<String>) -> Self {
194        Self {
195            code,
196            msg: msg.into(),
197        }
198    }
199}
200
201/// Machine-readable rejection causes.
202#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
203#[serde(rename_all = "snake_case")]
204pub enum ErrorCode {
205    /// The message parsed as JSON but is not a valid message.
206    BadSchema,
207    /// The `type` field names a message this daemon does not implement.
208    UnknownType,
209    /// The line exceeded [`crate::MAX_PAYLOAD_BYTES`].
210    PayloadTooLarge,
211    /// A query-form request arrived with no resolver configured.
212    NoResolver,
213    /// A resolver exists, and the user has not permitted this daemon to ground for a
214    /// client.
215    ///
216    /// Distinct from [`Self::NoResolver`], which says grounding is not set up. This says it
217    /// is set up and was refused, which is a different thing for a client to do something
218    /// about: one is a configuration problem and the other is a person declining.
219    ///
220    /// Drawing is never refused this way. Any peer that reaches the socket can draw, since
221    /// a process running as the user could open its own window and draw anyway. Grounding
222    /// is the only capability Arin actually holds, because it is the one backed by the
223    /// Screen Recording grant.
224    NotPermitted,
225    /// A resolver ran and could not ground the query.
226    ResolveFailed,
227    /// The `display_id` does not name a connected display.
228    UnknownDisplay,
229    /// The annotation exists but belongs to a different session.
230    NotOwner,
231    /// The `v` field names an incompatible major version.
232    VersionUnsupported,
233    /// A code introduced by a newer daemon than this build knows about.
234    #[serde(untagged)]
235    Unknown(String),
236}
237
238impl ErrorCode {
239    /// The wire spelling of this code.
240    pub fn as_str(&self) -> &str {
241        match self {
242            Self::BadSchema => "bad_schema",
243            Self::UnknownType => "unknown_type",
244            Self::PayloadTooLarge => "payload_too_large",
245            Self::NoResolver => "no_resolver",
246            Self::NotPermitted => "not_permitted",
247            Self::ResolveFailed => "resolve_failed",
248            Self::UnknownDisplay => "unknown_display",
249            Self::NotOwner => "not_owner",
250            Self::VersionUnsupported => "version_unsupported",
251            Self::Unknown(s) => s,
252        }
253    }
254}
255
256impl std::fmt::Display for ErrorCode {
257    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
258        f.write_str(self.as_str())
259    }
260}
261
262#[cfg(test)]
263mod tests {
264    use super::*;
265
266    #[test]
267    fn unknown_codes_survive_a_round_trip() {
268        let json = r#""teleported_into_the_sun""#;
269        let code: ErrorCode = serde_json::from_str(json).unwrap();
270        assert_eq!(code, ErrorCode::Unknown("teleported_into_the_sun".into()));
271        assert_eq!(serde_json::to_string(&code).unwrap(), json);
272    }
273
274    #[test]
275    fn known_codes_take_priority_over_the_fallback() {
276        assert_eq!(
277            serde_json::from_str::<ErrorCode>(r#""not_owner""#).unwrap(),
278            ErrorCode::NotOwner
279        );
280        assert_eq!(
281            serde_json::from_str::<InvalidationReason>(r#""display_change""#).unwrap(),
282            InvalidationReason::DisplayChange
283        );
284    }
285}