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