moosicbox_app_state 0.5.0

MoosicBox App State package
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
//! Persistent storage functionality for `MoosicBox` application state.
//!
//! This module provides persistence capabilities using `SQLite` as the backing store,
//! allowing application state to be saved and restored across application restarts.
//!
//! # Features
//!
//! * File-based or in-memory `SQLite` storage
//! * Connection management (add, update, delete, list)
//! * Connection name and ID persistence
//! * Default download location storage
//!
//! # Example
//!
//! ```no_run
//! # use moosicbox_app_state::AppState;
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Create state with file-based persistence
//! let state = AppState::new()
//!     .with_persistence("/path/to/state.db")
//!     .await?;
//!
//! // Or use in-memory persistence for testing
//! let test_state = AppState::new()
//!     .with_persistence_in_memory()
//!     .await?;
//! # Ok(())
//! # }
//! ```

use std::{path::Path, sync::Arc};

use hyperchad::state::{StatePersistence as _, sqlite::SqlitePersistence};
use moosicbox_app_models::Connection;
use strum::{AsRefStr, EnumString};

use crate::{AppState, AppStateError, ConnectionConfig};

/// Keys used for persisting application state to storage.
///
/// These keys are used to store and retrieve various pieces of state
/// from the persistence layer (`SQLite` database).
#[derive(Debug, Clone, Copy, EnumString, AsRefStr)]
#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
pub enum PersistenceKey {
    /// Unique identifier for the current connection
    ConnectionId,
    /// Display name for the current connection
    ConnectionName,
    /// Currently active connection configuration
    Connection,
    /// List of all saved connections
    Connections,
    /// Default location for downloaded files
    DefaultDownloadLocation,
}

impl From<PersistenceKey> for String {
    fn from(value: PersistenceKey) -> Self {
        value.to_string()
    }
}

impl std::fmt::Display for PersistenceKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.as_ref().fmt(f)
    }
}

impl AppState {
    /// Initializes persistence with a file-based `SQLite` database at the specified location.
    ///
    /// This method sets up the persistence layer and loads any previously saved state.
    /// Use this when you need persistent storage across application restarts.
    ///
    /// # Errors
    ///
    /// * If the persistence fails to initialize
    pub async fn set_persistence(
        &mut self,
        location: impl AsRef<Path>,
    ) -> Result<&mut Self, AppStateError> {
        *self.persistence.write().await = Some(Arc::new(SqlitePersistence::new(location).await?));
        self.init_persistence().await?;
        Ok(self)
    }

    /// Builder method to initialize persistence with a file-based `SQLite` database.
    ///
    /// Consumes self and returns the configured instance. Equivalent to `set_persistence`
    /// but designed for method chaining during initialization.
    ///
    /// # Errors
    ///
    /// * If the persistence fails to initialize
    pub async fn with_persistence(
        mut self,
        location: impl AsRef<Path>,
    ) -> Result<Self, AppStateError> {
        self.set_persistence(location).await?;
        Ok(self)
    }

    /// Initializes persistence with an in-memory `SQLite` database.
    ///
    /// State will be lost when the application terminates. Useful for testing
    /// or when persistent storage is not needed.
    ///
    /// # Errors
    ///
    /// * If the persistence fails to initialize
    pub async fn set_persistence_in_memory(&mut self) -> Result<&mut Self, AppStateError> {
        *self.persistence.write().await = Some(Arc::new(SqlitePersistence::new_in_memory().await?));
        self.init_persistence().await?;
        Ok(self)
    }

    /// Builder method to initialize persistence with an in-memory `SQLite` database.
    ///
    /// Consumes self and returns the configured instance. Equivalent to `set_persistence_in_memory`
    /// but designed for method chaining during initialization.
    ///
    /// # Errors
    ///
    /// * If the persistence fails to initialize
    pub async fn with_persistence_in_memory(mut self) -> Result<Self, AppStateError> {
        self.set_persistence_in_memory().await?;
        Ok(self)
    }

    /// Gets the persistence layer instance.
    ///
    /// Returns a reference to the `SQLite` persistence layer for direct access
    /// to persistence operations.
    ///
    /// # Panics
    ///
    /// * If the persistence is not set
    #[must_use]
    pub async fn persistence(&self) -> Arc<SqlitePersistence> {
        self.persistence.read().await.clone().unwrap()
    }

    #[allow(clippy::unused_async, clippy::unused_async_trait_impl)]
    async fn init_persistence(&self) -> Result<(), AppStateError> {
        Ok(())
    }

    /// Activates the persisted connection with a complete runtime context.
    ///
    /// The endpoint, profile, connection name, and stable connection identifier are
    /// applied in one state update so connection-dependent services cannot observe a
    /// partially initialized context.
    ///
    /// # Errors
    ///
    /// * If the persistence layer cannot load the current connection or identity
    /// * If activating the connection state fails
    pub async fn activate_persisted_connection(
        &self,
        profile: impl Into<String>,
    ) -> Result<(), AppStateError> {
        let Some(connection) = self.get_current_connection().await? else {
            self.disconnect().await?;
            return Ok(());
        };
        let connection_name = self.get_connection_name().await?;
        let connection_id = self.get_or_init_connection_id().await?;
        let config = ConnectionConfig::new(connection.api_url, profile, connection_id)?
            .with_connection_name(connection_name);

        self.activate_connection(config).await
    }

    /// Selects and immediately activates a persisted remote connection.
    ///
    /// Persistence remains the owner of the user's backend selection while the
    /// runtime lifecycle receives one complete validated configuration.
    ///
    /// # Errors
    ///
    /// * If persistence cannot save the selected connection
    /// * If the connection identity cannot be loaded or created
    /// * If the connection cannot form a valid runtime configuration
    /// * If activation fails
    pub async fn select_connection(
        &self,
        connection: impl AsRef<Connection>,
        profile: impl Into<String>,
    ) -> Result<(), AppStateError> {
        let connection = connection.as_ref();
        let persistence = self.persistence().await;
        persistence
            .set(PersistenceKey::Connection, connection)
            .await?;
        persistence
            .set(PersistenceKey::ConnectionName, &connection.name)
            .await?;

        let connection_id = self.get_or_init_connection_id().await?;
        let config = ConnectionConfig::new(connection.api_url.clone(), profile, connection_id)?
            .with_connection_name(Some(connection.name.clone()));
        self.replace_connection(config).await
    }

    /// Activates a runtime endpoint while preserving the persisted connection identity.
    ///
    /// This is used by bundled mode, where the endpoint is selected at runtime and
    /// must not be stored as a synthetic remote connection.
    ///
    /// # Errors
    ///
    /// * If the persistence layer cannot load or create the connection identity
    /// * If the endpoint cannot form a valid runtime connection configuration
    /// * If activating the connection fails
    pub async fn activate_endpoint(
        &self,
        endpoint: impl Into<String>,
        profile: impl Into<String>,
        connection_name: impl Into<String>,
    ) -> Result<(), AppStateError> {
        let connection_id = self.get_or_init_connection_id().await?;
        let config = ConnectionConfig::new(endpoint, profile, connection_id)?
            .with_connection_name(Some(connection_name.into()));
        self.activate_connection(config).await
    }

    /// Retrieves all saved connections from persistent storage.
    ///
    /// Returns an empty list if no connections have been saved.
    ///
    /// # Errors
    ///
    /// * If the persistence fails
    pub async fn get_connections(&self) -> Result<Vec<Connection>, AppStateError> {
        let persistence = self.persistence().await;
        Ok(persistence
            .get(PersistenceKey::Connections)
            .await?
            .unwrap_or_default())
    }

    /// Retrieves the currently active connection from persistent storage.
    ///
    /// Returns `None` if no connection is currently set as active.
    ///
    /// # Errors
    ///
    /// * If the persistence fails
    pub async fn get_current_connection(&self) -> Result<Option<Connection>, AppStateError> {
        let persistence = self.persistence().await;
        Ok(persistence.get(PersistenceKey::Connection).await?)
    }

    /// Saves the currently selected remote connection without changing runtime state.
    ///
    /// Use [`Self::select_connection`] when a user action must both persist and
    /// activate a remote connection.
    ///
    /// # Errors
    ///
    /// * If the persistence fails
    pub async fn set_current_connection(
        &self,
        connection: impl AsRef<Connection>,
    ) -> Result<(), AppStateError> {
        let connection = connection.as_ref();

        self.persistence()
            .await
            .set(PersistenceKey::Connection, connection)
            .await?;

        Ok(())
    }

    /// Removes the currently active connection from persistent storage.
    ///
    /// Returns the removed connection if one was set, or `None` if no connection
    /// was active.
    ///
    /// # Errors
    ///
    /// * If the persistence fails
    pub async fn remove_current_connection(&self) -> Result<Option<Connection>, AppStateError> {
        let persistence = self.persistence().await;
        Ok(persistence.take(PersistenceKey::Connection).await?)
    }

    /// Retrieves the connection name from persistent storage.
    ///
    /// Returns `None` if no connection name has been set.
    ///
    /// # Errors
    ///
    /// * If the persistence fails
    pub async fn get_connection_name(&self) -> Result<Option<String>, AppStateError> {
        let persistence = self.persistence().await;
        Ok(persistence.get(PersistenceKey::ConnectionName).await?)
    }

    /// Updates the connection name in persistent storage.
    ///
    /// Saves the provided name to the persistence layer for future retrieval.
    ///
    /// # Errors
    ///
    /// * If the persistence fails
    pub async fn update_connection_name(
        &self,
        name: impl Into<String>,
    ) -> Result<(), AppStateError> {
        let persistence = self.persistence().await;
        let name = name.into();
        persistence
            .set(PersistenceKey::ConnectionName, &name)
            .await?;
        Ok(())
    }

    /// Gets the connection ID from persistent storage, or creates a new one if it doesn't exist.
    ///
    /// The connection ID is a unique identifier for this application instance. If one
    /// doesn't exist in persistence, a new ID is generated and saved automatically.
    ///
    /// # Errors
    ///
    /// * If the persistence fails
    pub async fn get_or_init_connection_id(&self) -> Result<String, AppStateError> {
        const KEY: PersistenceKey = PersistenceKey::ConnectionId;

        let persistence = self.persistence().await;

        Ok(if let Some(connection_id) = persistence.get(KEY).await? {
            connection_id
        } else {
            let connection_id = nanoid::nanoid!();

            persistence.set(KEY, &connection_id).await?;

            connection_id
        })
    }

    /// Adds a new connection to the list of saved connections.
    ///
    /// If this is the first connection being added and no current connection is set,
    /// it will automatically be set as the current connection. Returns the updated
    /// list of all connections.
    ///
    /// # Errors
    ///
    /// * If the persistence fails
    pub async fn add_connection(
        &self,
        connection: impl Into<Connection>,
    ) -> Result<Vec<Connection>, AppStateError> {
        let persistence = self.persistence().await;
        let connection = connection.into();
        let mut connections: Vec<Connection> = persistence
            .get(PersistenceKey::Connections)
            .await?
            .unwrap_or_default();

        if self.get_current_connection().await?.is_none() {
            self.set_current_connection(connection.clone()).await?;
        }

        connections.push(connection);

        persistence
            .set(PersistenceKey::Connections, &connections)
            .await?;
        Ok(connections)
    }

    /// Deletes a connection from the list of saved connections by name.
    ///
    /// If the deleted connection was the current connection, it will be unset.
    /// Returns the updated list of remaining connections.
    ///
    /// # Errors
    ///
    /// * If the persistence fails
    pub async fn delete_connection(&self, name: &str) -> Result<Vec<Connection>, AppStateError> {
        let persistence = self.persistence().await;
        let mut connections: Vec<Connection> = persistence
            .get(PersistenceKey::Connections)
            .await?
            .unwrap_or_default();

        if let Some(current_connection) = self.get_current_connection().await?
            && current_connection.name == name
        {
            self.remove_current_connection().await?;
            self.disconnect().await?;
        }

        connections.retain(|x| x.name != name);
        persistence
            .set(PersistenceKey::Connections, &connections)
            .await?;
        Ok(connections)
    }

    /// Updates an existing connection in the list of saved connections.
    ///
    /// Finds the connection with the given name and replaces it with the new
    /// connection data. If the updated connection is the current connection,
    /// it will also update the current connection. Returns the updated list
    /// of all connections.
    ///
    /// # Errors
    ///
    /// * If the persistence fails
    pub async fn update_connection(
        &self,
        name: &str,
        connection: impl Into<Connection>,
    ) -> Result<Vec<Connection>, AppStateError> {
        let connection = connection.into();

        let persistence = self.persistence().await;
        let mut connections: Vec<Connection> = persistence
            .get(PersistenceKey::Connections)
            .await?
            .unwrap_or_default();

        if let Some(current_connection) = self.get_current_connection().await?
            && current_connection.name == name
        {
            self.select_connection(&connection, "master").await?;
        }

        for existing in &mut connections {
            if existing.name == name {
                *existing = connection;
                persistence
                    .set(PersistenceKey::Connections, &connections)
                    .await?;
                break;
            }
        }

        Ok(connections)
    }

    pub(crate) async fn persist_default_download_location(
        &self,
        path: impl AsRef<str>,
    ) -> Result<(), AppStateError> {
        let path = path.as_ref();
        let persistence = self.persistence().await;
        persistence
            .set(PersistenceKey::DefaultDownloadLocation, &path.to_string())
            .await?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{ConnectionConfig, ConnectionStatus};

    #[test]
    fn test_connection_config_rejects_incomplete_values() {
        assert!(ConnectionConfig::new("", "master", "connection").is_err());
        assert!(ConnectionConfig::new("ftp://example.com", "master", "connection").is_err());
        assert!(ConnectionConfig::new("https://example.com", "", "connection").is_err());
        assert!(ConnectionConfig::new("https://example.com", "master", "").is_err());
    }

    #[test]
    fn test_connection_status_defaults_to_unconfigured() {
        assert_eq!(ConnectionStatus::default(), ConnectionStatus::Unconfigured);
    }

    #[test_log::test(switchy_async::test)]
    async fn unchanged_connection_does_not_restart_lifecycle() {
        let state = AppState::new()
            .with_persistence_in_memory()
            .await
            .expect("Failed to create in-memory persistence");
        let config = ConnectionConfig::new("http://127.0.0.1:9", "master", "stable")
            .expect("Invalid connection");

        assert!(
            state
                .replace_connection_if_changed(config.clone())
                .await
                .expect("Failed to activate connection")
        );
        let generation = state.connection_generation();
        assert!(
            !state
                .replace_connection_if_changed(config)
                .await
                .expect("Failed to compare connection")
        );
        assert_eq!(state.connection_generation(), generation);
    }

    #[test_log::test(switchy_async::test)]
    async fn changed_credentials_replace_connection_atomically() {
        let state = AppState::new()
            .with_persistence_in_memory()
            .await
            .expect("Failed to create in-memory persistence");
        let first = ConnectionConfig::new("http://127.0.0.1:9", "master", "stable")
            .expect("Invalid connection")
            .with_credentials(Some("client".to_string()), None, None);
        let replacement = first.clone().with_credentials(
            Some("client".to_string()),
            Some("signature".to_string()),
            None,
        );

        state
            .replace_connection(first)
            .await
            .expect("Failed to activate connection");
        let generation = state.connection_generation();
        assert!(
            state
                .replace_connection_if_changed(replacement.clone())
                .await
                .expect("Failed to replace credentials")
        );
        assert!(state.connection_generation() > generation);
        assert_eq!(
            state.connection_config.read().await.as_ref(),
            Some(&replacement)
        );
    }

    #[test_log::test(switchy_async::test)]
    async fn switching_while_retrying_invalidates_the_retry_generation() {
        let state = AppState::new()
            .with_persistence_in_memory()
            .await
            .expect("Failed to create in-memory persistence");
        let first = ConnectionConfig::new("http://127.0.0.1:9", "master", "first")
            .expect("Invalid first connection");
        let second = ConnectionConfig::new("http://127.0.0.1:10", "master", "second")
            .expect("Invalid second connection");

        state
            .activate_connection(first)
            .await
            .expect("Failed to activate first connection");
        state
            .retry_connection()
            .await
            .expect("Failed to retry connection");
        let retry_generation = state.connection_generation();

        state
            .replace_connection(second.clone())
            .await
            .expect("Failed to switch connection");

        assert!(!state.is_active_connection_generation(retry_generation));
        assert!(
            !state
                .fail_connection(retry_generation, "stale retry failed")
                .await
        );
        assert_eq!(state.connection_config.read().await.as_ref(), Some(&second));
        assert_eq!(
            state.connection_status().await,
            ConnectionStatus::Connecting
        );
    }

    #[test_log::test(switchy_async::test)]
    async fn shutdown_during_retry_clears_runtime_ownership() {
        let state = AppState::new()
            .with_persistence_in_memory()
            .await
            .expect("Failed to create in-memory persistence");
        let config = ConnectionConfig::new("http://127.0.0.1:9", "master", "connection")
            .expect("Invalid connection");

        state
            .activate_connection(config)
            .await
            .expect("Failed to activate connection");
        state
            .retry_connection()
            .await
            .expect("Failed to retry connection");
        let retry_generation = state.connection_generation();

        state.disconnect().await.expect("Failed to disconnect");

        assert!(!state.is_active_connection_generation(retry_generation));
        assert!(state.connection_config.read().await.is_none());
        assert_eq!(
            state.connection_status().await,
            ConnectionStatus::Unconfigured
        );
        assert!(
            !state
                .fail_connection(retry_generation, "stale retry failed")
                .await
        );
    }

    #[test_log::test(switchy_async::test)]
    async fn test_replace_retry_and_disconnect_advance_generation() {
        let state = AppState::new()
            .with_persistence_in_memory()
            .await
            .expect("Failed to create in-memory persistence");
        let first = ConnectionConfig::new("http://127.0.0.1:9", "master", "first")
            .expect("Invalid first connection");
        let second = ConnectionConfig::new("http://127.0.0.1:10", "master", "second")
            .expect("Invalid second connection");

        state
            .activate_connection(first)
            .await
            .expect("Failed to activate first connection");
        let first_generation = state.connection_generation();

        state
            .replace_connection(second)
            .await
            .expect("Failed to replace connection");
        let second_generation = state.connection_generation();
        assert!(second_generation > first_generation);
        assert!(!state.is_active_connection_generation(first_generation));

        state
            .retry_connection()
            .await
            .expect("Failed to retry connection");
        let retry_generation = state.connection_generation();
        assert!(retry_generation > second_generation);

        state.disconnect().await.expect("Failed to disconnect");
        assert!(state.connection_generation() > retry_generation);
        assert_eq!(
            state.connection_status().await,
            ConnectionStatus::Unconfigured
        );
        assert!(state.connection_config.read().await.is_none());
    }

    #[test_log::test(switchy_async::test)]
    async fn test_activate_persisted_connection_applies_complete_context() {
        let state = AppState::new()
            .with_persistence_in_memory()
            .await
            .expect("Failed to create in-memory persistence");
        let connection = Connection {
            name: "Test Server".to_string(),
            api_url: "http://127.0.0.1:9".to_string(),
        };
        let persistence = state.persistence().await;
        persistence
            .set(PersistenceKey::Connection, &connection)
            .await
            .expect("Failed to persist current connection");
        persistence
            .set(PersistenceKey::ConnectionName, &connection.name)
            .await
            .expect("Failed to persist connection name");

        state
            .activate_persisted_connection("master")
            .await
            .expect("Failed to activate persisted connection");

        assert_eq!(
            state.api_url.read().await.as_deref(),
            Some("http://127.0.0.1:9")
        );
        assert_eq!(state.profile.read().await.as_deref(), Some("master"));
        assert_eq!(
            state.connection_name.read().await.as_deref(),
            Some("Test Server")
        );
        assert!(state.connection_id.read().await.is_some());
        assert_eq!(
            state.connection_status().await,
            ConnectionStatus::Connecting
        );
        let config = state
            .connection_config
            .read()
            .await
            .clone()
            .expect("Missing active connection configuration");
        assert_eq!(config.api_url(), "http://127.0.0.1:9");
        assert_eq!(config.profile(), "master");
        assert_ne!(config.connection_id().len(), 0);

        state
            .close_ws_connection()
            .await
            .expect("Failed to close websocket connection");
    }

    #[test_log::test(switchy_async::test)]
    async fn test_app_state_with_persistence_in_memory() {
        let state = AppState::new()
            .with_persistence_in_memory()
            .await
            .expect("Failed to create in-memory persistence");

        assert!(state.persistence.read().await.is_some());
    }

    #[test_log::test(switchy_async::test)]
    async fn test_app_state_add_and_get_connections() {
        let state = AppState::new()
            .with_persistence_in_memory()
            .await
            .expect("Failed to create in-memory persistence");

        let connection = Connection {
            name: "Test Server".to_string(),
            api_url: "https://test.example.com".to_string(),
        };

        let connections = state
            .add_connection(connection.clone())
            .await
            .expect("Failed to add connection");

        assert_eq!(connections.len(), 1);
        assert_eq!(connections[0].name, "Test Server");

        let retrieved_connections = state
            .get_connections()
            .await
            .expect("Failed to get connections");

        assert_eq!(retrieved_connections.len(), 1);
        assert_eq!(retrieved_connections[0], connection);
    }

    #[test_log::test(switchy_async::test)]
    async fn test_app_state_set_and_get_current_connection() {
        let state = AppState::new()
            .with_persistence_in_memory()
            .await
            .expect("Failed to create in-memory persistence");

        let connection = Connection {
            name: "Current Server".to_string(),
            api_url: "https://current.example.com".to_string(),
        };

        state
            .set_current_connection(&connection)
            .await
            .expect("Failed to set current connection");

        let current = state
            .get_current_connection()
            .await
            .expect("Failed to get current connection")
            .expect("No current connection found");

        assert_eq!(current, connection);
        assert_eq!(
            state.connection_status().await,
            ConnectionStatus::Unconfigured
        );
        assert!(state.connection_config.read().await.is_none());
    }

    #[test_log::test(switchy_async::test)]
    async fn test_select_connection_persists_and_replaces_runtime_atomically() {
        let state = AppState::new()
            .with_persistence_in_memory()
            .await
            .expect("Failed to create in-memory persistence");
        let connection = Connection {
            name: "Selected Server".to_string(),
            api_url: "http://127.0.0.1:9".to_string(),
        };

        state
            .select_connection(&connection, "master")
            .await
            .expect("Failed to select connection");

        assert_eq!(
            state
                .get_current_connection()
                .await
                .expect("Failed to load selected connection"),
            Some(connection.clone())
        );
        // Activation schedules the WebSocket task before returning. The unavailable
        // endpoint can already have advanced it to its first reconnect attempt.
        assert!(matches!(
            state.connection_status().await,
            ConnectionStatus::Connecting | ConnectionStatus::Reconnecting { .. }
        ));
        let config = state
            .connection_config
            .read()
            .await
            .clone()
            .expect("Missing active runtime connection");
        assert_eq!(config.api_url(), connection.api_url);
        assert_eq!(config.profile(), "master");
    }

    #[test_log::test(switchy_async::test)]
    async fn test_app_state_remove_current_connection() {
        let state = AppState::new()
            .with_persistence_in_memory()
            .await
            .expect("Failed to create in-memory persistence");

        let connection = Connection {
            name: "Temp Server".to_string(),
            api_url: "https://temp.example.com".to_string(),
        };

        state
            .set_current_connection(&connection)
            .await
            .expect("Failed to set current connection");

        let removed = state
            .remove_current_connection()
            .await
            .expect("Failed to remove current connection")
            .expect("No connection to remove");

        assert_eq!(removed, connection);

        let current = state
            .get_current_connection()
            .await
            .expect("Failed to get current connection");

        assert!(current.is_none());
    }

    #[test_log::test(switchy_async::test)]
    async fn test_app_state_delete_connection() {
        let state = AppState::new()
            .with_persistence_in_memory()
            .await
            .expect("Failed to create in-memory persistence");

        let connection1 = Connection {
            name: "Server 1".to_string(),
            api_url: "https://server1.example.com".to_string(),
        };

        let connection2 = Connection {
            name: "Server 2".to_string(),
            api_url: "https://server2.example.com".to_string(),
        };

        state
            .add_connection(connection1.clone())
            .await
            .expect("Failed to add connection 1");
        state
            .add_connection(connection2.clone())
            .await
            .expect("Failed to add connection 2");

        let remaining = state
            .delete_connection("Server 1")
            .await
            .expect("Failed to delete connection");

        assert_eq!(remaining.len(), 1);
        assert_eq!(remaining[0].name, "Server 2");
    }

    #[test_log::test(switchy_async::test)]
    async fn test_app_state_delete_current_connection() {
        let state = AppState::new()
            .with_persistence_in_memory()
            .await
            .expect("Failed to create in-memory persistence");

        let connection = Connection {
            name: "Current".to_string(),
            api_url: "https://current.example.com".to_string(),
        };

        state
            .add_connection(connection.clone())
            .await
            .expect("Failed to add connection");

        // First connection is automatically set as current
        let current = state
            .get_current_connection()
            .await
            .expect("Failed to get current connection");
        assert!(current.is_some());

        state
            .delete_connection("Current")
            .await
            .expect("Failed to delete connection");

        let current_after = state
            .get_current_connection()
            .await
            .expect("Failed to get current connection");
        assert!(current_after.is_none());
    }

    #[test_log::test(switchy_async::test)]
    async fn test_app_state_update_connection() {
        let state = AppState::new()
            .with_persistence_in_memory()
            .await
            .expect("Failed to create in-memory persistence");

        let connection = Connection {
            name: "Original".to_string(),
            api_url: "https://original.example.com".to_string(),
        };

        state
            .add_connection(connection.clone())
            .await
            .expect("Failed to add connection");

        let updated_connection = Connection {
            name: "Updated".to_string(),
            api_url: "https://updated.example.com".to_string(),
        };

        let connections = state
            .update_connection("Original", updated_connection.clone())
            .await
            .expect("Failed to update connection");

        assert_eq!(connections.len(), 1);
        assert_eq!(connections[0].name, "Updated");
        assert_eq!(connections[0].api_url, "https://updated.example.com");
    }

    #[test_log::test(switchy_async::test)]
    async fn test_app_state_get_or_init_connection_id() {
        let state = AppState::new()
            .with_persistence_in_memory()
            .await
            .expect("Failed to create in-memory persistence");

        let connection_id1 = state
            .get_or_init_connection_id()
            .await
            .expect("Failed to get connection ID");

        assert_ne!(connection_id1.len(), 0);

        // Getting again should return the same ID
        let connection_id2 = state
            .get_or_init_connection_id()
            .await
            .expect("Failed to get connection ID");

        assert_eq!(connection_id1, connection_id2);
    }

    #[test_log::test(switchy_async::test)]
    async fn test_app_state_connection_name_persistence() {
        let state = AppState::new()
            .with_persistence_in_memory()
            .await
            .expect("Failed to create in-memory persistence");

        state
            .update_connection_name("My Connection")
            .await
            .expect("Failed to update connection name");

        let name = state
            .get_connection_name()
            .await
            .expect("Failed to get connection name")
            .expect("No connection name found");

        assert_eq!(name, "My Connection");
    }

    #[test_log::test(switchy_async::test)]
    async fn test_app_state_default_download_location() {
        let state = AppState::new()
            .with_persistence_in_memory()
            .await
            .expect("Failed to create in-memory persistence");

        let path = "/downloads/music";
        state
            .set_default_download_location(path.to_string())
            .await
            .expect("Failed to set default download location");

        let retrieved_path = state.get_default_download_location();

        assert_eq!(retrieved_path, Some(path.to_string()));
    }
}