claude.rs

  1pub mod tools;
  2
  3use collections::HashMap;
  4use project::Project;
  5use settings::SettingsStore;
  6use smol::process::Child;
  7use std::cell::RefCell;
  8use std::fmt::Display;
  9use std::path::Path;
 10use std::pin::pin;
 11use std::rc::Rc;
 12use uuid::Uuid;
 13
 14use agentic_coding_protocol as acp_old;
 15use anyhow::{Result, anyhow};
 16use futures::channel::oneshot;
 17use futures::future::LocalBoxFuture;
 18use futures::{AsyncBufReadExt, AsyncWriteExt, SinkExt};
 19use futures::{
 20    AsyncRead, AsyncWrite, FutureExt, StreamExt,
 21    channel::mpsc::{self, UnboundedReceiver, UnboundedSender},
 22    io::BufReader,
 23    select_biased,
 24};
 25use gpui::{App, AppContext, Entity, Task};
 26use serde::{Deserialize, Serialize};
 27use util::ResultExt;
 28
 29use crate::claude::tools::ClaudeTool;
 30use crate::mcp_server::{self, McpConfig, ZedMcpServer};
 31use crate::{AgentServer, AgentServerCommand, AllAgentServersSettings};
 32use acp_thread::{AcpThread, AgentConnection, OldAcpClientDelegate};
 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        ""
 48    }
 49
 50    fn logo(&self) -> ui::IconName {
 51        ui::IconName::AiClaude
 52    }
 53
 54    fn supports_always_allow(&self) -> bool {
 55        false
 56    }
 57
 58    fn new_thread(
 59        &self,
 60        root_dir: &Path,
 61        project: &Entity<Project>,
 62        cx: &mut App,
 63    ) -> Task<Result<Entity<AcpThread>>> {
 64        let project = project.clone();
 65        let root_dir = root_dir.to_path_buf();
 66        let title = self.name().into();
 67        cx.spawn(async move |cx| {
 68            let (mut delegate_tx, delegate_rx) = watch::channel(None);
 69            let tool_id_map = Rc::new(RefCell::new(HashMap::default()));
 70
 71            let permission_mcp_server =
 72                ZedMcpServer::new(delegate_rx, tool_id_map.clone(), cx).await?;
 73
 74            let mut mcp_servers = HashMap::default();
 75            mcp_servers.insert(
 76                crate::mcp_server::SERVER_NAME.to_string(),
 77                permission_mcp_server.server_config()?,
 78            );
 79            let mcp_config = McpConfig { mcp_servers };
 80
 81            let mcp_config_file = tempfile::NamedTempFile::new()?;
 82            let (mcp_config_file, mcp_config_path) = mcp_config_file.into_parts();
 83
 84            let mut mcp_config_file = smol::fs::File::from(mcp_config_file);
 85            mcp_config_file
 86                .write_all(serde_json::to_string(&mcp_config)?.as_bytes())
 87                .await?;
 88            mcp_config_file.flush().await?;
 89
 90            let settings = cx.read_global(|settings: &SettingsStore, _| {
 91                settings.get::<AllAgentServersSettings>(None).claude.clone()
 92            })?;
 93
 94            let Some(command) =
 95                AgentServerCommand::resolve("claude", &[], settings, &project, cx).await
 96            else {
 97                anyhow::bail!("Failed to find claude binary");
 98            };
 99
100            let (incoming_message_tx, mut incoming_message_rx) = mpsc::unbounded();
101            let (outgoing_tx, outgoing_rx) = mpsc::unbounded();
102            let (cancel_tx, mut cancel_rx) = mpsc::unbounded::<oneshot::Sender<Result<()>>>();
103
104            let session_id = Uuid::new_v4();
105
106            log::trace!("Starting session with id: {}", session_id);
107
108            cx.background_spawn(async move {
109                let mut outgoing_rx = Some(outgoing_rx);
110                let mut mode = ClaudeSessionMode::Start;
111
112                loop {
113                    let mut child =
114                        spawn_claude(&command, mode, session_id, &mcp_config_path, &root_dir)
115                            .await?;
116                    mode = ClaudeSessionMode::Resume;
117
118                    let pid = child.id();
119                    log::trace!("Spawned (pid: {})", pid);
120
121                    let mut io_fut = pin!(
122                        ClaudeAgentConnection::handle_io(
123                            outgoing_rx.take().unwrap(),
124                            incoming_message_tx.clone(),
125                            child.stdin.take().unwrap(),
126                            child.stdout.take().unwrap(),
127                        )
128                        .fuse()
129                    );
130
131                    select_biased! {
132                        done_tx = cancel_rx.next() => {
133                            if let Some(done_tx) = done_tx {
134                                log::trace!("Interrupted (pid: {})", pid);
135                                let result = send_interrupt(pid as i32);
136                                outgoing_rx.replace(io_fut.await?);
137                                done_tx.send(result).log_err();
138                                continue;
139                            }
140                        }
141                        result = io_fut => {
142                            result?;
143                        }
144                    }
145
146                    log::trace!("Stopped (pid: {})", pid);
147                    break;
148                }
149
150                drop(mcp_config_path);
151                anyhow::Ok(())
152            })
153            .detach();
154
155            cx.new(|cx| {
156                let end_turn_tx = Rc::new(RefCell::new(None));
157                let delegate = OldAcpClientDelegate::new(cx.entity().downgrade(), cx.to_async());
158                delegate_tx.send(Some(delegate.clone())).log_err();
159
160                let handler_task = cx.foreground_executor().spawn({
161                    let end_turn_tx = end_turn_tx.clone();
162                    let tool_id_map = tool_id_map.clone();
163                    let delegate = delegate.clone();
164                    async move {
165                        while let Some(message) = incoming_message_rx.next().await {
166                            ClaudeAgentConnection::handle_message(
167                                delegate.clone(),
168                                message,
169                                end_turn_tx.clone(),
170                                tool_id_map.clone(),
171                            )
172                            .await
173                        }
174                    }
175                });
176
177                let mut connection = ClaudeAgentConnection {
178                    delegate,
179                    outgoing_tx,
180                    end_turn_tx,
181                    cancel_tx,
182                    session_id,
183                    _handler_task: handler_task,
184                    _mcp_server: None,
185                };
186
187                connection._mcp_server = Some(permission_mcp_server);
188                acp_thread::AcpThread::new(connection, title, None, project.clone(), cx)
189            })
190        })
191    }
192}
193
194#[cfg(unix)]
195fn send_interrupt(pid: libc::pid_t) -> anyhow::Result<()> {
196    let pid = nix::unistd::Pid::from_raw(pid);
197
198    nix::sys::signal::kill(pid, nix::sys::signal::SIGINT)
199        .map_err(|e| anyhow!("Failed to interrupt process: {}", e))
200}
201
202#[cfg(windows)]
203fn send_interrupt(_pid: i32) -> anyhow::Result<()> {
204    panic!("Cancel not implemented on Windows")
205}
206
207impl AgentConnection for ClaudeAgentConnection {
208    /// Send a request to the agent and wait for a response.
209    fn request_any(
210        &self,
211        params: acp_old::AnyAgentRequest,
212    ) -> LocalBoxFuture<'static, Result<acp_old::AnyAgentResult>> {
213        let delegate = self.delegate.clone();
214        let end_turn_tx = self.end_turn_tx.clone();
215        let outgoing_tx = self.outgoing_tx.clone();
216        let mut cancel_tx = self.cancel_tx.clone();
217        let session_id = self.session_id;
218        async move {
219            match params {
220                // todo: consider sending an empty request so we get the init response?
221                acp_old::AnyAgentRequest::InitializeParams(_) => Ok(
222                    acp_old::AnyAgentResult::InitializeResponse(acp::InitializeResponse {
223                        is_authenticated: true,
224                        protocol_version: acp_old::ProtocolVersion::latest(),
225                    }),
226                ),
227                acp_old::AnyAgentRequest::AuthenticateParams(_) => {
228                    Err(anyhow!("Authentication not supported"))
229                }
230                acp_old::AnyAgentRequest::SendUserMessageParams(message) => {
231                    delegate.clear_completed_plan_entries().await?;
232
233                    let (tx, rx) = oneshot::channel();
234                    end_turn_tx.borrow_mut().replace(tx);
235                    let mut content = String::new();
236                    for chunk in message.chunks {
237                        match chunk {
238                            acp_old::UserMessageChunk::Text { text } => content.push_str(&text),
239                            acp_old::UserMessageChunk::Path { path } => {
240                                content.push_str(&format!("@{path:?}"))
241                            }
242                        }
243                    }
244                    outgoing_tx.unbounded_send(SdkMessage::User {
245                        message: Message {
246                            role: Role::User,
247                            content: Content::UntaggedText(content),
248                            id: None,
249                            model: None,
250                            stop_reason: None,
251                            stop_sequence: None,
252                            usage: None,
253                        },
254                        session_id: Some(session_id),
255                    })?;
256                    rx.await??;
257                    Ok(acp_old::AnyAgentResult::SendUserMessageResponse(
258                        acp::SendUserMessageResponse,
259                    ))
260                }
261                acp_old::AnyAgentRequest::CancelSendMessageParams(_) => {
262                    let (done_tx, done_rx) = oneshot::channel();
263                    cancel_tx.send(done_tx).await?;
264                    done_rx.await??;
265
266                    Ok(acp_old::AnyAgentResult::CancelSendMessageResponse(
267                        acp::CancelSendMessageResponse,
268                    ))
269                }
270            }
271        }
272        .boxed_local()
273    }
274}
275
276#[derive(Clone, Copy)]
277enum ClaudeSessionMode {
278    Start,
279    Resume,
280}
281
282async fn spawn_claude(
283    command: &AgentServerCommand,
284    mode: ClaudeSessionMode,
285    session_id: Uuid,
286    mcp_config_path: &Path,
287    root_dir: &Path,
288) -> Result<Child> {
289    let child = util::command::new_smol_command(&command.path)
290        .args([
291            "--input-format",
292            "stream-json",
293            "--output-format",
294            "stream-json",
295            "--print",
296            "--verbose",
297            "--mcp-config",
298            mcp_config_path.to_string_lossy().as_ref(),
299            "--permission-prompt-tool",
300            &format!(
301                "mcp__{}__{}",
302                mcp_server::SERVER_NAME,
303                mcp_server::PERMISSION_TOOL
304            ),
305            "--allowedTools",
306            "mcp__zed__Read,mcp__zed__Edit",
307            "--disallowedTools",
308            "Read,Edit",
309        ])
310        .args(match mode {
311            ClaudeSessionMode::Start => ["--session-id".to_string(), session_id.to_string()],
312            ClaudeSessionMode::Resume => ["--resume".to_string(), session_id.to_string()],
313        })
314        .args(command.args.iter().map(|arg| arg.as_str()))
315        .current_dir(root_dir)
316        .stdin(std::process::Stdio::piped())
317        .stdout(std::process::Stdio::piped())
318        .stderr(std::process::Stdio::inherit())
319        .kill_on_drop(true)
320        .spawn()?;
321
322    Ok(child)
323}
324
325struct ClaudeAgentConnection {
326    delegate: OldAcpClientDelegate,
327    session_id: Uuid,
328    outgoing_tx: UnboundedSender<SdkMessage>,
329    end_turn_tx: Rc<RefCell<Option<oneshot::Sender<Result<()>>>>>,
330    cancel_tx: UnboundedSender<oneshot::Sender<Result<()>>>,
331    _mcp_server: Option<ZedMcpServer>,
332    _handler_task: Task<()>,
333}
334
335impl ClaudeAgentConnection {
336    async fn handle_message(
337        delegate: OldAcpClientDelegate,
338        message: SdkMessage,
339        end_turn_tx: Rc<RefCell<Option<oneshot::Sender<Result<()>>>>>,
340        tool_id_map: Rc<RefCell<HashMap<String, acp::ToolCallId>>>,
341    ) {
342        match message {
343            SdkMessage::Assistant { message, .. } | SdkMessage::User { message, .. } => {
344                for chunk in message.content.chunks() {
345                    match chunk {
346                        ContentChunk::Text { text } | ContentChunk::UntaggedText(text) => {
347                            delegate
348                                .stream_assistant_message_chunk(
349                                    acp_old::StreamAssistantMessageChunkParams {
350                                        chunk: acp::AssistantMessageChunk::Text { text },
351                                    },
352                                )
353                                .await
354                                .log_err();
355                        }
356                        ContentChunk::ToolUse { id, name, input } => {
357                            let claude_tool = ClaudeTool::infer(&name, input);
358
359                            if let ClaudeTool::TodoWrite(Some(params)) = claude_tool {
360                                delegate
361                                    .update_plan(acp::UpdatePlanParams {
362                                        entries: params.todos.into_iter().map(Into::into).collect(),
363                                    })
364                                    .await
365                                    .log_err();
366                            } else if let Some(resp) = delegate
367                                .push_tool_call(claude_tool.as_acp())
368                                .await
369                                .log_err()
370                            {
371                                tool_id_map.borrow_mut().insert(id, resp.id);
372                            }
373                        }
374                        ContentChunk::ToolResult {
375                            content,
376                            tool_use_id,
377                        } => {
378                            let id = tool_id_map.borrow_mut().remove(&tool_use_id);
379                            if let Some(id) = id {
380                                let content = content.to_string();
381                                delegate
382                                    .update_tool_call(acp_old::UpdateToolCallParams {
383                                        tool_call_id: id,
384                                        status: acp::ToolCallStatus::Finished,
385                                        // Don't unset existing content
386                                        content: (!content.is_empty()).then_some(
387                                            acp_old::ToolCallContent::Markdown {
388                                                // For now we only include text content
389                                                markdown: content,
390                                            },
391                                        ),
392                                    })
393                                    .await
394                                    .log_err();
395                            }
396                        }
397                        ContentChunk::Image
398                        | ContentChunk::Document
399                        | ContentChunk::Thinking
400                        | ContentChunk::RedactedThinking
401                        | ContentChunk::WebSearchToolResult => {
402                            delegate
403                                .stream_assistant_message_chunk(
404                                    acp_old::StreamAssistantMessageChunkParams {
405                                        chunk: acp::AssistantMessageChunk::Text {
406                                            text: format!("Unsupported content: {:?}", chunk),
407                                        },
408                                    },
409                                )
410                                .await
411                                .log_err();
412                        }
413                    }
414                }
415            }
416            SdkMessage::Result {
417                is_error, subtype, ..
418            } => {
419                if let Some(end_turn_tx) = end_turn_tx.borrow_mut().take() {
420                    if is_error {
421                        end_turn_tx.send(Err(anyhow!("Error: {subtype}"))).ok();
422                    } else {
423                        end_turn_tx.send(Ok(())).ok();
424                    }
425                }
426            }
427            SdkMessage::System { .. } => {}
428        }
429    }
430
431    async fn handle_io(
432        mut outgoing_rx: UnboundedReceiver<SdkMessage>,
433        incoming_tx: UnboundedSender<SdkMessage>,
434        mut outgoing_bytes: impl Unpin + AsyncWrite,
435        incoming_bytes: impl Unpin + AsyncRead,
436    ) -> Result<UnboundedReceiver<SdkMessage>> {
437        let mut output_reader = BufReader::new(incoming_bytes);
438        let mut outgoing_line = Vec::new();
439        let mut incoming_line = String::new();
440        loop {
441            select_biased! {
442                message = outgoing_rx.next() => {
443                    if let Some(message) = message {
444                        outgoing_line.clear();
445                        serde_json::to_writer(&mut outgoing_line, &message)?;
446                        log::trace!("send: {}", String::from_utf8_lossy(&outgoing_line));
447                        outgoing_line.push(b'\n');
448                        outgoing_bytes.write_all(&outgoing_line).await.ok();
449                    } else {
450                        break;
451                    }
452                }
453                bytes_read = output_reader.read_line(&mut incoming_line).fuse() => {
454                    if bytes_read? == 0 {
455                        break
456                    }
457                    log::trace!("recv: {}", &incoming_line);
458                    match serde_json::from_str::<SdkMessage>(&incoming_line) {
459                        Ok(message) => {
460                            incoming_tx.unbounded_send(message).log_err();
461                        }
462                        Err(error) => {
463                            log::error!("failed to parse incoming message: {error}. Raw: {incoming_line}");
464                        }
465                    }
466                    incoming_line.clear();
467                }
468            }
469        }
470
471        Ok(outgoing_rx)
472    }
473}
474
475#[derive(Debug, Clone, Serialize, Deserialize)]
476struct Message {
477    role: Role,
478    content: Content,
479    #[serde(skip_serializing_if = "Option::is_none")]
480    id: Option<String>,
481    #[serde(skip_serializing_if = "Option::is_none")]
482    model: Option<String>,
483    #[serde(skip_serializing_if = "Option::is_none")]
484    stop_reason: Option<String>,
485    #[serde(skip_serializing_if = "Option::is_none")]
486    stop_sequence: Option<String>,
487    #[serde(skip_serializing_if = "Option::is_none")]
488    usage: Option<Usage>,
489}
490
491#[derive(Debug, Clone, Serialize, Deserialize)]
492#[serde(untagged)]
493enum Content {
494    UntaggedText(String),
495    Chunks(Vec<ContentChunk>),
496}
497
498impl Content {
499    pub fn chunks(self) -> impl Iterator<Item = ContentChunk> {
500        match self {
501            Self::Chunks(chunks) => chunks.into_iter(),
502            Self::UntaggedText(text) => vec![ContentChunk::Text { text: text.clone() }].into_iter(),
503        }
504    }
505}
506
507impl Display for Content {
508    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
509        match self {
510            Content::UntaggedText(txt) => write!(f, "{}", txt),
511            Content::Chunks(chunks) => {
512                for chunk in chunks {
513                    write!(f, "{}", chunk)?;
514                }
515                Ok(())
516            }
517        }
518    }
519}
520
521#[derive(Debug, Clone, Serialize, Deserialize)]
522#[serde(tag = "type", rename_all = "snake_case")]
523enum ContentChunk {
524    Text {
525        text: String,
526    },
527    ToolUse {
528        id: String,
529        name: String,
530        input: serde_json::Value,
531    },
532    ToolResult {
533        content: Content,
534        tool_use_id: String,
535    },
536    // TODO
537    Image,
538    Document,
539    Thinking,
540    RedactedThinking,
541    WebSearchToolResult,
542    #[serde(untagged)]
543    UntaggedText(String),
544}
545
546impl Display for ContentChunk {
547    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
548        match self {
549            ContentChunk::Text { text } => write!(f, "{}", text),
550            ContentChunk::UntaggedText(text) => write!(f, "{}", text),
551            ContentChunk::ToolResult { content, .. } => write!(f, "{}", content),
552            ContentChunk::Image
553            | ContentChunk::Document
554            | ContentChunk::Thinking
555            | ContentChunk::RedactedThinking
556            | ContentChunk::ToolUse { .. }
557            | ContentChunk::WebSearchToolResult => {
558                write!(f, "\n{:?}\n", &self)
559            }
560        }
561    }
562}
563
564#[derive(Debug, Clone, Serialize, Deserialize)]
565struct Usage {
566    input_tokens: u32,
567    cache_creation_input_tokens: u32,
568    cache_read_input_tokens: u32,
569    output_tokens: u32,
570    service_tier: String,
571}
572
573#[derive(Debug, Clone, Serialize, Deserialize)]
574#[serde(rename_all = "snake_case")]
575enum Role {
576    System,
577    Assistant,
578    User,
579}
580
581#[derive(Debug, Clone, Serialize, Deserialize)]
582struct MessageParam {
583    role: Role,
584    content: String,
585}
586
587#[derive(Debug, Clone, Serialize, Deserialize)]
588#[serde(tag = "type", rename_all = "snake_case")]
589enum SdkMessage {
590    // An assistant message
591    Assistant {
592        message: Message, // from Anthropic SDK
593        #[serde(skip_serializing_if = "Option::is_none")]
594        session_id: Option<Uuid>,
595    },
596
597    // A user message
598    User {
599        message: Message, // from Anthropic SDK
600        #[serde(skip_serializing_if = "Option::is_none")]
601        session_id: Option<Uuid>,
602    },
603
604    // Emitted as the last message in a conversation
605    Result {
606        subtype: ResultErrorType,
607        duration_ms: f64,
608        duration_api_ms: f64,
609        is_error: bool,
610        num_turns: i32,
611        #[serde(skip_serializing_if = "Option::is_none")]
612        result: Option<String>,
613        session_id: String,
614        total_cost_usd: f64,
615    },
616    // Emitted as the first message at the start of a conversation
617    System {
618        cwd: String,
619        session_id: String,
620        tools: Vec<String>,
621        model: String,
622        mcp_servers: Vec<McpServer>,
623        #[serde(rename = "apiKeySource")]
624        api_key_source: String,
625        #[serde(rename = "permissionMode")]
626        permission_mode: PermissionMode,
627    },
628}
629
630#[derive(Debug, Clone, Serialize, Deserialize)]
631#[serde(rename_all = "snake_case")]
632enum ResultErrorType {
633    Success,
634    ErrorMaxTurns,
635    ErrorDuringExecution,
636}
637
638impl Display for ResultErrorType {
639    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
640        match self {
641            ResultErrorType::Success => write!(f, "success"),
642            ResultErrorType::ErrorMaxTurns => write!(f, "error_max_turns"),
643            ResultErrorType::ErrorDuringExecution => write!(f, "error_during_execution"),
644        }
645    }
646}
647
648#[derive(Debug, Clone, Serialize, Deserialize)]
649struct McpServer {
650    name: String,
651    status: String,
652}
653
654#[derive(Debug, Clone, Serialize, Deserialize)]
655#[serde(rename_all = "camelCase")]
656enum PermissionMode {
657    Default,
658    AcceptEdits,
659    BypassPermissions,
660    Plan,
661}
662
663#[cfg(test)]
664pub(crate) mod tests {
665    use super::*;
666    use serde_json::json;
667
668    crate::common_e2e_tests!(ClaudeCode);
669
670    pub fn local_command() -> AgentServerCommand {
671        AgentServerCommand {
672            path: "claude".into(),
673            args: vec![],
674            env: None,
675        }
676    }
677
678    #[test]
679    fn test_deserialize_content_untagged_text() {
680        let json = json!("Hello, world!");
681        let content: Content = serde_json::from_value(json).unwrap();
682        match content {
683            Content::UntaggedText(text) => assert_eq!(text, "Hello, world!"),
684            _ => panic!("Expected UntaggedText variant"),
685        }
686    }
687
688    #[test]
689    fn test_deserialize_content_chunks() {
690        let json = json!([
691            {
692                "type": "text",
693                "text": "Hello"
694            },
695            {
696                "type": "tool_use",
697                "id": "tool_123",
698                "name": "calculator",
699                "input": {"operation": "add", "a": 1, "b": 2}
700            }
701        ]);
702        let content: Content = serde_json::from_value(json).unwrap();
703        match content {
704            Content::Chunks(chunks) => {
705                assert_eq!(chunks.len(), 2);
706                match &chunks[0] {
707                    ContentChunk::Text { text } => assert_eq!(text, "Hello"),
708                    _ => panic!("Expected Text chunk"),
709                }
710                match &chunks[1] {
711                    ContentChunk::ToolUse { id, name, input } => {
712                        assert_eq!(id, "tool_123");
713                        assert_eq!(name, "calculator");
714                        assert_eq!(input["operation"], "add");
715                        assert_eq!(input["a"], 1);
716                        assert_eq!(input["b"], 2);
717                    }
718                    _ => panic!("Expected ToolUse chunk"),
719                }
720            }
721            _ => panic!("Expected Chunks variant"),
722        }
723    }
724
725    #[test]
726    fn test_deserialize_tool_result_untagged_text() {
727        let json = json!({
728            "type": "tool_result",
729            "content": "Result content",
730            "tool_use_id": "tool_456"
731        });
732        let chunk: ContentChunk = serde_json::from_value(json).unwrap();
733        match chunk {
734            ContentChunk::ToolResult {
735                content,
736                tool_use_id,
737            } => {
738                match content {
739                    Content::UntaggedText(text) => assert_eq!(text, "Result content"),
740                    _ => panic!("Expected UntaggedText content"),
741                }
742                assert_eq!(tool_use_id, "tool_456");
743            }
744            _ => panic!("Expected ToolResult variant"),
745        }
746    }
747
748    #[test]
749    fn test_deserialize_tool_result_chunks() {
750        let json = json!({
751            "type": "tool_result",
752            "content": [
753                {
754                    "type": "text",
755                    "text": "Processing complete"
756                },
757                {
758                    "type": "text",
759                    "text": "Result: 42"
760                }
761            ],
762            "tool_use_id": "tool_789"
763        });
764        let chunk: ContentChunk = serde_json::from_value(json).unwrap();
765        match chunk {
766            ContentChunk::ToolResult {
767                content,
768                tool_use_id,
769            } => {
770                match content {
771                    Content::Chunks(chunks) => {
772                        assert_eq!(chunks.len(), 2);
773                        match &chunks[0] {
774                            ContentChunk::Text { text } => assert_eq!(text, "Processing complete"),
775                            _ => panic!("Expected Text chunk"),
776                        }
777                        match &chunks[1] {
778                            ContentChunk::Text { text } => assert_eq!(text, "Result: 42"),
779                            _ => panic!("Expected Text chunk"),
780                        }
781                    }
782                    _ => panic!("Expected Chunks content"),
783                }
784                assert_eq!(tool_use_id, "tool_789");
785            }
786            _ => panic!("Expected ToolResult variant"),
787        }
788    }
789}