reovim-server 0.14.4

Reovim server - the editing engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
//! `PresenceService` gRPC implementation (Phase 14, Epic #465).
//!
//! Multi-client presence awareness for collaborative editing.
//! Clients can see each other's cursors, follow viewports, and coordinate.
//!
//! # Architecture
//!
//! ```text
//! Client A ──► Join() ──► Server assigns ClientId
//!              │              └─► Emits presence_joined notification
//!//!              ├─► StreamPresence() ──► Receives all presence updates
//!//!              ├─► UpdatePresence() ──► Updates cursor/viewport/mode
//!              │              └─► Emits presence_updated notification
//!//!              └─► Leave() ──► Server removes client
//!                       └─► Emits presence_left notification
//! ```

// `Status` is tonic's standard error type - size is inherent to the library
#![allow(clippy::result_large_err)]
// gRPC protocol uses u64 for IDs, but internally we use usize. On 64-bit
// platforms (our target), these are equivalent. Truncation on 32-bit is acceptable.
#![allow(clippy::cast_possible_truncation)]

use std::{pin::Pin, sync::Arc, time::SystemTime};

use {
    futures::Stream,
    reovim_protocol::v2::{
        ClientInfo as ProtoClientInfo, ClientMetadata as ProtoClientMetadata,
        ClientPresence as ProtoClientPresence, ClientRelation as ProtoClientRelation,
        ClientRelationType as ProtoRelationType, ClientRole as ProtoRole,
        ClientViewState as ProtoViewState, JoinRequest, JoinResponse, LeaveRequest, LeaveResponse,
        LineRange, ListClientsRequest, ListClientsResponse, Notification, Position, PresenceUpdate,
        SetRelationRequest, SetRelationResponse, SetRoleRequest, SetRoleResponse,
        SetSyncModeRequest, SetSyncModeResponse, StreamPresenceRequest, SyncMode as ProtoSyncMode,
        TransitionError as ProtoTransitionError, UpdatePresenceRequest, UpdatePresenceResponse,
        notification::Payload, presence_service_server::PresenceService, presence_update::Update,
    },
    tokio_stream::wrappers::{BroadcastStream, errors::BroadcastStreamRecvError},
    tonic::{Request, Response, Status},
};

use crate::{
    grpc::auth::require_client_id,
    session::{
        Client, ClientId, ClientPresence, ClientRelation, Session, SessionId, SessionRegistry,
        SyncMode, TokenRegistry, TransitionResult,
    },
};

use reovim_kernel::api::BufferId;

/// Get current Unix timestamp in milliseconds.
#[allow(clippy::cast_possible_truncation)]
fn current_timestamp_ms() -> u64 {
    SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .expect("system time before UNIX_EPOCH")
        .as_millis() as u64
}

/// Convert internal `Client` to new `ClientInfo` protobuf format (#480).
pub fn to_proto_client_info(client: &Client) -> ProtoClientInfo {
    let relation = client.relation.map(|r| match r {
        ClientRelation::Following { target } => ProtoClientRelation {
            r#type: ProtoRelationType::RelationTypeFollowing as i32,
            target_id: target.as_usize() as u64,
        },
        ClientRelation::Sharing { with } => ProtoClientRelation {
            r#type: ProtoRelationType::RelationTypeSharing as i32,
            target_id: with.as_usize() as u64,
        },
    });

    // Get cursor from active window
    let cursor = client
        .state
        .windows
        .active()
        .map(|w| Position {
            line: w.cursor.line as u64,
            column: w.cursor.column as u64,
        })
        .unwrap_or_default();

    // Get buffer_id from active window
    let buffer_id = client.state.windows.active().and_then(|w| w.buffer_id);

    let view = ProtoViewState {
        mode: client.state.mode_stack.current().name().to_string(),
        cursor: Some(cursor),
        buffer_id: buffer_id.map(|id| id.as_usize() as u64),
        selection: None, // TODO: convert selection if present
    };

    let metadata = ProtoClientMetadata {
        client_type: client.metadata.client_type.clone(),
        display_name: client.metadata.display_name.clone(),
        joined_at_ms: client.metadata.joined_at_ms,
    };

    ProtoClientInfo {
        id: client.id.as_usize() as u64,
        relation,
        view: Some(view),
        metadata: Some(metadata),
    }
}

/// Convert internal `ClientPresence` to protobuf format.
///
/// Note: cursor is no longer included in proto (Phase 14, #471).
/// Cursor tracking moved to `CursorMoved` notifications with `client_id`.
fn to_proto_presence(presence: &ClientPresence) -> ProtoClientPresence {
    let (sync_mode, follow_target) = match presence.sync_mode {
        SyncMode::Independent => (ProtoSyncMode::Independent as i32, None),
        SyncMode::Follow { target } => {
            (ProtoSyncMode::Follow as i32, Some(target.as_usize() as u64))
        }
        SyncMode::Present => (ProtoSyncMode::Present as i32, None),
    };

    ProtoClientPresence {
        client_id: presence.client_id.as_usize() as u64,
        client_type: presence.client_type.clone(),
        display_name: presence.display_name.clone(),
        // Phase #479: Use optional field to eliminate ID ambiguity
        buffer_id: presence.buffer_id.map(|id| id as u64),
        // cursor field removed - now tracked via CursorMoved with client_id
        visible_lines: Some(LineRange {
            start: presence.visible_lines.0 as u64,
            end: presence.visible_lines.1 as u64,
        }),
        mode: presence.mode.clone(),
        sync_mode,
        follow_target,
        joined_at_ms: presence.joined_at_ms(),
    }
}

/// Build `presence_joined` notification.
fn build_presence_joined_notification(presence: &ClientPresence) -> Notification {
    use reovim_protocol::v2::PresenceJoinedPayload;

    Notification {
        event_type: "presence_joined".to_string(),
        timestamp_ms: current_timestamp_ms(),
        payload: Some(Payload::PresenceJoined(PresenceJoinedPayload {
            client: Some(to_proto_presence(presence)),
        })),
    }
}

/// Build `presence_left` notification.
fn build_presence_left_notification(client_id: ClientId, display_name: &str) -> Notification {
    use reovim_protocol::v2::PresenceLeftPayload;

    Notification {
        event_type: "presence_left".to_string(),
        timestamp_ms: current_timestamp_ms(),
        payload: Some(Payload::PresenceLeft(PresenceLeftPayload {
            client_id: client_id.as_usize() as u64,
            display_name: display_name.to_string(),
        })),
    }
}

/// Build `presence_updated` notification.
pub fn build_presence_updated_notification(presence: &ClientPresence) -> Notification {
    use reovim_protocol::v2::PresenceUpdatedPayload;

    Notification {
        event_type: "presence_updated".to_string(),
        timestamp_ms: current_timestamp_ms(),
        payload: Some(Payload::PresenceUpdated(PresenceUpdatedPayload {
            client: Some(to_proto_presence(presence)),
        })),
    }
}

/// Convert notification to `PresenceUpdate` for streaming.
///
/// Returns `None` if the notification is not a presence-related event.
fn notification_to_presence_update(notification: &Notification) -> Option<PresenceUpdate> {
    match &notification.payload {
        Some(Payload::PresenceJoined(payload)) => Some(PresenceUpdate {
            update: Some(Update::Joined(payload.client.clone()?)),
        }),
        Some(Payload::PresenceUpdated(payload)) => Some(PresenceUpdate {
            update: Some(Update::Updated(payload.client.clone()?)),
        }),
        Some(Payload::PresenceLeft(payload)) => Some(PresenceUpdate {
            update: Some(Update::Left(payload.client_id)),
        }),
        _ => None,
    }
}

/// gRPC `PresenceService` implementation.
///
/// Provides multi-client presence awareness:
/// - Join/leave session
/// - Stream presence updates in real-time
/// - Update cursor/viewport/mode
/// - Set sync mode (follow, present)
pub struct PresenceServiceImpl {
    /// Shared session registry for client ID generation.
    sessions: Arc<SessionRegistry>,
    /// Default session ID to use when not specified.
    default_session_id: SessionId,
    /// Token registry for session-based authentication (#483).
    tokens: Arc<TokenRegistry>,
}

impl PresenceServiceImpl {
    /// Create a new `PresenceService` with access to the session registry.
    #[must_use]
    pub const fn new(
        sessions: Arc<SessionRegistry>,
        default_session_id: SessionId,
        tokens: Arc<TokenRegistry>,
    ) -> Self {
        Self {
            sessions,
            default_session_id,
            tokens,
        }
    }

    /// Get the default session.
    fn get_session(&self) -> Result<Arc<Session>, Status> {
        self.sessions
            .get(&self.default_session_id)
            .ok_or_else(|| Status::not_found("No active session"))
    }
}

#[tonic::async_trait]
impl PresenceService for PresenceServiceImpl {
    /// Join the session and receive assigned client ID + peer list.
    ///
    /// # Flow
    ///
    /// 1. Server generates unique `ClientId` via `SessionRegistry::next_client_id()`
    /// 2. Creates `ClientPresence` with provided type/name
    /// 3. Adds to `PresenceMap`, collecting existing peers
    /// 4. Emits `presence_joined` notification to all subscribers
    /// 5. Returns assigned ID and peer list to caller
    async fn join(&self, request: Request<JoinRequest>) -> Result<Response<JoinResponse>, Status> {
        let req = request.into_inner();
        let session = self.get_session()?;

        // Generate unique client ID
        let client_id = self.sessions.next_client_id();

        // Phase #479: Create per-client state (mode, cursor, windows)
        // This MUST happen before any state queries (get_mode, get_cursor, etc.)
        // The metadata carries client_type and display_name for diagnostics.
        let metadata = crate::session::ClientMetadata::new(&req.client_type, &req.display_name);
        session.add_client_with_metadata(client_id, metadata);

        // Create presence and populate buffer_id from the new client's state.
        // ClientPresence::new() defaults to buffer_id: None, but the client
        // was just assigned a window+buffer by add_client_with_metadata().
        // Without this, PresenceJoined notifications carry buffer_id: None,
        // and existing clients skip rendering the new cursor (different-buffer filter).
        let mut presence = ClientPresence::new(client_id, &req.client_type, &req.display_name);
        presence.buffer_id = session.with_clients(|clients| {
            clients.get(&client_id).and_then(|c| {
                c.state
                    .windows
                    .active()
                    .and_then(|w| w.buffer_id.map(BufferId::as_usize))
            })
        });

        // Add to presence map, get existing peers
        let peers = session.presence().join(presence.clone());

        // Emit notification to all subscribers
        session.emit_notification(build_presence_joined_notification(&presence));

        // Convert peers to protobuf format (legacy)
        let proto_peers: Vec<ProtoClientPresence> = peers.iter().map(to_proto_presence).collect();

        // Convert clients to new ClientInfo format (#480)
        let peers_v2: Vec<ProtoClientInfo> = session.with_clients(|clients| {
            clients
                .values()
                .filter(|c| c.id != client_id) // Exclude self
                .map(to_proto_client_info)
                .collect()
        });

        // Start per-client illuminate tick (#664)
        session.with_state_mut_sync(|state| {
            use reovim_driver_session::{ClientId as DriverClientId, TickSchedulerHandle};

            if let Some(tick_handle) = state.app.services.get::<TickSchedulerHandle>() {
                tick_handle.start(
                    DriverClientId::new(client_id.as_usize()),
                    "illuminate",
                    std::time::Duration::from_millis(100),
                );
            }
        });

        // Generate session token for this client (#483)
        let token = self.tokens.register(client_id);

        Ok(Response::new(JoinResponse {
            client_id: client_id.as_usize() as u64,
            peers: proto_peers,
            peers_v2,
            session_token: token.to_string(),
        }))
    }

    /// Leave the session.
    ///
    /// Removes client from presence map and emits `presence_left` notification.
    async fn leave(
        &self,
        request: Request<LeaveRequest>,
    ) -> Result<Response<LeaveResponse>, Status> {
        // #483 Phase 5: Token-only authentication
        let token_client_id = request.extensions().get::<ClientId>().copied();
        let _req = request.into_inner(); // LeaveRequest has no fields after #483
        let session = self.get_session()?;

        let client_id = require_client_id(token_client_id)?;

        // Revoke session token (#483)
        self.tokens.revoke_by_client(client_id);

        // Remove from presence map
        if let Some(presence) = session.presence().leave(client_id) {
            // Emit notification
            session.emit_notification(build_presence_left_notification(
                client_id,
                &presence.display_name,
            ));
            Ok(Response::new(LeaveResponse { ok: true }))
        } else {
            // Client not found - still return ok: false (not an error)
            Ok(Response::new(LeaveResponse { ok: false }))
        }
    }

    /// Stream type for `StreamPresence` RPC.
    type StreamPresenceStream =
        Pin<Box<dyn Stream<Item = Result<PresenceUpdate, Status>> + Send + 'static>>;

    /// Stream presence updates in real-time.
    ///
    /// Subscribes to the session's notification broadcast and filters
    /// for presence-related events (joined, updated, left).
    ///
    /// # Disconnect Handling
    ///
    /// Clients are expected to call `Leave()` for clean disconnect.
    /// The stream drop does NOT automatically remove the client from
    /// presence map because `StreamPresenceRequest` doesn't include
    /// `client_id` (by design - streaming is separate from presence lifecycle).
    ///
    /// Future enhancement: Could add optional `client_id` to request or
    /// use gRPC metadata for automatic cleanup on stream drop.
    async fn stream_presence(
        &self,
        _request: Request<StreamPresenceRequest>,
    ) -> Result<Response<Self::StreamPresenceStream>, Status> {
        let session = self.get_session()?;

        // Get the notification receiver from the session
        let rx = session.subscribe_notifications();

        // Create stream from broadcast receiver
        let stream = BroadcastStream::new(rx);

        // Map and filter the stream for presence events only
        let output_stream = async_stream::stream! {
            let mut stream = stream;
            while let Some(result) = futures::StreamExt::next(&mut stream).await {
                match result {
                    Ok(notification) => {
                        // Convert to PresenceUpdate if it's a presence event
                        if let Some(update) = notification_to_presence_update(&notification) {
                            yield Ok(update);
                        }
                    }
                    Err(BroadcastStreamRecvError::Lagged(n)) => {
                        // Client fell behind, log and continue
                        tracing::warn!(lagged = n, "Presence stream subscriber lagged behind");
                    }
                }
            }
        };

        Ok(Response::new(Box::pin(output_stream)))
    }

    /// Update client's presence state (cursor, viewport, mode).
    ///
    /// Only provided fields are updated; unset fields retain current values.
    async fn update_presence(
        &self,
        request: Request<UpdatePresenceRequest>,
    ) -> Result<Response<UpdatePresenceResponse>, Status> {
        // #483 Phase 5: Token-only authentication
        let token_client_id = request.extensions().get::<ClientId>().copied();
        let req = request.into_inner();
        let session = self.get_session()?;

        // #483 Phase 5: Token-only authentication
        let client_id = require_client_id(token_client_id)?;

        // Update presence via closure
        // Note: cursor field removed from request (Phase 14, #471) - now tracked via CursorMoved
        let updated = session.presence().update(client_id, |presence| {
            if let Some(buffer_id) = req.buffer_id {
                presence.buffer_id = Some(buffer_id as usize);
            }
            // cursor field removed - tracked via CursorMoved with client_id
            if let Some(visible_lines) = &req.visible_lines {
                presence.visible_lines = (visible_lines.start as usize, visible_lines.end as usize);
            }
            if let Some(mode) = &req.mode {
                presence.mode.clone_from(mode);
            }
        });

        updated.map_or_else(
            || Err(Status::not_found(format!("Client {client_id} not found in presence map"))),
            |presence| {
                session.emit_notification(build_presence_updated_notification(&presence));
                Ok(Response::new(UpdatePresenceResponse { ok: true }))
            },
        )
    }

    /// Set client's sync mode (independent, follow, present).
    async fn set_sync_mode(
        &self,
        request: Request<SetSyncModeRequest>,
    ) -> Result<Response<SetSyncModeResponse>, Status> {
        // #483 Phase 5: Token-only authentication
        let token_client_id = request.extensions().get::<ClientId>().copied();
        let req = request.into_inner();
        let session = self.get_session()?;

        // #483 Phase 5: Token-only authentication
        let client_id = require_client_id(token_client_id)?;

        // Parse sync mode
        let sync_mode = match ProtoSyncMode::try_from(req.mode) {
            Ok(ProtoSyncMode::Independent) => SyncMode::Independent,
            Ok(ProtoSyncMode::Present) => SyncMode::Present,
            Ok(ProtoSyncMode::Follow) => {
                // FOLLOW requires a target
                let target = req.follow_target.ok_or_else(|| {
                    Status::invalid_argument("follow_target is required for FOLLOW mode")
                })?;
                let target_id = ClientId::new(target as usize);

                // Verify target exists
                if !session.presence().contains(target_id) {
                    return Err(Status::invalid_argument(format!(
                        "Follow target {target_id} does not exist"
                    )));
                }

                SyncMode::Follow { target: target_id }
            }
            Err(_) => {
                return Err(Status::invalid_argument(format!("Invalid sync mode: {}", req.mode)));
            }
        };

        // Update presence
        let updated = session.presence().update(client_id, |presence| {
            presence.sync_mode = sync_mode;
        });

        updated.map_or_else(
            || Err(Status::not_found(format!("Client {client_id} not found in presence map"))),
            |presence| {
                session.emit_notification(build_presence_updated_notification(&presence));
                Ok(Response::new(SetSyncModeResponse { ok: true }))
            },
        )
    }

    /// List all currently connected clients.
    async fn list_clients(
        &self,
        _request: Request<ListClientsRequest>,
    ) -> Result<Response<ListClientsResponse>, Status> {
        let session = self.get_session()?;

        // Legacy format
        let clients: Vec<ProtoClientPresence> = session
            .presence()
            .list()
            .iter()
            .map(to_proto_presence)
            .collect();

        // New unified format (#480)
        let clients_v2: Vec<ProtoClientInfo> =
            session.with_clients(|c| c.values().map(to_proto_client_info).collect());

        Ok(Response::new(ListClientsResponse {
            clients,
            clients_v2,
        }))
    }

    /// Set a client's editing role (Phase 11.2, Epic #465).
    ///
    /// Controls input routing:
    /// - Owner: Input goes to own state (independent)
    /// - Follow: Input is ignored (read-only spectator)
    /// - Share: Input goes to owner's state
    ///
    /// **Note**: This RPC uses the old `ClientRole` enum. For new code,
    /// prefer using `set_client_relation()` with `ClientRelation` directly.
    async fn set_role(
        &self,
        request: Request<SetRoleRequest>,
    ) -> Result<Response<SetRoleResponse>, Status> {
        use crate::session::ClientRelation;

        // #483 Phase 5: Token-only authentication
        let token_client_id = request.extensions().get::<ClientId>().copied();
        let req = request.into_inner();
        let session = self.get_session()?;

        // #483 Phase 5: Token-only authentication
        let client_id = require_client_id(token_client_id)?;

        // Validate client exists
        if !session.has_client(client_id) {
            return Ok(Response::new(SetRoleResponse {
                ok: false,
                error: Some(format!("Client {client_id} not found")),
            }));
        }

        // Map proto role to ClientRelation (#480: unified model)
        let relation = match req.role() {
            ProtoRole::Owner => None, // Independent
            ProtoRole::Follow => {
                let target_id = req.target_id.ok_or_else(|| {
                    Status::invalid_argument("target_id required for FOLLOW role")
                })?;
                Some(ClientRelation::Following {
                    target: ClientId::new(target_id as usize),
                })
            }
            ProtoRole::Share => {
                let owner_id = req.target_id.ok_or_else(|| {
                    Status::invalid_argument("target_id (owner) required for SHARE role")
                })?;
                Some(ClientRelation::Sharing {
                    with: ClientId::new(owner_id as usize),
                })
            }
        };

        // Set the relation with validation
        match session.set_client_relation(client_id, relation) {
            Ok(()) => Ok(Response::new(SetRoleResponse {
                ok: true,
                error: None,
            })),
            Err(err) => {
                use crate::session::TransitionResult;
                let error_msg = match err {
                    TransitionResult::TargetNotFound(id) => {
                        format!("Target client {} not found", id.as_usize())
                    }
                    TransitionResult::WouldCreateCycle => {
                        "Cannot set relation: would create a cycle".to_string()
                    }
                    TransitionResult::CannotTargetSelf => "Cannot target self".to_string(),
                    TransitionResult::RequiresCursorSync { .. } => {
                        "Cursor sync required for this transition".to_string()
                    }
                    TransitionResult::Ok => unreachable!(),
                };
                Err(Status::failed_precondition(error_msg))
            }
        }
    }

    /// Set client's relation (#480 Client Architecture Unification).
    ///
    /// Unified API for managing client relationships. Replaces the separate
    /// `SetSyncMode` and `SetRole` RPCs with a single validated transition.
    ///
    /// # Arguments
    ///
    /// * `client_id` - Client ID to set relation for
    /// * `relation` - New relation. `None` = independent
    ///
    /// # Returns
    ///
    /// * `ok: true` if relation was set
    /// * `error` - Error code if validation failed
    async fn set_relation(
        &self,
        request: Request<SetRelationRequest>,
    ) -> Result<Response<SetRelationResponse>, Status> {
        // #483 Phase 5: Token-only authentication
        let token_client_id = request.extensions().get::<ClientId>().copied();
        let req = request.into_inner();
        let session = self.get_session()?;

        // #483 Phase 5: Token-only authentication
        let client_id = require_client_id(token_client_id)?;

        // Convert proto relation to internal relation
        let relation = req.relation.map(|r| {
            let target_id = ClientId::new(r.target_id as usize);
            match ProtoRelationType::try_from(r.r#type) {
                Ok(ProtoRelationType::RelationTypeFollowing) => {
                    ClientRelation::Following { target: target_id }
                }
                Ok(ProtoRelationType::RelationTypeSharing) => {
                    ClientRelation::Sharing { with: target_id }
                }
                Err(_) => ClientRelation::Following { target: target_id }, // Default to following
            }
        });

        // Set the relation with validation
        match session.set_client_relation(client_id, relation) {
            Ok(()) => Ok(Response::new(SetRelationResponse {
                ok: true,
                error: None,
            })),
            Err(err) => {
                let error_code = match err {
                    TransitionResult::TargetNotFound(_) => ProtoTransitionError::TargetNotFound,
                    TransitionResult::WouldCreateCycle => ProtoTransitionError::WouldCreateCycle,
                    TransitionResult::CannotTargetSelf => ProtoTransitionError::CannotTargetSelf,
                    TransitionResult::RequiresCursorSync { .. } => {
                        ProtoTransitionError::RequiresCursorSync
                    }
                    TransitionResult::Ok => unreachable!(),
                };
                Ok(Response::new(SetRelationResponse {
                    ok: false,
                    error: Some(error_code as i32),
                }))
            }
        }
    }
}

#[cfg(test)]
#[path = "presence_tests.rs"]
mod tests;