Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

agent: Use v2 tool events and permission choices (#65393)

Ben Brandt7fb155e9a26d
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs
index bda14eee2d5..ecd30dcdeaa 100644
--- a/crates/acp_thread/src/acp_thread.rs
+++ b/crates/acp_thread/src/acp_thread.rs
@@ -1148,18 +1148,51 @@ struct ToolCallPatch {
}
enum ToolContentPatch {
- Legacy(Vec<acp_v1::ToolCallContent>),
- Protocol(Vec<acp_v2::ToolCallContent>),
+ V1(Vec<acp_v1::ToolCallContent>),
+ V2(Vec<acp_v2::ToolCallContent>),
+}
+
+#[derive(Clone, Copy)]
+struct ToolTerminalResolver<'a> {
+ terminals: &'a HashMap<acp_v2::TerminalId, Entity<Terminal>>,
+ client_managed_only: bool,
+}
+
+impl<'a> ToolTerminalResolver<'a> {
+ fn registered(terminals: &'a HashMap<acp_v2::TerminalId, Entity<Terminal>>) -> Self {
+ Self {
+ terminals,
+ client_managed_only: false,
+ }
+ }
+
+ fn resolve(self, id: &acp_v2::TerminalId, cx: &App) -> Result<Entity<Terminal>> {
+ let terminal = self
+ .terminals
+ .get(id)
+ .cloned()
+ .ok_or_else(|| anyhow!("Terminal with id `{id}` not found"))?;
+ if self.client_managed_only {
+ // Process ownership survives completion and does not depend on
+ // whether the renderer still has an active PTY.
+ anyhow::ensure!(
+ terminal.read(cx).is_process_backed(),
+ "Client-managed tool content cannot reference an agent-owned display terminal"
+ );
+ }
+ Ok(terminal)
+ }
}
impl ToolContentPatch {
fn prepare(
self,
- terminals: &HashMap<acp_v1::TerminalId, Entity<Terminal>>,
+ terminals: ToolTerminalResolver<'_>,
+ cx: &App,
) -> Result<Vec<PreparedToolCallContent>> {
match self {
- Self::Legacy(content) => PreparedToolCallContent::prepare(content, terminals),
- Self::Protocol(content) => PreparedToolCallContent::prepare_v2(content, terminals),
+ Self::V1(content) => PreparedToolCallContent::prepare(content, terminals, cx),
+ Self::V2(content) => PreparedToolCallContent::prepare_v2(content, terminals, cx),
}
}
}
@@ -1206,7 +1239,7 @@ impl ToolCallPatch {
name: legacy_tool_field(fields.name),
kind: legacy_tool_field(fields.kind.and_then(tool_kind_from_v1)),
status: legacy_tool_field(fields.status.and_then(tool_status_from_v1)),
- content: legacy_tool_field(fields.content.map(ToolContentPatch::Legacy)),
+ content: legacy_tool_field(fields.content.map(ToolContentPatch::V1)),
locations: legacy_tool_field(
fields
.locations
@@ -1224,7 +1257,7 @@ impl ToolCallPatch {
name: update.name,
kind: update.kind,
status: update.status,
- content: update.content.map_value(ToolContentPatch::Protocol),
+ content: update.content.map_value(ToolContentPatch::V2),
locations: update
.locations
.map_value(|locations| locations.into_iter().map(Into::into).collect()),
@@ -1240,7 +1273,7 @@ impl ToolCall {
tool_call: acp_v1::ToolCall,
status: Option<ToolCallStatus>,
language_registry: Arc<LanguageRegistry>,
- terminals: &HashMap<acp_v1::TerminalId, Entity<Terminal>>,
+ terminals: &HashMap<acp_v2::TerminalId, Entity<Terminal>>,
cx: &mut App,
) -> Result<Self> {
let update = acp_v1::ToolCallUpdate::from(tool_call);
@@ -1248,7 +1281,7 @@ impl ToolCall {
acp_v2::ToolCallId::new(update.tool_call_id.0),
ToolCallPatch::legacy(update.fields, update.meta),
language_registry,
- terminals,
+ ToolTerminalResolver::registered(terminals),
cx,
)?;
if let Some(status) = status {
@@ -1261,13 +1294,13 @@ impl ToolCall {
id: acp_v2::ToolCallId,
patch: ToolCallPatch,
language_registry: Arc<LanguageRegistry>,
- terminals: &HashMap<acp_v1::TerminalId, Entity<Terminal>>,
+ terminals: ToolTerminalResolver<'_>,
cx: &mut App,
) -> Result<Self> {
let content = patch
.content
.take()
- .map(|content| content.prepare(terminals))
+ .map(|content| content.prepare(terminals, cx))
.transpose()?
.unwrap_or_default()
.into_iter()
@@ -1349,7 +1382,7 @@ impl ToolCall {
.unwrap_or(ToolCallStatus::Pending)
}
- fn permission_status(&self) -> Option<acp_v1::ToolCallStatus> {
+ fn permission_status(&self) -> Option<acp_v2::ToolCallStatus> {
self.local_status
.or_else(|| ToolCallStatus::from_reported(self.reported_status.as_ref()))
.and_then(|status| status.as_acp_status())
@@ -1411,27 +1444,11 @@ impl ToolCall {
})
}
- fn update_fields(
- &mut self,
- fields: acp_v1::ToolCallUpdateFields,
- meta: Option<acp_v1::Meta>,
- language_registry: Arc<LanguageRegistry>,
- terminals: &HashMap<acp_v1::TerminalId, Entity<Terminal>>,
- cx: &mut App,
- ) -> Result<()> {
- self.apply_patch(
- ToolCallPatch::legacy(fields, meta),
- language_registry,
- terminals,
- cx,
- )
- }
-
fn apply_patch(
&mut self,
patch: ToolCallPatch,
language_registry: Arc<LanguageRegistry>,
- terminals: &HashMap<acp_v1::TerminalId, Entity<Terminal>>,
+ terminals: ToolTerminalResolver<'_>,
cx: &mut App,
) -> Result<()> {
let legacy_terminal_labels = matches!(&patch.meta, ToolMetadataPatch::Legacy(_));
@@ -1455,7 +1472,7 @@ impl ToolCall {
let content = match content {
MaybeUndefined::Undefined => None,
MaybeUndefined::Null => Some(Vec::new()),
- MaybeUndefined::Value(content) => Some(content.prepare(terminals)?),
+ MaybeUndefined::Value(content) => Some(content.prepare(terminals, cx)?),
};
let was_plain_text =
self.effective_title().is_none() || self.kind() == &acp_v2::ToolKind::Execute;
@@ -1516,15 +1533,16 @@ impl ToolCall {
if !title.is_undefined() {
self.title = title.take().map(SharedString::from);
- if legacy_terminal_labels
- && self.kind() == &acp_v2::ToolKind::Execute
+ if self.kind() == &acp_v2::ToolKind::Execute
&& let Some(title) = self.effective_title()
{
// A missing tool title must not overwrite an actual terminal command.
for terminal in self.terminals() {
- terminal.update(cx, |terminal, cx| {
- terminal.update_command_label(title, cx);
- });
+ if legacy_terminal_labels || terminal.read(cx).is_process_backed() {
+ terminal.update(cx, |terminal, cx| {
+ terminal.update_command_label(title, cx);
+ });
+ }
}
}
}
@@ -1794,15 +1812,15 @@ pub enum SelectedPermissionParams {
#[derive(Debug, Clone)]
pub struct SelectedPermissionOutcome {
- pub option_id: acp_v1::PermissionOptionId,
- pub option_kind: acp_v1::PermissionOptionKind,
+ pub option_id: acp_v2::PermissionOptionId,
+ pub option_kind: acp_v2::PermissionOptionKind,
pub params: Option<SelectedPermissionParams>,
}
impl SelectedPermissionOutcome {
pub fn new(
- option_id: acp_v1::PermissionOptionId,
- option_kind: acp_v1::PermissionOptionKind,
+ option_id: acp_v2::PermissionOptionId,
+ option_kind: acp_v2::PermissionOptionKind,
) -> Self {
Self {
option_id,
@@ -1817,12 +1835,6 @@ impl SelectedPermissionOutcome {
}
}
-impl From<SelectedPermissionOutcome> for acp_v1::SelectedPermissionOutcome {
- fn from(value: SelectedPermissionOutcome) -> Self {
- Self::new(value.option_id)
- }
-}
-
#[derive(Clone, Debug)]
pub enum RequestPermissionOutcome {
Cancelled,
@@ -1830,16 +1842,6 @@ pub enum RequestPermissionOutcome {
Selected(SelectedPermissionOutcome),
}
-impl From<RequestPermissionOutcome> for acp_v1::RequestPermissionOutcome {
- fn from(value: RequestPermissionOutcome) -> Self {
- match value {
- RequestPermissionOutcome::Cancelled
- | RequestPermissionOutcome::InterruptedByFollowUp => Self::Cancelled,
- RequestPermissionOutcome::Selected(outcome) => Self::Selected(outcome.into()),
- }
- }
-}
-
/// What a `WaitingForConfirmation` prompt represents semantically.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuthorizationKind {
@@ -1893,20 +1895,21 @@ impl ToolCallStatus {
}
}
- fn as_acp_status(&self) -> Option<acp_v1::ToolCallStatus> {
+ fn as_acp_status(&self) -> Option<acp_v2::ToolCallStatus> {
match self {
- ToolCallStatus::Pending => Some(acp_v1::ToolCallStatus::Pending),
- ToolCallStatus::InProgress => Some(acp_v1::ToolCallStatus::InProgress),
- ToolCallStatus::Completed => Some(acp_v1::ToolCallStatus::Completed),
- ToolCallStatus::Failed => Some(acp_v1::ToolCallStatus::Failed),
- ToolCallStatus::WaitingForConfirmation
- | ToolCallStatus::Rejected
- | ToolCallStatus::Canceled => None,
+ ToolCallStatus::Pending => Some(acp_v2::ToolCallStatus::Pending),
+ ToolCallStatus::InProgress => Some(acp_v2::ToolCallStatus::InProgress),
+ ToolCallStatus::Completed => Some(acp_v2::ToolCallStatus::Completed),
+ ToolCallStatus::Failed => Some(acp_v2::ToolCallStatus::Failed),
+ // A new authorization can retry a locally canceled tool; the
+ // incoming request then supplies its continuation status.
+ ToolCallStatus::Canceled => None,
+ ToolCallStatus::WaitingForConfirmation | ToolCallStatus::Rejected => None,
}
}
- fn status_after_permission_grant(status: acp_v1::ToolCallStatus) -> ToolCallStatus {
- match ToolCallStatus::from(status) {
+ fn status_after_permission_grant(status: acp_v2::ToolCallStatus) -> ToolCallStatus {
+ match Self::from_reported(Some(&status)).unwrap_or(Self::Pending) {
ToolCallStatus::Pending => ToolCallStatus::InProgress,
status => status,
}
@@ -2974,7 +2977,8 @@ enum PreparedToolCallContent {
impl PreparedToolCallContent {
fn prepare(
content: Vec<acp_v1::ToolCallContent>,
- terminals: &HashMap<acp_v1::TerminalId, Entity<Terminal>>,
+ terminals: ToolTerminalResolver<'_>,
+ cx: &App,
) -> Result<Vec<Self>> {
let mut prepared = Vec::with_capacity(content.len());
for content in content {
@@ -2986,10 +2990,7 @@ impl PreparedToolCallContent {
acp_v1::ToolCallContent::Terminal(acp_v1::Terminal {
terminal_id, meta, ..
}) => Self::Terminal {
- terminal: terminals
- .get(&terminal_id)
- .cloned()
- .ok_or_else(|| anyhow!("Terminal with id `{terminal_id}` not found"))?,
+ terminal: terminals.resolve(&acp_v2::TerminalId::new(terminal_id.0), cx)?,
meta,
},
_ => continue,
@@ -3001,31 +3002,27 @@ impl PreparedToolCallContent {
fn prepare_v2(
content: Vec<acp_v2::ToolCallContent>,
- terminals: &HashMap<acp_v1::TerminalId, Entity<Terminal>>,
+ terminals: ToolTerminalResolver<'_>,
+ cx: &App,
) -> Result<Vec<Self>> {
content
.into_iter()
- .map(|content| Self::from_v2(content, terminals))
+ .map(|content| Self::from_v2(content, terminals, cx))
.collect()
}
fn from_v2(
content: acp_v2::ToolCallContent,
- terminals: &HashMap<acp_v1::TerminalId, Entity<Terminal>>,
+ terminals: ToolTerminalResolver<'_>,
+ cx: &App,
) -> Result<Self> {
match content {
acp_v2::ToolCallContent::Content(content) => Ok(Self::ContentBlock(*content)),
acp_v2::ToolCallContent::Diff(diff) => Ok(Self::DiffPatch(diff)),
- acp_v2::ToolCallContent::Terminal(terminal) => {
- let terminal_id = acp_v1::TerminalId::new(terminal.terminal_id.0);
- Ok(Self::Terminal {
- terminal: terminals
- .get(&terminal_id)
- .cloned()
- .ok_or_else(|| anyhow!("Terminal with id `{terminal_id}` not found"))?,
- meta: terminal.meta,
- })
- }
+ acp_v2::ToolCallContent::Terminal(terminal) => Ok(Self::Terminal {
+ terminal: terminals.resolve(&terminal.terminal_id, cx)?,
+ meta: terminal.meta,
+ }),
other => Ok(Self::Other(other)),
}
}
@@ -3173,24 +3170,21 @@ impl ToolCallContent {
#[derive(Debug, PartialEq)]
pub enum ToolCallUpdate {
- UpdateFields(acp_v1::ToolCallUpdate),
+ V2(acp_v2::ToolCallUpdate),
+ V1(acp_v1::ToolCallUpdate),
UpdateDiff(ToolCallUpdateDiff),
UpdateTerminal(ToolCallUpdateTerminal),
}
-impl ToolCallUpdate {
- fn id(&self) -> acp_v2::ToolCallId {
- match self {
- Self::UpdateFields(update) => acp_v2::ToolCallId::new(update.tool_call_id.0.clone()),
- Self::UpdateDiff(diff) => diff.id.clone(),
- Self::UpdateTerminal(terminal) => terminal.id.clone(),
- }
+impl From<acp_v2::ToolCallUpdate> for ToolCallUpdate {
+ fn from(update: acp_v2::ToolCallUpdate) -> Self {
+ Self::V2(update)
}
}
impl From<acp_v1::ToolCallUpdate> for ToolCallUpdate {
fn from(update: acp_v1::ToolCallUpdate) -> Self {
- Self::UpdateFields(update)
+ Self::V1(update)
}
}
@@ -3449,9 +3443,9 @@ pub struct AcpThread {
available_commands: Vec<acp_v2::AvailableCommand>,
_observe_prompt_capabilities: Task<anyhow::Result<()>>,
_idle_sleep_subscriptions: Vec<Subscription>,
- terminals: HashMap<acp_v1::TerminalId, Entity<Terminal>>,
- pending_terminal_output: HashMap<acp_v1::TerminalId, Vec<Vec<u8>>>,
- pending_terminal_exit: HashMap<acp_v1::TerminalId, acp_v1::TerminalExitStatus>,
+ terminals: HashMap<acp_v2::TerminalId, Entity<Terminal>>,
+ pending_terminal_output: HashMap<acp_v2::TerminalId, Vec<Vec<u8>>>,
+ pending_terminal_exit: HashMap<acp_v2::TerminalId, acp_v1::TerminalExitStatus>,
had_error: bool,
/// The user's unsent prompt text, persisted so it can be restored when reloading the thread.
draft_prompt: Option<Vec<acp_v2::ContentBlock>>,
@@ -3622,16 +3616,16 @@ pub enum TerminalProviderEvent {
#[derive(Debug, Clone)]
pub enum TerminalProviderCommand {
WriteInput {
- terminal_id: acp_v1::TerminalId,
+ terminal_id: acp_v2::TerminalId,
bytes: Vec<u8>,
},
Resize {
- terminal_id: acp_v1::TerminalId,
+ terminal_id: acp_v2::TerminalId,
cols: u16,
rows: u16,
},
Close {
- terminal_id: acp_v1::TerminalId,
+ terminal_id: acp_v2::TerminalId,
},
}
@@ -5279,69 +5273,95 @@ impl AcpThread {
update: impl Into<ToolCallUpdate>,
cx: &mut Context<Self>,
) -> Result<()> {
- let update = update.into();
- let languages = self.project.read(cx).languages().clone();
-
- let id = update.id();
- let ix = match self.index_for_tool_call(&id) {
- Some(ix) => ix,
- None => {
- // Tool call not found - create a failed tool call entry
- let failed_tool_call = ToolCall::from_acp(
- acp_v1::ToolCall::new(acp_v1::ToolCallId::new(id.0), "Tool call not found")
- .kind(acp_v1::ToolKind::Fetch)
- .status(acp_v1::ToolCallStatus::Failed)
- .content(vec!["Tool call not found".into()]),
- Some(ToolCallStatus::Failed),
+ match update.into() {
+ ToolCallUpdate::V1(update) => {
+ let id = acp_v2::ToolCallId::new(update.tool_call_id.0);
+ let Some(index) = self.tool_call_index_for_update(&id, cx)? else {
+ return Ok(());
+ };
+ let languages = self.project.read(cx).languages().clone();
+ let Some(AgentThreadEntry::ToolCall(call)) = self.entries.get_mut(index) else {
+ anyhow::bail!("Tool call entry disappeared while updating");
+ };
+ let patch = ToolCallPatch::legacy(update.fields, update.meta);
+ let location_updated = !patch.locations.is_undefined();
+ let authorization_id = call.authorization_id();
+ let result = call.apply_patch(
+ patch,
languages,
- &self.terminals,
+ ToolTerminalResolver::registered(&self.terminals),
cx,
- )?;
- self.push_entry(AgentThreadEntry::ToolCall(failed_tool_call), cx);
- return Ok(());
- }
- };
- let AgentThreadEntry::ToolCall(call) = &mut self.entries[ix] else {
- unreachable!()
- };
-
- match update {
- ToolCallUpdate::UpdateFields(update) => {
- let location_updated = update.fields.locations.is_some();
- let authorization_id = call.authorization_id();
- let result =
- call.update_fields(update.fields, update.meta, languages, &self.terminals, cx);
+ );
let detached_id =
authorization_id.filter(|id| call.authorization_id() != Some(*id));
if let Some(id) = detached_id {
self.resolve_permission_request(id, RequestPermissionOutcome::Cancelled, cx);
}
if let Err(error) = result {
- cx.emit(AcpThreadEvent::EntryUpdated(ix));
+ cx.emit(AcpThreadEvent::EntryUpdated(index));
return Err(error);
}
if location_updated {
self.resolve_locations(id, cx);
}
+ cx.emit(AcpThreadEvent::EntryUpdated(index));
+ Ok(())
}
+ ToolCallUpdate::V2(update) => self.upsert_local_tool_call(update, cx),
ToolCallUpdate::UpdateDiff(update) => {
- call.structured_content.clear();
- call.structured_content
- .push(ToolCallContent::Diff(update.diff));
- call.update_raw_output_content(&languages, cx);
+ self.update_tool_call_content(update.id, ToolCallContent::Diff(update.diff), cx)
}
- ToolCallUpdate::UpdateTerminal(update) => {
- call.structured_content.clear();
- call.structured_content.push(ToolCallContent::Terminal {
+ ToolCallUpdate::UpdateTerminal(update) => self.update_tool_call_content(
+ update.id,
+ ToolCallContent::Terminal {
terminal: update.terminal,
meta: None,
- });
- call.update_raw_output_content(&languages, cx);
- }
+ },
+ cx,
+ ),
}
+ }
- cx.emit(AcpThreadEvent::EntryUpdated(ix));
+ fn tool_call_index_for_update(
+ &mut self,
+ id: &acp_v2::ToolCallId,
+ cx: &mut Context<Self>,
+ ) -> Result<Option<usize>> {
+ if let Some(index) = self.index_for_tool_call(id) {
+ return Ok(Some(index));
+ }
+ let languages = self.project.read(cx).languages().clone();
+ let failed_tool_call = ToolCall::from_acp(
+ acp_v1::ToolCall::new(acp_v1::ToolCallId::new(id.0.clone()), "Tool call not found")
+ .kind(acp_v1::ToolKind::Fetch)
+ .status(acp_v1::ToolCallStatus::Failed)
+ .content(vec!["Tool call not found".into()]),
+ Some(ToolCallStatus::Failed),
+ languages,
+ &self.terminals,
+ cx,
+ )?;
+ self.push_entry(AgentThreadEntry::ToolCall(failed_tool_call), cx);
+ Ok(None)
+ }
+ fn update_tool_call_content(
+ &mut self,
+ id: acp_v2::ToolCallId,
+ content: ToolCallContent,
+ cx: &mut Context<Self>,
+ ) -> Result<()> {
+ let Some(index) = self.tool_call_index_for_update(&id, cx)? else {
+ return Ok(());
+ };
+ let languages = self.project.read(cx).languages().clone();
+ let Some(AgentThreadEntry::ToolCall(call)) = self.entries.get_mut(index) else {
+ anyhow::bail!("Tool call entry disappeared while updating content");
+ };
+ call.structured_content.clear();
+ call.structured_content.push(content);
+ call.update_raw_output_content(&languages, cx);
+ cx.emit(AcpThreadEvent::EntryUpdated(index));
Ok(())
}
@@ -5384,19 +5404,39 @@ impl AcpThread {
status: Option<ToolCallStatus>,
cx: &mut Context<Self>,
) -> Result<(), acp_v1::Error> {
- let language_registry = self.project.read(cx).languages().clone();
let id = acp_v2::ToolCallId::new(update.tool_call_id.0.clone());
+ let update = if self.index_for_tool_call(&id).is_none() {
+ acp_v1::ToolCallUpdate::from(acp_v1::ToolCall::try_from(update)?)
+ } else {
+ update
+ };
+ self.upsert_legacy_behavior_tool_call(
+ id,
+ ToolCallPatch::legacy(update.fields, update.meta),
+ status,
+ cx,
+ )
+ .map_err(Into::into)
+ }
+
+ fn upsert_legacy_behavior_tool_call(
+ &mut self,
+ id: acp_v2::ToolCallId,
+ patch: ToolCallPatch,
+ status: Option<ToolCallStatus>,
+ cx: &mut Context<Self>,
+ ) -> Result<()> {
+ let language_registry = self.project.read(cx).languages().clone();
if let Some(ix) = self.index_for_tool_call(&id) {
let AgentThreadEntry::ToolCall(call) = &mut self.entries[ix] else {
unreachable!()
};
let authorization_id = call.authorization_id();
- let result = call.update_fields(
- update.fields,
- update.meta,
+ let result = call.apply_patch(
+ patch,
language_registry,
- &self.terminals,
+ ToolTerminalResolver::registered(&self.terminals),
cx,
);
let detached_id = authorization_id.filter(|id| call.authorization_id() != Some(*id));
@@ -5410,18 +5450,25 @@ impl AcpThread {
}
if let Err(error) = result {
cx.emit(AcpThreadEvent::EntryUpdated(ix));
- return Err(acp_v1::Error::from(error));
+ return Err(error);
}
cx.emit(AcpThreadEvent::EntryUpdated(ix));
} else {
- let call = ToolCall::from_acp(
- update.try_into()?,
- status,
+ anyhow::ensure!(
+ patch.title.value().is_some(),
+ "title is required for a tool call"
+ );
+ let mut call = ToolCall::from_patch(
+ id.clone(),
+ patch,
language_registry,
- &self.terminals,
+ ToolTerminalResolver::registered(&self.terminals),
cx,
)?;
+ if let Some(status) = status {
+ call.set_legacy_status(status);
+ }
self.push_entry(AgentThreadEntry::ToolCall(call), cx);
};
@@ -5429,7 +5476,8 @@ impl AcpThread {
Ok(())
}
- pub fn upsert_tool_call_patch(
+ /// Wire updates may create agent-reported display terminals.
+ pub fn upsert_wire_tool_call(
&mut self,
update: acp_v2::ToolCallUpdate,
cx: &mut Context<Self>,
@@ -5441,17 +5489,43 @@ impl AcpThread {
}
let id = update.tool_call_id.clone();
let patch = ToolCallPatch::protocol(update);
+ self.upsert_tool_call_patch(id, patch, false, cx)
+ }
+
+ /// In-process updates may reference registered client-managed terminals, but
+ /// must not create or take ownership of agent-reported display terminals.
+ pub fn upsert_local_tool_call(
+ &mut self,
+ update: acp_v2::ToolCallUpdate,
+ cx: &mut Context<Self>,
+ ) -> Result<()> {
+ let id = update.tool_call_id.clone();
+ let patch = ToolCallPatch::protocol(update);
+ self.upsert_tool_call_patch(id, patch, true, cx)
+ }
+
+ fn upsert_tool_call_patch(
+ &mut self,
+ id: acp_v2::ToolCallId,
+ patch: ToolCallPatch,
+ client_managed_terminals_only: bool,
+ cx: &mut Context<Self>,
+ ) -> Result<()> {
let locations_changed = !patch.locations.is_undefined();
if let Some(status) = ToolCallStatus::from_reported(patch.status.value()) {
self.report_tool_call_completed(status);
}
let languages = self.project.read(cx).languages().clone();
+ let terminals = ToolTerminalResolver {
+ terminals: &self.terminals,
+ client_managed_only: client_managed_terminals_only,
+ };
if let Some(index) = self.index_for_tool_call(&id) {
let AgentThreadEntry::ToolCall(call) = &mut self.entries[index] else {
unreachable!()
};
let authorization_id = call.authorization_id();
- let result = call.apply_patch(patch, languages, &self.terminals, cx);
+ let result = call.apply_patch(patch, languages, terminals, cx);
let detached_id = authorization_id.filter(|id| call.authorization_id() != Some(*id));
if let Some(id) = detached_id {
self.resolve_permission_request(id, RequestPermissionOutcome::Cancelled, cx);
@@ -5459,7 +5533,7 @@ impl AcpThread {
cx.emit(AcpThreadEvent::EntryUpdated(index));
result?;
} else {
- let call = ToolCall::from_patch(id.clone(), patch, languages, &self.terminals, cx)?;
+ let call = ToolCall::from_patch(id.clone(), patch, languages, terminals, cx)?;
self.push_entry(AgentThreadEntry::ToolCall(call), cx);
}
if locations_changed {
@@ -5481,7 +5555,11 @@ impl AcpThread {
..
} = chunk;
self.ensure_tool_content_terminal(&content, cx);
- let content = PreparedToolCallContent::from_v2(content, &self.terminals)?;
+ let content = PreparedToolCallContent::from_v2(
+ content,
+ ToolTerminalResolver::registered(&self.terminals),
+ cx,
+ )?;
let language_registry = self.project.read(cx).languages().clone();
let id = tool_call_id;
@@ -5493,7 +5571,7 @@ impl AcpThread {
id.clone(),
ToolCallPatch::protocol(acp_v2::ToolCallUpdate::new(id)),
language_registry.clone(),
- &self.terminals,
+ ToolTerminalResolver::registered(&self.terminals),
cx,
)?;
call.append_content(content, &language_registry, cx);
@@ -5508,10 +5586,7 @@ impl AcpThread {
cx: &mut Context<Self>,
) {
if let acp_v2::ToolCallContent::Terminal(terminal) = content {
- self.ensure_display_terminal(
- acp_v1::TerminalId::new(terminal.terminal_id.0.clone()),
- cx,
- );
+ self.ensure_display_terminal(terminal.terminal_id.clone(), cx);
}
}
@@ -5761,18 +5836,59 @@ impl AcpThread {
kind: AuthorizationKind,
cx: &mut Context<Self>,
) -> Result<(PermissionRequestId, Task<RequestPermissionOutcome>)> {
- let (tx, rx) = oneshot::channel();
-
let tool_call_id = acp_v2::ToolCallId::new(tool_call.tool_call_id.0.clone());
let current_status = self
.tool_call(&tool_call_id)
.and_then(|(_, tool_call)| tool_call.permission_status())
- .or(tool_call.fields.status)
- .and_then(tool_status_from_v1);
+ .or_else(|| tool_call.fields.status.and_then(tool_status_from_v1));
let current_status = ToolCallStatus::from_reported(current_status.as_ref())
.unwrap_or(ToolCallStatus::Pending);
self.upsert_tool_call_inner(tool_call, Some(current_status), cx)?;
+ self.install_tool_call_authorization(tool_call_id, options, kind, cx)
+ }
+
+ pub fn request_tool_call_update_authorization(
+ &mut self,
+ tool_call: acp_v2::ToolCallUpdate,
+ options: PermissionOptions,
+ kind: AuthorizationKind,
+ cx: &mut Context<Self>,
+ ) -> Result<Task<RequestPermissionOutcome>> {
+ self.request_tool_call_update_authorization_with_id(tool_call, options, kind, cx)
+ .map(|(_, task)| task)
+ }
+
+ pub fn request_tool_call_update_authorization_with_id(
+ &mut self,
+ tool_call: acp_v2::ToolCallUpdate,
+ options: PermissionOptions,
+ kind: AuthorizationKind,
+ cx: &mut Context<Self>,
+ ) -> Result<(PermissionRequestId, Task<RequestPermissionOutcome>)> {
+ let tool_call_id = tool_call.tool_call_id.clone();
+ let current_status = self
+ .tool_call(&tool_call_id)
+ .and_then(|(_, call)| call.permission_status())
+ .or_else(|| tool_call.status.value().cloned());
+ let current_status = ToolCallStatus::from_reported(current_status.as_ref())
+ .unwrap_or(ToolCallStatus::Pending);
+ self.upsert_local_tool_call(tool_call, cx)?;
+ let (_, call) = self
+ .tool_call_mut(&tool_call_id)
+ .context("tool call disappeared while requesting authorization")?;
+ call.set_local_status(current_status);
+ self.install_tool_call_authorization(tool_call_id, options, kind, cx)
+ }
+
+ fn install_tool_call_authorization(
+ &mut self,
+ tool_call_id: acp_v2::ToolCallId,
+ options: PermissionOptions,
+ kind: AuthorizationKind,
+ cx: &mut Context<Self>,
+ ) -> Result<(PermissionRequestId, Task<RequestPermissionOutcome>)> {
+ let (tx, rx) = oneshot::channel();
if let Some(id) = self
.tool_call(&tool_call_id)
.and_then(|(_, call)| call.authorization_id())
@@ -5882,7 +5998,7 @@ impl AcpThread {
log::debug!("Permission choice is not an offered option");
return;
};
- outcome.option_kind = option.kind;
+ outcome.option_kind = option.kind.clone();
let tool_call_id = tool_call_id.clone();
let kind = *kind;
let Some((_, call)) = self.tool_call_mut(&tool_call_id) else {
@@ -5897,9 +6013,18 @@ impl AcpThread {
AuthorizationKind::PermissionGrant => {
let current_status = call.permission_status().unwrap_or_default();
match outcome.option_kind {
- acp_v1::PermissionOptionKind::RejectOnce
- | acp_v1::PermissionOptionKind::RejectAlways => ToolCallStatus::Rejected,
- _ => ToolCallStatus::status_after_permission_grant(current_status),
+ acp_v2::PermissionOptionKind::RejectOnce
+ | acp_v2::PermissionOptionKind::RejectAlways => ToolCallStatus::Rejected,
+ acp_v2::PermissionOptionKind::AllowOnce
+ | acp_v2::PermissionOptionKind::AllowAlways => {
+ ToolCallStatus::status_after_permission_grant(current_status)
+ }
+ _ => {
+ log::warn!(
+ "Cannot authorize a tool with an unknown permission option kind"
+ );
+ return;
+ }
}
}
};
@@ -6689,7 +6814,7 @@ impl AcpThread {
this.flush_streaming_text(cx);
if let Some((ix, _)) = this.user_message_mut(&client_id) {
// Collect all terminals from entries that will be removed
- let terminals_to_remove: Vec<acp_v1::TerminalId> = this.entries[ix..]
+ let terminals_to_remove: Vec<acp_v2::TerminalId> = this.entries[ix..]
.iter()
.flat_map(|entry| entry.terminals())
.filter_map(|terminal| terminal.read(cx).id().clone().into())
@@ -7079,7 +7204,7 @@ impl AcpThread {
// without a PTY in that case.
let headless = HeadlessTerminal::is_enabled(cx);
- let terminal_id = acp_v1::TerminalId::new(Uuid::new_v4().to_string());
+ let terminal_id = acp_v2::TerminalId::new(Uuid::new_v4().to_string());
let terminal_task = cx.spawn({
let terminal_id = terminal_id.clone();
async move |_this, cx| {
@@ -7200,7 +7325,7 @@ impl AcpThread {
pub fn kill_terminal(
&mut self,
- terminal_id: acp_v1::TerminalId,
+ terminal_id: acp_v2::TerminalId,
cx: &mut Context<Self>,
) -> Result<()> {
self.terminals
@@ -7215,7 +7340,7 @@ impl AcpThread {
pub fn release_terminal(
&mut self,
- terminal_id: acp_v1::TerminalId,
+ terminal_id: acp_v2::TerminalId,
cx: &mut Context<Self>,
) -> Result<()> {
self.terminals
@@ -7228,7 +7353,7 @@ impl AcpThread {
Ok(())
}
- pub fn terminal(&self, terminal_id: acp_v1::TerminalId) -> Result<Entity<Terminal>> {
+ pub fn terminal(&self, terminal_id: acp_v2::TerminalId) -> Result<Entity<Terminal>> {
self.terminals
.get(&terminal_id)
.context("Terminal not found")
@@ -7257,7 +7382,7 @@ impl AcpThread {
pub fn register_terminal_created(
&mut self,
- terminal_id: acp_v1::TerminalId,
+ terminal_id: acp_v2::TerminalId,
command_label: String,
working_dir: Option<PathBuf>,
output_byte_limit: Option<u64>,
@@ -7300,7 +7425,7 @@ impl AcpThread {
patch: DisplayTerminalPatch,
cx: &mut Context<Self>,
) -> Result<()> {
- let terminal = self.ensure_display_terminal(acp_v1::TerminalId::new(terminal_id.0), cx);
+ let terminal = self.ensure_display_terminal(terminal_id, cx);
terminal.update(cx, |terminal, cx| terminal.apply_display_patch(patch, cx))
}
@@ -7310,13 +7435,13 @@ impl AcpThread {
data: &[u8],
cx: &mut Context<Self>,
) -> Result<()> {
- let terminal = self.ensure_display_terminal(acp_v1::TerminalId::new(terminal_id.0), cx);
+ let terminal = self.ensure_display_terminal(terminal_id, cx);
terminal.update(cx, |terminal, cx| terminal.append_display_bytes(data, cx))
}
fn ensure_display_terminal(
&mut self,
- terminal_id: acp_v1::TerminalId,
+ terminal_id: acp_v2::TerminalId,
cx: &mut Context<Self>,
) -> Entity<Terminal> {
if let Some(terminal) = self.terminals.get(&terminal_id) {
@@ -7336,7 +7461,7 @@ impl AcpThread {
fn register_display_terminal(
&mut self,
- terminal_id: acp_v1::TerminalId,
+ terminal_id: acp_v2::TerminalId,
command: Option<&str>,
cwd: Option<PathBuf>,
output_byte_limit: Option<u64>,
@@ -7395,6 +7520,7 @@ impl AcpThread {
output_byte_limit,
terminal,
} => {
+ let terminal_id = acp_v2::TerminalId::new(terminal_id.0);
let entity = self
.terminals
.get(&terminal_id)
@@ -7422,6 +7548,7 @@ impl AcpThread {
cx.notify();
}
TerminalProviderEvent::Output { terminal_id, data } => {
+ let terminal_id = acp_v2::TerminalId::new(terminal_id.0);
if let Some(entity) = self.terminals.get(&terminal_id) {
entity.update(cx, |term, cx| {
term.write_display_output(&data, cx);
@@ -7434,6 +7561,7 @@ impl AcpThread {
}
}
TerminalProviderEvent::TitleChanged { terminal_id, title } => {
+ let terminal_id = acp_v2::TerminalId::new(terminal_id.0);
if let Some(entity) = self.terminals.get(&terminal_id) {
entity.update(cx, |term, cx| {
term.inner().update(cx, |inner, cx| {
@@ -7447,6 +7575,7 @@ impl AcpThread {
terminal_id,
status,
} => {
+ let terminal_id = acp_v2::TerminalId::new(terminal_id.0);
if let Some(entity) = self.terminals.get(&terminal_id) {
entity.update(cx, |term, cx| term.finish_display(status, cx));
} else {
@@ -8836,7 +8965,8 @@ mod tests {
};
let prepared = PreparedToolCallContent::prepare_v2(
vec![make_content("first", "first")],
- &HashMap::default(),
+ ToolTerminalResolver::registered(&HashMap::default()),
+ cx,
)
.expect("prepare content");
let mut content = ToolCallContent::from_prepared(
@@ -8847,7 +8977,8 @@ mod tests {
let original = content.markdown().expect("markdown").clone();
let prepared = PreparedToolCallContent::prepare_v2(
vec![make_content("second", "second")],
- &HashMap::default(),
+ ToolTerminalResolver::registered(&HashMap::default()),
+ cx,
)
.expect("prepare update");
content.update_from_prepared(
@@ -9154,7 +9285,8 @@ mod tests {
.expect("unknown content");
let prepared = PreparedToolCallContent::prepare_v2(
vec![acp_v2::ToolCallContent::Diff(diff.clone()), unknown.clone()],
- &HashMap::default(),
+ ToolTerminalResolver::registered(&HashMap::default()),
+ cx,
)
.expect("prepare v2 content");
let mut content: Vec<_> = prepared
@@ -9424,7 +9556,9 @@ mod tests {
// After Created, buffered Output should have been flushed into the renderer
let content = thread.read_with(cx, |thread, cx| {
- let term = thread.terminal(terminal_id.clone()).unwrap();
+ let term = thread
+ .terminal(acp_v2::TerminalId::new(terminal_id.0.clone()))
+ .unwrap();
term.read_with(cx, |t, cx| t.inner().read(cx).get_content())
});
@@ -9480,7 +9614,7 @@ mod tests {
cx.run_until_parked();
thread.update(cx, |thread, cx| {
let terminal = thread
- .terminal(terminal_id.clone())
+ .terminal(acp_v2::TerminalId::new(terminal_id.0.clone()))
.expect("display terminal");
terminal.update(cx, |terminal, cx| {
assert!(!terminal.is_process_backed());
@@ -9511,7 +9645,7 @@ mod tests {
cx.run_until_parked();
thread.read_with(cx, |thread, cx| {
let terminal = thread
- .terminal(terminal_id.clone())
+ .terminal(acp_v2::TerminalId::new(terminal_id.0.clone()))
.expect("display terminal");
let output = terminal.read(cx).current_output(cx);
assert!(output.output.contains("line 14999"));
@@ -9530,7 +9664,9 @@ mod tests {
cx.run_until_parked();
let content = thread.read_with(cx, |thread, cx| {
- let term = thread.terminal(terminal_id.clone()).unwrap();
+ let term = thread
+ .terminal(acp_v2::TerminalId::new(terminal_id.0.clone()))
+ .unwrap();
let output = term.read(cx).current_output(cx);
assert_eq!(
output.exit_status.and_then(|status| status.exit_code),
@@ -9547,7 +9683,7 @@ mod tests {
let terminal = thread.read_with(cx, |thread, _| {
thread
- .terminal(terminal_id.clone())
+ .terminal(acp_v2::TerminalId::new(terminal_id.0.clone()))
.expect("display terminal")
});
let ended_at = terminal.read_with(cx, |terminal, _| {
@@ -9566,7 +9702,7 @@ mod tests {
);
assert_eq!(
thread
- .terminal(terminal_id.clone())
+ .terminal(acp_v2::TerminalId::new(terminal_id.0.clone()))
.expect("terminal")
.entity_id(),
terminal.entity_id(),
@@ -9614,7 +9750,7 @@ mod tests {
for reference_first in [true, false] {
let thread = new_test_thread(cx).await;
let terminal_id = acp_v2::TerminalId::new("shared-terminal");
- let lookup_id = acp_v1::TerminalId::new("shared-terminal");
+ let lookup_id = terminal_id.clone();
let tool_id = acp_v2::ToolCallId::new("terminal-tool");
let reference = acp_v2::ToolCallUpdate::new("terminal-tool")
.title("Tool caption")
@@ -9625,7 +9761,7 @@ mod tests {
if reference_first {
thread
.update(cx, |thread, cx| {
- thread.upsert_tool_call_patch(reference.clone(), cx)
+ thread.upsert_wire_tool_call(reference.clone(), cx)
})
.expect("reference creates a placeholder");
} else {
@@ -9649,9 +9785,7 @@ mod tests {
.expect("append to placeholder");
} else {
thread
- .update(cx, |thread, cx| {
- thread.upsert_tool_call_patch(reference, cx)
- })
+ .update(cx, |thread, cx| thread.upsert_wire_tool_call(reference, cx))
.expect("reference existing display terminal");
}
thread
@@ -9668,7 +9802,7 @@ mod tests {
.expect("update display terminal");
thread
.update(cx, |thread, cx| {
- thread.upsert_tool_call_patch(
+ thread.upsert_wire_tool_call(
acp_v2::ToolCallUpdate::new("terminal-tool").title("New caption"),
cx,
)
@@ -9737,7 +9871,7 @@ mod tests {
),
("unrelated-tool", Vec::new()),
] {
- thread.upsert_tool_call_patch(
+ thread.upsert_wire_tool_call(
acp_v2::ToolCallUpdate::new(id).content(content),
cx,
)?;
@@ -9795,14 +9929,16 @@ mod tests {
cx,
);
thread
- .upsert_tool_call_patch(
+ .upsert_wire_tool_call(
acp_v2::ToolCallUpdate::new("tool").content(vec![
acp_v2::ToolCallContent::Terminal(acp_v2::Terminal::new("mixed")),
]),
cx,
)
.expect("reference consumes queued legacy output");
- let terminal = thread.terminal(terminal_id.clone()).expect("placeholder");
+ let terminal = thread
+ .terminal(acp_v2::TerminalId::new(terminal_id.0.clone()))
+ .expect("placeholder");
let renderer = terminal.read(cx).inner().clone();
assert!(renderer.read(cx).get_content().contains("old\noutput"));
let ended_at = terminal.read(cx).output().expect("reported exit").ended_at;
@@ -9847,7 +9983,9 @@ mod tests {
cx,
);
}
- let reused = thread.terminal(terminal_id).expect("hydrated terminal");
+ let reused = thread
+ .terminal(acp_v2::TerminalId::new(terminal_id.0))
+ .expect("hydrated terminal");
assert_eq!(reused, terminal);
let terminal = reused.read(cx);
assert_eq!(terminal.inner(), &renderer);
@@ -9904,7 +10042,7 @@ mod tests {
init_test(cx);
let thread = new_test_thread(cx).await;
let terminal_id = acp_v2::TerminalId::new("snapshot-terminal");
- let lookup_id = acp_v1::TerminalId::new("snapshot-terminal");
+ let lookup_id = terminal_id.clone();
let terminal_meta = acp_v2::Meta::from_iter([("terminal".into(), 1.into())]);
let output_meta = acp_v2::Meta::from_iter([("output".into(), 2.into())]);
let status_meta = acp_v2::Meta::from_iter([("exit".into(), 3.into())]);
@@ -9990,7 +10128,7 @@ mod tests {
.update(cx, |thread, cx| {
thread.on_terminal_provider_event(
TerminalProviderEvent::Exit {
- terminal_id: lookup_id.clone(),
+ terminal_id: acp_v1::TerminalId::new(lookup_id.0.clone()),
status: acp_v1::TerminalExitStatus::new().exit_code(5),
},
cx,
@@ -10006,7 +10144,7 @@ mod tests {
)?;
thread.on_terminal_provider_event(
TerminalProviderEvent::Exit {
- terminal_id: lookup_id.clone(),
+ terminal_id: acp_v1::TerminalId::new(lookup_id.0.clone()),
status: acp_v1::TerminalExitStatus::new().exit_code(6),
},
cx,
@@ -10082,7 +10220,7 @@ mod tests {
) {
init_test(cx);
let thread = new_test_thread(cx).await;
- let terminal_id = acp_v1::TerminalId::new("native-terminal");
+ let terminal_id = acp_v2::TerminalId::new("native-terminal");
let lower = cx.new(|cx| {
::terminal::TerminalBuilder::new_display_only(
::terminal::terminal_settings::CursorShape::default(),
@@ -10234,7 +10372,9 @@ mod tests {
// Output should be present after Created (flushed from buffer)
let content = thread.read_with(cx, |thread, cx| {
- let term = thread.terminal(terminal_id.clone()).unwrap();
+ let term = thread
+ .terminal(acp_v2::TerminalId::new(terminal_id.0.clone()))
+ .unwrap();
let output = term.read(cx).current_output(cx);
let exit_status = output.exit_status.expect("buffered exit status");
assert_eq!(exit_status.signal.as_deref(), Some("SIGTERM"));
@@ -10293,7 +10433,7 @@ mod tests {
.await
.unwrap();
- let terminal_id = acp_v1::TerminalId::new(uuid::Uuid::new_v4().to_string());
+ let terminal_id = acp_v2::TerminalId::new(uuid::Uuid::new_v4().to_string());
// We use printf instead of echo and chain with && sleep to ensure proper execution
let (program, args) = ShellBuilder::new(&Shell::System, false).build(
@@ -10349,6 +10489,31 @@ mod tests {
cx,
);
assert!(terminal.read(cx).is_process_backed());
+ let tool_id = acp_v2::ToolCallId::new("native-process-tool");
+ thread
+ .upsert_local_tool_call(
+ acp_v2::ToolCallUpdate::new(tool_id.clone())
+ .title("Native process")
+ .kind(acp_v2::ToolKind::Execute)
+ .content(vec![acp_v2::ToolCallContent::Terminal(
+ acp_v2::Terminal::new(terminal_id.clone()),
+ )]),
+ cx,
+ )
+ .expect("native reference uses the registered process terminal");
+ let (_, call) = thread.tool_call(&tool_id).expect("native tool");
+ assert_eq!(call.terminals().next(), Some(&terminal));
+ assert_eq!(thread.terminals.len(), 1);
+ thread
+ .update_tool_call(
+ acp_v2::ToolCallUpdate::new(tool_id).title("Updated native command"),
+ cx,
+ )
+ .expect("v2 title update changes the client-managed command label");
+ assert_eq!(
+ terminal.read(cx).command().read(cx).source().as_ref(),
+ "```\nUpdated native command\n```"
+ );
});
// Poll until the printf command produces output, rather than using a
@@ -11062,8 +11227,8 @@ mod tests {
thread.authorize_tool_call(
tool_call_id,
SelectedPermissionOutcome::new(
- acp_v1::PermissionOptionId::new("allow"),
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionId::new("allow"),
+ acp_v2::PermissionOptionKind::AllowOnce,
),
cx,
);
@@ -13199,22 +13364,33 @@ mod tests {
});
}
- #[test]
- fn test_legacy_tool_update_id_shares_backing_arc() {
+ #[gpui::test]
+ async fn test_legacy_tool_update_id_shares_backing_arc(cx: &mut TestAppContext) {
+ init_test(cx);
for value in ["", "tool/ \0 雪 😀"] {
- let backing: Arc<str> = value.into();
- let wire_id = acp_v1::ToolCallId::new(backing.clone());
- let update = ToolCallUpdate::from(acp_v1::ToolCallUpdate::new(
- wire_id.clone(),
- acp_v1::ToolCallUpdateFields::new(),
- ));
- let id = update.id();
- assert_eq!(id, acp_v2::ToolCallId::new(value));
- assert!(Arc::ptr_eq(&id.0, &backing));
- assert_eq!(
- serde_json::to_value(&id).expect("canonical ID"),
- serde_json::to_value(&wire_id).expect("wire ID"),
- );
+ let thread = new_test_thread(cx).await;
+ thread.update(cx, |thread, cx| {
+ let backing: Arc<str> = value.into();
+ let wire_id = acp_v1::ToolCallId::new(backing.clone());
+ thread
+ .update_tool_call(
+ acp_v1::ToolCallUpdate::new(
+ wire_id.clone(),
+ acp_v1::ToolCallUpdateFields::new(),
+ ),
+ cx,
+ )
+ .expect("legacy update creates the failed placeholder");
+ let (_, call) = thread
+ .tool_call(&acp_v2::ToolCallId::new(value))
+ .expect("canonical tool");
+ assert_eq!(&call.id, &acp_v2::ToolCallId::new(value));
+ assert!(Arc::ptr_eq(&call.id.0, &backing));
+ assert_eq!(
+ serde_json::to_value(&call.id).expect("canonical ID"),
+ serde_json::to_value(&wire_id).expect("wire ID"),
+ );
+ });
}
}
@@ -13241,26 +13417,441 @@ mod tests {
}
#[gpui::test]
- async fn test_tool_ids_preserve_identity_across_legacy_and_v2_updates(cx: &mut TestAppContext) {
+ async fn test_native_tool_updates_preserve_json_null(cx: &mut TestAppContext) {
init_test(cx);
- for value in ["", "tool/ \0 雪 😀"] {
- let thread = new_test_thread(cx).await;
- let backing: Arc<str> = value.into();
- let id = acp_v2::ToolCallId::new(backing.clone());
- let wire_id = acp_v1::ToolCallId::new(backing.clone());
- thread.update(cx, |thread, cx| {
- thread
- .upsert_tool_call(
- acp_v1::ToolCall::new(wire_id.clone(), "Legacy tool")
- .raw_input(json!({"retain": true})),
- cx,
- )
- .expect("legacy tool");
- let (_, call) = thread.tool_call(&id).expect("canonical tool");
- assert!(Arc::ptr_eq(&call.id.0, &backing));
+ let thread = new_test_thread(cx).await;
+ thread.update(cx, |thread, cx| {
+ let id = acp_v2::ToolCallId::new("native");
+ thread
+ .upsert_local_tool_call(
+ acp_v2::ToolCallUpdate::new(id.clone())
+ .raw_input(json!({"input": true}))
+ .raw_output(json!({"output": true})),
+ cx,
+ )
+ .expect("native creation");
+ thread
+ .update_tool_call(acp_v2::ToolCallUpdate::new(id.clone()), cx)
+ .expect("omitted raw fields preserve native state");
+ let (_, call) = thread.tool_call(&id).expect("tool");
+ assert_eq!(call.raw_input, Some(json!({"input": true})));
+ assert_eq!(call.raw_output, Some(json!({"output": true})));
- thread
- .upsert_tool_call_patch(
+ thread
+ .update_tool_call(
+ acp_v2::ToolCallUpdate::new(id.clone())
+ .raw_input(json!(null))
+ .raw_output(json!(null)),
+ cx,
+ )
+ .expect("JSON null remains data in a typed update");
+ let (_, call) = thread.tool_call(&id).expect("tool");
+ assert_eq!(call.raw_input, Some(json!(null)));
+ assert_eq!(call.raw_output, Some(json!(null)));
+
+ thread
+ .update_tool_call(
+ acp_v2::ToolCallUpdate::new(id.clone())
+ .raw_input(None)
+ .raw_output(None),
+ cx,
+ )
+ .expect("explicit clear removes raw fields");
+ let (_, call) = thread.tool_call(&id).expect("tool");
+ assert!(call.raw_input.is_none());
+ assert!(call.raw_output.is_none());
+ });
+ }
+
+ #[gpui::test]
+ async fn test_native_tool_terminal_references_require_client_processes(
+ cx: &mut TestAppContext,
+ ) {
+ init_test(cx);
+ let thread = new_test_thread(cx).await;
+ cx.executor().allow_parking();
+ cx.update(|cx| cx.set_global(::terminal::HeadlessTerminal(true)));
+ let terminal = thread
+ .update(cx, |thread, cx| {
+ thread.create_terminal(
+ "echo native-output".into(),
+ Vec::new(),
+ Vec::new(),
+ None,
+ None,
+ None,
+ cx,
+ )
+ })
+ .await
+ .expect("real client process");
+ let terminal_id = terminal.read_with(cx, |terminal, _| terminal.id().clone());
+ let lower = terminal.read_with(cx, |terminal, _| terminal.inner().clone());
+ let process_exit = terminal.read_with(cx, |terminal, _| {
+ assert!(terminal.is_process_backed());
+ terminal.wait_for_exit().expect("client process exit")
+ });
+ process_exit.await;
+ thread.update(cx, |thread, cx| {
+ assert!(terminal.read(cx).is_process_backed());
+ let inner_meta = acp_v2::Meta::from_iter([("inner".into(), json!({"all": [1, 2]}))]);
+ let item_meta = acp_v2::Meta::from_iter([("item".into(), json!({"keep": true}))]);
+ let source =
+ acp_v2::ContentBlock::Text(acp_v2::TextContent::new("text").meta(inner_meta));
+ let content = vec![
+ acp_v2::ToolCallContent::Content(Box::new(
+ acp_v2::Content::new(source.clone()).meta(item_meta.clone()),
+ )),
+ acp_v2::ToolCallContent::Terminal(
+ acp_v2::Terminal::new(terminal_id.clone()).meta(item_meta.clone()),
+ ),
+ ];
+ let id = acp_v2::ToolCallId::new("native-content");
+ thread
+ .upsert_local_tool_call(
+ acp_v2::ToolCallUpdate::new(id.clone())
+ .title("Native tool")
+ .content(content.clone()),
+ cx,
+ )
+ .expect("native content can reference a completed client process");
+ thread
+ .update_tool_call(acp_v2::ToolCallUpdate::new(id.clone()).content(content), cx)
+ .expect("native content update uses the same conversion");
+ let (_, call) = thread.tool_call(&id).expect("tool");
+ assert_eq!(call.structured_content.len(), 2);
+ let ToolCallContent::ContentBlock { block, meta } =
+ call.structured_content.first().expect("content")
+ else {
+ panic!("expected retained content block");
+ };
+ assert_eq!(block.source.as_ref(), Some(&source));
+ assert_eq!(meta.as_ref(), Some(&item_meta));
+ let ToolCallContent::Terminal {
+ terminal: retained,
+ meta,
+ } = call.structured_content.last().expect("terminal")
+ else {
+ panic!("expected retained terminal");
+ };
+ assert_eq!(retained, &terminal);
+ assert_eq!(meta.as_ref(), Some(&item_meta));
+ assert!(retained.read(cx).is_process_backed());
+ assert_eq!(retained.read(cx).inner(), &lower);
+ assert_eq!(thread.terminals.len(), 1);
+
+ let missing = acp_v2::ToolCallContent::Terminal(acp_v2::Terminal::new("missing"));
+ assert!(
+ thread
+ .upsert_local_tool_call(
+ acp_v2::ToolCallUpdate::new("missing-content")
+ .title("Missing")
+ .content(vec![missing.clone()]),
+ cx,
+ )
+ .is_err()
+ );
+ assert!(thread.tool_call(&"missing-content".into()).is_none());
+ assert!(
+ thread
+ .update_tool_call(
+ acp_v2::ToolCallUpdate::new(id.clone())
+ .title("Must not mutate")
+ .content(vec![missing]),
+ cx,
+ )
+ .is_err()
+ );
+ assert!(thread.terminal(acp_v2::TerminalId::new("missing")).is_err());
+ assert_eq!(thread.terminals.len(), 1);
+ let (_, call) = thread.tool_call(&id).expect("unchanged tool");
+ assert_eq!(call.title.as_deref(), Some("Native tool"));
+ assert_eq!(call.terminals().next(), Some(&terminal));
+
+ thread
+ .upsert_display_terminal(
+ "agent-display".into(),
+ DisplayTerminalPatch::default(),
+ cx,
+ )
+ .expect("existing agent-owned display");
+ let display = acp_v2::ToolCallContent::Terminal(acp_v2::Terminal::new("agent-display"));
+ assert!(
+ thread
+ .upsert_local_tool_call(
+ acp_v2::ToolCallUpdate::new("display-create")
+ .title("Must not create")
+ .content(vec![display.clone()]),
+ cx,
+ )
+ .is_err()
+ );
+ assert!(thread.tool_call(&"display-create".into()).is_none());
+ assert!(
+ thread
+ .update_tool_call(
+ acp_v2::ToolCallUpdate::new(id.clone())
+ .title("Must not mutate")
+ .content(vec![display.clone()]),
+ cx,
+ )
+ .is_err()
+ );
+ assert!(
+ thread
+ .request_tool_call_update_authorization(
+ acp_v2::ToolCallUpdate::new(id.clone())
+ .title("Must not authorize")
+ .content(vec![display]),
+ PermissionOptions::Flat(vec![acp_v2::PermissionOption::new(
+ "allow",
+ "Allow",
+ acp_v2::PermissionOptionKind::AllowOnce,
+ )]),
+ AuthorizationKind::PermissionGrant,
+ cx,
+ )
+ .is_err()
+ );
+ let (_, call) = thread.tool_call(&id).expect("unchanged native tool");
+ assert_eq!(call.title.as_deref(), Some("Native tool"));
+ assert_eq!(call.terminals().next(), Some(&terminal));
+ assert!(call.authorization_id().is_none());
+ assert!(thread.pending_permission_requests().next().is_none());
+ assert_eq!(thread.terminals.len(), 2);
+ });
+ terminal.read_with(cx, |terminal, _| {
+ let output = terminal.output().expect("completed client process");
+ assert!(output.content.contains("native-output"));
+ assert_eq!(output.exit_status.exit_code, Some(0));
+ });
+ }
+
+ #[gpui::test]
+ async fn test_native_permission_replacement_retains_continuation_and_owner(
+ cx: &mut TestAppContext,
+ ) {
+ init_test(cx);
+ let thread = new_test_thread(cx).await;
+ let id = acp_v2::ToolCallId::new("native-permission");
+ thread.update(cx, |thread, cx| {
+ thread
+ .upsert_local_tool_call(
+ acp_v2::ToolCallUpdate::new(id.clone())
+ .title("Native tool")
+ .status(acp_v2::ToolCallStatus::InProgress),
+ cx,
+ )
+ .expect("native tool");
+ });
+ let options = PermissionOptions::Flat(vec![acp_v2::PermissionOption::new(
+ "allow",
+ "Allow",
+ acp_v2::PermissionOptionKind::AllowOnce,
+ )]);
+ let (old_owner, old_response) = thread
+ .update(cx, |thread, cx| {
+ thread.request_tool_call_update_authorization_with_id(
+ acp_v2::ToolCallUpdate::new(id.clone()),
+ options.clone(),
+ AuthorizationKind::PermissionGrant,
+ cx,
+ )
+ })
+ .expect("first request");
+ let (new_owner, response) = thread
+ .update(cx, |thread, cx| {
+ thread.request_tool_call_update_authorization_with_id(
+ acp_v2::ToolCallUpdate::new(id.clone())
+ .status(acp_v2::ToolCallStatus::Completed),
+ options,
+ AuthorizationKind::PermissionGrant,
+ cx,
+ )
+ })
+ .expect("replacement captures underlying progress before descriptive completion");
+ assert_ne!(old_owner, new_owner);
+ assert!(matches!(
+ old_response.await,
+ RequestPermissionOutcome::Cancelled
+ ));
+ thread.update(cx, |thread, cx| {
+ assert!(thread.permission_request(old_owner).is_none());
+ let (_, call) = thread.tool_call(&id).expect("tool");
+ assert_eq!(call.authorization_id(), Some(new_owner));
+ assert_eq!(call.status(), ToolCallStatus::WaitingForConfirmation);
+ assert_eq!(
+ call.reported_status,
+ Some(acp_v2::ToolCallStatus::Completed)
+ );
+ assert_eq!(
+ call.permission_status(),
+ Some(acp_v2::ToolCallStatus::InProgress)
+ );
+ thread.authorize_permission_request(
+ new_owner,
+ SelectedPermissionOutcome::new(
+ "allow".into(),
+ acp_v2::PermissionOptionKind::AllowOnce,
+ ),
+ cx,
+ );
+ let (_, call) = thread.tool_call(&id).expect("tool");
+ assert_eq!(call.status(), ToolCallStatus::InProgress);
+ assert_eq!(
+ call.reported_status,
+ Some(acp_v2::ToolCallStatus::Completed)
+ );
+ assert!(call.authorization_id().is_none());
+ assert!(thread.permission_request(new_owner).is_none());
+ assert!(thread.pending_permission_requests().next().is_none());
+ });
+ assert!(matches!(
+ response.await,
+ RequestPermissionOutcome::Selected(_)
+ ));
+ }
+
+ #[gpui::test]
+ async fn test_native_permission_cancellation_and_reported_completion(cx: &mut TestAppContext) {
+ init_test(cx);
+ let thread = new_test_thread(cx).await;
+ let id = acp_v2::ToolCallId::new("native-permission");
+ let options = PermissionOptions::Flat(vec![acp_v2::PermissionOption::new(
+ "allow",
+ "Allow",
+ acp_v2::PermissionOptionKind::AllowOnce,
+ )]);
+ let (owner, response) = thread
+ .update(cx, |thread, cx| {
+ thread.request_tool_call_update_authorization_with_id(
+ acp_v2::ToolCallUpdate::new(id.clone()),
+ options.clone(),
+ AuthorizationKind::PermissionGrant,
+ cx,
+ )
+ })
+ .expect("ID-only request creates native tool with client fallback defaults");
+ thread.update(cx, |thread, cx| {
+ let (_, call) = thread.tool_call(&id).expect("tool");
+ assert_eq!(call.title, None);
+ assert_eq!(call.reported_kind, None);
+ assert_eq!(call.reported_status, None);
+ assert_eq!(call.kind(), &acp_v2::ToolKind::Other);
+ assert_eq!(
+ call.permission_status(),
+ Some(acp_v2::ToolCallStatus::Pending)
+ );
+ assert_eq!(call.status(), ToolCallStatus::WaitingForConfirmation);
+ thread.cancel_permission_request(owner, cx);
+ });
+ assert!(matches!(
+ response.await,
+ RequestPermissionOutcome::Cancelled
+ ));
+ thread.read_with(cx, |thread, _| {
+ let (_, call) = thread.tool_call(&id).expect("tool");
+ assert_eq!(call.status(), ToolCallStatus::Canceled);
+ assert!(call.authorization_id().is_none());
+ assert!(thread.permission_request(owner).is_none());
+ assert!(thread.pending_permission_requests().next().is_none());
+ });
+ let response = thread
+ .update(cx, |thread, cx| {
+ thread.request_tool_call_update_authorization(
+ acp_v2::ToolCallUpdate::new(id.clone())
+ .status(acp_v2::ToolCallStatus::InProgress),
+ options.clone(),
+ AuthorizationKind::PermissionGrant,
+ cx,
+ )
+ })
+ .expect("local canceled state falls back to the incoming continuation");
+ thread.update(cx, |thread, cx| {
+ assert_eq!(
+ thread.tool_call(&id).expect("tool").1.permission_status(),
+ Some(acp_v2::ToolCallStatus::InProgress)
+ );
+ thread.authorize_tool_call(
+ id.clone(),
+ SelectedPermissionOutcome::new(
+ "allow".into(),
+ acp_v2::PermissionOptionKind::AllowOnce,
+ ),
+ cx,
+ );
+ assert_eq!(
+ thread.tool_call(&id).expect("tool").1.status(),
+ ToolCallStatus::InProgress
+ );
+ });
+ assert!(matches!(
+ response.await,
+ RequestPermissionOutcome::Selected(_)
+ ));
+ let (owner, response) = thread
+ .update(cx, |thread, cx| {
+ thread.request_tool_call_update_authorization_with_id(
+ acp_v2::ToolCallUpdate::new(id.clone()),
+ options,
+ AuthorizationKind::PermissionGrant,
+ cx,
+ )
+ })
+ .expect("request before completion");
+ thread.update(cx, |thread, cx| {
+ thread
+ .update_tool_call(
+ acp_v2::ToolCallUpdate::new(id.clone())
+ .title("Must not mutate")
+ .status(acp_v2::ToolCallStatus::Completed)
+ .content(vec![acp_v2::ToolCallContent::Terminal(
+ acp_v2::Terminal::new("missing"),
+ )]),
+ cx,
+ )
+ .expect_err("missing terminal must not be fabricated");
+ let (_, call) = thread.tool_call(&id).expect("tool");
+ assert_eq!(call.status(), ToolCallStatus::Completed);
+ assert_eq!(
+ call.reported_status,
+ Some(acp_v2::ToolCallStatus::Completed)
+ );
+ assert!(call.title.is_none());
+ assert!(call.structured_content.is_empty());
+ assert!(call.authorization_id().is_none());
+ assert!(thread.permission_request(owner).is_none());
+ assert!(thread.permission_request_for_tool(&id).is_none());
+ assert!(thread.pending_permission_requests().next().is_none());
+ assert!(thread.terminals.is_empty());
+ });
+ assert!(matches!(
+ response.await,
+ RequestPermissionOutcome::Cancelled
+ ));
+ }
+
+ #[gpui::test]
+ async fn test_tool_ids_preserve_identity_across_legacy_and_v2_updates(cx: &mut TestAppContext) {
+ init_test(cx);
+ for value in ["", "tool/ \0 雪 😀"] {
+ let thread = new_test_thread(cx).await;
+ let backing: Arc<str> = value.into();
+ let id = acp_v2::ToolCallId::new(backing.clone());
+ let wire_id = acp_v1::ToolCallId::new(backing.clone());
+ thread.update(cx, |thread, cx| {
+ thread
+ .upsert_tool_call(
+ acp_v1::ToolCall::new(wire_id.clone(), "Legacy tool")
+ .raw_input(json!({"retain": true})),
+ cx,
+ )
+ .expect("legacy tool");
+ let (_, call) = thread.tool_call(&id).expect("canonical tool");
+ assert!(Arc::ptr_eq(&call.id.0, &backing));
+
+ thread
+ .upsert_wire_tool_call(
acp_v2::ToolCallUpdate::new(acp_v2::ToolCallId::new(value))
.title("V2 patch"),
cx,
@@ -13358,7 +13949,7 @@ mod tests {
thread.update(cx, |thread, cx| {
let id = acp_v2::ToolCallId::new("kept");
thread
- .upsert_tool_call_patch(
+ .upsert_wire_tool_call(
acp_v2::ToolCallUpdate::new("kept")
.kind(acp_v2::ToolKind::Execute)
.status(acp_v2::ToolCallStatus::Completed),
@@ -13401,7 +13992,7 @@ mod tests {
"fallback".into(),
ToolCallPatch::legacy(acp_v1::ToolCallUpdateFields::new(), None),
languages,
- &thread.terminals,
+ ToolTerminalResolver::registered(&thread.terminals),
cx,
)
.expect("missing enums use display fallbacks");
@@ -13426,7 +14017,7 @@ mod tests {
thread.update(cx, |thread, cx| {
let id = acp_v2::ToolCallId::new("patch");
thread
- .upsert_tool_call_patch(acp_v2::ToolCallUpdate::new("patch"), cx)
+ .upsert_wire_tool_call(acp_v2::ToolCallUpdate::new("patch"), cx)
.expect("ID-only upsert");
let (_, call) = thread.tool_call(&id).expect("new tool");
assert_eq!(call.reported_kind, None);
@@ -13436,7 +14027,7 @@ mod tests {
assert!(call.content().is_empty());
thread
- .upsert_tool_call_patch(
+ .upsert_wire_tool_call(
serde_json::from_value(json!({
"toolCallId": "patch",
"title": "**Title**",
@@ -13491,7 +14082,7 @@ mod tests {
json!({"toolCallId": "patch", "_meta": {}}),
] {
thread
- .upsert_tool_call_patch(serde_json::from_value(patch).expect("patch"), cx)
+ .upsert_wire_tool_call(serde_json::from_value(patch).expect("patch"), cx)
.expect("metadata-only update");
let (_, call) = thread.tool_call(&id).expect("tool");
assert_eq!(call.label, label);
@@ -13504,14 +14095,14 @@ mod tests {
Some(acp_v2::Meta::new())
);
thread
- .upsert_tool_call_patch(acp_v2::ToolCallUpdate::new("patch").title(" "), cx)
+ .upsert_wire_tool_call(acp_v2::ToolCallUpdate::new("patch").title(" "), cx)
.expect("whitespace title");
let (_, call) = thread.tool_call(&id).expect("tool");
assert_eq!(call.title.as_deref(), Some(" "));
assert_eq!(call.label.read(cx).source(), "named");
thread
- .upsert_tool_call_patch(
+ .upsert_wire_tool_call(
serde_json::from_value(json!({
"toolCallId": "patch",
"title": null, "name": null, "kind": null, "status": null,
@@ -13538,7 +14129,7 @@ mod tests {
assert!(block.source.is_none());
assert_eq!(thread.entries().len(), 1);
thread
- .upsert_tool_call_patch(
+ .upsert_wire_tool_call(
serde_json::from_value(json!({"toolCallId": "patch", "rawOutput": null}))
.expect("raw clear"),
cx,
@@ -13546,7 +14137,7 @@ mod tests {
.expect("clear retained raw output");
assert!(thread.tool_call(&id).expect("tool").1.content().is_empty());
thread
- .upsert_tool_call_patch(
+ .upsert_wire_tool_call(
acp_v2::ToolCallUpdate::new("patch")
.content(vec!["refilled".into()])
.status(acp_v2::ToolCallStatus::Completed),
@@ -13620,7 +14211,7 @@ mod tests {
assert_eq!(second.content().len(), 1);
assert_eq!(second.content()[0].to_markdown(cx), "second");
thread
- .upsert_tool_call_patch(
+ .upsert_wire_tool_call(
acp_v2::ToolCallUpdate::new("first")
.content(vec!["replacement".into()])
.raw_output(json!("raw fallback")),
@@ -13645,10 +14236,7 @@ mod tests {
["replacement", "after replacement"]
);
thread
- .upsert_tool_call_patch(
- acp_v2::ToolCallUpdate::new("first").content(Vec::new()),
- cx,
- )
+ .upsert_wire_tool_call(acp_v2::ToolCallUpdate::new("first").content(Vec::new()), cx)
.expect("clear structured content");
assert_eq!(
thread.tool_call(&first_id).expect("tool").1.content()[0].to_markdown(cx),
@@ -13685,10 +14273,10 @@ mod tests {
.status(acp_v1::ToolCallStatus::Completed)
.meta(tool_meta.clone())
.into(),
- PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(
+ PermissionOptions::Flat(vec![acp_v2::PermissionOption::new(
"allow",
"Allow",
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
)]),
AuthorizationKind::PermissionGrant,
cx,
@@ -13795,7 +14383,7 @@ mod tests {
assert_eq!(call.tool_name.as_deref(), Some("legacy_name"));
assert!(call.subagent_session_info.is_some());
thread
- .upsert_tool_call_patch(
+ .upsert_wire_tool_call(
acp_v2::ToolCallUpdate::new("metadata").meta(acp_v2::Meta::new()),
cx,
)
@@ -13806,7 +14394,7 @@ mod tests {
assert!(call.subagent_session_info.is_none());
assert_eq!(call.label.read(cx).source(), "Tool call");
thread
- .upsert_tool_call_patch(
+ .upsert_wire_tool_call(
acp_v2::ToolCallUpdate::new("metadata")
.name("first_class")
.meta(meta),
@@ -13818,7 +14406,7 @@ mod tests {
Some("first_class")
);
thread
- .upsert_tool_call_patch(
+ .upsert_wire_tool_call(
acp_v2::ToolCallUpdate::new("metadata").meta(None::<acp_v2::Meta>),
cx,
)
@@ -13843,10 +14431,10 @@ mod tests {
thread.request_tool_call_authorization(
acp_v1::ToolCall::new(acp_v1::ToolCallId::new(id.0.clone()), "Authorize")
.into(),
- PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(
+ PermissionOptions::Flat(vec![acp_v2::PermissionOption::new(
"allow",
"Allow",
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
)]),
AuthorizationKind::PermissionGrant,
cx,
@@ -13856,7 +14444,7 @@ mod tests {
thread.update(cx, |thread, cx| {
for status in [json!("_future_status"), serde_json::Value::Null] {
thread
- .upsert_tool_call_patch(
+ .upsert_wire_tool_call(
serde_json::from_value(
json!({"toolCallId": "permission", "status": status}),
)
@@ -13884,7 +14472,7 @@ mod tests {
assert_eq!(call.reported_status, None);
assert_eq!(call.status(), ToolCallStatus::Canceled);
thread
- .upsert_tool_call_patch(
+ .upsert_wire_tool_call(
acp_v2::ToolCallUpdate::new("permission")
.status(None::<acp_v2::ToolCallStatus>),
cx,
@@ -13895,7 +14483,7 @@ mod tests {
ToolCallStatus::Canceled
);
thread
- .upsert_tool_call_patch(
+ .upsert_wire_tool_call(
acp_v2::ToolCallUpdate::new("permission")
.status(acp_v2::ToolCallStatus::InProgress),
cx,
@@ -13918,10 +14506,10 @@ mod tests {
acp_v1::ToolCallId::new(id.0.clone()),
acp_v1::ToolCallUpdateFields::new(),
),
- PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(
+ PermissionOptions::Flat(vec![acp_v2::PermissionOption::new(
"allow",
"Allow",
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
)]),
AuthorizationKind::PermissionGrant,
cx,
@@ -13930,7 +14518,7 @@ mod tests {
.expect("second request");
thread.update(cx, |thread, cx| {
let original_label = thread.tool_call(&id).expect("tool").1.label.clone();
- let result = thread.upsert_tool_call_patch(
+ let result = thread.upsert_wire_tool_call(
serde_json::from_value(json!({
"toolCallId": "permission",
"status": "cancelled",
@@ -14014,9 +14602,9 @@ mod tests {
.expect("initial tool");
});
let option_kind = if kind == AuthorizationKind::ActionChoice {
- acp_v1::PermissionOptionKind::RejectOnce
+ acp_v2::PermissionOptionKind::RejectOnce
} else {
- acp_v1::PermissionOptionKind::AllowOnce
+ acp_v2::PermissionOptionKind::AllowOnce
};
let permission = thread
.update(cx, |thread, cx| {
@@ -14025,10 +14613,10 @@ mod tests {
acp_v1::ToolCallId::new(id.0.clone()),
acp_v1::ToolCallUpdateFields::new().status(incoming),
),
- PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(
+ PermissionOptions::Flat(vec![acp_v2::PermissionOption::new(
"selected",
"Choose",
- option_kind,
+ option_kind.clone(),
)]),
kind,
cx,
@@ -14041,7 +14629,7 @@ mod tests {
let (_, call) = thread.tool_call(&id).expect("waiting tool");
assert_eq!(call.status(), ToolCallStatus::WaitingForConfirmation);
assert_eq!(call.reported_status.as_ref(), Some(&reported));
- assert_eq!(call.permission_status(), Some(initial));
+ assert_eq!(call.permission_status(), tool_status_from_v1(initial));
thread.authorize_tool_call(
id.clone(),
SelectedPermissionOutcome::new("selected".into(), option_kind),
@@ -14058,7 +14646,7 @@ mod tests {
);
thread.update(cx, |thread, cx| {
thread
- .upsert_tool_call_patch(
+ .upsert_wire_tool_call(
acp_v2::ToolCallUpdate::new("continuation")
.status(None::<acp_v2::ToolCallStatus>),
cx,
@@ -14068,7 +14656,7 @@ mod tests {
assert_eq!(call.reported_status, None);
assert_eq!(call.status(), expected);
thread
- .upsert_tool_call_patch(
+ .upsert_wire_tool_call(
acp_v2::ToolCallUpdate::new("continuation").status(reported),
cx,
)
@@ -14188,7 +14776,7 @@ mod tests {
let (_, call) = thread.tool_call(&id).expect("tool");
assert_eq!(call.locations, vec![relative.clone()]);
thread
- .upsert_tool_call_patch(acp_v2::ToolCallUpdate::new("location-migration"), cx)
+ .upsert_wire_tool_call(acp_v2::ToolCallUpdate::new("location-migration"), cx)
.expect("omitted locations");
assert_eq!(
thread.tool_call(&id).expect("tool").1.locations,
@@ -14203,7 +14791,7 @@ mod tests {
};
thread.update(cx, |thread, cx| {
thread
- .upsert_tool_call_patch(
+ .upsert_wire_tool_call(
acp_v2::ToolCallUpdate::new("location-migration").locations(vec![
acp_v2::ToolCallLocation::new(acp_v2::AbsolutePath::new(
absolute.path.clone(),
@@ -14234,14 +14822,14 @@ mod tests {
assert_eq!(location, absolute);
let resolved_locations = call.resolved_locations.clone();
thread
- .upsert_tool_call_patch(acp_v2::ToolCallUpdate::new("location-migration"), cx)
+ .upsert_wire_tool_call(acp_v2::ToolCallUpdate::new("location-migration"), cx)
.expect("omission preserves resolved projections");
assert_eq!(
thread.tool_call(&id).expect("tool").1.resolved_locations,
resolved_locations
);
thread
- .upsert_tool_call_patch(
+ .upsert_wire_tool_call(
acp_v2::ToolCallUpdate::new("location-migration").locations(vec![
acp_v2::ToolCallLocation::new(acp_v2::AbsolutePath::new(
respelled.path.clone(),
@@ -14285,7 +14873,7 @@ mod tests {
cx.run_until_parked();
thread.update(cx, |thread, cx| {
thread
- .upsert_tool_call_patch(
+ .upsert_wire_tool_call(
acp_v2::ToolCallUpdate::new("location-migration")
.locations(None::<Vec<acp_v2::ToolCallLocation>>),
cx,
@@ -14320,7 +14908,7 @@ mod tests {
.expect("session");
let id = acp_v2::ToolCallId::new("locations");
thread.update(cx, |thread, cx| {
- thread.upsert_tool_call_patch(
+ thread.upsert_wire_tool_call(
serde_json::from_value(json!({
"toolCallId": "locations",
"locations": [{"path": path!("/project/file.rs"), "line": 2, "_meta": {"location": true}}]
@@ -14331,7 +14919,7 @@ mod tests {
assert_eq!(call.locations[0].path, PathBuf::from(path!("/project/file.rs")));
assert_eq!(call.locations[0].line, Some(2));
assert_eq!(call.locations[0].meta, Some(acp_v1::Meta::from_iter([("location".into(), json!(true))])));
- thread.upsert_tool_call_patch(
+ thread.upsert_wire_tool_call(
serde_json::from_value(json!({"toolCallId": "locations", "locations": null})).expect("clear locations"),
cx,
).expect("clear before the previous lookup finishes");
@@ -14489,8 +15077,13 @@ mod tests {
),
] {
cx.update(|cx| {
- call.update_fields(update, None, languages.clone(), &HashMap::default(), cx)
- .expect("tool label update should apply");
+ call.apply_patch(
+ ToolCallPatch::legacy(update, None),
+ languages.clone(),
+ ToolTerminalResolver::registered(&HashMap::default()),
+ cx,
+ )
+ .expect("tool label update should apply");
});
cx.run_until_parked();
cx.read(|cx| {
@@ -14537,11 +15130,13 @@ mod tests {
let created_export = cx.read(|cx| created_with_raw_output.to_markdown(cx));
cx.update(|cx| {
updated_with_raw_output
- .update_fields(
- acp_v1::ToolCallUpdateFields::new().raw_output(serde_json::json!("first")),
- None,
+ .apply_patch(
+ ToolCallPatch::legacy(
+ acp_v1::ToolCallUpdateFields::new().raw_output(serde_json::json!("first")),
+ None,
+ ),
languages.clone(),
- &HashMap::default(),
+ ToolTerminalResolver::registered(&HashMap::default()),
cx,
)
.expect("first raw output update should apply");
@@ -14558,20 +15153,24 @@ mod tests {
.clone();
cx.update(|cx| {
created_with_raw_output
- .update_fields(
- acp_v1::ToolCallUpdateFields::new().raw_output(serde_json::json!("second")),
- None,
+ .apply_patch(
+ ToolCallPatch::legacy(
+ acp_v1::ToolCallUpdateFields::new().raw_output(serde_json::json!("second")),
+ None,
+ ),
languages.clone(),
- &HashMap::default(),
+ ToolTerminalResolver::registered(&HashMap::default()),
cx,
)
.expect("second raw output update should apply");
updated_with_raw_output
- .update_fields(
- acp_v1::ToolCallUpdateFields::new().raw_output(serde_json::json!("second")),
- None,
+ .apply_patch(
+ ToolCallPatch::legacy(
+ acp_v1::ToolCallUpdateFields::new().raw_output(serde_json::json!("second")),
+ None,
+ ),
languages.clone(),
- &HashMap::default(),
+ ToolTerminalResolver::registered(&HashMap::default()),
cx,
)
.expect("second raw output update should apply");
@@ -14622,11 +15221,13 @@ mod tests {
);
});
cx.update(|cx| {
- call.update_fields(
- acp_v1::ToolCallUpdateFields::new().raw_output(serde_json::json!("new raw")),
- None,
+ call.apply_patch(
+ ToolCallPatch::legacy(
+ acp_v1::ToolCallUpdateFields::new().raw_output(serde_json::json!("new raw")),
+ None,
+ ),
languages.clone(),
- &HashMap::default(),
+ ToolTerminalResolver::registered(&HashMap::default()),
cx,
)
.expect("raw output should update without replacing structured content");
@@ -14636,11 +15237,10 @@ mod tests {
);
});
cx.update(|cx| {
- call.update_fields(
- acp_v1::ToolCallUpdateFields::new().content(vec![]),
- None,
+ call.apply_patch(
+ ToolCallPatch::legacy(acp_v1::ToolCallUpdateFields::new().content(vec![]), None),
languages.clone(),
- &HashMap::default(),
+ ToolTerminalResolver::registered(&HashMap::default()),
cx,
)
.expect("clearing structured content should apply");
@@ -14653,11 +15253,13 @@ mod tests {
);
});
cx.update(|cx| {
- call.update_fields(
- acp_v1::ToolCallUpdateFields::new().content(vec!["replacement".into()]),
- None,
+ call.apply_patch(
+ ToolCallPatch::legacy(
+ acp_v1::ToolCallUpdateFields::new().content(vec!["replacement".into()]),
+ None,
+ ),
languages,
- &HashMap::default(),
+ ToolTerminalResolver::registered(&HashMap::default()),
cx,
)
.expect("structured content should replace the raw fallback");
@@ -14925,13 +15527,15 @@ mod tests {
let diff = diff.clone();
let input = call.raw_input_markdown.clone().expect("input");
for text in ["input", "input appended", "replacement", ""] {
- call.update_fields(
- acp_v1::ToolCallUpdateFields::new()
- .content(content.clone())
- .raw_input(json!(text)),
- None,
+ call.apply_patch(
+ ToolCallPatch::legacy(
+ acp_v1::ToolCallUpdateFields::new()
+ .content(content.clone())
+ .raw_input(json!(text)),
+ None,
+ ),
languages.clone(),
- &terminals,
+ ToolTerminalResolver::registered(&terminals),
cx,
)
.expect("update snapshots");
@@ -14943,16 +15547,18 @@ mod tests {
};
assert_eq!(block.markdown(), Some(&output));
}
- call.update_fields(
- acp_v1::ToolCallUpdateFields::new().content(vec![
- "output".into(),
- acp_v1::ToolCallContent::Diff(
- acp_v1::Diff::new("second.rs", "new text").old_text("old text"),
- ),
- ]),
- None,
+ call.apply_patch(
+ ToolCallPatch::legacy(
+ acp_v1::ToolCallUpdateFields::new().content(vec![
+ "output".into(),
+ acp_v1::ToolCallContent::Diff(
+ acp_v1::Diff::new("second.rs", "new text").old_text("old text"),
+ ),
+ ]),
+ None,
+ ),
languages.clone(),
- &terminals,
+ ToolTerminalResolver::registered(&terminals),
cx,
)
.expect("same diff text at another path");
@@ -14961,13 +15567,15 @@ mod tests {
assert_eq!(changed.read(cx).file_path(cx).as_deref(), Some("second.rs"));
assert_eq!(diff.read(cx).file_path(cx).as_deref(), Some("first.rs"));
- call.update_fields(
- acp_v1::ToolCallUpdateFields::new()
- .content(Vec::new())
- .raw_input(serde_json::Value::Null),
- None,
+ call.apply_patch(
+ ToolCallPatch::legacy(
+ acp_v1::ToolCallUpdateFields::new()
+ .content(Vec::new())
+ .raw_input(serde_json::Value::Null),
+ None,
+ ),
languages.clone(),
- &terminals,
+ ToolTerminalResolver::registered(&terminals),
cx,
)
.expect("clear structured content and render a typed null input");
@@ -14976,14 +15584,16 @@ mod tests {
assert_eq!(call.content().len(), 1);
assert_eq!(call.content()[0].to_markdown(cx), "raw fallback");
assert!(
- call.update_fields(
- acp_v1::ToolCallUpdateFields::new().content(vec![
- "partial output".into(),
- acp_v1::ToolCallContent::Terminal(acp_v1::Terminal::new("missing")),
- ]),
- None,
+ call.apply_patch(
+ ToolCallPatch::legacy(
+ acp_v1::ToolCallUpdateFields::new().content(vec![
+ "partial output".into(),
+ acp_v1::ToolCallContent::Terminal(acp_v1::Terminal::new("missing")),
+ ]),
+ None,
+ ),
languages,
- &terminals,
+ ToolTerminalResolver::registered(&terminals),
cx,
)
.is_err()
@@ -15036,7 +15646,9 @@ mod tests {
thread
.upsert_tool_call(initial, cx)
.expect("retry after terminal arrives");
- let terminal = thread.terminal(terminal_id.clone()).expect("terminal");
+ let terminal = thread
+ .terminal(acp_v2::TerminalId::new(terminal_id.0.clone()))
+ .expect("terminal");
let command = terminal.read(cx).command().clone();
let (_, call) = thread.tool_call(&id).expect("tool");
assert_eq!(call.terminals().next(), Some(&terminal));
@@ -15113,10 +15725,10 @@ mod tests {
.raw_input(json!({"original": true}))
.raw_output(json!("original raw"))
.into(),
- PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(
+ PermissionOptions::Flat(vec![acp_v2::PermissionOption::new(
"allow",
"Allow",
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
)]),
AuthorizationKind::PermissionGrant,
cx,
@@ -15159,7 +15771,7 @@ mod tests {
};
assert!(result.is_err(), "unknown terminal must fail conversion");
let (_, call) = thread.tool_call(&id).expect("tool must remain");
- assert_eq!(call.permission_status(), Some(status));
+ assert_eq!(call.permission_status(), tool_status_from_v1(status));
assert_eq!(call.label, label);
assert_eq!(call.label.read(cx).source(), "Original title");
assert_eq!(call.kind(), &acp_v2::ToolKind::Read);
@@ -15183,7 +15795,7 @@ mod tests {
id.clone(),
SelectedPermissionOutcome::new(
"allow".into(),
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
),
cx,
);
@@ -15242,7 +15854,7 @@ mod tests {
.unwrap();
let tool_call_id = acp_v2::ToolCallId::new("toolu_01duplicate");
- let allow_option_id = acp_v1::PermissionOptionId::new("allow");
+ let allow_option_id = acp_v2::PermissionOptionId::new("allow");
let permission_task = thread
.update(cx, |thread, cx| {
thread.request_tool_call_authorization(
@@ -15254,10 +15866,10 @@ mod tests {
.status(acp_v1::ToolCallStatus::Pending)
.content(vec!["original content".into()])
.into(),
- PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(
+ PermissionOptions::Flat(vec![acp_v2::PermissionOption::new(
allow_option_id.clone(),
"Allow",
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
)]),
AuthorizationKind::PermissionGrant,
cx,
@@ -15325,7 +15937,7 @@ mod tests {
let selected_outcome = SelectedPermissionOutcome::new(
allow_option_id.clone(),
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
);
thread.update(cx, |thread, cx| {
thread.authorize_tool_call(tool_call_id.clone(), selected_outcome, cx);
@@ -15341,7 +15953,7 @@ mod tests {
match permission_task.await {
RequestPermissionOutcome::Selected(outcome) => {
assert_eq!(outcome.option_id, allow_option_id);
- assert_eq!(outcome.option_kind, acp_v1::PermissionOptionKind::AllowOnce);
+ assert_eq!(outcome.option_kind, acp_v2::PermissionOptionKind::AllowOnce);
}
RequestPermissionOutcome::Cancelled
| RequestPermissionOutcome::InterruptedByFollowUp => {
@@ -15400,10 +16012,10 @@ mod tests {
.kind(acp_v1::ToolKind::Execute)
.status(acp_v1::ToolCallStatus::Pending)
.into(),
- PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(
- acp_v1::PermissionOptionId::new("allow"),
+ PermissionOptions::Flat(vec![acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new("allow"),
"Allow",
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
)]),
AuthorizationKind::PermissionGrant,
cx,
@@ -15431,7 +16043,7 @@ mod tests {
assert_eq!(tool_call.status(), ToolCallStatus::WaitingForConfirmation);
assert_eq!(
tool_call.permission_status(),
- Some(acp_v1::ToolCallStatus::InProgress)
+ Some(acp_v2::ToolCallStatus::InProgress)
);
});
@@ -15439,8 +16051,8 @@ mod tests {
thread.authorize_tool_call(
tool_call_id.clone(),
SelectedPermissionOutcome::new(
- acp_v1::PermissionOptionId::new("allow"),
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionId::new("allow"),
+ acp_v2::PermissionOptionKind::AllowOnce,
),
cx,
);
@@ -15455,8 +16067,8 @@ mod tests {
match permission_task.await {
RequestPermissionOutcome::Selected(outcome) => {
- assert_eq!(outcome.option_id, acp_v1::PermissionOptionId::new("allow"));
- assert_eq!(outcome.option_kind, acp_v1::PermissionOptionKind::AllowOnce);
+ assert_eq!(outcome.option_id, acp_v2::PermissionOptionId::new("allow"));
+ assert_eq!(outcome.option_kind, acp_v2::PermissionOptionKind::AllowOnce);
}
RequestPermissionOutcome::Cancelled
| RequestPermissionOutcome::InterruptedByFollowUp => {
@@ -15508,10 +16120,10 @@ mod tests {
.kind(acp_v1::ToolKind::Execute)
.status(acp_v1::ToolCallStatus::Pending)
.into(),
- PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(
- acp_v1::PermissionOptionId::new("allow"),
+ PermissionOptions::Flat(vec![acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new("allow"),
"Allow",
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
)]),
AuthorizationKind::PermissionGrant,
cx,
@@ -15527,7 +16139,7 @@ mod tests {
assert_eq!(tool_call.status(), ToolCallStatus::WaitingForConfirmation);
assert_eq!(
tool_call.permission_status(),
- Some(acp_v1::ToolCallStatus::InProgress)
+ Some(acp_v2::ToolCallStatus::InProgress)
);
});
@@ -15535,8 +16147,8 @@ mod tests {
thread.authorize_tool_call(
tool_call_id.clone(),
SelectedPermissionOutcome::new(
- acp_v1::PermissionOptionId::new("allow"),
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionId::new("allow"),
+ acp_v2::PermissionOptionKind::AllowOnce,
),
cx,
);
@@ -15544,8 +16156,8 @@ mod tests {
match permission_task.await {
RequestPermissionOutcome::Selected(outcome) => {
- assert_eq!(outcome.option_id, acp_v1::PermissionOptionId::new("allow"));
- assert_eq!(outcome.option_kind, acp_v1::PermissionOptionKind::AllowOnce);
+ assert_eq!(outcome.option_id, acp_v2::PermissionOptionId::new("allow"));
+ assert_eq!(outcome.option_kind, acp_v2::PermissionOptionKind::AllowOnce);
}
RequestPermissionOutcome::Cancelled
| RequestPermissionOutcome::InterruptedByFollowUp => {
@@ -15581,10 +16193,10 @@ mod tests {
.kind(acp_v1::ToolKind::Execute)
.status(acp_v1::ToolCallStatus::Pending)
.into(),
- PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(
- acp_v1::PermissionOptionId::new("allow"),
+ PermissionOptions::Flat(vec![acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new("allow"),
"Allow",
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
)]),
AuthorizationKind::PermissionGrant,
cx,
@@ -15639,10 +16251,10 @@ mod tests {
.kind(acp_v1::ToolKind::Execute)
.status(acp_v1::ToolCallStatus::Pending)
.into(),
- PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(
- acp_v1::PermissionOptionId::new("allow"),
+ PermissionOptions::Flat(vec![acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new("allow"),
"Allow",
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
)]),
AuthorizationKind::PermissionGrant,
cx,
@@ -18346,6 +18958,9 @@ mod tests {
.unwrap();
});
+ let terminal_id = acp_v2::TerminalId::new(terminal_id.0);
+ let terminal_id_1 = acp_v2::TerminalId::new(terminal_id_1.0);
+ let terminal_id_2 = acp_v2::TerminalId::new(terminal_id_2.0);
// Verify terminal exists and is in the thread
let terminal_exists_before =
thread.read_with(cx, |thread, _| thread.terminals.contains_key(&terminal_id));
@@ -20194,8 +20809,8 @@ mod tests {
thread.authorize_tool_call(
second_id,
SelectedPermissionOutcome::new(
- acp_v1::PermissionOptionId::new("reject"),
- acp_v1::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionId::new("reject"),
+ acp_v2::PermissionOptionKind::RejectOnce,
),
cx,
);
@@ -20203,7 +20818,7 @@ mod tests {
assert!(matches!(
second_permission.await,
RequestPermissionOutcome::Selected(outcome)
- if outcome.option_kind == acp_v1::PermissionOptionKind::RejectOnce
+ if outcome.option_kind == acp_v2::PermissionOptionKind::RejectOnce
));
cx.run_until_parked();
assert_eq!(cx.active_idle_sleep_preventions(), 0);
@@ -20227,8 +20842,8 @@ mod tests {
thread.authorize_tool_call(
first_id,
SelectedPermissionOutcome::new(
- acp_v1::PermissionOptionId::new("allow"),
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionId::new("allow"),
+ acp_v2::PermissionOptionKind::AllowOnce,
),
cx,
);
@@ -20236,7 +20851,7 @@ mod tests {
assert!(matches!(
first_permission.await,
RequestPermissionOutcome::Selected(outcome)
- if outcome.option_kind == acp_v1::PermissionOptionKind::AllowOnce
+ if outcome.option_kind == acp_v2::PermissionOptionKind::AllowOnce
));
cx.run_until_parked();
assert!(!thread.read_with(cx, |thread, _| thread.is_waiting_for_confirmation()));
@@ -20325,8 +20940,8 @@ mod tests {
thread.authorize_tool_call(
tool_call_id,
SelectedPermissionOutcome::new(
- acp_v1::PermissionOptionId::new("allow"),
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionId::new("allow"),
+ acp_v2::PermissionOptionKind::AllowOnce,
),
cx,
);
@@ -20550,8 +21165,8 @@ mod tests {
thread.authorize_tool_call(
tool_call_id,
SelectedPermissionOutcome::new(
- acp_v1::PermissionOptionId::new("allow"),
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionId::new("allow"),
+ acp_v2::PermissionOptionKind::AllowOnce,
),
cx,
);
@@ -20822,7 +21437,7 @@ mod tests {
let (index, first) = thread.tool_call(&first_id).expect("first tool");
let original_label = first.label.clone();
thread
- .upsert_tool_call_patch(
+ .upsert_wire_tool_call(
acp_v2::ToolCallUpdate::new("first")
.status(status.clone())
.title("Terminal result")
@@ -20839,7 +21454,7 @@ mod tests {
assert_eq!(first.label, original_label);
assert_eq!(first.label.read(cx).source(), "Terminal result");
let terminal = first.terminals().next().expect("terminal placeholder");
- assert_eq!(terminal.read(cx).id(), &acp_v1::TerminalId::new("unseen"));
+ assert_eq!(terminal.read(cx).id(), &acp_v2::TerminalId::new("unseen"));
assert!(!terminal.read(cx).is_process_backed());
assert!(
thread
@@ -20903,10 +21518,10 @@ mod tests {
acp_v1::Terminal::new("missing"),
)]),
),
- PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(
+ PermissionOptions::Flat(vec![acp_v2::PermissionOption::new(
"new-choice",
"New choice",
- acp_v1::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionKind::RejectOnce,
)]),
AuthorizationKind::ActionChoice,
cx,
@@ -21075,7 +21690,7 @@ mod tests {
first_id,
SelectedPermissionOutcome::new(
"allow".into(),
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
),
cx,
);
@@ -21147,7 +21762,7 @@ mod tests {
old_id,
SelectedPermissionOutcome::new(
"reject".into(),
- acp_v1::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionKind::RejectOnce,
),
cx,
);
@@ -21216,7 +21831,7 @@ mod tests {
new_id,
SelectedPermissionOutcome::new(
"allow".into(),
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
),
cx,
);
@@ -21225,7 +21840,7 @@ mod tests {
new_response.await,
RequestPermissionOutcome::Selected(outcome)
if outcome.option_id == "allow".into()
- && outcome.option_kind == acp_v1::PermissionOptionKind::AllowOnce
+ && outcome.option_kind == acp_v2::PermissionOptionKind::AllowOnce
));
thread.read_with(cx, |thread, _| {
assert!(thread.permission_request(new_id).is_none());
@@ -21254,34 +21869,34 @@ mod tests {
(
AuthorizationKind::PermissionGrant,
"allow",
- acp_v1::PermissionOptionKind::AllowOnce,
- acp_v1::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::RejectOnce,
ToolCallStatus::InProgress,
),
(
AuthorizationKind::PermissionGrant,
"reject",
- acp_v1::PermissionOptionKind::RejectOnce,
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
ToolCallStatus::Rejected,
),
(
AuthorizationKind::ActionChoice,
"reject",
- acp_v1::PermissionOptionKind::RejectOnce,
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
ToolCallStatus::InProgress,
),
] {
- let allow = acp_v1::PermissionOption::new(
+ let allow = acp_v2::PermissionOption::new(
"allow",
"Allow",
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
);
- let reject = acp_v1::PermissionOption::new(
+ let reject = acp_v2::PermissionOption::new(
"reject",
"Reject",
- acp_v1::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionKind::RejectOnce,
);
let choice = PermissionOptionChoice {
allow: allow.clone(),
@@ -21308,7 +21923,7 @@ mod tests {
] {
let (mut selected_outcome, expected_patterns) = match &options {
PermissionOptions::Flat(_) => (
- SelectedPermissionOutcome::new(option_id.into(), offered_kind),
+ SelectedPermissionOutcome::new(option_id.into(), offered_kind.clone()),
None,
),
PermissionOptions::Dropdown(choices) => (
@@ -21325,7 +21940,7 @@ mod tests {
Some(vec!["^git status$".to_owned()]),
),
};
- selected_outcome.option_kind = spoofed_kind;
+ selected_outcome.option_kind = spoofed_kind.clone();
let thread = new_test_thread(cx).await;
let (events, _subscription) = track_permission_events(&thread, cx);
let tool_id = acp_v2::ToolCallId::new("choice");
@@ -21346,7 +21961,7 @@ mod tests {
thread.update(cx, |thread, cx| {
thread.authorize_permission_request(
request_id,
- SelectedPermissionOutcome::new("not-offered".into(), spoofed_kind),
+ SelectedPermissionOutcome::new("not-offered".into(), spoofed_kind.clone()),
cx,
);
let request = thread
@@ -21386,6 +22001,63 @@ mod tests {
}
}
+ #[gpui::test]
+ async fn test_unknown_permission_kind_keeps_authorization_pending(cx: &mut TestAppContext) {
+ init_test(cx);
+ let thread = new_test_thread(cx).await;
+ let tool_call_id = acp_v2::ToolCallId::new("unknown-permission-kind");
+ let option_id = acp_v2::PermissionOptionId::new("future-choice");
+ let option_kind = acp_v2::PermissionOptionKind::Other("_future_choice".into());
+ let (request_id, mut response) = thread.update(cx, |thread, cx| {
+ thread
+ .request_tool_call_authorization_with_id(
+ acp_v1::ToolCall::new(
+ acp_v1::ToolCallId::new(tool_call_id.0.clone()),
+ "Choose",
+ )
+ .into(),
+ PermissionOptions::Flat(vec![acp_v2::PermissionOption::new(
+ option_id.clone(),
+ "Future choice",
+ option_kind.clone(),
+ )]),
+ AuthorizationKind::PermissionGrant,
+ cx,
+ )
+ .expect("permission request")
+ });
+ thread.update(cx, |thread, cx| {
+ thread.authorize_permission_request(
+ request_id,
+ SelectedPermissionOutcome::new(
+ option_id.clone(),
+ acp_v2::PermissionOptionKind::AllowOnce,
+ ),
+ cx,
+ );
+ let request = thread
+ .permission_request(request_id)
+ .expect("unknown choice stays pending");
+ let option = request
+ .legacy_options()
+ .and_then(|options| options.option_for_id(&option_id))
+ .expect("offered option");
+ assert_eq!(option.kind, option_kind);
+ assert!(Arc::ptr_eq(&option.option_id.0, &option_id.0));
+ let (_, call) = thread.tool_call(&tool_call_id).expect("waiting tool");
+ assert_eq!(call.authorization_id(), Some(request_id));
+ assert_eq!(call.status(), ToolCallStatus::WaitingForConfirmation);
+ });
+ assert!((&mut response).now_or_never().is_none());
+ thread.update(cx, |thread, cx| {
+ thread.cancel_permission_request(request_id, cx);
+ });
+ assert!(matches!(
+ response.await,
+ RequestPermissionOutcome::Cancelled
+ ));
+ }
+
#[gpui::test]
async fn test_entry_removal_cleans_permission_records_without_reusing_identity(
cx: &mut TestAppContext,
@@ -21452,7 +22124,7 @@ mod tests {
removed_id,
SelectedPermissionOutcome::new(
"reject".into(),
- acp_v1::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionKind::RejectOnce,
),
cx,
);
@@ -21739,7 +22411,7 @@ mod tests {
tool_id.clone(),
SelectedPermissionOutcome::new(
"allow".into(),
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
),
cx,
);
@@ -22218,15 +22890,15 @@ mod tests {
)
.into(),
PermissionOptions::Flat(vec![
- acp_v1::PermissionOption::new(
- acp_v1::PermissionOptionId::new("allow"),
+ acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new("allow"),
"Allow",
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
),
- acp_v1::PermissionOption::new(
- acp_v1::PermissionOptionId::new("reject"),
+ acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new("reject"),
"Reject",
- acp_v1::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionKind::RejectOnce,
),
]),
AuthorizationKind::PermissionGrant,
@@ -22418,7 +23090,7 @@ mod tests {
.expect("tool call should remain present")
.1
.permission_status(),
- Some(acp_v1::ToolCallStatus::Completed)
+ Some(acp_v2::ToolCallStatus::Completed)
);
assert!(!thread.is_waiting_for_confirmation());
assert!(thread.permission_request(permission_id).is_none());
diff --git a/crates/acp_thread/src/connection.rs b/crates/acp_thread/src/connection.rs
index ddd2ad02ef5..c799611b99e 100644
--- a/crates/acp_thread/src/connection.rs
+++ b/crates/acp_thread/src/connection.rs
@@ -614,8 +614,8 @@ impl AgentModelList {
#[derive(Debug, Clone)]
pub struct PermissionOptionChoice {
- pub allow: acp_v1::PermissionOption,
- pub deny: acp_v1::PermissionOption,
+ pub allow: acp_v2::PermissionOption,
+ pub deny: acp_v2::PermissionOption,
pub sub_patterns: Vec<String>,
}
@@ -639,7 +639,8 @@ impl PermissionOptionChoice {
None
};
- crate::SelectedPermissionOutcome::new(option.option_id.clone(), option.kind).params(params)
+ crate::SelectedPermissionOutcome::new(option.option_id.clone(), option.kind.clone())
+ .params(params)
}
}
@@ -656,7 +657,7 @@ pub struct PermissionPattern {
#[derive(Debug, Clone)]
pub enum PermissionOptions {
- Flat(Vec<acp_v1::PermissionOption>),
+ Flat(Vec<acp_v2::PermissionOption>),
Dropdown(Vec<PermissionOptionChoice>),
DropdownWithPatterns {
choices: Vec<PermissionOptionChoice>,
@@ -676,8 +677,8 @@ impl PermissionOptions {
pub fn option_for_id(
&self,
- id: &acp_v1::PermissionOptionId,
- ) -> Option<&acp_v1::PermissionOption> {
+ id: &acp_v2::PermissionOptionId,
+ ) -> Option<&acp_v2::PermissionOption> {
match self {
Self::Flat(options) => options.iter().find(|option| &option.option_id == id),
Self::Dropdown(choices) | Self::DropdownWithPatterns { choices, .. } => {
@@ -696,8 +697,8 @@ impl PermissionOptions {
pub fn first_option_of_kind(
&self,
- kind: acp_v1::PermissionOptionKind,
- ) -> Option<&acp_v1::PermissionOption> {
+ kind: acp_v2::PermissionOptionKind,
+ ) -> Option<&acp_v2::PermissionOption> {
match self {
PermissionOptions::Flat(options) => options.iter().find(|option| option.kind == kind),
PermissionOptions::Dropdown(options) => options.iter().find_map(|choice| {
@@ -723,13 +724,13 @@ impl PermissionOptions {
}
}
- pub fn allow_once_option_id(&self) -> Option<acp_v1::PermissionOptionId> {
- self.first_option_of_kind(acp_v1::PermissionOptionKind::AllowOnce)
+ pub fn allow_once_option_id(&self) -> Option<acp_v2::PermissionOptionId> {
+ self.first_option_of_kind(acp_v2::PermissionOptionKind::AllowOnce)
.map(|option| option.option_id.clone())
}
- pub fn deny_once_option_id(&self) -> Option<acp_v1::PermissionOptionId> {
- self.first_option_of_kind(acp_v1::PermissionOptionKind::RejectOnce)
+ pub fn deny_once_option_id(&self) -> Option<acp_v2::PermissionOptionId> {
+ self.first_option_of_kind(acp_v2::PermissionOptionKind::RejectOnce)
.map(|option| option.option_id.clone())
}
@@ -777,10 +778,11 @@ impl PermissionOptions {
&always_choice.deny
};
- let outcome = crate::SelectedPermissionOutcome::new(option.option_id.clone(), option.kind)
- .params(Some(crate::SelectedPermissionParams::Terminal {
- patterns: checked_patterns,
- }));
+ let outcome =
+ crate::SelectedPermissionOutcome::new(option.option_id.clone(), option.kind.clone())
+ .params(Some(crate::SelectedPermissionParams::Terminal {
+ patterns: checked_patterns,
+ }));
Some(outcome)
}
}
diff --git a/crates/acp_thread/src/terminal.rs b/crates/acp_thread/src/terminal.rs
index 781b0f0cfde..9c10ebc9392 100644
--- a/crates/acp_thread/src/terminal.rs
+++ b/crates/acp_thread/src/terminal.rs
@@ -400,7 +400,7 @@ pub(crate) async fn prepare_sandbox_wrap(
}
pub struct Terminal {
- id: acp_v1::TerminalId,
+ id: acp_v2::TerminalId,
command: Entity<Markdown>,
working_dir: Option<PathBuf>,
terminal: Entity<terminal::Terminal>,
@@ -478,7 +478,7 @@ pub struct TerminalOutput {
impl Terminal {
pub fn new(
- id: acp_v1::TerminalId,
+ id: acp_v2::TerminalId,
command_label: &str,
working_dir: Option<PathBuf>,
output_byte_limit: Option<usize>,
@@ -555,7 +555,7 @@ impl Terminal {
}
pub fn new_display(
- id: acp_v1::TerminalId,
+ id: acp_v2::TerminalId,
command_label: Option<&str>,
working_dir: Option<PathBuf>,
output_byte_limit: Option<usize>,
@@ -589,7 +589,7 @@ impl Terminal {
}
}
- pub fn id(&self) -> &acp_v1::TerminalId {
+ pub fn id(&self) -> &acp_v2::TerminalId {
&self.id
}
diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rs
index 2deba3ad5d0..29f8f5fda33 100644
--- a/crates/agent/src/agent.rs
+++ b/crates/agent/src/agent.rs
@@ -2348,7 +2348,7 @@ impl NativeAgentConnection {
kind,
}) => {
let outcome_task = acp_thread.update(cx, |thread, cx| {
- thread.request_tool_call_authorization(
+ thread.request_tool_call_update_authorization(
tool_call, options, kind, cx,
)
})??;
@@ -2357,10 +2357,10 @@ impl NativeAgentConnection {
acp_thread::RequestPermissionOutcome::Selected(outcome) => outcome,
acp_thread::RequestPermissionOutcome::InterruptedByFollowUp => {
acp_thread::SelectedPermissionOutcome::new(
- acp_v1::PermissionOptionId::new(
+ acp_v2::PermissionOptionId::new(
FOLLOW_UP_PERMISSION_DENIED_OPTION_ID,
),
- acp_v1::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionKind::RejectOnce,
)
}
acp_thread::RequestPermissionOutcome::Cancelled => return,
@@ -2423,11 +2423,6 @@ impl NativeAgentConnection {
}
}
}
- ThreadEvent::ToolCall(tool_call) => {
- acp_thread.update(cx, |thread, cx| {
- thread.upsert_tool_call(tool_call, cx)
- })??;
- }
ThreadEvent::ToolCallUpdate(update) => {
acp_thread.update(cx, |thread, cx| {
thread.update_tool_call(update, cx)
@@ -2466,7 +2461,7 @@ impl NativeAgentConnection {
}
ThreadEvent::Stop(stop_reason) => {
log::debug!("Assistant message complete: {:?}", stop_reason);
- return Ok(acp_v1::PromptResponse::new(stop_reason));
+ return legacy_native_completion(stop_reason);
}
}
}
@@ -2483,6 +2478,20 @@ impl NativeAgentConnection {
}
}
+fn legacy_native_completion(stop_reason: acp_v2::StopReason) -> Result<acp_v1::PromptResponse> {
+ // Native events are version-neutral, but the completion-based connection API
+ // still returns a v1 response. This is not a v2 acceptance receipt.
+ let stop_reason = match stop_reason {
+ acp_v2::StopReason::EndTurn => acp_v1::StopReason::EndTurn,
+ acp_v2::StopReason::MaxTokens => acp_v1::StopReason::MaxTokens,
+ acp_v2::StopReason::MaxTurnRequests => acp_v1::StopReason::MaxTurnRequests,
+ acp_v2::StopReason::Refusal => acp_v1::StopReason::Refusal,
+ acp_v2::StopReason::Cancelled => acp_v1::StopReason::Cancelled,
+ _ => anyhow::bail!("Native agent returned an unsupported stop reason"),
+ };
+ Ok(acp_v1::PromptResponse::new(stop_reason))
+}
+
struct Command<'a> {
prompt_name: &'a str,
arg_value: &'a str,
@@ -3695,7 +3704,7 @@ pub struct AcpTerminalHandle {
}
impl TerminalHandle for AcpTerminalHandle {
- fn id(&self, cx: &AsyncApp) -> Result<acp_v1::TerminalId> {
+ fn id(&self, cx: &AsyncApp) -> Result<acp_v2::TerminalId> {
Ok(self.terminal.read_with(cx, |term, _cx| term.id().clone()))
}
@@ -3977,6 +3986,27 @@ mod internal_tests {
use settings::{LanguageModelProviderSetting, SettingsStore};
use util::{path, rel_path::rel_path};
+ #[test]
+ fn native_stop_reasons_preserve_legacy_completions() -> Result<()> {
+ for (native, legacy) in [
+ (acp_v2::StopReason::EndTurn, acp_v1::StopReason::EndTurn),
+ (acp_v2::StopReason::MaxTokens, acp_v1::StopReason::MaxTokens),
+ (
+ acp_v2::StopReason::MaxTurnRequests,
+ acp_v1::StopReason::MaxTurnRequests,
+ ),
+ (acp_v2::StopReason::Refusal, acp_v1::StopReason::Refusal),
+ (acp_v2::StopReason::Cancelled, acp_v1::StopReason::Cancelled),
+ ] {
+ assert_eq!(legacy_native_completion(native)?.stop_reason, legacy);
+ }
+ assert!(
+ legacy_native_completion(acp_v2::StopReason::Other("_future".into())).is_err(),
+ "an unsupported reason must not masquerade as successful completion"
+ );
+ Ok(())
+ }
+
#[gpui::test]
fn test_available_native_agent_hides_hidden_providers(cx: &mut TestAppContext) {
init_test(cx);
@@ -4119,18 +4149,19 @@ mod internal_tests {
authorization
.response
.send(acp_thread::SelectedPermissionOutcome::new(
- acp_v1::PermissionOptionId::new("allow"),
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionId::new("allow"),
+ acp_v2::PermissionOptionKind::AllowOnce,
))
.expect("authorization response should send");
let update = receiver.expect_update_fields().await;
let terminal_id = update
.content
- .iter()
+ .value()
+ .into_iter()
.flatten()
.find_map(|content| match content {
- acp_v1::ToolCallContent::Terminal(terminal) => Some(terminal.terminal_id.clone()),
+ acp_v2::ToolCallContent::Terminal(terminal) => Some(terminal.terminal_id.clone()),
_ => None,
})
.expect("terminal tool should announce its real terminal");
diff --git a/crates/agent/src/tests/mod.rs b/crates/agent/src/tests/mod.rs
index c23b8edaf8b..9fe0e172b86 100644
--- a/crates/agent/src/tests/mod.rs
+++ b/crates/agent/src/tests/mod.rs
@@ -3,6 +3,7 @@ use acp_thread::{
AgentConnection, AgentModelGroupName, AgentModelId, AgentModelList, AgentThreadEntry,
ClientUserMessageId, PermissionOptions, ThreadStatus,
};
+use agent_client_protocol::schema::MaybeUndefined;
use agent_client_protocol::schema::v1 as acp;
use agent_client_protocol::schema::v2 as acp_v2;
use agent_settings::{AgentProfileId, AgentSettings, AutoCompactThreshold, COMPACTION_PROMPT};
@@ -77,7 +78,7 @@ pub(crate) struct FakeTerminalHandle {
exit_sender: std::cell::RefCell<Option<futures::channel::oneshot::Sender<()>>>,
wait_for_exit: Shared<Task<acp::TerminalExitStatus>>,
output: acp::TerminalOutputResponse,
- id: acp::TerminalId,
+ id: acp_v2::TerminalId,
}
impl FakeTerminalHandle {
@@ -101,7 +102,7 @@ impl FakeTerminalHandle {
exit_sender: std::cell::RefCell::new(Some(exit_sender)),
wait_for_exit,
output: acp::TerminalOutputResponse::new("partial output".to_string(), false),
- id: acp::TerminalId::new("fake_terminal".to_string()),
+ id: acp_v2::TerminalId::new("fake_terminal".to_string()),
}
}
@@ -120,7 +121,7 @@ impl FakeTerminalHandle {
exit_sender: std::cell::RefCell::new(Some(exit_sender)),
wait_for_exit,
output: acp::TerminalOutputResponse::new("command output".to_string(), false),
- id: acp::TerminalId::new("fake_terminal".to_string()),
+ id: acp_v2::TerminalId::new("fake_terminal".to_string()),
}
}
@@ -145,7 +146,7 @@ impl FakeTerminalHandle {
}
impl crate::TerminalHandle for FakeTerminalHandle {
- fn id(&self, _cx: &AsyncApp) -> Result<acp::TerminalId> {
+ fn id(&self, _cx: &AsyncApp) -> Result<acp_v2::TerminalId> {
Ok(self.id.clone())
}
@@ -364,7 +365,7 @@ async fn test_echo(cx: &mut TestAppContext) {
"Hello\n"
)
});
- assert_eq!(stop_events(events), vec![acp::StopReason::EndTurn]);
+ assert_eq!(stop_events(events), vec![acp_v2::StopReason::EndTurn]);
}
#[gpui::test]
@@ -399,10 +400,10 @@ async fn test_terminal_tool_timeout_kills_handle(cx: &mut TestAppContext) {
let update = rx.expect_update_fields().await;
assert!(
- update.content.iter().any(|blocks| {
+ update.content.value().iter().any(|blocks| {
blocks
.iter()
- .any(|c| matches!(c, acp::ToolCallContent::Terminal(_)))
+ .any(|c| matches!(c, acp_v2::ToolCallContent::Terminal(_)))
}),
"expected tool call update to include terminal content"
);
@@ -467,10 +468,10 @@ async fn test_terminal_tool_without_timeout_does_not_kill_handle(cx: &mut TestAp
let update = rx.expect_update_fields().await;
assert!(
- update.content.iter().any(|blocks| {
+ update.content.value().iter().any(|blocks| {
blocks
.iter()
- .any(|c| matches!(c, acp::ToolCallContent::Terminal(_)))
+ .any(|c| matches!(c, acp_v2::ToolCallContent::Terminal(_)))
}),
"expected tool call update to include terminal content"
);
@@ -540,7 +541,7 @@ async fn test_thinking(cx: &mut TestAppContext) {
"}
)
});
- assert_eq!(stop_events(events), vec![acp::StopReason::EndTurn]);
+ assert_eq!(stop_events(events), vec![acp_v2::StopReason::EndTurn]);
}
#[gpui::test]
@@ -830,7 +831,7 @@ async fn test_basic_tool_calls(cx: &mut TestAppContext) {
.unwrap()
.collect()
.await;
- assert_eq!(stop_events(events), vec![acp::StopReason::EndTurn]);
+ assert_eq!(stop_events(events), vec![acp_v2::StopReason::EndTurn]);
// Test a tool calls that's likely to complete *after* streaming stops.
let events = thread
@@ -849,7 +850,7 @@ async fn test_basic_tool_calls(cx: &mut TestAppContext) {
.unwrap()
.collect()
.await;
- assert_eq!(stop_events(events), vec![acp::StopReason::EndTurn]);
+ assert_eq!(stop_events(events), vec![acp_v2::StopReason::EndTurn]);
thread.update(cx, |thread, _cx| {
assert!(
thread
@@ -887,7 +888,9 @@ async fn test_streaming_tool_calls(cx: &mut TestAppContext) {
let mut saw_partial_tool_use = false;
while let Some(event) = events.next().await {
- if let Ok(ThreadEvent::ToolCall(tool_call)) = event {
+ if let Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::V2(tool_call))) = event
+ && tool_call.status == MaybeUndefined::Value(acp_v2::ToolCallStatus::Pending)
+ {
thread.update(cx, |thread, _cx| {
// Look for a tool use in the thread's last message
let message = thread.last_received_or_pending_message().unwrap();
@@ -895,29 +898,14 @@ async fn test_streaming_tool_calls(cx: &mut TestAppContext) {
let last_content = agent_message.content.last().unwrap();
if let AgentMessageContent::ToolUse(last_tool_use) = last_content {
assert_eq!(last_tool_use.name.as_ref(), "word_list");
- if tool_call.status == acp::ToolCallStatus::Pending {
- if !last_tool_use.is_input_complete
- && last_tool_use
- .input
- .as_json()
- .and_then(|input| input.get("g"))
- .is_none()
- {
- saw_partial_tool_use = true;
- }
- } else {
- last_tool_use
- .input
- .as_json()
- .expect("tool input should be JSON")
- .get("a")
- .expect("'a' has streamed because input is now complete");
- last_tool_use
+ if !last_tool_use.is_input_complete
+ && last_tool_use
.input
.as_json()
- .expect("tool input should be JSON")
- .get("g")
- .expect("'g' has streamed because input is now complete");
+ .and_then(|input| input.get("g"))
+ .is_none()
+ {
+ saw_partial_tool_use = true;
}
} else {
panic!("last content should be a tool use");
@@ -990,8 +978,8 @@ async fn test_tool_authorization(cx: &mut TestAppContext) {
tool_call_auth_1
.response
.send(acp_thread::SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("allow"),
- acp::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionId::new("allow"),
+ acp_v2::PermissionOptionKind::AllowOnce,
))
.unwrap();
cx.run_until_parked();
@@ -1000,15 +988,15 @@ async fn test_tool_authorization(cx: &mut TestAppContext) {
tool_call_auth_2
.response
.send(acp_thread::SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("deny"),
- acp::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionId::new("deny"),
+ acp_v2::PermissionOptionKind::RejectOnce,
))
.unwrap();
interrupted_tool_call_auth
.response
.send(acp_thread::SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new(FOLLOW_UP_PERMISSION_DENIED_OPTION_ID),
- acp::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionId::new(FOLLOW_UP_PERMISSION_DENIED_OPTION_ID),
+ acp_v2::PermissionOptionKind::RejectOnce,
))
.unwrap();
cx.run_until_parked();
@@ -1062,8 +1050,8 @@ async fn test_tool_authorization(cx: &mut TestAppContext) {
tool_call_auth_3
.response
.send(acp_thread::SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("always_allow:tool_requiring_permission"),
- acp::PermissionOptionKind::AllowAlways,
+ acp_v2::PermissionOptionId::new("always_allow:tool_requiring_permission"),
+ acp_v2::PermissionOptionKind::AllowAlways,
))
.unwrap();
cx.run_until_parked();
@@ -1141,10 +1129,19 @@ async fn test_tool_hallucination(cx: &mut TestAppContext) {
fake.end_last(&model);
let tool_call = expect_tool_call(&mut events).await;
- assert_eq!(tool_call.title, "nonexistent_tool");
- assert_eq!(tool_call.status, acp::ToolCallStatus::Pending);
+ assert_eq!(
+ tool_call.title,
+ MaybeUndefined::Value("nonexistent_tool".into())
+ );
+ assert_eq!(
+ tool_call.status,
+ MaybeUndefined::Value(acp_v2::ToolCallStatus::Pending)
+ );
let update = expect_tool_call_update_fields(&mut events).await;
- assert_eq!(update.fields.status, Some(acp::ToolCallStatus::Failed));
+ assert_eq!(
+ update.status,
+ MaybeUndefined::Value(acp_v2::ToolCallStatus::Failed)
+ );
}
/// Regression test: some providers (confirmed on Bedrock Mantle/GPT-5.x)
@@ -1313,7 +1310,10 @@ async fn test_replayed_tool_call_ids_scoped_across_messages(cx: &mut TestAppCont
let mut replay_events = restored.update(cx, |thread, cx| thread.replay(cx));
let mut tool_call_ids = Vec::new();
while let Some(event) = replay_events.next().await {
- if let ThreadEvent::ToolCall(tool_call) = event.unwrap() {
+ if let ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::V2(tool_call)) =
+ event.unwrap()
+ && tool_call.status == MaybeUndefined::Value(acp_v2::ToolCallStatus::Pending)
+ {
tool_call_ids.push(tool_call.tool_call_id);
}
}
@@ -1331,30 +1331,36 @@ async fn test_replayed_tool_call_ids_scoped_across_messages(cx: &mut TestAppCont
);
}
-async fn expect_tool_call(events: &mut UnboundedReceiver<Result<ThreadEvent>>) -> acp::ToolCall {
+async fn expect_tool_call(
+ events: &mut UnboundedReceiver<Result<ThreadEvent>>,
+) -> acp_v2::ToolCallUpdate {
let event = events
.next()
.await
.expect("no tool call authorization event received")
.unwrap();
match event {
- ThreadEvent::ToolCall(tool_call) => tool_call,
+ ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::V2(tool_call)) => tool_call,
event => {
panic!("Unexpected event {event:?}");
}
}
}
-/// Like [`expect_tool_call`], but skips other events until a `ToolCall`
+/// Like [`expect_tool_call`], but skips other events until a pending tool update
/// appears -- useful across multiple request/response cycles in one turn.
-async fn next_tool_call(events: &mut UnboundedReceiver<Result<ThreadEvent>>) -> acp::ToolCall {
+async fn next_tool_call(
+ events: &mut UnboundedReceiver<Result<ThreadEvent>>,
+) -> acp_v2::ToolCallUpdate {
loop {
let event = events
.next()
.await
.expect("no tool call event received")
.unwrap();
- if let ThreadEvent::ToolCall(tool_call) = event {
+ if let ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::V2(tool_call)) = event
+ && tool_call.status == MaybeUndefined::Value(acp_v2::ToolCallStatus::Pending)
+ {
return tool_call;
}
}
@@ -1362,14 +1368,14 @@ async fn next_tool_call(events: &mut UnboundedReceiver<Result<ThreadEvent>>) ->
async fn expect_tool_call_update_fields(
events: &mut UnboundedReceiver<Result<ThreadEvent>>,
-) -> acp::ToolCallUpdate {
+) -> acp_v2::ToolCallUpdate {
let event = events
.next()
.await
.expect("no tool call authorization event received")
.unwrap();
match event {
- ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(update)) => update,
+ ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::V2(update)) => update,
event => {
panic!("Unexpected event {event:?}");
}
@@ -1388,18 +1394,18 @@ async fn next_tool_call_authorization(
if let ThreadEvent::ToolCallAuthorization(tool_call_authorization) = event {
let permission_kinds = tool_call_authorization
.options
- .first_option_of_kind(acp::PermissionOptionKind::AllowAlways)
- .map(|option| option.kind);
+ .first_option_of_kind(acp_v2::PermissionOptionKind::AllowAlways)
+ .map(|option| option.kind.clone());
let allow_once = tool_call_authorization
.options
- .first_option_of_kind(acp::PermissionOptionKind::AllowOnce)
- .map(|option| option.kind);
+ .first_option_of_kind(acp_v2::PermissionOptionKind::AllowOnce)
+ .map(|option| option.kind.clone());
assert_eq!(
permission_kinds,
- Some(acp::PermissionOptionKind::AllowAlways)
+ Some(acp_v2::PermissionOptionKind::AllowAlways)
);
- assert_eq!(allow_once, Some(acp::PermissionOptionKind::AllowOnce));
+ assert_eq!(allow_once, Some(acp_v2::PermissionOptionKind::AllowOnce));
return tool_call_authorization;
}
}
@@ -1538,11 +1544,11 @@ fn test_permission_options_symlink_target_are_flat_once_only() {
assert_eq!(options.len(), 2);
assert!(options.iter().any(|option| {
option.option_id.0.as_ref() == "allow"
- && option.kind == acp::PermissionOptionKind::AllowOnce
+ && option.kind == acp_v2::PermissionOptionKind::AllowOnce
}));
assert!(options.iter().any(|option| {
option.option_id.0.as_ref() == "deny"
- && option.kind == acp::PermissionOptionKind::RejectOnce
+ && option.kind == acp_v2::PermissionOptionKind::RejectOnce
}));
}
@@ -1666,7 +1672,7 @@ async fn test_concurrent_tool_calls(cx: &mut TestAppContext) {
.await;
let stop_reasons = stop_events(events);
- assert_eq!(stop_reasons, vec![acp::StopReason::EndTurn]);
+ assert_eq!(stop_reasons, vec![acp_v2::StopReason::EndTurn]);
thread.update(cx, |thread, _cx| {
let last_message = thread.last_received_or_pending_message().unwrap();
@@ -2320,14 +2326,16 @@ async fn test_mcp_tool_result_displayed_when_server_disconnected(cx: &mut TestAp
while let Some(event) = replay_events.next().await {
let event = event.unwrap();
match &event {
- ThreadEvent::ToolCall(tc) => {
+ ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::V2(tc))
+ if tc.status == MaybeUndefined::Value(acp_v2::ToolCallStatus::Pending) =>
+ {
tool_call_id = Some(tc.tool_call_id.clone());
found_tool_call = Some(tc.clone());
}
- ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(update))
+ ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::V2(update))
if tool_call_id.as_ref() == Some(&update.tool_call_id) =>
{
- if update.fields.raw_output.is_some() {
+ if update.raw_output.is_value() {
found_tool_call_update_with_output = Some(update.clone());
}
}
@@ -2348,15 +2356,15 @@ async fn test_mcp_tool_result_displayed_when_server_disconnected(cx: &mut TestAp
let update = found_tool_call_update_with_output.unwrap();
assert_eq!(
- update.fields.raw_output,
- Some(expected_tool_output.into()),
+ update.raw_output,
+ MaybeUndefined::Value(expected_tool_output.into()),
"raw_output should contain the saved tool result"
);
// Also verify the status is correct (completed, not failed)
assert_eq!(
- update.fields.status,
- Some(acp::ToolCallStatus::Completed),
+ update.status,
+ MaybeUndefined::Value(acp_v2::ToolCallStatus::Completed),
"Tool call status should reflect the original completion status"
);
}
@@ -2568,20 +2576,21 @@ async fn test_cancellation(cx: &mut TestAppContext) {
let mut echo_completed = false;
while let Some(event) = events.next().await {
match event.unwrap() {
- ThreadEvent::ToolCall(tool_call) => {
- assert_eq!(tool_call.title, expected_tools.remove(0));
- if tool_call.title == "Echo" {
+ ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::V2(tool_call))
+ if tool_call.status == MaybeUndefined::Value(acp_v2::ToolCallStatus::Pending) =>
+ {
+ assert_eq!(
+ tool_call.title,
+ MaybeUndefined::Value(expected_tools.remove(0).into())
+ );
+ if tool_call.title.value().map(String::as_str) == Some("Echo") {
echo_id = Some(tool_call.tool_call_id);
}
}
- ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(
- acp::ToolCallUpdate {
+ ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::V2(
+ acp_v2::ToolCallUpdate {
tool_call_id,
- fields:
- acp::ToolCallUpdateFields {
- status: Some(acp::ToolCallStatus::Completed),
- ..
- },
+ status: MaybeUndefined::Value(acp_v2::ToolCallStatus::Completed),
..
},
)) if Some(&tool_call_id) == echo_id.as_ref() => {
@@ -2603,7 +2612,7 @@ async fn test_cancellation(cx: &mut TestAppContext) {
assert!(
matches!(
last_event,
- Some(Ok(ThreadEvent::Stop(acp::StopReason::Cancelled)))
+ Some(Ok(ThreadEvent::Stop(acp_v2::StopReason::Cancelled)))
),
"unexpected event {last_event:?}"
);
@@ -2628,7 +2637,7 @@ async fn test_cancellation(cx: &mut TestAppContext) {
vec![AgentMessageContent::Text("Hello".to_string())]
);
});
- assert_eq!(stop_events(events), vec![acp::StopReason::EndTurn]);
+ assert_eq!(stop_events(events), vec![acp_v2::StopReason::EndTurn]);
}
#[gpui::test]
@@ -2693,7 +2702,7 @@ async fn test_terminal_tool_cancellation_captures_output(cx: &mut TestAppContext
// Verify we got a cancellation stop event
assert_eq!(
stop_events(remaining_events),
- vec![acp::StopReason::Cancelled],
+ vec![acp_v2::StopReason::Cancelled],
);
// Verify the tool result contains the terminal output, not just "Tool canceled by user"
@@ -2784,8 +2793,10 @@ async fn test_cancellation_aware_tool_responds_to_cancellation(cx: &mut TestAppC
cx.run_until_parked();
while let Some(Some(event)) = events.next().now_or_never() {
- if let Ok(ThreadEvent::ToolCall(tool_call)) = &event {
- if tool_call.title == "Cancellation Aware Tool" {
+ if let Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::V2(tool_call))) =
+ &event
+ {
+ if tool_call.title.value().map(String::as_str) == Some("Cancellation Aware Tool") {
tool_started = true;
break;
}
@@ -2826,7 +2837,7 @@ async fn test_cancellation_aware_tool_responds_to_cancellation(cx: &mut TestAppC
// Verify we got a cancellation stop event
assert_eq!(
stop_events(remaining_events),
- vec![acp::StopReason::Cancelled],
+ vec![acp_v2::StopReason::Cancelled],
);
// Verify we can send a new message after cancellation
@@ -2866,7 +2877,7 @@ async fn verify_thread_recovery(
vec![AgentMessageContent::Text("Hello".to_string())]
);
});
- assert_eq!(stop_events(events), vec![acp::StopReason::EndTurn]);
+ assert_eq!(stop_events(events), vec![acp_v2::StopReason::EndTurn]);
}
/// Waits for a terminal tool to start by watching for a ToolCallUpdate with terminal content.
@@ -2879,14 +2890,12 @@ async fn wait_for_terminal_tool_started(
cx.run_until_parked();
while let Some(Some(event)) = events.next().now_or_never() {
- if let Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(
- update,
- ))) = &event
+ if let Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::V2(update))) = &event
{
- if update.fields.content.as_ref().is_some_and(|content| {
+ if update.content.value().is_some_and(|content| {
content
.iter()
- .any(|c| matches!(c, acp::ToolCallContent::Terminal(_)))
+ .any(|c| matches!(c, acp_v2::ToolCallContent::Terminal(_)))
}) {
return;
}
@@ -3063,14 +3072,12 @@ async fn test_cancel_multiple_concurrent_terminal_tools(cx: &mut TestAppContext)
cx.run_until_parked();
while let Some(Some(event)) = events.next().now_or_never() {
- if let Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(
- update,
- ))) = &event
+ if let Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::V2(update))) = &event
{
- if update.fields.content.as_ref().is_some_and(|content| {
+ if update.content.value().is_some_and(|content| {
content
.iter()
- .any(|c| matches!(c, acp::ToolCallContent::Terminal(_)))
+ .any(|c| matches!(c, acp_v2::ToolCallContent::Terminal(_)))
}) {
terminals_started += 1;
if terminals_started >= 2 {
@@ -3117,7 +3124,7 @@ async fn test_cancel_multiple_concurrent_terminal_tools(cx: &mut TestAppContext)
// Verify we got a cancellation stop event
assert_eq!(
stop_events(remaining_events),
- vec![acp::StopReason::Cancelled],
+ vec![acp_v2::StopReason::Cancelled],
);
}
@@ -3192,7 +3199,7 @@ async fn test_terminal_tool_stopped_via_terminal_card_button(cx: &mut TestAppCon
// Verify we got an EndTurn (not Cancelled, since we didn't cancel the thread)
assert_eq!(
stop_events(remaining_events),
- vec![acp::StopReason::EndTurn],
+ vec![acp_v2::StopReason::EndTurn],
);
// Verify the tool result indicates user stopped
@@ -3298,7 +3305,7 @@ async fn test_terminal_tool_timeout_expires(cx: &mut TestAppContext) {
// Verify we got an EndTurn (the tool completed, just with timeout)
assert_eq!(
stop_events(remaining_events),
- vec![acp::StopReason::EndTurn],
+ vec![acp_v2::StopReason::EndTurn],
);
// Verify the tool result indicates timeout, not user stopped
@@ -3365,9 +3372,9 @@ async fn test_in_progress_send_canceled_by_next_send(cx: &mut TestAppContext) {
fake.end_last(&model);
let events_1 = events_1.collect::<Vec<_>>().await;
- assert_eq!(stop_events(events_1), vec![acp::StopReason::Cancelled]);
+ assert_eq!(stop_events(events_1), vec![acp_v2::StopReason::Cancelled]);
let events_2 = events_2.collect::<Vec<_>>().await;
- assert_eq!(stop_events(events_2), vec![acp::StopReason::EndTurn]);
+ assert_eq!(stop_events(events_2), vec![acp_v2::StopReason::EndTurn]);
}
#[gpui::test]
@@ -3449,10 +3456,10 @@ async fn test_retry_cancelled_promptly_on_new_send(cx: &mut TestAppContext) {
fake.end_stream(&model_b, &model_b_request);
let events_1 = events_1.collect::<Vec<_>>().await;
- assert_eq!(stop_events(events_1), vec![acp::StopReason::Cancelled]);
+ assert_eq!(stop_events(events_1), vec![acp_v2::StopReason::Cancelled]);
let events_2 = events_2.collect::<Vec<_>>().await;
- assert_eq!(stop_events(events_2), vec![acp::StopReason::EndTurn]);
+ assert_eq!(stop_events(events_2), vec![acp_v2::StopReason::EndTurn]);
}
#[gpui::test]
@@ -3492,8 +3499,8 @@ async fn test_subsequent_successful_sends_dont_cancel(cx: &mut TestAppContext) {
fake.end_last(&model);
let events_2 = events_2.collect::<Vec<_>>().await;
- assert_eq!(stop_events(events_1), vec![acp::StopReason::EndTurn]);
- assert_eq!(stop_events(events_2), vec![acp::StopReason::EndTurn]);
+ assert_eq!(stop_events(events_1), vec![acp_v2::StopReason::EndTurn]);
+ assert_eq!(stop_events(events_2), vec![acp_v2::StopReason::EndTurn]);
}
#[gpui::test]
@@ -3545,7 +3552,7 @@ async fn test_refusal(cx: &mut TestAppContext) {
LanguageModelCompletionEvent::Stop(StopReason::Refusal),
);
let events = events.collect::<Vec<_>>().await;
- assert_eq!(stop_events(events), vec![acp::StopReason::Refusal]);
+ assert_eq!(stop_events(events), vec![acp_v2::StopReason::Refusal]);
thread.read_with(cx, |thread, _| {
assert_eq!(thread.to_markdown(), "");
});
@@ -4568,38 +4575,33 @@ async fn test_tool_updates_to_completion(cx: &mut TestAppContext) {
let tool_call = expect_tool_call(&mut events).await;
assert_eq!(
tool_call,
- acp::ToolCall::new(acp::ToolCallId::new(tool_call_id.0.clone()), "Echo")
+ acp_v2::ToolCallUpdate::new(tool_call_id.clone())
+ .title("Echo")
.name("echo")
+ .kind(acp_v2::ToolKind::Other)
+ .status(acp_v2::ToolCallStatus::Pending)
.raw_input(json!({}))
);
let update = expect_tool_call_update_fields(&mut events).await;
assert_eq!(
update,
- acp::ToolCallUpdate::new(
- acp::ToolCallId::new(tool_call_id.0.clone()),
- acp::ToolCallUpdateFields::new()
- .title("Echo")
- .kind(acp::ToolKind::Other)
- .raw_input(json!({ "text": "Hello!"}))
- )
+ acp_v2::ToolCallUpdate::new(tool_call_id.clone())
+ .title("Echo")
+ .kind(acp_v2::ToolKind::Other)
+ .raw_input(json!({ "text": "Hello!"}))
);
let update = expect_tool_call_update_fields(&mut events).await;
assert_eq!(
update,
- acp::ToolCallUpdate::new(
- acp::ToolCallId::new(tool_call_id.0.clone()),
- acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::InProgress)
- )
+ acp_v2::ToolCallUpdate::new(tool_call_id.clone())
+ .status(acp_v2::ToolCallStatus::InProgress)
);
let update = expect_tool_call_update_fields(&mut events).await;
assert_eq!(
update,
- acp::ToolCallUpdate::new(
- acp::ToolCallId::new(tool_call_id.0),
- acp::ToolCallUpdateFields::new()
- .status(acp::ToolCallStatus::Completed)
- .raw_output("Hello!")
- )
+ acp_v2::ToolCallUpdate::new(tool_call_id)
+ .status(acp_v2::ToolCallStatus::Completed)
+ .raw_output("Hello!")
);
}
@@ -5114,7 +5116,7 @@ async fn test_streaming_tool_json_parse_error_is_forwarded_to_running_tool(
}
/// Filters out the stop events for asserting against in tests
-fn stop_events(result_events: Vec<Result<ThreadEvent>>) -> Vec<acp::StopReason> {
+fn stop_events(result_events: Vec<Result<ThreadEvent>>) -> Vec<acp_v2::StopReason> {
result_events
.into_iter()
.filter_map(|event| match event.unwrap() {
@@ -5240,6 +5242,8 @@ async fn setup(cx: &mut TestAppContext, model: TestModel) -> ThreadTest {
let context_server_store = project.read_with(cx, |project, _| project.context_server_store());
let context_server_registry =
cx.new(|cx| ContextServerRegistry::new(context_server_store.clone(), cx));
+ // Thread::new snapshots the default profile, so load the watched settings first.
+ cx.run_until_parked();
let thread = cx.new(|cx| {
Thread::new(
project,
@@ -5675,10 +5679,10 @@ async fn test_terminal_tool_permission_rules(cx: &mut TestAppContext) {
let update = rx.expect_update_fields().await;
assert!(
- update.content.iter().any(|blocks| {
+ update.content.value().iter().any(|blocks| {
blocks
.iter()
- .any(|c| matches!(c, acp::ToolCallContent::Terminal(_)))
+ .any(|c| matches!(c, acp_v2::ToolCallContent::Terminal(_)))
}),
"expected terminal content (allow rule should skip confirmation and override default deny)"
);
@@ -8156,9 +8160,10 @@ async fn test_fetch_tool_prompts_for_ungranted_host(cx: &mut TestAppContext) {
cx.run_until_parked();
let authorization = rx.expect_authorization().await;
- let details =
- acp_thread::sandbox_authorization_details_from_meta(&authorization.tool_call.meta)
- .expect("an ungranted host should request a sandbox network grant");
+ let details = acp_thread::sandbox_authorization_details_from_meta(
+ &authorization.tool_call.meta.value().cloned(),
+ )
+ .expect("an ungranted host should request a sandbox network grant");
assert_eq!(details.network_hosts, vec!["example.com".to_string()]);
assert!(!details.network_all_hosts);
}
@@ -8407,9 +8412,10 @@ async fn test_fetch_tool_reauthorizes_redirect_to_new_host(cx: &mut TestAppConte
cx.run_until_parked();
let authorization = rx.expect_authorization().await;
- let details =
- acp_thread::sandbox_authorization_details_from_meta(&authorization.tool_call.meta)
- .expect("a redirect to an ungranted host should request a sandbox network grant");
+ let details = acp_thread::sandbox_authorization_details_from_meta(
+ &authorization.tool_call.meta.value().cloned(),
+ )
+ .expect("a redirect to an ungranted host should request a sandbox network grant");
assert_eq!(
details.network_hosts,
vec!["redirect-target.example".to_string()]
@@ -8527,8 +8533,8 @@ async fn test_always_allow_resolves_pending_authorizations(cx: &mut TestAppConte
tool_call_auth_1
.response
.send(acp_thread::SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("always_allow:tool_requiring_permission"),
- acp::PermissionOptionKind::AllowAlways,
+ acp_v2::PermissionOptionId::new("always_allow:tool_requiring_permission"),
+ acp_v2::PermissionOptionKind::AllowAlways,
))
.unwrap();
cx.run_until_parked();
@@ -8538,8 +8544,8 @@ async fn test_always_allow_resolves_pending_authorizations(cx: &mut TestAppConte
let late_send = tool_call_auth_2
.response
.send(acp_thread::SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("allow"),
- acp::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionId::new("allow"),
+ acp_v2::PermissionOptionKind::AllowOnce,
));
assert!(
late_send.is_err(),
@@ -8624,8 +8630,8 @@ async fn test_external_settings_edit_resolves_pending_authorization(cx: &mut Tes
let late_send = tool_call_auth
.response
.send(acp_thread::SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("allow"),
- acp::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionId::new("allow"),
+ acp_v2::PermissionOptionKind::AllowOnce,
));
assert!(
late_send.is_err(),
@@ -8699,8 +8705,8 @@ async fn test_external_deny_rule_resolves_pending_authorization(cx: &mut TestApp
let late_send = tool_call_auth
.response
.send(acp_thread::SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("allow"),
- acp::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionId::new("allow"),
+ acp_v2::PermissionOptionKind::AllowOnce,
));
assert!(
late_send.is_err(),
@@ -8773,8 +8779,8 @@ async fn test_unrelated_settings_change_does_not_resolve_pending_authorization(
tool_call_auth
.response
.send(acp_thread::SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("allow"),
- acp::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionId::new("allow"),
+ acp_v2::PermissionOptionKind::AllowOnce,
))
.expect("response receiver should still be alive");
cx.run_until_parked();
@@ -8857,8 +8863,8 @@ async fn test_always_allow_does_not_resolve_unrelated_tool_authorization(cx: &mu
auth_for_tool_1
.response
.send(acp_thread::SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("always_allow:tool_requiring_permission"),
- acp::PermissionOptionKind::AllowAlways,
+ acp_v2::PermissionOptionId::new("always_allow:tool_requiring_permission"),
+ acp_v2::PermissionOptionKind::AllowAlways,
))
.unwrap();
cx.run_until_parked();
@@ -8868,8 +8874,8 @@ async fn test_always_allow_does_not_resolve_unrelated_tool_authorization(cx: &mu
auth_for_tool_2
.response
.send(acp_thread::SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("allow"),
- acp::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionId::new("allow"),
+ acp_v2::PermissionOptionKind::AllowOnce,
))
.expect("tool 2's response receiver should still be alive");
cx.run_until_parked();
@@ -8953,7 +8959,11 @@ async fn test_queued_message_ends_turn_at_boundary(cx: &mut TestAppContext) {
let tool_call_ids: Vec<_> = all_events
.iter()
.filter_map(|e| match e {
- Ok(ThreadEvent::ToolCall(tc)) => Some(tc.tool_call_id.to_string()),
+ Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::V2(tc)))
+ if tc.status == MaybeUndefined::Value(acp_v2::ToolCallStatus::Pending) =>
+ {
+ Some(tc.tool_call_id.to_string())
+ }
_ => None,
})
.collect();
@@ -8969,7 +8979,7 @@ async fn test_queued_message_ends_turn_at_boundary(cx: &mut TestAppContext) {
let stop_reasons = stop_events(all_events);
assert_eq!(
stop_reasons,
- vec![acp::StopReason::EndTurn],
+ vec![acp_v2::StopReason::EndTurn],
"Turn should have ended after tool completion due to queued message"
);
@@ -9056,7 +9066,7 @@ async fn test_queued_message_does_not_end_turn_without_boundary_flag(cx: &mut Te
let stop_reasons = stop_events(all_events);
assert_eq!(
stop_reasons,
- vec![acp::StopReason::EndTurn],
+ vec![acp_v2::StopReason::EndTurn],
"Turn should end only after the agent finishes, not at the tool boundary"
);
}
diff --git a/crates/agent/src/tests/test_tools.rs b/crates/agent/src/tests/test_tools.rs
index 56a5733761c..49143662ce5 100644
--- a/crates/agent/src/tests/test_tools.rs
+++ b/crates/agent/src/tests/test_tools.rs
@@ -1,4 +1,5 @@
use super::*;
+use agent_client_protocol::schema::v2 as acp;
use gpui::{App, SharedString, Task};
use std::future;
use std::sync::Mutex;
diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rs
index e25f43752a3..33dad16b706 100644
--- a/crates/agent/src/thread.rs
+++ b/crates/agent/src/thread.rs
@@ -760,7 +760,7 @@ pub enum AgentMessageContent {
}
pub trait TerminalHandle {
- fn id(&self, cx: &AsyncApp) -> Result<acp::TerminalId>;
+ fn id(&self, cx: &AsyncApp) -> Result<acp_v2::TerminalId>;
fn current_output(&self, cx: &AsyncApp) -> Result<acp::TerminalOutputResponse>;
fn wait_for_exit(&self, cx: &AsyncApp) -> Result<Shared<Task<acp::TerminalExitStatus>>>;
fn kill(&self, cx: &AsyncApp) -> Result<()>;
@@ -903,7 +903,6 @@ pub enum ThreadEvent {
UserMessage(UserMessage),
AgentText(String),
AgentThinking(String),
- ToolCall(acp::ToolCall),
ToolCallUpdate(acp_thread::ToolCallUpdate),
ToolCallAuthorization(ToolCallAuthorization),
ToolCallAuthorizationResolved {
@@ -915,7 +914,7 @@ pub enum ThreadEvent {
Retry(acp_thread::RetryStatus),
ContextCompaction(acp_thread::ContextCompaction),
ContextCompactionUpdate(acp_thread::ContextCompactionUpdate),
- Stop(acp::StopReason),
+ Stop(acp_v2::StopReason),
}
#[derive(Debug)]
@@ -994,15 +993,15 @@ impl ToolPermissionContext {
let input_values = &self.input_values;
if self.scope == ToolPermissionScope::SymlinkTarget {
return acp_thread::PermissionOptions::Flat(vec![
- acp::PermissionOption::new(
- acp::PermissionOptionId::new("allow"),
+ acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new("allow"),
"Yes",
- acp::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
),
- acp::PermissionOption::new(
- acp::PermissionOptionId::new("deny"),
+ acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new("deny"),
"No",
- acp::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionKind::RejectOnce,
),
]);
}
@@ -1010,15 +1009,15 @@ impl ToolPermissionContext {
// Skills always prompt, so offer only once-only allow/deny.
if self.scope == ToolPermissionScope::AgentSkills {
return acp_thread::PermissionOptions::Flat(vec![
- acp::PermissionOption::new(
- acp::PermissionOptionId::new("allow"),
+ acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new("allow"),
"Allow",
- acp::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
),
- acp::PermissionOption::new(
- acp::PermissionOptionId::new("deny"),
+ acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new("deny"),
"Deny",
- acp::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionKind::RejectOnce,
),
]);
}
@@ -1039,28 +1038,28 @@ impl ToolPermissionContext {
if all_patterns.len() > 1 {
let mut choices = Vec::new();
choices.push(acp_thread::PermissionOptionChoice {
- allow: acp::PermissionOption::new(
- acp::PermissionOptionId::new(format!("always_allow:{}", tool_name)),
+ allow: acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new(format!("always_allow:{}", tool_name)),
format!("Always for {}", tool_name.replace('_', " ")),
- acp::PermissionOptionKind::AllowAlways,
+ acp_v2::PermissionOptionKind::AllowAlways,
),
- deny: acp::PermissionOption::new(
- acp::PermissionOptionId::new(format!("always_deny:{}", tool_name)),
+ deny: acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new(format!("always_deny:{}", tool_name)),
format!("Always for {}", tool_name.replace('_', " ")),
- acp::PermissionOptionKind::RejectAlways,
+ acp_v2::PermissionOptionKind::RejectAlways,
),
sub_patterns: vec![],
});
choices.push(acp_thread::PermissionOptionChoice {
- allow: acp::PermissionOption::new(
- acp::PermissionOptionId::new("allow"),
+ allow: acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new("allow"),
"Only this time",
- acp::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
),
- deny: acp::PermissionOption::new(
- acp::PermissionOptionId::new("deny"),
+ deny: acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new("deny"),
"Only this time",
- acp::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionKind::RejectOnce,
),
sub_patterns: vec![],
});
@@ -1124,13 +1123,13 @@ impl ToolPermissionContext {
let mut push_choice =
|label: String, allow_id, deny_id, allow_kind, deny_kind, sub_patterns: Vec<String>| {
choices.push(acp_thread::PermissionOptionChoice {
- allow: acp::PermissionOption::new(
- acp::PermissionOptionId::new(allow_id),
+ allow: acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new(allow_id),
label.clone(),
allow_kind,
),
- deny: acp::PermissionOption::new(
- acp::PermissionOptionId::new(deny_id),
+ deny: acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new(deny_id),
label,
deny_kind,
),
@@ -1143,8 +1142,8 @@ impl ToolPermissionContext {
format!("Always for {}", tool_name.replace('_', " ")),
format!("always_allow:{}", tool_name),
format!("always_deny:{}", tool_name),
- acp::PermissionOptionKind::AllowAlways,
- acp::PermissionOptionKind::RejectAlways,
+ acp_v2::PermissionOptionKind::AllowAlways,
+ acp_v2::PermissionOptionKind::RejectAlways,
vec![],
);
@@ -1158,8 +1157,8 @@ impl ToolPermissionContext {
button_text,
format!("always_allow:{}", tool_name),
format!("always_deny:{}", tool_name),
- acp::PermissionOptionKind::AllowAlways,
- acp::PermissionOptionKind::RejectAlways,
+ acp_v2::PermissionOptionKind::AllowAlways,
+ acp_v2::PermissionOptionKind::RejectAlways,
vec![pattern],
);
}
@@ -1169,8 +1168,8 @@ impl ToolPermissionContext {
"Only this time".to_string(),
"allow".to_string(),
"deny".to_string(),
- acp::PermissionOptionKind::AllowOnce,
- acp::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::RejectOnce,
vec![],
);
@@ -1180,7 +1179,7 @@ impl ToolPermissionContext {
#[derive(Debug)]
pub struct ToolCallAuthorization {
- pub tool_call: acp::ToolCallUpdate,
+ pub tool_call: acp_v2::ToolCallUpdate,
pub options: acp_thread::PermissionOptions,
pub response: oneshot::Sender<acp_thread::SelectedPermissionOutcome>,
pub context: Option<ToolPermissionContext>,
@@ -1215,9 +1214,9 @@ fn auto_resolve_permission_outcome(
is_allow: bool,
) -> Result<acp_thread::SelectedPermissionOutcome> {
let kind = if is_allow {
- acp::PermissionOptionKind::AllowOnce
+ acp_v2::PermissionOptionKind::AllowOnce
} else {
- acp::PermissionOptionKind::RejectOnce
+ acp_v2::PermissionOptionKind::RejectOnce
};
let option = options
.first_option_of_kind(kind)
@@ -1225,7 +1224,7 @@ fn auto_resolve_permission_outcome(
Ok(acp_thread::SelectedPermissionOutcome::new(
option.option_id.clone(),
- option.kind,
+ option.kind.clone(),
))
}
@@ -1640,11 +1639,11 @@ impl Thread {
let replay_content = tool_result.and_then(Self::tool_result_content_for_replay);
let status = tool_result
.as_ref()
- .map_or(acp::ToolCallStatus::Failed, |result| {
+ .map_or(acp_v2::ToolCallStatus::Failed, |result| {
if result.is_error {
- acp::ToolCallStatus::Failed
+ acp_v2::ToolCallStatus::Failed
} else {
- acp::ToolCallStatus::Completed
+ acp_v2::ToolCallStatus::Completed
}
});
@@ -1670,25 +1669,23 @@ impl Thread {
let Some(tool) = tool else {
// Tool not found (e.g., MCP server not connected after restart),
// but still display the saved result if available.
- stream
- .sender
- .unbounded_send(Ok(ThreadEvent::ToolCall(
- acp::ToolCall::new(
- acp::ToolCallId::new(tool_call_id.0.clone()),
- tool_use.name.to_string(),
- )
- .name(tool_use.name.to_string())
- .status(status)
- .raw_input(tool_use.input.to_display_json()),
- )))
- .ok();
- let mut fields = acp::ToolCallUpdateFields::new()
- .status(status)
- .raw_output(output);
- if let Some(content) = replay_content {
- fields = fields.content(content);
- }
- stream.update_tool_call_fields(&tool_call_id, fields, None);
+ stream.send_tool_call(
+ &tool_call_id,
+ &tool_use.name,
+ tool_use.name.to_string().into(),
+ acp_v2::ToolKind::Other,
+ tool_use.input.to_display_json(),
+ );
+ stream.update_tool_call_fields(&tool_call_id, |update| {
+ let mut update = update.status(status);
+ if let Some(output) = output {
+ update = update.raw_output(output);
+ }
+ if let Some(content) = replay_content {
+ update = update.content(content);
+ }
+ update
+ });
return;
};
@@ -1700,11 +1697,7 @@ impl Thread {
stream.send_tool_call(&tool_call_id, &tool_use.name, title, kind, input.clone());
if let Some(content) = replay_content {
- stream.update_tool_call_fields(
- &tool_call_id,
- acp::ToolCallUpdateFields::new().content(content),
- None,
- );
+ stream.update_tool_call_fields(&tool_call_id, |update| update.content(content));
}
if let Some(output) = output.clone() {
@@ -1722,13 +1715,14 @@ impl Thread {
tool.replay(input, output, tool_event_stream, cx).log_err();
}
- stream.update_tool_call_fields(
- &tool_call_id,
- acp::ToolCallUpdateFields::new()
- .status(status)
- .raw_output(output),
- None,
- );
+ stream.update_tool_call_fields(&tool_call_id, |update| {
+ let update = update.status(status);
+ if let Some(output) = output {
+ update.raw_output(output)
+ } else {
+ update
+ }
+ });
}
/// A canceled tool result carries only the model-facing `TOOL_CANCELED_MESSAGE`
@@ -1745,7 +1739,7 @@ impl Thread {
fn tool_result_content_for_replay(
tool_result: &LanguageModelToolResult,
- ) -> Option<Vec<acp::ToolCallContent>> {
+ ) -> Option<Vec<acp_v2::ToolCallContent>> {
let has_image = tool_result
.content
.iter()
@@ -1762,16 +1756,14 @@ impl Thread {
if text.is_empty() {
None
} else {
- Some(acp::ToolCallContent::Content(acp::Content::new(
- acp::ContentBlock::Text(acp::TextContent::new(text.to_string())),
- )))
+ Some(acp_v2::ToolCallContent::from(text.to_string()))
}
}
- LanguageModelToolResultContent::Image(image) => Some(
- acp::ToolCallContent::Content(acp::Content::new(acp::ContentBlock::Image(
- acp::ImageContent::new(image.source.clone(), "image/png"),
- ))),
- ),
+ LanguageModelToolResultContent::Image(image) => {
+ Some(acp_v2::ToolCallContent::from(acp_v2::ContentBlock::Image(
+ acp_v2::ImageContent::new(image.source.clone(), "image/png"),
+ )))
+ }
})
.collect::<Vec<_>>();
@@ -2704,7 +2696,7 @@ impl Thread {
// On success, the telemetry event is deferred until the next
// completion reports usage (see `handle_completion_event`),
// so we leave `pending_compaction_telemetry` in place here.
- Ok(_) => event_stream.send_stop(acp::StopReason::EndTurn),
+ Ok(_) => event_stream.send_stop(acp_v2::StopReason::EndTurn),
Err(error) => {
log::error!("Manual compaction failed: {:?}", error);
this.update(cx, |this, _| {
@@ -2806,17 +2798,17 @@ impl Thread {
match turn_result {
Ok(()) => {
log::debug!("Turn execution completed");
- event_stream.send_stop(acp::StopReason::EndTurn);
+ event_stream.send_stop(acp_v2::StopReason::EndTurn);
}
Err(error) => {
log::error!("Turn execution failed: {:?}", error);
match error.downcast::<CompletionError>() {
Ok(CompletionError::Refusal) => {
- event_stream.send_stop(acp::StopReason::Refusal);
+ event_stream.send_stop(acp_v2::StopReason::Refusal);
_ = this.update(cx, |this, _| this.messages.truncate(message_ix));
}
Ok(CompletionError::MaxTokens) => {
- event_stream.send_stop(acp::StopReason::MaxTokens);
+ event_stream.send_stop(acp_v2::StopReason::MaxTokens);
}
Ok(CompletionError::Other(error)) | Err(error) => {
event_stream.send_error(error);
@@ -3394,14 +3386,18 @@ impl Thread {
event_stream.update_tool_call_fields(
&scoped_tool_call_id(owning_message_ix, &tool_result.tool_use_id),
- acp::ToolCallUpdateFields::new()
- .status(if tool_result.is_error {
- acp::ToolCallStatus::Failed
+ |update| {
+ let update = update.status(if tool_result.is_error {
+ acp_v2::ToolCallStatus::Failed
} else {
- acp::ToolCallStatus::Completed
- })
- .raw_output(tool_result.output.clone()),
- None,
+ acp_v2::ToolCallStatus::Completed
+ });
+ if let Some(output) = tool_result.output.clone() {
+ update.raw_output(output)
+ } else {
+ update
+ }
+ },
);
this.update(cx, |this, _cx| {
this.pending_message()
@@ -3599,7 +3595,7 @@ impl Thread {
let owning_message_ix = self.messages.len();
let tool = self.tool(tool_use.name.as_ref());
let mut title = SharedString::from(&tool_use.name);
- let mut kind = acp::ToolKind::Other;
+ let mut kind = acp_v2::ToolKind::Other;
if let Some(tool) = tool.as_ref() {
if let Ok(input) = tool_use.input.clone().into_json() {
title = tool.initial_title(input, cx);
@@ -3743,9 +3739,7 @@ impl Thread {
self.sandbox_grants.clone(),
Some(cx.weak_entity()),
);
- tool_event_stream.update_fields(
- acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::InProgress),
- );
+ tool_event_stream.update_fields(|update| update.status(acp_v2::ToolCallStatus::InProgress));
let supports_images = self.model().is_some_and(|model| model.supports_images());
let tool_result = tool.run(tool_input, tool_event_stream, cx);
cx.foreground_executor().spawn(async move {
@@ -3827,7 +3821,7 @@ impl Thread {
self.send_or_update_tool_use(
&tool_use,
SharedString::from(&tool_use.name),
- acp::ToolKind::Other,
+ acp_v2::ToolKind::Other,
owning_message_ix,
event_stream,
);
@@ -3879,7 +3873,7 @@ impl Thread {
&mut self,
tool_use: &LanguageModelToolUse,
title: SharedString,
- kind: acp::ToolKind,
+ kind: acp_v2::ToolKind,
owning_message_ix: usize,
event_stream: &ThreadEventStream,
) {
@@ -3910,14 +3904,12 @@ impl Thread {
.content
.push(AgentMessageContent::ToolUse(tool_use.clone()));
} else {
- event_stream.update_tool_call_fields(
- &tool_call_id,
- acp::ToolCallUpdateFields::new()
+ event_stream.update_tool_call_fields(&tool_call_id, |update| {
+ update
.title(title.as_str())
.kind(kind)
- .raw_input(tool_use.input.to_display_json()),
- None,
- );
+ .raw_input(tool_use.input.to_display_json())
+ });
}
}
@@ -5241,7 +5233,7 @@ where
)
}
- fn kind() -> acp::ToolKind;
+ fn kind() -> acp_v2::ToolKind;
/// The initial tool title to display. Can be updated during the tool run.
fn initial_title(
@@ -5328,7 +5320,7 @@ impl From<anyhow::Error> for AgentToolOutput {
pub trait AnyAgentTool {
fn name(&self) -> SharedString;
fn description(&self) -> SharedString;
- fn kind(&self) -> acp::ToolKind;
+ fn kind(&self) -> acp_v2::ToolKind;
fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString;
fn input_schema(&self) -> serde_json::Value;
fn supports_input_streaming(&self) -> bool {
@@ -5368,7 +5360,7 @@ where
T::description()
}
- fn kind(&self) -> acp::ToolKind {
+ fn kind(&self) -> acp_v2::ToolKind {
T::kind()
}
@@ -5494,17 +5486,13 @@ impl ThreadEventStream {
id: &acp_v2::ToolCallId,
tool_name: &str,
title: SharedString,
- kind: acp::ToolKind,
+ kind: acp_v2::ToolKind,
input: serde_json::Value,
) {
self.sender
- .unbounded_send(Ok(ThreadEvent::ToolCall(Self::initial_tool_call(
- id,
- tool_name,
- title.to_string(),
- kind,
- input,
- ))))
+ .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
+ Self::initial_tool_call(id, tool_name, title.to_string(), kind, input).into(),
+ )))
.ok();
}
@@ -5512,27 +5500,26 @@ impl ThreadEventStream {
id: &acp_v2::ToolCallId,
tool_name: &str,
title: String,
- kind: acp::ToolKind,
+ kind: acp_v2::ToolKind,
input: serde_json::Value,
- ) -> acp::ToolCall {
- acp::ToolCall::new(acp::ToolCallId::new(id.0.clone()), title)
+ ) -> acp_v2::ToolCallUpdate {
+ acp_v2::ToolCallUpdate::new(id.clone())
+ .title(title)
.name(tool_name)
.kind(kind)
+ .status(acp_v2::ToolCallStatus::Pending)
.raw_input(input)
}
fn update_tool_call_fields(
&self,
tool_call_id: &acp_v2::ToolCallId,
- fields: acp::ToolCallUpdateFields,
- meta: Option<acp::Meta>,
+ update: impl FnOnce(acp_v2::ToolCallUpdate) -> acp_v2::ToolCallUpdate,
) {
+ let mut update = update(acp_v2::ToolCallUpdate::new(tool_call_id.clone()));
+ update.tool_call_id = tool_call_id.clone();
self.sender
- .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
- acp::ToolCallUpdate::new(acp::ToolCallId::new(tool_call_id.0.clone()), fields)
- .meta(meta)
- .into(),
- )))
+ .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(update.into())))
.ok();
}
@@ -5613,7 +5600,7 @@ impl ThreadEventStream {
.ok();
}
- fn send_stop(&self, reason: acp::StopReason) {
+ fn send_stop(&self, reason: acp_v2::StopReason) {
self.sender
.unbounded_send(Ok(ThreadEvent::Stop(reason)))
.ok();
@@ -5629,7 +5616,7 @@ impl ThreadEventStream {
acp_thread::ContextCompactionStatus::Canceled,
);
}
- self.send_stop(acp::StopReason::Cancelled);
+ self.send_stop(acp_v2::StopReason::Cancelled);
}
fn send_error(&self, error: impl Into<anyhow::Error>) {
@@ -5806,18 +5793,12 @@ impl ToolCallEventStream {
&self.tool_call_id
}
- pub fn update_fields(&self, fields: acp::ToolCallUpdateFields) {
- self.stream
- .update_tool_call_fields(&self.tool_call_id, fields, None);
- }
-
- pub fn update_fields_with_meta(
+ pub fn update_fields(
&self,
- fields: acp::ToolCallUpdateFields,
- meta: Option<acp::Meta>,
+ update: impl FnOnce(acp_v2::ToolCallUpdate) -> acp_v2::ToolCallUpdate,
) {
self.stream
- .update_tool_call_fields(&self.tool_call_id, fields, meta);
+ .update_tool_call_fields(&self.tool_call_id, update);
}
pub fn resolve_authorization(&self, outcome: acp_thread::SelectedPermissionOutcome) {
@@ -5863,28 +5844,28 @@ impl ToolCallEventStream {
let title = title.into();
let options = acp_thread::PermissionOptions::Dropdown(vec![
acp_thread::PermissionOptionChoice {
- allow: acp::PermissionOption::new(
- acp::PermissionOptionId::new(format!("always_allow_mcp:{tool_id}")),
+ allow: acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new(format!("always_allow_mcp:{tool_id}")),
format!("Always for {display_name} MCP tool"),
- acp::PermissionOptionKind::AllowAlways,
+ acp_v2::PermissionOptionKind::AllowAlways,
),
- deny: acp::PermissionOption::new(
- acp::PermissionOptionId::new(format!("always_deny_mcp:{tool_id}")),
+ deny: acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new(format!("always_deny_mcp:{tool_id}")),
format!("Always for {display_name} MCP tool"),
- acp::PermissionOptionKind::RejectAlways,
+ acp_v2::PermissionOptionKind::RejectAlways,
),
sub_patterns: vec![],
},
acp_thread::PermissionOptionChoice {
- allow: acp::PermissionOption::new(
- acp::PermissionOptionId::new("allow"),
+ allow: acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new("allow"),
"Only this time",
- acp::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
),
- deny: acp::PermissionOption::new(
- acp::PermissionOptionId::new("deny"),
+ deny: acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new("deny"),
"Only this time",
- acp::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionKind::RejectOnce,
),
sub_patterns: vec![],
},
@@ -6005,25 +5986,25 @@ impl ToolCallEventStream {
"Allow for this thread"
};
let options = acp_thread::PermissionOptions::Flat(vec![
- acp::PermissionOption::new(
- acp::PermissionOptionId::new(acp_thread::SandboxPermission::AllowOnce.as_id()),
+ acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new(acp_thread::SandboxPermission::AllowOnce.as_id()),
"Allow once",
- acp::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
),
- acp::PermissionOption::new(
- acp::PermissionOptionId::new(acp_thread::SandboxPermission::AllowThread.as_id()),
+ acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new(acp_thread::SandboxPermission::AllowThread.as_id()),
allow_thread_label,
- acp::PermissionOptionKind::AllowAlways,
+ acp_v2::PermissionOptionKind::AllowAlways,
),
- acp::PermissionOption::new(
- acp::PermissionOptionId::new(acp_thread::SandboxPermission::AllowAlways.as_id()),
+ acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new(acp_thread::SandboxPermission::AllowAlways.as_id()),
"Allow always",
- acp::PermissionOptionKind::AllowAlways,
+ acp_v2::PermissionOptionKind::AllowAlways,
),
- acp::PermissionOption::new(
- acp::PermissionOptionId::new(acp_thread::SandboxPermission::Deny.as_id()),
+ acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new(acp_thread::SandboxPermission::Deny.as_id()),
"Deny",
- acp::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionKind::RejectOnce,
),
]);
@@ -6043,13 +6024,7 @@ impl ToolCallEventStream {
.sender
.unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
ToolCallAuthorization {
- tool_call: acp::ToolCallUpdate::new(
- acp::ToolCallId::new(tool_call_id.0.clone()),
- // Leave the title untouched so the card keeps
- // showing the command (matching the fallback flow).
- acp::ToolCallUpdateFields::new(),
- )
- .meta(
+ tool_call: acp_v2::ToolCallUpdate::new(tool_call_id.clone()).meta(
acp_thread::meta_with_sandbox_authorization(
sandbox_authorization_details,
),
@@ -6137,24 +6112,19 @@ impl ToolCallEventStream {
reason: String::new(),
};
let options = acp_thread::PermissionOptions::Flat(vec![
- acp::PermissionOption::new(
- acp::PermissionOptionId::new(acp_thread::SandboxPermission::AllowOnce.as_id()),
+ acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new(acp_thread::SandboxPermission::AllowOnce.as_id()),
"Continue",
- acp::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
),
- acp::PermissionOption::new(
- acp::PermissionOptionId::new(acp_thread::SandboxPermission::Deny.as_id()),
+ acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new(acp_thread::SandboxPermission::Deny.as_id()),
"Abort",
- acp::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionKind::RejectOnce,
),
]);
let stream = self.stream.clone();
- // The update must target the ACP-facing (scoped) id: an update keyed
- // by the raw provider id matches no existing tool call, and creating
- // one from empty fields is rejected downstream ("title is required"),
- // which tears down the stream and turns the prompt into a phantom
- // decline.
let tool_call_id = self.tool_call_id.clone();
cx.spawn(async move |_cx| {
let (response_tx, response_rx) = oneshot::channel();
@@ -6163,14 +6133,8 @@ impl ToolCallEventStream {
.sender
.unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
ToolCallAuthorization {
- tool_call: acp::ToolCallUpdate::new(
- acp::ToolCallId::new(tool_call_id.0),
- // Leave the title untouched so the card keeps
- // showing the command (matching the escalation
- // flow).
- acp::ToolCallUpdateFields::new(),
- )
- .meta(acp_thread::meta_with_sandbox_authorization(details)),
+ tool_call: acp_v2::ToolCallUpdate::new(tool_call_id)
+ .meta(acp_thread::meta_with_sandbox_authorization(details)),
options,
response: response_tx,
context: None,
@@ -6397,30 +6361,30 @@ impl ToolCallEventStream {
// governs keybindings. Use `RejectAlways` (which has none) so the
// "allow once" shortcut maps to "Run without sandbox once" rather
// than to Retry.
- acp::PermissionOption::new(
- acp::PermissionOptionId::new(acp_thread::SANDBOX_FALLBACK_RETRY_OPTION_ID),
+ acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new(acp_thread::SANDBOX_FALLBACK_RETRY_OPTION_ID),
retry_label,
- acp::PermissionOptionKind::RejectAlways,
+ acp_v2::PermissionOptionKind::RejectAlways,
),
- acp::PermissionOption::new(
- acp::PermissionOptionId::new(acp_thread::SandboxPermission::AllowOnce.as_id()),
+ acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new(acp_thread::SandboxPermission::AllowOnce.as_id()),
"Run without sandbox once",
- acp::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
),
- acp::PermissionOption::new(
- acp::PermissionOptionId::new(acp_thread::SandboxPermission::AllowThread.as_id()),
+ acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new(acp_thread::SandboxPermission::AllowThread.as_id()),
allow_thread_label,
- acp::PermissionOptionKind::AllowAlways,
+ acp_v2::PermissionOptionKind::AllowAlways,
),
- acp::PermissionOption::new(
- acp::PermissionOptionId::new(acp_thread::SandboxPermission::AllowAlways.as_id()),
+ acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new(acp_thread::SandboxPermission::AllowAlways.as_id()),
"Always run without sandbox",
- acp::PermissionOptionKind::AllowAlways,
+ acp_v2::PermissionOptionKind::AllowAlways,
),
- acp::PermissionOption::new(
- acp::PermissionOptionId::new(acp_thread::SandboxPermission::Deny.as_id()),
+ acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new(acp_thread::SandboxPermission::Deny.as_id()),
"Deny",
- acp::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionKind::RejectOnce,
),
]);
@@ -6441,11 +6405,7 @@ impl ToolCallEventStream {
// failure reason): it's critical the user can see what
// they're approving to run unsandboxed. The reason is
// surfaced separately by the fallback details / warning.
- tool_call: acp::ToolCallUpdate::new(
- acp::ToolCallId::new(tool_call_id.0.clone()),
- acp::ToolCallUpdateFields::new(),
- )
- .meta(
+ tool_call: acp_v2::ToolCallUpdate::new(tool_call_id.clone()).meta(
acp_thread::meta_with_sandbox_fallback_authorization(details),
),
options,
@@ -6529,19 +6489,19 @@ impl ToolCallEventStream {
&self,
title: Option<String>,
message: Option<String>,
- options: Vec<acp::PermissionOption>,
+ options: Vec<acp_v2::PermissionOption>,
cx: &mut App,
- ) -> Task<Result<acp::PermissionOptionId>> {
+ ) -> Task<Result<acp_v2::PermissionOptionId>> {
let options = acp_thread::PermissionOptions::Flat(options);
let stream = self.stream.clone();
let tool_call_id = self.tool_call_id.clone();
cx.spawn(async move |_cx| {
- let mut fields = acp::ToolCallUpdateFields::new();
+ let mut update = acp_v2::ToolCallUpdate::new(tool_call_id.clone());
if let Some(title) = title {
- fields = fields.title(title);
+ update = update.title(title);
}
if let Some(message) = message {
- fields = fields.content(vec![acp::ToolCallContent::from(message)]);
+ update = update.content(vec![acp_v2::ToolCallContent::from(message)]);
}
let (response_tx, response_rx) = oneshot::channel();
@@ -6550,10 +6510,7 @@ impl ToolCallEventStream {
.sender
.unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
ToolCallAuthorization {
- tool_call: acp::ToolCallUpdate::new(
- acp::ToolCallId::new(tool_call_id.0.clone()),
- fields,
- ),
+ tool_call: update,
options,
response: response_tx,
context: None,
@@ -6662,10 +6619,8 @@ impl ToolCallEventStream {
.sender
.unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
ToolCallAuthorization {
- tool_call: acp::ToolCallUpdate::new(
- acp::ToolCallId::new(tool_call_id.0.clone()),
- acp::ToolCallUpdateFields::new().title(title),
- ),
+ tool_call: acp_v2::ToolCallUpdate::new(tool_call_id.clone())
+ .title(title),
options,
response: response_tx,
context,
@@ -6878,13 +6833,11 @@ impl ToolCallEventStreamReceiver {
}
}
- pub async fn expect_update_fields(&mut self) -> acp::ToolCallUpdateFields {
+ pub async fn expect_update_fields(&mut self) -> acp_v2::ToolCallUpdate {
let event = self.0.next().await;
- if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(
- update,
- )))) = event
+ if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::V2(update)))) = event
{
- update.fields
+ update
} else {
panic!("Expected update fields but got: {:?}", event);
}
@@ -7040,6 +6993,7 @@ fn convert_image(image_content: acp::ImageContent) -> LanguageModelImage {
#[cfg(test)]
mod tests {
use super::*;
+ use agent_client_protocol::schema::MaybeUndefined;
use gpui::TestAppContext;
use language_model::LanguageModelToolUseId;
use language_model::fake_provider::FakeLanguageModelProvider;
@@ -7048,7 +7002,7 @@ mod tests {
use std::sync::Arc;
#[gpui::test]
- async fn test_tool_call_events_preserve_opaque_id_storage() {
+ async fn test_tool_call_events_preserve_opaque_id_storage(cx: &mut TestAppContext) {
let storage: Arc<str> = Arc::from(" call/雪:\"quoted\"\\opaque ");
let tool_call_id = acp_v2::ToolCallId::new(storage.clone());
let (sender, mut receiver) = mpsc::unbounded();
@@ -7058,38 +7012,110 @@ mod tests {
&tool_call_id,
"test_tool",
"Test tool".into(),
- acp::ToolKind::Other,
- json!({}),
+ acp_v2::ToolKind::Unknown("_native".into()),
+ json!(null),
);
- let ThreadEvent::ToolCall(tool_call) = receiver
+ let ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::V2(tool_call)) = receiver
.next()
.await
.expect("tool call event exists")
.expect("tool call event succeeded")
else {
- panic!("expected v1 tool call payload");
+ panic!("expected native tool call payload");
};
assert_eq!(tool_call.tool_call_id.0.as_ref(), storage.as_ref());
assert!(Arc::ptr_eq(&tool_call.tool_call_id.0, &storage));
-
- stream.update_tool_call_fields(&tool_call_id, acp::ToolCallUpdateFields::new(), None);
- let ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(update)) =
- receiver
- .next()
- .await
- .expect("update event exists")
- .expect("update event succeeded")
+ assert_eq!(tool_call.title, MaybeUndefined::Value("Test tool".into()));
+ assert_eq!(tool_call.name, MaybeUndefined::Value("test_tool".into()));
+ assert_eq!(
+ tool_call.kind,
+ MaybeUndefined::Value(acp_v2::ToolKind::Unknown("_native".into()))
+ );
+ assert_eq!(
+ tool_call.status,
+ MaybeUndefined::Value(acp_v2::ToolCallStatus::Pending)
+ );
+ assert_eq!(tool_call.raw_input, MaybeUndefined::Value(json!(null)));
+ assert!(tool_call.raw_output.is_undefined());
+ assert!(tool_call.content.is_undefined());
+ assert!(tool_call.locations.is_undefined());
+ assert!(tool_call.meta.is_undefined());
+
+ stream.update_tool_call_fields(&tool_call_id, |update| update);
+ let ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::V2(update)) = receiver
+ .next()
+ .await
+ .expect("update event exists")
+ .expect("update event succeeded")
else {
- panic!("expected v1 tool call update payload");
+ panic!("expected native tool call update payload");
};
assert_eq!(update.tool_call_id.0.as_ref(), storage.as_ref());
assert!(Arc::ptr_eq(&update.tool_call_id.0, &storage));
+ assert!(update.title.is_undefined());
+ assert!(update.name.is_undefined());
+ assert!(update.kind.is_undefined());
+ assert!(update.status.is_undefined());
+ assert!(update.content.is_undefined());
+ assert!(update.locations.is_undefined());
+ assert!(update.raw_input.is_undefined());
+ assert!(update.raw_output.is_undefined());
+ assert!(update.meta.is_undefined());
+
+ let (_cancellation_tx, cancellation_rx) = watch::channel(false);
+ let tool_stream = ToolCallEventStream::new(
+ "provider_id".into(),
+ tool_call_id.clone(),
+ stream.clone(),
+ None,
+ cancellation_rx,
+ Rc::default(),
+ None,
+ );
+ let authorize = cx.update(|cx| {
+ tool_stream.authorize_always_prompt(
+ "Confirm tool",
+ ToolPermissionContext::new("test_tool", vec![]),
+ cx,
+ )
+ });
+ let ThreadEvent::ToolCallAuthorization(authorization) = receiver
+ .next()
+ .await
+ .expect("authorization exists")
+ .expect("authorization succeeded")
+ else {
+ panic!("expected native authorization payload");
+ };
+ assert!(Arc::ptr_eq(
+ &authorization.tool_call.tool_call_id.0,
+ &storage
+ ));
+ assert_eq!(
+ authorization.tool_call.title,
+ MaybeUndefined::Value("Confirm tool".into())
+ );
+ assert!(authorization.tool_call.content.is_undefined());
+ assert_eq!(
+ authorization.kind,
+ acp_thread::AuthorizationKind::PermissionGrant
+ );
+ assert!(
+ authorization
+ .response
+ .send(acp_thread::SelectedPermissionOutcome::new(
+ acp_v2::PermissionOptionId::new("allow"),
+ acp_v2::PermissionOptionKind::AllowOnce,
+ ))
+ .is_ok()
+ );
+ authorize.await.expect("once-only approval succeeds");
stream.resolve_tool_call_authorization(
&tool_call_id,
acp_thread::SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("allow"),
- acp::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionId::new("allow"),
+ acp_v2::PermissionOptionKind::AllowOnce,
),
);
let ThreadEvent::ToolCallAuthorizationResolved { tool_call_id, .. } = receiver
@@ -7104,6 +7130,129 @@ mod tests {
assert!(Arc::ptr_eq(&tool_call_id.0, &storage));
}
+ #[gpui::test]
+ async fn test_native_tool_updates_preserve_source_fields() {
+ let (stream, mut receiver) = ToolCallEventStream::test();
+ let meta = acp_v2::Meta::from_iter([("extension".into(), json!({"opaque": null}))]);
+ let content = vec![acp_v2::ToolCallContent::Content(Box::new(
+ acp_v2::Content::new(acp_v2::ContentBlock::Image(
+ acp_v2::ImageContent::new("image payload", "image/png").meta(meta.clone()),
+ ))
+ .meta(meta.clone()),
+ ))];
+ let locations = vec![
+ acp_v2::ToolCallLocation::new(PathBuf::from("/repo/雪.rs"))
+ .line(7)
+ .meta(meta.clone()),
+ ];
+ stream.update_fields(|update| {
+ update
+ .kind(acp_v2::ToolKind::Unknown("_native".into()))
+ .status(acp_v2::ToolCallStatus::Other("_paused".into()))
+ .content(content.clone())
+ .locations(locations.clone())
+ .raw_input(json!(null))
+ .raw_output(json!(null))
+ .meta(meta.clone())
+ });
+ let ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::V2(update)) = receiver
+ .next()
+ .await
+ .expect("native update exists")
+ .expect("native update succeeded")
+ else {
+ panic!("expected native tool call update");
+ };
+ assert!(Arc::ptr_eq(
+ &update.tool_call_id.0,
+ &stream.tool_call_id().0
+ ));
+ assert_eq!(
+ update.kind,
+ MaybeUndefined::Value(acp_v2::ToolKind::Unknown("_native".into()))
+ );
+ assert_eq!(
+ update.status,
+ MaybeUndefined::Value(acp_v2::ToolCallStatus::Other("_paused".into()))
+ );
+ assert_eq!(update.content, MaybeUndefined::Value(content));
+ assert_eq!(update.locations, MaybeUndefined::Value(locations));
+ assert_eq!(update.raw_input, MaybeUndefined::Value(json!(null)));
+ assert_eq!(update.raw_output, MaybeUndefined::Value(json!(null)));
+ assert_eq!(update.meta, MaybeUndefined::Value(meta));
+ assert!(update.title.is_undefined());
+
+ stream.update_fields(|update| update.meta(MaybeUndefined::Null));
+ assert!(receiver.expect_update_fields().await.meta.is_null());
+
+ stream.update_fields(|_| acp_v2::ToolCallUpdate::new("another_tool_call"));
+ let update = receiver.expect_update_fields().await;
+ assert_eq!(update.tool_call_id, *stream.tool_call_id());
+ assert!(update.meta.is_undefined());
+ }
+
+ #[gpui::test]
+ async fn test_native_decision_prompt_preserves_action_choice_and_interruption(
+ cx: &mut TestAppContext,
+ ) {
+ let (stream, mut receiver) = ToolCallEventStream::test();
+ for option_id in ["discard", FOLLOW_UP_PERMISSION_DENIED_OPTION_ID] {
+ let decision = cx.update(|cx| {
+ stream.prompt_for_decision(
+ None,
+ Some("Choose an action".into()),
+ vec![acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new("discard"),
+ "Discard",
+ acp_v2::PermissionOptionKind::RejectOnce,
+ )],
+ cx,
+ )
+ });
+ let authorization = receiver.expect_authorization().await;
+ assert!(Arc::ptr_eq(
+ &authorization.tool_call.tool_call_id.0,
+ &stream.tool_call_id().0
+ ));
+ assert!(authorization.tool_call.title.is_undefined());
+ assert!(authorization.tool_call.status.is_undefined());
+ assert_eq!(
+ authorization.tool_call.content,
+ MaybeUndefined::Value(vec![acp_v2::ToolCallContent::from("Choose an action")])
+ );
+ assert_eq!(
+ authorization.kind,
+ acp_thread::AuthorizationKind::ActionChoice
+ );
+ assert!(
+ authorization
+ .response
+ .send(acp_thread::SelectedPermissionOutcome::new(
+ acp_v2::PermissionOptionId::new(option_id),
+ acp_v2::PermissionOptionKind::RejectOnce,
+ ))
+ .is_ok()
+ );
+ let result = decision.await;
+ if option_id == FOLLOW_UP_PERMISSION_DENIED_OPTION_ID {
+ assert_eq!(
+ result
+ .expect_err("follow-up interrupts decision")
+ .to_string(),
+ TOOL_CALL_INTERRUPTED_BY_FOLLOW_UP_MESSAGE
+ );
+ } else {
+ assert_eq!(
+ result
+ .expect("action choice is not a permission denial")
+ .0
+ .as_ref(),
+ "discard"
+ );
+ }
+ }
+ }
+
#[test]
fn compaction_capacity_respects_prompt_and_combined_limits() {
assert_eq!(
@@ -8524,8 +8673,8 @@ mod tests {
const NAME: &'static str = "registered_image_tool";
- fn kind() -> acp::ToolKind {
- acp::ToolKind::Other
+ fn kind() -> acp_v2::ToolKind {
+ acp_v2::ToolKind::Other
}
fn initial_title(
@@ -8573,15 +8722,21 @@ mod tests {
)
});
let authorization = receiver.expect_authorization().await;
- let details =
- acp_thread::sandbox_authorization_details_from_meta(&authorization.tool_call.meta)
- .expect("sandbox authorization should include request details");
+ let details = acp_thread::sandbox_authorization_details_from_meta(
+ &authorization.tool_call.meta.value().cloned(),
+ )
+ .expect("sandbox authorization should include request details");
assert!(details.network_hosts.is_empty());
assert!(!details.network_all_hosts);
assert_eq!(details.allow_fs_write_all, request.allow_fs_write_all);
assert_eq!(details.unsandboxed, request.unsandboxed);
assert_eq!(details.write_paths, request.write_paths);
- assert!(authorization.tool_call.fields.content.is_none());
+ assert!(authorization.tool_call.title.is_undefined());
+ assert!(authorization.tool_call.content.is_undefined());
+ assert_eq!(
+ authorization.kind,
+ acp_thread::AuthorizationKind::PermissionGrant
+ );
let acp_thread::PermissionOptions::Flat(options) = &authorization.options else {
panic!("expected flat sandbox permission options");
@@ -8592,33 +8747,37 @@ mod tests {
(
option.option_id.0.as_ref(),
option.name.as_ref(),
- option.kind,
+ option.kind.clone(),
)
})
.collect::<Vec<_>>();
assert_eq!(
options,
vec![
- ("allow", "Allow once", acp::PermissionOptionKind::AllowOnce),
+ (
+ "allow",
+ "Allow once",
+ acp_v2::PermissionOptionKind::AllowOnce
+ ),
(
"allow_thread",
"Allow for this thread",
- acp::PermissionOptionKind::AllowAlways,
+ acp_v2::PermissionOptionKind::AllowAlways,
),
(
"allow_always",
"Allow always",
- acp::PermissionOptionKind::AllowAlways,
+ acp_v2::PermissionOptionKind::AllowAlways,
),
- ("deny", "Deny", acp::PermissionOptionKind::RejectOnce),
+ ("deny", "Deny", acp_v2::PermissionOptionKind::RejectOnce),
]
);
let send_result = authorization
.response
.send(acp_thread::SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("allow_always"),
- acp::PermissionOptionKind::AllowAlways,
+ acp_v2::PermissionOptionId::new("allow_always"),
+ acp_v2::PermissionOptionKind::AllowAlways,
));
assert!(send_result.is_ok());
authorize.await.unwrap();
@@ -8652,7 +8811,7 @@ mod tests {
});
let authorization = receiver.expect_authorization().await;
let details = acp_thread::sandbox_fallback_authorization_details_from_meta(
- &authorization.tool_call.meta,
+ &authorization.tool_call.meta.value().cloned(),
)
.expect("fallback authorization should include details");
assert_eq!(details.command.as_deref(), Some("cargo build"));
@@ -8661,6 +8820,12 @@ mod tests {
details.docs_section.as_deref(),
Some("installing-bubblewrap")
);
+ assert!(authorization.tool_call.title.is_undefined());
+ assert!(authorization.tool_call.content.is_undefined());
+ assert_eq!(
+ authorization.kind,
+ acp_thread::AuthorizationKind::ActionChoice
+ );
let acp_thread::PermissionOptions::Flat(options) = &authorization.options else {
panic!("expected flat fallback permission options");
@@ -8683,8 +8848,8 @@ mod tests {
authorization
.response
.send(acp_thread::SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new(acp_thread::SANDBOX_FALLBACK_RETRY_OPTION_ID),
- acp::PermissionOptionKind::RejectAlways,
+ acp_v2::PermissionOptionId::new(acp_thread::SANDBOX_FALLBACK_RETRY_OPTION_ID),
+ acp_v2::PermissionOptionKind::RejectAlways,
))
.unwrap();
assert_eq!(authorize.await.unwrap(), SandboxFallbackDecision::Retry);
@@ -8721,8 +8886,8 @@ mod tests {
authorization
.response
.send(acp_thread::SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new(acp_thread::SANDBOX_FALLBACK_RETRY_OPTION_ID),
- acp::PermissionOptionKind::RejectAlways,
+ acp_v2::PermissionOptionId::new(acp_thread::SANDBOX_FALLBACK_RETRY_OPTION_ID),
+ acp_v2::PermissionOptionKind::RejectAlways,
))
.unwrap();
authorize.await.unwrap();
@@ -8755,8 +8920,8 @@ mod tests {
authorization
.response
.send(acp_thread::SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new(acp_thread::SandboxPermission::AllowThread.as_id()),
- acp::PermissionOptionKind::AllowAlways,
+ acp_v2::PermissionOptionId::new(acp_thread::SandboxPermission::AllowThread.as_id()),
+ acp_v2::PermissionOptionKind::AllowAlways,
))
.unwrap();
assert_eq!(
@@ -8788,8 +8953,8 @@ mod tests {
authorization
.response
.send(acp_thread::SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new(acp_thread::SandboxPermission::Deny.as_id()),
- acp::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionId::new(acp_thread::SandboxPermission::Deny.as_id()),
+ acp_v2::PermissionOptionKind::RejectOnce,
))
.unwrap();
assert_eq!(authorize.await.unwrap(), SandboxFallbackDecision::Deny);
@@ -8820,16 +8985,17 @@ mod tests {
&authorization.tool_call.tool_call_id.0,
&event_stream.tool_call_id().0,
));
- let details =
- acp_thread::sandbox_authorization_details_from_meta(&authorization.tool_call.meta)
- .expect("warning authorization should include sandbox details");
+ let details = acp_thread::sandbox_authorization_details_from_meta(
+ &authorization.tool_call.meta.value().cloned(),
+ )
+ .expect("warning authorization should include sandbox details");
assert!(details.warn_windows_fs);
authorization
.response
.send(acp_thread::SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new(acp_thread::SandboxPermission::AllowOnce.as_id()),
- acp::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionId::new(acp_thread::SandboxPermission::AllowOnce.as_id()),
+ acp_v2::PermissionOptionKind::AllowOnce,
))
.unwrap();
authorize.await.unwrap();
@@ -8839,28 +9005,28 @@ mod tests {
fn test_auto_resolve_permission_outcome_uses_once_only_options() {
let options = acp_thread::PermissionOptions::Dropdown(vec![
acp_thread::PermissionOptionChoice {
- allow: acp::PermissionOption::new(
- acp::PermissionOptionId::new("always_allow:test_tool"),
+ allow: acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new("always_allow:test_tool"),
"Always allow",
- acp::PermissionOptionKind::AllowAlways,
+ acp_v2::PermissionOptionKind::AllowAlways,
),
- deny: acp::PermissionOption::new(
- acp::PermissionOptionId::new("always_deny:test_tool"),
+ deny: acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new("always_deny:test_tool"),
"Always deny",
- acp::PermissionOptionKind::RejectAlways,
+ acp_v2::PermissionOptionKind::RejectAlways,
),
sub_patterns: vec![],
},
acp_thread::PermissionOptionChoice {
- allow: acp::PermissionOption::new(
- acp::PermissionOptionId::new("allow"),
+ allow: acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new("allow"),
"Allow once",
- acp::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
),
- deny: acp::PermissionOption::new(
- acp::PermissionOptionId::new("deny"),
+ deny: acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new("deny"),
"Deny once",
- acp::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionKind::RejectOnce,
),
sub_patterns: vec![],
},
@@ -8868,13 +9034,13 @@ mod tests {
let allow = auto_resolve_permission_outcome(&options, true)
.expect("allow auto-resolve should use once-only option");
- assert_eq!(allow.option_id, acp::PermissionOptionId::new("allow"));
- assert_eq!(allow.option_kind, acp::PermissionOptionKind::AllowOnce);
+ assert_eq!(allow.option_id, acp_v2::PermissionOptionId::new("allow"));
+ assert_eq!(allow.option_kind, acp_v2::PermissionOptionKind::AllowOnce);
let deny = auto_resolve_permission_outcome(&options, false)
.expect("deny auto-resolve should use once-only option");
- assert_eq!(deny.option_id, acp::PermissionOptionId::new("deny"));
- assert_eq!(deny.option_kind, acp::PermissionOptionKind::RejectOnce);
+ assert_eq!(deny.option_id, acp_v2::PermissionOptionId::new("deny"));
+ assert_eq!(deny.option_kind, acp_v2::PermissionOptionKind::RejectOnce);
}
#[test]
@@ -9080,46 +9246,69 @@ mod tests {
let registered_tool_call_id = scoped_tool_call_id(0, &registered_tool_use_id).to_string();
let missing_tool_call_id = scoped_tool_call_id(0, &missing_tool_use_id).to_string();
let mut tool_names_by_id = HashMap::default();
- let mut tool_use_ids_with_image_content = HashSet::default();
+ let mut raw_inputs_by_id = HashMap::default();
+ let mut content_by_id = HashMap::default();
+ let mut statuses_by_id = HashMap::default();
while let Some(event) = replay_events.next().await {
let event = event.unwrap();
match event {
- ThreadEvent::ToolCall(tool_call) => {
- tool_names_by_id.insert(tool_call.tool_call_id.to_string(), tool_call.name);
- }
- ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(update))
- if update.fields.content.as_ref().is_some_and(|content| {
- content.iter().any(|content| {
- matches!(
- content,
- acp::ToolCallContent::Content(acp::Content {
- content: acp::ContentBlock::Image(_),
- ..
- })
- )
- })
- }) =>
- {
- tool_use_ids_with_image_content.insert(update.tool_call_id.to_string());
+ ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::V2(update)) => {
+ if let MaybeUndefined::Value(name) = update.name {
+ tool_names_by_id.insert(update.tool_call_id.to_string(), name);
+ }
+ if let MaybeUndefined::Value(input) = update.raw_input {
+ raw_inputs_by_id.insert(update.tool_call_id.to_string(), input);
+ }
+ if let MaybeUndefined::Value(content) = update.content {
+ content_by_id.insert(update.tool_call_id.to_string(), content);
+ }
+ if let MaybeUndefined::Value(status) = update.status {
+ statuses_by_id.insert(update.tool_call_id.to_string(), status);
+ }
}
_ => {}
}
}
- // Both tool uses live in the message pushed above, at index 0 (see
- // `scoped_tool_call_id`).
- assert!(tool_use_ids_with_image_content.contains(&registered_tool_call_id));
- assert!(tool_use_ids_with_image_content.contains(&missing_tool_call_id));
+ let image_content = acp_v2::ToolCallContent::from(acp_v2::ContentBlock::Image(
+ acp_v2::ImageContent::new(image_data, "image/png"),
+ ));
+ assert_eq!(
+ content_by_id.get(&registered_tool_call_id),
+ Some(&vec![
+ acp_v2::ToolCallContent::from("before"),
+ image_content.clone(),
+ acp_v2::ToolCallContent::from("after"),
+ ])
+ );
+ assert_eq!(
+ content_by_id.get(&missing_tool_call_id),
+ Some(&vec![image_content])
+ );
+ for tool_call_id in [&registered_tool_call_id, &missing_tool_call_id] {
+ assert_eq!(
+ statuses_by_id.get(tool_call_id),
+ Some(&acp_v2::ToolCallStatus::Completed)
+ );
+ }
+ assert_eq!(
+ raw_inputs_by_id.get(&registered_tool_call_id),
+ Some(&json!(null))
+ );
+ assert_eq!(
+ raw_inputs_by_id.get(&missing_tool_call_id),
+ Some(&json!({}))
+ );
assert_eq!(
tool_names_by_id
.get(&registered_tool_call_id)
- .and_then(Option::as_deref),
+ .map(String::as_str),
Some(ReplayImageTool::NAME)
);
assert_eq!(
tool_names_by_id
.get(&missing_tool_call_id)
- .and_then(Option::as_deref),
+ .map(String::as_str),
Some("missing_image_tool")
);
}
diff --git a/crates/agent/src/tools/apply_code_action_tool.rs b/crates/agent/src/tools/apply_code_action_tool.rs
index aa3d5ac18bf..039b1ee73d6 100644
--- a/crates/agent/src/tools/apply_code_action_tool.rs
+++ b/crates/agent/src/tools/apply_code_action_tool.rs
@@ -1,7 +1,7 @@
use std::fmt::Write;
use std::sync::Arc;
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp;
use gpui::{App, Entity, SharedString, Task};
use project::Project;
use schemars::JsonSchema;
diff --git a/crates/agent/src/tools/ask_user_tool.rs b/crates/agent/src/tools/ask_user_tool.rs
index 69fc9d415f9..5361d60064c 100644
--- a/crates/agent/src/tools/ask_user_tool.rs
+++ b/crates/agent/src/tools/ask_user_tool.rs
@@ -2,7 +2,6 @@ use std::collections::BTreeMap;
use std::sync::Arc;
use crate::{AgentTool, ToolCallEventStream, ToolInput};
-use agent_client_protocol::schema::v1 as acp;
use agent_client_protocol::schema::v2 as acp_v2;
use anyhow::Result;
use gpui::{App, SharedString, Task};
@@ -75,8 +74,8 @@ impl AgentTool for AskUserTool {
const NAME: &'static str = "ask_user";
- fn kind() -> acp::ToolKind {
- acp::ToolKind::Other
+ fn kind() -> acp_v2::ToolKind {
+ acp_v2::ToolKind::Other
}
fn initial_title(
@@ -149,9 +148,7 @@ impl AgentTool for AskUserTool {
}
};
- event_stream.update_fields(
- acp::ToolCallUpdateFields::new().title(format!("Answered: {selected}")),
- );
+ event_stream.update_fields(|update| update.title(format!("Answered: {selected}")));
Ok(AskUserToolOutput::Answered { selected })
})
diff --git a/crates/agent/src/tools/context_server_registry.rs b/crates/agent/src/tools/context_server_registry.rs
index 9fd027a10bd..d7b307fca79 100644
--- a/crates/agent/src/tools/context_server_registry.rs
+++ b/crates/agent/src/tools/context_server_registry.rs
@@ -1,5 +1,5 @@
use crate::{AgentToolOutput, AnyAgentTool, ToolCallEventStream, ToolInput};
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp;
use anyhow::Result;
use collections::{BTreeMap, HashMap};
use context_server::{ContextServerId, client::NotificationSubscription};
@@ -403,18 +403,18 @@ impl AnyAgentTool for ContextServerTool {
match content {
context_server::types::ToolResponseContent::Text { text } => {
concatenated_text.push_str(&text);
- tool_call_content.push(acp::ToolCallContent::Content(acp::Content::new(
+ tool_call_content.push(acp::ToolCallContent::from(
acp::ContentBlock::Text(acp::TextContent::new(text.clone())),
- )));
+ ));
llm_output.push(LanguageModelToolResultContent::Text(text.into()));
}
context_server::types::ToolResponseContent::Image { data, mime_type } => {
- tool_call_content.push(acp::ToolCallContent::Content(acp::Content::new(
+ tool_call_content.push(acp::ToolCallContent::from(
acp::ContentBlock::Image(acp::ImageContent::new(
data.clone(),
mime_type.clone(),
)),
- )));
+ ));
let language_model_image = cx
.background_spawn({
let mime_type = mime_type.clone();
@@ -455,7 +455,7 @@ impl AnyAgentTool for ContextServerTool {
}
if !tool_call_content.is_empty() {
event_stream
- .update_fields(acp::ToolCallUpdateFields::new().content(tool_call_content));
+ .update_fields(|update| update.content(tool_call_content));
}
let raw_output = serde_json::Value::String(concatenated_text);
Ok(AgentToolOutput {
diff --git a/crates/agent/src/tools/copy_path_tool.rs b/crates/agent/src/tools/copy_path_tool.rs
index 1730da89669..c2f1fdfde97 100644
--- a/crates/agent/src/tools/copy_path_tool.rs
+++ b/crates/agent/src/tools/copy_path_tool.rs
@@ -7,7 +7,7 @@ use crate::{
AgentTool, ToolCallEventStream, ToolInput, ToolPermissionDecision,
authorize_with_sensitive_settings, decide_permission_for_paths,
};
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp;
use agent_settings::AgentSettings;
use futures::FutureExt as _;
use gpui::{App, Entity, Task};
@@ -323,7 +323,11 @@ mod tests {
});
let auth = event_rx.expect_authorization().await;
- let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
+ let title = auth
+ .tool_call
+ .title
+ .value()
+ .expect("expected authorization title");
assert!(
title.contains("agent skills"),
"Authorization title should mention agent skills, got: {title}",
@@ -389,7 +393,11 @@ mod tests {
});
let auth = event_rx.expect_authorization().await;
- let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
+ let title = auth
+ .tool_call
+ .title
+ .value()
+ .expect("expected authorization title");
assert!(
title.contains("agent skills"),
"Authorization title should mention agent skills, got: {title}",
@@ -461,7 +469,11 @@ mod tests {
let task = cx.update(|cx| tool.run(ToolInput::resolved(input), event_stream, cx));
let auth = event_rx.expect_authorization().await;
- let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
+ let title = auth
+ .tool_call
+ .title
+ .value()
+ .expect("expected authorization title");
assert!(
title.contains("points outside the project")
|| title.contains("symlinks outside project"),
@@ -570,7 +582,11 @@ mod tests {
let task = cx.update(|cx| tool.run(ToolInput::resolved(input), event_stream, cx));
let auth = event_rx.expect_authorization().await;
- let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
+ let title = auth
+ .tool_call
+ .title
+ .value()
+ .expect("expected authorization title");
assert!(
title.contains("points outside the project")
|| title.contains("symlinks outside project"),
diff --git a/crates/agent/src/tools/create_directory_tool.rs b/crates/agent/src/tools/create_directory_tool.rs
index 9871d2bf77b..329b0ed2668 100644
--- a/crates/agent/src/tools/create_directory_tool.rs
+++ b/crates/agent/src/tools/create_directory_tool.rs
@@ -2,7 +2,7 @@ use super::tool_permissions::{
authorize_symlink_access, canonicalize_worktree_roots, detect_symlink_escape,
resolve_creatable_global_skill_path, sensitive_settings_kind,
};
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp;
use agent_settings::AgentSettings;
use futures::FutureExt as _;
use gpui::{App, AppContext as _, AsyncApp, Entity, SharedString, Task};
@@ -388,7 +388,11 @@ mod tests {
});
let auth = event_rx.expect_authorization().await;
- let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
+ let title = auth
+ .tool_call
+ .title
+ .value()
+ .expect("expected authorization title");
assert!(
title.contains("agent skills"),
"Authorization title should mention agent skills, got: {title}",
@@ -501,7 +505,11 @@ mod tests {
});
let auth = event_rx.expect_authorization().await;
- let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
+ let title = auth
+ .tool_call
+ .title
+ .value()
+ .expect("expected authorization title");
assert!(
title.contains("points outside the project") || title.contains("symlink"),
"Authorization title should mention symlink escape, got: {title}",
@@ -624,7 +632,11 @@ mod tests {
});
let auth = event_rx.expect_authorization().await;
- let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
+ let title = auth
+ .tool_call
+ .title
+ .value()
+ .expect("expected authorization title");
assert!(
title.contains("points outside the project") || title.contains("symlink"),
"Authorization title should mention symlink escape, got: {title}",
@@ -751,8 +763,10 @@ mod tests {
});
let auth = event_rx.expect_authorization().await;
- let details = acp_thread::sandbox_authorization_details_from_meta(&auth.tool_call.meta)
- .expect("out-of-project create should request a sandbox write grant");
+ let details = acp_thread::sandbox_authorization_details_from_meta(
+ &auth.tool_call.meta.clone().take(),
+ )
+ .expect("out-of-project create should request a sandbox write grant");
// The grant is for exactly the new directory, not its parent, and
// carries the resolved canonical established when it was created.
let expected_canonical = scratch.path().canonicalize().unwrap().join("new_grant_dir");
diff --git a/crates/agent/src/tools/create_thread_tool.rs b/crates/agent/src/tools/create_thread_tool.rs
index 6d7dfdb99b8..b63471d1699 100644
--- a/crates/agent/src/tools/create_thread_tool.rs
+++ b/crates/agent/src/tools/create_thread_tool.rs
@@ -1,4 +1,4 @@
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp;
use anyhow::Result;
use gpui::{App, SharedString, Task};
use language_model::LanguageModelToolResultContent;
diff --git a/crates/agent/src/tools/delete_path_tool.rs b/crates/agent/src/tools/delete_path_tool.rs
index 0f837e5144e..3cec50c9a3b 100644
--- a/crates/agent/src/tools/delete_path_tool.rs
+++ b/crates/agent/src/tools/delete_path_tool.rs
@@ -7,7 +7,7 @@ use crate::{
authorize_with_sensitive_settings, decide_permission_for_path,
};
use action_log::ActionLog;
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp;
use agent_settings::AgentSettings;
use futures::{FutureExt as _, SinkExt, StreamExt, channel::mpsc};
use gpui::{App, AppContext, Entity, SharedString, Task};
@@ -322,7 +322,11 @@ mod tests {
});
let auth = event_rx.expect_authorization().await;
- let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
+ let title = auth
+ .tool_call
+ .title
+ .value()
+ .expect("expected authorization title");
assert!(
title.contains("agent skills"),
"Authorization title should mention agent skills, got: {title}",
@@ -479,7 +483,11 @@ mod tests {
});
let auth = event_rx.expect_authorization().await;
- let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
+ let title = auth
+ .tool_call
+ .title
+ .value()
+ .expect("expected authorization title");
assert!(
title.contains("points outside the project") || title.contains("symlink"),
"Authorization title should mention symlink escape, got: {title}",
@@ -609,7 +617,11 @@ mod tests {
});
let auth = event_rx.expect_authorization().await;
- let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
+ let title = auth
+ .tool_call
+ .title
+ .value()
+ .expect("expected authorization title");
assert!(
title.contains("points outside the project") || title.contains("symlink"),
"Authorization title should mention symlink escape, got: {title}",
diff --git a/crates/agent/src/tools/diagnostics_tool.rs b/crates/agent/src/tools/diagnostics_tool.rs
index ea5bdd8e71d..ecd86007e68 100644
--- a/crates/agent/src/tools/diagnostics_tool.rs
+++ b/crates/agent/src/tools/diagnostics_tool.rs
@@ -1,5 +1,5 @@
use crate::{AgentTool, ToolCallEventStream, ToolInput};
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp;
use futures::{Future, FutureExt as _};
use gpui::{App, AsyncApp, Entity, Task};
use language::{DiagnosticSeverity, OffsetRangeExt};
diff --git a/crates/agent/src/tools/edit_file_tool.rs b/crates/agent/src/tools/edit_file_tool.rs
index b46e5662d51..e8b3a7cd0e1 100644
--- a/crates/agent/src/tools/edit_file_tool.rs
+++ b/crates/agent/src/tools/edit_file_tool.rs
@@ -7,7 +7,7 @@ use super::edit_session::{
};
use crate::{AgentTool, Thread, ToolCallEventStream, ToolInput, ToolInputPayload};
use action_log::ActionLog;
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp;
use anyhow::Result;
use futures::FutureExt as _;
use gpui::{App, AsyncApp, Entity, Task, WeakEntity};
@@ -287,6 +287,7 @@ impl AgentTool for EditFileTool {
mod tests {
use super::*;
use crate::{ContextServerRegistry, Templates, ToolInputSender};
+ use agent_client_protocol::schema::MaybeUndefined;
use fs::Fs as _;
use gpui::{AppContext as _, TestAppContext, UpdateGlobal};
use language_model::LanguageModelRegistry;
@@ -652,7 +653,11 @@ mod tests {
event_rx.expect_update_fields().await;
let auth = event_rx.expect_authorization().await;
- let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
+ let title = auth
+ .tool_call
+ .title
+ .value()
+ .expect("expected authorization title");
assert!(
title.contains("agent skills"),
"Authorization title should mention agent skills, got: {title}",
@@ -737,18 +742,17 @@ mod tests {
) -> Option<String> {
use futures::StreamExt as _;
while let Some(event) = receiver.next().await {
- let Ok(crate::ThreadEvent::ToolCallUpdate(
- acp_thread::ToolCallUpdate::UpdateFields(update),
- )) = event
+ let Ok(crate::ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::V2(update))) =
+ event
else {
continue;
};
- let Some(content) = update.fields.content else {
+ let Some(content) = update.content.take() else {
continue;
};
for item in content {
- if let acp::ToolCallContent::Content(c) = item
- && let acp::ContentBlock::Text(text) = c.content
+ if let acp::ToolCallContent::Content(content) = item
+ && let acp::ContentBlock::Text(text) = content.content
{
return Some(text.text);
}
@@ -1491,8 +1495,8 @@ mod tests {
let event = stream_rx.expect_authorization().await;
assert_eq!(
- event.tool_call.fields.title,
- Some("Edit `.zed/settings.json` (local settings)".into())
+ event.tool_call.title,
+ MaybeUndefined::Value("Edit `.zed/settings.json` (local settings)".into())
);
// Test 2: Path outside project should require confirmation
@@ -1502,8 +1506,8 @@ mod tests {
let event = stream_rx.expect_authorization().await;
assert_eq!(
- event.tool_call.fields.title,
- Some("Edit `/etc/hosts`".into())
+ event.tool_call.title,
+ MaybeUndefined::Value("Edit `/etc/hosts`".into())
);
// Test 3: Relative path without .zed should not require confirmation
@@ -1520,8 +1524,8 @@ mod tests {
});
let event = stream_rx.expect_authorization().await;
assert_eq!(
- event.tool_call.fields.title,
- Some("Edit `root/.zed/tasks.json` (local settings)".into())
+ event.tool_call.title,
+ MaybeUndefined::Value("Edit `root/.zed/tasks.json` (local settings)".into())
);
// Test 5: When global default is allow, sensitive and outside-project
@@ -1538,8 +1542,8 @@ mod tests {
.update(|cx| edit_tool.authorize(&PathBuf::from(".zed/settings.json"), &stream_tx, cx));
let event = stream_rx.expect_authorization().await;
assert_eq!(
- event.tool_call.fields.title,
- Some("Edit `.zed/settings.json` (local settings)".into())
+ event.tool_call.title,
+ MaybeUndefined::Value("Edit `.zed/settings.json` (local settings)".into())
);
// 5.2: /etc/hosts is outside the project, but Allow auto-approves
@@ -1569,8 +1573,8 @@ mod tests {
let event = stream_rx.expect_authorization().await;
assert_eq!(
- event.tool_call.fields.title,
- Some("Edit `/etc/hosts`".into())
+ event.tool_call.title,
+ MaybeUndefined::Value("Edit `/etc/hosts`".into())
);
// 5.5: .agents/skills is a sensitive path — still prompts. The
@@ -1587,8 +1591,10 @@ mod tests {
});
let event = stream_rx.expect_authorization().await;
assert_eq!(
- event.tool_call.fields.title,
- Some("Edit `root/.agents/skills/my-skill/SKILL.md` (agent skills)".into())
+ event.tool_call.title,
+ MaybeUndefined::Value(
+ "Edit `root/.agents/skills/my-skill/SKILL.md` (agent skills)".into()
+ )
);
// Skills always prompt, so no "Always allow" option is offered.
assert!(
@@ -1615,9 +1621,8 @@ mod tests {
assert!(
event
.tool_call
- .fields
.title
- .as_deref()
+ .value()
.is_some_and(|title| title.ends_with("(agent skills)"))
);
}
@@ -1656,12 +1661,11 @@ mod tests {
assert!(
event
.tool_call
- .fields
.title
- .as_deref()
+ .value()
.is_some_and(|title| title.ends_with("(agent skills)")),
"`..` traversal into .agents/skills must still prompt: {:?}",
- event.tool_call.fields.title,
+ event.tool_call.title,
);
}
@@ -1695,12 +1699,11 @@ mod tests {
assert!(
event
.tool_call
- .fields
.title
- .as_deref()
+ .value()
.is_some_and(|title| title.ends_with("(local settings)")),
"`..` traversal into .zed must still prompt: {:?}",
- event.tool_call.fields.title,
+ event.tool_call.title,
);
}
@@ -1738,12 +1741,11 @@ mod tests {
assert!(
event
.tool_call
- .fields
.title
- .as_deref()
+ .value()
.is_some_and(|title| title.ends_with("(local settings)")),
"Intra-project symlink to .zed must still prompt: {:?}",
- event.tool_call.fields.title,
+ event.tool_call.title,
);
}
@@ -1781,12 +1783,11 @@ mod tests {
assert!(
event
.tool_call
- .fields
.title
- .as_deref()
+ .value()
.is_some_and(|title| title.ends_with("(agent skills)")),
"Intra-project symlink to .agents/skills must still prompt: {:?}",
- event.tool_call.fields.title,
+ event.tool_call.title,
);
}
@@ -1816,9 +1817,8 @@ mod tests {
assert!(
event
.tool_call
- .fields
.title
- .as_deref()
+ .value()
.is_some_and(|title| title.contains("points outside the project")),
"Expected symlink escape authorization for create under external symlink"
);
@@ -1873,7 +1873,11 @@ mod tests {
});
let auth = stream_rx.expect_authorization().await;
- let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
+ let title = auth
+ .tool_call
+ .title
+ .value()
+ .expect("expected authorization title");
assert!(
title.contains("points outside the project"),
"title should mention symlink escape, got: {title}"
@@ -2547,7 +2551,11 @@ mod tests {
let _update = stream_rx.expect_update_fields().await;
let auth = stream_rx.expect_authorization().await;
- let content = auth.tool_call.fields.content.as_deref().unwrap_or(&[]);
+ let content = auth
+ .tool_call
+ .content
+ .value()
+ .expect("expected authorization content");
let acp::ToolCallContent::Content(text) = content.first().expect("expected message body")
else {
panic!("expected text body, got: {:?}", content.first());
diff --git a/crates/agent/src/tools/edit_session.rs b/crates/agent/src/tools/edit_session.rs
index 4d0d77b1d27..063bcf84e41 100644
--- a/crates/agent/src/tools/edit_session.rs
+++ b/crates/agent/src/tools/edit_session.rs
@@ -6,7 +6,7 @@ use super::tool_permissions::resolve_creatable_global_skill_path;
use crate::{Thread, ToolCallEventStream};
use acp_thread::Diff;
use action_log::ActionLog;
-use agent_client_protocol::schema::v1::{self as acp, ToolCallLocation, ToolCallUpdateFields};
+use agent_client_protocol::schema::v2 as acp;
use anyhow::Result;
use collections::HashSet;
use futures::{FutureExt, channel::oneshot};
@@ -301,9 +301,7 @@ pub(crate) async fn run_session(
.await;
let (_new_text, diff) = session.compute_new_text_and_diff(cx).await;
if diff.is_empty() {
- event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![
- acp::ToolCallContent::Content(acp::Content::new(error.clone())),
- ]));
+ event_stream.update_fields(|update| update.content(vec![error.clone().into()]));
}
Err(EditSessionOutput::Error {
error,
@@ -315,9 +313,7 @@ pub(crate) async fn run_session(
error,
session: None,
} => {
- event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![
- acp::ToolCallContent::Content(acp::Content::new(error.clone())),
- ]));
+ event_stream.update_fields(|update| update.content(vec![error.clone().into()]));
Err(EditSessionOutput::Error {
error,
input_path: None,
@@ -532,10 +528,9 @@ impl EditPipeline {
let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
let line = snapshot.offset_to_point(range.start).row;
- event_stream.update_fields(
- ToolCallUpdateFields::new()
- .locations(vec![ToolCallLocation::new(abs_path).line(Some(line))]),
- );
+ event_stream.update_fields(|update| {
+ update.locations(vec![acp::ToolCallLocation::new(abs_path).line(Some(line))])
+ });
let buffer_indent = snapshot.line_indent_for_row(line);
let query_lines = matcher.query_lines();
@@ -721,9 +716,9 @@ impl EditSession {
project_path,
} = target;
- event_stream.update_fields(
- ToolCallUpdateFields::new().locations(vec![ToolCallLocation::new(abs_path.clone())]),
- );
+ event_stream.update_fields(|update| {
+ update.locations(vec![acp::ToolCallLocation::new(abs_path.clone())])
+ });
cx.update(|cx| context.authorize(tool_name, &path, event_stream, cx))
.await
@@ -1154,9 +1149,7 @@ async fn resolve_dirty_buffer(
was cancelled. Ask the user how they'd like to proceed before \
retrying."
.to_string();
- event_stream.update_fields(
- acp::ToolCallUpdateFields::new().content(vec![error.clone().into()]),
- );
+ event_stream.update_fields(|update| update.content(vec![error.clone().into()]));
return Err(error);
}
}
diff --git a/crates/agent/src/tools/fetch_tool.rs b/crates/agent/src/tools/fetch_tool.rs
index 028f1279d41..5555a184117 100644
--- a/crates/agent/src/tools/fetch_tool.rs
+++ b/crates/agent/src/tools/fetch_tool.rs
@@ -2,7 +2,7 @@ use std::rc::Rc;
use std::sync::Arc;
use std::{borrow::Cow, cell::RefCell};
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp;
use anyhow::{Context as _, Result, bail};
use futures::{AsyncReadExt as _, FutureExt as _};
use gpui::{App, AppContext as _, Task};
diff --git a/crates/agent/src/tools/find_path_tool.rs b/crates/agent/src/tools/find_path_tool.rs
index eb08000d3a8..7ae86f335cd 100644
--- a/crates/agent/src/tools/find_path_tool.rs
+++ b/crates/agent/src/tools/find_path_tool.rs
@@ -1,6 +1,6 @@
use crate::{AgentTool, ToolCallEventStream, ToolInput};
use acp_thread::MentionUri;
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp;
use anyhow::{Result, anyhow};
use futures::FutureExt as _;
use gpui::{App, AppContext, Entity, SharedString, Task};
@@ -144,11 +144,11 @@ impl AgentTool for FindPathTool {
..cmp::min(input.offset + RESULTS_PER_PAGE, matches.len())];
event_stream.update_fields(
- acp::ToolCallUpdateFields::new()
+ |update| update
.title(if paginated_matches.is_empty() {
- "No matches".into()
+ "No matches".to_string()
} else if paginated_matches.len() == 1 {
- "1 match".into()
+ "1 match".to_string()
} else {
format!("{} matches", paginated_matches.len())
})
@@ -159,12 +159,12 @@ impl AgentTool for FindPathTool {
let uri = MentionUri::File {
abs_path: path.clone(),
};
- acp::ToolCallContent::Content(acp::Content::new(
+ acp::ToolCallContent::from(
acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
path.to_string_lossy(),
uri.to_uri().to_string(),
)),
- ))
+ )
})
.collect::<Vec<_>>(),
),
diff --git a/crates/agent/src/tools/find_references_tool.rs b/crates/agent/src/tools/find_references_tool.rs
index 8bcf8e7e1ab..86c41a6276d 100644
--- a/crates/agent/src/tools/find_references_tool.rs
+++ b/crates/agent/src/tools/find_references_tool.rs
@@ -3,7 +3,7 @@ use std::sync::Arc;
use super::symbol_locator::{LocationDisplay, SymbolLocator};
use crate::{AgentTool, ToolCallEventStream, ToolInput};
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp;
use gpui::{App, Entity, SharedString, Task};
use project::Project;
use schemars::JsonSchema;
diff --git a/crates/agent/src/tools/get_code_actions_tool.rs b/crates/agent/src/tools/get_code_actions_tool.rs
index db6db293f6a..7f77b2e049b 100644
--- a/crates/agent/src/tools/get_code_actions_tool.rs
+++ b/crates/agent/src/tools/get_code_actions_tool.rs
@@ -1,7 +1,7 @@
use std::fmt::Write;
use std::sync::Arc;
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp;
use gpui::{App, Entity, SharedString, Task};
use project::Project;
use schemars::JsonSchema;
diff --git a/crates/agent/src/tools/go_to_definition_tool.rs b/crates/agent/src/tools/go_to_definition_tool.rs
index 57c355d69de..95375bd8414 100644
--- a/crates/agent/src/tools/go_to_definition_tool.rs
+++ b/crates/agent/src/tools/go_to_definition_tool.rs
@@ -3,7 +3,7 @@ use std::sync::Arc;
use super::symbol_locator::{LocationDisplay, SymbolLocator};
use crate::{AgentTool, ToolCallEventStream, ToolInput};
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp;
use gpui::{App, Entity, SharedString, Task};
use project::Project;
use schemars::JsonSchema;
diff --git a/crates/agent/src/tools/grep_tool.rs b/crates/agent/src/tools/grep_tool.rs
index f624bbdea7d..eed142de9f7 100644
--- a/crates/agent/src/tools/grep_tool.rs
+++ b/crates/agent/src/tools/grep_tool.rs
@@ -1,6 +1,6 @@
use crate::{AgentTool, ToolCallEventStream, ToolInput};
use acp_thread::MentionUri;
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp;
use anyhow::Result;
use futures::{FutureExt as _, StreamExt};
use gpui::{App, Entity, SharedString, Task};
@@ -348,19 +348,19 @@ impl AgentTool for GrepTool {
line_range: range.start.row..=end_row,
column: None,
};
- content.push(acp::ToolCallContent::Content(acp::Content::new(
+ content.push(acp::ToolCallContent::from(
acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
format!("{}#{}", path.display(), line_label),
uri.to_uri().to_string(),
)),
- )));
+ ));
locations.push(
- acp::ToolCallLocation::new(abs_path).line(Some(range.start.row)),
+ acp::ToolCallLocation::new(abs_path.clone()).line(Some(range.start.row)),
);
}
// Use a fence longer than any backtick run in the snippet so
// matches containing code fences don't break the rendering.
- content.push(acp::ToolCallContent::Content(acp::Content::new(
+ content.push(acp::ToolCallContent::from(
acp::ContentBlock::Text(acp::TextContent::new(
MarkdownCodeBlock {
tag: "",
@@ -368,7 +368,7 @@ impl AgentTool for GrepTool {
}
.to_string(),
)),
- )));
+ ));
if let Some(ancestor_range) = ancestor_range
&& end_row < ancestor_range.end.row {
@@ -383,7 +383,7 @@ impl AgentTool for GrepTool {
if !content.is_empty() {
event_stream.update_fields(
- acp::ToolCallUpdateFields::new()
+ |update| update
.content(content)
.locations(locations),
);
@@ -636,7 +636,7 @@ mod tests {
);
// Pull the ResourceLink blocks (the clickable links) out of the content.
- let content = update.content.expect("expected content blocks");
+ let content = update.content.take().expect("expected content blocks");
let links = content
.iter()
.filter_map(|block| match block {
@@ -678,11 +678,11 @@ mod tests {
// Each match also reports a location so the panel can reveal the file at
// the matched (0-based) row.
- let locations = update.locations.expect("expected locations");
+ let locations = update.locations.take().expect("expected locations");
assert_eq!(locations.len(), 2);
assert!(
locations.iter().any(|location| {
- location.path.to_string_lossy().replace('\\', "/")
+ location.path.0.to_string_lossy().replace('\\', "/")
== path!("/root/src/alpha.txt").replace('\\', "/")
&& location.line == Some(0)
}),
@@ -690,7 +690,7 @@ mod tests {
);
assert!(
locations.iter().any(|location| {
- location.path.to_string_lossy().replace('\\', "/")
+ location.path.0.to_string_lossy().replace('\\', "/")
== path!("/root/beta.txt").replace('\\', "/")
&& location.line == Some(0)
}),
@@ -732,7 +732,7 @@ mod tests {
let update = events.expect_update_fields().await;
// Find the snippet text block emitted alongside the clickable link.
- let content = update.content.expect("expected content blocks");
+ let content = update.content.take().expect("expected content blocks");
let snippet = content
.iter()
.find_map(|block| match block {
diff --git a/crates/agent/src/tools/list_agents_and_models_tool.rs b/crates/agent/src/tools/list_agents_and_models_tool.rs
index a3df18d0931..185510ede22 100644
--- a/crates/agent/src/tools/list_agents_and_models_tool.rs
+++ b/crates/agent/src/tools/list_agents_and_models_tool.rs
@@ -1,4 +1,4 @@
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp;
use anyhow::Result;
use gpui::{App, SharedString, Task};
use language_model::LanguageModelToolResultContent;
diff --git a/crates/agent/src/tools/list_directory_tool.rs b/crates/agent/src/tools/list_directory_tool.rs
index 0fd86f2ad37..209ca1f89e6 100644
--- a/crates/agent/src/tools/list_directory_tool.rs
+++ b/crates/agent/src/tools/list_directory_tool.rs
@@ -3,7 +3,7 @@ use super::tool_permissions::{
resolve_global_skill_path, resolve_project_path,
};
use crate::{AgentTool, ToolCallEventStream, ToolInput};
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp;
use anyhow::{Context as _, Result, anyhow};
use fs::Fs;
use futures::StreamExt as _;
@@ -912,7 +912,11 @@ mod tests {
});
let auth = event_rx.expect_authorization().await;
- let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
+ let title = auth
+ .tool_call
+ .title
+ .value()
+ .expect("expected authorization title");
assert!(
title.contains("points outside the project"),
"Authorization title should mention symlink escape, got: {title}",
diff --git a/crates/agent/src/tools/move_path_tool.rs b/crates/agent/src/tools/move_path_tool.rs
index 57eafc7f9c0..f43637c094c 100644
--- a/crates/agent/src/tools/move_path_tool.rs
+++ b/crates/agent/src/tools/move_path_tool.rs
@@ -7,7 +7,7 @@ use crate::{
AgentTool, ToolCallEventStream, ToolInput, ToolPermissionDecision,
authorize_with_sensitive_settings, decide_permission_for_paths,
};
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp;
use agent_settings::AgentSettings;
use futures::FutureExt as _;
use gpui::{App, Entity, SharedString, Task};
@@ -349,7 +349,11 @@ mod tests {
});
let auth = event_rx.expect_authorization().await;
- let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
+ let title = auth
+ .tool_call
+ .title
+ .value()
+ .expect("expected authorization title");
assert!(
title.contains("agent skills"),
"Authorization title should mention agent skills, got: {title}",
@@ -415,7 +419,11 @@ mod tests {
});
let auth = event_rx.expect_authorization().await;
- let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
+ let title = auth
+ .tool_call
+ .title
+ .value()
+ .expect("expected authorization title");
assert!(
title.contains("agent skills"),
"Authorization title should mention agent skills, got: {title}",
@@ -487,7 +495,11 @@ mod tests {
let task = cx.update(|cx| tool.run(ToolInput::resolved(input), event_stream, cx));
let auth = event_rx.expect_authorization().await;
- let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
+ let title = auth
+ .tool_call
+ .title
+ .value()
+ .expect("expected authorization title");
assert!(
title.contains("points outside the project")
|| title.contains("symlinks outside project"),
@@ -596,7 +608,11 @@ mod tests {
let task = cx.update(|cx| tool.run(ToolInput::resolved(input), event_stream, cx));
let auth = event_rx.expect_authorization().await;
- let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
+ let title = auth
+ .tool_call
+ .title
+ .value()
+ .expect("expected authorization title");
assert!(
title.contains("points outside the project")
|| title.contains("symlinks outside project"),
diff --git a/crates/agent/src/tools/read_file_tool.rs b/crates/agent/src/tools/read_file_tool.rs
index 19b1c86093a..82f74df7cc0 100644
--- a/crates/agent/src/tools/read_file_tool.rs
+++ b/crates/agent/src/tools/read_file_tool.rs
@@ -1,5 +1,5 @@
use action_log::ActionLog;
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp;
use anyhow::{Context as _, Result, anyhow};
use futures::FutureExt as _;
use gpui::{App, Entity, SharedString, Task};
@@ -109,10 +109,12 @@ async fn read_global_skill_file(
) -> Result<LanguageModelToolResultContent, LanguageModelToolResultContent> {
let content = fs.load(canonical_path).await.map_err(tool_content_err)?;
- event_stream.update_fields(acp::ToolCallUpdateFields::new().locations(vec![
- acp::ToolCallLocation::new(canonical_path)
- .line(start_line.map(|line| line.saturating_sub(1))),
- ]));
+ event_stream.update_fields(|update| {
+ update.locations(vec![
+ acp::ToolCallLocation::new(canonical_path.to_path_buf())
+ .line(start_line.map(|line| line.saturating_sub(1))),
+ ])
+ });
let (raw_text, first_line_number) = if start_line.is_some() || end_line.is_some() {
// `split_inclusive` keeps each line's terminator attached, so CRLF stays
@@ -134,9 +136,7 @@ async fn read_global_skill_file(
text: &result_text,
}
.to_string();
- event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![
- acp::ToolCallContent::Content(acp::Content::new(markdown)),
- ]));
+ event_stream.update_fields(|update| update.content(vec![markdown.into()]));
Ok(result_text.into())
}
@@ -356,8 +356,8 @@ impl AgentTool for ReadFileTool {
let file_path = input.path.clone();
cx.update(|_cx| {
- event_stream.update_fields(acp::ToolCallUpdateFields::new().locations(vec![
- acp::ToolCallLocation::new(&abs_path)
+ event_stream.update_fields(|update| update.locations(vec![
+ acp::ToolCallLocation::new(abs_path.clone())
.line(input.start_line.map(|line| line.saturating_sub(1))),
]));
});
@@ -384,10 +384,12 @@ impl AgentTool for ReadFileTool {
.context("processing image")
.map_err(tool_content_err)?;
- event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![
- acp::ToolCallContent::Content(acp::Content::new(acp::ContentBlock::Image(
- acp::ImageContent::new(language_model_image.source.clone(), "image/png"),
- ))),
+ event_stream.update_fields(|update| update.content(vec![
+ acp::ContentBlock::Image(acp::ImageContent::new(
+ language_model_image.source.clone(),
+ "image/png",
+ ))
+ .into(),
]));
return Ok(language_model_image.into());
@@ -503,9 +505,9 @@ impl AgentTool for ReadFileTool {
// so highlighting would be both expensive and incorrect.
let tag: &str = if is_outline_response { "" } else { &input.path };
let markdown = MarkdownCodeBlock { tag, text }.to_string();
- event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![
- acp::ToolCallContent::Content(acp::Content::new(markdown)),
- ]));
+ event_stream.update_fields(
+ |update| update.content(vec![markdown.into()]),
+ );
}
});
@@ -526,9 +528,7 @@ impl AgentTool for ReadFileTool {
text: &text,
}
.to_string();
- event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![
- acp::ToolCallContent::Content(acp::Content::new(markdown)),
- ]));
+ event_stream.update_fields(|update| update.content(vec![markdown.into()]));
}
Ok(())
@@ -774,7 +774,10 @@ mod test {
// markdown content destined for the tool-call UI.
let _location_update = rx.expect_update_fields().await;
let content_update = rx.expect_update_fields().await;
- let content_blocks = content_update.content.expect("expected content update");
+ let content_blocks = content_update
+ .content
+ .take()
+ .expect("expected content update");
let acp::ToolCallContent::Content(content) = content_blocks
.first()
.expect("expected at least one content block")
@@ -830,7 +833,10 @@ mod test {
let _location_update = rx.expect_update_fields().await;
let content_update = rx.expect_update_fields().await;
- let content_blocks = content_update.content.expect("expected content update");
+ let content_blocks = content_update
+ .content
+ .take()
+ .expect("expected content update");
let acp::ToolCallContent::Content(content) = content_blocks
.first()
.expect("expected at least one content block")
@@ -1283,9 +1289,8 @@ mod test {
assert!(
authorization
.tool_call
- .fields
.title
- .as_deref()
+ .value()
.is_some_and(|title| title.contains("points outside the project")),
"Expected symlink escape authorization before reading the image"
);
@@ -1578,7 +1583,11 @@ mod test {
});
let auth = event_rx.expect_authorization().await;
- let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
+ let title = auth
+ .tool_call
+ .title
+ .value()
+ .expect("expected authorization title");
assert!(
title.contains("points outside the project"),
"title: {title}"
diff --git a/crates/agent/src/tools/rename_tool.rs b/crates/agent/src/tools/rename_tool.rs
index b9065cc5ca9..10b5a00a097 100644
--- a/crates/agent/src/tools/rename_tool.rs
+++ b/crates/agent/src/tools/rename_tool.rs
@@ -1,7 +1,7 @@
use std::fmt::Write;
use std::sync::Arc;
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp;
use collections::HashSet;
use gpui::{App, Entity, SharedString, Task};
use project::Project;
diff --git a/crates/agent/src/tools/skill_tool.rs b/crates/agent/src/tools/skill_tool.rs
index 92efb459604..d6920292a8e 100644
--- a/crates/agent/src/tools/skill_tool.rs
+++ b/crates/agent/src/tools/skill_tool.rs
@@ -1,4 +1,4 @@
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp;
use agent_skills::Skill;
use anyhow::Result;
use gpui::{App, AsyncApp, SharedString, Task};
@@ -695,7 +695,11 @@ mod tests {
// The tool must request authorization before producing a result.
let auth = event_rx.expect_authorization().await;
- let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
+ let title = auth
+ .tool_call
+ .title
+ .value()
+ .expect("expected authorization title");
assert!(
title.contains("my-skill"),
"auth title should reference the skill name: {title}"
@@ -704,8 +708,8 @@ mod tests {
// Approve once and confirm the tool then completes successfully.
auth.response
.send(acp_thread::SelectedPermissionOutcome::new(
- agent_client_protocol::schema::v1::PermissionOptionId::new("allow"),
- agent_client_protocol::schema::v1::PermissionOptionKind::AllowOnce,
+ acp::PermissionOptionId::new("allow"),
+ acp::PermissionOptionKind::AllowOnce,
))
.unwrap();
diff --git a/crates/agent/src/tools/spawn_agent_tool.rs b/crates/agent/src/tools/spawn_agent_tool.rs
index 73dad1e9619..449c5ec907f 100644
--- a/crates/agent/src/tools/spawn_agent_tool.rs
+++ b/crates/agent/src/tools/spawn_agent_tool.rs
@@ -1,5 +1,4 @@
use acp_thread::{SUBAGENT_SESSION_INFO_META_KEY, SubagentSessionInfo};
-use agent_client_protocol::schema::v1 as acp;
use agent_client_protocol::schema::v2 as acp_v2;
use anyhow::Result;
use gpui::{App, SharedString, Task};
@@ -140,8 +139,8 @@ impl AgentTool for SpawnAgentTool {
const NAME: &'static str = "spawn_agent";
- fn kind() -> acp::ToolKind {
- acp::ToolKind::Other
+ fn kind() -> acp_v2::ToolKind {
+ acp_v2::ToolKind::Other
}
fn initial_title(
@@ -204,13 +203,12 @@ impl AgentTool for SpawnAgentTool {
};
event_stream.subagent_spawned(subagent.id());
- event_stream.update_fields_with_meta(
- acp::ToolCallUpdateFields::new(),
- Some(acp::Meta::from_iter([(
+ event_stream.update_fields(|update| {
+ update.meta(acp_v2::Meta::from_iter([(
SUBAGENT_SESSION_INFO_META_KEY.into(),
serde_json::json!(&session_info),
- )])),
- );
+ )]))
+ });
Ok((subagent, session_info))
})?;
@@ -231,7 +229,7 @@ impl AgentTool for SpawnAgentTool {
session_info.message_end_index =
cx.update(|cx| Some(subagent.num_entries(cx).saturating_sub(1)));
- let meta = Some(acp::Meta::from_iter([(
+ let meta = Some(acp_v2::Meta::from_iter([(
SUBAGENT_SESSION_INFO_META_KEY.into(),
serde_json::json!(&session_info),
)]));
@@ -257,10 +255,13 @@ impl AgentTool for SpawnAgentTool {
)
}
};
- event_stream.update_fields_with_meta(
- acp::ToolCallUpdateFields::new().content(vec![output.into()]),
- meta,
- );
+ event_stream.update_fields(|update| {
+ let update = update.content(vec![output.into()]);
+ match meta {
+ Some(meta) => update.meta(meta),
+ None => update,
+ }
+ });
result
})
}
@@ -286,15 +287,18 @@ impl AgentTool for SpawnAgentTool {
};
let meta = session_info.map(|session_info| {
- acp::Meta::from_iter([(
+ acp_v2::Meta::from_iter([(
SUBAGENT_SESSION_INFO_META_KEY.into(),
serde_json::json!(&session_info),
)])
});
- event_stream.update_fields_with_meta(
- acp::ToolCallUpdateFields::new().content(vec![content]),
- meta,
- );
+ event_stream.update_fields(|update| {
+ let update = update.content(vec![content]);
+ match meta {
+ Some(meta) => update.meta(meta),
+ None => update,
+ }
+ });
Ok(())
}
diff --git a/crates/agent/src/tools/terminal_tool.rs b/crates/agent/src/tools/terminal_tool.rs
index a674dd50312..bf4b37a2b0d 100644
--- a/crates/agent/src/tools/terminal_tool.rs
+++ b/crates/agent/src/tools/terminal_tool.rs
@@ -1,4 +1,5 @@
use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp_v2;
use anyhow::Result;
use futures::FutureExt as _;
use gpui::{App, AsyncApp, Entity, SharedString, Task};
@@ -296,8 +297,8 @@ impl AgentTool for TerminalTool {
const NAME: &'static str = "terminal";
- fn kind() -> acp::ToolKind {
- acp::ToolKind::Execute
+ fn kind() -> acp_v2::ToolKind {
+ acp_v2::ToolKind::Execute
}
fn allow_in_restricted_mode() -> bool {
@@ -338,8 +339,8 @@ impl AgentTool for SandboxedTerminalTool {
const NAME: &'static str = "sandboxed_terminal";
- fn kind() -> acp::ToolKind {
- acp::ToolKind::Execute
+ fn kind() -> acp_v2::ToolKind {
+ acp_v2::ToolKind::Execute
}
fn allow_in_restricted_mode() -> bool {
@@ -981,17 +982,15 @@ async fn run_terminal_tool(
});
let terminal_id = terminal.id(cx).map_err(|e| e.to_string())?;
- let fields = acp::ToolCallUpdateFields::new().content(vec![acp::ToolCallContent::Terminal(
- acp::Terminal::new(terminal_id),
- )]);
- if let Some(reason) = &sandbox_not_applied {
- event_stream.update_fields_with_meta(
- fields,
- Some(acp_thread::meta_with_sandbox_not_applied(reason)),
- );
- } else {
- event_stream.update_fields(fields);
- }
+ event_stream.update_fields(|update| {
+ let update = update.content(vec![acp_v2::ToolCallContent::Terminal(
+ acp_v2::Terminal::new(terminal_id),
+ )]);
+ match &sandbox_not_applied {
+ Some(reason) => update.meta(acp_thread::meta_with_sandbox_not_applied(reason)),
+ None => update,
+ }
+ });
let timeout = input.timeout_ms.map(Duration::from_millis);
@@ -2179,7 +2178,7 @@ mod tests {
!matches!(
rx.try_recv(),
Ok(Ok(crate::ThreadEvent::ToolCallUpdate(
- acp_thread::ToolCallUpdate::UpdateFields(_)
+ acp_thread::ToolCallUpdate::V2(_)
)))
),
"invalid command should not emit a terminal card update"
@@ -2196,11 +2195,17 @@ mod tests {
fs.insert_tree("/root", serde_json::json!({})).await;
let project = project::Project::test(fs, ["/root".as_ref()], cx).await;
- let environment = std::rc::Rc::new(cx.update(|cx| {
- crate::tests::FakeThreadEnvironment::default().with_terminal(
- crate::tests::FakeTerminalHandle::new_with_immediate_exit(cx, 0),
+ let (environment, process_terminal_id) = cx.update(|cx| {
+ let terminal = crate::tests::FakeTerminalHandle::new_with_immediate_exit(cx, 0);
+ let terminal_id = crate::TerminalHandle::id(&terminal, &cx.to_async())
+ .expect("expected process terminal ID");
+ (
+ std::rc::Rc::new(
+ crate::tests::FakeThreadEnvironment::default().with_terminal(terminal),
+ ),
+ terminal_id,
)
- }));
+ });
cx.update(|cx| {
let mut settings = agent_settings::AgentSettings::get_global(cx).clone();
@@ -2227,13 +2232,19 @@ mod tests {
});
let update = rx.expect_update_fields().await;
+ let terminal_reference = update
+ .content
+ .value()
+ .and_then(|content| {
+ content.iter().find_map(|content| match content {
+ acp_v2::ToolCallContent::Terminal(terminal) => Some(terminal),
+ _ => None,
+ })
+ })
+ .expect("expected terminal content update in unconditional allow-all mode");
assert!(
- update.content.iter().any(|blocks| {
- blocks
- .iter()
- .any(|content| matches!(content, acp::ToolCallContent::Terminal(_)))
- }),
- "expected terminal content update in unconditional allow-all mode"
+ Arc::ptr_eq(&terminal_reference.terminal_id.0, &process_terminal_id.0),
+ "native terminal references must reuse the process terminal ID"
);
let result = task
@@ -2360,10 +2371,10 @@ mod tests {
let update = rx.expect_update_fields().await;
assert!(
- update.content.iter().any(|blocks| {
+ update.content.value().is_some_and(|blocks| {
blocks
.iter()
- .any(|content| matches!(content, acp::ToolCallContent::Terminal(_)))
+ .any(|content| matches!(content, acp_v2::ToolCallContent::Terminal(_)))
}),
"expected terminal content update for matching env-prefixed allow rule"
);
@@ -2428,10 +2439,10 @@ mod tests {
let update = rx.expect_update_fields().await;
assert!(
- update.content.iter().any(|blocks| {
+ update.content.value().is_some_and(|blocks| {
blocks
.iter()
- .any(|content| matches!(content, acp::ToolCallContent::Terminal(_)))
+ .any(|content| matches!(content, acp_v2::ToolCallContent::Terminal(_)))
}),
"expected terminal content update"
);
@@ -2842,10 +2853,10 @@ mod tests {
let update = rx.expect_update_fields().await;
assert!(
- update.content.iter().any(|blocks| {
+ update.content.value().is_some_and(|blocks| {
blocks
.iter()
- .any(|content| matches!(content, acp::ToolCallContent::Terminal(_)))
+ .any(|content| matches!(content, acp_v2::ToolCallContent::Terminal(_)))
}),
"terminal-specific allow-all should bypass substitution rejection"
);
@@ -2982,10 +2993,10 @@ mod tests {
let update = rx.expect_update_fields().await;
assert!(
- update.content.iter().any(|blocks| {
+ update.content.value().is_some_and(|blocks| {
blocks
.iter()
- .any(|content| matches!(content, acp::ToolCallContent::Terminal(_)))
+ .any(|content| matches!(content, acp_v2::ToolCallContent::Terminal(_)))
}),
"multi-assignment pattern should match and produce terminal content"
);
@@ -3060,10 +3071,10 @@ mod tests {
let update = rx.expect_update_fields().await;
assert!(
- update.content.iter().any(|blocks| {
+ update.content.value().is_some_and(|blocks| {
blocks
.iter()
- .any(|content| matches!(content, acp::ToolCallContent::Terminal(_)))
+ .any(|content| matches!(content, acp_v2::ToolCallContent::Terminal(_)))
}),
"quoted whitespace value should match pattern with quoted form"
);
@@ -3292,9 +3303,10 @@ mod tests {
let task = cx.update(|cx| tool.run(crate::ToolInput::resolved(input), event_stream, cx));
let authorization = receiver.expect_authorization().await;
- let details =
- acp_thread::sandbox_authorization_details_from_meta(&authorization.tool_call.meta)
- .expect("legacy allow_fs_write should request sandbox authorization details");
+ let details = acp_thread::sandbox_authorization_details_from_meta(
+ &authorization.tool_call.meta.clone().take(),
+ )
+ .expect("legacy allow_fs_write should request sandbox authorization details");
assert!(details.network_hosts.is_empty());
assert!(!details.network_all_hosts);
assert!(details.allow_fs_write_all);
@@ -3310,33 +3322,37 @@ mod tests {
(
option.option_id.0.as_ref(),
option.name.as_ref(),
- option.kind,
+ option.kind.clone(),
)
})
.collect::<Vec<_>>();
assert_eq!(
options,
vec![
- ("allow", "Allow once", acp::PermissionOptionKind::AllowOnce),
+ (
+ "allow",
+ "Allow once",
+ acp_v2::PermissionOptionKind::AllowOnce
+ ),
(
"allow_thread",
"Allow for this thread",
- acp::PermissionOptionKind::AllowAlways,
+ acp_v2::PermissionOptionKind::AllowAlways,
),
(
"allow_always",
"Allow always",
- acp::PermissionOptionKind::AllowAlways,
+ acp_v2::PermissionOptionKind::AllowAlways,
),
- ("deny", "Deny", acp::PermissionOptionKind::RejectOnce),
+ ("deny", "Deny", acp_v2::PermissionOptionKind::RejectOnce),
]
);
authorization
.response
.send(acp_thread::SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("deny"),
- acp::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionId::new("deny"),
+ acp_v2::PermissionOptionKind::RejectOnce,
))
.expect("authorization response should send");
@@ -3388,10 +3404,11 @@ mod tests {
let authorization = receiver.expect_authorization().await;
// The sandbox approval deliberately leaves the tool-call title untouched
// so the card keeps showing the command being approved.
- assert_eq!(authorization.tool_call.fields.title, None);
- let details =
- acp_thread::sandbox_authorization_details_from_meta(&authorization.tool_call.meta)
- .expect("unsandboxed should request sandbox authorization details");
+ assert!(authorization.tool_call.title.is_undefined());
+ let details = acp_thread::sandbox_authorization_details_from_meta(
+ &authorization.tool_call.meta.clone().take(),
+ )
+ .expect("unsandboxed should request sandbox authorization details");
assert!(details.network_hosts.is_empty());
assert!(!details.network_all_hosts);
assert!(!details.allow_fs_write_all);
@@ -3407,33 +3424,37 @@ mod tests {
(
option.option_id.0.as_ref(),
option.name.as_ref(),
- option.kind,
+ option.kind.clone(),
)
})
.collect::<Vec<_>>();
assert_eq!(
options,
vec![
- ("allow", "Allow once", acp::PermissionOptionKind::AllowOnce),
+ (
+ "allow",
+ "Allow once",
+ acp_v2::PermissionOptionKind::AllowOnce
+ ),
(
"allow_thread",
"Allow for this thread",
- acp::PermissionOptionKind::AllowAlways,
+ acp_v2::PermissionOptionKind::AllowAlways,
),
(
"allow_always",
"Allow always",
- acp::PermissionOptionKind::AllowAlways,
+ acp_v2::PermissionOptionKind::AllowAlways,
),
- ("deny", "Deny", acp::PermissionOptionKind::RejectOnce),
+ ("deny", "Deny", acp_v2::PermissionOptionKind::RejectOnce),
]
);
authorization
.response
.send(acp_thread::SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("deny"),
- acp::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionId::new("deny"),
+ acp_v2::PermissionOptionKind::RejectOnce,
))
.expect("authorization response should send");
@@ -3505,8 +3526,8 @@ mod tests {
authorization
.response
.send(acp_thread::SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("allow_always"),
- acp::PermissionOptionKind::AllowAlways,
+ acp_v2::PermissionOptionId::new("allow_always"),
+ acp_v2::PermissionOptionKind::AllowAlways,
))
.expect("authorization response should send");
task.await.expect("granted command should run");
@@ -3543,9 +3564,10 @@ mod tests {
cx.update(|cx| tool2.run(crate::ToolInput::resolved(resolved2), event_stream2, cx));
let authorization2 = receiver2.expect_authorization().await;
- let details =
- acp_thread::sandbox_authorization_details_from_meta(&authorization2.tool_call.meta)
- .expect("the identical request should prompt for sandbox authorization again");
+ let details = acp_thread::sandbox_authorization_details_from_meta(
+ &authorization2.tool_call.meta.clone().take(),
+ )
+ .expect("the identical request should prompt for sandbox authorization again");
assert!(
details
.write_paths
@@ -3558,8 +3580,8 @@ mod tests {
authorization2
.response
.send(acp_thread::SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("deny"),
- acp::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionId::new("deny"),
+ acp_v2::PermissionOptionKind::RejectOnce,
))
.expect("authorization response should send");
let result = task2
diff --git a/crates/agent/src/tools/tool_permissions.rs b/crates/agent/src/tools/tool_permissions.rs
index d658a0470d1..8fb7fea1cf9 100644
--- a/crates/agent/src/tools/tool_permissions.rs
+++ b/crates/agent/src/tools/tool_permissions.rs
@@ -2,7 +2,7 @@ use crate::{
Thread, ToolCallEventStream, ToolPermissionContext, ToolPermissionDecision,
decide_permission_for_path,
};
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp;
use agent_skills::is_agents_skills_path;
use anyhow::{Result, anyhow};
use fs::Fs;
diff --git a/crates/agent/src/tools/web_search_tool.rs b/crates/agent/src/tools/web_search_tool.rs
index 73ac052c346..ac3dbe9ce65 100644
--- a/crates/agent/src/tools/web_search_tool.rs
+++ b/crates/agent/src/tools/web_search_tool.rs
@@ -1,7 +1,7 @@
use std::sync::Arc;
use crate::{AgentTool, ToolCallEventStream, ToolInput};
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp;
use anyhow::Result;
use cloud_llm_client::WebSearchResponse;
use futures::FutureExt as _;
@@ -109,7 +109,7 @@ impl AgentTool for WebSearchTool {
Ok(response) => response,
Err(err) => {
event_stream
- .update_fields(acp::ToolCallUpdateFields::new().title("Web Search Failed"));
+ .update_fields(|update| update.title("Web Search Failed"));
return Err(WebSearchToolOutput::Error { error: err.to_string() });
}
}
@@ -144,23 +144,21 @@ fn emit_update(response: &WebSearchResponse, event_stream: &ToolCallEventStream)
} else {
format!("{} results", response.results.len())
};
- event_stream.update_fields(
- acp::ToolCallUpdateFields::new()
+ event_stream.update_fields(|update| {
+ update
.title(format!("Searched the web: {result_text}"))
.content(
response
.results
.iter()
.map(|result| {
- acp::ToolCallContent::Content(acp::Content::new(
- acp::ContentBlock::ResourceLink(
- acp::ResourceLink::new(result.title.clone(), result.url.clone())
- .title(result.title.clone())
- .description(result.text.clone()),
- ),
+ acp::ToolCallContent::from(acp::ContentBlock::ResourceLink(
+ acp::ResourceLink::new(result.title.clone(), result.url.clone())
+ .title(result.title.clone())
+ .description(result.text.clone()),
))
})
.collect::<Vec<_>>(),
- ),
- );
+ )
+ });
}
diff --git a/crates/agent/src/tools/write_file_tool.rs b/crates/agent/src/tools/write_file_tool.rs
index f423247a4d6..fee6b841e47 100644
--- a/crates/agent/src/tools/write_file_tool.rs
+++ b/crates/agent/src/tools/write_file_tool.rs
@@ -4,7 +4,7 @@ use super::edit_session::{
};
use crate::{AgentTool, Thread, ToolCallEventStream, ToolInput, ToolInputPayload};
use action_log::ActionLog;
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v2 as acp;
use futures::FutureExt as _;
use gpui::{App, AsyncApp, Entity, Task, WeakEntity};
use language::LanguageRegistry;
@@ -368,7 +368,11 @@ mod tests {
event_rx.expect_update_fields().await;
let auth = event_rx.expect_authorization().await;
- let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
+ let title = auth
+ .tool_call
+ .title
+ .value()
+ .expect("expected authorization title");
assert!(
title.contains("agent skills"),
"Authorization title should mention agent skills, got: {title}",
@@ -1199,7 +1203,11 @@ mod tests {
let auth = stream_rx.expect_authorization().await;
// Verify the prompt is the overwrite-mode prompt.
- let content = auth.tool_call.fields.content.as_deref().unwrap_or(&[]);
+ let content = auth
+ .tool_call
+ .content
+ .value()
+ .expect("expected authorization content");
let acp::ToolCallContent::Content(text) = content.first().expect("expected message body")
else {
panic!("expected text body, got: {:?}", content.first());
diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs
index 0e36a60810e..90d49e18a86 100644
--- a/crates/agent_servers/src/acp.rs
+++ b/crates/agent_servers/src/acp.rs
@@ -2765,6 +2765,62 @@ mod tests {
use feature_flags::{AcpBetaFeatureFlag, FeatureFlag as _};
use settings::Settings as _;
+ #[test]
+ fn test_v1_permission_conversion_preserves_options_and_arc_ids() {
+ for (legacy_kind, kind) in [
+ (
+ acp::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
+ ),
+ (
+ acp::PermissionOptionKind::AllowAlways,
+ acp_v2::PermissionOptionKind::AllowAlways,
+ ),
+ (
+ acp::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionKind::RejectOnce,
+ ),
+ (
+ acp::PermissionOptionKind::RejectAlways,
+ acp_v2::PermissionOptionKind::RejectAlways,
+ ),
+ ] {
+ let option_id = acp::PermissionOptionId::new("agent-defined-choice");
+ let meta = acp::Meta::from_iter([("custom".into(), serde_json::json!({"keep": true}))]);
+ let option = permission_option_from_v1(
+ acp::PermissionOption::new(option_id.clone(), "Agent's label", legacy_kind)
+ .meta(meta.clone()),
+ )
+ .expect("known permission option kind");
+ assert!(Arc::ptr_eq(&option.option_id.0, &option_id.0));
+ assert_eq!(option.name, "Agent's label");
+ assert_eq!(option.kind, kind);
+ assert_eq!(option.meta, Some(meta));
+
+ let outcome = permission_outcome_to_v1(acp_thread::RequestPermissionOutcome::Selected(
+ acp_thread::SelectedPermissionOutcome::new(option.option_id, kind),
+ ));
+ let acp::RequestPermissionOutcome::Selected(outcome) = outcome else {
+ panic!("selected permission outcome");
+ };
+ assert!(Arc::ptr_eq(&outcome.option_id.0, &option_id.0));
+ assert_eq!(outcome.option_id, option_id);
+ }
+ }
+
+ #[test]
+ fn test_v1_permission_conversion_preserves_cancellation() {
+ for outcome in [
+ acp_thread::RequestPermissionOutcome::Cancelled,
+ acp_thread::RequestPermissionOutcome::InterruptedByFollowUp,
+ ] {
+ assert_eq!(
+ permission_outcome_to_v1(outcome),
+ acp::RequestPermissionOutcome::Cancelled,
+ );
+ }
+ }
+
#[derive(Debug, PartialEq)]
struct V2TerminalReceive {
envelope_meta: Option<acp_v2::Meta>,
@@ -2981,7 +3037,7 @@ mod tests {
fn terminal(&self, id: &str, cx: &gpui::TestAppContext) -> Entity<acp_thread::Terminal> {
self.thread.read_with(cx, |thread, _| {
thread
- .terminal(acp::TerminalId::new(id))
+ .terminal(acp_v2::TerminalId::new(id))
.expect("display terminal")
})
}
@@ -2993,7 +3049,7 @@ mod tests {
harness
.thread
.update(cx, |thread, cx| {
- thread.upsert_tool_call_patch(
+ thread.upsert_wire_tool_call(
acp_v2::ToolCallUpdate::new("terminal-tool").content(vec![
acp_v2::ToolCallContent::Terminal(acp_v2::Terminal::new("terminal-1")),
]),
@@ -3235,7 +3291,7 @@ mod tests {
assert_eq!(observe(cx), before);
assert_eq!(harness.terminal("terminal-1", cx), terminal);
harness.thread.read_with(cx, |thread, _| {
- assert!(thread.terminal(acp::TerminalId::new("unseen")).is_err());
+ assert!(thread.terminal(acp_v2::TerminalId::new("unseen")).is_err());
});
assert_eq!(
harness.received.lock().expect("receive mutex").len(),
@@ -6343,8 +6399,8 @@ exit 7
thread.authorize_permission_request(
successor_id,
acp_thread::SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("allow-successor"),
- acp::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionId::new("allow-successor"),
+ acp_v2::PermissionOptionKind::AllowOnce,
),
cx,
);
@@ -7352,6 +7408,42 @@ fn respond_result<T: JsonRpcResponse>(responder: Responder<T>, result: Result<T,
}
}
+fn permission_option_from_v1(
+ option: acp::PermissionOption,
+) -> Result<acp_v2::PermissionOption, acp::Error> {
+ let kind = match option.kind {
+ acp::PermissionOptionKind::AllowOnce => acp_v2::PermissionOptionKind::AllowOnce,
+ acp::PermissionOptionKind::AllowAlways => acp_v2::PermissionOptionKind::AllowAlways,
+ acp::PermissionOptionKind::RejectOnce => acp_v2::PermissionOptionKind::RejectOnce,
+ acp::PermissionOptionKind::RejectAlways => acp_v2::PermissionOptionKind::RejectAlways,
+ _ => {
+ return Err(acp::Error::invalid_params().data("unsupported permission option kind"));
+ }
+ };
+ Ok(acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new(option.option_id.0),
+ option.name,
+ kind,
+ )
+ .meta(option.meta))
+}
+
+fn permission_outcome_to_v1(
+ outcome: acp_thread::RequestPermissionOutcome,
+) -> acp::RequestPermissionOutcome {
+ match outcome {
+ acp_thread::RequestPermissionOutcome::Cancelled
+ | acp_thread::RequestPermissionOutcome::InterruptedByFollowUp => {
+ acp::RequestPermissionOutcome::Cancelled
+ }
+ acp_thread::RequestPermissionOutcome::Selected(outcome) => {
+ acp::RequestPermissionOutcome::Selected(acp::SelectedPermissionOutcome::new(
+ acp::PermissionOptionId::new(outcome.option_id.0),
+ ))
+ }
+ }
+}
+
fn handle_request_permission(
args: acp::RequestPermissionRequest,
responder: Responder<acp::RequestPermissionResponse>,
@@ -7365,11 +7457,20 @@ fn handle_request_permission(
let cancellation = responder.cancellation();
cx.spawn(async move |cx| {
+ let options = match args
+ .options
+ .into_iter()
+ .map(permission_option_from_v1)
+ .collect::<Result<Vec<_>, _>>()
+ {
+ Ok(options) => options,
+ Err(error) => return respond_err(responder, error),
+ };
let (request_id, task) = match thread
.update(cx, |thread, cx| {
thread.request_tool_call_authorization_with_id(
args.tool_call,
- acp_thread::PermissionOptions::Flat(args.options),
+ acp_thread::PermissionOptions::Flat(options),
acp_thread::AuthorizationKind::PermissionGrant,
cx,
)
@@ -7386,7 +7487,9 @@ fn handle_request_permission(
match result {
Ok(outcome) => {
responder
- .respond(acp::RequestPermissionResponse::new(outcome.into()))
+ .respond(acp::RequestPermissionResponse::new(
+ permission_outcome_to_v1(outcome),
+ ))
.log_err();
}
Err(e) => {
@@ -7800,7 +7903,7 @@ fn handle_create_terminal(
let terminal_entity = thread.update(cx, |thread, cx| {
thread.register_terminal_created(
- acp::TerminalId::new(uuid::Uuid::new_v4().to_string()),
+ acp_v2::TerminalId::new(uuid::Uuid::new_v4().to_string()),
format!("{} {}", args.command, args.args.join(" ")),
args.cwd.clone(),
args.output_byte_limit,
@@ -7816,7 +7919,9 @@ fn handle_create_terminal(
match result {
Ok(terminal_id) => {
responder
- .respond(acp::CreateTerminalResponse::new(terminal_id))
+ .respond(acp::CreateTerminalResponse::new(acp::TerminalId::new(
+ terminal_id.0,
+ )))
.log_err();
}
Err(e) => respond_err(responder, e),
@@ -7837,7 +7942,9 @@ fn handle_kill_terminal(
};
match thread
- .update(cx, |thread, cx| thread.kill_terminal(args.terminal_id, cx))
+ .update(cx, |thread, cx| {
+ thread.kill_terminal(acp_v2::TerminalId::new(args.terminal_id.0), cx)
+ })
.flatten_acp()
{
Ok(()) => {
@@ -7862,7 +7969,7 @@ fn handle_release_terminal(
match thread
.update(cx, |thread, cx| {
- thread.release_terminal(args.terminal_id, cx)
+ thread.release_terminal(acp_v2::TerminalId::new(args.terminal_id.0), cx)
})
.flatten_acp()
{
@@ -7889,7 +7996,7 @@ fn handle_terminal_output(
match thread
.read_with(cx, |thread, cx| -> anyhow::Result<_> {
let out = thread
- .terminal(args.terminal_id)?
+ .terminal(acp_v2::TerminalId::new(args.terminal_id.0))?
.read(cx)
.current_output(cx);
Ok(out)
@@ -7920,7 +8027,10 @@ fn handle_wait_for_terminal_exit(
.run_until_cancelled(async {
let exit_status = thread
.update(cx, |thread, cx| {
- thread.terminal(args.terminal_id)?.read(cx).wait_for_exit()
+ thread
+ .terminal(acp_v2::TerminalId::new(args.terminal_id.0))?
+ .read(cx)
+ .wait_for_exit()
})
.flatten_acp()?
.await;
diff --git a/crates/agent_servers/src/e2e_tests.rs b/crates/agent_servers/src/e2e_tests.rs
index 95fbe3c17bc..f3e5ed32f56 100644
--- a/crates/agent_servers/src/e2e_tests.rs
+++ b/crates/agent_servers/src/e2e_tests.rs
@@ -1,6 +1,6 @@
use crate::{AgentServer, AgentServerDelegate};
use acp_thread::{AcpThread, AgentThreadEntry, ToolCallStatus};
-use agent_client_protocol::schema::{v1 as acp, v2 as acp_v2};
+use agent_client_protocol::schema::v2 as acp_v2;
use client::RefreshLlmTokenListener;
use futures::{FutureExt, StreamExt, channel::mpsc, select};
use gpui::AppContext;
@@ -153,7 +153,7 @@ where
pub async fn test_tool_call_with_permission<T, F>(
server: F,
- allow_option_id: acp::PermissionOptionId,
+ allow_option_id: acp_v2::PermissionOptionId,
cx: &mut TestAppContext,
) where
T: AgentServer + 'static,
@@ -203,7 +203,7 @@ pub async fn test_tool_call_with_permission<T, F>(
tool_call_id,
acp_thread::SelectedPermissionOutcome::new(
allow_option_id,
- acp::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
),
cx,
);
@@ -358,7 +358,7 @@ macro_rules! common_e2e_tests {
async fn tool_call_with_permission(cx: &mut ::gpui::TestAppContext) {
$crate::e2e_tests::test_tool_call_with_permission(
$server,
- ::agent_client_protocol::schema::v1::PermissionOptionId::new($allow_option_id),
+ ::agent_client_protocol::schema::v2::PermissionOptionId::new($allow_option_id),
cx,
)
.await;
diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs
index ea6eac30693..701d9f458f8 100644
--- a/crates/agent_ui/src/conversation_view.rs
+++ b/crates/agent_ui/src/conversation_view.rs
@@ -553,7 +553,7 @@ impl Conversation {
pub fn authorize_pending_tool_call(
&mut self,
session_id: &acp_v2::SessionId,
- kind: acp_v1::PermissionOptionKind,
+ kind: acp_v2::PermissionOptionKind,
cx: &mut Context<Self>,
) -> Option<()> {
let (authorize_session_id, request) = self.pending_permission_request(session_id, cx)?;
@@ -561,7 +561,7 @@ impl Conversation {
self.authorize_permission_request(
authorize_session_id,
request.id,
- SelectedPermissionOutcome::new(option.option_id.clone(), option.kind),
+ SelectedPermissionOutcome::new(option.option_id.clone(), option.kind.clone()),
cx,
);
Some(())
@@ -682,9 +682,9 @@ impl EventEmitter<RootThreadUpdated> for ConversationView {}
fn permission_option_for_action(
options: &PermissionOptions,
- kind: acp_v1::PermissionOptionKind,
-) -> Option<&acp_v1::PermissionOption> {
- if kind == acp_v1::PermissionOptionKind::AllowAlways
+ kind: acp_v2::PermissionOptionKind,
+) -> Option<&acp_v2::PermissionOption> {
+ if kind == acp_v2::PermissionOptionKind::AllowAlways
&& let PermissionOptions::Flat(options) = options
&& let Some(option) = options.iter().find(|option| {
option.option_id.0.as_ref() == acp_thread::SandboxPermission::AllowAlways.as_id()
@@ -710,14 +710,14 @@ fn resolve_outcome_from_selection(
PermissionOptions::DropdownWithPatterns { choices, .. } => choices.as_slice(),
PermissionOptions::Flat(_) => {
let kind = if is_allow {
- acp_v1::PermissionOptionKind::AllowOnce
+ acp_v2::PermissionOptionKind::AllowOnce
} else {
- acp_v1::PermissionOptionKind::RejectOnce
+ acp_v2::PermissionOptionKind::RejectOnce
};
let option = options.first_option_of_kind(kind)?;
return Some(SelectedPermissionOutcome::new(
option.option_id.clone(),
- option.kind,
+ option.kind.clone(),
));
}
};
@@ -6690,10 +6690,10 @@ pub(crate) mod tests {
let connection =
StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
tool_call_id,
- PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(
+ PermissionOptions::Flat(vec![acp_v2::PermissionOption::new(
"1",
"Allow",
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
)]),
)]));
@@ -10495,7 +10495,7 @@ pub(crate) mod tests {
}))
.expect("new patch should deserialize");
thread
- .update(cx, |thread, cx| thread.upsert_tool_call_patch(patch, cx))
+ .update(cx, |thread, cx| thread.upsert_wire_tool_call(patch, cx))
.expect("new patch should apply");
cx.run_until_parked();
@@ -10535,7 +10535,7 @@ pub(crate) mod tests {
}))
.expect("metadata patch should deserialize");
thread
- .update(cx, |thread, cx| thread.upsert_tool_call_patch(metadata, cx))
+ .update(cx, |thread, cx| thread.upsert_wire_tool_call(metadata, cx))
.expect("metadata patch should apply");
cx.run_until_parked();
thread_view.read_with(cx, |view, cx| {
@@ -10586,7 +10586,7 @@ pub(crate) mod tests {
}))
.expect("patch should deserialize");
thread
- .update(cx, |thread, cx| thread.upsert_tool_call_patch(patch, cx))
+ .update(cx, |thread, cx| thread.upsert_wire_tool_call(patch, cx))
.expect("patch should apply");
cx.run_until_parked();
let _authorization = thread
@@ -10596,10 +10596,10 @@ pub(crate) mod tests {
acp_v1::ToolCallId::new(tool_call_id.0.clone()),
acp_v1::ToolCallUpdateFields::new(),
),
- PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(
+ PermissionOptions::Flat(vec![acp_v2::PermissionOption::new(
"allow-review",
"Allow",
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
)]),
acp_thread::AuthorizationKind::PermissionGrant,
cx,
@@ -10689,7 +10689,7 @@ pub(crate) mod tests {
}))
.expect("initial tool patch should deserialize");
thread
- .update(cx, |thread, cx| thread.upsert_tool_call_patch(patch, cx))
+ .update(cx, |thread, cx| thread.upsert_wire_tool_call(patch, cx))
.expect("initial tool patch should apply");
cx.run_until_parked();
@@ -10751,7 +10751,7 @@ pub(crate) mod tests {
}))
.expect("diff patch should deserialize");
thread
- .update(cx, |thread, cx| thread.upsert_tool_call_patch(patch, cx))
+ .update(cx, |thread, cx| thread.upsert_wire_tool_call(patch, cx))
.expect("diff patch should apply");
cx.run_until_parked();
cx.executor()
@@ -10980,7 +10980,7 @@ pub(crate) mod tests {
}))
.expect("clear patch should deserialize");
thread
- .update(cx, |thread, cx| thread.upsert_tool_call_patch(patch, cx))
+ .update(cx, |thread, cx| thread.upsert_wire_tool_call(patch, cx))
.expect("clear patch should apply");
cx.run_until_parked();
cx.executor()
@@ -11045,7 +11045,7 @@ pub(crate) mod tests {
] {
thread
.update(cx, |thread, cx| {
- thread.upsert_tool_call_patch(
+ thread.upsert_wire_tool_call(
acp_v2::ToolCallUpdate::new(id)
.title("Inspect output")
.status(acp_v2::ToolCallStatus::Completed)
@@ -13496,7 +13496,7 @@ pub(crate) mod tests {
let thread = thread_view.read_with(cx, |view, _| view.thread.clone());
thread.update(cx, |thread, cx| {
thread
- .upsert_tool_call_patch(
+ .upsert_wire_tool_call(
acp_v2::ToolCallUpdate::new("tool")
.title("Run command")
.kind(acp_v2::ToolKind::Execute)
@@ -13516,7 +13516,7 @@ pub(crate) mod tests {
});
let terminal = thread.read_with(cx, |thread, _| {
thread
- .terminal(acp_v1::TerminalId::new("display"))
+ .terminal(acp_v2::TerminalId::new("display"))
.expect("placeholder")
});
let renderer = terminal.read_with(cx, |terminal, _| terminal.inner().clone());
@@ -13693,7 +13693,7 @@ pub(crate) mod tests {
});
let acp_terminal = thread.read_with(cx, |thread, _| {
thread
- .terminal(terminal_id.clone())
+ .terminal(acp_v2::TerminalId::new(terminal_id.0.clone()))
.expect("terminal tool call should contain a terminal")
});
let terminal_view = entry_state.read_with(cx, |state, _| {
@@ -13794,7 +13794,7 @@ pub(crate) mod tests {
let acp_terminal = thread.update(cx, |thread, cx| {
let acp_terminal = thread.register_terminal_created(
- terminal_id.clone(),
+ acp_v2::TerminalId::new(terminal_id.0.clone()),
"client-owned command".into(),
None,
None,
@@ -14764,40 +14764,40 @@ pub(crate) mod tests {
fn flat_allow_deny_options() -> PermissionOptions {
PermissionOptions::Flat(vec![
- acp_v1::PermissionOption::new(
- acp_v1::PermissionOptionId::new("allow"),
+ acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new("allow"),
"Yes",
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
),
- acp_v1::PermissionOption::new(
- acp_v1::PermissionOptionId::new("deny"),
+ acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new("deny"),
"No",
- acp_v1::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionKind::RejectOnce,
),
])
}
fn sandbox_permission_options() -> PermissionOptions {
PermissionOptions::Flat(vec![
- acp_v1::PermissionOption::new(
- acp_v1::PermissionOptionId::new("allow"),
+ acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new("allow"),
"Allow once",
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
),
- acp_v1::PermissionOption::new(
- acp_v1::PermissionOptionId::new("allow_thread"),
+ acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new("allow_thread"),
"Allow for this thread",
- acp_v1::PermissionOptionKind::AllowAlways,
+ acp_v2::PermissionOptionKind::AllowAlways,
),
- acp_v1::PermissionOption::new(
- acp_v1::PermissionOptionId::new("allow_always"),
+ acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new("allow_always"),
"Allow always",
- acp_v1::PermissionOptionKind::AllowAlways,
+ acp_v2::PermissionOptionKind::AllowAlways,
),
- acp_v1::PermissionOption::new(
- acp_v1::PermissionOptionId::new("deny"),
+ acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new("deny"),
"Deny",
- acp_v1::PermissionOptionKind::RejectOnce,
+ acp_v2::PermissionOptionKind::RejectOnce,
),
])
}
@@ -14808,13 +14808,31 @@ pub(crate) mod tests {
let option = super::permission_option_for_action(
&options,
- acp_v1::PermissionOptionKind::AllowAlways,
+ acp_v2::PermissionOptionKind::AllowAlways,
)
.unwrap();
assert_eq!(option.option_id.0.as_ref(), "allow_always");
}
+ #[test]
+ fn permission_option_for_action_preserves_other_kind() {
+ let kind = acp_v2::PermissionOptionKind::Other("custom_permission".into());
+ let options = PermissionOptions::Flat(vec![acp_v2::PermissionOption::new(
+ "custom",
+ "Custom permission",
+ kind.clone(),
+ )]);
+
+ let option = super::permission_option_for_action(&options, kind.clone())
+ .expect("custom permission kind should match");
+ let outcome = SelectedPermissionOutcome::new(option.option_id.clone(), option.kind.clone());
+
+ assert_eq!(outcome.option_id, acp_v2::PermissionOptionId::new("custom"));
+ assert_eq!(outcome.option_kind, kind);
+ assert!(super::resolve_outcome_from_selection(&options, None, true).is_none());
+ }
+
#[test]
fn resolve_outcome_from_selection_flat_allow_picks_allow_once() {
let options = flat_allow_deny_options();
@@ -14822,7 +14840,7 @@ pub(crate) mod tests {
let outcome = super::resolve_outcome_from_selection(&options, None, true).unwrap();
assert_eq!(outcome.option_id.0.as_ref(), "allow");
- assert_eq!(outcome.option_kind, acp_v1::PermissionOptionKind::AllowOnce);
+ assert_eq!(outcome.option_kind, acp_v2::PermissionOptionKind::AllowOnce);
}
#[test]
@@ -14834,7 +14852,7 @@ pub(crate) mod tests {
assert_eq!(outcome.option_id.0.as_ref(), "deny");
assert_eq!(
outcome.option_kind,
- acp_v1::PermissionOptionKind::RejectOnce
+ acp_v2::PermissionOptionKind::RejectOnce
);
}
@@ -14860,7 +14878,7 @@ pub(crate) mod tests {
// Last choice is "Only this time" → option_id "allow".
assert_eq!(outcome.option_id.0.as_ref(), "allow");
- assert_eq!(outcome.option_kind, acp_v1::PermissionOptionKind::AllowOnce);
+ assert_eq!(outcome.option_kind, acp_v2::PermissionOptionKind::AllowOnce);
}
#[test]
@@ -14877,7 +14895,7 @@ pub(crate) mod tests {
assert!(outcome.option_id.0.contains("always_allow:terminal"));
assert_eq!(
outcome.option_kind,
- acp_v1::PermissionOptionKind::AllowAlways
+ acp_v2::PermissionOptionKind::AllowAlways
);
}
@@ -14917,7 +14935,7 @@ pub(crate) mod tests {
super::resolve_outcome_from_selection(&options, Some(&selection), true).unwrap();
assert_eq!(outcome.option_id.0.as_ref(), "allow");
- assert_eq!(outcome.option_kind, acp_v1::PermissionOptionKind::AllowOnce);
+ assert_eq!(outcome.option_kind, acp_v2::PermissionOptionKind::AllowOnce);
}
#[test]
@@ -14938,7 +14956,7 @@ pub(crate) mod tests {
assert_eq!(
outcome.option_kind,
- acp_v1::PermissionOptionKind::AllowAlways
+ acp_v2::PermissionOptionKind::AllowAlways
);
assert!(
outcome.params.is_some(),
@@ -15175,10 +15193,10 @@ pub(crate) mod tests {
request_test_tool_authorization_with_options(
thread,
tool_call_id,
- PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(
- acp_v1::PermissionOptionId::new(option_id),
+ PermissionOptions::Flat(vec![acp_v2::PermissionOption::new(
+ acp_v2::PermissionOptionId::new(option_id),
"Allow",
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
)]),
cx,
)
@@ -15621,6 +15639,73 @@ pub(crate) mod tests {
}
}
+ #[gpui::test]
+ async fn test_permission_action_rejects_unknown_kinds(cx: &mut TestAppContext) {
+ init_test(cx);
+ let (conversation_view, cx) =
+ setup_conversation_view(StubAgentServer::default_response(), cx).await;
+ add_to_workspace(conversation_view.clone(), cx);
+ let thread_view = active_thread(&conversation_view, cx);
+ let thread = thread_view.read_with(cx, |view, _| view.thread.clone());
+ let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
+
+ for (action_kind, option_kind) in [
+ ("AllowOnce", acp_v2::PermissionOptionKind::AllowOnce),
+ ("AllowAlways", acp_v2::PermissionOptionKind::AllowAlways),
+ ("RejectOnce", acp_v2::PermissionOptionKind::RejectOnce),
+ ("RejectAlways", acp_v2::PermissionOptionKind::RejectAlways),
+ ] {
+ let (request_id, response) = request_test_tool_authorization_with_options(
+ &thread,
+ "permission-action",
+ PermissionOptions::Flat(vec![acp_v2::PermissionOption::new(
+ "selected",
+ "Select",
+ option_kind.clone(),
+ )]),
+ cx,
+ );
+ cx.run_until_parked();
+ let action = crate::AuthorizeToolCall {
+ tool_call_id: "permission-action".into(),
+ request_id: Some(request_id),
+ session_id: Some(session_id.0.to_string()),
+ option_id: "selected".into(),
+ option_kind: "UnknownPermissionKind".into(),
+ };
+ conversation_view.update_in(cx, |_, window, cx| {
+ window.dispatch_action(action.boxed_clone(), cx);
+ });
+ cx.run_until_parked();
+ thread.read_with(cx, |thread, _| {
+ assert!(
+ thread.permission_request(request_id).is_some(),
+ "unknown action kinds must leave the request pending"
+ );
+ });
+
+ conversation_view.update_in(cx, |_, window, cx| {
+ window.dispatch_action(
+ crate::AuthorizeToolCall {
+ option_kind: action_kind.into(),
+ ..action.clone()
+ }
+ .boxed_clone(),
+ cx,
+ );
+ });
+ cx.run_until_parked();
+ let acp_thread::RequestPermissionOutcome::Selected(outcome) = response.await else {
+ panic!("known permission action should select an option");
+ };
+ assert_eq!(
+ outcome.option_id,
+ acp_v2::PermissionOptionId::new("selected")
+ );
+ assert_eq!(outcome.option_kind, option_kind);
+ }
+ }
+
#[gpui::test]
async fn test_replaced_permission_ignores_captured_actions(cx: &mut TestAppContext) {
init_test(cx);
@@ -15759,8 +15844,8 @@ pub(crate) mod tests {
session_id.clone(),
acp_v2::ToolCallId::new("tc-1"),
SelectedPermissionOutcome::new(
- acp_v1::PermissionOptionId::new("allow-1"),
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionId::new("allow-1"),
+ acp_v2::PermissionOptionKind::AllowOnce,
),
cx,
);
@@ -15783,8 +15868,8 @@ pub(crate) mod tests {
session_id.clone(),
acp_v2::ToolCallId::new("tc-2"),
SelectedPermissionOutcome::new(
- acp_v1::PermissionOptionId::new("allow-2"),
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionId::new("allow-2"),
+ acp_v2::PermissionOptionKind::AllowOnce,
),
cx,
);
@@ -16099,8 +16184,8 @@ pub(crate) mod tests {
thread.authorize_tool_call(
acp_v2::ToolCallId::new("resolved-tool"),
SelectedPermissionOutcome::new(
- acp_v1::PermissionOptionId::new("allow-child"),
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionId::new("allow-child"),
+ acp_v2::PermissionOptionKind::AllowOnce,
),
cx,
);
@@ -16114,10 +16199,10 @@ pub(crate) mod tests {
thread
.request_tool_call_authorization(
acp_v1::ToolCall::new("queued-tool", "Queued permission").into(),
- PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(
+ PermissionOptions::Flat(vec![acp_v2::PermissionOption::new(
"allow-child",
"Allow",
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
)]),
acp_thread::AuthorizationKind::PermissionGrant,
cx,
@@ -16155,8 +16240,8 @@ pub(crate) mod tests {
subagent_session_id.clone(),
tool_id,
SelectedPermissionOutcome::new(
- acp_v1::PermissionOptionId::new("allow-child"),
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionId::new("allow-child"),
+ acp_v2::PermissionOptionKind::AllowOnce,
),
cx,
);
@@ -16234,8 +16319,8 @@ pub(crate) mod tests {
session_id_a.clone(),
acp_v2::ToolCallId::new("tc-a"),
SelectedPermissionOutcome::new(
- acp_v1::PermissionOptionId::new("allow-a"),
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionId::new("allow-a"),
+ acp_v2::PermissionOptionKind::AllowOnce,
),
cx,
);
@@ -16847,10 +16932,10 @@ pub(crate) mod tests {
let connection =
StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
tool_call_id_value.clone(),
- PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(
+ PermissionOptions::Flat(vec![acp_v2::PermissionOption::new(
"allow",
"Allow",
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
)]),
)]));
connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::ToolCall(tool_call)]);
diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs
index 5cf83569651..06d34f0db55 100644
--- a/crates/agent_ui/src/conversation_view/thread_view.rs
+++ b/crates/agent_ui/src/conversation_view/thread_view.rs
@@ -4,7 +4,7 @@ use crate::{
open_abs_path_at_point, project_path_for_file_link,
thread_metadata_store::{ThreadId, ThreadMetadataStore},
};
-use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2};
+use agent_client_protocol::schema::v2 as acp_v2;
use std::{cell::RefCell, path::Path};
use acp_thread::{
@@ -2965,7 +2965,7 @@ impl ThreadView {
if self.pending_allow_blocked_by_confusables(cx) {
return;
}
- self.authorize_pending_tool_call(acp_v1::PermissionOptionKind::AllowAlways, window, cx);
+ self.authorize_pending_tool_call(acp_v2::PermissionOptionKind::AllowAlways, window, cx);
}
pub fn allow_once(&mut self, _: &AllowOnce, window: &mut Window, cx: &mut Context<Self>) {
@@ -3002,7 +3002,7 @@ impl ThreadView {
pub fn authorize_pending_tool_call(
&mut self,
- kind: acp_v1::PermissionOptionKind,
+ kind: acp_v2::PermissionOptionKind,
window: &mut Window,
cx: &mut Context<Self>,
) -> Option<()> {
@@ -3238,13 +3238,13 @@ impl ThreadView {
) else {
return;
};
- let option_id = acp_v1::PermissionOptionId::new(action.option_id.clone());
+ let option_id = acp_v2::PermissionOptionId::new(action.option_id.clone());
let option_kind = match action.option_kind.as_str() {
- "AllowOnce" => acp_v1::PermissionOptionKind::AllowOnce,
- "AllowAlways" => acp_v1::PermissionOptionKind::AllowAlways,
- "RejectOnce" => acp_v1::PermissionOptionKind::RejectOnce,
- "RejectAlways" => acp_v1::PermissionOptionKind::RejectAlways,
- _ => acp_v1::PermissionOptionKind::AllowOnce,
+ "AllowOnce" => acp_v2::PermissionOptionKind::AllowOnce,
+ "AllowAlways" => acp_v2::PermissionOptionKind::AllowAlways,
+ "RejectOnce" => acp_v2::PermissionOptionKind::RejectOnce,
+ "RejectAlways" => acp_v2::PermissionOptionKind::RejectAlways,
+ _ => return,
};
self.authorize_permission_request(
@@ -10471,14 +10471,14 @@ impl ThreadView {
&self,
session_id: acp_v2::SessionId,
is_first: bool,
- options: &[acp_v1::PermissionOption],
+ options: &[acp_v2::PermissionOption],
entry_ix: usize,
request_id: PermissionRequestId,
focus_handle: &FocusHandle,
allow_disabled: bool,
cx: &Context<Self>,
) -> Div {
- let mut seen_kinds: ArrayVec<acp_v1::PermissionOptionKind, 3, u8> = ArrayVec::new();
+ let mut seen_kinds: ArrayVec<acp_v2::PermissionOptionKind, 3, u8> = ArrayVec::new();
div()
.p_1()
@@ -10505,14 +10505,14 @@ impl ThreadView {
None,
)
} else {
- match option.kind {
- acp_v1::PermissionOptionKind::AllowOnce => (
+ match &option.kind {
+ acp_v2::PermissionOptionKind::AllowOnce => (
Icon::new(IconName::Check)
.size(IconSize::XSmall)
.color(Color::Success),
Some(&AllowOnce as &dyn Action),
),
- acp_v1::PermissionOptionKind::AllowAlways => (
+ acp_v2::PermissionOptionKind::AllowAlways => (
Icon::new(IconName::CheckDouble)
.size(IconSize::XSmall)
.color(Color::Success),
@@ -10524,13 +10524,13 @@ impl ThreadView {
Some(&AllowAlways as &dyn Action)
},
),
- acp_v1::PermissionOptionKind::RejectOnce => (
+ acp_v2::PermissionOptionKind::RejectOnce => (
Icon::new(IconName::Close)
.size(IconSize::XSmall)
.color(Color::Error),
Some(&RejectOnce as &dyn Action),
),
- acp_v1::PermissionOptionKind::RejectAlways | _ => (
+ acp_v2::PermissionOptionKind::RejectAlways | _ => (
Icon::new(IconName::Close)
.size(IconSize::XSmall)
.color(Color::Error),
@@ -10543,8 +10543,8 @@ impl ThreadView {
// warning is unacknowledged; "deny"/"retry" stay enabled.
let is_allow = matches!(
option.kind,
- acp_v1::PermissionOptionKind::AllowOnce
- | acp_v1::PermissionOptionKind::AllowAlways
+ acp_v2::PermissionOptionKind::AllowOnce
+ | acp_v2::PermissionOptionKind::AllowAlways
) && !is_retry;
let disabled = allow_disabled && is_allow;
@@ -10558,7 +10558,7 @@ impl ThreadView {
return this;
}
- seen_kinds.push(option.kind).unwrap();
+ seen_kinds.push(option.kind.clone()).unwrap();
this.key_binding(
KeyBinding::for_action_in(action, focus_handle, cx)
@@ -10568,13 +10568,16 @@ impl ThreadView {
.label_size(LabelSize::Small)
.on_click(cx.listener({
let option_id = option.option_id.clone();
- let option_kind = option.kind;
+ let option_kind = option.kind.clone();
let session_id = session_id.clone();
move |this, _, window, cx| {
this.authorize_permission_request(
session_id.clone(),
request_id,
- SelectedPermissionOutcome::new(option_id.clone(), option_kind),
+ SelectedPermissionOutcome::new(
+ option_id.clone(),
+ option_kind.clone(),
+ ),
window,
cx,
);
diff --git a/crates/remote_server/src/remote_editing_tests.rs b/crates/remote_server/src/remote_editing_tests.rs
index 7b34f7ae135..df0c86536b8 100644
--- a/crates/remote_server/src/remote_editing_tests.rs
+++ b/crates/remote_server/src/remote_editing_tests.rs
@@ -4860,8 +4860,8 @@ async fn test_adding_remote_skill(cx: &mut TestAppContext, server_cx: &mut TestA
authorization
.response
.send(acp_thread::SelectedPermissionOutcome::new(
- agent_client_protocol::schema::v1::PermissionOptionId::new("allow"),
- agent_client_protocol::schema::v1::PermissionOptionKind::AllowOnce,
+ agent_client_protocol::schema::v2::PermissionOptionId::new("allow"),
+ agent_client_protocol::schema::v2::PermissionOptionKind::AllowOnce,
))
.unwrap();
@@ -4910,8 +4910,8 @@ async fn test_adding_remote_skill(cx: &mut TestAppContext, server_cx: &mut TestA
authorization
.response
.send(acp_thread::SelectedPermissionOutcome::new(
- agent_client_protocol::schema::v1::PermissionOptionId::new("allow"),
- agent_client_protocol::schema::v1::PermissionOptionKind::AllowOnce,
+ agent_client_protocol::schema::v2::PermissionOptionId::new("allow"),
+ agent_client_protocol::schema::v2::PermissionOptionKind::AllowOnce,
))
.unwrap();
diff --git a/crates/sidebar/src/sidebar_tests.rs b/crates/sidebar/src/sidebar_tests.rs
index a7ed6772ee5..4f22a0e9aba 100644
--- a/crates/sidebar/src/sidebar_tests.rs
+++ b/crates/sidebar/src/sidebar_tests.rs
@@ -604,7 +604,7 @@ fn request_test_tool_authorization(
) {
let tool_call_id = acp::ToolCallId::new(tool_call_id);
let label = format!("Tool {tool_call_id}");
- let option_id = acp_v1::PermissionOptionId::new(option_id);
+ let option_id = acp_v2::PermissionOptionId::new(option_id);
let _authorization_task = cx.update(|_, cx| {
thread.update(cx, |thread, cx| {
thread
@@ -612,10 +612,10 @@ fn request_test_tool_authorization(
acp_v1::ToolCall::new(acp_v1::ToolCallId::new(tool_call_id.0), label)
.kind(acp_v1::ToolKind::Edit)
.into(),
- PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(
+ PermissionOptions::Flat(vec![acp_v2::PermissionOption::new(
option_id,
"Allow",
- acp_v1::PermissionOptionKind::AllowOnce,
+ acp_v2::PermissionOptionKind::AllowOnce,
)]),
acp_thread::AuthorizationKind::PermissionGrant,
cx,
diff --git a/crates/zed/src/visual_test_runner.rs b/crates/zed/src/visual_test_runner.rs
index 23a62953753..f97554ec7b0 100644
--- a/crates/zed/src/visual_test_runner.rs
+++ b/crates/zed/src/visual_test_runner.rs
@@ -2092,15 +2092,28 @@ fn run_agent_thread_view_test(
let mut tool_locations: Vec<acp::ToolCallLocation> = Vec::new();
while let Ok(event) = event_receiver.try_recv() {
- if let Ok(agent::ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(
- update,
- ))) = event
+ if let Ok(agent::ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::V2(update))) =
+ event
{
- if let Some(content) = update.fields.content {
- tool_content.extend(content);
+ if let Some(content) = update.content.take() {
+ for content in content {
+ let acp_v2::ToolCallContent::Content(content) = content else {
+ anyhow::bail!(
+ "ReadFileTool produced non-content output in the image fixture"
+ );
+ };
+ tool_content.push(acp::ToolCallContent::Content(
+ acp::Content::new(acp_thread::content::to_v1(content.content)?)
+ .meta(content.meta),
+ ));
+ }
}
- if let Some(locations) = update.fields.locations {
- tool_locations.extend(locations);
+ if let Some(locations) = update.locations.take() {
+ tool_locations.extend(locations.into_iter().map(|location| {
+ acp::ToolCallLocation::new(location.path.into_inner())
+ .line(location.line)
+ .meta(location.meta)
+ }));
}
}
}