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