1mod mcp_server;
2pub mod tools;
3
4use collections::HashMap;
5use context_server::listener::McpServerTool;
6use project::Project;
7use settings::SettingsStore;
8use smol::process::Child;
9use std::cell::RefCell;
10use std::fmt::Display;
11use std::path::Path;
12use std::rc::Rc;
13use uuid::Uuid;
14
15use agent_client_protocol as acp;
16use anyhow::{Result, anyhow};
17use futures::channel::oneshot;
18use futures::{AsyncBufReadExt, AsyncWriteExt};
19use futures::{
20 AsyncRead, AsyncWrite, FutureExt, StreamExt,
21 channel::mpsc::{self, UnboundedReceiver, UnboundedSender},
22 io::BufReader,
23 select_biased,
24};
25use gpui::{App, AppContext, AsyncApp, Entity, Task, WeakEntity};
26use serde::{Deserialize, Serialize};
27use util::ResultExt;
28
29use crate::claude::mcp_server::{ClaudeZedMcpServer, McpConfig};
30use crate::claude::tools::ClaudeTool;
31use crate::{AgentServer, AgentServerCommand, AllAgentServersSettings};
32use acp_thread::{AcpThread, AgentConnection};
33
34#[derive(Clone)]
35pub struct ClaudeCode;
36
37impl AgentServer for ClaudeCode {
38 fn name(&self) -> &'static str {
39 "Claude Code"
40 }
41
42 fn empty_state_headline(&self) -> &'static str {
43 self.name()
44 }
45
46 fn empty_state_message(&self) -> &'static str {
47 "How can I help you today?"
48 }
49
50 fn logo(&self) -> ui::IconName {
51 ui::IconName::AiClaude
52 }
53
54 fn connect(
55 &self,
56 _root_dir: &Path,
57 _project: &Entity<Project>,
58 _cx: &mut App,
59 ) -> Task<Result<Rc<dyn AgentConnection>>> {
60 let connection = ClaudeAgentConnection {
61 sessions: Default::default(),
62 };
63
64 Task::ready(Ok(Rc::new(connection) as _))
65 }
66}
67
68struct ClaudeAgentConnection {
69 sessions: Rc<RefCell<HashMap<acp::SessionId, ClaudeAgentSession>>>,
70}
71
72impl AgentConnection for ClaudeAgentConnection {
73 fn new_thread(
74 self: Rc<Self>,
75 project: Entity<Project>,
76 cwd: &Path,
77 cx: &mut AsyncApp,
78 ) -> Task<Result<Entity<AcpThread>>> {
79 let cwd = cwd.to_owned();
80 cx.spawn(async move |cx| {
81 let (mut thread_tx, thread_rx) = watch::channel(WeakEntity::new_invalid());
82 let permission_mcp_server = ClaudeZedMcpServer::new(thread_rx.clone(), cx).await?;
83
84 let mut mcp_servers = HashMap::default();
85 mcp_servers.insert(
86 mcp_server::SERVER_NAME.to_string(),
87 permission_mcp_server.server_config()?,
88 );
89 let mcp_config = McpConfig { mcp_servers };
90
91 let mcp_config_file = tempfile::NamedTempFile::new()?;
92 let (mcp_config_file, mcp_config_path) = mcp_config_file.into_parts();
93
94 let mut mcp_config_file = smol::fs::File::from(mcp_config_file);
95 mcp_config_file
96 .write_all(serde_json::to_string(&mcp_config)?.as_bytes())
97 .await?;
98 mcp_config_file.flush().await?;
99
100 let settings = cx.read_global(|settings: &SettingsStore, _| {
101 settings.get::<AllAgentServersSettings>(None).claude.clone()
102 })?;
103
104 let Some(command) = AgentServerCommand::resolve(
105 "claude",
106 &[],
107 Some(&util::paths::home_dir().join(".claude/local/claude")),
108 settings,
109 &project,
110 cx,
111 )
112 .await
113 else {
114 anyhow::bail!("Failed to find claude binary");
115 };
116
117 let (incoming_message_tx, mut incoming_message_rx) = mpsc::unbounded();
118 let (outgoing_tx, outgoing_rx) = mpsc::unbounded();
119
120 let session_id = acp::SessionId(Uuid::new_v4().to_string().into());
121
122 log::trace!("Starting session with id: {}", session_id);
123
124 let mut child = spawn_claude(
125 &command,
126 ClaudeSessionMode::Start,
127 session_id.clone(),
128 &mcp_config_path,
129 &cwd,
130 )?;
131
132 let stdin = child.stdin.take().unwrap();
133 let stdout = child.stdout.take().unwrap();
134
135 let pid = child.id();
136 log::trace!("Spawned (pid: {})", pid);
137
138 cx.background_spawn(async move {
139 let mut outgoing_rx = Some(outgoing_rx);
140
141 ClaudeAgentSession::handle_io(
142 outgoing_rx.take().unwrap(),
143 incoming_message_tx.clone(),
144 stdin,
145 stdout,
146 )
147 .await?;
148
149 log::trace!("Stopped (pid: {})", pid);
150
151 drop(mcp_config_path);
152 anyhow::Ok(())
153 })
154 .detach();
155
156 let end_turn_tx = Rc::new(RefCell::new(None));
157 let handler_task = cx.spawn({
158 let end_turn_tx = end_turn_tx.clone();
159 let mut thread_rx = thread_rx.clone();
160 async move |cx| {
161 while let Some(message) = incoming_message_rx.next().await {
162 ClaudeAgentSession::handle_message(
163 thread_rx.clone(),
164 message,
165 end_turn_tx.clone(),
166 cx,
167 )
168 .await
169 }
170
171 if let Some(status) = child.status().await.log_err() {
172 if let Some(thread) = thread_rx.recv().await.ok() {
173 thread
174 .update(cx, |thread, cx| {
175 thread.emit_server_exited(status, cx);
176 })
177 .ok();
178 }
179 }
180 }
181 });
182
183 let thread = cx.new(|cx| {
184 AcpThread::new("Claude Code", self.clone(), project, session_id.clone(), cx)
185 })?;
186
187 thread_tx.send(thread.downgrade())?;
188
189 let session = ClaudeAgentSession {
190 outgoing_tx,
191 end_turn_tx,
192 _handler_task: handler_task,
193 _mcp_server: Some(permission_mcp_server),
194 };
195
196 self.sessions.borrow_mut().insert(session_id, session);
197
198 Ok(thread)
199 })
200 }
201
202 fn auth_methods(&self) -> &[acp::AuthMethod] {
203 &[]
204 }
205
206 fn authenticate(&self, _: acp::AuthMethodId, _cx: &mut App) -> Task<Result<()>> {
207 Task::ready(Err(anyhow!("Authentication not supported")))
208 }
209
210 fn prompt(
211 &self,
212 params: acp::PromptRequest,
213 cx: &mut App,
214 ) -> Task<Result<acp::PromptResponse>> {
215 let sessions = self.sessions.borrow();
216 let Some(session) = sessions.get(¶ms.session_id) else {
217 return Task::ready(Err(anyhow!(
218 "Attempted to send message to nonexistent session {}",
219 params.session_id
220 )));
221 };
222
223 let (tx, rx) = oneshot::channel();
224 session.end_turn_tx.borrow_mut().replace(tx);
225
226 let mut content = String::new();
227 for chunk in params.prompt {
228 match chunk {
229 acp::ContentBlock::Text(text_content) => {
230 content.push_str(&text_content.text);
231 }
232 acp::ContentBlock::ResourceLink(resource_link) => {
233 content.push_str(&format!("@{}", resource_link.uri));
234 }
235 acp::ContentBlock::Audio(_)
236 | acp::ContentBlock::Image(_)
237 | acp::ContentBlock::Resource(_) => {
238 // TODO
239 }
240 }
241 }
242
243 if let Err(err) = session.outgoing_tx.unbounded_send(SdkMessage::User {
244 message: Message {
245 role: Role::User,
246 content: Content::UntaggedText(content),
247 id: None,
248 model: None,
249 stop_reason: None,
250 stop_sequence: None,
251 usage: None,
252 },
253 session_id: Some(params.session_id.to_string()),
254 }) {
255 return Task::ready(Err(anyhow!(err)));
256 }
257
258 cx.foreground_executor().spawn(async move { rx.await? })
259 }
260
261 fn cancel(&self, session_id: &acp::SessionId, _cx: &mut App) {
262 let sessions = self.sessions.borrow();
263 let Some(session) = sessions.get(&session_id) else {
264 log::warn!("Attempted to cancel nonexistent session {}", session_id);
265 return;
266 };
267
268 session
269 .outgoing_tx
270 .unbounded_send(SdkMessage::new_interrupt_message())
271 .log_err();
272
273 if let Some(end_turn_tx) = session.end_turn_tx.borrow_mut().take() {
274 end_turn_tx
275 .send(Ok(acp::PromptResponse {
276 stop_reason: acp::StopReason::Cancelled,
277 }))
278 .ok();
279 }
280 }
281}
282
283#[derive(Clone, Copy)]
284enum ClaudeSessionMode {
285 Start,
286 #[expect(dead_code)]
287 Resume,
288}
289
290fn spawn_claude(
291 command: &AgentServerCommand,
292 mode: ClaudeSessionMode,
293 session_id: acp::SessionId,
294 mcp_config_path: &Path,
295 root_dir: &Path,
296) -> Result<Child> {
297 let child = util::command::new_smol_command(&command.path)
298 .args([
299 "--input-format",
300 "stream-json",
301 "--output-format",
302 "stream-json",
303 "--print",
304 "--verbose",
305 "--mcp-config",
306 mcp_config_path.to_string_lossy().as_ref(),
307 "--permission-prompt-tool",
308 &format!(
309 "mcp__{}__{}",
310 mcp_server::SERVER_NAME,
311 mcp_server::PermissionTool::NAME,
312 ),
313 "--allowedTools",
314 &format!(
315 "mcp__{}__{},mcp__{}__{}",
316 mcp_server::SERVER_NAME,
317 mcp_server::EditTool::NAME,
318 mcp_server::SERVER_NAME,
319 mcp_server::ReadTool::NAME
320 ),
321 "--disallowedTools",
322 "Read,Edit",
323 ])
324 .args(match mode {
325 ClaudeSessionMode::Start => ["--session-id".to_string(), session_id.to_string()],
326 ClaudeSessionMode::Resume => ["--resume".to_string(), session_id.to_string()],
327 })
328 .args(command.args.iter().map(|arg| arg.as_str()))
329 .current_dir(root_dir)
330 .stdin(std::process::Stdio::piped())
331 .stdout(std::process::Stdio::piped())
332 .stderr(std::process::Stdio::inherit())
333 .kill_on_drop(true)
334 .spawn()?;
335
336 Ok(child)
337}
338
339struct ClaudeAgentSession {
340 outgoing_tx: UnboundedSender<SdkMessage>,
341 end_turn_tx: Rc<RefCell<Option<oneshot::Sender<Result<acp::PromptResponse>>>>>,
342 _mcp_server: Option<ClaudeZedMcpServer>,
343 _handler_task: Task<()>,
344}
345
346impl ClaudeAgentSession {
347 async fn handle_message(
348 mut thread_rx: watch::Receiver<WeakEntity<AcpThread>>,
349 message: SdkMessage,
350 end_turn_tx: Rc<RefCell<Option<oneshot::Sender<Result<acp::PromptResponse>>>>>,
351 cx: &mut AsyncApp,
352 ) {
353 match message {
354 // we should only be sending these out, they don't need to be in the thread
355 SdkMessage::ControlRequest { .. } => {}
356 SdkMessage::Assistant {
357 message,
358 session_id: _,
359 }
360 | SdkMessage::User {
361 message,
362 session_id: _,
363 } => {
364 let Some(thread) = thread_rx
365 .recv()
366 .await
367 .log_err()
368 .and_then(|entity| entity.upgrade())
369 else {
370 log::error!("Received an SDK message but thread is gone");
371 return;
372 };
373
374 for chunk in message.content.chunks() {
375 match chunk {
376 ContentChunk::Text { text } | ContentChunk::UntaggedText(text) => {
377 thread
378 .update(cx, |thread, cx| {
379 thread.push_assistant_content_block(text.into(), false, cx)
380 })
381 .log_err();
382 }
383 ContentChunk::Thinking { thinking } => {
384 thread
385 .update(cx, |thread, cx| {
386 thread.push_assistant_content_block(thinking.into(), true, cx)
387 })
388 .log_err();
389 }
390 ContentChunk::RedactedThinking => {
391 thread
392 .update(cx, |thread, cx| {
393 thread.push_assistant_content_block(
394 "[REDACTED]".into(),
395 true,
396 cx,
397 )
398 })
399 .log_err();
400 }
401 ContentChunk::ToolUse { id, name, input } => {
402 let claude_tool = ClaudeTool::infer(&name, input);
403
404 thread
405 .update(cx, |thread, cx| {
406 if let ClaudeTool::TodoWrite(Some(params)) = claude_tool {
407 thread.update_plan(
408 acp::Plan {
409 entries: params
410 .todos
411 .into_iter()
412 .map(Into::into)
413 .collect(),
414 },
415 cx,
416 )
417 } else {
418 thread.upsert_tool_call(
419 claude_tool.as_acp(acp::ToolCallId(id.into())),
420 cx,
421 );
422 }
423 })
424 .log_err();
425 }
426 ContentChunk::ToolResult {
427 content,
428 tool_use_id,
429 } => {
430 let content = content.to_string();
431 thread
432 .update(cx, |thread, cx| {
433 thread.update_tool_call(
434 acp::ToolCallUpdate {
435 id: acp::ToolCallId(tool_use_id.into()),
436 fields: acp::ToolCallUpdateFields {
437 status: Some(acp::ToolCallStatus::Completed),
438 content: (!content.is_empty())
439 .then(|| vec![content.into()]),
440 ..Default::default()
441 },
442 },
443 cx,
444 )
445 })
446 .log_err();
447 }
448 ContentChunk::Image
449 | ContentChunk::Document
450 | ContentChunk::WebSearchToolResult => {
451 thread
452 .update(cx, |thread, cx| {
453 thread.push_assistant_content_block(
454 format!("Unsupported content: {:?}", chunk).into(),
455 false,
456 cx,
457 )
458 })
459 .log_err();
460 }
461 }
462 }
463 }
464 SdkMessage::Result {
465 is_error,
466 subtype,
467 result,
468 ..
469 } => {
470 if let Some(end_turn_tx) = end_turn_tx.borrow_mut().take() {
471 if is_error || subtype == ResultErrorType::ErrorDuringExecution {
472 end_turn_tx
473 .send(Err(anyhow!(
474 "Error: {}",
475 result.unwrap_or_else(|| subtype.to_string())
476 )))
477 .ok();
478 } else {
479 let stop_reason = match subtype {
480 ResultErrorType::Success => acp::StopReason::EndTurn,
481 ResultErrorType::ErrorMaxTurns => acp::StopReason::MaxTurnRequests,
482 ResultErrorType::ErrorDuringExecution => unreachable!(),
483 };
484 end_turn_tx
485 .send(Ok(acp::PromptResponse { stop_reason }))
486 .ok();
487 }
488 }
489 }
490 SdkMessage::System { .. } | SdkMessage::ControlResponse { .. } => {}
491 }
492 }
493
494 async fn handle_io(
495 mut outgoing_rx: UnboundedReceiver<SdkMessage>,
496 incoming_tx: UnboundedSender<SdkMessage>,
497 mut outgoing_bytes: impl Unpin + AsyncWrite,
498 incoming_bytes: impl Unpin + AsyncRead,
499 ) -> Result<UnboundedReceiver<SdkMessage>> {
500 let mut output_reader = BufReader::new(incoming_bytes);
501 let mut outgoing_line = Vec::new();
502 let mut incoming_line = String::new();
503 loop {
504 select_biased! {
505 message = outgoing_rx.next() => {
506 if let Some(message) = message {
507 outgoing_line.clear();
508 serde_json::to_writer(&mut outgoing_line, &message)?;
509 log::trace!("send: {}", String::from_utf8_lossy(&outgoing_line));
510 outgoing_line.push(b'\n');
511 outgoing_bytes.write_all(&outgoing_line).await.ok();
512 } else {
513 break;
514 }
515 }
516 bytes_read = output_reader.read_line(&mut incoming_line).fuse() => {
517 if bytes_read? == 0 {
518 break
519 }
520 log::trace!("recv: {}", &incoming_line);
521 match serde_json::from_str::<SdkMessage>(&incoming_line) {
522 Ok(message) => {
523 incoming_tx.unbounded_send(message).log_err();
524 }
525 Err(error) => {
526 log::error!("failed to parse incoming message: {error}. Raw: {incoming_line}");
527 }
528 }
529 incoming_line.clear();
530 }
531 }
532 }
533
534 Ok(outgoing_rx)
535 }
536}
537
538#[derive(Debug, Clone, Serialize, Deserialize)]
539struct Message {
540 role: Role,
541 content: Content,
542 #[serde(skip_serializing_if = "Option::is_none")]
543 id: Option<String>,
544 #[serde(skip_serializing_if = "Option::is_none")]
545 model: Option<String>,
546 #[serde(skip_serializing_if = "Option::is_none")]
547 stop_reason: Option<String>,
548 #[serde(skip_serializing_if = "Option::is_none")]
549 stop_sequence: Option<String>,
550 #[serde(skip_serializing_if = "Option::is_none")]
551 usage: Option<Usage>,
552}
553
554#[derive(Debug, Clone, Serialize, Deserialize)]
555#[serde(untagged)]
556enum Content {
557 UntaggedText(String),
558 Chunks(Vec<ContentChunk>),
559}
560
561impl Content {
562 pub fn chunks(self) -> impl Iterator<Item = ContentChunk> {
563 match self {
564 Self::Chunks(chunks) => chunks.into_iter(),
565 Self::UntaggedText(text) => vec![ContentChunk::Text { text: text.clone() }].into_iter(),
566 }
567 }
568}
569
570impl Display for Content {
571 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
572 match self {
573 Content::UntaggedText(txt) => write!(f, "{}", txt),
574 Content::Chunks(chunks) => {
575 for chunk in chunks {
576 write!(f, "{}", chunk)?;
577 }
578 Ok(())
579 }
580 }
581 }
582}
583
584#[derive(Debug, Clone, Serialize, Deserialize)]
585#[serde(tag = "type", rename_all = "snake_case")]
586enum ContentChunk {
587 Text {
588 text: String,
589 },
590 ToolUse {
591 id: String,
592 name: String,
593 input: serde_json::Value,
594 },
595 ToolResult {
596 content: Content,
597 tool_use_id: String,
598 },
599 Thinking {
600 thinking: String,
601 },
602 RedactedThinking,
603 // TODO
604 Image,
605 Document,
606 WebSearchToolResult,
607 #[serde(untagged)]
608 UntaggedText(String),
609}
610
611impl Display for ContentChunk {
612 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
613 match self {
614 ContentChunk::Text { text } => write!(f, "{}", text),
615 ContentChunk::Thinking { thinking } => write!(f, "Thinking: {}", thinking),
616 ContentChunk::RedactedThinking => write!(f, "Thinking: [REDACTED]"),
617 ContentChunk::UntaggedText(text) => write!(f, "{}", text),
618 ContentChunk::ToolResult { content, .. } => write!(f, "{}", content),
619 ContentChunk::Image
620 | ContentChunk::Document
621 | ContentChunk::ToolUse { .. }
622 | ContentChunk::WebSearchToolResult => {
623 write!(f, "\n{:?}\n", &self)
624 }
625 }
626 }
627}
628
629#[derive(Debug, Clone, Serialize, Deserialize)]
630struct Usage {
631 input_tokens: u32,
632 cache_creation_input_tokens: u32,
633 cache_read_input_tokens: u32,
634 output_tokens: u32,
635 service_tier: String,
636}
637
638#[derive(Debug, Clone, Serialize, Deserialize)]
639#[serde(rename_all = "snake_case")]
640enum Role {
641 System,
642 Assistant,
643 User,
644}
645
646#[derive(Debug, Clone, Serialize, Deserialize)]
647struct MessageParam {
648 role: Role,
649 content: String,
650}
651
652#[derive(Debug, Clone, Serialize, Deserialize)]
653#[serde(tag = "type", rename_all = "snake_case")]
654enum SdkMessage {
655 // An assistant message
656 Assistant {
657 message: Message, // from Anthropic SDK
658 #[serde(skip_serializing_if = "Option::is_none")]
659 session_id: Option<String>,
660 },
661 // A user message
662 User {
663 message: Message, // from Anthropic SDK
664 #[serde(skip_serializing_if = "Option::is_none")]
665 session_id: Option<String>,
666 },
667 // Emitted as the last message in a conversation
668 Result {
669 subtype: ResultErrorType,
670 duration_ms: f64,
671 duration_api_ms: f64,
672 is_error: bool,
673 num_turns: i32,
674 #[serde(skip_serializing_if = "Option::is_none")]
675 result: Option<String>,
676 session_id: String,
677 total_cost_usd: f64,
678 },
679 // Emitted as the first message at the start of a conversation
680 System {
681 cwd: String,
682 session_id: String,
683 tools: Vec<String>,
684 model: String,
685 mcp_servers: Vec<McpServer>,
686 #[serde(rename = "apiKeySource")]
687 api_key_source: String,
688 #[serde(rename = "permissionMode")]
689 permission_mode: PermissionMode,
690 },
691 /// Messages used to control the conversation, outside of chat messages to the model
692 ControlRequest {
693 request_id: String,
694 request: ControlRequest,
695 },
696 /// Response to a control request
697 ControlResponse { response: ControlResponse },
698}
699
700#[derive(Debug, Clone, Serialize, Deserialize)]
701#[serde(tag = "subtype", rename_all = "snake_case")]
702enum ControlRequest {
703 /// Cancel the current conversation
704 Interrupt,
705}
706
707#[derive(Debug, Clone, Serialize, Deserialize)]
708struct ControlResponse {
709 request_id: String,
710 subtype: ResultErrorType,
711}
712
713#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
714#[serde(rename_all = "snake_case")]
715enum ResultErrorType {
716 Success,
717 ErrorMaxTurns,
718 ErrorDuringExecution,
719}
720
721impl Display for ResultErrorType {
722 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
723 match self {
724 ResultErrorType::Success => write!(f, "success"),
725 ResultErrorType::ErrorMaxTurns => write!(f, "error_max_turns"),
726 ResultErrorType::ErrorDuringExecution => write!(f, "error_during_execution"),
727 }
728 }
729}
730
731impl SdkMessage {
732 fn new_interrupt_message() -> Self {
733 use rand::Rng;
734 // In the Claude Code TS SDK they just generate a random 12 character string,
735 // `Math.random().toString(36).substring(2, 15)`
736 let request_id = rand::thread_rng()
737 .sample_iter(&rand::distributions::Alphanumeric)
738 .take(12)
739 .map(char::from)
740 .collect();
741
742 Self::ControlRequest {
743 request_id,
744 request: ControlRequest::Interrupt,
745 }
746 }
747}
748
749#[derive(Debug, Clone, Serialize, Deserialize)]
750struct McpServer {
751 name: String,
752 status: String,
753}
754
755#[derive(Debug, Clone, Serialize, Deserialize)]
756#[serde(rename_all = "camelCase")]
757enum PermissionMode {
758 Default,
759 AcceptEdits,
760 BypassPermissions,
761 Plan,
762}
763
764#[cfg(test)]
765pub(crate) mod tests {
766 use super::*;
767 use crate::e2e_tests;
768 use gpui::TestAppContext;
769 use serde_json::json;
770
771 crate::common_e2e_tests!(ClaudeCode, allow_option_id = "allow");
772
773 pub fn local_command() -> AgentServerCommand {
774 AgentServerCommand {
775 path: "claude".into(),
776 args: vec![],
777 env: None,
778 }
779 }
780
781 #[gpui::test]
782 #[cfg_attr(not(feature = "e2e"), ignore)]
783 async fn test_todo_plan(cx: &mut TestAppContext) {
784 let fs = e2e_tests::init_test(cx).await;
785 let project = Project::test(fs, [], cx).await;
786 let thread =
787 e2e_tests::new_test_thread(ClaudeCode, project.clone(), "/private/tmp", cx).await;
788
789 thread
790 .update(cx, |thread, cx| {
791 thread.send_raw(
792 "Create a todo plan for initializing a new React app. I'll follow it myself, do not execute on it.",
793 cx,
794 )
795 })
796 .await
797 .unwrap();
798
799 let mut entries_len = 0;
800
801 thread.read_with(cx, |thread, _| {
802 entries_len = thread.plan().entries.len();
803 assert!(thread.plan().entries.len() > 0, "Empty plan");
804 });
805
806 thread
807 .update(cx, |thread, cx| {
808 thread.send_raw(
809 "Mark the first entry status as in progress without acting on it.",
810 cx,
811 )
812 })
813 .await
814 .unwrap();
815
816 thread.read_with(cx, |thread, _| {
817 assert!(matches!(
818 thread.plan().entries[0].status,
819 acp::PlanEntryStatus::InProgress
820 ));
821 assert_eq!(thread.plan().entries.len(), entries_len);
822 });
823
824 thread
825 .update(cx, |thread, cx| {
826 thread.send_raw(
827 "Now mark the first entry as completed without acting on it.",
828 cx,
829 )
830 })
831 .await
832 .unwrap();
833
834 thread.read_with(cx, |thread, _| {
835 assert!(matches!(
836 thread.plan().entries[0].status,
837 acp::PlanEntryStatus::Completed
838 ));
839 assert_eq!(thread.plan().entries.len(), entries_len);
840 });
841 }
842
843 #[test]
844 fn test_deserialize_content_untagged_text() {
845 let json = json!("Hello, world!");
846 let content: Content = serde_json::from_value(json).unwrap();
847 match content {
848 Content::UntaggedText(text) => assert_eq!(text, "Hello, world!"),
849 _ => panic!("Expected UntaggedText variant"),
850 }
851 }
852
853 #[test]
854 fn test_deserialize_content_chunks() {
855 let json = json!([
856 {
857 "type": "text",
858 "text": "Hello"
859 },
860 {
861 "type": "tool_use",
862 "id": "tool_123",
863 "name": "calculator",
864 "input": {"operation": "add", "a": 1, "b": 2}
865 }
866 ]);
867 let content: Content = serde_json::from_value(json).unwrap();
868 match content {
869 Content::Chunks(chunks) => {
870 assert_eq!(chunks.len(), 2);
871 match &chunks[0] {
872 ContentChunk::Text { text } => assert_eq!(text, "Hello"),
873 _ => panic!("Expected Text chunk"),
874 }
875 match &chunks[1] {
876 ContentChunk::ToolUse { id, name, input } => {
877 assert_eq!(id, "tool_123");
878 assert_eq!(name, "calculator");
879 assert_eq!(input["operation"], "add");
880 assert_eq!(input["a"], 1);
881 assert_eq!(input["b"], 2);
882 }
883 _ => panic!("Expected ToolUse chunk"),
884 }
885 }
886 _ => panic!("Expected Chunks variant"),
887 }
888 }
889
890 #[test]
891 fn test_deserialize_tool_result_untagged_text() {
892 let json = json!({
893 "type": "tool_result",
894 "content": "Result content",
895 "tool_use_id": "tool_456"
896 });
897 let chunk: ContentChunk = serde_json::from_value(json).unwrap();
898 match chunk {
899 ContentChunk::ToolResult {
900 content,
901 tool_use_id,
902 } => {
903 match content {
904 Content::UntaggedText(text) => assert_eq!(text, "Result content"),
905 _ => panic!("Expected UntaggedText content"),
906 }
907 assert_eq!(tool_use_id, "tool_456");
908 }
909 _ => panic!("Expected ToolResult variant"),
910 }
911 }
912
913 #[test]
914 fn test_deserialize_tool_result_chunks() {
915 let json = json!({
916 "type": "tool_result",
917 "content": [
918 {
919 "type": "text",
920 "text": "Processing complete"
921 },
922 {
923 "type": "text",
924 "text": "Result: 42"
925 }
926 ],
927 "tool_use_id": "tool_789"
928 });
929 let chunk: ContentChunk = serde_json::from_value(json).unwrap();
930 match chunk {
931 ContentChunk::ToolResult {
932 content,
933 tool_use_id,
934 } => {
935 match content {
936 Content::Chunks(chunks) => {
937 assert_eq!(chunks.len(), 2);
938 match &chunks[0] {
939 ContentChunk::Text { text } => assert_eq!(text, "Processing complete"),
940 _ => panic!("Expected Text chunk"),
941 }
942 match &chunks[1] {
943 ContentChunk::Text { text } => assert_eq!(text, "Result: 42"),
944 _ => panic!("Expected Text chunk"),
945 }
946 }
947 _ => panic!("Expected Chunks content"),
948 }
949 assert_eq!(tool_use_id, "tool_789");
950 }
951 _ => panic!("Expected ToolResult variant"),
952 }
953 }
954}