ricecoder 0.1.72

Terminal-first, spec-driven coding assistant that understands your project before generating code
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
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
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
//! Sessions command - Manage ricecoder sessions

use crate::commands::Command;
use crate::error::{CliError, CliResult};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;

/// Sessions command action
#[derive(Debug, Clone)]
pub enum SessionsAction {
    /// List all sessions
    List,
    /// Create a new session
    Create { name: String },
    /// Delete a session
    Delete { id: String },
    /// Rename a session
    Rename { id: String, name: String },
    /// Switch to a session
    Switch { id: String },
    /// Show session info
    Info { id: String },
    /// Share a session with a shareable link
    Share {
        expires_in: Option<u64>,
        no_history: bool,
        no_context: bool,
    },
    /// List all active shares
    ShareList,
    /// Revoke a share
    ShareRevoke { share_id: String },
    /// Show share information
    ShareInfo { share_id: String },
    /// View a shared session
    ShareView { share_id: String },
}

/// Session data for persistence
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionInfo {
    /// Session ID
    pub id: String,
    /// Session name
    pub name: String,
    /// Creation timestamp
    pub created_at: u64,
    /// Last modified timestamp
    pub modified_at: u64,
    /// Number of messages
    pub message_count: usize,
}

/// Sessions command handler
pub struct SessionsCommand {
    action: SessionsAction,
}

impl SessionsCommand {
    /// Create a new sessions command
    pub fn new(action: SessionsAction) -> Self {
        Self { action }
    }

    /// Get the sessions directory
    fn sessions_dir() -> CliResult<PathBuf> {
        let home = dirs::home_dir()
            .ok_or_else(|| CliError::Internal("Could not determine home directory".to_string()))?;
        let sessions_dir = home.join(".ricecoder").join("sessions");

        // Create directory if it doesn't exist
        fs::create_dir_all(&sessions_dir).map_err(|e| {
            CliError::Internal(format!("Failed to create sessions directory: {}", e))
        })?;

        Ok(sessions_dir)
    }

    /// Get the sessions index file
    fn sessions_index() -> CliResult<PathBuf> {
        let sessions_dir = Self::sessions_dir()?;
        Ok(sessions_dir.join("index.json"))
    }

    /// Load all sessions from index
    fn load_sessions() -> CliResult<Vec<SessionInfo>> {
        let index_path = Self::sessions_index()?;

        if !index_path.exists() {
            return Ok(Vec::new());
        }

        let content = fs::read_to_string(&index_path)
            .map_err(|e| CliError::Internal(format!("Failed to read sessions index: {}", e)))?;

        // Handle empty file
        if content.trim().is_empty() {
            return Ok(Vec::new());
        }

        let sessions: Vec<SessionInfo> = serde_json::from_str(&content)
            .map_err(|e| CliError::Internal(format!("Failed to parse sessions index: {}", e)))?;

        Ok(sessions)
    }

    /// Save sessions to index
    fn save_sessions(sessions: &[SessionInfo]) -> CliResult<()> {
        let index_path = Self::sessions_index()?;

        let content = serde_json::to_string_pretty(sessions)
            .map_err(|e| CliError::Internal(format!("Failed to serialize sessions: {}", e)))?;

        fs::write(&index_path, content)
            .map_err(|e| CliError::Internal(format!("Failed to write sessions index: {}", e)))?;

        Ok(())
    }
}

impl Command for SessionsCommand {
    fn execute(&self) -> CliResult<()> {
        match &self.action {
            SessionsAction::List => list_sessions(),
            SessionsAction::Create { name } => create_session(name),
            SessionsAction::Delete { id } => delete_session(id),
            SessionsAction::Rename { id, name } => rename_session(id, name),
            SessionsAction::Switch { id } => switch_session(id),
            SessionsAction::Info { id } => show_session_info(id),
            SessionsAction::Share {
                expires_in,
                no_history,
                no_context,
            } => handle_share(*expires_in, *no_history, *no_context),
            SessionsAction::ShareList => handle_share_list(),
            SessionsAction::ShareRevoke { share_id } => handle_share_revoke(share_id),
            SessionsAction::ShareInfo { share_id } => handle_share_info(share_id),
            SessionsAction::ShareView { share_id } => handle_share_view(share_id),
        }
    }
}

/// List all sessions
fn list_sessions() -> CliResult<()> {
    let sessions = SessionsCommand::load_sessions()?;

    if sessions.is_empty() {
        println!("No sessions found. Create one with: rice sessions create <name>");
        return Ok(());
    }

    println!("Sessions:");
    println!();

    for session in sessions {
        println!("  {} - {}", session.id, session.name);
        println!("    Messages: {}", session.message_count);
        println!("    Created: {}", format_timestamp(session.created_at));
        println!("    Modified: {}", format_timestamp(session.modified_at));
        println!();
    }

    Ok(())
}

/// Create a new session
fn create_session(name: &str) -> CliResult<()> {
    let mut sessions = SessionsCommand::load_sessions()?;

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);

    let id = format!("session-{}", now);

    let session = SessionInfo {
        id: id.clone(),
        name: name.to_string(),
        created_at: now,
        modified_at: now,
        message_count: 0,
    };

    sessions.push(session);
    SessionsCommand::save_sessions(&sessions)?;

    println!("Created session: {} ({})", id, name);
    Ok(())
}

/// Delete a session
fn delete_session(id: &str) -> CliResult<()> {
    let mut sessions = SessionsCommand::load_sessions()?;

    let initial_len = sessions.len();
    sessions.retain(|s| s.id != id);

    if sessions.len() == initial_len {
        return Err(CliError::Internal(format!("Session not found: {}", id)));
    }

    SessionsCommand::save_sessions(&sessions)?;
    println!("Deleted session: {}", id);
    Ok(())
}

/// Rename a session
fn rename_session(id: &str, name: &str) -> CliResult<()> {
    let mut sessions = SessionsCommand::load_sessions()?;

    let session = sessions
        .iter_mut()
        .find(|s| s.id == id)
        .ok_or_else(|| CliError::Internal(format!("Session not found: {}", id)))?;

    let old_name = session.name.clone();
    session.name = name.to_string();
    session.modified_at = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);

    SessionsCommand::save_sessions(&sessions)?;
    println!("Renamed session from '{}' to '{}'", old_name, name);
    Ok(())
}

/// Switch to a session
fn switch_session(id: &str) -> CliResult<()> {
    let sessions = SessionsCommand::load_sessions()?;

    let session = sessions
        .iter()
        .find(|s| s.id == id)
        .ok_or_else(|| CliError::Internal(format!("Session not found: {}", id)))?;

    // Store current session in config
    let config_path = dirs::home_dir()
        .ok_or_else(|| CliError::Internal("Could not determine home directory".to_string()))?
        .join(".ricecoder")
        .join("current_session.txt");

    fs::write(&config_path, &session.id)
        .map_err(|e| CliError::Internal(format!("Failed to save current session: {}", e)))?;

    println!("Switched to session: {} ({})", session.id, session.name);
    Ok(())
}

/// Show session info
fn show_session_info(id: &str) -> CliResult<()> {
    let sessions = SessionsCommand::load_sessions()?;

    let session = sessions
        .iter()
        .find(|s| s.id == id)
        .ok_or_else(|| CliError::Internal(format!("Session not found: {}", id)))?;

    println!("Session: {}", session.id);
    println!("  Name: {}", session.name);
    println!("  Messages: {}", session.message_count);
    println!("  Created: {}", format_timestamp(session.created_at));
    println!("  Modified: {}", format_timestamp(session.modified_at));
    Ok(())
}

/// Format timestamp as human-readable string
fn format_timestamp(secs: u64) -> String {
    use std::time::UNIX_EPOCH;

    let duration = std::time::Duration::from_secs(secs);
    let datetime = UNIX_EPOCH + duration;

    // Simple formatting - just show seconds since epoch for now
    // In production, use chrono or similar
    format!(
        "{} seconds ago",
        std::time::SystemTime::now()
            .duration_since(datetime)
            .map(|d| d.as_secs())
            .unwrap_or(0)
    )
}

/// Handle share command - generate a shareable link
fn handle_share(expires_in: Option<u64>, no_history: bool, no_context: bool) -> CliResult<()> {
    use ricecoder_sessions::{ShareService, SharePermissions};
    use chrono::Duration;

    // Create share service
    let share_service = ShareService::new();

    // Build permission flags
    let include_history = !no_history;
    let include_context = !no_context;

    // Get current session ID (for now, use a placeholder)
    let session_id = "current-session";

    // Create permissions
    let permissions = SharePermissions {
        read_only: true,
        include_history,
        include_context,
    };

    // Convert expires_in to Duration
    let expires_in_duration = expires_in.map(|secs| Duration::seconds(secs as i64));

    // Generate share link
    let share = share_service
        .generate_share_link(session_id, permissions, expires_in_duration)
        .map_err(|e| CliError::Internal(format!("Failed to generate share link: {}", e)))?;

    // Display share information
    println!("Share link: {}", share.id);
    println!();
    println!("Permissions:");
    println!("  History: {}", if include_history { "Yes" } else { "No" });
    println!("  Context: {}", if include_context { "Yes" } else { "No" });

    if let Some(expiration) = expires_in {
        println!("  Expires in: {} seconds", expiration);
    } else {
        println!("  Expires: Never");
    }

    println!();
    println!("Share this link with others to grant access to your session.");

    Ok(())
}

/// Handle share list command - list all active shares
fn handle_share_list() -> CliResult<()> {
    use ricecoder_sessions::ShareService;

    // Create share service
    let share_service = ShareService::new();

    // List all active shares
    let shares = share_service
        .list_shares()
        .map_err(|e| CliError::Internal(format!("Failed to list shares: {}", e)))?;

    if shares.is_empty() {
        println!("Active shares:");
        println!();
        println!("  No shares found. Create one with: rice sessions share");
        println!();
        return Ok(());
    }

    println!("Active shares:");
    println!();
    println!("{:<40} {:<20} {:<20} {:<20} {:<30}", "Share ID", "Session ID", "Created", "Expires", "Permissions");
    println!("{}", "-".repeat(130));

    for share in shares {
        let created = share.created_at.format("%Y-%m-%d %H:%M:%S").to_string();
        let expires = share
            .expires_at
            .map(|dt| dt.format("%Y-%m-%d %H:%M:%S").to_string())
            .unwrap_or_else(|| "Never".to_string());
        let permissions = format!(
            "History: {}, Context: {}",
            if share.permissions.include_history { "Yes" } else { "No" },
            if share.permissions.include_context { "Yes" } else { "No" }
        );

        println!(
            "{:<40} {:<20} {:<20} {:<20} {:<30}",
            &share.id[..40.min(share.id.len())],
            &share.session_id[..20.min(share.session_id.len())],
            created,
            expires,
            &permissions[..30.min(permissions.len())]
        );
    }

    println!();

    Ok(())
}

/// Handle share revoke command - revoke a share
fn handle_share_revoke(share_id: &str) -> CliResult<()> {
    use ricecoder_sessions::ShareService;

    // Create share service
    let share_service = ShareService::new();

    // Revoke the share
    share_service
        .revoke_share(share_id)
        .map_err(|e| CliError::Internal(format!("Failed to revoke share: {}", e)))?;

    println!("Share {} revoked successfully", share_id);
    Ok(())
}

/// Handle share info command - show share details
fn handle_share_info(share_id: &str) -> CliResult<()> {
    use ricecoder_sessions::ShareService;

    // Create share service
    let share_service = ShareService::new();

    // Get share details
    let share = share_service
        .get_share(share_id)
        .map_err(|e| CliError::Internal(format!("Failed to get share info: {}", e)))?;

    println!("Share: {}", share.id);
    println!("  Session: {}", share.session_id);
    println!("  Created: {}", share.created_at.format("%Y-%m-%d %H:%M:%S"));
    println!(
        "  Expires: {}",
        share
            .expires_at
            .map(|dt| dt.format("%Y-%m-%d %H:%M:%S").to_string())
            .unwrap_or_else(|| "Never".to_string())
    );
    println!("  Permissions:");
    println!("    History: {}", if share.permissions.include_history { "Yes" } else { "No" });
    println!("    Context: {}", if share.permissions.include_context { "Yes" } else { "No" });
    println!("    Read-Only: {}", if share.permissions.read_only { "Yes" } else { "No" });
    println!("  Status: Active");

    Ok(())
}

/// Handle share view command - view a shared session
fn handle_share_view(share_id: &str) -> CliResult<()> {
    use ricecoder_sessions::{ShareService, Session, SessionContext, SessionMode};

    // Create share service
    let share_service = ShareService::new();

    // Validate share exists and is not expired
    let share = share_service
        .get_share(share_id)
        .map_err(|e| match e {
            ricecoder_sessions::SessionError::ShareNotFound(_) => {
                CliError::Internal(format!("Share not found: {}", share_id))
            }
            ricecoder_sessions::SessionError::ShareExpired(_) => {
                CliError::Internal(format!("Share has expired: {}", share_id))
            }
            _ => CliError::Internal(format!("Failed to access share: {}", e)),
        })?;

    // For now, create a mock session to display
    // In a real implementation, this would retrieve the actual session from storage
    let mock_session = Session::new(
        format!("Shared Session ({})", &share.session_id[..8.min(share.session_id.len())]),
        SessionContext::new("openai".to_string(), "gpt-4".to_string(), SessionMode::Chat),
    );

    // Create filtered session view based on permissions
    let shared_session = share_service.create_shared_session_view(&mock_session, &share.permissions);

    // Display shared session with read-only mode enforced
    display_shared_session(&shared_session, &share)
}

/// Display a shared session with read-only mode enforced
fn display_shared_session(
    session: &ricecoder_sessions::Session,
    share: &ricecoder_sessions::SessionShare,
) -> CliResult<()> {
    use ricecoder_sessions::MessageRole;

    // Display header with permission indicators
    println!();
    println!("╔════════════════════════════════════════════════════════════════╗");
    println!("║ Shared Session: {} [Read-Only]", session.name);
    println!("║ Permissions: [History: {}] [Context: {}]",
        if share.permissions.include_history { "Yes" } else { "No" },
        if share.permissions.include_context { "Yes" } else { "No" }
    );
    println!("╚════════════════════════════════════════════════════════════════╝");
    println!();

    // Display session metadata
    println!("Session Information:");
    println!("  Created: {}", session.created_at.format("%Y-%m-%d %H:%M:%S"));
    if let Some(expires_at) = share.expires_at {
        println!("  Expires: {}", expires_at.format("%Y-%m-%d %H:%M:%S"));
    } else {
        println!("  Expires: Never");
    }
    println!("  Status: Read-Only");
    println!();

    // Display messages if history is included
    if share.permissions.include_history {
        if session.history.is_empty() {
            println!("Messages: (empty)");
        } else {
            println!("Messages ({} total):", session.history.len());
            println!();

            // Pagination: show first 10 messages
            let messages_per_page = 10;
            let total_messages = session.history.len();
            let pages = (total_messages + messages_per_page - 1) / messages_per_page;
            let current_page = 1;
            let start_idx = (current_page - 1) * messages_per_page;
            let end_idx = (start_idx + messages_per_page).min(total_messages);

            for (idx, msg) in session.history[start_idx..end_idx].iter().enumerate() {
                let role_str = match msg.role {
                    MessageRole::User => "User",
                    MessageRole::Assistant => "Assistant",
                    MessageRole::System => "System",
                };

                println!("[{}] {}: {}", start_idx + idx + 1, role_str, msg.content);
                println!("    Timestamp: {}", msg.timestamp.format("%Y-%m-%d %H:%M:%S"));
                println!();
            }

            // Display pagination info
            println!("Message {} - {} of {} (Page {} of {})", 
                start_idx + 1,
                end_idx,
                total_messages,
                current_page,
                pages
            );
            
            if pages > 1 {
                println!("(Use 'rice sessions share view <share_id> --page <N>' to view other pages)");
            }
        }
    } else {
        println!("Messages: (history excluded from share)");
    }

    println!();

    // Display context if included
    if share.permissions.include_context {
        println!("Context:");
        if let Some(project_path) = &session.context.project_path {
            println!("  Project: {}", project_path);
        }
        println!("  Provider: {}", session.context.provider);
        println!("  Model: {}", session.context.model);

        if !session.context.files.is_empty() {
            println!("  Files:");
            for file in &session.context.files {
                println!("    - {}", file);
            }
        } else {
            println!("  Files: (none)");
        }
    } else {
        println!("Context: (context excluded from share)");
    }

    println!();
    println!("This is a read-only view. You cannot modify this shared session.");
    println!();

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_sessions_command_creation() {
        let cmd = SessionsCommand::new(SessionsAction::List);
        assert!(matches!(cmd.action, SessionsAction::List));
    }

    #[test]
    fn test_create_session_action() {
        let cmd = SessionsCommand::new(SessionsAction::Create {
            name: "test".to_string(),
        });
        assert!(matches!(cmd.action, SessionsAction::Create { .. }));
    }

    #[test]
    fn test_delete_session_action() {
        let cmd = SessionsCommand::new(SessionsAction::Delete {
            id: "session-1".to_string(),
        });
        assert!(matches!(cmd.action, SessionsAction::Delete { .. }));
    }

    #[test]
    fn test_session_info_serialization() {
        let session = SessionInfo {
            id: "session-1".to_string(),
            name: "Test Session".to_string(),
            created_at: 1000,
            modified_at: 2000,
            message_count: 5,
        };

        let json = serde_json::to_string(&session).unwrap();
        let deserialized: SessionInfo = serde_json::from_str(&json).unwrap();

        assert_eq!(session.id, deserialized.id);
        assert_eq!(session.name, deserialized.name);
        assert_eq!(session.message_count, deserialized.message_count);
    }

    #[test]
    fn test_rename_session_action() {
        let cmd = SessionsCommand::new(SessionsAction::Rename {
            id: "session-1".to_string(),
            name: "New Name".to_string(),
        });
        assert!(matches!(cmd.action, SessionsAction::Rename { .. }));
    }

    #[test]
    fn test_switch_session_action() {
        let cmd = SessionsCommand::new(SessionsAction::Switch {
            id: "session-1".to_string(),
        });
        assert!(matches!(cmd.action, SessionsAction::Switch { .. }));
    }

    #[test]
    fn test_info_session_action() {
        let cmd = SessionsCommand::new(SessionsAction::Info {
            id: "session-1".to_string(),
        });
        assert!(matches!(cmd.action, SessionsAction::Info { .. }));
    }

    #[test]
    fn test_share_action() {
        let cmd = SessionsCommand::new(SessionsAction::Share {
            expires_in: Some(3600),
            no_history: false,
            no_context: false,
        });
        assert!(matches!(cmd.action, SessionsAction::Share { .. }));
    }

    #[test]
    fn test_share_action_with_flags() {
        let cmd = SessionsCommand::new(SessionsAction::Share {
            expires_in: None,
            no_history: true,
            no_context: true,
        });
        assert!(matches!(cmd.action, SessionsAction::Share { .. }));
    }

    #[test]
    fn test_share_list_action() {
        let cmd = SessionsCommand::new(SessionsAction::ShareList);
        assert!(matches!(cmd.action, SessionsAction::ShareList));
    }

    #[test]
    fn test_share_revoke_action() {
        let cmd = SessionsCommand::new(SessionsAction::ShareRevoke {
            share_id: "share-123".to_string(),
        });
        assert!(matches!(cmd.action, SessionsAction::ShareRevoke { .. }));
    }

    #[test]
    fn test_share_info_action() {
        let cmd = SessionsCommand::new(SessionsAction::ShareInfo {
            share_id: "share-123".to_string(),
        });
        assert!(matches!(cmd.action, SessionsAction::ShareInfo { .. }));
    }

    #[test]
    fn test_share_command_with_expiration() {
        let cmd = SessionsCommand::new(SessionsAction::Share {
            expires_in: Some(3600),
            no_history: false,
            no_context: false,
        });

        match cmd.action {
            SessionsAction::Share {
                expires_in,
                no_history,
                no_context,
            } => {
                assert_eq!(expires_in, Some(3600));
                assert!(!no_history);
                assert!(!no_context);
            }
            _ => panic!("Expected Share action"),
        }
    }

    #[test]
    fn test_share_command_without_history() {
        let cmd = SessionsCommand::new(SessionsAction::Share {
            expires_in: None,
            no_history: true,
            no_context: false,
        });

        match cmd.action {
            SessionsAction::Share {
                expires_in,
                no_history,
                no_context,
            } => {
                assert_eq!(expires_in, None);
                assert!(no_history);
                assert!(!no_context);
            }
            _ => panic!("Expected Share action"),
        }
    }

    #[test]
    fn test_share_command_without_context() {
        let cmd = SessionsCommand::new(SessionsAction::Share {
            expires_in: None,
            no_history: false,
            no_context: true,
        });

        match cmd.action {
            SessionsAction::Share {
                expires_in,
                no_history,
                no_context,
            } => {
                assert_eq!(expires_in, None);
                assert!(!no_history);
                assert!(no_context);
            }
            _ => panic!("Expected Share action"),
        }
    }

    #[test]
    fn test_share_command_all_restrictions() {
        let cmd = SessionsCommand::new(SessionsAction::Share {
            expires_in: Some(7200),
            no_history: true,
            no_context: true,
        });

        match cmd.action {
            SessionsAction::Share {
                expires_in,
                no_history,
                no_context,
            } => {
                assert_eq!(expires_in, Some(7200));
                assert!(no_history);
                assert!(no_context);
            }
            _ => panic!("Expected Share action"),
        }
    }

    #[test]
    fn test_share_revoke_action_with_id() {
        let share_id = "test-share-id-12345";
        let cmd = SessionsCommand::new(SessionsAction::ShareRevoke {
            share_id: share_id.to_string(),
        });

        match cmd.action {
            SessionsAction::ShareRevoke { share_id: id } => {
                assert_eq!(id, share_id);
            }
            _ => panic!("Expected ShareRevoke action"),
        }
    }

    #[test]
    fn test_share_info_action_with_id() {
        let share_id = "test-share-id-67890";
        let cmd = SessionsCommand::new(SessionsAction::ShareInfo {
            share_id: share_id.to_string(),
        });

        match cmd.action {
            SessionsAction::ShareInfo { share_id: id } => {
                assert_eq!(id, share_id);
            }
            _ => panic!("Expected ShareInfo action"),
        }
    }

    #[test]
    fn test_session_info_with_zero_messages() {
        let session = SessionInfo {
            id: "session-1".to_string(),
            name: "Empty Session".to_string(),
            created_at: 1000,
            modified_at: 1000,
            message_count: 0,
        };

        assert_eq!(session.message_count, 0);
        assert_eq!(session.name, "Empty Session");
    }

    #[test]
    fn test_session_info_with_many_messages() {
        let session = SessionInfo {
            id: "session-2".to_string(),
            name: "Busy Session".to_string(),
            created_at: 1000,
            modified_at: 5000,
            message_count: 100,
        };

        assert_eq!(session.message_count, 100);
        assert!(session.modified_at > session.created_at);
    }

    #[test]
    fn test_share_permissions_all_enabled() {
        use ricecoder_sessions::SharePermissions;

        let perms = SharePermissions {
            read_only: true,
            include_history: true,
            include_context: true,
        };

        assert!(perms.read_only);
        assert!(perms.include_history);
        assert!(perms.include_context);
    }

    #[test]
    fn test_share_permissions_history_only() {
        use ricecoder_sessions::SharePermissions;

        let perms = SharePermissions {
            read_only: true,
            include_history: true,
            include_context: false,
        };

        assert!(perms.read_only);
        assert!(perms.include_history);
        assert!(!perms.include_context);
    }

    #[test]
    fn test_share_permissions_context_only() {
        use ricecoder_sessions::SharePermissions;

        let perms = SharePermissions {
            read_only: true,
            include_history: false,
            include_context: true,
        };

        assert!(perms.read_only);
        assert!(!perms.include_history);
        assert!(perms.include_context);
    }

    #[test]
    fn test_share_permissions_nothing_included() {
        use ricecoder_sessions::SharePermissions;

        let perms = SharePermissions {
            read_only: true,
            include_history: false,
            include_context: false,
        };

        assert!(perms.read_only);
        assert!(!perms.include_history);
        assert!(!perms.include_context);
    }

    #[test]
    fn test_share_view_action() {
        let cmd = SessionsCommand::new(SessionsAction::ShareView {
            share_id: "share-123".to_string(),
        });
        assert!(matches!(cmd.action, SessionsAction::ShareView { .. }));
    }

    #[test]
    fn test_share_view_action_with_id() {
        let share_id = "test-share-view-id";
        let cmd = SessionsCommand::new(SessionsAction::ShareView {
            share_id: share_id.to_string(),
        });

        match cmd.action {
            SessionsAction::ShareView { share_id: id } => {
                assert_eq!(id, share_id);
            }
            _ => panic!("Expected ShareView action"),
        }
    }

    #[test]
    fn test_share_service_get_share() {
        use ricecoder_sessions::{ShareService, SharePermissions};
        use chrono::Duration;

        let service = ShareService::new();

        // Generate a share
        let permissions = SharePermissions {
            read_only: true,
            include_history: true,
            include_context: true,
        };

        let share = service
            .generate_share_link("session-1", permissions, None)
            .expect("Failed to generate share");

        // Verify we can retrieve it
        let retrieved = service
            .get_share(&share.id)
            .expect("Failed to retrieve share");

        assert_eq!(retrieved.id, share.id);
        assert_eq!(retrieved.session_id, "session-1");
        assert!(retrieved.permissions.read_only);
    }

    #[test]
    fn test_share_service_get_nonexistent_share() {
        use ricecoder_sessions::ShareService;

        let service = ShareService::new();

        // Try to get a share that doesn't exist
        let result = service.get_share("nonexistent-share");

        assert!(result.is_err());
    }

    #[test]
    fn test_share_service_revoke_share() {
        use ricecoder_sessions::{ShareService, SharePermissions};

        let service = ShareService::new();

        // Generate a share
        let permissions = SharePermissions {
            read_only: true,
            include_history: true,
            include_context: true,
        };

        let share = service
            .generate_share_link("session-1", permissions, None)
            .expect("Failed to generate share");

        // Revoke it
        service
            .revoke_share(&share.id)
            .expect("Failed to revoke share");

        // Verify it's gone
        let result = service.get_share(&share.id);
        assert!(result.is_err());
    }

    #[test]
    fn test_share_service_list_shares() {
        use ricecoder_sessions::{ShareService, SharePermissions};

        let service = ShareService::new();

        // Generate multiple shares
        let permissions = SharePermissions {
            read_only: true,
            include_history: true,
            include_context: true,
        };

        let share1 = service
            .generate_share_link("session-1", permissions.clone(), None)
            .expect("Failed to generate share 1");

        let share2 = service
            .generate_share_link("session-2", permissions.clone(), None)
            .expect("Failed to generate share 2");

        // List all shares
        let shares = service.list_shares().expect("Failed to list shares");

        assert!(shares.len() >= 2);
        assert!(shares.iter().any(|s| s.id == share1.id));
        assert!(shares.iter().any(|s| s.id == share2.id));
    }

    #[test]
    fn test_share_service_create_shared_session_view_with_history() {
        use ricecoder_sessions::{ShareService, SharePermissions, Session, SessionContext, SessionMode, Message, MessageRole};

        let service = ShareService::new();

        // Create a session with messages
        let mut session = Session::new(
            "Test Session".to_string(),
            SessionContext::new("openai".to_string(), "gpt-4".to_string(), SessionMode::Chat),
        );

        session.history.push(Message::new(
            MessageRole::User,
            "Hello".to_string(),
        ));

        session.history.push(Message::new(
            MessageRole::Assistant,
            "Hi there!".to_string(),
        ));

        // Create a view with history included
        let permissions = SharePermissions {
            read_only: true,
            include_history: true,
            include_context: true,
        };

        let view = service.create_shared_session_view(&session, &permissions);

        assert_eq!(view.history.len(), 2);
    }

    #[test]
    fn test_share_service_create_shared_session_view_without_history() {
        use ricecoder_sessions::{ShareService, SharePermissions, Session, SessionContext, SessionMode, Message, MessageRole};

        let service = ShareService::new();

        // Create a session with messages
        let mut session = Session::new(
            "Test Session".to_string(),
            SessionContext::new("openai".to_string(), "gpt-4".to_string(), SessionMode::Chat),
        );

        session.history.push(Message::new(
            MessageRole::User,
            "Hello".to_string(),
        ));

        session.history.push(Message::new(
            MessageRole::Assistant,
            "Hi there!".to_string(),
        ));

        // Create a view with history excluded
        let permissions = SharePermissions {
            read_only: true,
            include_history: false,
            include_context: true,
        };

        let view = service.create_shared_session_view(&session, &permissions);

        assert_eq!(view.history.len(), 0);
    }

    #[test]
    fn test_share_service_create_shared_session_view_without_context() {
        use ricecoder_sessions::{ShareService, SharePermissions, Session, SessionContext, SessionMode};

        let service = ShareService::new();

        // Create a session with context
        let mut session = Session::new(
            "Test Session".to_string(),
            SessionContext::new("openai".to_string(), "gpt-4".to_string(), SessionMode::Chat),
        );

        session.context.files.push("file1.rs".to_string());
        session.context.files.push("file2.rs".to_string());

        // Create a view with context excluded
        let permissions = SharePermissions {
            read_only: true,
            include_history: true,
            include_context: false,
        };

        let view = service.create_shared_session_view(&session, &permissions);

        assert_eq!(view.context.files.len(), 0);
    }

    #[test]
    fn test_share_service_list_shares_for_session() {
        use ricecoder_sessions::{ShareService, SharePermissions};

        let service = ShareService::new();

        // Generate shares for different sessions
        let permissions = SharePermissions {
            read_only: true,
            include_history: true,
            include_context: true,
        };

        let share1 = service
            .generate_share_link("session-1", permissions.clone(), None)
            .expect("Failed to generate share 1");

        let share2 = service
            .generate_share_link("session-1", permissions.clone(), None)
            .expect("Failed to generate share 2");

        let share3 = service
            .generate_share_link("session-2", permissions.clone(), None)
            .expect("Failed to generate share 3");

        // List shares for session-1
        let session1_shares = service
            .list_shares_for_session("session-1")
            .expect("Failed to list shares for session-1");

        assert_eq!(session1_shares.len(), 2);
        assert!(session1_shares.iter().any(|s| s.id == share1.id));
        assert!(session1_shares.iter().any(|s| s.id == share2.id));
        assert!(!session1_shares.iter().any(|s| s.id == share3.id));
    }

    #[test]
    fn test_share_service_invalidate_session_shares() {
        use ricecoder_sessions::{ShareService, SharePermissions};

        let service = ShareService::new();

        // Generate shares for a session
        let permissions = SharePermissions {
            read_only: true,
            include_history: true,
            include_context: true,
        };

        let share1 = service
            .generate_share_link("session-1", permissions.clone(), None)
            .expect("Failed to generate share 1");

        let share2 = service
            .generate_share_link("session-1", permissions.clone(), None)
            .expect("Failed to generate share 2");

        // Invalidate all shares for session-1
        let invalidated = service
            .invalidate_session_shares("session-1")
            .expect("Failed to invalidate shares");

        assert_eq!(invalidated, 2);

        // Verify shares are gone
        let result1 = service.get_share(&share1.id);
        let result2 = service.get_share(&share2.id);

        assert!(result1.is_err());
        assert!(result2.is_err());
    }

    #[test]
    fn test_share_service_read_only_enforcement() {
        use ricecoder_sessions::{ShareService, SharePermissions};

        let service = ShareService::new();

        // Generate a share with read_only=true
        let permissions = SharePermissions {
            read_only: true,
            include_history: true,
            include_context: true,
        };

        let share = service
            .generate_share_link("session-1", permissions, None)
            .expect("Failed to generate share");

        // Verify read_only is enforced
        assert!(share.permissions.read_only);
    }
}