1use crate::{
2 ContextServerRegistry, CopyPathTool, CreateDirectoryTool, DbLanguageModel, DbThread,
3 DeletePathTool, DiagnosticsTool, EditFileTool, FetchTool, FindPathTool, GrepTool,
4 ListDirectoryTool, MovePathTool, NowTool, OpenTool, ProjectSnapshot, ReadFileTool,
5 RestoreFileFromDiskTool, SaveFileTool, SpawnAgentTool, StreamingEditFileTool,
6 SystemPromptTemplate, Template, Templates, TerminalTool, ToolPermissionDecision, WebSearchTool,
7 decide_permission_from_settings,
8};
9use acp_thread::{MentionUri, UserMessageId};
10use action_log::ActionLog;
11use feature_flags::{FeatureFlagAppExt as _, StreamingEditFileToolFeatureFlag};
12
13use agent_client_protocol as acp;
14use agent_settings::{
15 AgentProfileId, AgentSettings, SUMMARIZE_THREAD_DETAILED_PROMPT, SUMMARIZE_THREAD_PROMPT,
16};
17use anyhow::{Context as _, Result, anyhow};
18use chrono::{DateTime, Utc};
19use client::UserStore;
20use cloud_api_types::Plan;
21use cloud_llm_client::CompletionIntent;
22use collections::{HashMap, HashSet, IndexMap};
23use fs::Fs;
24use futures::stream;
25use futures::{
26 FutureExt,
27 channel::{mpsc, oneshot},
28 future::Shared,
29 stream::FuturesUnordered,
30};
31use gpui::{
32 App, AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Task, WeakEntity,
33};
34use heck::ToSnakeCase as _;
35use language_model::{
36 LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent, LanguageModelId,
37 LanguageModelImage, LanguageModelProviderId, LanguageModelRegistry, LanguageModelRequest,
38 LanguageModelRequestMessage, LanguageModelRequestTool, LanguageModelToolResult,
39 LanguageModelToolResultContent, LanguageModelToolSchemaFormat, LanguageModelToolUse,
40 LanguageModelToolUseId, Role, SelectedModel, Speed, StopReason, TokenUsage,
41 ZED_CLOUD_PROVIDER_ID,
42};
43use project::Project;
44use prompt_store::ProjectContext;
45use schemars::{JsonSchema, Schema};
46use serde::de::DeserializeOwned;
47use serde::{Deserialize, Serialize};
48use settings::{LanguageModelSelection, Settings, ToolPermissionMode, update_settings_file};
49use smol::stream::StreamExt;
50use std::{
51 collections::BTreeMap,
52 marker::PhantomData,
53 ops::RangeInclusive,
54 path::Path,
55 rc::Rc,
56 sync::Arc,
57 time::{Duration, Instant},
58};
59use std::{fmt::Write, path::PathBuf};
60use util::{ResultExt, debug_panic, markdown::MarkdownCodeBlock, paths::PathStyle};
61use uuid::Uuid;
62
63const TOOL_CANCELED_MESSAGE: &str = "Tool canceled by user";
64pub const MAX_TOOL_NAME_LENGTH: usize = 64;
65pub const MAX_SUBAGENT_DEPTH: u8 = 1;
66
67/// Context passed to a subagent thread for lifecycle management
68#[derive(Clone, Debug, Serialize, Deserialize)]
69pub struct SubagentContext {
70 /// ID of the parent thread
71 pub parent_thread_id: acp::SessionId,
72
73 /// Current depth level (0 = root agent, 1 = first-level subagent, etc.)
74 pub depth: u8,
75}
76
77/// The ID of the user prompt that initiated a request.
78///
79/// This equates to the user physically submitting a message to the model (e.g., by pressing the Enter key).
80#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Serialize, Deserialize)]
81pub struct PromptId(Arc<str>);
82
83impl PromptId {
84 pub fn new() -> Self {
85 Self(Uuid::new_v4().to_string().into())
86 }
87}
88
89impl std::fmt::Display for PromptId {
90 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91 write!(f, "{}", self.0)
92 }
93}
94
95pub(crate) const MAX_RETRY_ATTEMPTS: u8 = 4;
96pub(crate) const BASE_RETRY_DELAY: Duration = Duration::from_secs(5);
97
98#[derive(Debug, Clone)]
99enum RetryStrategy {
100 ExponentialBackoff {
101 initial_delay: Duration,
102 max_attempts: u8,
103 },
104 Fixed {
105 delay: Duration,
106 max_attempts: u8,
107 },
108}
109
110#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
111pub enum Message {
112 User(UserMessage),
113 Agent(AgentMessage),
114 Resume,
115}
116
117impl Message {
118 pub fn as_agent_message(&self) -> Option<&AgentMessage> {
119 match self {
120 Message::Agent(agent_message) => Some(agent_message),
121 _ => None,
122 }
123 }
124
125 pub fn to_request(&self) -> Vec<LanguageModelRequestMessage> {
126 match self {
127 Message::User(message) => {
128 if message.content.is_empty() {
129 vec![]
130 } else {
131 vec![message.to_request()]
132 }
133 }
134 Message::Agent(message) => message.to_request(),
135 Message::Resume => vec![LanguageModelRequestMessage {
136 role: Role::User,
137 content: vec!["Continue where you left off".into()],
138 cache: false,
139 reasoning_details: None,
140 }],
141 }
142 }
143
144 pub fn to_markdown(&self) -> String {
145 match self {
146 Message::User(message) => message.to_markdown(),
147 Message::Agent(message) => message.to_markdown(),
148 Message::Resume => "[resume]\n".into(),
149 }
150 }
151
152 pub fn role(&self) -> Role {
153 match self {
154 Message::User(_) | Message::Resume => Role::User,
155 Message::Agent(_) => Role::Assistant,
156 }
157 }
158}
159
160#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
161pub struct UserMessage {
162 pub id: UserMessageId,
163 pub content: Vec<UserMessageContent>,
164}
165
166#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
167pub enum UserMessageContent {
168 Text(String),
169 Mention { uri: MentionUri, content: String },
170 Image(LanguageModelImage),
171}
172
173impl UserMessage {
174 pub fn to_markdown(&self) -> String {
175 let mut markdown = String::new();
176
177 for content in &self.content {
178 match content {
179 UserMessageContent::Text(text) => {
180 markdown.push_str(text);
181 markdown.push('\n');
182 }
183 UserMessageContent::Image(_) => {
184 markdown.push_str("<image />\n");
185 }
186 UserMessageContent::Mention { uri, content } => {
187 if !content.is_empty() {
188 let _ = writeln!(&mut markdown, "{}\n\n{}", uri.as_link(), content);
189 } else {
190 let _ = writeln!(&mut markdown, "{}", uri.as_link());
191 }
192 }
193 }
194 }
195
196 markdown
197 }
198
199 fn to_request(&self) -> LanguageModelRequestMessage {
200 let mut message = LanguageModelRequestMessage {
201 role: Role::User,
202 content: Vec::with_capacity(self.content.len()),
203 cache: false,
204 reasoning_details: None,
205 };
206
207 const OPEN_CONTEXT: &str = "<context>\n\
208 The following items were attached by the user. \
209 They are up-to-date and don't need to be re-read.\n\n";
210
211 const OPEN_FILES_TAG: &str = "<files>";
212 const OPEN_DIRECTORIES_TAG: &str = "<directories>";
213 const OPEN_SYMBOLS_TAG: &str = "<symbols>";
214 const OPEN_SELECTIONS_TAG: &str = "<selections>";
215 const OPEN_THREADS_TAG: &str = "<threads>";
216 const OPEN_FETCH_TAG: &str = "<fetched_urls>";
217 const OPEN_RULES_TAG: &str =
218 "<rules>\nThe user has specified the following rules that should be applied:\n";
219 const OPEN_DIAGNOSTICS_TAG: &str = "<diagnostics>";
220 const OPEN_DIFFS_TAG: &str = "<diffs>";
221 const MERGE_CONFLICT_TAG: &str = "<merge_conflicts>";
222
223 let mut file_context = OPEN_FILES_TAG.to_string();
224 let mut directory_context = OPEN_DIRECTORIES_TAG.to_string();
225 let mut symbol_context = OPEN_SYMBOLS_TAG.to_string();
226 let mut selection_context = OPEN_SELECTIONS_TAG.to_string();
227 let mut thread_context = OPEN_THREADS_TAG.to_string();
228 let mut fetch_context = OPEN_FETCH_TAG.to_string();
229 let mut rules_context = OPEN_RULES_TAG.to_string();
230 let mut diagnostics_context = OPEN_DIAGNOSTICS_TAG.to_string();
231 let mut diffs_context = OPEN_DIFFS_TAG.to_string();
232 let mut merge_conflict_context = MERGE_CONFLICT_TAG.to_string();
233
234 for chunk in &self.content {
235 let chunk = match chunk {
236 UserMessageContent::Text(text) => {
237 language_model::MessageContent::Text(text.clone())
238 }
239 UserMessageContent::Image(value) => {
240 language_model::MessageContent::Image(value.clone())
241 }
242 UserMessageContent::Mention { uri, content } => {
243 match uri {
244 MentionUri::File { abs_path } => {
245 write!(
246 &mut file_context,
247 "\n{}",
248 MarkdownCodeBlock {
249 tag: &codeblock_tag(abs_path, None),
250 text: &content.to_string(),
251 }
252 )
253 .ok();
254 }
255 MentionUri::PastedImage => {
256 debug_panic!("pasted image URI should not be used in mention content")
257 }
258 MentionUri::Directory { .. } => {
259 write!(&mut directory_context, "\n{}\n", content).ok();
260 }
261 MentionUri::Symbol {
262 abs_path: path,
263 line_range,
264 ..
265 } => {
266 write!(
267 &mut symbol_context,
268 "\n{}",
269 MarkdownCodeBlock {
270 tag: &codeblock_tag(path, Some(line_range)),
271 text: content
272 }
273 )
274 .ok();
275 }
276 MentionUri::Selection {
277 abs_path: path,
278 line_range,
279 ..
280 } => {
281 write!(
282 &mut selection_context,
283 "\n{}",
284 MarkdownCodeBlock {
285 tag: &codeblock_tag(
286 path.as_deref().unwrap_or("Untitled".as_ref()),
287 Some(line_range)
288 ),
289 text: content
290 }
291 )
292 .ok();
293 }
294 MentionUri::Thread { .. } => {
295 write!(&mut thread_context, "\n{}\n", content).ok();
296 }
297 MentionUri::TextThread { .. } => {
298 write!(&mut thread_context, "\n{}\n", content).ok();
299 }
300 MentionUri::Rule { .. } => {
301 write!(
302 &mut rules_context,
303 "\n{}",
304 MarkdownCodeBlock {
305 tag: "",
306 text: content
307 }
308 )
309 .ok();
310 }
311 MentionUri::Fetch { url } => {
312 write!(&mut fetch_context, "\nFetch: {}\n\n{}", url, content).ok();
313 }
314 MentionUri::Diagnostics { .. } => {
315 write!(&mut diagnostics_context, "\n{}\n", content).ok();
316 }
317 MentionUri::TerminalSelection { .. } => {
318 write!(
319 &mut selection_context,
320 "\n{}",
321 MarkdownCodeBlock {
322 tag: "console",
323 text: content
324 }
325 )
326 .ok();
327 }
328 MentionUri::GitDiff { base_ref } => {
329 write!(
330 &mut diffs_context,
331 "\nBranch diff against {}:\n{}",
332 base_ref,
333 MarkdownCodeBlock {
334 tag: "diff",
335 text: content
336 }
337 )
338 .ok();
339 }
340 MentionUri::MergeConflict { file_path } => {
341 write!(
342 &mut merge_conflict_context,
343 "\nMerge conflict in {}:\n{}",
344 file_path,
345 MarkdownCodeBlock {
346 tag: "diff",
347 text: content
348 }
349 )
350 .ok();
351 }
352 }
353
354 language_model::MessageContent::Text(uri.as_link().to_string())
355 }
356 };
357
358 message.content.push(chunk);
359 }
360
361 let len_before_context = message.content.len();
362
363 if file_context.len() > OPEN_FILES_TAG.len() {
364 file_context.push_str("</files>\n");
365 message
366 .content
367 .push(language_model::MessageContent::Text(file_context));
368 }
369
370 if directory_context.len() > OPEN_DIRECTORIES_TAG.len() {
371 directory_context.push_str("</directories>\n");
372 message
373 .content
374 .push(language_model::MessageContent::Text(directory_context));
375 }
376
377 if symbol_context.len() > OPEN_SYMBOLS_TAG.len() {
378 symbol_context.push_str("</symbols>\n");
379 message
380 .content
381 .push(language_model::MessageContent::Text(symbol_context));
382 }
383
384 if selection_context.len() > OPEN_SELECTIONS_TAG.len() {
385 selection_context.push_str("</selections>\n");
386 message
387 .content
388 .push(language_model::MessageContent::Text(selection_context));
389 }
390
391 if diffs_context.len() > OPEN_DIFFS_TAG.len() {
392 diffs_context.push_str("</diffs>\n");
393 message
394 .content
395 .push(language_model::MessageContent::Text(diffs_context));
396 }
397
398 if thread_context.len() > OPEN_THREADS_TAG.len() {
399 thread_context.push_str("</threads>\n");
400 message
401 .content
402 .push(language_model::MessageContent::Text(thread_context));
403 }
404
405 if fetch_context.len() > OPEN_FETCH_TAG.len() {
406 fetch_context.push_str("</fetched_urls>\n");
407 message
408 .content
409 .push(language_model::MessageContent::Text(fetch_context));
410 }
411
412 if rules_context.len() > OPEN_RULES_TAG.len() {
413 rules_context.push_str("</user_rules>\n");
414 message
415 .content
416 .push(language_model::MessageContent::Text(rules_context));
417 }
418
419 if diagnostics_context.len() > OPEN_DIAGNOSTICS_TAG.len() {
420 diagnostics_context.push_str("</diagnostics>\n");
421 message
422 .content
423 .push(language_model::MessageContent::Text(diagnostics_context));
424 }
425
426 if merge_conflict_context.len() > MERGE_CONFLICT_TAG.len() {
427 merge_conflict_context.push_str("</merge_conflicts>\n");
428 message
429 .content
430 .push(language_model::MessageContent::Text(merge_conflict_context));
431 }
432
433 if message.content.len() > len_before_context {
434 message.content.insert(
435 len_before_context,
436 language_model::MessageContent::Text(OPEN_CONTEXT.into()),
437 );
438 message
439 .content
440 .push(language_model::MessageContent::Text("</context>".into()));
441 }
442
443 message
444 }
445}
446
447fn codeblock_tag(full_path: &Path, line_range: Option<&RangeInclusive<u32>>) -> String {
448 let mut result = String::new();
449
450 if let Some(extension) = full_path.extension().and_then(|ext| ext.to_str()) {
451 let _ = write!(result, "{} ", extension);
452 }
453
454 let _ = write!(result, "{}", full_path.display());
455
456 if let Some(range) = line_range {
457 if range.start() == range.end() {
458 let _ = write!(result, ":{}", range.start() + 1);
459 } else {
460 let _ = write!(result, ":{}-{}", range.start() + 1, range.end() + 1);
461 }
462 }
463
464 result
465}
466
467impl AgentMessage {
468 pub fn to_markdown(&self) -> String {
469 let mut markdown = String::new();
470
471 for content in &self.content {
472 match content {
473 AgentMessageContent::Text(text) => {
474 markdown.push_str(text);
475 markdown.push('\n');
476 }
477 AgentMessageContent::Thinking { text, .. } => {
478 markdown.push_str("<think>");
479 markdown.push_str(text);
480 markdown.push_str("</think>\n");
481 }
482 AgentMessageContent::RedactedThinking(_) => {
483 markdown.push_str("<redacted_thinking />\n")
484 }
485 AgentMessageContent::ToolUse(tool_use) => {
486 markdown.push_str(&format!(
487 "**Tool Use**: {} (ID: {})\n",
488 tool_use.name, tool_use.id
489 ));
490 markdown.push_str(&format!(
491 "{}\n",
492 MarkdownCodeBlock {
493 tag: "json",
494 text: &format!("{:#}", tool_use.input)
495 }
496 ));
497 }
498 }
499 }
500
501 for tool_result in self.tool_results.values() {
502 markdown.push_str(&format!(
503 "**Tool Result**: {} (ID: {})\n\n",
504 tool_result.tool_name, tool_result.tool_use_id
505 ));
506 if tool_result.is_error {
507 markdown.push_str("**ERROR:**\n");
508 }
509
510 match &tool_result.content {
511 LanguageModelToolResultContent::Text(text) => {
512 writeln!(markdown, "{text}\n").ok();
513 }
514 LanguageModelToolResultContent::Image(_) => {
515 writeln!(markdown, "<image />\n").ok();
516 }
517 }
518
519 if let Some(output) = tool_result.output.as_ref() {
520 writeln!(
521 markdown,
522 "**Debug Output**:\n\n```json\n{}\n```\n",
523 serde_json::to_string_pretty(output).unwrap()
524 )
525 .unwrap();
526 }
527 }
528
529 markdown
530 }
531
532 pub fn to_request(&self) -> Vec<LanguageModelRequestMessage> {
533 let mut assistant_message = LanguageModelRequestMessage {
534 role: Role::Assistant,
535 content: Vec::with_capacity(self.content.len()),
536 cache: false,
537 reasoning_details: self.reasoning_details.clone(),
538 };
539 for chunk in &self.content {
540 match chunk {
541 AgentMessageContent::Text(text) => {
542 assistant_message
543 .content
544 .push(language_model::MessageContent::Text(text.clone()));
545 }
546 AgentMessageContent::Thinking { text, signature } => {
547 assistant_message
548 .content
549 .push(language_model::MessageContent::Thinking {
550 text: text.clone(),
551 signature: signature.clone(),
552 });
553 }
554 AgentMessageContent::RedactedThinking(value) => {
555 assistant_message.content.push(
556 language_model::MessageContent::RedactedThinking(value.clone()),
557 );
558 }
559 AgentMessageContent::ToolUse(tool_use) => {
560 if self.tool_results.contains_key(&tool_use.id) {
561 assistant_message
562 .content
563 .push(language_model::MessageContent::ToolUse(tool_use.clone()));
564 }
565 }
566 };
567 }
568
569 let mut user_message = LanguageModelRequestMessage {
570 role: Role::User,
571 content: Vec::new(),
572 cache: false,
573 reasoning_details: None,
574 };
575
576 for tool_result in self.tool_results.values() {
577 let mut tool_result = tool_result.clone();
578 // Surprisingly, the API fails if we return an empty string here.
579 // It thinks we are sending a tool use without a tool result.
580 if tool_result.content.is_empty() {
581 tool_result.content = "<Tool returned an empty string>".into();
582 }
583 user_message
584 .content
585 .push(language_model::MessageContent::ToolResult(tool_result));
586 }
587
588 let mut messages = Vec::new();
589 if !assistant_message.content.is_empty() {
590 messages.push(assistant_message);
591 }
592 if !user_message.content.is_empty() {
593 messages.push(user_message);
594 }
595 messages
596 }
597}
598
599#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
600pub struct AgentMessage {
601 pub content: Vec<AgentMessageContent>,
602 pub tool_results: IndexMap<LanguageModelToolUseId, LanguageModelToolResult>,
603 pub reasoning_details: Option<serde_json::Value>,
604}
605
606#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
607pub enum AgentMessageContent {
608 Text(String),
609 Thinking {
610 text: String,
611 signature: Option<String>,
612 },
613 RedactedThinking(String),
614 ToolUse(LanguageModelToolUse),
615}
616
617pub trait TerminalHandle {
618 fn id(&self, cx: &AsyncApp) -> Result<acp::TerminalId>;
619 fn current_output(&self, cx: &AsyncApp) -> Result<acp::TerminalOutputResponse>;
620 fn wait_for_exit(&self, cx: &AsyncApp) -> Result<Shared<Task<acp::TerminalExitStatus>>>;
621 fn kill(&self, cx: &AsyncApp) -> Result<()>;
622 fn was_stopped_by_user(&self, cx: &AsyncApp) -> Result<bool>;
623}
624
625pub trait SubagentHandle {
626 /// The session ID of this subagent thread
627 fn id(&self) -> acp::SessionId;
628 /// The current number of entries in the thread.
629 /// Useful for knowing where the next turn will begin
630 fn num_entries(&self, cx: &App) -> usize;
631 /// Runs a turn for a given message and returns both the response and the index of that output message.
632 fn send(&self, message: String, cx: &AsyncApp) -> Task<Result<String>>;
633}
634
635pub trait ThreadEnvironment {
636 fn create_terminal(
637 &self,
638 command: String,
639 cwd: Option<PathBuf>,
640 output_byte_limit: Option<u64>,
641 cx: &mut AsyncApp,
642 ) -> Task<Result<Rc<dyn TerminalHandle>>>;
643
644 fn create_subagent(&self, label: String, cx: &mut App) -> Result<Rc<dyn SubagentHandle>>;
645
646 fn resume_subagent(
647 &self,
648 _session_id: acp::SessionId,
649 _cx: &mut App,
650 ) -> Result<Rc<dyn SubagentHandle>> {
651 Err(anyhow::anyhow!(
652 "Resuming subagent sessions is not supported"
653 ))
654 }
655}
656
657#[derive(Debug)]
658pub enum ThreadEvent {
659 UserMessage(UserMessage),
660 AgentText(String),
661 AgentThinking(String),
662 ToolCall(acp::ToolCall),
663 ToolCallUpdate(acp_thread::ToolCallUpdate),
664 ToolCallAuthorization(ToolCallAuthorization),
665 SubagentSpawned(acp::SessionId),
666 Retry(acp_thread::RetryStatus),
667 Stop(acp::StopReason),
668}
669
670#[derive(Debug)]
671pub struct NewTerminal {
672 pub command: String,
673 pub output_byte_limit: Option<u64>,
674 pub cwd: Option<PathBuf>,
675 pub response: oneshot::Sender<Result<Entity<acp_thread::Terminal>>>,
676}
677
678#[derive(Debug, Clone)]
679pub struct ToolPermissionContext {
680 pub tool_name: String,
681 pub input_values: Vec<String>,
682 pub scope: ToolPermissionScope,
683}
684
685#[derive(Debug, Clone, Copy, PartialEq, Eq)]
686pub enum ToolPermissionScope {
687 ToolInput,
688 SymlinkTarget,
689}
690
691impl ToolPermissionContext {
692 pub fn new(tool_name: impl Into<String>, input_values: Vec<String>) -> Self {
693 Self {
694 tool_name: tool_name.into(),
695 input_values,
696 scope: ToolPermissionScope::ToolInput,
697 }
698 }
699
700 pub fn symlink_target(tool_name: impl Into<String>, target_paths: Vec<String>) -> Self {
701 Self {
702 tool_name: tool_name.into(),
703 input_values: target_paths,
704 scope: ToolPermissionScope::SymlinkTarget,
705 }
706 }
707
708 /// Builds the permission options for this tool context.
709 ///
710 /// This is the canonical source for permission option generation.
711 /// Tests should use this function rather than manually constructing options.
712 ///
713 /// # Shell Compatibility for Terminal Tool
714 ///
715 /// For the terminal tool, "Always allow" options are only shown when the user's
716 /// shell supports POSIX-like command chaining syntax (`&&`, `||`, `;`, `|`).
717 ///
718 /// **Why this matters:** When a user sets up an "always allow" pattern like `^cargo`,
719 /// we need to parse the command to extract all sub-commands and verify that EVERY
720 /// sub-command matches the pattern. Otherwise, an attacker could craft a command like
721 /// `cargo build && rm -rf /` that would bypass the security check.
722 ///
723 /// **Supported shells:** Posix (sh, bash, dash, zsh), Fish 3.0+, PowerShell 7+/Pwsh,
724 /// Cmd, Xonsh, Csh, Tcsh
725 ///
726 /// **Unsupported shells:** Nushell (uses `and`/`or` keywords), Elvish (uses `and`/`or`
727 /// keywords), Rc (Plan 9 shell - no `&&`/`||` operators)
728 ///
729 /// For unsupported shells, we hide the "Always allow" UI options entirely, and if
730 /// the user has `always_allow` rules configured in settings, `ToolPermissionDecision::from_input`
731 /// will return a `Deny` with an explanatory error message.
732 pub fn build_permission_options(&self) -> acp_thread::PermissionOptions {
733 use crate::pattern_extraction::*;
734 use util::shell::ShellKind;
735
736 let tool_name = &self.tool_name;
737 let input_values = &self.input_values;
738 if self.scope == ToolPermissionScope::SymlinkTarget {
739 return acp_thread::PermissionOptions::Flat(vec![
740 acp::PermissionOption::new(
741 acp::PermissionOptionId::new("allow"),
742 "Yes",
743 acp::PermissionOptionKind::AllowOnce,
744 ),
745 acp::PermissionOption::new(
746 acp::PermissionOptionId::new("deny"),
747 "No",
748 acp::PermissionOptionKind::RejectOnce,
749 ),
750 ]);
751 }
752
753 // Check if the user's shell supports POSIX-like command chaining.
754 // See the doc comment above for the full explanation of why this is needed.
755 let shell_supports_always_allow = if tool_name == TerminalTool::NAME {
756 ShellKind::system().supports_posix_chaining()
757 } else {
758 true
759 };
760
761 let extract_for_value = |value: &str| -> (Option<String>, Option<String>) {
762 if tool_name == TerminalTool::NAME {
763 (
764 extract_terminal_pattern(value),
765 extract_terminal_pattern_display(value),
766 )
767 } else if tool_name == CopyPathTool::NAME
768 || tool_name == MovePathTool::NAME
769 || tool_name == EditFileTool::NAME
770 || tool_name == DeletePathTool::NAME
771 || tool_name == CreateDirectoryTool::NAME
772 || tool_name == SaveFileTool::NAME
773 {
774 (
775 extract_path_pattern(value),
776 extract_path_pattern_display(value),
777 )
778 } else if tool_name == FetchTool::NAME {
779 (
780 extract_url_pattern(value),
781 extract_url_pattern_display(value),
782 )
783 } else {
784 (None, None)
785 }
786 };
787
788 // Extract patterns from all input values. Only offer a pattern-specific
789 // "always allow/deny" button when every value produces the same pattern.
790 let (pattern, pattern_display) = match input_values.as_slice() {
791 [single] => extract_for_value(single),
792 _ => {
793 let mut iter = input_values.iter().map(|v| extract_for_value(v));
794 match iter.next() {
795 Some(first) => {
796 if iter.all(|pair| pair.0 == first.0) {
797 first
798 } else {
799 (None, None)
800 }
801 }
802 None => (None, None),
803 }
804 }
805 };
806
807 let mut choices = Vec::new();
808
809 let mut push_choice = |label: String, allow_id, deny_id, allow_kind, deny_kind| {
810 choices.push(acp_thread::PermissionOptionChoice {
811 allow: acp::PermissionOption::new(
812 acp::PermissionOptionId::new(allow_id),
813 label.clone(),
814 allow_kind,
815 ),
816 deny: acp::PermissionOption::new(
817 acp::PermissionOptionId::new(deny_id),
818 label,
819 deny_kind,
820 ),
821 });
822 };
823
824 if shell_supports_always_allow {
825 push_choice(
826 format!("Always for {}", tool_name.replace('_', " ")),
827 format!("always_allow:{}", tool_name),
828 format!("always_deny:{}", tool_name),
829 acp::PermissionOptionKind::AllowAlways,
830 acp::PermissionOptionKind::RejectAlways,
831 );
832
833 if let (Some(pattern), Some(display)) = (pattern, pattern_display) {
834 let button_text = if tool_name == TerminalTool::NAME {
835 format!("Always for `{}` commands", display)
836 } else {
837 format!("Always for `{}`", display)
838 };
839 push_choice(
840 button_text,
841 format!("always_allow_pattern:{}\n{}", tool_name, pattern),
842 format!("always_deny_pattern:{}\n{}", tool_name, pattern),
843 acp::PermissionOptionKind::AllowAlways,
844 acp::PermissionOptionKind::RejectAlways,
845 );
846 }
847 }
848
849 push_choice(
850 "Only this time".to_string(),
851 "allow".to_string(),
852 "deny".to_string(),
853 acp::PermissionOptionKind::AllowOnce,
854 acp::PermissionOptionKind::RejectOnce,
855 );
856
857 acp_thread::PermissionOptions::Dropdown(choices)
858 }
859}
860
861#[derive(Debug)]
862pub struct ToolCallAuthorization {
863 pub tool_call: acp::ToolCallUpdate,
864 pub options: acp_thread::PermissionOptions,
865 pub response: oneshot::Sender<acp::PermissionOptionId>,
866 pub context: Option<ToolPermissionContext>,
867}
868
869#[derive(Debug, thiserror::Error)]
870enum CompletionError {
871 #[error("max tokens")]
872 MaxTokens,
873 #[error("refusal")]
874 Refusal,
875 #[error(transparent)]
876 Other(#[from] anyhow::Error),
877}
878
879pub struct Thread {
880 id: acp::SessionId,
881 prompt_id: PromptId,
882 updated_at: DateTime<Utc>,
883 title: Option<SharedString>,
884 pending_title_generation: Option<Task<()>>,
885 pending_summary_generation: Option<Shared<Task<Option<SharedString>>>>,
886 summary: Option<SharedString>,
887 messages: Vec<Message>,
888 user_store: Entity<UserStore>,
889 /// Holds the task that handles agent interaction until the end of the turn.
890 /// Survives across multiple requests as the model performs tool calls and
891 /// we run tools, report their results.
892 running_turn: Option<RunningTurn>,
893 /// Flag indicating the UI has a queued message waiting to be sent.
894 /// Used to signal that the turn should end at the next message boundary.
895 has_queued_message: bool,
896 pending_message: Option<AgentMessage>,
897 pub(crate) tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
898 request_token_usage: HashMap<UserMessageId, language_model::TokenUsage>,
899 #[allow(unused)]
900 cumulative_token_usage: TokenUsage,
901 #[allow(unused)]
902 initial_project_snapshot: Shared<Task<Option<Arc<ProjectSnapshot>>>>,
903 pub(crate) context_server_registry: Entity<ContextServerRegistry>,
904 profile_id: AgentProfileId,
905 project_context: Entity<ProjectContext>,
906 pub(crate) templates: Arc<Templates>,
907 model: Option<Arc<dyn LanguageModel>>,
908 summarization_model: Option<Arc<dyn LanguageModel>>,
909 thinking_enabled: bool,
910 thinking_effort: Option<String>,
911 speed: Option<Speed>,
912 prompt_capabilities_tx: watch::Sender<acp::PromptCapabilities>,
913 pub(crate) prompt_capabilities_rx: watch::Receiver<acp::PromptCapabilities>,
914 pub(crate) project: Entity<Project>,
915 pub(crate) action_log: Entity<ActionLog>,
916 /// True if this thread was imported from a shared thread and can be synced.
917 imported: bool,
918 /// If this is a subagent thread, contains context about the parent
919 subagent_context: Option<SubagentContext>,
920 /// The user's unsent prompt text, persisted so it can be restored when reloading the thread.
921 draft_prompt: Option<Vec<acp::ContentBlock>>,
922 ui_scroll_position: Option<gpui::ListOffset>,
923 /// Weak references to running subagent threads for cancellation propagation
924 running_subagents: Vec<WeakEntity<Thread>>,
925}
926
927impl Thread {
928 fn prompt_capabilities(model: Option<&dyn LanguageModel>) -> acp::PromptCapabilities {
929 let image = model.map_or(true, |model| model.supports_images());
930 acp::PromptCapabilities::new()
931 .image(image)
932 .embedded_context(true)
933 }
934
935 pub fn new_subagent(parent_thread: &Entity<Thread>, cx: &mut Context<Self>) -> Self {
936 let project = parent_thread.read(cx).project.clone();
937 let project_context = parent_thread.read(cx).project_context.clone();
938 let context_server_registry = parent_thread.read(cx).context_server_registry.clone();
939 let templates = parent_thread.read(cx).templates.clone();
940 let model = parent_thread.read(cx).model().cloned();
941 let parent_action_log = parent_thread.read(cx).action_log().clone();
942 let action_log =
943 cx.new(|_cx| ActionLog::new(project.clone()).with_linked_action_log(parent_action_log));
944 let mut thread = Self::new_internal(
945 project,
946 project_context,
947 context_server_registry,
948 templates,
949 model,
950 action_log,
951 cx,
952 );
953 thread.subagent_context = Some(SubagentContext {
954 parent_thread_id: parent_thread.read(cx).id().clone(),
955 depth: parent_thread.read(cx).depth() + 1,
956 });
957 thread
958 }
959
960 pub fn new(
961 project: Entity<Project>,
962 project_context: Entity<ProjectContext>,
963 context_server_registry: Entity<ContextServerRegistry>,
964 templates: Arc<Templates>,
965 model: Option<Arc<dyn LanguageModel>>,
966 cx: &mut Context<Self>,
967 ) -> Self {
968 Self::new_internal(
969 project.clone(),
970 project_context,
971 context_server_registry,
972 templates,
973 model,
974 cx.new(|_cx| ActionLog::new(project)),
975 cx,
976 )
977 }
978
979 fn new_internal(
980 project: Entity<Project>,
981 project_context: Entity<ProjectContext>,
982 context_server_registry: Entity<ContextServerRegistry>,
983 templates: Arc<Templates>,
984 model: Option<Arc<dyn LanguageModel>>,
985 action_log: Entity<ActionLog>,
986 cx: &mut Context<Self>,
987 ) -> Self {
988 let settings = AgentSettings::get_global(cx);
989 let profile_id = settings.default_profile.clone();
990 let enable_thinking = settings
991 .default_model
992 .as_ref()
993 .is_some_and(|model| model.enable_thinking);
994 let thinking_effort = settings
995 .default_model
996 .as_ref()
997 .and_then(|model| model.effort.clone());
998 let (prompt_capabilities_tx, prompt_capabilities_rx) =
999 watch::channel(Self::prompt_capabilities(model.as_deref()));
1000 Self {
1001 id: acp::SessionId::new(uuid::Uuid::new_v4().to_string()),
1002 prompt_id: PromptId::new(),
1003 updated_at: Utc::now(),
1004 title: None,
1005 pending_title_generation: None,
1006 pending_summary_generation: None,
1007 summary: None,
1008 messages: Vec::new(),
1009 user_store: project.read(cx).user_store(),
1010 running_turn: None,
1011 has_queued_message: false,
1012 pending_message: None,
1013 tools: BTreeMap::default(),
1014 request_token_usage: HashMap::default(),
1015 cumulative_token_usage: TokenUsage::default(),
1016 initial_project_snapshot: {
1017 let project_snapshot = Self::project_snapshot(project.clone(), cx);
1018 cx.foreground_executor()
1019 .spawn(async move { Some(project_snapshot.await) })
1020 .shared()
1021 },
1022 context_server_registry,
1023 profile_id,
1024 project_context,
1025 templates,
1026 model,
1027 summarization_model: None,
1028 thinking_enabled: enable_thinking,
1029 speed: None,
1030 thinking_effort,
1031 prompt_capabilities_tx,
1032 prompt_capabilities_rx,
1033 project,
1034 action_log,
1035 imported: false,
1036 subagent_context: None,
1037 draft_prompt: None,
1038 ui_scroll_position: None,
1039 running_subagents: Vec::new(),
1040 }
1041 }
1042
1043 pub fn id(&self) -> &acp::SessionId {
1044 &self.id
1045 }
1046
1047 /// Returns true if this thread was imported from a shared thread.
1048 pub fn is_imported(&self) -> bool {
1049 self.imported
1050 }
1051
1052 pub fn replay(
1053 &mut self,
1054 cx: &mut Context<Self>,
1055 ) -> mpsc::UnboundedReceiver<Result<ThreadEvent>> {
1056 let (tx, rx) = mpsc::unbounded();
1057 let stream = ThreadEventStream(tx);
1058 for message in &self.messages {
1059 match message {
1060 Message::User(user_message) => stream.send_user_message(user_message),
1061 Message::Agent(assistant_message) => {
1062 for content in &assistant_message.content {
1063 match content {
1064 AgentMessageContent::Text(text) => stream.send_text(text),
1065 AgentMessageContent::Thinking { text, .. } => {
1066 stream.send_thinking(text)
1067 }
1068 AgentMessageContent::RedactedThinking(_) => {}
1069 AgentMessageContent::ToolUse(tool_use) => {
1070 self.replay_tool_call(
1071 tool_use,
1072 assistant_message.tool_results.get(&tool_use.id),
1073 &stream,
1074 cx,
1075 );
1076 }
1077 }
1078 }
1079 }
1080 Message::Resume => {}
1081 }
1082 }
1083 rx
1084 }
1085
1086 fn replay_tool_call(
1087 &self,
1088 tool_use: &LanguageModelToolUse,
1089 tool_result: Option<&LanguageModelToolResult>,
1090 stream: &ThreadEventStream,
1091 cx: &mut Context<Self>,
1092 ) {
1093 // Extract saved output and status first, so they're available even if tool is not found
1094 let output = tool_result
1095 .as_ref()
1096 .and_then(|result| result.output.clone());
1097 let status = tool_result
1098 .as_ref()
1099 .map_or(acp::ToolCallStatus::Failed, |result| {
1100 if result.is_error {
1101 acp::ToolCallStatus::Failed
1102 } else {
1103 acp::ToolCallStatus::Completed
1104 }
1105 });
1106
1107 let tool = self.tools.get(tool_use.name.as_ref()).cloned().or_else(|| {
1108 self.context_server_registry
1109 .read(cx)
1110 .servers()
1111 .find_map(|(_, tools)| {
1112 if let Some(tool) = tools.get(tool_use.name.as_ref()) {
1113 Some(tool.clone())
1114 } else {
1115 None
1116 }
1117 })
1118 });
1119
1120 let Some(tool) = tool else {
1121 // Tool not found (e.g., MCP server not connected after restart),
1122 // but still display the saved result if available.
1123 // We need to send both ToolCall and ToolCallUpdate events because the UI
1124 // only converts raw_output to displayable content in update_fields, not from_acp.
1125 stream
1126 .0
1127 .unbounded_send(Ok(ThreadEvent::ToolCall(
1128 acp::ToolCall::new(tool_use.id.to_string(), tool_use.name.to_string())
1129 .status(status)
1130 .raw_input(tool_use.input.clone()),
1131 )))
1132 .ok();
1133 stream.update_tool_call_fields(
1134 &tool_use.id,
1135 acp::ToolCallUpdateFields::new()
1136 .status(status)
1137 .raw_output(output),
1138 None,
1139 );
1140 return;
1141 };
1142
1143 let title = tool.initial_title(tool_use.input.clone(), cx);
1144 let kind = tool.kind();
1145 stream.send_tool_call(
1146 &tool_use.id,
1147 &tool_use.name,
1148 title,
1149 kind,
1150 tool_use.input.clone(),
1151 );
1152
1153 if let Some(output) = output.clone() {
1154 // For replay, we use a dummy cancellation receiver since the tool already completed
1155 let (_cancellation_tx, cancellation_rx) = watch::channel(false);
1156 let tool_event_stream = ToolCallEventStream::new(
1157 tool_use.id.clone(),
1158 stream.clone(),
1159 Some(self.project.read(cx).fs().clone()),
1160 cancellation_rx,
1161 );
1162 tool.replay(tool_use.input.clone(), output, tool_event_stream, cx)
1163 .log_err();
1164 }
1165
1166 stream.update_tool_call_fields(
1167 &tool_use.id,
1168 acp::ToolCallUpdateFields::new()
1169 .status(status)
1170 .raw_output(output),
1171 None,
1172 );
1173 }
1174
1175 pub fn from_db(
1176 id: acp::SessionId,
1177 db_thread: DbThread,
1178 project: Entity<Project>,
1179 project_context: Entity<ProjectContext>,
1180 context_server_registry: Entity<ContextServerRegistry>,
1181 templates: Arc<Templates>,
1182 cx: &mut Context<Self>,
1183 ) -> Self {
1184 let settings = AgentSettings::get_global(cx);
1185 let profile_id = db_thread
1186 .profile
1187 .unwrap_or_else(|| settings.default_profile.clone());
1188
1189 let mut model = LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
1190 db_thread
1191 .model
1192 .and_then(|model| {
1193 let model = SelectedModel {
1194 provider: model.provider.clone().into(),
1195 model: model.model.into(),
1196 };
1197 registry.select_model(&model, cx)
1198 })
1199 .or_else(|| registry.default_model())
1200 .map(|model| model.model)
1201 });
1202
1203 if model.is_none() {
1204 model = Self::resolve_profile_model(&profile_id, cx);
1205 }
1206 if model.is_none() {
1207 model = LanguageModelRegistry::global(cx).update(cx, |registry, _cx| {
1208 registry.default_model().map(|model| model.model)
1209 });
1210 }
1211
1212 let (prompt_capabilities_tx, prompt_capabilities_rx) =
1213 watch::channel(Self::prompt_capabilities(model.as_deref()));
1214
1215 let action_log = cx.new(|_| ActionLog::new(project.clone()));
1216
1217 Self {
1218 id,
1219 prompt_id: PromptId::new(),
1220 title: if db_thread.title.is_empty() {
1221 None
1222 } else {
1223 Some(db_thread.title.clone())
1224 },
1225 pending_title_generation: None,
1226 pending_summary_generation: None,
1227 summary: db_thread.detailed_summary,
1228 messages: db_thread.messages,
1229 user_store: project.read(cx).user_store(),
1230 running_turn: None,
1231 has_queued_message: false,
1232 pending_message: None,
1233 tools: BTreeMap::default(),
1234 request_token_usage: db_thread.request_token_usage.clone(),
1235 cumulative_token_usage: db_thread.cumulative_token_usage,
1236 initial_project_snapshot: Task::ready(db_thread.initial_project_snapshot).shared(),
1237 context_server_registry,
1238 profile_id,
1239 project_context,
1240 templates,
1241 model,
1242 summarization_model: None,
1243 thinking_enabled: db_thread.thinking_enabled,
1244 thinking_effort: db_thread.thinking_effort,
1245 speed: db_thread.speed,
1246 project,
1247 action_log,
1248 updated_at: db_thread.updated_at,
1249 prompt_capabilities_tx,
1250 prompt_capabilities_rx,
1251 imported: db_thread.imported,
1252 subagent_context: db_thread.subagent_context,
1253 draft_prompt: db_thread.draft_prompt,
1254 ui_scroll_position: db_thread.ui_scroll_position.map(|sp| gpui::ListOffset {
1255 item_ix: sp.item_ix,
1256 offset_in_item: gpui::px(sp.offset_in_item),
1257 }),
1258 running_subagents: Vec::new(),
1259 }
1260 }
1261
1262 pub fn to_db(&self, cx: &App) -> Task<DbThread> {
1263 let initial_project_snapshot = self.initial_project_snapshot.clone();
1264 let mut thread = DbThread {
1265 title: self.title(),
1266 messages: self.messages.clone(),
1267 updated_at: self.updated_at,
1268 detailed_summary: self.summary.clone(),
1269 initial_project_snapshot: None,
1270 cumulative_token_usage: self.cumulative_token_usage,
1271 request_token_usage: self.request_token_usage.clone(),
1272 model: self.model.as_ref().map(|model| DbLanguageModel {
1273 provider: model.provider_id().to_string(),
1274 model: model.id().0.to_string(),
1275 }),
1276 profile: Some(self.profile_id.clone()),
1277 imported: self.imported,
1278 subagent_context: self.subagent_context.clone(),
1279 speed: self.speed,
1280 thinking_enabled: self.thinking_enabled,
1281 thinking_effort: self.thinking_effort.clone(),
1282 draft_prompt: self.draft_prompt.clone(),
1283 ui_scroll_position: self.ui_scroll_position.map(|lo| {
1284 crate::db::SerializedScrollPosition {
1285 item_ix: lo.item_ix,
1286 offset_in_item: lo.offset_in_item.as_f32(),
1287 }
1288 }),
1289 };
1290
1291 cx.background_spawn(async move {
1292 let initial_project_snapshot = initial_project_snapshot.await;
1293 thread.initial_project_snapshot = initial_project_snapshot;
1294 thread
1295 })
1296 }
1297
1298 /// Create a snapshot of the current project state including git information and unsaved buffers.
1299 fn project_snapshot(
1300 project: Entity<Project>,
1301 cx: &mut Context<Self>,
1302 ) -> Task<Arc<ProjectSnapshot>> {
1303 let task = project::telemetry_snapshot::TelemetrySnapshot::new(&project, cx);
1304 cx.spawn(async move |_, _| {
1305 let snapshot = task.await;
1306
1307 Arc::new(ProjectSnapshot {
1308 worktree_snapshots: snapshot.worktree_snapshots,
1309 timestamp: Utc::now(),
1310 })
1311 })
1312 }
1313
1314 pub fn project_context(&self) -> &Entity<ProjectContext> {
1315 &self.project_context
1316 }
1317
1318 pub fn project(&self) -> &Entity<Project> {
1319 &self.project
1320 }
1321
1322 pub fn action_log(&self) -> &Entity<ActionLog> {
1323 &self.action_log
1324 }
1325
1326 pub fn is_empty(&self) -> bool {
1327 self.messages.is_empty() && self.title.is_none()
1328 }
1329
1330 pub fn draft_prompt(&self) -> Option<&[acp::ContentBlock]> {
1331 self.draft_prompt.as_deref()
1332 }
1333
1334 pub fn set_draft_prompt(&mut self, prompt: Option<Vec<acp::ContentBlock>>) {
1335 self.draft_prompt = prompt;
1336 }
1337
1338 pub fn ui_scroll_position(&self) -> Option<gpui::ListOffset> {
1339 self.ui_scroll_position
1340 }
1341
1342 pub fn set_ui_scroll_position(&mut self, position: Option<gpui::ListOffset>) {
1343 self.ui_scroll_position = position;
1344 }
1345
1346 pub fn model(&self) -> Option<&Arc<dyn LanguageModel>> {
1347 self.model.as_ref()
1348 }
1349
1350 pub fn set_model(&mut self, model: Arc<dyn LanguageModel>, cx: &mut Context<Self>) {
1351 let old_usage = self.latest_token_usage();
1352 self.model = Some(model.clone());
1353 let new_caps = Self::prompt_capabilities(self.model.as_deref());
1354 let new_usage = self.latest_token_usage();
1355 if old_usage != new_usage {
1356 cx.emit(TokenUsageUpdated(new_usage));
1357 }
1358 self.prompt_capabilities_tx.send(new_caps).log_err();
1359
1360 for subagent in &self.running_subagents {
1361 subagent
1362 .update(cx, |thread, cx| thread.set_model(model.clone(), cx))
1363 .ok();
1364 }
1365
1366 cx.notify()
1367 }
1368
1369 pub fn summarization_model(&self) -> Option<&Arc<dyn LanguageModel>> {
1370 self.summarization_model.as_ref()
1371 }
1372
1373 pub fn set_summarization_model(
1374 &mut self,
1375 model: Option<Arc<dyn LanguageModel>>,
1376 cx: &mut Context<Self>,
1377 ) {
1378 self.summarization_model = model.clone();
1379
1380 for subagent in &self.running_subagents {
1381 subagent
1382 .update(cx, |thread, cx| {
1383 thread.set_summarization_model(model.clone(), cx)
1384 })
1385 .ok();
1386 }
1387 cx.notify()
1388 }
1389
1390 pub fn thinking_enabled(&self) -> bool {
1391 self.thinking_enabled
1392 }
1393
1394 pub fn set_thinking_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
1395 self.thinking_enabled = enabled;
1396
1397 for subagent in &self.running_subagents {
1398 subagent
1399 .update(cx, |thread, cx| thread.set_thinking_enabled(enabled, cx))
1400 .ok();
1401 }
1402 cx.notify();
1403 }
1404
1405 pub fn thinking_effort(&self) -> Option<&String> {
1406 self.thinking_effort.as_ref()
1407 }
1408
1409 pub fn set_thinking_effort(&mut self, effort: Option<String>, cx: &mut Context<Self>) {
1410 self.thinking_effort = effort.clone();
1411
1412 for subagent in &self.running_subagents {
1413 subagent
1414 .update(cx, |thread, cx| {
1415 thread.set_thinking_effort(effort.clone(), cx)
1416 })
1417 .ok();
1418 }
1419 cx.notify();
1420 }
1421
1422 pub fn speed(&self) -> Option<Speed> {
1423 self.speed
1424 }
1425
1426 pub fn set_speed(&mut self, speed: Speed, cx: &mut Context<Self>) {
1427 self.speed = Some(speed);
1428
1429 for subagent in &self.running_subagents {
1430 subagent
1431 .update(cx, |thread, cx| thread.set_speed(speed, cx))
1432 .ok();
1433 }
1434 cx.notify();
1435 }
1436
1437 pub fn last_message(&self) -> Option<&Message> {
1438 self.messages.last()
1439 }
1440
1441 #[cfg(any(test, feature = "test-support"))]
1442 pub fn last_received_or_pending_message(&self) -> Option<Message> {
1443 if let Some(message) = self.pending_message.clone() {
1444 Some(Message::Agent(message))
1445 } else {
1446 self.messages.last().cloned()
1447 }
1448 }
1449
1450 pub fn add_default_tools(
1451 &mut self,
1452 environment: Rc<dyn ThreadEnvironment>,
1453 cx: &mut Context<Self>,
1454 ) {
1455 // Only update the agent location for the root thread, not for subagents.
1456 let update_agent_location = self.parent_thread_id().is_none();
1457
1458 let language_registry = self.project.read(cx).languages().clone();
1459 self.add_tool(CopyPathTool::new(self.project.clone()));
1460 self.add_tool(CreateDirectoryTool::new(self.project.clone()));
1461 self.add_tool(DeletePathTool::new(
1462 self.project.clone(),
1463 self.action_log.clone(),
1464 ));
1465 self.add_tool(DiagnosticsTool::new(self.project.clone()));
1466 self.add_tool(EditFileTool::new(
1467 self.project.clone(),
1468 cx.weak_entity(),
1469 language_registry.clone(),
1470 Templates::new(),
1471 ));
1472 self.add_tool(StreamingEditFileTool::new(
1473 self.project.clone(),
1474 cx.weak_entity(),
1475 self.action_log.clone(),
1476 language_registry,
1477 ));
1478 self.add_tool(FetchTool::new(self.project.read(cx).client().http_client()));
1479 self.add_tool(FindPathTool::new(self.project.clone()));
1480 self.add_tool(GrepTool::new(self.project.clone()));
1481 self.add_tool(ListDirectoryTool::new(self.project.clone()));
1482 self.add_tool(MovePathTool::new(self.project.clone()));
1483 self.add_tool(NowTool);
1484 self.add_tool(OpenTool::new(self.project.clone()));
1485 self.add_tool(ReadFileTool::new(
1486 self.project.clone(),
1487 self.action_log.clone(),
1488 update_agent_location,
1489 ));
1490 self.add_tool(SaveFileTool::new(self.project.clone()));
1491 self.add_tool(RestoreFileFromDiskTool::new(self.project.clone()));
1492 self.add_tool(TerminalTool::new(self.project.clone(), environment.clone()));
1493 self.add_tool(WebSearchTool);
1494
1495 if self.depth() < MAX_SUBAGENT_DEPTH {
1496 self.add_tool(SpawnAgentTool::new(environment));
1497 }
1498 }
1499
1500 pub fn add_tool<T: AgentTool>(&mut self, tool: T) {
1501 debug_assert!(
1502 !self.tools.contains_key(T::NAME),
1503 "Duplicate tool name: {}",
1504 T::NAME,
1505 );
1506 self.tools.insert(T::NAME.into(), tool.erase());
1507 }
1508
1509 #[cfg(any(test, feature = "test-support"))]
1510 pub fn remove_tool(&mut self, name: &str) -> bool {
1511 self.tools.remove(name).is_some()
1512 }
1513
1514 pub fn profile(&self) -> &AgentProfileId {
1515 &self.profile_id
1516 }
1517
1518 pub fn set_profile(&mut self, profile_id: AgentProfileId, cx: &mut Context<Self>) {
1519 if self.profile_id == profile_id {
1520 return;
1521 }
1522
1523 self.profile_id = profile_id.clone();
1524
1525 // Swap to the profile's preferred model when available.
1526 if let Some(model) = Self::resolve_profile_model(&self.profile_id, cx) {
1527 self.set_model(model, cx);
1528 }
1529
1530 for subagent in &self.running_subagents {
1531 subagent
1532 .update(cx, |thread, cx| thread.set_profile(profile_id.clone(), cx))
1533 .ok();
1534 }
1535 }
1536
1537 pub fn cancel(&mut self, cx: &mut Context<Self>) -> Task<()> {
1538 for subagent in self.running_subagents.drain(..) {
1539 if let Some(subagent) = subagent.upgrade() {
1540 subagent.update(cx, |thread, cx| thread.cancel(cx)).detach();
1541 }
1542 }
1543
1544 let Some(running_turn) = self.running_turn.take() else {
1545 self.flush_pending_message(cx);
1546 return Task::ready(());
1547 };
1548
1549 let turn_task = running_turn.cancel();
1550
1551 cx.spawn(async move |this, cx| {
1552 turn_task.await;
1553 this.update(cx, |this, cx| {
1554 this.flush_pending_message(cx);
1555 })
1556 .ok();
1557 })
1558 }
1559
1560 pub fn set_has_queued_message(&mut self, has_queued: bool) {
1561 self.has_queued_message = has_queued;
1562 }
1563
1564 pub fn has_queued_message(&self) -> bool {
1565 self.has_queued_message
1566 }
1567
1568 fn update_token_usage(&mut self, update: language_model::TokenUsage, cx: &mut Context<Self>) {
1569 let Some(last_user_message) = self.last_user_message() else {
1570 return;
1571 };
1572
1573 self.request_token_usage
1574 .insert(last_user_message.id.clone(), update);
1575 cx.emit(TokenUsageUpdated(self.latest_token_usage()));
1576 cx.notify();
1577 }
1578
1579 pub fn truncate(&mut self, message_id: UserMessageId, cx: &mut Context<Self>) -> Result<()> {
1580 self.cancel(cx).detach();
1581 // Clear pending message since cancel will try to flush it asynchronously,
1582 // and we don't want that content to be added after we truncate
1583 self.pending_message.take();
1584 let Some(position) = self.messages.iter().position(
1585 |msg| matches!(msg, Message::User(UserMessage { id, .. }) if id == &message_id),
1586 ) else {
1587 return Err(anyhow!("Message not found"));
1588 };
1589
1590 for message in self.messages.drain(position..) {
1591 match message {
1592 Message::User(message) => {
1593 self.request_token_usage.remove(&message.id);
1594 }
1595 Message::Agent(_) | Message::Resume => {}
1596 }
1597 }
1598 self.clear_summary();
1599 cx.notify();
1600 Ok(())
1601 }
1602
1603 pub fn latest_request_token_usage(&self) -> Option<language_model::TokenUsage> {
1604 let last_user_message = self.last_user_message()?;
1605 let tokens = self.request_token_usage.get(&last_user_message.id)?;
1606 Some(*tokens)
1607 }
1608
1609 pub fn latest_token_usage(&self) -> Option<acp_thread::TokenUsage> {
1610 let usage = self.latest_request_token_usage()?;
1611 let model = self.model.clone()?;
1612 Some(acp_thread::TokenUsage {
1613 max_tokens: model.max_token_count(),
1614 max_output_tokens: model.max_output_tokens(),
1615 used_tokens: usage.total_tokens(),
1616 input_tokens: usage.input_tokens,
1617 output_tokens: usage.output_tokens,
1618 })
1619 }
1620
1621 /// Get the total input token count as of the message before the given message.
1622 ///
1623 /// Returns `None` if:
1624 /// - `target_id` is the first message (no previous message)
1625 /// - The previous message hasn't received a response yet (no usage data)
1626 /// - `target_id` is not found in the messages
1627 pub fn tokens_before_message(&self, target_id: &UserMessageId) -> Option<u64> {
1628 let mut previous_user_message_id: Option<&UserMessageId> = None;
1629
1630 for message in &self.messages {
1631 if let Message::User(user_msg) = message {
1632 if &user_msg.id == target_id {
1633 let prev_id = previous_user_message_id?;
1634 let usage = self.request_token_usage.get(prev_id)?;
1635 return Some(usage.input_tokens);
1636 }
1637 previous_user_message_id = Some(&user_msg.id);
1638 }
1639 }
1640 None
1641 }
1642
1643 /// Look up the active profile and resolve its preferred model if one is configured.
1644 fn resolve_profile_model(
1645 profile_id: &AgentProfileId,
1646 cx: &mut Context<Self>,
1647 ) -> Option<Arc<dyn LanguageModel>> {
1648 let selection = AgentSettings::get_global(cx)
1649 .profiles
1650 .get(profile_id)?
1651 .default_model
1652 .clone()?;
1653 Self::resolve_model_from_selection(&selection, cx)
1654 }
1655
1656 /// Translate a stored model selection into the configured model from the registry.
1657 fn resolve_model_from_selection(
1658 selection: &LanguageModelSelection,
1659 cx: &mut Context<Self>,
1660 ) -> Option<Arc<dyn LanguageModel>> {
1661 let selected = SelectedModel {
1662 provider: LanguageModelProviderId::from(selection.provider.0.clone()),
1663 model: LanguageModelId::from(selection.model.clone()),
1664 };
1665 LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
1666 registry
1667 .select_model(&selected, cx)
1668 .map(|configured| configured.model)
1669 })
1670 }
1671
1672 pub fn resume(
1673 &mut self,
1674 cx: &mut Context<Self>,
1675 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1676 self.messages.push(Message::Resume);
1677 cx.notify();
1678
1679 log::debug!("Total messages in thread: {}", self.messages.len());
1680 self.run_turn(cx)
1681 }
1682
1683 /// Sending a message results in the model streaming a response, which could include tool calls.
1684 /// After calling tools, the model will stops and waits for any outstanding tool calls to be completed and their results sent.
1685 /// The returned channel will report all the occurrences in which the model stops before erroring or ending its turn.
1686 pub fn send<T>(
1687 &mut self,
1688 id: UserMessageId,
1689 content: impl IntoIterator<Item = T>,
1690 cx: &mut Context<Self>,
1691 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>>
1692 where
1693 T: Into<UserMessageContent>,
1694 {
1695 let content = content.into_iter().map(Into::into).collect::<Vec<_>>();
1696 log::debug!("Thread::send content: {:?}", content);
1697
1698 self.messages
1699 .push(Message::User(UserMessage { id, content }));
1700 cx.notify();
1701
1702 self.send_existing(cx)
1703 }
1704
1705 pub fn send_existing(
1706 &mut self,
1707 cx: &mut Context<Self>,
1708 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1709 let model = self.model().context("No language model configured")?;
1710
1711 log::info!("Thread::send called with model: {}", model.name().0);
1712 self.advance_prompt_id();
1713
1714 log::debug!("Total messages in thread: {}", self.messages.len());
1715 self.run_turn(cx)
1716 }
1717
1718 pub fn push_acp_user_block(
1719 &mut self,
1720 id: UserMessageId,
1721 blocks: impl IntoIterator<Item = acp::ContentBlock>,
1722 path_style: PathStyle,
1723 cx: &mut Context<Self>,
1724 ) {
1725 let content = blocks
1726 .into_iter()
1727 .map(|block| UserMessageContent::from_content_block(block, path_style))
1728 .collect::<Vec<_>>();
1729 self.messages
1730 .push(Message::User(UserMessage { id, content }));
1731 cx.notify();
1732 }
1733
1734 pub fn push_acp_agent_block(&mut self, block: acp::ContentBlock, cx: &mut Context<Self>) {
1735 let text = match block {
1736 acp::ContentBlock::Text(text_content) => text_content.text,
1737 acp::ContentBlock::Image(_) => "[image]".to_string(),
1738 acp::ContentBlock::Audio(_) => "[audio]".to_string(),
1739 acp::ContentBlock::ResourceLink(resource_link) => resource_link.uri,
1740 acp::ContentBlock::Resource(resource) => match resource.resource {
1741 acp::EmbeddedResourceResource::TextResourceContents(resource) => resource.uri,
1742 acp::EmbeddedResourceResource::BlobResourceContents(resource) => resource.uri,
1743 _ => "[resource]".to_string(),
1744 },
1745 _ => "[unknown]".to_string(),
1746 };
1747
1748 self.messages.push(Message::Agent(AgentMessage {
1749 content: vec![AgentMessageContent::Text(text)],
1750 ..Default::default()
1751 }));
1752 cx.notify();
1753 }
1754
1755 #[cfg(feature = "eval")]
1756 pub fn proceed(
1757 &mut self,
1758 cx: &mut Context<Self>,
1759 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1760 self.run_turn(cx)
1761 }
1762
1763 fn run_turn(
1764 &mut self,
1765 cx: &mut Context<Self>,
1766 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1767 // Flush the old pending message synchronously before cancelling,
1768 // to avoid a race where the detached cancel task might flush the NEW
1769 // turn's pending message instead of the old one.
1770 self.flush_pending_message(cx);
1771 self.cancel(cx).detach();
1772
1773 let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
1774 let event_stream = ThreadEventStream(events_tx);
1775 let message_ix = self.messages.len().saturating_sub(1);
1776 self.clear_summary();
1777 let (cancellation_tx, mut cancellation_rx) = watch::channel(false);
1778 self.running_turn = Some(RunningTurn {
1779 event_stream: event_stream.clone(),
1780 tools: self.enabled_tools(cx),
1781 cancellation_tx,
1782 streaming_tool_inputs: HashMap::default(),
1783 _task: cx.spawn(async move |this, cx| {
1784 log::debug!("Starting agent turn execution");
1785
1786 let turn_result =
1787 Self::run_turn_internal(&this, &event_stream, cancellation_rx.clone(), cx)
1788 .await;
1789
1790 // Check if we were cancelled - if so, cancel() already took running_turn
1791 // and we shouldn't touch it (it might be a NEW turn now)
1792 let was_cancelled = *cancellation_rx.borrow();
1793 if was_cancelled {
1794 log::debug!("Turn was cancelled, skipping cleanup");
1795 return;
1796 }
1797
1798 _ = this.update(cx, |this, cx| this.flush_pending_message(cx));
1799
1800 match turn_result {
1801 Ok(()) => {
1802 log::debug!("Turn execution completed");
1803 event_stream.send_stop(acp::StopReason::EndTurn);
1804 }
1805 Err(error) => {
1806 log::error!("Turn execution failed: {:?}", error);
1807 match error.downcast::<CompletionError>() {
1808 Ok(CompletionError::Refusal) => {
1809 event_stream.send_stop(acp::StopReason::Refusal);
1810 _ = this.update(cx, |this, _| this.messages.truncate(message_ix));
1811 }
1812 Ok(CompletionError::MaxTokens) => {
1813 event_stream.send_stop(acp::StopReason::MaxTokens);
1814 }
1815 Ok(CompletionError::Other(error)) | Err(error) => {
1816 event_stream.send_error(error);
1817 }
1818 }
1819 }
1820 }
1821
1822 _ = this.update(cx, |this, _| this.running_turn.take());
1823 }),
1824 });
1825 Ok(events_rx)
1826 }
1827
1828 async fn run_turn_internal(
1829 this: &WeakEntity<Self>,
1830 event_stream: &ThreadEventStream,
1831 mut cancellation_rx: watch::Receiver<bool>,
1832 cx: &mut AsyncApp,
1833 ) -> Result<()> {
1834 let mut attempt = 0;
1835 let mut intent = CompletionIntent::UserPrompt;
1836 loop {
1837 // Re-read the model and refresh tools on each iteration so that
1838 // mid-turn changes (e.g. the user switches model, toggles tools,
1839 // or changes profile) take effect between tool-call rounds.
1840 let (model, request) = this.update(cx, |this, cx| {
1841 let model = this.model.clone().context("No language model configured")?;
1842 this.refresh_turn_tools(cx);
1843 let request = this.build_completion_request(intent, cx)?;
1844 anyhow::Ok((model, request))
1845 })??;
1846
1847 telemetry::event!(
1848 "Agent Thread Completion",
1849 thread_id = this.read_with(cx, |this, _| this.id.to_string())?,
1850 parent_thread_id = this.read_with(cx, |this, _| this
1851 .parent_thread_id()
1852 .map(|id| id.to_string()))?,
1853 prompt_id = this.read_with(cx, |this, _| this.prompt_id.to_string())?,
1854 model = model.telemetry_id(),
1855 model_provider = model.provider_id().to_string(),
1856 attempt
1857 );
1858
1859 log::debug!("Calling model.stream_completion, attempt {}", attempt);
1860
1861 let (mut events, mut error) = match model.stream_completion(request, cx).await {
1862 Ok(events) => (events.fuse(), None),
1863 Err(err) => (stream::empty().boxed().fuse(), Some(err)),
1864 };
1865 let mut tool_results: FuturesUnordered<Task<LanguageModelToolResult>> =
1866 FuturesUnordered::new();
1867 let mut early_tool_results: Vec<LanguageModelToolResult> = Vec::new();
1868 let mut cancelled = false;
1869 loop {
1870 // Race between getting the first event, tool completion, and cancellation.
1871 let first_event = futures::select! {
1872 event = events.next().fuse() => event,
1873 tool_result = futures::StreamExt::select_next_some(&mut tool_results) => {
1874 let is_error = tool_result.is_error;
1875 let is_still_streaming = this
1876 .read_with(cx, |this, _cx| {
1877 this.running_turn
1878 .as_ref()
1879 .and_then(|turn| turn.streaming_tool_inputs.get(&tool_result.tool_use_id))
1880 .map_or(false, |inputs| !inputs.has_received_final())
1881 })
1882 .unwrap_or(false);
1883
1884 early_tool_results.push(tool_result);
1885
1886 // Only break if the tool errored and we are still
1887 // streaming the input of the tool. If the tool errored
1888 // but we are no longer streaming its input (i.e. there
1889 // are parallel tool calls) we want to continue
1890 // processing those tool inputs.
1891 if is_error && is_still_streaming {
1892 break;
1893 }
1894 continue;
1895 }
1896 _ = cancellation_rx.changed().fuse() => {
1897 if *cancellation_rx.borrow() {
1898 cancelled = true;
1899 break;
1900 }
1901 continue;
1902 }
1903 };
1904 let Some(first_event) = first_event else {
1905 break;
1906 };
1907
1908 // Collect all immediately available events to process as a batch
1909 let mut batch = vec![first_event];
1910 while let Some(event) = events.next().now_or_never().flatten() {
1911 batch.push(event);
1912 }
1913
1914 // Process the batch in a single update
1915 let batch_result = this.update(cx, |this, cx| {
1916 let mut batch_tool_results = Vec::new();
1917 let mut batch_error = None;
1918
1919 for event in batch {
1920 log::trace!("Received completion event: {:?}", event);
1921 match event {
1922 Ok(event) => {
1923 match this.handle_completion_event(
1924 event,
1925 event_stream,
1926 cancellation_rx.clone(),
1927 cx,
1928 ) {
1929 Ok(Some(task)) => batch_tool_results.push(task),
1930 Ok(None) => {}
1931 Err(err) => {
1932 batch_error = Some(err);
1933 break;
1934 }
1935 }
1936 }
1937 Err(err) => {
1938 batch_error = Some(err.into());
1939 break;
1940 }
1941 }
1942 }
1943
1944 cx.notify();
1945 (batch_tool_results, batch_error)
1946 })?;
1947
1948 tool_results.extend(batch_result.0);
1949 if let Some(err) = batch_result.1 {
1950 error = Some(err.downcast()?);
1951 break;
1952 }
1953 }
1954
1955 // Drop the stream to release the rate limit permit before tool execution.
1956 // The stream holds a semaphore guard that limits concurrent requests.
1957 // Without this, the permit would be held during potentially long-running
1958 // tool execution, which could cause deadlocks when tools spawn subagents
1959 // that need their own permits.
1960 drop(events);
1961
1962 // Drop streaming tool input senders that never received their final input.
1963 // This prevents deadlock when the LLM stream ends (e.g. because of an error)
1964 // before sending a tool use with `is_input_complete: true`.
1965 this.update(cx, |this, _cx| {
1966 if let Some(running_turn) = this.running_turn.as_mut() {
1967 if running_turn.streaming_tool_inputs.is_empty() {
1968 return;
1969 }
1970 log::warn!("Dropping partial tool inputs because the stream ended");
1971 running_turn.streaming_tool_inputs.drain();
1972 }
1973 })?;
1974
1975 let end_turn = tool_results.is_empty() && early_tool_results.is_empty();
1976
1977 for tool_result in early_tool_results {
1978 Self::process_tool_result(this, event_stream, cx, tool_result)?;
1979 }
1980 while let Some(tool_result) = tool_results.next().await {
1981 Self::process_tool_result(this, event_stream, cx, tool_result)?;
1982 }
1983
1984 this.update(cx, |this, cx| {
1985 this.flush_pending_message(cx);
1986 if this.title.is_none() && this.pending_title_generation.is_none() {
1987 this.generate_title(cx);
1988 }
1989 })?;
1990
1991 if cancelled {
1992 log::debug!("Turn cancelled by user, exiting");
1993 return Ok(());
1994 }
1995
1996 if let Some(error) = error {
1997 attempt += 1;
1998 let retry = this.update(cx, |this, cx| {
1999 let user_store = this.user_store.read(cx);
2000 this.handle_completion_error(error, attempt, user_store.plan())
2001 })??;
2002 let timer = cx.background_executor().timer(retry.duration);
2003 event_stream.send_retry(retry);
2004 futures::select! {
2005 _ = timer.fuse() => {}
2006 _ = cancellation_rx.changed().fuse() => {
2007 if *cancellation_rx.borrow() {
2008 log::debug!("Turn cancelled during retry delay, exiting");
2009 return Ok(());
2010 }
2011 }
2012 }
2013 this.update(cx, |this, _cx| {
2014 if let Some(Message::Agent(message)) = this.messages.last() {
2015 if message.tool_results.is_empty() {
2016 intent = CompletionIntent::UserPrompt;
2017 this.messages.push(Message::Resume);
2018 }
2019 }
2020 })?;
2021 } else if end_turn {
2022 return Ok(());
2023 } else {
2024 let has_queued = this.update(cx, |this, _| this.has_queued_message())?;
2025 if has_queued {
2026 log::debug!("Queued message found, ending turn at message boundary");
2027 return Ok(());
2028 }
2029 intent = CompletionIntent::ToolResults;
2030 attempt = 0;
2031 }
2032 }
2033 }
2034
2035 fn process_tool_result(
2036 this: &WeakEntity<Thread>,
2037 event_stream: &ThreadEventStream,
2038 cx: &mut AsyncApp,
2039 tool_result: LanguageModelToolResult,
2040 ) -> Result<(), anyhow::Error> {
2041 log::debug!("Tool finished {:?}", tool_result);
2042
2043 event_stream.update_tool_call_fields(
2044 &tool_result.tool_use_id,
2045 acp::ToolCallUpdateFields::new()
2046 .status(if tool_result.is_error {
2047 acp::ToolCallStatus::Failed
2048 } else {
2049 acp::ToolCallStatus::Completed
2050 })
2051 .raw_output(tool_result.output.clone()),
2052 None,
2053 );
2054 this.update(cx, |this, _cx| {
2055 this.pending_message()
2056 .tool_results
2057 .insert(tool_result.tool_use_id.clone(), tool_result);
2058 })?;
2059 Ok(())
2060 }
2061
2062 fn handle_completion_error(
2063 &mut self,
2064 error: LanguageModelCompletionError,
2065 attempt: u8,
2066 plan: Option<Plan>,
2067 ) -> Result<acp_thread::RetryStatus> {
2068 let Some(model) = self.model.as_ref() else {
2069 return Err(anyhow!(error));
2070 };
2071
2072 let auto_retry = if model.provider_id() == ZED_CLOUD_PROVIDER_ID {
2073 plan.is_some()
2074 } else {
2075 true
2076 };
2077
2078 if !auto_retry {
2079 return Err(anyhow!(error));
2080 }
2081
2082 let Some(strategy) = Self::retry_strategy_for(&error) else {
2083 return Err(anyhow!(error));
2084 };
2085
2086 let max_attempts = match &strategy {
2087 RetryStrategy::ExponentialBackoff { max_attempts, .. } => *max_attempts,
2088 RetryStrategy::Fixed { max_attempts, .. } => *max_attempts,
2089 };
2090
2091 if attempt > max_attempts {
2092 return Err(anyhow!(error));
2093 }
2094
2095 let delay = match &strategy {
2096 RetryStrategy::ExponentialBackoff { initial_delay, .. } => {
2097 let delay_secs = initial_delay.as_secs() * 2u64.pow((attempt - 1) as u32);
2098 Duration::from_secs(delay_secs)
2099 }
2100 RetryStrategy::Fixed { delay, .. } => *delay,
2101 };
2102 log::debug!("Retry attempt {attempt} with delay {delay:?}");
2103
2104 Ok(acp_thread::RetryStatus {
2105 last_error: error.to_string().into(),
2106 attempt: attempt as usize,
2107 max_attempts: max_attempts as usize,
2108 started_at: Instant::now(),
2109 duration: delay,
2110 })
2111 }
2112
2113 /// A helper method that's called on every streamed completion event.
2114 /// Returns an optional tool result task, which the main agentic loop will
2115 /// send back to the model when it resolves.
2116 fn handle_completion_event(
2117 &mut self,
2118 event: LanguageModelCompletionEvent,
2119 event_stream: &ThreadEventStream,
2120 cancellation_rx: watch::Receiver<bool>,
2121 cx: &mut Context<Self>,
2122 ) -> Result<Option<Task<LanguageModelToolResult>>> {
2123 log::trace!("Handling streamed completion event: {:?}", event);
2124 use LanguageModelCompletionEvent::*;
2125
2126 match event {
2127 StartMessage { .. } => {
2128 self.flush_pending_message(cx);
2129 self.pending_message = Some(AgentMessage::default());
2130 }
2131 Text(new_text) => self.handle_text_event(new_text, event_stream),
2132 Thinking { text, signature } => {
2133 self.handle_thinking_event(text, signature, event_stream)
2134 }
2135 RedactedThinking { data } => self.handle_redacted_thinking_event(data),
2136 ReasoningDetails(details) => {
2137 let last_message = self.pending_message();
2138 // Store the last non-empty reasoning_details (overwrites earlier ones)
2139 // This ensures we keep the encrypted reasoning with signatures, not the early text reasoning
2140 if let serde_json::Value::Array(ref arr) = details {
2141 if !arr.is_empty() {
2142 last_message.reasoning_details = Some(details);
2143 }
2144 } else {
2145 last_message.reasoning_details = Some(details);
2146 }
2147 }
2148 ToolUse(tool_use) => {
2149 return Ok(self.handle_tool_use_event(tool_use, event_stream, cancellation_rx, cx));
2150 }
2151 ToolUseJsonParseError {
2152 id,
2153 tool_name,
2154 raw_input,
2155 json_parse_error,
2156 } => {
2157 return Ok(Some(Task::ready(
2158 self.handle_tool_use_json_parse_error_event(
2159 id,
2160 tool_name,
2161 raw_input,
2162 json_parse_error,
2163 event_stream,
2164 ),
2165 )));
2166 }
2167 UsageUpdate(usage) => {
2168 telemetry::event!(
2169 "Agent Thread Completion Usage Updated",
2170 thread_id = self.id.to_string(),
2171 parent_thread_id = self.parent_thread_id().map(|id| id.to_string()),
2172 prompt_id = self.prompt_id.to_string(),
2173 model = self.model.as_ref().map(|m| m.telemetry_id()),
2174 model_provider = self.model.as_ref().map(|m| m.provider_id().to_string()),
2175 input_tokens = usage.input_tokens,
2176 output_tokens = usage.output_tokens,
2177 cache_creation_input_tokens = usage.cache_creation_input_tokens,
2178 cache_read_input_tokens = usage.cache_read_input_tokens,
2179 );
2180 self.update_token_usage(usage, cx);
2181 }
2182 Stop(StopReason::Refusal) => return Err(CompletionError::Refusal.into()),
2183 Stop(StopReason::MaxTokens) => return Err(CompletionError::MaxTokens.into()),
2184 Stop(StopReason::ToolUse | StopReason::EndTurn) => {}
2185 Started | Queued { .. } => {}
2186 }
2187
2188 Ok(None)
2189 }
2190
2191 fn handle_text_event(&mut self, new_text: String, event_stream: &ThreadEventStream) {
2192 event_stream.send_text(&new_text);
2193
2194 let last_message = self.pending_message();
2195 if let Some(AgentMessageContent::Text(text)) = last_message.content.last_mut() {
2196 text.push_str(&new_text);
2197 } else {
2198 last_message
2199 .content
2200 .push(AgentMessageContent::Text(new_text));
2201 }
2202 }
2203
2204 fn handle_thinking_event(
2205 &mut self,
2206 new_text: String,
2207 new_signature: Option<String>,
2208 event_stream: &ThreadEventStream,
2209 ) {
2210 event_stream.send_thinking(&new_text);
2211
2212 let last_message = self.pending_message();
2213 if let Some(AgentMessageContent::Thinking { text, signature }) =
2214 last_message.content.last_mut()
2215 {
2216 text.push_str(&new_text);
2217 *signature = new_signature.or(signature.take());
2218 } else {
2219 last_message.content.push(AgentMessageContent::Thinking {
2220 text: new_text,
2221 signature: new_signature,
2222 });
2223 }
2224 }
2225
2226 fn handle_redacted_thinking_event(&mut self, data: String) {
2227 let last_message = self.pending_message();
2228 last_message
2229 .content
2230 .push(AgentMessageContent::RedactedThinking(data));
2231 }
2232
2233 fn handle_tool_use_event(
2234 &mut self,
2235 tool_use: LanguageModelToolUse,
2236 event_stream: &ThreadEventStream,
2237 cancellation_rx: watch::Receiver<bool>,
2238 cx: &mut Context<Self>,
2239 ) -> Option<Task<LanguageModelToolResult>> {
2240 cx.notify();
2241
2242 let tool = self.tool(tool_use.name.as_ref());
2243 let mut title = SharedString::from(&tool_use.name);
2244 let mut kind = acp::ToolKind::Other;
2245 if let Some(tool) = tool.as_ref() {
2246 title = tool.initial_title(tool_use.input.clone(), cx);
2247 kind = tool.kind();
2248 }
2249
2250 self.send_or_update_tool_use(&tool_use, title, kind, event_stream);
2251
2252 let Some(tool) = tool else {
2253 let content = format!("No tool named {} exists", tool_use.name);
2254 return Some(Task::ready(LanguageModelToolResult {
2255 content: LanguageModelToolResultContent::Text(Arc::from(content)),
2256 tool_use_id: tool_use.id,
2257 tool_name: tool_use.name,
2258 is_error: true,
2259 output: None,
2260 }));
2261 };
2262
2263 if !tool_use.is_input_complete {
2264 if tool.supports_input_streaming() {
2265 let running_turn = self.running_turn.as_mut()?;
2266 if let Some(sender) = running_turn.streaming_tool_inputs.get(&tool_use.id) {
2267 sender.send_partial(tool_use.input);
2268 return None;
2269 }
2270
2271 let (sender, tool_input) = ToolInputSender::channel();
2272 sender.send_partial(tool_use.input);
2273 running_turn
2274 .streaming_tool_inputs
2275 .insert(tool_use.id.clone(), sender);
2276
2277 let tool = tool.clone();
2278 log::debug!("Running streaming tool {}", tool_use.name);
2279 return Some(self.run_tool(
2280 tool,
2281 tool_input,
2282 tool_use.id,
2283 tool_use.name,
2284 event_stream,
2285 cancellation_rx,
2286 cx,
2287 ));
2288 } else {
2289 return None;
2290 }
2291 }
2292
2293 if let Some(sender) = self
2294 .running_turn
2295 .as_mut()?
2296 .streaming_tool_inputs
2297 .remove(&tool_use.id)
2298 {
2299 sender.send_final(tool_use.input);
2300 return None;
2301 }
2302
2303 log::debug!("Running tool {}", tool_use.name);
2304 let tool_input = ToolInput::ready(tool_use.input);
2305 Some(self.run_tool(
2306 tool,
2307 tool_input,
2308 tool_use.id,
2309 tool_use.name,
2310 event_stream,
2311 cancellation_rx,
2312 cx,
2313 ))
2314 }
2315
2316 fn run_tool(
2317 &self,
2318 tool: Arc<dyn AnyAgentTool>,
2319 tool_input: ToolInput<serde_json::Value>,
2320 tool_use_id: LanguageModelToolUseId,
2321 tool_name: Arc<str>,
2322 event_stream: &ThreadEventStream,
2323 cancellation_rx: watch::Receiver<bool>,
2324 cx: &mut Context<Self>,
2325 ) -> Task<LanguageModelToolResult> {
2326 let fs = self.project.read(cx).fs().clone();
2327 let tool_event_stream = ToolCallEventStream::new(
2328 tool_use_id.clone(),
2329 event_stream.clone(),
2330 Some(fs),
2331 cancellation_rx,
2332 );
2333 tool_event_stream.update_fields(
2334 acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::InProgress),
2335 );
2336 let supports_images = self.model().is_some_and(|model| model.supports_images());
2337 let tool_result = tool.run(tool_input, tool_event_stream, cx);
2338 cx.foreground_executor().spawn(async move {
2339 let (is_error, output) = match tool_result.await {
2340 Ok(mut output) => {
2341 if let LanguageModelToolResultContent::Image(_) = &output.llm_output
2342 && !supports_images
2343 {
2344 output = AgentToolOutput::from_error(
2345 "Attempted to read an image, but this model doesn't support it.",
2346 );
2347 (true, output)
2348 } else {
2349 (false, output)
2350 }
2351 }
2352 Err(output) => (true, output),
2353 };
2354
2355 LanguageModelToolResult {
2356 tool_use_id,
2357 tool_name,
2358 is_error,
2359 content: output.llm_output,
2360 output: Some(output.raw_output),
2361 }
2362 })
2363 }
2364
2365 fn handle_tool_use_json_parse_error_event(
2366 &mut self,
2367 tool_use_id: LanguageModelToolUseId,
2368 tool_name: Arc<str>,
2369 raw_input: Arc<str>,
2370 json_parse_error: String,
2371 event_stream: &ThreadEventStream,
2372 ) -> LanguageModelToolResult {
2373 let tool_use = LanguageModelToolUse {
2374 id: tool_use_id.clone(),
2375 name: tool_name.clone(),
2376 raw_input: raw_input.to_string(),
2377 input: serde_json::json!({}),
2378 is_input_complete: true,
2379 thought_signature: None,
2380 };
2381 self.send_or_update_tool_use(
2382 &tool_use,
2383 SharedString::from(&tool_use.name),
2384 acp::ToolKind::Other,
2385 event_stream,
2386 );
2387
2388 let tool_output = format!("Error parsing input JSON: {json_parse_error}");
2389 LanguageModelToolResult {
2390 tool_use_id,
2391 tool_name,
2392 is_error: true,
2393 content: LanguageModelToolResultContent::Text(tool_output.into()),
2394 output: Some(serde_json::Value::String(raw_input.to_string())),
2395 }
2396 }
2397
2398 fn send_or_update_tool_use(
2399 &mut self,
2400 tool_use: &LanguageModelToolUse,
2401 title: SharedString,
2402 kind: acp::ToolKind,
2403 event_stream: &ThreadEventStream,
2404 ) {
2405 // Ensure the last message ends in the current tool use
2406 let last_message = self.pending_message();
2407
2408 let has_tool_use = last_message.content.iter_mut().rev().any(|content| {
2409 if let AgentMessageContent::ToolUse(last_tool_use) = content {
2410 if last_tool_use.id == tool_use.id {
2411 *last_tool_use = tool_use.clone();
2412 return true;
2413 }
2414 }
2415 false
2416 });
2417
2418 if !has_tool_use {
2419 event_stream.send_tool_call(
2420 &tool_use.id,
2421 &tool_use.name,
2422 title,
2423 kind,
2424 tool_use.input.clone(),
2425 );
2426 last_message
2427 .content
2428 .push(AgentMessageContent::ToolUse(tool_use.clone()));
2429 } else {
2430 event_stream.update_tool_call_fields(
2431 &tool_use.id,
2432 acp::ToolCallUpdateFields::new()
2433 .title(title.as_str())
2434 .kind(kind)
2435 .raw_input(tool_use.input.clone()),
2436 None,
2437 );
2438 }
2439 }
2440
2441 pub fn title(&self) -> SharedString {
2442 self.title.clone().unwrap_or("New Thread".into())
2443 }
2444
2445 pub fn is_generating_summary(&self) -> bool {
2446 self.pending_summary_generation.is_some()
2447 }
2448
2449 pub fn is_generating_title(&self) -> bool {
2450 self.pending_title_generation.is_some()
2451 }
2452
2453 pub fn summary(&mut self, cx: &mut Context<Self>) -> Shared<Task<Option<SharedString>>> {
2454 if let Some(summary) = self.summary.as_ref() {
2455 return Task::ready(Some(summary.clone())).shared();
2456 }
2457 if let Some(task) = self.pending_summary_generation.clone() {
2458 return task;
2459 }
2460 let Some(model) = self.summarization_model.clone() else {
2461 log::error!("No summarization model available");
2462 return Task::ready(None).shared();
2463 };
2464 let mut request = LanguageModelRequest {
2465 intent: Some(CompletionIntent::ThreadContextSummarization),
2466 temperature: AgentSettings::temperature_for_model(&model, cx),
2467 ..Default::default()
2468 };
2469
2470 for message in &self.messages {
2471 request.messages.extend(message.to_request());
2472 }
2473
2474 request.messages.push(LanguageModelRequestMessage {
2475 role: Role::User,
2476 content: vec![SUMMARIZE_THREAD_DETAILED_PROMPT.into()],
2477 cache: false,
2478 reasoning_details: None,
2479 });
2480
2481 let task = cx
2482 .spawn(async move |this, cx| {
2483 let mut summary = String::new();
2484 let mut messages = model.stream_completion(request, cx).await.log_err()?;
2485 while let Some(event) = messages.next().await {
2486 let event = event.log_err()?;
2487 let text = match event {
2488 LanguageModelCompletionEvent::Text(text) => text,
2489 _ => continue,
2490 };
2491
2492 let mut lines = text.lines();
2493 summary.extend(lines.next());
2494 }
2495
2496 log::debug!("Setting summary: {}", summary);
2497 let summary = SharedString::from(summary);
2498
2499 this.update(cx, |this, cx| {
2500 this.summary = Some(summary.clone());
2501 this.pending_summary_generation = None;
2502 cx.notify()
2503 })
2504 .ok()?;
2505
2506 Some(summary)
2507 })
2508 .shared();
2509 self.pending_summary_generation = Some(task.clone());
2510 task
2511 }
2512
2513 pub fn generate_title(&mut self, cx: &mut Context<Self>) {
2514 let Some(model) = self.summarization_model.clone() else {
2515 return;
2516 };
2517
2518 log::debug!(
2519 "Generating title with model: {:?}",
2520 self.summarization_model.as_ref().map(|model| model.name())
2521 );
2522 let mut request = LanguageModelRequest {
2523 intent: Some(CompletionIntent::ThreadSummarization),
2524 temperature: AgentSettings::temperature_for_model(&model, cx),
2525 ..Default::default()
2526 };
2527
2528 for message in &self.messages {
2529 request.messages.extend(message.to_request());
2530 }
2531
2532 request.messages.push(LanguageModelRequestMessage {
2533 role: Role::User,
2534 content: vec![SUMMARIZE_THREAD_PROMPT.into()],
2535 cache: false,
2536 reasoning_details: None,
2537 });
2538 self.pending_title_generation = Some(cx.spawn(async move |this, cx| {
2539 let mut title = String::new();
2540
2541 let generate = async {
2542 let mut messages = model.stream_completion(request, cx).await?;
2543 while let Some(event) = messages.next().await {
2544 let event = event?;
2545 let text = match event {
2546 LanguageModelCompletionEvent::Text(text) => text,
2547 _ => continue,
2548 };
2549
2550 let mut lines = text.lines();
2551 title.extend(lines.next());
2552
2553 // Stop if the LLM generated multiple lines.
2554 if lines.next().is_some() {
2555 break;
2556 }
2557 }
2558 anyhow::Ok(())
2559 };
2560
2561 if generate
2562 .await
2563 .context("failed to generate thread title")
2564 .log_err()
2565 .is_some()
2566 {
2567 _ = this.update(cx, |this, cx| this.set_title(title.into(), cx));
2568 } else {
2569 // Emit TitleUpdated even on failure so that the propagation
2570 // chain (agent::Thread → NativeAgent → AcpThread) fires and
2571 // clears any provisional title that was set before the turn.
2572 _ = this.update(cx, |_, cx| {
2573 cx.emit(TitleUpdated);
2574 cx.notify();
2575 });
2576 }
2577 _ = this.update(cx, |this, _| this.pending_title_generation = None);
2578 }));
2579 }
2580
2581 pub fn set_title(&mut self, title: SharedString, cx: &mut Context<Self>) {
2582 self.pending_title_generation = None;
2583 if Some(&title) != self.title.as_ref() {
2584 self.title = Some(title);
2585 cx.emit(TitleUpdated);
2586 cx.notify();
2587 }
2588 }
2589
2590 fn clear_summary(&mut self) {
2591 self.summary = None;
2592 self.pending_summary_generation = None;
2593 }
2594
2595 fn last_user_message(&self) -> Option<&UserMessage> {
2596 self.messages
2597 .iter()
2598 .rev()
2599 .find_map(|message| match message {
2600 Message::User(user_message) => Some(user_message),
2601 Message::Agent(_) => None,
2602 Message::Resume => None,
2603 })
2604 }
2605
2606 fn pending_message(&mut self) -> &mut AgentMessage {
2607 self.pending_message.get_or_insert_default()
2608 }
2609
2610 fn flush_pending_message(&mut self, cx: &mut Context<Self>) {
2611 let Some(mut message) = self.pending_message.take() else {
2612 return;
2613 };
2614
2615 if message.content.is_empty() {
2616 return;
2617 }
2618
2619 for content in &message.content {
2620 let AgentMessageContent::ToolUse(tool_use) = content else {
2621 continue;
2622 };
2623
2624 if !message.tool_results.contains_key(&tool_use.id) {
2625 message.tool_results.insert(
2626 tool_use.id.clone(),
2627 LanguageModelToolResult {
2628 tool_use_id: tool_use.id.clone(),
2629 tool_name: tool_use.name.clone(),
2630 is_error: true,
2631 content: LanguageModelToolResultContent::Text(TOOL_CANCELED_MESSAGE.into()),
2632 output: None,
2633 },
2634 );
2635 }
2636 }
2637
2638 self.messages.push(Message::Agent(message));
2639 self.updated_at = Utc::now();
2640 self.clear_summary();
2641 cx.notify()
2642 }
2643
2644 pub(crate) fn build_completion_request(
2645 &self,
2646 completion_intent: CompletionIntent,
2647 cx: &App,
2648 ) -> Result<LanguageModelRequest> {
2649 let completion_intent =
2650 if self.is_subagent() && completion_intent == CompletionIntent::UserPrompt {
2651 CompletionIntent::Subagent
2652 } else {
2653 completion_intent
2654 };
2655
2656 let model = self.model().context("No language model configured")?;
2657 let tools = if let Some(turn) = self.running_turn.as_ref() {
2658 turn.tools
2659 .iter()
2660 .filter_map(|(tool_name, tool)| {
2661 log::trace!("Including tool: {}", tool_name);
2662 Some(LanguageModelRequestTool {
2663 name: tool_name.to_string(),
2664 description: tool.description().to_string(),
2665 input_schema: tool.input_schema(model.tool_input_format()).log_err()?,
2666 use_input_streaming: tool.supports_input_streaming(),
2667 })
2668 })
2669 .collect::<Vec<_>>()
2670 } else {
2671 Vec::new()
2672 };
2673
2674 log::debug!("Building completion request");
2675 log::debug!("Completion intent: {:?}", completion_intent);
2676
2677 let available_tools: Vec<_> = self
2678 .running_turn
2679 .as_ref()
2680 .map(|turn| turn.tools.keys().cloned().collect())
2681 .unwrap_or_default();
2682
2683 log::debug!("Request includes {} tools", available_tools.len());
2684 let messages = self.build_request_messages(available_tools, cx);
2685 log::debug!("Request will include {} messages", messages.len());
2686
2687 let request = LanguageModelRequest {
2688 thread_id: Some(self.id.to_string()),
2689 prompt_id: Some(self.prompt_id.to_string()),
2690 intent: Some(completion_intent),
2691 messages,
2692 tools,
2693 tool_choice: None,
2694 stop: Vec::new(),
2695 temperature: AgentSettings::temperature_for_model(model, cx),
2696 thinking_allowed: self.thinking_enabled,
2697 thinking_effort: self.thinking_effort.clone(),
2698 speed: self.speed(),
2699 };
2700
2701 log::debug!("Completion request built successfully");
2702 Ok(request)
2703 }
2704
2705 fn enabled_tools(&self, cx: &App) -> BTreeMap<SharedString, Arc<dyn AnyAgentTool>> {
2706 let Some(model) = self.model.as_ref() else {
2707 return BTreeMap::new();
2708 };
2709 let Some(profile) = AgentSettings::get_global(cx).profiles.get(&self.profile_id) else {
2710 return BTreeMap::new();
2711 };
2712 fn truncate(tool_name: &SharedString) -> SharedString {
2713 if tool_name.len() > MAX_TOOL_NAME_LENGTH {
2714 let mut truncated = tool_name.to_string();
2715 truncated.truncate(MAX_TOOL_NAME_LENGTH);
2716 truncated.into()
2717 } else {
2718 tool_name.clone()
2719 }
2720 }
2721
2722 let use_streaming_edit_tool =
2723 cx.has_flag::<StreamingEditFileToolFeatureFlag>() && model.supports_streaming_tools();
2724
2725 let mut tools = self
2726 .tools
2727 .iter()
2728 .filter_map(|(tool_name, tool)| {
2729 // For streaming_edit_file, check profile against "edit_file" since that's what users configure
2730 let profile_tool_name = if tool_name == StreamingEditFileTool::NAME {
2731 EditFileTool::NAME
2732 } else {
2733 tool_name.as_ref()
2734 };
2735
2736 if tool.supports_provider(&model.provider_id())
2737 && profile.is_tool_enabled(profile_tool_name)
2738 {
2739 match (tool_name.as_ref(), use_streaming_edit_tool) {
2740 (StreamingEditFileTool::NAME, false) | (EditFileTool::NAME, true) => None,
2741 (StreamingEditFileTool::NAME, true) => {
2742 // Expose streaming tool as "edit_file"
2743 Some((SharedString::from(EditFileTool::NAME), tool.clone()))
2744 }
2745 _ => Some((truncate(tool_name), tool.clone())),
2746 }
2747 } else {
2748 None
2749 }
2750 })
2751 .collect::<BTreeMap<_, _>>();
2752
2753 let mut context_server_tools = Vec::new();
2754 let mut seen_tools = tools.keys().cloned().collect::<HashSet<_>>();
2755 let mut duplicate_tool_names = HashSet::default();
2756 for (server_id, server_tools) in self.context_server_registry.read(cx).servers() {
2757 for (tool_name, tool) in server_tools {
2758 if profile.is_context_server_tool_enabled(&server_id.0, &tool_name) {
2759 let tool_name = truncate(tool_name);
2760 if !seen_tools.insert(tool_name.clone()) {
2761 duplicate_tool_names.insert(tool_name.clone());
2762 }
2763 context_server_tools.push((server_id.clone(), tool_name, tool.clone()));
2764 }
2765 }
2766 }
2767
2768 // When there are duplicate tool names, disambiguate by prefixing them
2769 // with the server ID (converted to snake_case for API compatibility).
2770 // In the rare case there isn't enough space for the disambiguated tool
2771 // name, keep only the last tool with this name.
2772 for (server_id, tool_name, tool) in context_server_tools {
2773 if duplicate_tool_names.contains(&tool_name) {
2774 let available = MAX_TOOL_NAME_LENGTH.saturating_sub(tool_name.len());
2775 if available >= 2 {
2776 let mut disambiguated = server_id.0.to_snake_case();
2777 disambiguated.truncate(available - 1);
2778 disambiguated.push('_');
2779 disambiguated.push_str(&tool_name);
2780 tools.insert(disambiguated.into(), tool.clone());
2781 } else {
2782 tools.insert(tool_name, tool.clone());
2783 }
2784 } else {
2785 tools.insert(tool_name, tool.clone());
2786 }
2787 }
2788
2789 tools
2790 }
2791
2792 fn refresh_turn_tools(&mut self, cx: &App) {
2793 let tools = self.enabled_tools(cx);
2794 if let Some(turn) = self.running_turn.as_mut() {
2795 turn.tools = tools;
2796 }
2797 }
2798
2799 fn tool(&self, name: &str) -> Option<Arc<dyn AnyAgentTool>> {
2800 self.running_turn.as_ref()?.tools.get(name).cloned()
2801 }
2802
2803 pub fn has_tool(&self, name: &str) -> bool {
2804 self.running_turn
2805 .as_ref()
2806 .is_some_and(|turn| turn.tools.contains_key(name))
2807 }
2808
2809 #[cfg(any(test, feature = "test-support"))]
2810 pub fn has_registered_tool(&self, name: &str) -> bool {
2811 self.tools.contains_key(name)
2812 }
2813
2814 pub fn registered_tool_names(&self) -> Vec<SharedString> {
2815 self.tools.keys().cloned().collect()
2816 }
2817
2818 pub(crate) fn register_running_subagent(&mut self, subagent: WeakEntity<Thread>) {
2819 self.running_subagents.push(subagent);
2820 }
2821
2822 pub(crate) fn unregister_running_subagent(
2823 &mut self,
2824 subagent_session_id: &acp::SessionId,
2825 cx: &App,
2826 ) {
2827 self.running_subagents.retain(|s| {
2828 s.upgrade()
2829 .map_or(false, |s| s.read(cx).id() != subagent_session_id)
2830 });
2831 }
2832
2833 #[cfg(any(test, feature = "test-support"))]
2834 pub fn running_subagent_ids(&self, cx: &App) -> Vec<acp::SessionId> {
2835 self.running_subagents
2836 .iter()
2837 .filter_map(|s| s.upgrade().map(|s| s.read(cx).id().clone()))
2838 .collect()
2839 }
2840
2841 pub fn is_subagent(&self) -> bool {
2842 self.subagent_context.is_some()
2843 }
2844
2845 pub fn parent_thread_id(&self) -> Option<acp::SessionId> {
2846 self.subagent_context
2847 .as_ref()
2848 .map(|c| c.parent_thread_id.clone())
2849 }
2850
2851 pub fn depth(&self) -> u8 {
2852 self.subagent_context.as_ref().map(|c| c.depth).unwrap_or(0)
2853 }
2854
2855 #[cfg(any(test, feature = "test-support"))]
2856 pub fn set_subagent_context(&mut self, context: SubagentContext) {
2857 self.subagent_context = Some(context);
2858 }
2859
2860 pub fn is_turn_complete(&self) -> bool {
2861 self.running_turn.is_none()
2862 }
2863
2864 fn build_request_messages(
2865 &self,
2866 available_tools: Vec<SharedString>,
2867 cx: &App,
2868 ) -> Vec<LanguageModelRequestMessage> {
2869 log::trace!(
2870 "Building request messages from {} thread messages",
2871 self.messages.len()
2872 );
2873
2874 let system_prompt = SystemPromptTemplate {
2875 project: self.project_context.read(cx),
2876 available_tools,
2877 model_name: self.model.as_ref().map(|m| m.name().0.to_string()),
2878 }
2879 .render(&self.templates)
2880 .context("failed to build system prompt")
2881 .expect("Invalid template");
2882 let mut messages = vec![LanguageModelRequestMessage {
2883 role: Role::System,
2884 content: vec![system_prompt.into()],
2885 cache: false,
2886 reasoning_details: None,
2887 }];
2888 for message in &self.messages {
2889 messages.extend(message.to_request());
2890 }
2891
2892 if let Some(last_message) = messages.last_mut() {
2893 last_message.cache = true;
2894 }
2895
2896 if let Some(message) = self.pending_message.as_ref() {
2897 messages.extend(message.to_request());
2898 }
2899
2900 messages
2901 }
2902
2903 pub fn to_markdown(&self) -> String {
2904 let mut markdown = String::new();
2905 for (ix, message) in self.messages.iter().enumerate() {
2906 if ix > 0 {
2907 markdown.push('\n');
2908 }
2909 match message {
2910 Message::User(_) => markdown.push_str("## User\n\n"),
2911 Message::Agent(_) => markdown.push_str("## Assistant\n\n"),
2912 Message::Resume => {}
2913 }
2914 markdown.push_str(&message.to_markdown());
2915 }
2916
2917 if let Some(message) = self.pending_message.as_ref() {
2918 markdown.push_str("\n## Assistant\n\n");
2919 markdown.push_str(&message.to_markdown());
2920 }
2921
2922 markdown
2923 }
2924
2925 fn advance_prompt_id(&mut self) {
2926 self.prompt_id = PromptId::new();
2927 }
2928
2929 fn retry_strategy_for(error: &LanguageModelCompletionError) -> Option<RetryStrategy> {
2930 use LanguageModelCompletionError::*;
2931 use http_client::StatusCode;
2932
2933 // General strategy here:
2934 // - If retrying won't help (e.g. invalid API key or payload too large), return None so we don't retry at all.
2935 // - If it's a time-based issue (e.g. server overloaded, rate limit exceeded), retry up to 4 times with exponential backoff.
2936 // - If it's an issue that *might* be fixed by retrying (e.g. internal server error), retry up to 3 times.
2937 match error {
2938 HttpResponseError {
2939 status_code: StatusCode::TOO_MANY_REQUESTS,
2940 ..
2941 } => Some(RetryStrategy::ExponentialBackoff {
2942 initial_delay: BASE_RETRY_DELAY,
2943 max_attempts: MAX_RETRY_ATTEMPTS,
2944 }),
2945 ServerOverloaded { retry_after, .. } | RateLimitExceeded { retry_after, .. } => {
2946 Some(RetryStrategy::Fixed {
2947 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2948 max_attempts: MAX_RETRY_ATTEMPTS,
2949 })
2950 }
2951 UpstreamProviderError {
2952 status,
2953 retry_after,
2954 ..
2955 } => match *status {
2956 StatusCode::TOO_MANY_REQUESTS | StatusCode::SERVICE_UNAVAILABLE => {
2957 Some(RetryStrategy::Fixed {
2958 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2959 max_attempts: MAX_RETRY_ATTEMPTS,
2960 })
2961 }
2962 StatusCode::INTERNAL_SERVER_ERROR => Some(RetryStrategy::Fixed {
2963 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2964 // Internal Server Error could be anything, retry up to 3 times.
2965 max_attempts: 3,
2966 }),
2967 status => {
2968 // There is no StatusCode variant for the unofficial HTTP 529 ("The service is overloaded"),
2969 // but we frequently get them in practice. See https://http.dev/529
2970 if status.as_u16() == 529 {
2971 Some(RetryStrategy::Fixed {
2972 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2973 max_attempts: MAX_RETRY_ATTEMPTS,
2974 })
2975 } else {
2976 Some(RetryStrategy::Fixed {
2977 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2978 max_attempts: 2,
2979 })
2980 }
2981 }
2982 },
2983 ApiInternalServerError { .. } => Some(RetryStrategy::Fixed {
2984 delay: BASE_RETRY_DELAY,
2985 max_attempts: 3,
2986 }),
2987 ApiReadResponseError { .. }
2988 | HttpSend { .. }
2989 | DeserializeResponse { .. }
2990 | BadRequestFormat { .. } => Some(RetryStrategy::Fixed {
2991 delay: BASE_RETRY_DELAY,
2992 max_attempts: 3,
2993 }),
2994 // Retrying these errors definitely shouldn't help.
2995 HttpResponseError {
2996 status_code:
2997 StatusCode::PAYLOAD_TOO_LARGE | StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED,
2998 ..
2999 }
3000 | AuthenticationError { .. }
3001 | PermissionError { .. }
3002 | NoApiKey { .. }
3003 | ApiEndpointNotFound { .. }
3004 | PromptTooLarge { .. } => None,
3005 // These errors might be transient, so retry them
3006 SerializeRequest { .. } | BuildRequestBody { .. } | StreamEndedUnexpectedly { .. } => {
3007 Some(RetryStrategy::Fixed {
3008 delay: BASE_RETRY_DELAY,
3009 max_attempts: 1,
3010 })
3011 }
3012 // Retry all other 4xx and 5xx errors once.
3013 HttpResponseError { status_code, .. }
3014 if status_code.is_client_error() || status_code.is_server_error() =>
3015 {
3016 Some(RetryStrategy::Fixed {
3017 delay: BASE_RETRY_DELAY,
3018 max_attempts: 3,
3019 })
3020 }
3021 Other(err) if err.is::<language_model::PaymentRequiredError>() => {
3022 // Retrying won't help for Payment Required errors.
3023 None
3024 }
3025 // Conservatively assume that any other errors are non-retryable
3026 HttpResponseError { .. } | Other(..) => Some(RetryStrategy::Fixed {
3027 delay: BASE_RETRY_DELAY,
3028 max_attempts: 2,
3029 }),
3030 }
3031 }
3032}
3033
3034struct RunningTurn {
3035 /// Holds the task that handles agent interaction until the end of the turn.
3036 /// Survives across multiple requests as the model performs tool calls and
3037 /// we run tools, report their results.
3038 _task: Task<()>,
3039 /// The current event stream for the running turn. Used to report a final
3040 /// cancellation event if we cancel the turn.
3041 event_stream: ThreadEventStream,
3042 /// The tools that are enabled for the current iteration of the turn.
3043 /// Refreshed at the start of each iteration via `refresh_turn_tools`.
3044 tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
3045 /// Sender to signal tool cancellation. When cancel is called, this is
3046 /// set to true so all tools can detect user-initiated cancellation.
3047 cancellation_tx: watch::Sender<bool>,
3048 /// Senders for tools that support input streaming and have already been
3049 /// started but are still receiving input from the LLM.
3050 streaming_tool_inputs: HashMap<LanguageModelToolUseId, ToolInputSender>,
3051}
3052
3053impl RunningTurn {
3054 fn cancel(mut self) -> Task<()> {
3055 log::debug!("Cancelling in progress turn");
3056 self.cancellation_tx.send(true).ok();
3057 self.event_stream.send_canceled();
3058 self._task
3059 }
3060}
3061
3062pub struct TokenUsageUpdated(pub Option<acp_thread::TokenUsage>);
3063
3064impl EventEmitter<TokenUsageUpdated> for Thread {}
3065
3066pub struct TitleUpdated;
3067
3068impl EventEmitter<TitleUpdated> for Thread {}
3069
3070/// A channel-based wrapper that delivers tool input to a running tool.
3071///
3072/// For non-streaming tools, created via `ToolInput::ready()` so `.recv()` resolves immediately.
3073/// For streaming tools, partial JSON snapshots arrive via `.recv_partial()` as the LLM streams
3074/// them, followed by the final complete input available through `.recv()`.
3075pub struct ToolInput<T> {
3076 partial_rx: mpsc::UnboundedReceiver<serde_json::Value>,
3077 final_rx: oneshot::Receiver<serde_json::Value>,
3078 _phantom: PhantomData<T>,
3079}
3080
3081impl<T: DeserializeOwned> ToolInput<T> {
3082 #[cfg(any(test, feature = "test-support"))]
3083 pub fn resolved(input: impl Serialize) -> Self {
3084 let value = serde_json::to_value(input).expect("failed to serialize tool input");
3085 Self::ready(value)
3086 }
3087
3088 pub fn ready(value: serde_json::Value) -> Self {
3089 let (partial_tx, partial_rx) = mpsc::unbounded();
3090 drop(partial_tx);
3091 let (final_tx, final_rx) = oneshot::channel();
3092 final_tx.send(value).ok();
3093 Self {
3094 partial_rx,
3095 final_rx,
3096 _phantom: PhantomData,
3097 }
3098 }
3099
3100 #[cfg(any(test, feature = "test-support"))]
3101 pub fn test() -> (ToolInputSender, Self) {
3102 let (sender, input) = ToolInputSender::channel();
3103 (sender, input.cast())
3104 }
3105
3106 /// Wait for the final deserialized input, ignoring all partial updates.
3107 /// Non-streaming tools can use this to wait until the whole input is available.
3108 pub async fn recv(mut self) -> Result<T> {
3109 // Drain any remaining partials
3110 while self.partial_rx.next().await.is_some() {}
3111 let value = self
3112 .final_rx
3113 .await
3114 .map_err(|_| anyhow!("tool input was not fully received"))?;
3115 serde_json::from_value(value).map_err(Into::into)
3116 }
3117
3118 /// Returns the next partial JSON snapshot, or `None` when input is complete.
3119 /// Once this returns `None`, call `recv()` to get the final input.
3120 pub async fn recv_partial(&mut self) -> Option<serde_json::Value> {
3121 self.partial_rx.next().await
3122 }
3123
3124 fn cast<U: DeserializeOwned>(self) -> ToolInput<U> {
3125 ToolInput {
3126 partial_rx: self.partial_rx,
3127 final_rx: self.final_rx,
3128 _phantom: PhantomData,
3129 }
3130 }
3131}
3132
3133pub struct ToolInputSender {
3134 partial_tx: mpsc::UnboundedSender<serde_json::Value>,
3135 final_tx: Option<oneshot::Sender<serde_json::Value>>,
3136}
3137
3138impl ToolInputSender {
3139 pub(crate) fn channel() -> (Self, ToolInput<serde_json::Value>) {
3140 let (partial_tx, partial_rx) = mpsc::unbounded();
3141 let (final_tx, final_rx) = oneshot::channel();
3142 let sender = Self {
3143 partial_tx,
3144 final_tx: Some(final_tx),
3145 };
3146 let input = ToolInput {
3147 partial_rx,
3148 final_rx,
3149 _phantom: PhantomData,
3150 };
3151 (sender, input)
3152 }
3153
3154 pub(crate) fn has_received_final(&self) -> bool {
3155 self.final_tx.is_none()
3156 }
3157
3158 pub(crate) fn send_partial(&self, value: serde_json::Value) {
3159 self.partial_tx.unbounded_send(value).ok();
3160 }
3161
3162 pub(crate) fn send_final(mut self, value: serde_json::Value) {
3163 // Close the partial channel so recv_partial() returns None
3164 self.partial_tx.close_channel();
3165 if let Some(final_tx) = self.final_tx.take() {
3166 final_tx.send(value).ok();
3167 }
3168 }
3169}
3170
3171pub trait AgentTool
3172where
3173 Self: 'static + Sized,
3174{
3175 type Input: for<'de> Deserialize<'de> + Serialize + JsonSchema;
3176 type Output: for<'de> Deserialize<'de> + Serialize + Into<LanguageModelToolResultContent>;
3177
3178 const NAME: &'static str;
3179
3180 fn description() -> SharedString {
3181 let schema = schemars::schema_for!(Self::Input);
3182 SharedString::new(
3183 schema
3184 .get("description")
3185 .and_then(|description| description.as_str())
3186 .unwrap_or_default(),
3187 )
3188 }
3189
3190 fn kind() -> acp::ToolKind;
3191
3192 /// The initial tool title to display. Can be updated during the tool run.
3193 fn initial_title(
3194 &self,
3195 input: Result<Self::Input, serde_json::Value>,
3196 cx: &mut App,
3197 ) -> SharedString;
3198
3199 /// Returns the JSON schema that describes the tool's input.
3200 fn input_schema(format: LanguageModelToolSchemaFormat) -> Schema {
3201 language_model::tool_schema::root_schema_for::<Self::Input>(format)
3202 }
3203
3204 /// Returns whether the tool supports streaming of tool use parameters.
3205 fn supports_input_streaming() -> bool {
3206 false
3207 }
3208
3209 /// Some tools rely on a provider for the underlying billing or other reasons.
3210 /// Allow the tool to check if they are compatible, or should be filtered out.
3211 fn supports_provider(_provider: &LanguageModelProviderId) -> bool {
3212 true
3213 }
3214
3215 /// Runs the tool with the provided input.
3216 ///
3217 /// Returns `Result<Self::Output, Self::Output>` rather than `Result<Self::Output, anyhow::Error>`
3218 /// because tool errors are sent back to the model as tool results. This means error output must
3219 /// be structured and readable by the agent — not an arbitrary `anyhow::Error`. Returning the
3220 /// same `Output` type for both success and failure lets tools provide structured data while
3221 /// still signaling whether the invocation succeeded or failed.
3222 fn run(
3223 self: Arc<Self>,
3224 input: ToolInput<Self::Input>,
3225 event_stream: ToolCallEventStream,
3226 cx: &mut App,
3227 ) -> Task<Result<Self::Output, Self::Output>>;
3228
3229 /// Emits events for a previous execution of the tool.
3230 fn replay(
3231 &self,
3232 _input: Self::Input,
3233 _output: Self::Output,
3234 _event_stream: ToolCallEventStream,
3235 _cx: &mut App,
3236 ) -> Result<()> {
3237 Ok(())
3238 }
3239
3240 fn erase(self) -> Arc<dyn AnyAgentTool> {
3241 Arc::new(Erased(Arc::new(self)))
3242 }
3243}
3244
3245pub struct Erased<T>(T);
3246
3247pub struct AgentToolOutput {
3248 pub llm_output: LanguageModelToolResultContent,
3249 pub raw_output: serde_json::Value,
3250}
3251
3252impl AgentToolOutput {
3253 pub fn from_error(message: impl Into<String>) -> Self {
3254 let message = message.into();
3255 let llm_output = LanguageModelToolResultContent::Text(Arc::from(message.as_str()));
3256 Self {
3257 raw_output: serde_json::Value::String(message),
3258 llm_output,
3259 }
3260 }
3261}
3262
3263pub trait AnyAgentTool {
3264 fn name(&self) -> SharedString;
3265 fn description(&self) -> SharedString;
3266 fn kind(&self) -> acp::ToolKind;
3267 fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString;
3268 fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value>;
3269 fn supports_input_streaming(&self) -> bool {
3270 false
3271 }
3272 fn supports_provider(&self, _provider: &LanguageModelProviderId) -> bool {
3273 true
3274 }
3275 /// See [`AgentTool::run`] for why this returns `Result<AgentToolOutput, AgentToolOutput>`.
3276 fn run(
3277 self: Arc<Self>,
3278 input: ToolInput<serde_json::Value>,
3279 event_stream: ToolCallEventStream,
3280 cx: &mut App,
3281 ) -> Task<Result<AgentToolOutput, AgentToolOutput>>;
3282 fn replay(
3283 &self,
3284 input: serde_json::Value,
3285 output: serde_json::Value,
3286 event_stream: ToolCallEventStream,
3287 cx: &mut App,
3288 ) -> Result<()>;
3289}
3290
3291impl<T> AnyAgentTool for Erased<Arc<T>>
3292where
3293 T: AgentTool,
3294{
3295 fn name(&self) -> SharedString {
3296 T::NAME.into()
3297 }
3298
3299 fn description(&self) -> SharedString {
3300 T::description()
3301 }
3302
3303 fn kind(&self) -> agent_client_protocol::ToolKind {
3304 T::kind()
3305 }
3306
3307 fn supports_input_streaming(&self) -> bool {
3308 T::supports_input_streaming()
3309 }
3310
3311 fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString {
3312 let parsed_input = serde_json::from_value(input.clone()).map_err(|_| input);
3313 self.0.initial_title(parsed_input, _cx)
3314 }
3315
3316 fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
3317 let mut json = serde_json::to_value(T::input_schema(format))?;
3318 language_model::tool_schema::adapt_schema_to_format(&mut json, format)?;
3319 Ok(json)
3320 }
3321
3322 fn supports_provider(&self, provider: &LanguageModelProviderId) -> bool {
3323 T::supports_provider(provider)
3324 }
3325
3326 fn run(
3327 self: Arc<Self>,
3328 input: ToolInput<serde_json::Value>,
3329 event_stream: ToolCallEventStream,
3330 cx: &mut App,
3331 ) -> Task<Result<AgentToolOutput, AgentToolOutput>> {
3332 let tool_input: ToolInput<T::Input> = input.cast();
3333 let task = self.0.clone().run(tool_input, event_stream, cx);
3334 cx.spawn(async move |_cx| match task.await {
3335 Ok(output) => {
3336 let raw_output = serde_json::to_value(&output).map_err(|e| {
3337 AgentToolOutput::from_error(format!("Failed to serialize tool output: {e}"))
3338 })?;
3339 Ok(AgentToolOutput {
3340 llm_output: output.into(),
3341 raw_output,
3342 })
3343 }
3344 Err(error_output) => {
3345 let raw_output = serde_json::to_value(&error_output).unwrap_or_else(|e| {
3346 log::error!("Failed to serialize tool error output: {e}");
3347 serde_json::Value::Null
3348 });
3349 Err(AgentToolOutput {
3350 llm_output: error_output.into(),
3351 raw_output,
3352 })
3353 }
3354 })
3355 }
3356
3357 fn replay(
3358 &self,
3359 input: serde_json::Value,
3360 output: serde_json::Value,
3361 event_stream: ToolCallEventStream,
3362 cx: &mut App,
3363 ) -> Result<()> {
3364 let input = serde_json::from_value(input)?;
3365 let output = serde_json::from_value(output)?;
3366 self.0.replay(input, output, event_stream, cx)
3367 }
3368}
3369
3370#[derive(Clone)]
3371struct ThreadEventStream(mpsc::UnboundedSender<Result<ThreadEvent>>);
3372
3373impl ThreadEventStream {
3374 fn send_user_message(&self, message: &UserMessage) {
3375 self.0
3376 .unbounded_send(Ok(ThreadEvent::UserMessage(message.clone())))
3377 .ok();
3378 }
3379
3380 fn send_text(&self, text: &str) {
3381 self.0
3382 .unbounded_send(Ok(ThreadEvent::AgentText(text.to_string())))
3383 .ok();
3384 }
3385
3386 fn send_thinking(&self, text: &str) {
3387 self.0
3388 .unbounded_send(Ok(ThreadEvent::AgentThinking(text.to_string())))
3389 .ok();
3390 }
3391
3392 fn send_tool_call(
3393 &self,
3394 id: &LanguageModelToolUseId,
3395 tool_name: &str,
3396 title: SharedString,
3397 kind: acp::ToolKind,
3398 input: serde_json::Value,
3399 ) {
3400 self.0
3401 .unbounded_send(Ok(ThreadEvent::ToolCall(Self::initial_tool_call(
3402 id,
3403 tool_name,
3404 title.to_string(),
3405 kind,
3406 input,
3407 ))))
3408 .ok();
3409 }
3410
3411 fn initial_tool_call(
3412 id: &LanguageModelToolUseId,
3413 tool_name: &str,
3414 title: String,
3415 kind: acp::ToolKind,
3416 input: serde_json::Value,
3417 ) -> acp::ToolCall {
3418 acp::ToolCall::new(id.to_string(), title)
3419 .kind(kind)
3420 .raw_input(input)
3421 .meta(acp_thread::meta_with_tool_name(tool_name))
3422 }
3423
3424 fn update_tool_call_fields(
3425 &self,
3426 tool_use_id: &LanguageModelToolUseId,
3427 fields: acp::ToolCallUpdateFields,
3428 meta: Option<acp::Meta>,
3429 ) {
3430 self.0
3431 .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
3432 acp::ToolCallUpdate::new(tool_use_id.to_string(), fields)
3433 .meta(meta)
3434 .into(),
3435 )))
3436 .ok();
3437 }
3438
3439 fn send_retry(&self, status: acp_thread::RetryStatus) {
3440 self.0.unbounded_send(Ok(ThreadEvent::Retry(status))).ok();
3441 }
3442
3443 fn send_stop(&self, reason: acp::StopReason) {
3444 self.0.unbounded_send(Ok(ThreadEvent::Stop(reason))).ok();
3445 }
3446
3447 fn send_canceled(&self) {
3448 self.0
3449 .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::Cancelled)))
3450 .ok();
3451 }
3452
3453 fn send_error(&self, error: impl Into<anyhow::Error>) {
3454 self.0.unbounded_send(Err(error.into())).ok();
3455 }
3456}
3457
3458#[derive(Clone)]
3459pub struct ToolCallEventStream {
3460 tool_use_id: LanguageModelToolUseId,
3461 stream: ThreadEventStream,
3462 fs: Option<Arc<dyn Fs>>,
3463 cancellation_rx: watch::Receiver<bool>,
3464}
3465
3466impl ToolCallEventStream {
3467 #[cfg(any(test, feature = "test-support"))]
3468 pub fn test() -> (Self, ToolCallEventStreamReceiver) {
3469 let (stream, receiver, _cancellation_tx) = Self::test_with_cancellation();
3470 (stream, receiver)
3471 }
3472
3473 #[cfg(any(test, feature = "test-support"))]
3474 pub fn test_with_cancellation() -> (Self, ToolCallEventStreamReceiver, watch::Sender<bool>) {
3475 let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
3476 let (cancellation_tx, cancellation_rx) = watch::channel(false);
3477
3478 let stream = ToolCallEventStream::new(
3479 "test_id".into(),
3480 ThreadEventStream(events_tx),
3481 None,
3482 cancellation_rx,
3483 );
3484
3485 (
3486 stream,
3487 ToolCallEventStreamReceiver(events_rx),
3488 cancellation_tx,
3489 )
3490 }
3491
3492 /// Signal cancellation for this event stream. Only available in tests.
3493 #[cfg(any(test, feature = "test-support"))]
3494 pub fn signal_cancellation_with_sender(cancellation_tx: &mut watch::Sender<bool>) {
3495 cancellation_tx.send(true).ok();
3496 }
3497
3498 fn new(
3499 tool_use_id: LanguageModelToolUseId,
3500 stream: ThreadEventStream,
3501 fs: Option<Arc<dyn Fs>>,
3502 cancellation_rx: watch::Receiver<bool>,
3503 ) -> Self {
3504 Self {
3505 tool_use_id,
3506 stream,
3507 fs,
3508 cancellation_rx,
3509 }
3510 }
3511
3512 /// Returns a future that resolves when the user cancels the tool call.
3513 /// Tools should select on this alongside their main work to detect user cancellation.
3514 pub fn cancelled_by_user(&self) -> impl std::future::Future<Output = ()> + '_ {
3515 let mut rx = self.cancellation_rx.clone();
3516 async move {
3517 loop {
3518 if *rx.borrow() {
3519 return;
3520 }
3521 if rx.changed().await.is_err() {
3522 // Sender dropped, will never be cancelled
3523 std::future::pending::<()>().await;
3524 }
3525 }
3526 }
3527 }
3528
3529 /// Returns true if the user has cancelled this tool call.
3530 /// This is useful for checking cancellation state after an operation completes,
3531 /// to determine if the completion was due to user cancellation.
3532 pub fn was_cancelled_by_user(&self) -> bool {
3533 *self.cancellation_rx.clone().borrow()
3534 }
3535
3536 pub fn tool_use_id(&self) -> &LanguageModelToolUseId {
3537 &self.tool_use_id
3538 }
3539
3540 pub fn update_fields(&self, fields: acp::ToolCallUpdateFields) {
3541 self.stream
3542 .update_tool_call_fields(&self.tool_use_id, fields, None);
3543 }
3544
3545 pub fn update_fields_with_meta(
3546 &self,
3547 fields: acp::ToolCallUpdateFields,
3548 meta: Option<acp::Meta>,
3549 ) {
3550 self.stream
3551 .update_tool_call_fields(&self.tool_use_id, fields, meta);
3552 }
3553
3554 pub fn update_diff(&self, diff: Entity<acp_thread::Diff>) {
3555 self.stream
3556 .0
3557 .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
3558 acp_thread::ToolCallUpdateDiff {
3559 id: acp::ToolCallId::new(self.tool_use_id.to_string()),
3560 diff,
3561 }
3562 .into(),
3563 )))
3564 .ok();
3565 }
3566
3567 pub fn subagent_spawned(&self, id: acp::SessionId) {
3568 self.stream
3569 .0
3570 .unbounded_send(Ok(ThreadEvent::SubagentSpawned(id)))
3571 .ok();
3572 }
3573
3574 /// Authorize a third-party tool (e.g., MCP tool from a context server).
3575 ///
3576 /// Unlike built-in tools, third-party tools don't support pattern-based permissions.
3577 /// They only support `default` (allow/deny/confirm) per tool.
3578 ///
3579 /// Uses the dropdown authorization flow with two granularities:
3580 /// - "Always for <display_name> MCP tool" → sets `tools.<tool_id>.default = "allow"` or "deny"
3581 /// - "Only this time" → allow/deny once
3582 pub fn authorize_third_party_tool(
3583 &self,
3584 title: impl Into<String>,
3585 tool_id: String,
3586 display_name: String,
3587 cx: &mut App,
3588 ) -> Task<Result<()>> {
3589 let settings = agent_settings::AgentSettings::get_global(cx);
3590
3591 let decision = decide_permission_from_settings(&tool_id, &[String::new()], &settings);
3592
3593 match decision {
3594 ToolPermissionDecision::Allow => return Task::ready(Ok(())),
3595 ToolPermissionDecision::Deny(reason) => return Task::ready(Err(anyhow!(reason))),
3596 ToolPermissionDecision::Confirm => {}
3597 }
3598
3599 let (response_tx, response_rx) = oneshot::channel();
3600 if let Err(error) = self
3601 .stream
3602 .0
3603 .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
3604 ToolCallAuthorization {
3605 tool_call: acp::ToolCallUpdate::new(
3606 self.tool_use_id.to_string(),
3607 acp::ToolCallUpdateFields::new().title(title.into()),
3608 ),
3609 options: acp_thread::PermissionOptions::Dropdown(vec![
3610 acp_thread::PermissionOptionChoice {
3611 allow: acp::PermissionOption::new(
3612 acp::PermissionOptionId::new(format!(
3613 "always_allow_mcp:{}",
3614 tool_id
3615 )),
3616 format!("Always for {} MCP tool", display_name),
3617 acp::PermissionOptionKind::AllowAlways,
3618 ),
3619 deny: acp::PermissionOption::new(
3620 acp::PermissionOptionId::new(format!(
3621 "always_deny_mcp:{}",
3622 tool_id
3623 )),
3624 format!("Always for {} MCP tool", display_name),
3625 acp::PermissionOptionKind::RejectAlways,
3626 ),
3627 },
3628 acp_thread::PermissionOptionChoice {
3629 allow: acp::PermissionOption::new(
3630 acp::PermissionOptionId::new("allow"),
3631 "Only this time",
3632 acp::PermissionOptionKind::AllowOnce,
3633 ),
3634 deny: acp::PermissionOption::new(
3635 acp::PermissionOptionId::new("deny"),
3636 "Only this time",
3637 acp::PermissionOptionKind::RejectOnce,
3638 ),
3639 },
3640 ]),
3641 response: response_tx,
3642 context: None,
3643 },
3644 )))
3645 {
3646 log::error!("Failed to send tool call authorization: {error}");
3647 return Task::ready(Err(anyhow!(
3648 "Failed to send tool call authorization: {error}"
3649 )));
3650 }
3651
3652 let fs = self.fs.clone();
3653 cx.spawn(async move |cx| {
3654 let response_str = response_rx.await?.0.to_string();
3655
3656 if response_str == format!("always_allow_mcp:{}", tool_id) {
3657 if let Some(fs) = fs.clone() {
3658 cx.update(|cx| {
3659 update_settings_file(fs, cx, move |settings, _| {
3660 settings
3661 .agent
3662 .get_or_insert_default()
3663 .set_tool_default_permission(&tool_id, ToolPermissionMode::Allow);
3664 });
3665 });
3666 }
3667 return Ok(());
3668 }
3669 if response_str == format!("always_deny_mcp:{}", tool_id) {
3670 if let Some(fs) = fs.clone() {
3671 cx.update(|cx| {
3672 update_settings_file(fs, cx, move |settings, _| {
3673 settings
3674 .agent
3675 .get_or_insert_default()
3676 .set_tool_default_permission(&tool_id, ToolPermissionMode::Deny);
3677 });
3678 });
3679 }
3680 return Err(anyhow!("Permission to run tool denied by user"));
3681 }
3682
3683 if response_str == "allow" {
3684 return Ok(());
3685 }
3686
3687 Err(anyhow!("Permission to run tool denied by user"))
3688 })
3689 }
3690
3691 pub fn authorize(
3692 &self,
3693 title: impl Into<String>,
3694 context: ToolPermissionContext,
3695 cx: &mut App,
3696 ) -> Task<Result<()>> {
3697 use settings::ToolPermissionMode;
3698
3699 let options = context.build_permission_options();
3700
3701 let (response_tx, response_rx) = oneshot::channel();
3702 if let Err(error) = self
3703 .stream
3704 .0
3705 .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
3706 ToolCallAuthorization {
3707 tool_call: acp::ToolCallUpdate::new(
3708 self.tool_use_id.to_string(),
3709 acp::ToolCallUpdateFields::new().title(title.into()),
3710 ),
3711 options,
3712 response: response_tx,
3713 context: Some(context),
3714 },
3715 )))
3716 {
3717 log::error!("Failed to send tool call authorization: {error}");
3718 return Task::ready(Err(anyhow!(
3719 "Failed to send tool call authorization: {error}"
3720 )));
3721 }
3722
3723 let fs = self.fs.clone();
3724 cx.spawn(async move |cx| {
3725 let response_str = response_rx.await?.0.to_string();
3726
3727 // Handle "always allow tool" - e.g., "always_allow:terminal"
3728 if let Some(tool) = response_str.strip_prefix("always_allow:") {
3729 if let Some(fs) = fs.clone() {
3730 let tool = tool.to_string();
3731 cx.update(|cx| {
3732 update_settings_file(fs, cx, move |settings, _| {
3733 settings
3734 .agent
3735 .get_or_insert_default()
3736 .set_tool_default_permission(&tool, ToolPermissionMode::Allow);
3737 });
3738 });
3739 }
3740 return Ok(());
3741 }
3742
3743 // Handle "always deny tool" - e.g., "always_deny:terminal"
3744 if let Some(tool) = response_str.strip_prefix("always_deny:") {
3745 if let Some(fs) = fs.clone() {
3746 let tool = tool.to_string();
3747 cx.update(|cx| {
3748 update_settings_file(fs, cx, move |settings, _| {
3749 settings
3750 .agent
3751 .get_or_insert_default()
3752 .set_tool_default_permission(&tool, ToolPermissionMode::Deny);
3753 });
3754 });
3755 }
3756 return Err(anyhow!("Permission to run tool denied by user"));
3757 }
3758
3759 // Handle "always allow pattern" - e.g., "always_allow_pattern:mcp:server:tool\n^cargo\s"
3760 if let Some(rest) = response_str.strip_prefix("always_allow_pattern:") {
3761 if let Some((pattern_tool_name, pattern)) = rest.split_once('\n') {
3762 let pattern_tool_name = pattern_tool_name.to_string();
3763 let pattern = pattern.to_string();
3764 if let Some(fs) = fs.clone() {
3765 cx.update(|cx| {
3766 update_settings_file(fs, cx, move |settings, _| {
3767 settings
3768 .agent
3769 .get_or_insert_default()
3770 .add_tool_allow_pattern(&pattern_tool_name, pattern);
3771 });
3772 });
3773 }
3774 } else {
3775 log::error!("Failed to parse always allow pattern: missing newline separator in '{rest}'");
3776 }
3777 return Ok(());
3778 }
3779
3780 // Handle "always deny pattern" - e.g., "always_deny_pattern:mcp:server:tool\n^cargo\s"
3781 if let Some(rest) = response_str.strip_prefix("always_deny_pattern:") {
3782 if let Some((pattern_tool_name, pattern)) = rest.split_once('\n') {
3783 let pattern_tool_name = pattern_tool_name.to_string();
3784 let pattern = pattern.to_string();
3785 if let Some(fs) = fs.clone() {
3786 cx.update(|cx| {
3787 update_settings_file(fs, cx, move |settings, _| {
3788 settings
3789 .agent
3790 .get_or_insert_default()
3791 .add_tool_deny_pattern(&pattern_tool_name, pattern);
3792 });
3793 });
3794 }
3795 } else {
3796 log::error!("Failed to parse always deny pattern: missing newline separator in '{rest}'");
3797 }
3798 return Err(anyhow!("Permission to run tool denied by user"));
3799 }
3800
3801 // Handle simple "allow" (allow once)
3802 if response_str == "allow" {
3803 return Ok(());
3804 }
3805
3806 // Handle simple "deny" (deny once)
3807 Err(anyhow!("Permission to run tool denied by user"))
3808 })
3809 }
3810}
3811
3812#[cfg(any(test, feature = "test-support"))]
3813pub struct ToolCallEventStreamReceiver(mpsc::UnboundedReceiver<Result<ThreadEvent>>);
3814
3815#[cfg(any(test, feature = "test-support"))]
3816impl ToolCallEventStreamReceiver {
3817 pub async fn expect_authorization(&mut self) -> ToolCallAuthorization {
3818 let event = self.0.next().await;
3819 if let Some(Ok(ThreadEvent::ToolCallAuthorization(auth))) = event {
3820 auth
3821 } else {
3822 panic!("Expected ToolCallAuthorization but got: {:?}", event);
3823 }
3824 }
3825
3826 pub async fn expect_update_fields(&mut self) -> acp::ToolCallUpdateFields {
3827 let event = self.0.next().await;
3828 if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(
3829 update,
3830 )))) = event
3831 {
3832 update.fields
3833 } else {
3834 panic!("Expected update fields but got: {:?}", event);
3835 }
3836 }
3837
3838 pub async fn expect_diff(&mut self) -> Entity<acp_thread::Diff> {
3839 let event = self.0.next().await;
3840 if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateDiff(
3841 update,
3842 )))) = event
3843 {
3844 update.diff
3845 } else {
3846 panic!("Expected diff but got: {:?}", event);
3847 }
3848 }
3849
3850 pub async fn expect_terminal(&mut self) -> Entity<acp_thread::Terminal> {
3851 let event = self.0.next().await;
3852 if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateTerminal(
3853 update,
3854 )))) = event
3855 {
3856 update.terminal
3857 } else {
3858 panic!("Expected terminal but got: {:?}", event);
3859 }
3860 }
3861}
3862
3863#[cfg(any(test, feature = "test-support"))]
3864impl std::ops::Deref for ToolCallEventStreamReceiver {
3865 type Target = mpsc::UnboundedReceiver<Result<ThreadEvent>>;
3866
3867 fn deref(&self) -> &Self::Target {
3868 &self.0
3869 }
3870}
3871
3872#[cfg(any(test, feature = "test-support"))]
3873impl std::ops::DerefMut for ToolCallEventStreamReceiver {
3874 fn deref_mut(&mut self) -> &mut Self::Target {
3875 &mut self.0
3876 }
3877}
3878
3879impl From<&str> for UserMessageContent {
3880 fn from(text: &str) -> Self {
3881 Self::Text(text.into())
3882 }
3883}
3884
3885impl From<String> for UserMessageContent {
3886 fn from(text: String) -> Self {
3887 Self::Text(text)
3888 }
3889}
3890
3891impl UserMessageContent {
3892 pub fn from_content_block(value: acp::ContentBlock, path_style: PathStyle) -> Self {
3893 match value {
3894 acp::ContentBlock::Text(text_content) => Self::Text(text_content.text),
3895 acp::ContentBlock::Image(image_content) => Self::Image(convert_image(image_content)),
3896 acp::ContentBlock::Audio(_) => {
3897 // TODO
3898 Self::Text("[audio]".to_string())
3899 }
3900 acp::ContentBlock::ResourceLink(resource_link) => {
3901 match MentionUri::parse(&resource_link.uri, path_style) {
3902 Ok(uri) => Self::Mention {
3903 uri,
3904 content: String::new(),
3905 },
3906 Err(err) => {
3907 log::error!("Failed to parse mention link: {}", err);
3908 Self::Text(format!("[{}]({})", resource_link.name, resource_link.uri))
3909 }
3910 }
3911 }
3912 acp::ContentBlock::Resource(resource) => match resource.resource {
3913 acp::EmbeddedResourceResource::TextResourceContents(resource) => {
3914 match MentionUri::parse(&resource.uri, path_style) {
3915 Ok(uri) => Self::Mention {
3916 uri,
3917 content: resource.text,
3918 },
3919 Err(err) => {
3920 log::error!("Failed to parse mention link: {}", err);
3921 Self::Text(
3922 MarkdownCodeBlock {
3923 tag: &resource.uri,
3924 text: &resource.text,
3925 }
3926 .to_string(),
3927 )
3928 }
3929 }
3930 }
3931 acp::EmbeddedResourceResource::BlobResourceContents(_) => {
3932 // TODO
3933 Self::Text("[blob]".to_string())
3934 }
3935 other => {
3936 log::warn!("Unexpected content type: {:?}", other);
3937 Self::Text("[unknown]".to_string())
3938 }
3939 },
3940 other => {
3941 log::warn!("Unexpected content type: {:?}", other);
3942 Self::Text("[unknown]".to_string())
3943 }
3944 }
3945 }
3946}
3947
3948impl From<UserMessageContent> for acp::ContentBlock {
3949 fn from(content: UserMessageContent) -> Self {
3950 match content {
3951 UserMessageContent::Text(text) => text.into(),
3952 UserMessageContent::Image(image) => {
3953 acp::ContentBlock::Image(acp::ImageContent::new(image.source, "image/png"))
3954 }
3955 UserMessageContent::Mention { uri, content } => acp::ContentBlock::Resource(
3956 acp::EmbeddedResource::new(acp::EmbeddedResourceResource::TextResourceContents(
3957 acp::TextResourceContents::new(content, uri.to_uri().to_string()),
3958 )),
3959 ),
3960 }
3961 }
3962}
3963
3964fn convert_image(image_content: acp::ImageContent) -> LanguageModelImage {
3965 LanguageModelImage {
3966 source: image_content.data.into(),
3967 size: None,
3968 }
3969}
3970
3971#[cfg(test)]
3972mod tests {
3973 use super::*;
3974 use gpui::TestAppContext;
3975 use language_model::LanguageModelToolUseId;
3976 use language_model::fake_provider::FakeLanguageModel;
3977 use serde_json::json;
3978 use std::sync::Arc;
3979
3980 async fn setup_thread_for_test(cx: &mut TestAppContext) -> (Entity<Thread>, ThreadEventStream) {
3981 cx.update(|cx| {
3982 let settings_store = settings::SettingsStore::test(cx);
3983 cx.set_global(settings_store);
3984 });
3985
3986 let fs = fs::FakeFs::new(cx.background_executor.clone());
3987 let templates = Templates::new();
3988 let project = Project::test(fs.clone(), [], cx).await;
3989
3990 cx.update(|cx| {
3991 let project_context = cx.new(|_cx| prompt_store::ProjectContext::default());
3992 let context_server_store = project.read(cx).context_server_store();
3993 let context_server_registry =
3994 cx.new(|cx| ContextServerRegistry::new(context_server_store, cx));
3995
3996 let thread = cx.new(|cx| {
3997 Thread::new(
3998 project,
3999 project_context,
4000 context_server_registry,
4001 templates,
4002 None,
4003 cx,
4004 )
4005 });
4006
4007 let (event_tx, _event_rx) = mpsc::unbounded();
4008 let event_stream = ThreadEventStream(event_tx);
4009
4010 (thread, event_stream)
4011 })
4012 }
4013
4014 fn setup_parent_with_subagents(
4015 cx: &mut TestAppContext,
4016 parent: &Entity<Thread>,
4017 count: usize,
4018 ) -> Vec<Entity<Thread>> {
4019 cx.update(|cx| {
4020 let mut subagents = Vec::new();
4021 for _ in 0..count {
4022 let subagent = cx.new(|cx| Thread::new_subagent(parent, cx));
4023 parent.update(cx, |thread, _cx| {
4024 thread.register_running_subagent(subagent.downgrade());
4025 });
4026 subagents.push(subagent);
4027 }
4028 subagents
4029 })
4030 }
4031
4032 #[gpui::test]
4033 async fn test_set_model_propagates_to_subagents(cx: &mut TestAppContext) {
4034 let (parent, _event_stream) = setup_thread_for_test(cx).await;
4035 let subagents = setup_parent_with_subagents(cx, &parent, 2);
4036
4037 let new_model: Arc<dyn LanguageModel> = Arc::new(FakeLanguageModel::with_id_and_thinking(
4038 "test-provider",
4039 "new-model",
4040 "New Model",
4041 false,
4042 ));
4043
4044 cx.update(|cx| {
4045 parent.update(cx, |thread, cx| {
4046 thread.set_model(new_model, cx);
4047 });
4048
4049 for subagent in &subagents {
4050 let subagent_model_id = subagent.read(cx).model().unwrap().id();
4051 assert_eq!(
4052 subagent_model_id.0.as_ref(),
4053 "new-model",
4054 "Subagent model should match parent model after set_model"
4055 );
4056 }
4057 });
4058 }
4059
4060 #[gpui::test]
4061 async fn test_set_summarization_model_propagates_to_subagents(cx: &mut TestAppContext) {
4062 let (parent, _event_stream) = setup_thread_for_test(cx).await;
4063 let subagents = setup_parent_with_subagents(cx, &parent, 2);
4064
4065 let summary_model: Arc<dyn LanguageModel> =
4066 Arc::new(FakeLanguageModel::with_id_and_thinking(
4067 "test-provider",
4068 "summary-model",
4069 "Summary Model",
4070 false,
4071 ));
4072
4073 cx.update(|cx| {
4074 parent.update(cx, |thread, cx| {
4075 thread.set_summarization_model(Some(summary_model), cx);
4076 });
4077
4078 for subagent in &subagents {
4079 let subagent_summary_id = subagent.read(cx).summarization_model().unwrap().id();
4080 assert_eq!(
4081 subagent_summary_id.0.as_ref(),
4082 "summary-model",
4083 "Subagent summarization model should match parent after set_summarization_model"
4084 );
4085 }
4086 });
4087 }
4088
4089 #[gpui::test]
4090 async fn test_set_thinking_enabled_propagates_to_subagents(cx: &mut TestAppContext) {
4091 let (parent, _event_stream) = setup_thread_for_test(cx).await;
4092 let subagents = setup_parent_with_subagents(cx, &parent, 2);
4093
4094 cx.update(|cx| {
4095 parent.update(cx, |thread, cx| {
4096 thread.set_thinking_enabled(true, cx);
4097 });
4098
4099 for subagent in &subagents {
4100 assert!(
4101 subagent.read(cx).thinking_enabled(),
4102 "Subagent thinking should be enabled after parent enables it"
4103 );
4104 }
4105
4106 parent.update(cx, |thread, cx| {
4107 thread.set_thinking_enabled(false, cx);
4108 });
4109
4110 for subagent in &subagents {
4111 assert!(
4112 !subagent.read(cx).thinking_enabled(),
4113 "Subagent thinking should be disabled after parent disables it"
4114 );
4115 }
4116 });
4117 }
4118
4119 #[gpui::test]
4120 async fn test_set_thinking_effort_propagates_to_subagents(cx: &mut TestAppContext) {
4121 let (parent, _event_stream) = setup_thread_for_test(cx).await;
4122 let subagents = setup_parent_with_subagents(cx, &parent, 2);
4123
4124 cx.update(|cx| {
4125 parent.update(cx, |thread, cx| {
4126 thread.set_thinking_effort(Some("high".to_string()), cx);
4127 });
4128
4129 for subagent in &subagents {
4130 assert_eq!(
4131 subagent.read(cx).thinking_effort().map(|s| s.as_str()),
4132 Some("high"),
4133 "Subagent thinking effort should match parent"
4134 );
4135 }
4136
4137 parent.update(cx, |thread, cx| {
4138 thread.set_thinking_effort(None, cx);
4139 });
4140
4141 for subagent in &subagents {
4142 assert_eq!(
4143 subagent.read(cx).thinking_effort(),
4144 None,
4145 "Subagent thinking effort should be None after parent clears it"
4146 );
4147 }
4148 });
4149 }
4150
4151 #[gpui::test]
4152 async fn test_set_speed_propagates_to_subagents(cx: &mut TestAppContext) {
4153 let (parent, _event_stream) = setup_thread_for_test(cx).await;
4154 let subagents = setup_parent_with_subagents(cx, &parent, 2);
4155
4156 cx.update(|cx| {
4157 parent.update(cx, |thread, cx| {
4158 thread.set_speed(Speed::Fast, cx);
4159 });
4160
4161 for subagent in &subagents {
4162 assert_eq!(
4163 subagent.read(cx).speed(),
4164 Some(Speed::Fast),
4165 "Subagent speed should match parent after set_speed"
4166 );
4167 }
4168 });
4169 }
4170
4171 #[gpui::test]
4172 async fn test_dropped_subagent_does_not_panic(cx: &mut TestAppContext) {
4173 let (parent, _event_stream) = setup_thread_for_test(cx).await;
4174 let subagents = setup_parent_with_subagents(cx, &parent, 1);
4175
4176 // Drop the subagent so the WeakEntity can no longer be upgraded
4177 drop(subagents);
4178
4179 // Should not panic even though the subagent was dropped
4180 cx.update(|cx| {
4181 parent.update(cx, |thread, cx| {
4182 thread.set_thinking_enabled(true, cx);
4183 thread.set_speed(Speed::Fast, cx);
4184 thread.set_thinking_effort(Some("high".to_string()), cx);
4185 });
4186 });
4187 }
4188
4189 #[gpui::test]
4190 async fn test_handle_tool_use_json_parse_error_adds_tool_use_to_content(
4191 cx: &mut TestAppContext,
4192 ) {
4193 let (thread, event_stream) = setup_thread_for_test(cx).await;
4194
4195 cx.update(|cx| {
4196 thread.update(cx, |thread, _cx| {
4197 let tool_use_id = LanguageModelToolUseId::from("test_tool_id");
4198 let tool_name: Arc<str> = Arc::from("test_tool");
4199 let raw_input: Arc<str> = Arc::from("{invalid json");
4200 let json_parse_error = "expected value at line 1 column 1".to_string();
4201
4202 // Call the function under test
4203 let result = thread.handle_tool_use_json_parse_error_event(
4204 tool_use_id.clone(),
4205 tool_name.clone(),
4206 raw_input.clone(),
4207 json_parse_error,
4208 &event_stream,
4209 );
4210
4211 // Verify the result is an error
4212 assert!(result.is_error);
4213 assert_eq!(result.tool_use_id, tool_use_id);
4214 assert_eq!(result.tool_name, tool_name);
4215 assert!(matches!(
4216 result.content,
4217 LanguageModelToolResultContent::Text(_)
4218 ));
4219
4220 // Verify the tool use was added to the message content
4221 {
4222 let last_message = thread.pending_message();
4223 assert_eq!(
4224 last_message.content.len(),
4225 1,
4226 "Should have one tool_use in content"
4227 );
4228
4229 match &last_message.content[0] {
4230 AgentMessageContent::ToolUse(tool_use) => {
4231 assert_eq!(tool_use.id, tool_use_id);
4232 assert_eq!(tool_use.name, tool_name);
4233 assert_eq!(tool_use.raw_input, raw_input.to_string());
4234 assert!(tool_use.is_input_complete);
4235 // Should fall back to empty object for invalid JSON
4236 assert_eq!(tool_use.input, json!({}));
4237 }
4238 _ => panic!("Expected ToolUse content"),
4239 }
4240 }
4241
4242 // Insert the tool result (simulating what the caller does)
4243 thread
4244 .pending_message()
4245 .tool_results
4246 .insert(result.tool_use_id.clone(), result);
4247
4248 // Verify the tool result was added
4249 let last_message = thread.pending_message();
4250 assert_eq!(
4251 last_message.tool_results.len(),
4252 1,
4253 "Should have one tool_result"
4254 );
4255 assert!(last_message.tool_results.contains_key(&tool_use_id));
4256 });
4257 });
4258 }
4259}