summaryrefslogtreecommitdiffstats
path: root/tests/sessions.rs
blob: 748b689d373dc3a92dca32f09b854f5072c8e566 (plain) (blame)
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
use std::fs;
use std::path::PathBuf;
use std::process::Command;

use serde_json::json;

/// Tests in this binary share process-wide environment variables.
static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

use agent686::session::{self, Session};

fn temp_dir(tag: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("agent686-sess-{tag}-{}", std::process::id()));
    let _ = fs::remove_dir_all(&dir);
    fs::create_dir_all(&dir).unwrap();
    dir
}

#[test]
fn sessions_create_list_and_replay() {
    let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let dir = temp_dir("roundtrip");
    std::env::set_var("AGENT686_DATA", &dir);

    let system = json!({ "role": "system", "content": "frozen" });
    let mut alpha = Session::create_as("alpha".into(), "model-a", &system).unwrap();
    assert!(
        Session::create_as("alpha".into(), "model-a", &system).is_err(),
        "duplicate ids must not overwrite a session"
    );

    alpha
        .append(&json!({ "role": "user", "content": "hello" }), None)
        .unwrap();
    alpha
        .append(
            &json!({ "role": "assistant", "content": "hi" }),
            Some("because"),
        )
        .unwrap();

    {
        use std::os::unix::fs::PermissionsExt;
        let mode = fs::metadata(alpha.path()).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "sessions must not be group/world readable");
    }

    assert!(session::exists("alpha"));
    assert!(!session::exists("nope"));

    let listed = session::list().unwrap();
    assert_eq!(listed.len(), 1);
    assert_eq!(listed[0].id, "alpha");
    assert_eq!(listed[0].model, "model-a");
    assert_eq!(listed[0].messages, 2);

    // A session holds an exclusive lock while open.
    drop(alpha);
    let (reopened, system_back, messages) = Session::open("alpha").unwrap();
    assert_eq!(reopened.id, "alpha");
    assert_eq!(system_back["content"], "frozen");
    assert_eq!(messages.len(), 2);
    assert_eq!(messages[1]["content"], "hi");
    // Reasoning is stored beside the message but must not be replayed.
    assert!(messages[1].get("_reasoning").is_none());
}

#[test]
fn cli_lists_sessions_without_a_key() {
    // Spawning holds a copy of the process's file descriptions between fork and
    // exec, which would keep a session lock alive while another test drops it.
    let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let dir = temp_dir("cli");
    let output = Command::new(env!("CARGO_BIN_EXE_agent686"))
        .env("AGENT686_DATA", &dir)
        .env_remove("OPENCODE_API_KEY")
        .arg("--list")
        .output()
        .unwrap();

    assert!(output.status.success(), "{output:?}");
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("no sessions"), "{stdout}");
}

#[test]
fn a_session_cannot_be_open_twice() {
    let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let dir = temp_dir("lock");
    std::env::set_var("AGENT686_DATA", &dir);

    let system = json!({ "role": "system", "content": "x" });
    let first = Session::create_as("locked".into(), "m", &system).unwrap();

    let error = Session::open("locked").err().expect("second open must fail");
    assert!(error.contains("already open"), "{error}");

    drop(first);
    Session::open("locked").expect("after the first handle closes it is available");
}

#[test]
fn listing_reports_the_model_in_use_after_a_switch() {
    let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let dir = temp_dir("model-switch");
    std::env::set_var("AGENT686_DATA", &dir);

    let system = json!({ "role": "system", "content": "x" });
    let mut session = Session::create_as("switch".into(), "model-a", &system).unwrap();
    session.record_model("model-b").unwrap();

    let listed = session::list().unwrap();
    assert_eq!(listed.len(), 1);
    assert_eq!(listed[0].model, "model-b");
}

#[test]
fn a_torn_utf8_line_does_not_brick_a_session() {
    let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let dir = temp_dir("torn");
    std::env::set_var("AGENT686_DATA", &dir);
    let sessions = dir.join("sessions");
    fs::create_dir_all(&sessions).unwrap();

    let mut raw = Vec::new();
    raw.extend_from_slice(
        br#"{"t":"header","session":"torn","model":"m","cwd":"/tmp","system":{"role":"system","content":"s"}}
"#,
    );
    raw.extend_from_slice(br#"{"t":"msg","role":"user","content":"hello"}
"#);
    // A killed write that split a multi-byte character.
    raw.extend_from_slice(b"{\"t\":\"msg\",\"role\":\"user\",\"content\":\"caf\xc3\"}\n");
    fs::write(sessions.join("torn.jsonl"), raw).unwrap();

    let (_session, _system, messages) = Session::open("torn").expect("torn line must not fail");
    // Lossy decoding keeps the message (with a replacement character) rather
    // than dropping a valid JSON line; what matters is that open succeeds.
    assert_eq!(messages.len(), 2);
    assert_eq!(messages[0]["content"], "hello");
    assert!(messages[1]["content"].as_str().unwrap().starts_with("caf"));
}

#[test]
fn last_reply_prefers_content_and_falls_back_to_reasoning() {
    let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let dir = temp_dir("last-reply");
    std::env::set_var("AGENT686_DATA", &dir);

    let system = json!({ "role": "system", "content": "x" });
    let mut session = Session::create_as("reply".into(), "m", &system).unwrap();
    session
        .append(
            &json!({ "role": "assistant", "content": "the answer" }),
            Some("the thinking"),
        )
        .unwrap();
    session
        .append(&json!({ "role": "assistant", "content": null }), Some("only thinking"))
        .unwrap();

    let reply = session::last_reply("reply").expect("there is a reply");
    assert_eq!(reply.content, "the answer", "prefers a real block");
    assert_eq!(reply.reasoning, "the thinking", "and its own reasoning");

    // With no content anywhere, reasoning is the fallback.
    let mut session = Session::create_as("reasoning-only".into(), "m", &system).unwrap();
    session
        .append(&json!({ "role": "assistant", "content": null }), Some("thoughts"))
        .unwrap();
    let reply = session::last_reply("reasoning-only").unwrap();
    assert!(reply.content.is_empty());
    assert_eq!(reply.reasoning, "thoughts");
}