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            let _ = calls.send(IdeCall { tool, args, reply });
377            // On its own thread, because a diff can wait for as long as the reviewer takes.
378            let (id, outgoing) = (id.clone(), outgoing.clone());
379            thread::spawn(move || {
380                let texts = done.recv().unwrap_or(fallback);
381                let _ = outgoing.send(result(&id, content(texts)));
382            });
383            return None;
384        }
385        method => json!({
386            "jsonrpc": "2.0",
387            "id": id,
388            "error": {"code": -32601, "message": format!("Unknown method {method}")},
389        })
390        .to_string(),
391    })
392}
393
394/// What a call answers if the app goes away first. Nothing was approved, so nothing is.
395fn tool_fallback(tool: &str, args: &Value) -> Vec<String> {
396    if tool == "openDiff" {
397        let tab = args["tab_name"].as_str().unwrap_or_default().to_string();
398        vec!["DIFF_REJECTED".to_string(), tab]
399    } else {
400        vec!["Cellix closed before answering".to_string()]
401    }
402}
403
404#[cfg(test)]
405mod tests {
406    use super::*;
407
408    #[test]
409    fn the_next_cellix_takes_the_same_port_and_token() {
410        // Between freeing a port and taking it again, another test or program on a busy
411        // machine can take it, which is the case `a_port_someone_else_took_is_given_up` covers.
412        // Only that is tried again; anything else fails as before.
413        for _ in 0..5 {
414            let dir = tempfile::tempdir().unwrap();
415            let root = dir.path().join("project");
416            let kept = dir.path().join("held/ide.json");
417            // The port a Cellix that has since quit was on.
418            let free = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
419            let port = free.local_addr().unwrap().port();
420            drop(free);
421            fs::create_dir_all(kept.parent().unwrap()).unwrap();
422            let noted = json!({"port": port, "token": "kept-token"}).to_string();
423            fs::write(&kept, noted).unwrap();
424            let next = IdeServer::start_in(&root, dir.path(), Some(&kept)).unwrap();
425            let taken =
426                next.port != port && TcpListener::bind((Ipv4Addr::LOCALHOST, port)).is_err();
427            if taken {
428                continue;
429            }
430            assert_eq!(next.port, port);
431            assert_eq!(lock_of(dir.path(), port)["authToken"], "kept-token");
432            return;
433        }
434        panic!("something else took the freed port five times running");
435    }
436
437    #[test]
438    fn a_port_someone_else_took_is_given_up() {
439        let dir = tempfile::tempdir().unwrap();
440        let root = dir.path().join("project");
441        let kept = dir.path().join("ide.json");
442        let first = IdeServer::start_in(&root, dir.path(), Some(&kept)).unwrap();
443        // Still running, so the port's taken: a second window here gets its own.
444        let second = IdeServer::start_in(&root, dir.path(), Some(&kept)).unwrap();
445        assert_ne!(first.port, second.port);
446        let (first_token, second_token) = (
447            lock_of(dir.path(), first.port)["authToken"].clone(),
448            lock_of(dir.path(), second.port)["authToken"].clone(),
449        );
450        assert_ne!(first_token, second_token, "a token goes with its port");
451    }
452    use tungstenite::client::IntoClientRequest;
453    use tungstenite::stream::MaybeTlsStream;
454
455    type Client = WebSocket<MaybeTlsStream<TcpStream>>;
456
457    fn lock_of(config: &Path, port: u16) -> Value {
458        let lock = config.join("ide").join(format!("{port}.lock"));
459        serde_json::from_str(&fs::read_to_string(lock).unwrap()).unwrap()
460    }
461
462    fn connect(port: u16, token: &str) -> tungstenite::Result<Client> {
463        let mut request = format!("ws://127.0.0.1:{port}")
464            .into_client_request()
465            .unwrap();
466        let headers = request.headers_mut();
467        headers.insert(AUTH_HEADER, token.parse().unwrap());
468        headers.insert("sec-websocket-protocol", "mcp".parse().unwrap());
469        let (client, response) = tungstenite::connect(request)?;
470        assert_eq!(response.headers()["sec-websocket-protocol"], SUBPROTOCOL);
471        Ok(client)
472    }
473
474    fn start() -> (tempfile::TempDir, IdeServer, Client) {
475        let dir = tempfile::tempdir().unwrap();
476        let server = IdeServer::start_in(dir.path(), dir.path(), None).unwrap();
477        let token = lock_of(dir.path(), server.port)["authToken"]
478            .as_str()
479            .unwrap()
480            .to_string();
481        let client = connect(server.port, &token).unwrap();
482        (dir, server, client)
483    }
484
485    fn call(client: &mut Client, id: u32, method: &str, params: Value) -> Value {
486        let message = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params});
487        client.send(Message::text(message.to_string())).unwrap();
488        read(client)
489    }
490
491    fn read(client: &mut Client) -> Value {
492        let message = client.read().unwrap();
493        serde_json::from_str(message.to_text().unwrap()).unwrap()
494    }
495
496    #[test]
497    fn claude_code_can_connect_and_list_tools() {
498        let (dir, server, mut client) = start();
499        let lock = lock_of(dir.path(), server.port);
500        assert_eq!(lock["ideName"], "Cellix");
501        assert_eq!(lock["transport"], "ws");
502        assert_eq!(lock["authToken"].as_str().unwrap().len(), 32);
503        let init = call(
504            &mut client,
505            1,
506            "initialize",
507            json!({"protocolVersion": "2025-06-18"}),
508        );
509        assert_eq!(init["result"]["protocolVersion"], "2025-06-18");
510        let tools = call(&mut client, 2, "tools/list", json!({}));
511        let names: Vec<&str> = tools["result"]["tools"]
512            .as_array()
513            .unwrap()
514            .iter()
515            .map(|t| t["name"].as_str().unwrap())
516            .collect();
517        for name in [
518            "openDiff",
519            "openFile",
520            "getDiagnostics",
521            "getWorkspaceFolders",
522        ] {
523            assert!(names.contains(&name), "{name}");
524        }
525        let folders = call(
526            &mut client,
527            3,
528            "tools/call",
529            json!({"name": "getWorkspaceFolders", "arguments": {}}),
530        );
531        let text = folders["result"]["content"][0]["text"].as_str().unwrap();
532        let reply: Value = serde_json::from_str(text).unwrap();
533        let folder = &reply["folders"][0];
534        assert_eq!(folder["path"], json!(dir.path()), "{text}");
535        assert_eq!(folder["uri"], file_url(dir.path()), "{text}");
536        let unknown = call(&mut client, 4, "nonsense", json!({}));
537        assert_eq!(unknown["error"]["code"], -32601);
538    }
539
540    #[test]
541    fn a_wrong_token_or_a_web_page_is_refused() {
542        let dir = tempfile::tempdir().unwrap();
543        let server = IdeServer::start_in(dir.path(), dir.path(), None).unwrap();
544        assert!(connect(server.port, "wrong").is_err());
545        let token = lock_of(dir.path(), server.port)["authToken"]
546            .as_str()
547            .unwrap()
548            .to_string();
549        let mut request = format!("ws://127.0.0.1:{}", server.port)
550            .into_client_request()
551            .unwrap();
552        request
553            .headers_mut()
554            .insert(AUTH_HEADER, token.parse().unwrap());
555        request
556            .headers_mut()
557            .insert("origin", "https://evil.example".parse().unwrap());
558        assert!(tungstenite::connect(request).is_err());
559    }
560
561    #[test]
562    fn file_urls_go_both_ways() {
563        let path = std::env::temp_dir().join("notes").join("a.md");
564        assert_eq!(Path::new(url_path(&file_url(&path))), path);
565        assert_eq!(url_path("docs/a.md"), "docs/a.md");
566        #[cfg(windows)]
567        assert_eq!(file_url(Path::new(r"C:\x\y.md")), "file:///C:/x/y.md");
568        #[cfg(unix)]
569        assert_eq!(file_url(Path::new("/x/y.md")), "file:///x/y.md");
570    }
571
572    /// Windows paths, drives and shares alike, on every platform.
573    #[test]
574    fn windows_file_urls_name_drives_and_shares() {
575        let cases = [
576            (r"C:\x\y.md", "file:///C:/x/y.md", "C:/x/y.md"),
577            (
578                r"\\server\share\y.md",
579                "file://server/share/y.md",
580                "//server/share/y.md",
581            ),
582        ];
583        for (path, url, back) in cases {
584            assert_eq!(file_url_for(path, true), url);
585            assert_eq!(url_path_for(url, true), back);
586        }
587        assert_eq!(
588            url_path_for("file://///server/share/y.md", true),
589            "//server/share/y.md"
590        );
591        assert_eq!(
592            url_path_for("file:////server/share/y.md", true),
593            "//server/share/y.md"
594        );
595        assert_eq!(url_path_for("file:///x/y.md", false), "/x/y.md");
596    }
597
598    #[test]
599    fn the_lock_file_is_private_and_goes_away() {
600        let dir = tempfile::tempdir().unwrap();
601        let server = IdeServer::start_in(dir.path(), dir.path(), None).unwrap();
602        let path = dir.path().join("ide").join(format!("{}.lock", server.port));
603        // Windows has no modes: the lock is private because the user's profile is.
604        #[cfg(unix)]
605        {
606            use std::os::unix::fs::PermissionsExt;
607            let mode = fs::metadata(&path).unwrap().permissions().mode();
608            assert_eq!(mode & 0o777, 0o600);
609        }
610        assert!(path.exists());
611        drop(server);
612        assert!(!path.exists());
613    }
614
615    #[test]
616    fn open_diff_waits_for_the_reviewer() {
617        let (_dir, server, mut client) = start();
618        let params = json!({"name": "openDiff", "arguments": {"tab_name": "t"}});
619        let message = json!({"jsonrpc": "2.0", "id": 9, "method": "tools/call", "params": params});
620        client.send(Message::text(message.to_string())).unwrap();
621        let waiting = server.calls.recv_timeout(Duration::from_secs(5)).unwrap();
622        assert_eq!(waiting.tool, "openDiff");
623        // A selection still gets through while the diff is open.
624        server.notify("selection_changed", json!({"text": "x"}));
625        assert_eq!(read(&mut client)["method"], "selection_changed");
626        waiting
627            .reply
628            .send(vec!["FILE_SAVED".into(), "new".into()])
629            .unwrap();
630        let done = read(&mut client);
631        assert_eq!(done["id"], 9);
632        assert_eq!(done["result"]["content"][1]["text"], "new");
633    }
634
635    #[test]
636    fn a_diff_abandoned_by_the_app_is_rejected() {
637        let (_dir, server, mut client) = start();
638        let params = json!({"name": "openDiff", "arguments": {"tab_name": "t"}});
639        let message = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": params});
640        client.send(Message::text(message.to_string())).unwrap();
641        drop(server.calls.recv_timeout(Duration::from_secs(5)).unwrap());
642        let done = read(&mut client);
643        assert_eq!(done["result"]["content"][0]["text"], "DIFF_REJECTED");
644    }
645}