Skip to main content

cellix_agent/
ide.rs

1//! The server Claude Code connects to when it treats Cellix as its IDE: MCP over a local
2//! WebSocket, announced by a lock file. Claude Code hasn't published this protocol, so it
3//! follows what its VS Code extension does.
4
5// tungstenite's handshake callback has to return its large error type.
6#![allow(clippy::result_large_err)]
7
8use std::fs;
9use std::io::{self, ErrorKind};
10use std::net::{Ipv4Addr, TcpListener, TcpStream};
11#[cfg(unix)]
12use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};
13use std::path::{Path, PathBuf};
14use std::sync::mpsc::{Receiver, Sender, channel};
15use std::sync::{Arc, Mutex};
16use std::thread;
17use std::time::Duration;
18
19use serde_json::{Value, json};
20use tungstenite::handshake::server::{ErrorResponse, Request, Response};
21use tungstenite::http::{HeaderValue, StatusCode};
22use tungstenite::{Message, WebSocket};
23
24use crate::new_token;
25
26const AUTH_HEADER: &str = "x-claude-code-ide-authorization";
27const SUBPROTOCOL: &str = "mcp";
28/// How long a connection waits for input before checking for notifications to send.
29const POLL: Duration = Duration::from_millis(50);
30
31/// Tools answered by the app, because they need its state. `openDiff` holds its reply
32/// until the reviewer decides.
33const TOOLS: [(&str, &str); 10] = [
34    ("openFile", "Open a file in Cellix"),
35    (
36        "openDiff",
37        "Show a proposed change and wait for the reviewer",
38    ),
39    ("getCurrentSelection", "The selection in the active editor"),
40    ("getLatestSelection", "The most recent selection"),
41    ("getOpenEditors", "The open tabs"),
42    ("getDiagnostics", "Language server errors and warnings"),
43    ("checkDocumentDirty", "Whether a file has unsaved edits"),
44    ("saveDocument", "Save a file"),
45    ("close_tab", "Close a proposed change"),
46    ("closeAllDiffTabs", "Close every proposed change"),
47];
48
49/// A tool call for the app. `reply` takes the text of each content item.
50#[derive(Debug)]
51pub struct IdeCall {
52    pub tool: String,
53    pub args: Value,
54    pub reply: Sender<Vec<String>>,
55}
56
57type Clients = Arc<Mutex<Vec<Sender<String>>>>;
58
59/// The running server. Dropping it removes the lock file, which is what hides this
60/// Cellix from `/ide`.
61pub struct IdeServer {
62    pub port: u16,
63    lock: PathBuf,
64    clients: Clients,
65    pub calls: Receiver<IdeCall>,
66}
67
68impl IdeServer {
69    /// The lock file that tells Claude Code this Cellix is here.
70    pub fn lock(&self) -> &Path {
71        &self.lock
72    }
73}
74
75impl Drop for IdeServer {
76    fn drop(&mut self) {
77        let _ = fs::remove_file(&self.lock);
78    }
79}
80
81fn config_dir() -> Option<PathBuf> {
82    let configured = std::env::var_os("CLAUDE_CONFIG_DIR").map(PathBuf::from);
83    configured.or_else(|| Some(PathBuf::from(std::env::var_os("HOME")?).join(".claude")))
84}
85
86/// A path as a file URL. A Windows path starts with its drive, `file:///C:/x`, and a share's
87/// names its server as the URL's host, `file://server/share/x`.
88pub fn file_url(path: &Path) -> String {
89    file_url_for(&path.display().to_string(), cfg!(windows))
90}
91
92fn file_url_for(text: &str, windows: bool) -> String {
93    if !windows {
94        return format!("file://{text}");
95    }
96    let text = text.replace('\\', "/");
97    match text.strip_prefix("//") {
98        Some(share) => format!("file://{share}"),
99        None => format!("file:///{text}"),
100    }
101}
102
103/// The path a file URL names, or the text as it is if it isn't one.
104pub fn url_path(text: &str) -> &str {
105    url_path_for(text, cfg!(windows))
106}
107
108fn url_path_for(text: &str, windows: bool) -> &str {
109    let Some(path) = text.strip_prefix("file://") else {
110        return text;
111    };
112    if !windows {
113        return path;
114    }
115    match path.strip_prefix('/') {
116        // `file:///C:/x` is `C:/x`, which Windows takes.
117        Some(rest) if rest.get(1..2) == Some(":") => rest,
118        // `file:////server/share` and `file://///server/share` are shares written the long way.
119        Some(rest) if rest.starts_with('/') => {
120            let names = rest.trim_start_matches('/');
121            &text[text.len() - names.len() - 2..]
122        }
123        Some(_) => path,
124        // `file://server/share/x` names a share, `//server/share/x`.
125        None => &text["file:".len()..],
126    }
127}
128
129/// A folder only this user can enter. On Windows, the user's profile already is one.
130fn private_folder(folder: &Path) -> io::Result<()> {
131    let mut builder = fs::DirBuilder::new();
132    builder.recursive(true);
133    #[cfg(unix)]
134    builder.mode(0o700);
135    builder.create(folder)
136}
137
138/// Writes a file only this user can read.
139fn write_private(file: &Path, bytes: &[u8]) -> io::Result<()> {
140    let mut options = fs::OpenOptions::new();
141    options.write(true).create(true).truncate(true);
142    #[cfg(unix)]
143    options.mode(0o600);
144    io::Write::write_all(&mut options.open(file)?, bytes)
145}
146
147impl IdeServer {
148    pub fn start(root: &Path) -> io::Result<Self> {
149        let config = config_dir().ok_or_else(|| io::Error::other("no home folder"))?;
150        Self::start_in(root, &config, None)
151    }
152
153    /// Starts on the port and token noted in `kept`, if it can, and notes what it used. An
154    /// agent that outlived the last Cellix was started pointing at that port, so this is the
155    /// only way it can find the next one.
156    pub fn start_kept(root: &Path, kept: &Path) -> io::Result<Self> {
157        let config = config_dir().ok_or_else(|| io::Error::other("no home folder"))?;
158        Self::start_in(root, &config, Some(kept))
159    }
160
161    fn start_in(root: &Path, config: &Path, kept: Option<&Path>) -> io::Result<Self> {
162        let noted: Option<Value> = kept
163            .and_then(|file| fs::read(file).ok())
164            .and_then(|bytes| serde_json::from_slice(&bytes).ok());
165        let old_port = noted.as_ref().and_then(|n| n["port"].as_u64());
166        let old_token = noted.as_ref().and_then(|n| n["token"].as_str());
167        let again = old_port
168            .and_then(|port| u16::try_from(port).ok())
169            .and_then(|port| TcpListener::bind((Ipv4Addr::LOCALHOST, port)).ok());
170        let reused = again.is_some();
171        let listener = match again {
172            Some(listener) => listener,
173            None => TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?,
174        };
175        let port = listener.local_addr()?.port();
176        let token = match old_token.filter(|_| reused) {
177            Some(token) => token.to_string(),
178            None => new_token()?,
179        };
180        if let Some(file) = kept {
181            if let Some(parent) = file.parent() {
182                private_folder(parent)?;
183            }
184            let noted = json!({"port": port, "token": token}).to_string();
185            write_private(file, noted.as_bytes())?;
186        }
187        let folder = config.join("ide");
188        private_folder(&folder)?;
189        let lock = folder.join(format!("{port}.lock"));
190        let contents = json!({
191            "pid": std::process::id(),
192            "workspaceFolders": [root],
193            "ideName": "Cellix",
194            "transport": "ws",
195            "authToken": token,
196        });
197        write_private(&lock, contents.to_string().as_bytes())?;
198        let (sender, calls) = channel();
199        let clients = Clients::default();
200        let shared = clients.clone();
201        let root = root.to_path_buf();
202        thread::spawn(move || {
203            for stream in listener.incoming().flatten() {
204                let context = (token.clone(), root.clone(), sender.clone(), shared.clone());
205                thread::spawn(move || connection(stream, context));
206            }
207        });
208        Ok(Self {
209            port,
210            lock,
211            clients,
212            calls,
213        })
214    }
215
216    /// Tells every connected client something changed.
217    pub fn notify(&self, method: &str, params: Value) {
218        let message = json!({"jsonrpc": "2.0", "method": method, "params": params}).to_string();
219        if let Ok(mut clients) = self.clients.lock() {
220            clients.retain(|client| client.send(message.clone()).is_ok());
221        }
222    }
223
224    pub fn connected(&self) -> bool {
225        self.clients.lock().is_ok_and(|c| !c.is_empty())
226    }
227}
228
229/// Only a client holding the token gets in. Browsers can't set this header, and refusing
230/// any Origin also keeps web pages off a port on localhost.
231fn authorize(
232    token: &str,
233    request: &Request,
234    mut response: Response,
235) -> Result<Response, ErrorResponse> {
236    let headers = request.headers();
237    let allowed = headers
238        .get(AUTH_HEADER)
239        .is_some_and(|value| value.as_bytes() == token.as_bytes());
240    if !allowed || headers.contains_key("origin") {
241        let mut refused = ErrorResponse::new(None);
242        *refused.status_mut() = StatusCode::UNAUTHORIZED;
243        return Err(refused);
244    }
245    let asked = headers
246        .get("sec-websocket-protocol")
247        .and_then(|value| value.to_str().ok())
248        .is_some_and(|value| value.split(',').any(|p| p.trim() == SUBPROTOCOL));
249    if asked {
250        response.headers_mut().insert(
251            "sec-websocket-protocol",
252            HeaderValue::from_static(SUBPROTOCOL),
253        );
254    }
255    Ok(response)
256}
257
258fn connection(stream: TcpStream, context: (String, PathBuf, Sender<IdeCall>, Clients)) {
259    let (token, root, calls, clients) = context;
260    let _ = stream.set_nodelay(true);
261    let check = |request: &Request, response: Response| authorize(&token, request, response);
262    let Ok(mut socket) = tungstenite::accept_hdr(stream, check) else {
263        return;
264    };
265    let (outgoing, queue) = channel();
266    if let Ok(mut clients) = clients.lock() {
267        clients.push(outgoing.clone());
268    }
269    if socket.get_ref().set_read_timeout(Some(POLL)).is_ok() {
270        let _ = pump(&mut socket, &queue, &outgoing, &root, &calls);
271    }
272    // Sends fail once `queue` drops, and the next notification clears this client out.
273    drop(queue);
274    if let Ok(mut clients) = clients.lock() {
275        clients.retain(|client| client.send(String::new()).is_ok());
276    }
277}
278
279fn pump(
280    socket: &mut WebSocket<TcpStream>,
281    queue: &Receiver<String>,
282    outgoing: &Sender<String>,
283    root: &Path,
284    calls: &Sender<IdeCall>,
285) -> tungstenite::Result<()> {
286    loop {
287        match socket.read() {
288            Ok(Message::Text(text)) => {
289                if let Some(reply) = answer(text.as_str(), root, calls, outgoing) {
290                    socket.send(Message::text(reply))?;
291                }
292            }
293            Ok(Message::Close(_)) => return Ok(()),
294            Ok(_) => {}
295            Err(tungstenite::Error::Io(e))
296                if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {}
297            Err(e) => return Err(e),
298        }
299        while let Ok(message) = queue.try_recv() {
300            if !message.is_empty() {
301                socket.send(Message::text(message))?;
302            }
303        }
304    }
305}
306
307fn result(id: &Value, result: Value) -> String {
308    json!({"jsonrpc": "2.0", "id": id, "result": result}).to_string()
309}
310
311fn tool_list() -> Value {
312    let open = json!({"type": "object", "additionalProperties": true});
313    let mut tools: Vec<Value> = TOOLS
314        .iter()
315        .map(|(name, description)| {
316            json!({"name": name, "description": description, "inputSchema": open})
317        })
318        .collect();
319    let folders = ("getWorkspaceFolders", "The folders Cellix has open");
320    tools.push(json!({"name": folders.0, "description": folders.1, "inputSchema": open}));
321    json!({"tools": tools})
322}
323
324fn content(texts: Vec<String>) -> Value {
325    let items: Vec<Value> = texts
326        .into_iter()
327        .map(|text| json!({"type": "text", "text": text}))
328        .collect();
329    json!({"content": items})
330}
331
332fn workspace_folders(root: &Path) -> String {
333    let name = root.file_name().unwrap_or_default().to_string_lossy();
334    json!({
335        "success": true,
336        "folders": [{"name": name, "uri": file_url(root), "path": root}],
337        "rootPath": root,
338    })
339    .to_string()
340}
341
342/// Answers one message, or returns None for notifications and for calls that finish later.
343fn answer(
344    text: &str,
345    root: &Path,
346    calls: &Sender<IdeCall>,
347    outgoing: &Sender<String>,
348) -> Option<String> {
349    let message: Value = serde_json::from_str(text).ok()?;
350    let id = message.get("id")?;
351    let params = &message["params"];
352    Some(match message["method"].as_str()? {
353        "initialize" => {
354            let version = params["protocolVersion"].as_str().unwrap_or("2025-03-26");
355            result(
356                id,
357                json!({
358                    "protocolVersion": version,
359                    "capabilities": {"tools": {"listChanged": false}},
360                    "serverInfo": {"name": "cellix", "version": env!("CARGO_PKG_VERSION")},
361                }),
362            )
363        }
364        "ping" => result(id, json!({})),
365        "tools/list" => result(id, tool_list()),
366        "prompts/list" => result(id, json!({"prompts": []})),
367        "resources/list" => result(id, json!({"resources": []})),
368        "tools/call" => {
369            let tool = params["name"].as_str().unwrap_or_default().to_string();
370            if tool == "getWorkspaceFolders" {
371                return Some(result(id, content(vec![workspace_folders(root)])));
372            }
373            let args = params["arguments"].clone();
374            let (reply, done) = channel();
375            let fallback = tool_fallback(&tool, &args);
376            if calls.send(IdeCall { tool, args, reply }).is_ok() {
377                crate::wake();
378            }
379            // On its own thread, because a diff can wait for as long as the reviewer takes.
380            let (id, outgoing) = (id.clone(), outgoing.clone());
381            thread::spawn(move || {
382                let texts = done.recv().unwrap_or(fallback);
383                let _ = outgoing.send(result(&id, content(texts)));
384            });
385            return None;
386        }
387        method => json!({
388            "jsonrpc": "2.0",
389            "id": id,
390            "error": {"code": -32601, "message": format!("Unknown method {method}")},
391        })
392        .to_string(),
393    })
394}
395
396/// What a call answers if the app goes away first. Nothing was approved, so nothing is.
397fn tool_fallback(tool: &str, args: &Value) -> Vec<String> {
398    if tool == "openDiff" {
399        let tab = args["tab_name"].as_str().unwrap_or_default().to_string();
400        vec!["DIFF_REJECTED".to_string(), tab]
401    } else {
402        vec!["Cellix closed before answering".to_string()]
403    }
404}
405
406#[cfg(test)]
407mod tests {
408    use super::*;
409
410    #[test]
411    fn the_next_cellix_takes_the_same_port_and_token() {
412        // Between freeing a port and taking it again, another test or program on a busy
413        // machine can take it, which is the case `a_port_someone_else_took_is_given_up` covers.
414        // Only that is tried again; anything else fails as before.
415        for _ in 0..5 {
416            let dir = tempfile::tempdir().unwrap();
417            let root = dir.path().join("project");
418            let kept = dir.path().join("held/ide.json");
419            // The port a Cellix that has since quit was on.
420            let free = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
421            let port = free.local_addr().unwrap().port();
422            drop(free);
423            fs::create_dir_all(kept.parent().unwrap()).unwrap();
424            let noted = json!({"port": port, "token": "kept-token"}).to_string();
425            fs::write(&kept, noted).unwrap();
426            let next = IdeServer::start_in(&root, dir.path(), Some(&kept)).unwrap();
427            let taken =
428                next.port != port && TcpListener::bind((Ipv4Addr::LOCALHOST, port)).is_err();
429            if taken {
430                continue;
431            }
432            assert_eq!(next.port, port);
433            assert_eq!(lock_of(dir.path(), port)["authToken"], "kept-token");
434            return;
435        }
436        panic!("something else took the freed port five times running");
437    }
438
439    #[test]
440    fn a_port_someone_else_took_is_given_up() {
441        let dir = tempfile::tempdir().unwrap();
442        let root = dir.path().join("project");
443        let kept = dir.path().join("ide.json");
444        let first = IdeServer::start_in(&root, dir.path(), Some(&kept)).unwrap();
445        // Still running, so the port's taken: a second window here gets its own.
446        let second = IdeServer::start_in(&root, dir.path(), Some(&kept)).unwrap();
447        assert_ne!(first.port, second.port);
448        let (first_token, second_token) = (
449            lock_of(dir.path(), first.port)["authToken"].clone(),
450            lock_of(dir.path(), second.port)["authToken"].clone(),
451        );
452        assert_ne!(first_token, second_token, "a token goes with its port");
453    }
454    use tungstenite::client::IntoClientRequest;
455    use tungstenite::stream::MaybeTlsStream;
456
457    type Client = WebSocket<MaybeTlsStream<TcpStream>>;
458
459    fn lock_of(config: &Path, port: u16) -> Value {
460        let lock = config.join("ide").join(format!("{port}.lock"));
461        serde_json::from_str(&fs::read_to_string(lock).unwrap()).unwrap()
462    }
463
464    fn connect(port: u16, token: &str) -> tungstenite::Result<Client> {
465        let mut request = format!("ws://127.0.0.1:{port}")
466            .into_client_request()
467            .unwrap();
468        let headers = request.headers_mut();
469        headers.insert(AUTH_HEADER, token.parse().unwrap());
470        headers.insert("sec-websocket-protocol", "mcp".parse().unwrap());
471        let (client, response) = tungstenite::connect(request)?;
472        assert_eq!(response.headers()["sec-websocket-protocol"], SUBPROTOCOL);
473        Ok(client)
474    }
475
476    fn start() -> (tempfile::TempDir, IdeServer, Client) {
477        let dir = tempfile::tempdir().unwrap();
478        let server = IdeServer::start_in(dir.path(), dir.path(), None).unwrap();
479        let token = lock_of(dir.path(), server.port)["authToken"]
480            .as_str()
481            .unwrap()
482            .to_string();
483        let client = connect(server.port, &token).unwrap();
484        (dir, server, client)
485    }
486
487    fn call(client: &mut Client, id: u32, method: &str, params: Value) -> Value {
488        let message = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params});
489        client.send(Message::text(message.to_string())).unwrap();
490        read(client)
491    }
492
493    fn read(client: &mut Client) -> Value {
494        let message = client.read().unwrap();
495        serde_json::from_str(message.to_text().unwrap()).unwrap()
496    }
497
498    #[test]
499    fn claude_code_can_connect_and_list_tools() {
500        let (dir, server, mut client) = start();
501        let lock = lock_of(dir.path(), server.port);
502        assert_eq!(lock["ideName"], "Cellix");
503        assert_eq!(lock["transport"], "ws");
504        assert_eq!(lock["authToken"].as_str().unwrap().len(), 32);
505        let init = call(
506            &mut client,
507            1,
508            "initialize",
509            json!({"protocolVersion": "2025-06-18"}),
510        );
511        assert_eq!(init["result"]["protocolVersion"], "2025-06-18");
512        let tools = call(&mut client, 2, "tools/list", json!({}));
513        let names: Vec<&str> = tools["result"]["tools"]
514            .as_array()
515            .unwrap()
516            .iter()
517            .map(|t| t["name"].as_str().unwrap())
518            .collect();
519        for name in [
520            "openDiff",
521            "openFile",
522            "getDiagnostics",
523            "getWorkspaceFolders",
524        ] {
525            assert!(names.contains(&name), "{name}");
526        }
527        let folders = call(
528            &mut client,
529            3,
530            "tools/call",
531            json!({"name": "getWorkspaceFolders", "arguments": {}}),
532        );
533        let text = folders["result"]["content"][0]["text"].as_str().unwrap();
534        let reply: Value = serde_json::from_str(text).unwrap();
535        let folder = &reply["folders"][0];
536        assert_eq!(folder["path"], json!(dir.path()), "{text}");
537        assert_eq!(folder["uri"], file_url(dir.path()), "{text}");
538        let unknown = call(&mut client, 4, "nonsense", json!({}));
539        assert_eq!(unknown["error"]["code"], -32601);
540    }
541
542    #[test]
543    fn a_wrong_token_or_a_web_page_is_refused() {
544        let dir = tempfile::tempdir().unwrap();
545        let server = IdeServer::start_in(dir.path(), dir.path(), None).unwrap();
546        assert!(connect(server.port, "wrong").is_err());
547        let token = lock_of(dir.path(), server.port)["authToken"]
548            .as_str()
549            .unwrap()
550            .to_string();
551        let mut request = format!("ws://127.0.0.1:{}", server.port)
552            .into_client_request()
553            .unwrap();
554        request
555            .headers_mut()
556            .insert(AUTH_HEADER, token.parse().unwrap());
557        request
558            .headers_mut()
559            .insert("origin", "https://evil.example".parse().unwrap());
560        assert!(tungstenite::connect(request).is_err());
561    }
562
563    #[test]
564    fn file_urls_go_both_ways() {
565        let path = std::env::temp_dir().join("notes").join("a.md");
566        assert_eq!(Path::new(url_path(&file_url(&path))), path);
567        assert_eq!(url_path("docs/a.md"), "docs/a.md");
568        #[cfg(windows)]
569        assert_eq!(file_url(Path::new(r"C:\x\y.md")), "file:///C:/x/y.md");
570        #[cfg(unix)]
571        assert_eq!(file_url(Path::new("/x/y.md")), "file:///x/y.md");
572    }
573
574    /// Windows paths, drives and shares alike, on every platform.
575    #[test]
576    fn windows_file_urls_name_drives_and_shares() {
577        let cases = [
578            (r"C:\x\y.md", "file:///C:/x/y.md", "C:/x/y.md"),
579            (
580                r"\\server\share\y.md",
581                "file://server/share/y.md",
582                "//server/share/y.md",
583            ),
584        ];
585        for (path, url, back) in cases {
586            assert_eq!(file_url_for(path, true), url);
587            assert_eq!(url_path_for(url, true), back);
588        }
589        assert_eq!(
590            url_path_for("file://///server/share/y.md", true),
591            "//server/share/y.md"
592        );
593        assert_eq!(
594            url_path_for("file:////server/share/y.md", true),
595            "//server/share/y.md"
596        );
597        assert_eq!(url_path_for("file:///x/y.md", false), "/x/y.md");
598    }
599
600    #[test]
601    fn the_lock_file_is_private_and_goes_away() {
602        let dir = tempfile::tempdir().unwrap();
603        let server = IdeServer::start_in(dir.path(), dir.path(), None).unwrap();
604        let path = dir.path().join("ide").join(format!("{}.lock", server.port));
605        // Windows has no modes: the lock is private because the user's profile is.
606        #[cfg(unix)]
607        {
608            use std::os::unix::fs::PermissionsExt;
609            let mode = fs::metadata(&path).unwrap().permissions().mode();
610            assert_eq!(mode & 0o777, 0o600);
611        }
612        assert!(path.exists());
613        drop(server);
614        assert!(!path.exists());
615    }
616
617    #[test]
618    fn open_diff_waits_for_the_reviewer() {
619        let (_dir, server, mut client) = start();
620        let params = json!({"name": "openDiff", "arguments": {"tab_name": "t"}});
621        let message = json!({"jsonrpc": "2.0", "id": 9, "method": "tools/call", "params": params});
622        client.send(Message::text(message.to_string())).unwrap();
623        let waiting = server.calls.recv_timeout(Duration::from_secs(5)).unwrap();
624        assert_eq!(waiting.tool, "openDiff");
625        // A selection still gets through while the diff is open.
626        server.notify("selection_changed", json!({"text": "x"}));
627        assert_eq!(read(&mut client)["method"], "selection_changed");
628        waiting
629            .reply
630            .send(vec!["FILE_SAVED".into(), "new".into()])
631            .unwrap();
632        let done = read(&mut client);
633        assert_eq!(done["id"], 9);
634        assert_eq!(done["result"]["content"][1]["text"], "new");
635    }
636
637    #[test]
638    fn a_diff_abandoned_by_the_app_is_rejected() {
639        let (_dir, server, mut client) = start();
640        let params = json!({"name": "openDiff", "arguments": {"tab_name": "t"}});
641        let message = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": params});
642        client.send(Message::text(message.to_string())).unwrap();
643        drop(server.calls.recv_timeout(Duration::from_secs(5)).unwrap());
644        let done = read(&mut client);
645        assert_eq!(done["result"]["content"][0]["text"], "DIFF_REJECTED");
646    }
647}