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