acp: Update agent-client-protocol to 5.0.0 (#66425)

Upgrades `agent-client-protocol` from 3.6.0 (schema 1.13.0) to 5.0.0
(schema 1.15.1), and brings Zed's v1 and v2 ACP clients in line with the
spec and schema changes made since then.

## SDK 5 port

- Schema types move from `schema::v1`/`schema::v2` to
`v1::schema`/`v2::schema`, builders to `Client.v1()`, and v2 handle
types to `agent_client_protocol::v2`.
- `agent_client_protocol::Error` is now the SDK's own type, not the v1
schema error. Zed uses it at the SDK boundary, and `ProtocolErrorInfo`
also recognizes it so auth-required detection keeps working.
- Foreground dispatch helpers are generic over the protocol marker, and
v2 request IDs come straight from the handles.
- SDK 5 only matches transport-closed errors that the SDK itself
produced, so peers can't forge them. A test that built one by hand now
covers only the local disconnect case. The `agent_servers` tests still
cover real transport loss.

## Spec changes

- `session/close` and `session/delete`: a `-32002` response counts as
success, on both v1 and v2.
- Permission and elicitation requests that name an unknown session get
`-32002` with `data.sessionId` instead of `-32603`. The v2 migration
guide makes this required for Clients too.
- v2 `usage_update.cost` is a patch field: omitted leaves it unchanged,
`null` clears it. A v1 update without a cost still leaves it unchanged.
- A `plan_update` whose type Zed can't render (`file`, `markdown`, or an
unknown type) still replaces the plan with that `planId`, so the old
entries stop showing.
- A diff `patch` with an unrecognized `format` renders from `changes`,
as if `patch` were omitted.
- v2 never sends an empty prompt.
- On v2, `session/cancel` no longer answers pending permission requests
locally. They stay open until the agent cancels them with
`$/cancel_request`, because requests for background work survive a
cancel. v1, including v1 subagents, keeps answering them with
`cancelled`.

## Follow-ups

These are left for separate PRs:
- Background-work UI: the `paused` status, the `background` list, and
cancel buttons for tool calls and terminals. Until then, `paused`
displays as in progress, which the spec allows.
- Subagent `cwd` and `additionalDirectories`.
- The new unstable methods: `auth/status`, `session/set_title`,
`session/status`, `session/archive`.

Release Notes:

- Improved compatibility with the latest Agent Client Protocol,
including handling of missing sessions, plan updates, diff formats, and
cancellation of permission requests.
This commit is contained in:
Ben Brandt
2026-11-02 15:26:50 +00:00
committed by GitHub
parent e38d4ec980
commit 4ec98df500
86 changed files with 567 additions and 422 deletions
Generated
+7 -6
View File
@@ -329,12 +329,13 @@ dependencies = [
[[package]]
name = "agent-client-protocol"
version = "3.6.0"
version = "5.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89b41f18aeb4a6d1a463b994cb880cc562cdea7d616ea3e22f9c6f2a438fc4f6"
checksum = "80ce60ce096020c2d0aa10445bc27b8856109e288abaf564ab517031ae819d69"
dependencies = [
"agent-client-protocol-derive",
"agent-client-protocol-schema",
"anyhow",
"futures 0.3.34",
"futures-concurrency",
"rustc-hash 2.1.1",
@@ -347,9 +348,9 @@ dependencies = [
[[package]]
name = "agent-client-protocol-derive"
version = "3.6.0"
version = "5.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d2d255cb5d3afa4760084fbcaf87c7d214d316328546cd777d8736a8af6e368"
checksum = "a12951a4e9a163a9384dec4e5681bd774c0fdb3871c5ed1deb7b44bc630df17a"
dependencies = [
"quote",
"syn 3.0.3",
@@ -357,9 +358,9 @@ dependencies = [
[[package]]
name = "agent-client-protocol-schema"
version = "1.13.0"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7c7cee33b16d162a617d5ea7292471c542ab31b416a2c089228aa8a6d4d18fe"
checksum = "1b2316d2cd561917bc2c16e3c64771c77e24363b56d40b58fdad091d02059992"
dependencies = [
"anyhow",
"derive_more",
+1 -1
View File
@@ -532,7 +532,7 @@ accesskit = { version = "0.24.0", features = ["enumn"] }
accesskit_macos = "0.26.0"
accesskit_unix = "0.22"
accesskit_windows = "0.34"
agent-client-protocol = { version = "=3.6.0", features = ["schemars", "unstable", "unstable_protocol_v2"] }
agent-client-protocol = { version = "=5.0.0", features = ["schemars", "unstable", "unstable_protocol_v2"] }
aho-corasick = "1.1"
alacritty_terminal = { git = "https://github.com/zed-industries/alacritty", rev = "4c129667ce56611becdc82de6e28218c80e2e88f" }
any_vec = "0.14"
+42 -41
View File
@@ -14,7 +14,7 @@ mod submission;
mod terminal;
pub use ::terminal::HeadlessTerminal;
use action_log::{ActionLog, ActionLogTelemetry};
use agent_client_protocol::schema::{MaybeUndefined, v1 as acp_v1, v2 as acp_v2};
use agent_client_protocol::{schema::MaybeUndefined, v1::schema as acp_v1, v2::schema as acp_v2};
use agent_settings::AgentSettings;
use anyhow::{Context as _, Result, anyhow};
use collections::{HashSet, IndexMap};
@@ -4985,8 +4985,11 @@ impl AcpThread {
acp_v1::SessionUpdate::UsageUpdate(update) => {
self.update_usage(
acp_v2::UsageUpdate::new(update.used, update.size)
.cost(update.cost.map(|cost| {
acp_v2::Cost::new(cost.amount, cost.currency).meta(cost.meta)
// v1 has no way to clear the cost, so a missing cost leaves it unchanged.
.cost(update.cost.map_or(MaybeUndefined::Undefined, |cost| {
MaybeUndefined::Value(
acp_v2::Cost::new(cost.amount, cost.currency).meta(cost.meta),
)
}))
.meta(update.meta),
cx,
@@ -6094,13 +6097,16 @@ impl AcpThread {
let usage = self.token_usage.get_or_insert_with(Default::default);
usage.max_tokens = update.size;
usage.used_tokens = update.used;
// The schema uses Option for cost, so omission and null both mean no new report.
if let Some(cost) = update.cost {
self.cost = Some(SessionCost {
amount: cost.amount,
currency: cost.currency.into(),
meta: cost.meta,
});
match update.cost {
MaybeUndefined::Undefined => {}
MaybeUndefined::Null => self.cost = None,
MaybeUndefined::Value(cost) => {
self.cost = Some(SessionCost {
amount: cost.amount,
currency: cost.currency.into(),
meta: cost.meta,
});
}
}
cx.emit(AcpThreadEvent::TokenUsageUpdated(
OutputTokensUpdate::Unchanged,
@@ -7534,15 +7540,17 @@ impl AcpThread {
{
self.connection.cancel(self.session_id(), cx)?;
}
if self.subagent_association.is_some() {
// The subagents RFD has a cancelled subagent answer all of its permission
// requests, including the tool-call ones a v1 subagent makes.
let request_ids = self.permission_requests.keys().copied().collect::<Vec<_>>();
for id in request_ids {
self.cancel_permission_request(id, cx);
if self.connection.answers_permission_requests_on_cancel() {
if self.subagent_association.is_some() {
// The subagents RFD has a cancelled subagent answer all of its permission
// requests, including the tool-call ones a v1 subagent makes.
let request_ids = self.permission_requests.keys().copied().collect::<Vec<_>>();
for id in request_ids {
self.cancel_permission_request(id, cx);
}
} else {
self.cancel_generic_permission_requests(cx);
}
} else {
self.cancel_generic_permission_requests(cx);
}
let receiver = self.activity.wait_for_idle()?;
let Some(receiver) = receiver else {
@@ -12167,29 +12175,22 @@ mod tests {
cx: &mut TestAppContext,
) {
init_test(cx);
for error in [
anyhow!("transport stopped").context(SubmissionDisconnected),
anyhow!(
agent_client_protocol::Error::internal_error().data(serde_json::json!({
"reason": agent_client_protocol::INCOMING_TRANSPORT_CLOSED_REASON,
"method": "session/prompt",
}))
),
] {
let (thread, _) = new_receipt_test_thread(cx).await;
let pending = thread.update(cx, |thread, cx| {
thread.submit_receipt(vec!["unknown".into()], Task::ready(Err(error)), cx)
});
let pending_id = pending.id;
assert!(pending.await.is_err());
thread.read_with(cx, |thread, _| {
assert!(matches!(
thread.submission(pending_id).expect("unknown").state,
SubmissionState::Disconnected { receipt: None }
));
assert!(!thread.has_unsettled_submissions());
});
}
// The SDK's transport-closed errors can only be produced by a real connection, so the
// agent_servers tests cover them.
let error = anyhow!("transport stopped").context(SubmissionDisconnected);
let (thread, _) = new_receipt_test_thread(cx).await;
let pending = thread.update(cx, |thread, cx| {
thread.submit_receipt(vec!["unknown".into()], Task::ready(Err(error)), cx)
});
let pending_id = pending.id;
assert!(pending.await.is_err());
thread.read_with(cx, |thread, _| {
assert!(matches!(
thread.submission(pending_id).expect("unknown").state,
SubmissionState::Disconnected { receipt: None }
));
assert!(!thread.has_unsettled_submissions());
});
}
#[gpui::test]
+1 -1
View File
@@ -1,4 +1,4 @@
use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2};
use agent_client_protocol::{v1::schema as acp_v1, v2::schema as acp_v2};
use anyhow::{Result, bail};
pub fn from_v1(methods: Vec<acp_v1::AuthMethod>) -> Result<Vec<acp_v2::AuthMethod>> {
+1 -1
View File
@@ -1,4 +1,4 @@
use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2};
use agent_client_protocol::{v1::schema as acp_v1, v2::schema as acp_v2};
use anyhow::{Result, bail};
pub fn from_v1(commands: Vec<acp_v1::AvailableCommand>) -> Result<Vec<acp_v2::AvailableCommand>> {
+1 -1
View File
@@ -1,4 +1,4 @@
use agent_client_protocol::schema::{MaybeUndefined, v1 as acp_v1, v2 as acp_v2};
use agent_client_protocol::{schema::MaybeUndefined, v1::schema as acp_v1, v2::schema as acp_v2};
use anyhow::{Result, bail};
pub fn update_from_v1(update: acp_v1::CompactionUpdate) -> Result<acp_v2::CompactionUpdate> {
+1 -1
View File
@@ -1,4 +1,4 @@
use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2};
use agent_client_protocol::{v1::schema as acp_v1, v2::schema as acp_v2};
use anyhow::{Result, bail};
pub fn from_v1(
+14 -1
View File
@@ -1,5 +1,5 @@
use crate::{AcpThread, ElicitationStore, ReceiptSubmission};
use agent_client_protocol::schema::{MaybeUndefined, v1 as acp_v1, v2 as acp_v2};
use agent_client_protocol::{schema::MaybeUndefined, v1::schema as acp_v1, v2::schema as acp_v2};
use anyhow::Result;
use chrono::{DateTime, Utc};
use collections::{HashMap, HashSet, IndexMap};
@@ -141,6 +141,12 @@ pub trait AgentConnection {
false
}
/// Whether cancelling a session's work answers its pending permission requests with
/// `cancelled` locally instead of waiting for the agent to cancel them.
fn answers_permission_requests_on_cancel(&self) -> bool {
true
}
/// Whether conversation teardown should invoke `close_session`.
/// The default preserves existing UI cleanup; backend-owned release hooks are separate.
/// Autonomous backends can opt out without disabling explicit close support.
@@ -583,6 +589,13 @@ pub struct ProtocolErrorInfo<'a> {
impl<'a> ProtocolErrorInfo<'a> {
pub fn from_error(error: &'a anyhow::Error) -> Option<Self> {
if let Some(error) = error.downcast_ref::<agent_client_protocol::Error>() {
return Some(Self {
code: error.code.into(),
message: &error.message,
data: error.data.as_ref(),
});
}
if let Some(error) = error.downcast_ref::<acp_v1::Error>() {
return Some(Self {
code: error.code.into(),
+1 -1
View File
@@ -1,4 +1,4 @@
use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2};
use agent_client_protocol::{v1::schema as acp_v1, v2::schema as acp_v2};
use anyhow::{Result, bail};
pub fn validate_prompt_content_for_v1(content: &[acp_v2::ContentBlock]) -> Result<()> {
+12 -7
View File
@@ -1,6 +1,6 @@
mod patch;
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
use anyhow::{Result, anyhow, ensure};
use buffer_diff::BufferDiff;
use collections::{HashMap, HashSet};
@@ -58,7 +58,12 @@ impl DiffPatch {
hunks: Vec::new(),
})
.collect::<Vec<_>>();
if source.patch.is_none() {
// A patch in a format Zed doesn't recognize renders as if it were omitted.
if source
.patch
.as_ref()
.is_none_or(|patch| patch.format != acp_v2::DiffPatchFormat::GitPatch)
{
return Self {
files,
fallback: None,
@@ -106,10 +111,6 @@ impl DiffPatch {
.patch
.as_ref()
.ok_or_else(|| anyhow!("no patch supplied"))?;
ensure!(
patch.format == acp_v2::DiffPatchFormat::GitPatch,
"unsupported patch format"
);
ensure!(
!source.changes.is_empty(),
"patch has no reported file changes"
@@ -1164,7 +1165,11 @@ mod tests {
source.patch.as_mut().expect("patch").format =
acp_v2::DiffPatchFormat::Other("_future".into());
let render = DiffPatch::new(&source, &languages, cx);
assert!(render.fallback.is_some());
assert_eq!(render.files.len(), 1);
assert!(
render.fallback.is_none(),
"an unrecognized format renders from changes as if patch were omitted"
);
let content = crate::ToolCallContent::DiffPatch { source, render };
assert!(
content
+1 -25
View File
@@ -1,4 +1,4 @@
use agent_client_protocol::schema::{v1, v2};
use agent_client_protocol::{v1::schema as v1, v2::schema as v2};
use anyhow::{Result, bail};
use std::collections::BTreeMap;
@@ -57,10 +57,6 @@ pub fn response_to_v1(
Ok(v1::CreateElicitationResponse::new(action).meta(response.meta))
}
pub fn error_to_v1(error: v2::Error) -> v1::Error {
v1::Error::new(error.code.into(), error.message).data(error.data)
}
fn scope_from_v1(scope: v1::ElicitationScope) -> Result<v2::ElicitationScope> {
Ok(match scope {
v1::ElicitationScope::Session(scope) => {
@@ -418,26 +414,6 @@ mod tests {
assert_eq!(serde_json::to_value(converted)?, fixture);
}
for (code, message, data) in [
(-32700, "Parse", None),
(-32600, "Invalid request", Some(json!(null))),
(-32601, "Missing method", Some(json!({}))),
(
-32602,
"Invalid parameters",
Some(json!({"parameter": [1, null]})),
),
(-32603, "Internal", Some(json!("detail"))),
(-32800, "Canceled", None),
(-32000, "Authentication", None),
(-32002, "Missing resource", None),
(17, "", Some(json!({"opaque": {"nested": [false, 2]}}))),
] {
let converted = error_to_v1(v2::Error::new(code, message).data(data.clone()));
assert_eq!(i32::from(converted.code), code);
assert_eq!(converted.message, message);
assert_eq!(converted.data, data);
}
Ok(())
}
}
+2 -2
View File
@@ -1,4 +1,4 @@
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use anyhow::{Context as _, Result, bail};
use file_icons::FileIcons;
use serde::{Deserialize, Serialize};
@@ -873,7 +873,7 @@ mod tests {
for value in ["", "session/ \0 雪 😀"] {
let wire = serde_json::json!({
"Thread": {
"id": agent_client_protocol::schema::v1::SessionId::new(value),
"id": agent_client_protocol::v1::schema::SessionId::new(value),
"name": "Thread",
},
});
+1 -1
View File
@@ -1,4 +1,4 @@
use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2};
use agent_client_protocol::{v1::schema as acp_v1, v2::schema as acp_v2};
use anyhow::{Result, bail};
pub fn from_v1(notice: acp_v1::Notice) -> Result<acp_v2::Notice> {
+1 -1
View File
@@ -1,4 +1,4 @@
use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2};
use agent_client_protocol::{v1::schema as acp_v1, v2::schema as acp_v2};
pub fn from_v1(capabilities: acp_v1::PromptCapabilities) -> acp_v2::PromptCapabilities {
acp_v2::PromptCapabilities::new()
+1 -1
View File
@@ -1,4 +1,4 @@
use agent_client_protocol::schema::{MaybeUndefined, v1 as acp_v1, v2 as acp_v2};
use agent_client_protocol::{schema::MaybeUndefined, v1::schema as acp_v1, v2::schema as acp_v2};
use anyhow::Result;
use gpui::SharedString;
+1 -1
View File
@@ -1,5 +1,5 @@
use crate::ReceiptSessionSubmissions;
use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2};
use agent_client_protocol::{v1::schema as acp_v1, v2::schema as acp_v2};
use futures::{
channel::oneshot,
future::{BoxFuture, LocalBoxFuture},
+1 -1
View File
@@ -1,4 +1,4 @@
use agent_client_protocol::schema::{MaybeUndefined, v1 as acp_v1, v2 as acp_v2};
use agent_client_protocol::{schema::MaybeUndefined, v1::schema as acp_v1, v2::schema as acp_v2};
use anyhow::{Result, bail};
use collections::HashMap;
use futures::{FutureExt as _, future::Shared};
+1 -1
View File
@@ -1,6 +1,6 @@
use std::{collections::HashSet, fmt::Display, rc::Rc, sync::Arc};
use agent_client_protocol::{Error, schema::v1::RequestId};
use agent_client_protocol::{Error, v1::schema::RequestId};
use agent_servers::{AcpDebugMessage, AcpDebugMessageContent, AcpDebugMessageDirection};
use agent_ui::agent_connection_store::AgentConnectionStatus;
use agent_ui::{Agent, AgentConnectionStore, AgentPanel};
+1 -1
View File
@@ -34,7 +34,7 @@ use acp_thread::{
AgentSessionListRequest, AgentSessionListResponse, ClientUserMessageId, ProcessOutput,
TokenUsageRatio,
};
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
use agent_skills::{
AGENTS_DIR_NAME, MAX_SKILL_DESCRIPTIONS_SIZE, MAX_SKILL_FILE_SIZE, ProjectSkillGroup,
SKILL_FILE_NAME, Skill, SkillIndex, SkillLoadError, SkillLoadWarning, SkillScopeId,
+2 -2
View File
@@ -1,6 +1,6 @@
use crate::{AgentMessage, AgentMessageContent, UserMessage, UserMessageContent};
use acp_thread::ClientUserMessageId;
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
use agent_settings::AgentProfileId;
use anyhow::Result;
use chrono::{DateTime, Utc};
@@ -821,7 +821,7 @@ impl ThreadsDatabase {
#[cfg(test)]
mod tests {
use super::*;
use agent_client_protocol::schema::v1 as acp;
use agent_client_protocol::v1::schema as acp;
use chrono::{DateTime, TimeZone, Utc};
use collections::HashMap;
use gpui::TestAppContext;
+1 -1
View File
@@ -4,7 +4,7 @@ use acp_thread::{
ClientUserMessageId, PermissionOptions, ProcessOutput, ThreadStatus,
};
use agent_client_protocol::schema::MaybeUndefined;
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
use agent_settings::{AgentProfileId, AgentSettings, AutoCompactThreshold, COMPACTION_PROMPT};
use anyhow::Result;
use client::{Client, RefreshLlmTokenListener, UserStore};
+1 -1
View File
@@ -1,5 +1,5 @@
use super::*;
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use gpui::{App, SharedString, Task};
use std::future;
use std::sync::Mutex;
+1 -1
View File
@@ -16,7 +16,7 @@ use crate::sandboxing::{
sandbox_worktree_writable_paths, sandboxing_available_for_project,
sandboxing_enabled_for_project,
};
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
use agent_settings::{
AgentProfileId, AgentProfileSettings, AgentSettings, AutoCompactThreshold, COMPACTION_PROMPT,
SUMMARIZE_THREAD_DETAILED_PROMPT, SUMMARIZE_THREAD_PROMPT, builtin_profiles,
+1 -1
View File
@@ -1,5 +1,5 @@
use crate::{DbThread, DbThreadMetadata, ThreadsDatabase};
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
use anyhow::{Result, anyhow};
use futures::{FutureExt, future::Shared};
use gpui::{App, Context, Entity, Global, Task, prelude::*};
@@ -1,7 +1,7 @@
use std::fmt::Write;
use std::sync::Arc;
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use gpui::{App, Entity, SharedString, Task};
use project::Project;
use schemars::JsonSchema;
+1 -1
View File
@@ -2,7 +2,7 @@ use std::collections::BTreeMap;
use std::sync::Arc;
use crate::{AgentTool, ToolCallEventStream, ToolInput};
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
use anyhow::Result;
use gpui::{App, SharedString, Task};
use language_model::LanguageModelToolResultContent;
@@ -1,5 +1,5 @@
use crate::{AgentToolOutput, AnyAgentTool, ToolCallEventStream, ToolInput};
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use anyhow::Result;
use collections::{BTreeMap, HashMap};
use context_server::{ContextServerId, client::NotificationSubscription};
+1 -1
View File
@@ -7,7 +7,7 @@ use crate::{
AgentTool, ToolCallEventStream, ToolInput, ToolPermissionDecision,
authorize_with_sensitive_settings, decide_permission_for_paths,
};
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use agent_settings::AgentSettings;
use futures::FutureExt as _;
use gpui::{App, Entity, Task};
@@ -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::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use agent_settings::AgentSettings;
use futures::FutureExt as _;
use gpui::{App, AppContext as _, AsyncApp, Entity, SharedString, Task};
+1 -1
View File
@@ -1,4 +1,4 @@
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use anyhow::Result;
use gpui::{App, SharedString, Task};
use language_model::LanguageModelToolResultContent;
+1 -1
View File
@@ -7,7 +7,7 @@ use crate::{
authorize_with_sensitive_settings, decide_permission_for_path,
};
use action_log::ActionLog;
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use agent_settings::AgentSettings;
use futures::{FutureExt as _, SinkExt, StreamExt, channel::mpsc};
use gpui::{App, AppContext, Entity, SharedString, Task};
+1 -1
View File
@@ -1,5 +1,5 @@
use crate::{AgentTool, ToolCallEventStream, ToolInput};
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use futures::{Future, FutureExt as _};
use gpui::{App, AsyncApp, Entity, Task};
use language::{DiagnosticSeverity, OffsetRangeExt};
+1 -1
View File
@@ -7,7 +7,7 @@ use super::edit_session::{
};
use crate::{AgentTool, Thread, ToolCallEventStream, ToolInput, ToolInputPayload};
use action_log::ActionLog;
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use anyhow::Result;
use futures::FutureExt as _;
use gpui::{App, AsyncApp, Entity, Task, WeakEntity};
+1 -1
View File
@@ -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::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use anyhow::Result;
use collections::HashSet;
use futures::{FutureExt, channel::oneshot};
+1 -1
View File
@@ -2,7 +2,7 @@ use std::rc::Rc;
use std::sync::Arc;
use std::{borrow::Cow, cell::RefCell};
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use anyhow::{Context as _, Result, bail};
use futures::{AsyncReadExt as _, FutureExt as _};
use gpui::{App, AppContext as _, Task};
+1 -1
View File
@@ -1,6 +1,6 @@
use crate::{AgentTool, ToolCallEventStream, ToolInput};
use acp_thread::MentionUri;
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use anyhow::{Result, anyhow};
use futures::FutureExt as _;
use gpui::{App, AppContext, Entity, SharedString, Task};
@@ -3,7 +3,7 @@ use std::sync::Arc;
use super::symbol_locator::{LocationDisplay, SymbolLocator};
use crate::{AgentTool, ToolCallEventStream, ToolInput};
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use gpui::{App, Entity, SharedString, Task};
use project::Project;
use schemars::JsonSchema;
@@ -1,7 +1,7 @@
use std::fmt::Write;
use std::sync::Arc;
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use gpui::{App, Entity, SharedString, Task};
use project::Project;
use schemars::JsonSchema;
@@ -3,7 +3,7 @@ use std::sync::Arc;
use super::symbol_locator::{LocationDisplay, SymbolLocator};
use crate::{AgentTool, ToolCallEventStream, ToolInput};
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use gpui::{App, Entity, SharedString, Task};
use project::Project;
use schemars::JsonSchema;
+1 -1
View File
@@ -1,6 +1,6 @@
use crate::{AgentTool, ToolCallEventStream, ToolInput};
use acp_thread::MentionUri;
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use anyhow::Result;
use futures::{FutureExt as _, StreamExt};
use gpui::{App, Entity, SharedString, Task};
@@ -1,4 +1,4 @@
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use anyhow::Result;
use gpui::{App, SharedString, Task};
use language_model::LanguageModelToolResultContent;
@@ -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::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use anyhow::{Context as _, Result, anyhow};
use fs::Fs;
use futures::StreamExt as _;
+1 -1
View File
@@ -7,7 +7,7 @@ use crate::{
AgentTool, ToolCallEventStream, ToolInput, ToolPermissionDecision,
authorize_with_sensitive_settings, decide_permission_for_paths,
};
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use agent_settings::AgentSettings;
use futures::FutureExt as _;
use gpui::{App, Entity, SharedString, Task};
+1 -1
View File
@@ -1,5 +1,5 @@
use action_log::ActionLog;
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use anyhow::{Context as _, Result, anyhow};
use futures::FutureExt as _;
use gpui::{App, Entity, SharedString, Task};
+1 -1
View File
@@ -1,7 +1,7 @@
use std::fmt::Write;
use std::sync::Arc;
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use collections::HashSet;
use gpui::{App, Entity, SharedString, Task};
use project::Project;
+1 -1
View File
@@ -1,4 +1,4 @@
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use agent_skills::Skill;
use anyhow::Result;
use gpui::{App, AsyncApp, SharedString, Task};
+1 -1
View File
@@ -1,5 +1,5 @@
use acp_thread::{SUBAGENT_SESSION_INFO_META_KEY, SubagentSessionInfo};
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
use anyhow::Result;
use gpui::{App, SharedString, Task};
use language_model::LanguageModelToolResultContent;
+1 -1
View File
@@ -1,5 +1,5 @@
use acp_thread::ProcessOutput;
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
use anyhow::Result;
use futures::FutureExt as _;
use gpui::{App, AsyncApp, Entity, SharedString, Task};
+1 -1
View File
@@ -2,7 +2,7 @@ use crate::{
Thread, ToolCallEventStream, ToolPermissionContext, ToolPermissionDecision,
decide_permission_for_path,
};
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use agent_skills::is_agents_skills_path;
use anyhow::{Result, anyhow};
use fs::Fs;
+1 -1
View File
@@ -1,7 +1,7 @@
use std::sync::Arc;
use crate::{AgentTool, ToolCallEventStream, ToolInput};
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use anyhow::Result;
use cloud_llm_client::WebSearchResponse;
use futures::FutureExt as _;
+1 -1
View File
@@ -4,7 +4,7 @@ use super::edit_session::{
};
use crate::{AgentTool, Thread, ToolCallEventStream, ToolInput, ToolInputPayload};
use action_log::ActionLog;
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use futures::FutureExt as _;
use gpui::{App, AsyncApp, Entity, Task, WeakEntity};
use language::LanguageRegistry;
+62 -50
View File
@@ -17,13 +17,14 @@ pub use v2::AcpV2Connection;
use acp_thread::{AcpThread, AuthRequired, ElicitationStore, LoadError};
use action_log::ActionLog;
use agent_client_protocol::schema::{
v1::{self as acp, ErrorCode},
v2 as acp_v2,
use agent_client_protocol::{
Agent, Client, HandleDispatchFrom, Handled, JsonRpcMessage, JsonRpcResponse, Protocol,
Responder, UntypedMessage,
v2::{Builder as V2Builder, ConnectionTo as V2ConnectionTo, Responder as V2Responder},
};
use agent_client_protocol::{
Agent, Client, HandleDispatchFrom, Handled, JsonRpcMessage, JsonRpcResponse, Responder,
UntypedMessage, V2Builder, V2ConnectionTo,
v1::schema::{self as acp, ErrorCode},
v2::schema as acp_v2,
};
use anyhow::{Context as _, Result, anyhow};
use collections::{HashMap, HashSet};
@@ -212,17 +213,20 @@ fn initialization_error(error: anyhow::Error, debug_log: &AcpDebugLog) -> anyhow
/// Helper for flattening the nested `Result` shapes that come out of
/// `entity.update(cx, |_, cx| fallible_op(cx))` into a single `Result<T,
/// acp::Error>`.
/// agent_client_protocol::Error>`.
///
/// `anyhow::Error` values get converted via `acp::Error::from`, which
/// downcasts an `acp::Error` back out of `anyhow` when present, so typed
/// `anyhow::Error` values get converted via `agent_client_protocol::Error::from`, which
/// downcasts an `agent_client_protocol::Error` back out of `anyhow` when present, so typed
/// errors like auth-required survive the trip.
trait FlattenAcpResult<T> {
fn flatten_acp(self) -> Result<T, acp::Error>;
fn flatten_acp(self) -> Result<T, agent_client_protocol::Error>;
}
impl<T> FlattenAcpResult<T> for Result<Result<T, anyhow::Error>, anyhow::Error> {
fn flatten_acp(self) -> Result<T, acp::Error> {
impl<T, E> FlattenAcpResult<T> for Result<Result<T, E>, anyhow::Error>
where
E: Into<agent_client_protocol::Error>,
{
fn flatten_acp(self) -> Result<T, agent_client_protocol::Error> {
match self {
Ok(Ok(value)) => Ok(value),
Ok(Err(err)) => Err(err.into()),
@@ -231,16 +235,6 @@ impl<T> FlattenAcpResult<T> for Result<Result<T, anyhow::Error>, anyhow::Error>
}
}
impl<T> FlattenAcpResult<T> for Result<Result<T, acp::Error>, anyhow::Error> {
fn flatten_acp(self) -> Result<T, acp::Error> {
match self {
Ok(Ok(value)) => Ok(value),
Ok(Err(err)) => Err(err),
Err(err) => Err(err.into()),
}
}
}
/// Holds state needed by foreground work dispatched from background handler closures.
struct ClientContext {
sessions: Rc<RefCell<HashMap<acp_v2::SessionId, AcpSession>>>,
@@ -254,8 +248,8 @@ struct ClientContext {
accepts_subagent_updates: bool,
}
fn dispatch_queue_closed_error() -> acp::Error {
acp::Error::internal_error().data("ACP foreground dispatch queue closed")
fn dispatch_queue_closed_error() -> agent_client_protocol::Error {
agent_client_protocol::Error::internal_error().data("ACP foreground dispatch queue closed")
}
/// Work items sent from `Send` handler closures to the `!Send` foreground thread.
@@ -324,7 +318,7 @@ impl ForegroundWorkItem for ClientDisconnectWork {
async fn settle_after_disconnect(
dispatch_tx: mpsc::UnboundedSender<ForegroundWork>,
) -> Result<(), acp::Error> {
) -> Result<(), agent_client_protocol::Error> {
let (acknowledgment, received) = futures::channel::oneshot::channel();
let work: ForegroundWork = Box::new(ClientDisconnectWork { acknowledgment });
if let Err(error) = dispatch_tx.unbounded_send(work) {
@@ -347,20 +341,22 @@ async fn drain_foreground_queue(dispatch_tx: &mpsc::UnboundedSender<ForegroundWo
.context("ACP foreground dispatch queue closed")
}
struct RequestForegroundWork<Req, Res>
struct RequestForegroundWork<Req, Res, P>
where
Req: Send + 'static,
Res: JsonRpcResponse + Send + 'static,
P: Protocol,
{
request: Req,
responder: Responder<Res>,
handler: fn(Req, Responder<Res>, &mut AsyncApp, &ClientContext),
responder: Responder<Res, P>,
handler: fn(Req, Responder<Res, P>, &mut AsyncApp, &ClientContext),
}
impl<Req, Res> ForegroundWorkItem for RequestForegroundWork<Req, Res>
impl<Req, Res, P> ForegroundWorkItem for RequestForegroundWork<Req, Res, P>
where
Req: Send + 'static,
Res: JsonRpcResponse + Send + 'static,
P: Protocol,
{
fn run(self: Box<Self>, cx: &mut AsyncApp, ctx: &ClientContext) {
let Self {
@@ -405,14 +401,15 @@ where
}
}
fn enqueue_request<Req, Res>(
fn enqueue_request<Req, Res, P>(
dispatch_tx: &mpsc::UnboundedSender<ForegroundWork>,
request: Req,
responder: Responder<Res>,
handler: fn(Req, Responder<Res>, &mut AsyncApp, &ClientContext),
responder: Responder<Res, P>,
handler: fn(Req, Responder<Res, P>, &mut AsyncApp, &ClientContext),
) where
Req: Send + 'static,
Res: JsonRpcResponse + Send + 'static,
P: Protocol,
{
let work: ForegroundWork = Box::new(RequestForegroundWork {
request,
@@ -728,7 +725,15 @@ fn is_disconnect_error(error: &anyhow::Error) -> bool {
})
}
fn map_acp_error(err: acp::Error) -> anyhow::Error {
/// Agents report `-32002` for a session that is already gone, which `session/close` and
/// `session/delete` treat as success.
fn is_resource_not_found(error: &anyhow::Error) -> bool {
error
.downcast_ref::<agent_client_protocol::Error>()
.is_some_and(|error| error.code == agent_client_protocol::ErrorCode::RESOURCE_NOT_FOUND)
}
fn map_acp_error(err: agent_client_protocol::Error) -> anyhow::Error {
let error = anyhow!(err);
match AuthRequired::from_error(&error) {
Some(auth_required) => error.context(auth_required),
@@ -739,12 +744,12 @@ fn map_acp_error(err: acp::Error) -> anyhow::Error {
fn session_thread(
ctx: &ClientContext,
session_id: &acp_v2::SessionId,
) -> Result<WeakEntity<AcpThread>, acp::Error> {
) -> Result<WeakEntity<AcpThread>, agent_client_protocol::Error> {
let sessions = ctx.sessions.borrow();
sessions
.get(session_id)
.map(|session| session.thread.clone())
.ok_or_else(|| acp::Error::internal_error().data(format!("unknown session: {session_id}")))
.ok_or_else(|| acp_v2::Error::session_not_found(session_id.clone()).into())
}
fn route_v2_session_notification(
@@ -940,7 +945,11 @@ fn handle_v2_session_notification(
.log_err();
}
fn respond_err<T: JsonRpcResponse>(responder: Responder<T>, err: acp::Error) {
fn respond_err<T: JsonRpcResponse, P: Protocol>(
responder: Responder<T, P>,
err: impl Into<agent_client_protocol::Error>,
) {
let err = err.into();
// Log the actual error we're returning — otherwise agents that hit an
// error path (e.g. unknown session) would see only the generic internal
// error returned over the wire with no trace of why on the client side.
@@ -951,7 +960,10 @@ fn respond_err<T: JsonRpcResponse>(responder: Responder<T>, err: acp::Error) {
responder.respond_with_error(err).log_err();
}
fn respond_result<T: JsonRpcResponse>(responder: Responder<T>, result: Result<T, acp::Error>) {
fn respond_result<T: JsonRpcResponse, P: Protocol>(
responder: Responder<T, P>,
result: Result<T, agent_client_protocol::Error>,
) {
match result {
Ok(response) => {
responder.respond(response).log_err();
@@ -962,13 +974,13 @@ fn respond_result<T: JsonRpcResponse>(responder: Responder<T>, result: Result<T,
fn handle_v2_request_permission(
request: acp_v2::RequestPermissionRequest,
responder: Responder<acp_v2::RequestPermissionResponse>,
responder: V2Responder<acp_v2::RequestPermissionResponse>,
cx: &mut AsyncApp,
context: &ClientContext,
) {
let cancellation = responder.cancellation();
if cancellation.is_cancelled() {
return respond_err(responder, acp::Error::request_cancelled());
return respond_err(responder, agent_client_protocol::Error::request_cancelled());
}
let thread = match session_thread(context, &request.session_id) {
Ok(thread) => thread,
@@ -976,9 +988,9 @@ fn handle_v2_request_permission(
};
let (request_id, task) = match thread
.update(cx, |thread, cx| {
thread
.request_permission(request, cx)
.map_err(|error| acp::Error::invalid_params().data(error.to_string()))
thread.request_permission(request, cx).map_err(|error| {
agent_client_protocol::Error::invalid_params().data(error.to_string())
})
})
.flatten_acp()
{
@@ -1010,15 +1022,15 @@ fn handle_v2_request_permission(
.detach();
}
fn handle_v2_create_elicitation(
fn handle_v2_create_elicitation<P: Protocol>(
args: acp_v2::CreateElicitationRequest,
responder: Responder<acp_v2::CreateElicitationResponse>,
responder: Responder<acp_v2::CreateElicitationResponse, P>,
cx: &mut AsyncApp,
ctx: &ClientContext,
) {
let cancellation = responder.cancellation();
if cancellation.is_cancelled() {
return respond_err(responder, acp::Error::request_cancelled());
return respond_err(responder, agent_client_protocol::Error::request_cancelled());
}
match args.scope() {
acp_v2::ElicitationScope::Session(scope) => {
@@ -1031,7 +1043,7 @@ fn handle_v2_create_elicitation(
.update(cx, |thread, cx| {
thread
.request_elicitation_with_id(args, cx)
.map_err(acp_thread::elicitation::error_to_v1)
.map_err(agent_client_protocol::Error::from)
})
.flatten_acp()
{
@@ -1040,7 +1052,7 @@ fn handle_v2_create_elicitation(
};
cx.spawn(async move |cx| {
let result: Result<_, acp::Error> = cancellation
let result: Result<_, agent_client_protocol::Error> = cancellation
.run_until_cancelled(async { Ok(task.await) })
.await;
@@ -1068,7 +1080,7 @@ fn handle_v2_create_elicitation(
{
return respond_err(
responder,
acp::Error::invalid_params()
agent_client_protocol::Error::invalid_params()
.data("Elicitation parent request is not owned by an active caller"),
);
}
@@ -1076,7 +1088,7 @@ fn handle_v2_create_elicitation(
let (elicitation_id, task) = match store.update(cx, |store, cx| {
store
.request_elicitation_with_id(args, cx)
.map_err(acp_thread::elicitation::error_to_v1)
.map_err(agent_client_protocol::Error::from)
}) {
Ok(task) => task,
Err(e) => return respond_err(responder, e),
@@ -1084,7 +1096,7 @@ fn handle_v2_create_elicitation(
let store = store.downgrade();
cx.spawn(async move |cx| {
let result: Result<_, acp::Error> = cancellation
let result: Result<_, agent_client_protocol::Error> = cancellation
.run_until_cancelled(async { Ok(task.await) })
.await;
@@ -1109,7 +1121,7 @@ fn handle_v2_create_elicitation(
_ => {
respond_err(
responder,
acp::Error::invalid_params().data("unknown elicitation scope"),
agent_client_protocol::Error::invalid_params().data("unknown elicitation scope"),
);
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
// The log shows v1 and v2 traffic. v1's ID type also covers the `null` ID of error
// responses, which v2 keeps even though v2 requests can't use it.
use agent_client_protocol::{Error, schema::v1::RequestId};
use agent_client_protocol::{Error, v1::schema::RequestId};
use std::{
collections::VecDeque,
sync::{Arc, Mutex},
+1 -1
View File
@@ -194,7 +194,7 @@ mod tests {
use super::*;
use crate::acp::v1::connect_client_future;
use acp_thread::{ElicitationStatus, ElicitationStore};
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use collections::HashMap;
use gpui::TestAppContext;
use std::{cell::RefCell, rc::Rc};
@@ -1,5 +1,5 @@
use acp_thread::{AcpThread, MessageKind};
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
use anyhow::Result;
use collections::HashMap;
use gpui::Context;
@@ -233,8 +233,18 @@ impl TryFrom<acp_v2::UpdateSessionNotification> for InboundSessionNotification {
InboundSessionUpdate::ToolCallContentChunk(chunk)
}
acp_v2::SessionUpdate::PlanUpdate(mut update) => {
// Zed only renders item plans, but any plan type replaces the plan with that ID.
let plan = match update.plan {
acp_v2::PlanUpdateContent::Items(plan) => plan,
acp_v2::PlanUpdateContent::File(plan) => {
acp_v2::PlanItems::new(plan.plan_id, Vec::new())
}
acp_v2::PlanUpdateContent::Markdown(plan) => {
acp_v2::PlanItems::new(plan.plan_id, Vec::new())
}
acp_v2::PlanUpdateContent::Other(plan) => {
acp_v2::PlanItems::new(plan.plan_id, Vec::new())
}
content => {
update.plan = content;
notification.update = acp_v2::SessionUpdate::PlanUpdate(update);
@@ -1,6 +1,6 @@
use acp_thread::{AcpThread, DisplayTerminalOutput, DisplayTerminalPatch};
use agent_client_protocol::schema::{MaybeUndefined, v2 as acp_v2};
use agent_client_protocol::{JsonRpcMessage, UntypedMessage};
use agent_client_protocol::{schema::MaybeUndefined, v2::schema as acp_v2};
use anyhow::{Context as _, Result};
use base64::{Engine as _, engine::general_purpose::STANDARD};
use gpui::Context;
@@ -139,7 +139,7 @@ mod tests {
)?;
let error =
parse_terminal_notification(&message).expect_err("malformed chunk must be rejected");
assert_eq!(error.code, agent_client_protocol::ErrorCode::InvalidParams);
assert_eq!(error.code, agent_client_protocol::ErrorCode::INVALID_PARAMS);
let serialized = serde_json::to_string(&error)?;
assert!(!serialized.contains("private-"));
assert!(serialized.len() < 200);
+178 -135
View File
@@ -11,14 +11,15 @@ use acp_thread::{
AgentSessionListResponse, ElicitationStore,
};
use action_log::ActionLog;
use agent_client_protocol::schema::{
MaybeUndefined, ProtocolVersion,
v1::{self as acp, ErrorCode},
v2 as acp_v2,
use agent_client_protocol::schema::{MaybeUndefined, ProtocolVersion};
use agent_client_protocol::{
Agent, Client, HandleDispatchFrom, JsonRpcRequest, Lines,
v1::{Builder, ConnectionTo, Responder},
v2::Builder as V2Builder,
};
use agent_client_protocol::{
Agent, Builder, Client, ConnectionTo, HandleDispatchFrom, JsonRpcRequest, Lines, Responder,
V2Builder,
v1::schema::{self as acp, ErrorCode},
v2::schema as acp_v2,
};
use anyhow::anyhow;
use async_channel;
@@ -327,10 +328,16 @@ impl AgentSessionList for AcpSessionList {
let updates_tx = self.updates_tx.clone();
let session_id = acp::SessionId::new(session_id.0.clone());
cx.foreground_executor().spawn(async move {
conn.send_request(acp::DeleteSessionRequest::new(session_id))
match conn
.send_request(acp::DeleteSessionRequest::new(session_id))
.block_task()
.await
.map_err(map_acp_error)?;
{
Ok(_) => {}
Err(error)
if error.code == agent_client_protocol::ErrorCode::RESOURCE_NOT_FOUND => {}
Err(error) => return Err(map_acp_error(error)),
}
updates_tx
.try_send(acp_thread::SessionListUpdate::Refresh)
.log_err();
@@ -384,7 +391,7 @@ pub(super) fn connect_client_future(
dispatch_tx: mpsc::UnboundedSender<ForegroundWork>,
connection_tx: futures::channel::oneshot::Sender<ConnectionTo<Agent>>,
shutdown: impl Future<Output = ()> + Send + 'static,
) -> impl Future<Output = Result<(), acp::Error>> {
) -> impl Future<Output = Result<(), agent_client_protocol::Error>> {
async move {
let cleanup = runtime::disconnect_cleanup(dispatch_tx.clone());
let future = client_builder(name, dispatch_tx)
@@ -429,7 +436,7 @@ fn client_builder(
}
Client
.builder()
.v1()
.name(name)
// --- Request handlers (agent→client) ---
.on_receive_request(
@@ -1337,7 +1344,7 @@ impl AgentConnection for AcpConnection {
.session_capabilities
.close
.is_some();
async move |result: Result<acp::NewSessionResponse, acp::Error>| {
async move |result: Result<acp::NewSessionResponse, agent_client_protocol::Error>| {
let session_id = result
.as_ref()
.ok()
@@ -1351,7 +1358,7 @@ impl AgentConnection for AcpConnection {
.on_receiving_result(
async move |result: Result<
acp::CloseSessionResponse,
acp::Error,
agent_client_protocol::Error,
>| {
if let Err(error) = result {
log::warn!(
@@ -2116,7 +2123,7 @@ pub mod test_support {
Rc::new(RefCell::new(None));
let agent_future = Agent
.builder()
.v1()
.name("fake-agent")
.on_receive_request(
async move |req: acp::InitializeRequest, responder, _cx| {
@@ -2190,7 +2197,8 @@ pub mod test_support {
let fail_next_prompt = fail_next_prompt.clone();
async move |_req: acp::PromptRequest, responder, _cx| {
if fail_next_prompt.swap(false, Ordering::SeqCst) {
responder.respond_with_error(acp::ErrorCode::InternalError.into())
responder
.respond_with_error(agent_client_protocol::Error::internal_error())
} else {
responder.respond(acp::PromptResponse::new(acp::StopReason::EndTurn))
}
@@ -2417,7 +2425,7 @@ mod tests {
#[test]
fn test_auth_error_mapping_retains_sdk_record_and_description() {
let original = acp::Error::new(-32000, "Sign in again")
let original = agent_client_protocol::Error::new(-32000, "Sign in again")
.data(serde_json::json!({"detail": {"retain": [null, 7]}}));
let mapped = map_acp_error(original.clone());
assert_eq!(
@@ -2444,11 +2452,11 @@ mod tests {
fs.insert_tree("/", serde_json::json!({ "a": {} })).await;
let project = project::Project::test(fs, [std::path::Path::new("/a")], cx).await;
let mut harness = test_support::connect_fake_acp_connection(project.clone(), cx).await;
let response_error = Arc::new(Mutex::new(acp::Error::auth_required()));
let response_error = Arc::new(Mutex::new(agent_client_protocol::Error::auth_required()));
let (client_transport, agent_transport) = agent_client_protocol::Channel::duplex();
let _agent_io_task = cx.background_spawn(
Agent
.builder()
.v1()
.name("prompt-auth-test-agent")
.on_receive_request(
async move |_request: acp::NewSessionRequest, responder, _cx| {
@@ -2497,8 +2505,8 @@ mod tests {
serde_json::json!({"auth": {"provider": "test", "retry": [null, false, 7]}}),
serde_json::json!({"details": "The user aborted a request"}),
] {
let original = acp::Error::new(
acp::ErrorCode::AuthRequired.into(),
let original = agent_client_protocol::Error::new(
agent_client_protocol::ErrorCode::AUTH_REQUIRED,
"Sign in to continue this prompt",
)
.data(data);
@@ -2703,10 +2711,10 @@ mod tests {
}
async fn v2_response<Response: 'static>(
response: Task<Result<Response, acp::Error>>,
response: Task<Result<Response, agent_client_protocol::Error>>,
cx: &mut gpui::TestAppContext,
description: &str,
) -> Result<Response, acp::Error> {
) -> Result<Response, agent_client_protocol::Error> {
let timeout = cx
.background_executor
.timer(std::time::Duration::from_secs(5));
@@ -2723,7 +2731,7 @@ mod tests {
request: Request,
cx: &mut gpui::TestAppContext,
) -> (
Task<Result<Request::Response, acp::Error>>,
Task<Result<Request::Response, agent_client_protocol::Error>>,
agent_client_protocol::RequestCancellationHandle,
)
where
@@ -3119,7 +3127,7 @@ mod tests {
(
"unknown",
json!([{"optionId": "allow", "name": "Allow", "kind": "allow_once"}]),
ErrorCode::InternalError,
ErrorCode::ResourceNotFound,
),
("v2-terminal-session", json!([]), ErrorCode::InvalidParams),
(
@@ -3524,7 +3532,7 @@ mod tests {
(
json!({"sessionId": "unknown", "mode": "form", "message": "Unknown session",
"requestedSchema": {"type": "object", "properties": {}}}),
ErrorCode::InternalError,
ErrorCode::ResourceNotFound,
),
(
json!({"sessionId": "v2-terminal-session", "mode": "url", "message": "Unsafe URL",
@@ -3856,7 +3864,7 @@ mod tests {
}
#[gpui::test]
async fn v2_usage_sdk_preserves_counters_and_optional_cost(cx: &mut gpui::TestAppContext) {
async fn v2_usage_sdk_preserves_counters_and_patches_cost(cx: &mut gpui::TestAppContext) {
use acp_thread::{AcpThreadEvent, TokenUsage};
use serde_json::json;
@@ -3895,19 +3903,19 @@ mod tests {
cx,
);
});
for (update, expected_amount, expected_currency) in [
// Omitted cost leaves the last report unchanged and `null` clears it.
for (update, expected_cost) in [
(
json!({"used": 1000, "size": 10000,
"cost": {"amount": 0.42, "currency": "USD", "_meta": {"scope": "cost"}}}),
0.42,
"USD",
Some((0.42, "USD")),
),
(json!({"used": 2000, "size": 20000}), 0.42, "USD"),
(json!({"used": 0, "size": 0, "cost": null}), 0.42, "USD"),
(json!({"used": 2000, "size": 20000}), Some((0.42, "USD"))),
(json!({"used": 0, "size": 0, "cost": null}), None),
(json!({"used": 1000, "size": 10000}), None),
(
json!({"used": 3000, "size": 30000, "cost": {"amount": 0, "currency": "EUR"}}),
0.0,
"EUR",
Some((0.0, "EUR")),
),
] {
let expected: acp_v2::UsageUpdate =
@@ -3929,13 +3937,18 @@ mod tests {
max_output_tokens: Some(789),
})
);
let cost = thread.cost().expect("retained cost");
assert_eq!(cost.amount, expected_amount);
assert_eq!(cost.currency.as_ref(), expected_currency);
assert_eq!(
cost.meta,
(expected_currency == "USD").then(|| v2_terminal_meta("cost"))
);
match expected_cost {
Some((expected_amount, expected_currency)) => {
let cost = thread.cost().expect("retained cost");
assert_eq!(cost.amount, expected_amount);
assert_eq!(cost.currency.as_ref(), expected_currency);
assert_eq!(
cost.meta,
(expected_currency == "USD").then(|| v2_terminal_meta("cost"))
);
}
None => assert!(thread.cost().is_none()),
}
assert!(thread.entries().is_empty());
assert!(!thread.had_error());
});
@@ -3952,7 +3965,7 @@ mod tests {
assert_eq!(thread.cost().expect("cost").amount, 0.0);
});
cx.run_until_parked();
assert_eq!(*events.borrow(), 6);
assert_eq!(*events.borrow(), 7);
assert!(harness.fallback.lock().expect("fallback mutex").is_empty());
}
@@ -5213,64 +5226,28 @@ mod tests {
#[gpui::test]
async fn v2_session_sdk_falls_through_unhandled_updates(cx: &mut gpui::TestAppContext) {
let harness = V2SessionHarness::new(cx).await;
harness.send(
serde_json::json!({"sessionUpdate": "plan_update",
"plan": {"type": "items", "planId": "unhandled-plan", "entries": [
{"content": "Retain", "priority": "low", "status": "pending"}]}}),
None,
);
harness.drain(cx).await;
let params = [
serde_json::json!({
"sessionId": "v2-terminal-session", "_meta": {"scope": "other envelope"},
"futureOuter": "keep",
"update": {
"sessionUpdate": "_future_terminal_neighbor",
"payload": {"bytes": ["not", "base64!"], "nested": {"unknown": null}},
"_meta": {"scope": "other update"}
}
}),
serde_json::json!({
"sessionId": "v2-terminal-session", "_meta": {"scope": "known envelope"},
"futureOuter": {"preserve": [1, null, true]},
"update": {"sessionUpdate": "plan_update",
"plan": {"type": "file", "planId": "unhandled-plan", "uri": "file:///tmp/plan.md"},
"_meta": {"scope": "known update"}, "futureKnownField": {"nested": "keep"}}
}),
serde_json::json!({
"sessionId": "v2-terminal-session",
"update": {"sessionUpdate": "plan_update",
"plan": {"type": "markdown", "planId": "unhandled-plan", "content": "Unsupported"}}
}),
serde_json::json!({
"sessionId": "v2-terminal-session",
"update": {"sessionUpdate": "plan_update",
"plan": {"type": "_future", "planId": "unhandled-plan", "payload": [null, 7]}}
}),
let params = serde_json::json!({
"sessionId": "v2-terminal-session", "_meta": {"scope": "other envelope"},
"futureOuter": "keep",
"update": {
"sessionUpdate": "_future_terminal_neighbor",
"payload": {"bytes": ["not", "base64!"], "nested": {"unknown": null}},
"_meta": {"scope": "other update"}
}
});
let sent = agent_client_protocol::UntypedMessage::new("session/update", &params)
.expect("raw SDK notification");
let notification: acp_v2::UpdateSessionNotification =
serde_json::from_value(params).expect("typed SDK notification");
let mut expected = vec![
notification
.to_untyped_message()
.expect("SDK typed fallthrough"),
];
let sent = params
.iter()
.map(|params| {
agent_client_protocol::UntypedMessage::new("session/update", params)
.expect("raw SDK notification")
})
.collect::<Vec<_>>();
let mut expected = params
.iter()
.map(|params| {
let notification: acp_v2::UpdateSessionNotification =
serde_json::from_value(params.clone()).expect("typed SDK notification");
notification
.to_untyped_message()
.expect("SDK typed fallthrough")
})
.collect::<Vec<_>>();
for message in &sent {
harness
.agent
.send_notification(message.clone())
.expect("send unrelated SDK update");
}
harness
.agent
.send_notification(sent)
.expect("send unrelated SDK update");
let unrelated_method = agent_client_protocol::UntypedMessage::new(
"_other/notification",
serde_json::json!({
@@ -5293,17 +5270,50 @@ mod tests {
thread.foreground_activity(),
acp_thread::ForegroundActivity::Idle
);
let plan = thread
.plan_by_id(&"unhandled-plan".into())
.expect("retained plan");
assert_eq!(
plan.entries.first().expect("entry").source.content,
"Retain"
);
assert!(thread.entries().is_empty());
});
}
#[gpui::test]
async fn v2_plan_sdk_unrenderable_types_replace_the_plan(cx: &mut gpui::TestAppContext) {
use serde_json::json;
let harness = V2SessionHarness::new(cx).await;
let plan_id = acp_v2::PlanId::new("plan");
for replacement in [
json!({"type": "file", "planId": "plan", "uri": "file:///tmp/plan.md"}),
json!({"type": "markdown", "planId": "plan", "content": "Unsupported"}),
json!({"type": "_future", "planId": "plan", "payload": [null, 7]}),
] {
harness.send(
json!({"sessionUpdate": "plan_update",
"plan": {"type": "items", "planId": "plan", "entries": [
{"content": "Stale", "priority": "low", "status": "pending"}]}}),
None,
);
harness.drain(cx).await;
harness.thread.read_with(cx, |thread, _| {
assert_eq!(thread.plan_by_id(&plan_id).expect("plan").entries.len(), 1);
});
harness.send(
json!({"sessionUpdate": "plan_update", "plan": replacement}),
None,
);
harness.drain(cx).await;
harness.thread.read_with(cx, |thread, _| {
assert!(
thread
.plan_by_id(&plan_id)
.expect("replaced plan")
.entries
.is_empty(),
"{replacement} must replace the stale entries"
);
});
}
assert!(harness.fallback.lock().expect("fallback mutex").is_empty());
}
fn init_settings_test(cx: &mut gpui::TestAppContext) {
cx.update(|cx| {
let settings_store = SettingsStore::test(cx);
@@ -6144,7 +6154,7 @@ mod tests {
cx.background_spawn(
Agent
.builder()
.v1()
.name("list-test-agent")
.on_receive_request(
{
@@ -6160,11 +6170,11 @@ mod tests {
.detach();
let (connection_tx, connection_rx) = futures::channel::oneshot::channel();
cx.background_spawn(Client.builder().name("list-test-client").connect_with(
cx.background_spawn(Client.v1().name("list-test-client").connect_with(
client_transport,
move |connection: ConnectionTo<Agent>| async move {
connection_tx.send(connection).ok();
futures::future::pending::<Result<(), acp::Error>>().await
futures::future::pending::<Result<(), agent_client_protocol::Error>>().await
},
))
.detach();
@@ -6227,17 +6237,24 @@ mod tests {
cx.background_spawn(
Agent
.builder()
.v1()
.name("delete-test-agent")
.on_receive_request(
{
let deleted_sessions = deleted_sessions.clone();
async move |request: acp::DeleteSessionRequest, responder, _cx| {
let missing = request.session_id.0.as_ref() == "missing";
deleted_sessions
.lock()
.expect("deleted sessions lock should not be poisoned")
.push(request.session_id);
responder.respond(acp::DeleteSessionResponse::default())
.push(request.session_id.clone());
if missing {
responder.respond_with_error(
acp::Error::session_not_found(request.session_id).into(),
)
} else {
responder.respond(acp::DeleteSessionResponse::default())
}
}
},
agent_client_protocol::on_receive_request!(),
@@ -6247,11 +6264,11 @@ mod tests {
.detach();
let (connection_tx, connection_rx) = futures::channel::oneshot::channel();
cx.background_spawn(Client.builder().name("delete-test-client").connect_with(
cx.background_spawn(Client.v1().name("delete-test-client").connect_with(
client_transport,
move |connection: ConnectionTo<Agent>| async move {
connection_tx.send(connection).ok();
futures::future::pending::<Result<(), acp::Error>>().await
futures::future::pending::<Result<(), agent_client_protocol::Error>>().await
},
))
.detach();
@@ -6271,7 +6288,7 @@ mod tests {
let requests = Arc::new(Mutex::new(Vec::new()));
cx.background_spawn(
Agent
.builder()
.v1()
.on_receive_request(
{
let requests = requests.clone();
@@ -6279,7 +6296,9 @@ mod tests {
let rejected = request.mode_id.0.as_ref() == "reject";
requests.lock().expect("mode requests").push(request);
if rejected {
responder.respond_with_error(acp::Error::invalid_params())
responder.respond_with_error(
agent_client_protocol::Error::invalid_params(),
)
} else {
responder.respond(acp::SetSessionModeResponse::default())
}
@@ -6291,11 +6310,11 @@ mod tests {
)
.detach();
let (sender, receiver) = futures::channel::oneshot::channel();
cx.background_spawn(Client.builder().connect_with(
cx.background_spawn(Client.v1().connect_with(
client_transport,
move |connection: ConnectionTo<Agent>| async move {
sender.send(connection).expect("client connection");
futures::future::pending::<Result<(), acp::Error>>().await
futures::future::pending::<Result<(), agent_client_protocol::Error>>().await
},
))
.detach();
@@ -6653,7 +6672,7 @@ mod tests {
#[gpui::test]
async fn default_config_options_preserve_state_on_error(cx: &mut gpui::TestAppContext) {
let (connection, requests) = connect_config_defaults_test_agent_with_handler(
|_| Err(acp::Error::invalid_params()),
|_| Err(agent_client_protocol::Error::invalid_params()),
cx,
)
.await;
@@ -6917,7 +6936,8 @@ mod tests {
async fn connect_config_defaults_test_agent_with_handler(
handler: impl Fn(
acp::SetSessionConfigOptionRequest,
) -> Result<acp::SetSessionConfigOptionResponse, acp::Error>
)
-> Result<acp::SetSessionConfigOptionResponse, agent_client_protocol::Error>
+ Send
+ Sync
+ 'static,
@@ -6931,7 +6951,10 @@ mod tests {
}
async fn connect_config_defaults_test_agent_with_async_handler<
F: Future<Output = Result<acp::SetSessionConfigOptionResponse, acp::Error>> + Send + 'static,
F: Future<
Output = Result<acp::SetSessionConfigOptionResponse, agent_client_protocol::Error>,
> + Send
+ 'static,
>(
handler: impl Fn(acp::SetSessionConfigOptionRequest) -> F + Send + Sync + 'static,
cx: &mut gpui::TestAppContext,
@@ -6969,7 +6992,7 @@ mod tests {
cx.background_spawn(
Agent
.builder()
.v1()
.name("config-defaults-test-agent")
.on_receive_request(
async move |request: acp::SetSessionConfigOptionRequest, responder, _cx| {
@@ -6987,13 +7010,13 @@ mod tests {
let (connection_tx, connection_rx) = futures::channel::oneshot::channel();
let client_io_task = cx.background_spawn(async move {
Client
.builder()
.v1()
.name("config-defaults-test-client")
.connect_with(
client_transport,
move |connection: ConnectionTo<Agent>| async move {
connection_tx.send(connection).ok();
futures::future::pending::<Result<(), acp::Error>>().await
futures::future::pending::<Result<(), agent_client_protocol::Error>>().await
},
)
.await
@@ -7045,6 +7068,19 @@ mod tests {
);
}
#[gpui::test]
async fn session_list_delete_treats_resource_not_found_as_deleted(
cx: &mut gpui::TestAppContext,
) {
let deleted_sessions = Arc::new(std::sync::Mutex::new(Vec::new()));
let connection = connect_session_delete_test_agent(deleted_sessions.clone(), cx).await;
let session_list = AcpSessionList::new(connection, true);
cx.update(|cx| session_list.delete_session(&acp_v2::SessionId::new("missing"), cx))
.await
.expect("-32002 counts as deleted");
}
#[gpui::test]
async fn session_list_delete_does_not_send_when_unsupported(cx: &mut gpui::TestAppContext) {
let deleted_sessions = Arc::new(std::sync::Mutex::new(Vec::new()));
@@ -7508,7 +7544,8 @@ exit 7
struct NewSessionTestBehavior {
received: async_channel::Sender<agent_client_protocol::RequestCancellation>,
respond: async_channel::Receiver<Result<acp::NewSessionResponse, acp::Error>>,
respond:
async_channel::Receiver<Result<acp::NewSessionResponse, agent_client_protocol::Error>>,
updates: Vec<acp::SessionUpdate>,
}
@@ -7567,7 +7604,7 @@ exit 7
// Build the fake agent side. It handles the requests issued by
// `AcpConnection` during the test and tracks load/close counts.
let agent_future = Agent
.builder()
.v1()
.name("fake-agent")
.on_receive_request(
async move |req: acp::InitializeRequest, responder, _cx| {
@@ -8703,12 +8740,15 @@ exit 7
)
});
request_received.recv().await.expect("new-session request");
let rejection = acp::Error::invalid_params();
let rejection = agent_client_protocol::Error::invalid_params();
respond
.try_send(Err(rejection.clone()))
.expect("reject session creation");
let error = creation.await.expect_err("creation must reject");
assert_eq!(error.downcast_ref::<acp::Error>(), Some(&rejection));
assert_eq!(
error.downcast_ref::<agent_client_protocol::Error>(),
Some(&rejection)
);
cx.run_until_parked();
assert!(connection.sessions.borrow().is_empty());
assert_eq!(close_count.load(Ordering::SeqCst), 0);
@@ -9994,14 +10034,15 @@ impl acp_thread::AgentSessionConfigOptions for AcpSessionConfigOptions {
fn permission_option_from_v1(
option: acp::PermissionOption,
) -> Result<acp_v2::PermissionOption, acp::Error> {
) -> Result<acp_v2::PermissionOption, agent_client_protocol::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"));
return Err(agent_client_protocol::Error::invalid_params()
.data("unsupported permission option kind"));
}
};
Ok(acp_v2::PermissionOption::new(
@@ -10099,11 +10140,12 @@ fn handle_create_elicitation(
) {
let args = match acp_thread::elicitation::request_from_v1(args) {
Ok(args) => args,
Err(error) => return respond_err(responder, acp::Error::from(error)),
Err(error) => return respond_err(responder, agent_client_protocol::Error::from(error)),
};
let responder = responder.wrap_params(|_, response| {
response.and_then(|response| {
acp_thread::elicitation::response_to_v1(response).map_err(acp::Error::from)
acp_thread::elicitation::response_to_v1(response)
.map_err(agent_client_protocol::Error::from)
})
});
handle_v2_create_elicitation(args, responder, cx, ctx);
@@ -10136,12 +10178,12 @@ fn handle_write_text_file(
};
cx.spawn(async move |cx| {
let result: Result<_, acp::Error> = async {
let result: Result<_, agent_client_protocol::Error> = async {
thread
.update(cx, |thread, cx| {
thread.write_text_file(args.path, args.content, cx)
})
.map_err(acp::Error::from)?
.map_err(agent_client_protocol::Error::from)?
.await?;
Ok(())
}
@@ -10178,8 +10220,9 @@ fn handle_read_text_file(
.update(cx, |thread, cx| {
thread.read_text_file(args.path, args.line, args.limit, false, cx)
})
.map_err(acp::Error::from)?
.map_err(agent_client_protocol::Error::from)?
.await
.map_err(agent_client_protocol::Error::from)
})
.await;
@@ -10406,14 +10449,14 @@ fn handle_create_terminal(
};
let project = match thread
.read_with(cx, |thread, _cx| thread.project().clone())
.map_err(acp::Error::from)
.map_err(agent_client_protocol::Error::from)
{
Ok(p) => p,
Err(e) => return respond_err(responder, e),
};
cx.spawn(async move |cx| {
let result: Result<_, acp::Error> = async {
let result: Result<_, agent_client_protocol::Error> = async {
let terminal_entity = acp_thread::create_terminal_entity(
args.command.clone(),
&args.args,
+135 -51
View File
@@ -3,8 +3,8 @@ use super::{
ContextServerConfiguration, ForegroundWork, PendingSessionUpdates, ReadOnlyConfigOptions,
UnsupportedVersion, apply_v2_session_notification, close_undelivered_session,
drain_foreground_queue, enqueue_notification, first_class_terminal_auth_task,
is_disconnect_error, map_acp_error, mcp_configurations_for_project, runtime, transport,
with_v2_client_ingress, work_dirs_from_session_info,
is_disconnect_error, is_resource_not_found, map_acp_error, mcp_configurations_for_project,
runtime, transport, with_v2_client_ingress, work_dirs_from_session_info,
};
use acp_thread::{
AcpThread, AgentConnection, AgentSessionConfigOptions, AgentSessionInfo, AgentSessionList,
@@ -13,9 +13,10 @@ use acp_thread::{
};
use action_log::ActionLog;
use agent_client_protocol::{
Agent, Client, ConnectTo, InitializeOutcome, JsonRpcRequest, JsonRpcResponse, Lines,
PreparedRequest, RequestCancellationHandle, V2ConnectionTo,
schema::{ProtocolVersion, v1 as acp_v1, v2 as acp},
Agent, Client, ConnectTo, JsonRpcRequest, JsonRpcResponse, Lines, RequestCancellationHandle,
schema::ProtocolVersion,
v2::schema as acp,
v2::{ConnectionTo as V2ConnectionTo, InitializeOutcome, PreparedRequest},
};
use anyhow::{Context as _, Result, anyhow};
use collections::HashMap;
@@ -41,14 +42,6 @@ fn is_connection_closed(connection: &V2ConnectionTo<Agent>) -> bool {
/// The SDK reports JSON-RPC IDs with the v1 type, which allows `null`. It never assigns
/// `null` to a request it sends and rejects incoming v2 requests that use it.
fn v2_request_id(request_id: &acp_v1::RequestId) -> Result<acp::RequestId> {
match request_id {
acp_v1::RequestId::Number(id) => Ok(acp::RequestId::Number(*id)),
acp_v1::RequestId::Str(id) => Ok(acp::RequestId::Str(id.clone())),
acp_v1::RequestId::Null => Err(anyhow!("v2 requests cannot have a null ID")),
}
}
fn cancel_request_elicitations(
request_id: acp::RequestId,
cx: &mut AsyncApp,
@@ -101,6 +94,7 @@ fn validate_prompt_content(
capabilities: &acp::PromptCapabilities,
content: &[acp::ContentBlock],
) -> Result<()> {
anyhow::ensure!(!content.is_empty(), "Prompt must not be empty");
for block in content {
let supported = match block {
acp::ContentBlock::Text(_) | acp::ContentBlock::ResourceLink(_) => true,
@@ -594,7 +588,7 @@ impl AcpV2Connection {
// An eagerly spawned child can publish before cancellation drops an unpolled caller.
async move {
let request = connection.prepare_request(request);
let request_id = v2_request_id(request.id())?;
let request_id = request.id().clone();
let cancellation = request.cancellation_handle();
enqueue_notification(&dispatch_tx, request_id.clone(), register_request);
let response = request.block_task();
@@ -1030,10 +1024,7 @@ impl AcpV2Connection {
};
thread.update(cx, |thread, cx| thread.mark_activity_unconfirmed(cx));
let request = self.connection.prepare_request(request);
let request_id = match v2_request_id(request.id()) {
Ok(request_id) => request_id,
Err(error) => return Task::ready(Err(error)),
};
let request_id = request.id().clone();
let cancellation = request.cancellation_handle();
let (response, applied) = Self::ordered_prepared_response(
&self.connection,
@@ -1167,7 +1158,7 @@ impl AcpV2Connection {
let response = async move {
preflight()?;
let (sender, received) = futures::channel::oneshot::channel();
let request_id = v2_request_id(request.id())?;
let request_id = request.id().clone();
let cancellation = request.cancellation_handle();
enqueue_notification(&dispatch_tx, request_id.clone(), register_request);
let published = request.on_receiving_result({
@@ -1306,10 +1297,7 @@ impl AgentConnection for AcpV2Connection {
.additional_directories(context.additional_directories.clone())
.mcp_servers(context.mcp_servers.clone());
let request = self.connection.prepare_request(request);
let request_id = match v2_request_id(request.id()) {
Ok(request_id) => request_id,
Err(error) => return Task::ready(Err(error)),
};
let request_id = request.id().clone();
let (response, applied) = Self::ordered_prepared_response(
&self.connection,
&self.dispatch_tx,
@@ -1553,6 +1541,13 @@ impl AgentConnection for AcpV2Connection {
if result.is_err() {
drain_foreground_queue(&dispatch_tx).await.log_err();
}
let result = result.or_else(|error| {
if is_resource_not_found(&error) {
Ok(())
} else {
Err(error)
}
});
if let Some(this) = this.upgrade() {
if result.is_ok() {
if let Some(thread) = thread.upgrade() {
@@ -1612,6 +1607,12 @@ impl AgentConnection for AcpV2Connection {
validate_prompt_content(&session.prompt.clone().unwrap_or_default(), content)
}
fn answers_permission_requests_on_cancel(&self) -> bool {
// Only the agent knows which requests belong to the cancelled foreground work:
// requests for background work stay open, and the rest get `$/cancel_request`.
false
}
fn should_close_sessions_on_release(&self) -> bool {
// V2 close cancels agent-owned work; disposing a view must only detach.
false
@@ -1782,8 +1783,11 @@ impl AgentSessionList for V2SessionList {
acp::DeleteSessionRequest::new(session_id.clone()),
);
cx.foreground_executor().spawn(async move {
response.await?;
Ok(())
match response.await {
Ok(_) => Ok(()),
Err(error) if is_resource_not_found(&error) => Ok(()),
Err(error) => Err(error),
}
})
}
@@ -1958,8 +1962,8 @@ mod tests {
use super::*;
use acp_thread::ElicitationStatus;
use agent_client_protocol::{
Responder,
schema::v1::{self as acp_v1, ErrorCode},
v1::schema::{self as acp_v1, ErrorCode},
v2::Responder,
};
use gpui::TestAppContext;
use serde_json::json;
@@ -2107,10 +2111,7 @@ mod tests {
responder: Responder<acp::NewSessionResponse>,
agent: V2ConnectionTo<Client>| {
new_sender
.try_send((
request.clone(),
v2_request_id(responder.id()).expect("v2 request ID"),
))
.try_send((request.clone(), responder.id().clone()))
.expect("record creation");
if *deferred_new.lock().expect("new response mode") {
new_reply_sender
@@ -2279,8 +2280,7 @@ mod tests {
.expect_err("barrier has no session owner");
assert_eq!(
error,
agent_client_protocol::Error::internal_error()
.data("unknown session: unbound-barrier")
acp::Error::session_not_found("unbound-barrier").into()
);
}
@@ -3140,6 +3140,56 @@ mod tests {
});
}
#[gpui::test]
async fn v2_cancel_sdk_leaves_permission_requests_to_the_agent(cx: &mut TestAppContext) {
let harness = SessionHarness::new(session_capabilities(), vec![], vec![], cx).await;
let thread = harness.thread(cx).await;
let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
harness.send_update(
&session_id.0,
acp::SessionUpdate::StateUpdate(acp::StateUpdate::Running(
acp::RunningStateUpdate::new(),
)),
);
let permission = harness
.agent
.send_request(acp::RequestPermissionRequest::new(
session_id.clone(),
"Keep watching",
vec![acp::PermissionOption::new(
"allow",
"Allow",
acp::PermissionOptionKind::AllowOnce,
)],
));
let permission_cancellation = permission.cancellation_handle();
let permission = cx.background_spawn(permission.block_task());
harness.drain_updates(cx).await;
let _cancellation = thread.update(cx, |thread, cx| thread.cancel(cx));
bounded(harness.cancellations.recv(), cx)
.await
.expect("session cancel");
cx.run_until_parked();
assert_eq!(
thread.read_with(cx, |thread, _| thread.pending_permission_requests().count()),
1,
"only the agent knows whether the request belongs to the cancelled work"
);
permission_cancellation.cancel().expect("cancel request");
let error = bounded(permission, cx)
.await
.expect_err("cancelled by the agent");
assert_eq!(
error.code,
agent_client_protocol::ErrorCode::REQUEST_CANCELLED
);
cx.run_until_parked();
assert_eq!(
thread.read_with(cx, |thread, _| thread.pending_permission_requests().count()),
0
);
}
#[gpui::test]
async fn v2_cancel_sdk_eof_fails_observation_without_inventing_idle(cx: &mut TestAppContext) {
use acp_thread::ForegroundActivity;
@@ -3501,6 +3551,7 @@ done
);
assert!(validate_prompt_content(&capabilities, &[block]).is_ok());
}
assert!(validate_prompt_content(&acp::PromptCapabilities::default(), &[]).is_err());
}
#[gpui::test]
@@ -3820,6 +3871,46 @@ done
assert!(harness.closes.is_empty());
}
#[gpui::test]
async fn v2_delete_sdk_treats_resource_not_found_as_deleted(cx: &mut TestAppContext) {
let capabilities = acp::AgentCapabilities::new()
.session(acp::SessionCapabilities::new().delete(acp::SessionDeleteCapabilities::new()));
let harness = SessionHarness::new(capabilities, vec![], vec![], cx).await;
let list = cx
.update(|cx| harness.client.session_list(cx))
.expect("session discovery");
let deleted = cx.update(|cx| list.delete_session(&"missing".into(), cx));
let (_, responder) = bounded(harness.delete_requests.recv(), cx)
.await
.expect("delete");
responder
.respond_with_error(acp::Error::session_not_found("missing").into())
.expect("not found");
bounded(deleted, cx)
.await
.expect("-32002 counts as deleted");
}
#[gpui::test]
async fn v2_close_sdk_treats_resource_not_found_as_closed(cx: &mut TestAppContext) {
let harness = SessionHarness::new(session_capabilities(), vec![], vec![], cx).await;
let thread = harness.resumed_thread(None, cx).await;
harness.defer_closes();
let closing = harness.close(cx);
let (request, responder) = bounded(harness.close_requests.recv(), cx)
.await
.expect("close");
responder
.respond_with_error(acp::Error::session_not_found(request.session_id).into())
.expect("not found");
bounded(closing, cx).await.expect("-32002 counts as closed");
bounded(harness.close(cx), cx)
.await
.expect_err("the closed session was released");
assert!(harness.close_requests.is_empty());
drop(thread);
}
#[gpui::test]
async fn v2_new_session_keeps_subagent_traffic_sent_before_its_response(
cx: &mut TestAppContext,
@@ -6023,9 +6114,7 @@ done
.agent
.send_request(acp::CreateElicitationRequest::new(
acp::ElicitationFormMode::new(
acp::ElicitationRequestScope::new(
v2_request_id(responder.id()).expect("v2 request ID"),
),
acp::ElicitationRequestScope::new(responder.id().clone()),
acp::ElicitationSchema::new(),
),
"Resume setup input",
@@ -6363,9 +6452,7 @@ done
.agent
.send_request(acp::CreateElicitationRequest::new(
acp::ElicitationFormMode::new(
acp::ElicitationRequestScope::new(
v2_request_id(responder.id()).expect("v2 request ID"),
),
acp::ElicitationRequestScope::new(responder.id().clone()),
acp::ElicitationSchema::new(),
),
"Resume setup",
@@ -6713,8 +6800,7 @@ done
async move |request: acp::LoginAuthRequest,
responder: Responder<acp::LoginAuthResponse>,
agent: V2ConnectionTo<Client>| {
let request_id =
v2_request_id(responder.id()).expect("v2 request ID");
let request_id = responder.id().clone();
let method_id = request.method_id.clone();
logins
.lock()
@@ -6898,8 +6984,7 @@ done
.expect("published prompt");
assert_eq!(received, request);
let cancellation = responder.cancellation();
let input =
harness.request_input(v2_request_id(responder.id()).expect("v2 request ID"), cx);
let input = harness.request_input(responder.id().clone(), cx);
harness.registered(cx).await;
let expected = acp::PromptResponse::new("accepted-message").meta(meta("receipt"));
responder
@@ -7002,7 +7087,7 @@ done
.await
.expect("first prompt");
let first_cancellation = first_responder.cancellation();
let first_id = v2_request_id(first_responder.id()).expect("v2 request ID");
let first_id = first_responder.id().clone();
let first_input = harness.request_input(first_id.clone(), cx);
harness.registered(cx).await;
let second = cx.update(|cx| {
@@ -7015,10 +7100,7 @@ done
.await
.expect("second prompt");
let second_cancellation = second_responder.cancellation();
let second_input = harness.request_input(
v2_request_id(second_responder.id()).expect("v2 request ID"),
cx,
);
let second_input = harness.request_input(second_responder.id().clone(), cx);
harness.registered(cx).await;
drop(first);
bounded(first_cancellation.cancelled(), cx).await;
@@ -7441,10 +7523,12 @@ done
// A v2 SDK server rewrites replies to its negotiated version; use a real v1 peer.
let _agent_task = cx.background_spawn(
Agent
.builder()
.v1()
.on_receive_request(
async move |_request: acp_v1::InitializeRequest,
responder: Responder<acp_v1::InitializeResponse>,
responder: agent_client_protocol::v1::Responder<
acp_v1::InitializeResponse,
>,
_| {
responder.respond(acp_v1::InitializeResponse::new(ProtocolVersion::V1))
},
@@ -7780,7 +7864,7 @@ exec sleep 60
.downcast_ref::<agent_client_protocol::InitializationVersionMismatch>()
.unwrap_or_else(|| panic!("version diagnostic was replaced: {error:?}"));
assert_eq!(mismatch.requested, ProtocolVersion::V2);
assert_eq!(mismatch.selected, ProtocolVersion::V1);
assert_eq!(mismatch.selected(), ProtocolVersion::V1);
}
}
}
+1 -1
View File
@@ -12,7 +12,7 @@ use http_client::read_no_proxy_from_env;
use project::{AgentId, Project, agent_server_store::AgentServerStore};
use acp_thread::AgentConnection;
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
use anyhow::Result;
use gpui::{App, AppContext, Entity, Task};
use settings::{AgentConfigOptionValue, SettingsStore};
+1 -1
View File
@@ -1,6 +1,6 @@
use crate::{AgentServer, AgentServerDelegate, load_proxy_env};
use acp_thread::AgentConnection;
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
use anyhow::{Context as _, Result};
use collections::HashSet;
use fs::Fs;
+3 -3
View File
@@ -3,7 +3,7 @@ use acp_thread::{
AcpThread, AcpThreadEvent, AgentThreadEntry, ForegroundActivity, SubmissionResponse,
ToolCallStatus,
};
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
use anyhow::{Context as _, Result, anyhow};
use client::RefreshLlmTokenListener;
use futures::{FutureExt, StreamExt, channel::mpsc, channel::oneshot, select};
@@ -357,7 +357,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::v2::PermissionOptionId::new($allow_option_id),
::agent_client_protocol::v2::schema::PermissionOptionId::new($allow_option_id),
cx,
)
.await;
@@ -534,7 +534,7 @@ pub fn get_zed_path() -> PathBuf {
mod tests {
use super::*;
use acp_thread::{AgentConnection, StubAgentConnection};
use agent_client_protocol::schema::v1 as acp_v1;
use agent_client_protocol::v1::schema as acp_v1;
use std::rc::Rc;
async fn stub_thread(
+2 -2
View File
@@ -12,7 +12,7 @@ use std::{
use acp_thread::{AcpThread, AcpThreadEvent, MentionUri, line_range_suffix};
use agent::{ContextServerRegistry, SharedThread, ThreadStore};
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
use agent_servers::AgentServer;
use agent_settings::UserAgentsMd;
use collections::HashSet;
@@ -7005,7 +7005,7 @@ mod tests {
};
use acp_thread::{AgentConnection, StubAgentConnection, ThreadStatus};
use action_log::ActionLog;
use agent_client_protocol::schema::v1 as acp;
use agent_client_protocol::v1::schema as acp;
use anyhow::{Result, anyhow};
use feature_flags::FeatureFlagAppExt;
use fs::FakeFs;
+1 -1
View File
@@ -42,7 +42,7 @@ use std::rc::Rc;
use std::sync::Arc;
use ::ui::IconName;
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
use agent_settings::{AgentProfileId, AgentSettings};
use anyhow::Context as _;
use command_palette_hooks::CommandPaletteFilter;
+1 -1
View File
@@ -7,7 +7,7 @@ use std::sync::atomic::AtomicBool;
use crate::DEFAULT_THREAD_TITLE;
use crate::thread_metadata_store::{ThreadMetadata, ThreadMetadataStore};
use acp_thread::MentionUri;
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use anyhow::Result;
use editor::{CompletionProvider, Editor, code_context_menus::COMPLETION_MENU_MAX_WIDTH};
use futures::FutureExt as _;
+1 -1
View File
@@ -1,7 +1,7 @@
use std::{rc::Rc, sync::Arc};
use acp_thread::AgentSessionConfigOptions;
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use agent_servers::AgentServer;
use collections::HashSet;
+16 -16
View File
@@ -8,7 +8,7 @@ use acp_thread::{
use acp_thread::{AgentConnection, Plan};
use action_log::{ActionLog, ActionLogTelemetry, DiffStats};
use agent::{NativeAgentServer, NoModelConfiguredError, ThreadStore};
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
#[cfg(test)]
use agent_servers::AgentServerDelegate;
use agent_servers::{AgentServer, GEMINI_TERMINAL_AUTH_METHOD_ID};
@@ -4308,7 +4308,7 @@ pub(crate) mod tests {
use acp_thread::{ClientUserMessageId, StubAgentConnection};
use action_log::ActionLog;
use agent::{AgentTool, EditFileTool, FetchTool, TerminalTool, ToolPermissionContext};
use agent_client_protocol::schema::v1 as acp_v1;
use agent_client_protocol::v1::schema as acp_v1;
use agent_servers::FakeAcpAgentServer;
use editor::MultiBufferOffset;
use editor::actions::Paste;
@@ -9707,7 +9707,7 @@ pub(crate) mod tests {
#[gpui::test]
async fn test_plan_panel_dismissal_and_status_updates(cx: &mut TestAppContext) {
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
init_test(cx);
let (conversation_view, cx) =
@@ -11945,7 +11945,7 @@ pub(crate) mod tests {
async fn test_keyed_updates_preserve_unchanged_thought_scroll_position(
cx: &mut TestAppContext,
) {
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
init_test(cx);
let (conversation_view, cx) =
@@ -12054,7 +12054,7 @@ pub(crate) mod tests {
async fn test_keyed_thought_snapshot_keeps_expansion_on_original_chunk(
cx: &mut TestAppContext,
) {
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
init_test(cx);
let (conversation_view, cx) =
@@ -12691,7 +12691,7 @@ pub(crate) mod tests {
#[gpui::test]
async fn test_new_patch_hunk_auto_expands_only_on_creation(cx: &mut TestAppContext) {
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
init_test(cx);
cx.update(|cx| {
@@ -12781,7 +12781,7 @@ pub(crate) mod tests {
#[gpui::test]
async fn test_awaiting_authorization_searches_visible_patch_content(cx: &mut TestAppContext) {
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
init_test(cx);
cx.update(|cx| {
@@ -12897,7 +12897,7 @@ pub(crate) mod tests {
async fn test_thread_search_tracks_shared_tool_patch_content_and_raw_fallback(
cx: &mut TestAppContext,
) {
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
init_test(cx);
let (conversation_view, cx) =
@@ -14021,7 +14021,7 @@ pub(crate) mod tests {
#[gpui::test]
async fn test_thread_search_refreshes_older_keyed_assistant_snapshot(cx: &mut TestAppContext) {
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
init_test(cx);
let (conversation_view, cx) =
@@ -14717,7 +14717,7 @@ pub(crate) mod tests {
async fn test_focused_read_only_keyed_user_message_refreshes_supported_snapshot(
cx: &mut TestAppContext,
) {
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
init_test(cx);
let (conversation_view, cx) =
@@ -14805,7 +14805,7 @@ pub(crate) mod tests {
async fn test_keyed_user_metadata_and_identical_snapshots_preserve_selection(
cx: &mut TestAppContext,
) {
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
use multi_buffer::MultiBufferOffset;
init_test(cx);
@@ -14868,10 +14868,10 @@ pub(crate) mod tests {
}
async fn assert_unsupported_source_message_cannot_regenerate(
unsupported: agent_client_protocol::schema::v2::ContentBlock,
unsupported: agent_client_protocol::v2::schema::ContentBlock,
cx: &mut TestAppContext,
) {
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
init_test(cx);
let (conversation_view, cx) =
@@ -14964,7 +14964,7 @@ pub(crate) mod tests {
#[gpui::test]
async fn test_unsupported_source_message_cannot_regenerate(cx: &mut TestAppContext) {
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
assert_unsupported_source_message_cannot_regenerate(
acp_v2::ContentBlock::Other(acp_v2::OtherContentBlock::new(
@@ -14978,7 +14978,7 @@ pub(crate) mod tests {
#[gpui::test]
async fn test_unknown_annotation_source_message_cannot_regenerate(cx: &mut TestAppContext) {
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
assert_unsupported_source_message_cannot_regenerate(
acp_v2::ContentBlock::Text(acp_v2::TextContent::new("annotated text").annotations(
@@ -14993,7 +14993,7 @@ pub(crate) mod tests {
async fn test_regenerate_does_not_resend_fallback_after_delayed_rewind(
cx: &mut TestAppContext,
) {
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
init_test(cx);
for (cancel_before_update, cancel_after_update) in
@@ -1,5 +1,5 @@
use acp_thread::{Elicitation, ElicitationEntryId, ElicitationStatus};
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use collections::{HashMap, HashSet};
use component::{Component, ComponentScope, example_group_with_title, single_example};
use editor::Editor;
@@ -2,7 +2,7 @@ use acp_thread::{
AcpThread, AgentThreadEntry, MessageIdentity, SessionMessage, SessionMessageSide, ToolCall,
ToolCallContent, ToolCallStatus,
};
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
use gpui::{App, Entity, SharedString};
use std::{fmt, ops::Range};
@@ -1013,7 +1013,7 @@ mod tests {
use acp_thread::{
ContextCompaction, ContextCompactionId, ContextCompactionStatus, MessageContent,
};
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
use language::LanguageRegistry;
use util::paths::PathStyle;
@@ -5,7 +5,7 @@ use crate::{
open_abs_path_at_point, project_path_for_file_link,
thread_metadata_store::{ThreadId, ThreadMetadataStore},
};
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
use std::{cell::RefCell, path::Path};
use acp_thread::{
+1 -1
View File
@@ -9,7 +9,7 @@
//! the format we persist.
use agent::ZED_AGENT_ID;
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
use anyhow::Context as _;
use db::kvp::KeyValueStore;
use gpui::{App, AppContext as _, Entity, Task};
+2 -2
View File
@@ -2,7 +2,7 @@ use std::{ops::Range, sync::Arc};
use acp_thread::{AcpThread, AgentThreadEntry, AssistantMessageChunk, ToolCall};
use agent::ThreadStore;
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
use agent_settings::AgentSettings;
use collections::{HashMap, HashSet};
use editor::{
@@ -932,7 +932,7 @@ mod tests {
use std::sync::Arc;
use acp_thread::{AgentConnection, StubAgentConnection};
use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2};
use agent_client_protocol::{v1::schema as acp_v1, v2::schema as acp_v2};
use buffer_diff::{DiffHunkStatus, DiffHunkStatusKind};
use editor::RowInfo;
use fs::FakeFs;
+1 -1
View File
@@ -1,7 +1,7 @@
use crate::diagnostics::{DiagnosticsOptions, codeblock_fence_for_path, collect_diagnostics};
use acp_thread::{MentionUri, selection_name};
use agent::{ThreadStore, outline};
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use agent_servers::{AgentServer, AgentServerDelegate};
use anyhow::{Context as _, Result, anyhow};
use collections::{HashMap, HashSet};
+2 -2
View File
@@ -11,7 +11,7 @@ use crate::{
};
use acp_thread::MentionUri;
use agent::ThreadStore;
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
use anyhow::{Result, anyhow};
use base64::Engine as _;
use editor::{
@@ -2316,7 +2316,7 @@ mod tests {
use super::PromptLocalCommand;
use acp_thread::MentionUri;
use agent::{ThreadStore, outline};
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
use base64::Engine as _;
use editor::{
AnchorRangeExt as _, Editor, EditorMode, MultiBufferOffset, SelectionEffects,
+1 -1
View File
@@ -1,5 +1,5 @@
use acp_thread::AgentSessionModes;
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use agent_servers::AgentServer;
use fs::Fs;
+1 -1
View File
@@ -1,5 +1,5 @@
use acp_thread::{AgentConnection, StubAgentConnection};
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use agent_servers::{AgentServer, AgentServerDelegate};
use gpui::{
App, AppContext as _, Context, Entity, EventEmitter, FocusHandle, Focusable, IntoElement,
+2 -2
View File
@@ -2,7 +2,7 @@ use std::time::Duration;
use acp_thread::AgentSessionListRequest;
use agent::ThreadStore;
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use chrono::Utc;
use collections::{HashMap, HashSet};
use db::kvp::Dismissable;
@@ -1262,7 +1262,7 @@ mod tests {
let directory = tempfile::tempdir().expect("temporary database directory should exist");
let connection = create_channel_db(directory.path(), ReleaseChannel::Nightly);
let legacy_session_id =
agent_client_protocol::schema::v1::SessionId::new("legacy/session:opaque-☃");
agent_client_protocol::v1::schema::SessionId::new("legacy/session:opaque-☃");
let saved_thread_id = ThreadId::new();
let draft_thread_id = ThreadId::new();
let mut insert = connection
+2 -2
View File
@@ -4,7 +4,7 @@ use std::{
};
use agent::{ThreadStore, ZED_AGENT_ID};
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use anyhow::Context as _;
use chrono::{DateTime, Utc};
use collections::{HashMap, HashSet};
@@ -1822,7 +1822,7 @@ mod tests {
use acp_thread::StubAgentConnection;
use action_log::ActionLog;
use agent::DbThread;
use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp};
use agent_client_protocol::{v1::schema as acp_v1, v2::schema as acp};
use gpui::{TestAppContext, VisualTestContext};
use project::FakeFs;
use project::Project;
+1 -1
View File
@@ -10,7 +10,7 @@ use crate::thread_metadata_store::{
use crate::{Agent, ArchiveSelectedThread, DEFAULT_THREAD_TITLE, RemoveSelectedThread};
use agent::ThreadStore;
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use agent_settings::AgentSettings;
use chrono::{DateTime, Datelike as _, Local, NaiveDate, TimeDelta, Utc};
use collections::HashMap;
+1 -1
View File
@@ -1,7 +1,7 @@
use std::{borrow::Cow, path::PathBuf, time::Duration};
use acp_thread::MentionUri;
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use editor::Editor;
use gpui::{
Animation, AnimationExt, AnyView, Context, IntoElement, TaskExt, WeakEntity, Window,
+1 -1
View File
@@ -1,4 +1,4 @@
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use component::{Component, ComponentScope, example_group_with_title, single_example};
use gpui::{AnyElement, App, ClickEvent, ElementId, Stateful, Window, px};
use ui::{Callout, Color, IconButton, IconName, IconSize, Severity, Tooltip, prelude::*};
+1 -1
View File
@@ -41,7 +41,7 @@ use std::time::{Duration, Instant};
use acp_thread::AgentConnection as _;
use agent::{NativeAgent, NativeAgentConnection, Templates, ThreadStore};
use agent_client_protocol::schema::v2 as acp_v2;
use agent_client_protocol::v2::schema as acp_v2;
use anyhow::{Context, Result};
use clap::Parser;
use feature_flags::FeatureFlagAppExt as _;
@@ -5115,8 +5115,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::v2::PermissionOptionId::new("allow"),
agent_client_protocol::schema::v2::PermissionOptionKind::AllowOnce,
agent_client_protocol::v2::schema::PermissionOptionId::new("allow"),
agent_client_protocol::v2::schema::PermissionOptionKind::AllowOnce,
))
.unwrap();
@@ -5165,8 +5165,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::v2::PermissionOptionId::new("allow"),
agent_client_protocol::schema::v2::PermissionOptionKind::AllowOnce,
agent_client_protocol::v2::schema::PermissionOptionId::new("allow"),
agent_client_protocol::v2::schema::PermissionOptionKind::AllowOnce,
))
.unwrap();
+1 -1
View File
@@ -3,7 +3,7 @@ mod thread_switcher;
use acp_thread::ThreadStatus;
use action_log::DiffStats;
use agent::{ThreadStore, ZED_AGENT_ID};
use agent_client_protocol::schema::v2 as acp;
use agent_client_protocol::v2::schema as acp;
use agent_settings::{AgentSettings, THREADS_LIST_MAX_WIDTH, THREADS_LIST_MIN_WIDTH};
use agent_ui::terminal_thread_metadata_store::{
TerminalThreadMetadata, TerminalThreadMetadataStore, terminal_title_prefix,
+1 -1
View File
@@ -1,7 +1,7 @@
use super::*;
use acp_thread::{AcpThread, PermissionOptions, StubAgentConnection};
use agent::ThreadStore;
use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2};
use agent_client_protocol::{v1::schema as acp_v1, v2::schema as acp_v2};
use agent_settings::AgentSettings;
use agent_ui::{
ThreadId,
+1 -1
View File
@@ -95,7 +95,7 @@ fn main() {
#[cfg(target_os = "macos")]
use {
acp_thread::{AgentConnection, StubAgentConnection},
agent_client_protocol::schema::v2 as acp_v2,
agent_client_protocol::v2::schema as acp_v2,
agent_servers::{AgentServer, AgentServerDelegate},
anyhow::{Context as _, Result},
assets::Assets,