From e36eb0576dc8884323a40df2d11612321805202e Mon Sep 17 00:00:00 2001 From: Ben Brandt Date: Thu, 2 Apr 2026 14:21:31 +0200 Subject: [PATCH 01/20] First pass at swapping out the crates --- Cargo.lock | 403 ++++--- Cargo.toml | 2 +- crates/acp_thread/Cargo.toml | 2 +- crates/acp_thread/src/acp_thread.rs | 2 +- crates/acp_thread/src/connection.rs | 4 +- crates/acp_thread/src/mention.rs | 2 +- crates/acp_thread/src/terminal.rs | 2 +- crates/acp_tools/Cargo.toml | 2 +- crates/acp_tools/src/acp_tools.rs | 140 +-- crates/agent/Cargo.toml | 2 +- crates/agent/src/agent.rs | 2 +- crates/agent/src/db.rs | 2 +- crates/agent/src/native_agent_server.rs | 2 +- crates/agent/src/tests/mod.rs | 4 +- crates/agent/src/thread.rs | 4 +- crates/agent/src/thread_store.rs | 2 +- .../src/tools/context_server_registry.rs | 2 +- crates/agent/src/tools/copy_path_tool.rs | 4 +- .../agent/src/tools/create_directory_tool.rs | 4 +- crates/agent/src/tools/delete_path_tool.rs | 4 +- crates/agent/src/tools/diagnostics_tool.rs | 2 +- crates/agent/src/tools/edit_file_tool.rs | 2 +- crates/agent/src/tools/fetch_tool.rs | 2 +- crates/agent/src/tools/find_path_tool.rs | 2 +- crates/agent/src/tools/grep_tool.rs | 2 +- crates/agent/src/tools/list_directory_tool.rs | 4 +- crates/agent/src/tools/move_path_tool.rs | 4 +- crates/agent/src/tools/now_tool.rs | 2 +- crates/agent/src/tools/open_tool.rs | 2 +- crates/agent/src/tools/read_file_tool.rs | 4 +- .../src/tools/restore_file_from_disk_tool.rs | 2 +- crates/agent/src/tools/save_file_tool.rs | 2 +- crates/agent/src/tools/spawn_agent_tool.rs | 2 +- .../src/tools/streaming_edit_file_tool.rs | 2 +- crates/agent/src/tools/terminal_tool.rs | 2 +- crates/agent/src/tools/update_plan_tool.rs | 2 +- crates/agent/src/tools/web_search_tool.rs | 2 +- crates/agent_servers/Cargo.toml | 2 +- crates/agent_servers/src/acp.rs | 1039 ++++++++++++----- crates/agent_servers/src/agent_servers.rs | 23 +- crates/agent_servers/src/custom.rs | 2 +- crates/agent_servers/src/e2e_tests.rs | 4 +- crates/agent_settings/Cargo.toml | 2 +- crates/agent_settings/src/agent_settings.rs | 2 +- crates/agent_ui/Cargo.toml | 2 +- crates/agent_ui/src/agent_panel.rs | 2 +- crates/agent_ui/src/agent_ui.rs | 6 +- crates/agent_ui/src/completion_provider.rs | 2 +- crates/agent_ui/src/config_options.rs | 2 +- crates/agent_ui/src/conversation_view.rs | 4 +- .../src/conversation_view/thread_view.rs | 11 +- crates/agent_ui/src/entry_view_state.rs | 4 +- crates/agent_ui/src/mention_set.rs | 2 +- crates/agent_ui/src/message_editor.rs | 4 +- crates/agent_ui/src/mode_selector.rs | 2 +- crates/agent_ui/src/model_selector.rs | 4 +- crates/agent_ui/src/test_support.rs | 2 +- crates/agent_ui/src/thread_history.rs | 2 +- crates/agent_ui/src/thread_import.rs | 2 +- crates/agent_ui/src/thread_metadata_store.rs | 4 +- crates/agent_ui/src/threads_archive_view.rs | 2 +- crates/agent_ui/src/ui/mention_crease.rs | 2 +- crates/eval_cli/Cargo.toml | 2 +- crates/eval_cli/src/main.rs | 2 +- crates/sidebar/Cargo.toml | 2 +- crates/sidebar/src/sidebar.rs | 2 +- crates/sidebar/src/thread_switcher.rs | 2 +- crates/zed/Cargo.toml | 2 +- crates/zed/src/main.rs | 3 +- crates/zed/src/visual_test_runner.rs | 2 +- 70 files changed, 1144 insertions(+), 637 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8b428dbcd537e3..849129850d7df2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7,7 +7,7 @@ name = "acp_thread" version = "0.1.0" dependencies = [ "action_log", - "agent-client-protocol", + "agent-client-protocol-core", "anyhow", "base64 0.22.1", "buffer_diff", @@ -15,7 +15,7 @@ dependencies = [ "collections", "env_logger 0.11.8", "file_icons", - "futures 0.3.31", + "futures 0.3.32", "gpui", "image", "indoc", @@ -50,7 +50,7 @@ dependencies = [ name = "acp_tools" version = "0.1.0" dependencies = [ - "agent-client-protocol", + "agent-client-protocol-core", "collections", "gpui", "language", @@ -75,7 +75,7 @@ dependencies = [ "collections", "ctor", "fs", - "futures 0.3.31", + "futures 0.3.32", "gpui", "language", "log", @@ -100,7 +100,7 @@ dependencies = [ "editor", "extension_host", "fs", - "futures 0.3.31", + "futures 0.3.32", "gpui", "language", "project", @@ -144,7 +144,7 @@ version = "0.1.0" dependencies = [ "acp_thread", "action_log", - "agent-client-protocol", + "agent-client-protocol-core", "agent_servers", "agent_settings", "anyhow", @@ -163,7 +163,7 @@ dependencies = [ "eval_utils", "feature_flags", "fs", - "futures 0.3.31", + "futures 0.3.32", "git", "gpui", "gpui_tokio", @@ -217,27 +217,42 @@ dependencies = [ ] [[package]] -name = "agent-client-protocol" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c56a59cf6315e99f874d2c1f96c69d2da5ffe0087d211297fc4a41f849770a2" +name = "agent-client-protocol-core" +version = "0.1.0" dependencies = [ + "agent-client-protocol-derive", "agent-client-protocol-schema", "anyhow", - "async-broadcast", - "async-trait", - "derive_more", - "futures 0.3.31", - "log", + "boxfnonce", + "futures 0.3.32", + "futures-concurrency", + "jsonrpcmsg", + "rmcp", + "rustc-hash 2.1.1", + "schemars", "serde", "serde_json", + "thiserror 2.0.17", + "tokio", + "tokio-util", + "tracing", + "uuid", +] + +[[package]] +name = "agent-client-protocol-derive" +version = "0.1.0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", ] [[package]] name = "agent-client-protocol-schema" -version = "0.11.2" +version = "0.11.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0497b9a95a404e35799904835c57c6f8c69b9d08ccfd3cb5b7d746425cd6789" +checksum = "ca68e7e55681ce56546c0cecc6bc8f20493d24b44c6d93ec46174f310730bba2" dependencies = [ "anyhow", "derive_more", @@ -254,7 +269,7 @@ dependencies = [ "acp_thread", "acp_tools", "action_log", - "agent-client-protocol", + "agent-client-protocol-core", "anyhow", "async-trait", "chrono", @@ -264,7 +279,7 @@ dependencies = [ "env_logger 0.11.8", "feature_flags", "fs", - "futures 0.3.31", + "futures 0.3.32", "google_ai", "gpui", "gpui_tokio", @@ -295,7 +310,7 @@ dependencies = [ name = "agent_settings" version = "0.1.0" dependencies = [ - "agent-client-protocol", + "agent-client-protocol-core", "anyhow", "collections", "convert_case 0.8.0", @@ -321,7 +336,7 @@ dependencies = [ "acp_thread", "action_log", "agent", - "agent-client-protocol", + "agent-client-protocol-core", "agent_servers", "agent_settings", "ai_onboarding", @@ -344,7 +359,7 @@ dependencies = [ "feature_flags", "file_icons", "fs", - "futures 0.3.31", + "futures 0.3.32", "fuzzy", "git", "gpui", @@ -629,7 +644,7 @@ version = "0.1.0" dependencies = [ "anyhow", "chrono", - "futures 0.3.31", + "futures 0.3.32", "http_client", "schemars", "serde", @@ -750,7 +765,7 @@ name = "askpass" version = "0.1.0" dependencies = [ "anyhow", - "futures 0.3.31", + "futures 0.3.32", "gpui", "log", "net", @@ -945,7 +960,7 @@ name = "async-pipe" version = "0.1.3" source = "git+https://github.com/zed-industries/async-pipe-rs?rev=82d00a04211cf4e1236029aa03e6b6ce2a74c553#82d00a04211cf4e1236029aa03e6b6ce2a74c553" dependencies = [ - "futures 0.3.31", + "futures 0.3.32", "log", ] @@ -1183,7 +1198,7 @@ dependencies = [ "clock", "ctor", "db", - "futures 0.3.31", + "futures 0.3.32", "futures-lite 1.13.0", "gpui", "http_client", @@ -1862,7 +1877,7 @@ dependencies = [ "anyhow", "aws-sdk-bedrockruntime", "aws-smithy-types", - "futures 0.3.31", + "futures 0.3.32", "schemars", "serde", "serde_json", @@ -2072,7 +2087,7 @@ version = "3.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "89ec27229c38ed0eb3c0feee3d2c1d6a4379ae44f418a29a658890e062d8f365" dependencies = [ - "darling 0.21.3", + "darling 0.23.0", "ident_case", "prettyplease", "proc-macro2", @@ -2110,6 +2125,12 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "boxfnonce" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5988cb1d626264ac94100be357308f29ff7cbdd3b36bda27f450a4ee3f713426" + [[package]] name = "breadcrumbs" version = "0.1.0" @@ -2151,7 +2172,7 @@ version = "0.1.0" dependencies = [ "clock", "ctor", - "futures 0.3.31", + "futures 0.3.32", "git2", "gpui", "language", @@ -2348,7 +2369,7 @@ dependencies = [ "collections", "feature_flags", "fs", - "futures 0.3.31", + "futures 0.3.32", "gpui", "gpui_tokio", "language", @@ -2669,7 +2690,7 @@ dependencies = [ "client", "clock", "collections", - "futures 0.3.31", + "futures 0.3.32", "gpui", "http_client", "language", @@ -2863,7 +2884,7 @@ dependencies = [ "derive_more", "feature_flags", "fs", - "futures 0.3.31", + "futures 0.3.32", "gpui", "gpui_tokio", "http_client", @@ -2917,7 +2938,7 @@ version = "0.1.0" dependencies = [ "anyhow", "cloud_api_types", - "futures 0.3.31", + "futures 0.3.32", "gpui", "gpui_tokio", "http_client", @@ -3049,7 +3070,7 @@ dependencies = [ "anyhow", "edit_prediction", "edit_prediction_types", - "futures 0.3.31", + "futures 0.3.32", "gpui", "http_client", "icons", @@ -3095,7 +3116,7 @@ dependencies = [ "extension", "file_finder", "fs", - "futures 0.3.31", + "futures 0.3.32", "git", "git_hosting_providers", "git_ui", @@ -3172,7 +3193,7 @@ dependencies = [ "collections", "db", "editor", - "futures 0.3.31", + "futures 0.3.32", "fuzzy", "gpui", "livekit_client", @@ -3433,7 +3454,7 @@ dependencies = [ "async-trait", "base64 0.22.1", "collections", - "futures 0.3.31", + "futures 0.3.32", "gpui", "http_client", "log", @@ -3494,7 +3515,7 @@ dependencies = [ "edit_prediction_types", "editor", "fs", - "futures 0.3.31", + "futures 0.3.32", "gpui", "icons", "indoc", @@ -3528,7 +3549,7 @@ dependencies = [ "collections", "dirs 4.0.0", "fs", - "futures 0.3.31", + "futures 0.3.32", "gpui", "http_client", "log", @@ -3978,7 +3999,7 @@ version = "0.1.0" dependencies = [ "cfg-if", "crash-handler", - "futures 0.3.31", + "futures 0.3.32", "log", "mach2 0.5.0", "minidumper", @@ -4035,7 +4056,7 @@ name = "credentials_provider" version = "0.1.0" dependencies = [ "anyhow", - "futures 0.3.31", + "futures 0.3.32", "gpui", "paths", "release_channel", @@ -4318,7 +4339,7 @@ dependencies = [ "collections", "dap-types", "fs", - "futures 0.3.31", + "futures 0.3.32", "gpui", "http_client", "language", @@ -4360,7 +4381,7 @@ dependencies = [ "dap", "dotenvy", "fs", - "futures 0.3.31", + "futures 0.3.32", "gpui", "http_client", "json_dotpath", @@ -4396,6 +4417,16 @@ dependencies = [ "darling_macro 0.21.3", ] +[[package]] +name = "darling" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d" +dependencies = [ + "darling_core 0.23.0", + "darling_macro 0.23.0", +] + [[package]] name = "darling_core" version = "0.20.11" @@ -4424,6 +4455,19 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "darling_core" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.117", +] + [[package]] name = "darling_macro" version = "0.20.11" @@ -4446,6 +4490,17 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "darling_macro" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" +dependencies = [ + "darling_core 0.23.0", + "quote", + "syn 2.0.117", +] + [[package]] name = "dashmap" version = "6.1.0" @@ -4531,7 +4586,7 @@ dependencies = [ "anyhow", "dap", "editor", - "futures 0.3.31", + "futures 0.3.32", "gpui", "project", "serde_json", @@ -4558,7 +4613,7 @@ dependencies = [ "editor", "feature_flags", "file_icons", - "futures 0.3.31", + "futures 0.3.32", "fuzzy", "gpui", "hex", @@ -4613,7 +4668,7 @@ name = "deepseek" version = "0.1.0" dependencies = [ "anyhow", - "futures 0.3.31", + "futures 0.3.32", "http_client", "schemars", "serde", @@ -4733,7 +4788,7 @@ dependencies = [ "async-trait", "env_logger 0.11.8", "fs", - "futures 0.3.31", + "futures 0.3.32", "gpui", "http 1.3.1", "http_client", @@ -5121,7 +5176,7 @@ dependencies = [ "edit_prediction_types", "feature_flags", "fs", - "futures 0.3.31", + "futures 0.3.32", "gpui", "heapless", "indoc", @@ -5181,7 +5236,7 @@ dependencies = [ "extension", "flate2", "fs", - "futures 0.3.31", + "futures 0.3.32", "gaoya", "gpui", "gpui_platform", @@ -5233,7 +5288,7 @@ dependencies = [ "clock", "collections", "env_logger 0.11.8", - "futures 0.3.31", + "futures 0.3.32", "gpui", "indoc", "language", @@ -5282,7 +5337,7 @@ dependencies = [ "editor", "feature_flags", "fs", - "futures 0.3.31", + "futures 0.3.32", "gpui", "indoc", "language", @@ -5327,7 +5382,7 @@ dependencies = [ "feature_flags", "file_icons", "fs", - "futures 0.3.31", + "futures 0.3.32", "fuzzy", "git", "gpui", @@ -5722,7 +5777,7 @@ version = "0.1.0" dependencies = [ "acp_thread", "agent", - "agent-client-protocol", + "agent-client-protocol-core", "agent_ui", "anyhow", "clap", @@ -5734,7 +5789,7 @@ dependencies = [ "extension", "feature_flags", "fs", - "futures 0.3.31", + "futures 0.3.32", "gpui", "gpui_platform", "gpui_tokio", @@ -5844,7 +5899,7 @@ dependencies = [ "collections", "dap", "fs", - "futures 0.3.31", + "futures 0.3.32", "gpui", "heck 0.5.0", "http_client", @@ -5912,7 +5967,7 @@ dependencies = [ "dap", "extension", "fs", - "futures 0.3.31", + "futures 0.3.32", "gpui", "gpui_tokio", "http_client", @@ -6120,7 +6175,7 @@ dependencies = [ "ctor", "editor", "file_icons", - "futures 0.3.31", + "futures 0.3.32", "fuzzy", "gpui", "menu", @@ -6422,7 +6477,7 @@ dependencies = [ "collections", "dunce", "fs", - "futures 0.3.31", + "futures 0.3.32", "git", "gpui", "ignore", @@ -6520,9 +6575,9 @@ checksum = "3a471a38ef8ed83cd6e40aa59c1ffe17db6855c18e3604d9c4ed8c08ebc28678" [[package]] name = "futures" -version = "0.3.31" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876" +checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d" dependencies = [ "futures-channel", "futures-core", @@ -6535,9 +6590,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.31" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" dependencies = [ "futures-core", "futures-sink", @@ -6558,15 +6613,15 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.31" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" [[package]] name = "futures-executor" -version = "0.3.31" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f" +checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" dependencies = [ "futures-core", "futures-task", @@ -6586,9 +6641,9 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.31" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" +checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" [[package]] name = "futures-lite" @@ -6620,9 +6675,9 @@ dependencies = [ [[package]] name = "futures-macro" -version = "0.3.31" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" +checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" dependencies = [ "proc-macro2", "quote", @@ -6631,21 +6686,21 @@ dependencies = [ [[package]] name = "futures-sink" -version = "0.3.31" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" [[package]] name = "futures-task" -version = "0.3.31" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" [[package]] name = "futures-util" -version = "0.3.31" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" dependencies = [ "futures 0.1.31", "futures-channel", @@ -6654,9 +6709,9 @@ dependencies = [ "futures-macro", "futures-sink", "futures-task", + "libc", "memchr", "pin-project-lite", - "pin-utils", "slab", "tokio-io", ] @@ -7083,7 +7138,7 @@ dependencies = [ "async-trait", "collections", "derive_more", - "futures 0.3.31", + "futures 0.3.32", "git2", "gpui", "http_client", @@ -7160,7 +7215,7 @@ version = "0.1.0" dependencies = [ "anyhow", "async-trait", - "futures 0.3.31", + "futures 0.3.32", "git", "gpui", "http_client", @@ -7192,7 +7247,7 @@ dependencies = [ "editor", "feature_flags", "file_icons", - "futures 0.3.31", + "futures 0.3.32", "fuzzy", "git", "gpui", @@ -7397,7 +7452,7 @@ name = "google_ai" version = "0.1.0" dependencies = [ "anyhow", - "futures 0.3.31", + "futures 0.3.32", "http_client", "schemars", "serde", @@ -7467,7 +7522,7 @@ dependencies = [ "env_logger 0.11.8", "etagere", "foreign-types 0.5.0", - "futures 0.3.31", + "futures 0.3.32", "futures-concurrency", "getrandom 0.3.4", "gpui_macros", @@ -7542,7 +7597,7 @@ dependencies = [ "calloop-wayland-source", "collections", "filedescriptor", - "futures 0.3.31", + "futures 0.3.32", "gpui", "gpui_wgpu", "http_client", @@ -7596,7 +7651,7 @@ dependencies = [ "dispatch2", "etagere", "foreign-types 0.5.0", - "futures 0.3.31", + "futures 0.3.32", "gpui", "image", "itertools 0.14.0", @@ -7665,7 +7720,7 @@ version = "0.1.0" dependencies = [ "anyhow", "console_error_panic_hook", - "futures 0.3.31", + "futures 0.3.32", "gpui", "gpui_wgpu", "http_client", @@ -7716,7 +7771,7 @@ dependencies = [ "anyhow", "collections", "etagere", - "futures 0.3.31", + "futures 0.3.32", "gpui", "image", "itertools 0.14.0", @@ -8200,7 +8255,7 @@ dependencies = [ "async-tar", "bytes 1.11.1", "derive_more", - "futures 0.3.31", + "futures 0.3.32", "http 1.3.1", "http-body 1.0.1", "log", @@ -9029,6 +9084,16 @@ dependencies = [ "util", ] +[[package]] +name = "jsonrpcmsg" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d833a15225c779251e13929203518c2ff26e2fe0f322d584b213f4f4dad37bd" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "jsonschema" version = "0.37.4" @@ -9083,7 +9148,7 @@ dependencies = [ "async-trait", "bytes 1.11.1", "chrono", - "futures 0.3.31", + "futures 0.3.32", "serde", "serde_json", "thiserror 2.0.17", @@ -9099,7 +9164,7 @@ dependencies = [ "anyhow", "async-trait", "async-tungstenite", - "futures 0.3.31", + "futures 0.3.32", "jupyter-protocol", "serde", "serde_json", @@ -9217,7 +9282,7 @@ dependencies = [ "ec4rs", "encoding_rs", "fs", - "futures 0.3.31", + "futures 0.3.32", "fuzzy", "globset", "gpui", @@ -9297,7 +9362,7 @@ dependencies = [ "collections", "extension", "fs", - "futures 0.3.31", + "futures 0.3.32", "gpui", "language", "log", @@ -9323,7 +9388,7 @@ dependencies = [ "cloud_llm_client", "collections", "credentials_provider", - "futures 0.3.31", + "futures 0.3.32", "gpui", "http_client", "icons", @@ -9367,7 +9432,7 @@ dependencies = [ "extension", "extension_host", "fs", - "futures 0.3.31", + "futures 0.3.32", "google_ai", "gpui", "gpui_tokio", @@ -9444,7 +9509,7 @@ dependencies = [ "command_palette_hooks", "edit_prediction", "editor", - "futures 0.3.31", + "futures 0.3.32", "gpui", "itertools 0.14.0", "language", @@ -9480,7 +9545,7 @@ dependencies = [ "chrono", "collections", "fs", - "futures 0.3.31", + "futures 0.3.32", "globset", "gpui", "grammars", @@ -9867,7 +9932,7 @@ dependencies = [ "core-video", "coreaudio-rs 0.12.1", "cpal", - "futures 0.3.31", + "futures 0.3.32", "gpui", "gpui_platform", "gpui_tokio", @@ -9911,7 +9976,7 @@ name = "lmstudio" version = "0.1.0" dependencies = [ "anyhow", - "futures 0.3.31", + "futures 0.3.32", "http_client", "schemars", "serde", @@ -9982,7 +10047,7 @@ dependencies = [ "async-pipe", "collections", "ctor", - "futures 0.3.31", + "futures 0.3.32", "gpui", "gpui_util", "log", @@ -10122,7 +10187,7 @@ dependencies = [ "collections", "env_logger 0.11.8", "fs", - "futures 0.3.31", + "futures 0.3.32", "gpui", "gpui_platform", "html5ever 0.27.0", @@ -10569,7 +10634,7 @@ name = "mistral" version = "0.1.0" dependencies = [ "anyhow", - "futures 0.3.31", + "futures 0.3.32", "http_client", "schemars", "serde", @@ -10758,7 +10823,7 @@ name = "nc" version = "0.1.0" dependencies = [ "anyhow", - "futures 0.3.31", + "futures 0.3.32", "net", "smol", ] @@ -10854,7 +10919,7 @@ dependencies = [ "async-std", "async-tar", "async-trait", - "futures 0.3.31", + "futures 0.3.32", "http_client", "log", "paths", @@ -11178,7 +11243,7 @@ version = "0.9.2" source = "git+https://github.com/KillTheMule/nvim-rs?rev=764dd270c642f77f10f3e19d05cc178a6cbe69f3#764dd270c642f77f10f3e19d05cc178a6cbe69f3" dependencies = [ "async-trait", - "futures 0.3.31", + "futures 0.3.32", "log", "rmp", "rmpv", @@ -11378,7 +11443,7 @@ name = "ollama" version = "0.1.0" dependencies = [ "anyhow", - "futures 0.3.31", + "futures 0.3.32", "http_client", "schemars", "serde", @@ -11485,7 +11550,7 @@ name = "open_ai" version = "0.1.0" dependencies = [ "anyhow", - "futures 0.3.31", + "futures 0.3.32", "http_client", "log", "rand 0.9.2", @@ -11503,7 +11568,7 @@ version = "0.1.0" dependencies = [ "editor", "file_icons", - "futures 0.3.31", + "futures 0.3.32", "fuzzy", "gpui", "picker", @@ -11524,7 +11589,7 @@ name = "open_router" version = "0.1.0" dependencies = [ "anyhow", - "futures 0.3.31", + "futures 0.3.32", "http_client", "schemars", "serde", @@ -11539,7 +11604,7 @@ name = "opencode" version = "0.1.0" dependencies = [ "anyhow", - "futures 0.3.31", + "futures 0.3.32", "google_ai", "http_client", "schemars", @@ -11853,6 +11918,12 @@ version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" +[[package]] +name = "pastey" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b867cad97c0791bbd3aaa6472142568c6c9e8f71937e98379f584cfb0cf35bec" + [[package]] name = "pathdiff" version = "0.2.3" @@ -12853,7 +12924,7 @@ checksum = "af3fb618632874fb76937c2361a7f22afd393c982a2165595407edc75b06d3c1" dependencies = [ "atomic", "crossbeam-queue", - "futures 0.3.31", + "futures 0.3.32", "log", "parking_lot", "pin-project", @@ -13086,7 +13157,7 @@ dependencies = [ "extension", "fancy-regex 0.17.0", "fs", - "futures 0.3.31", + "futures 0.3.32", "fuzzy", "git", "git2", @@ -13152,7 +13223,7 @@ dependencies = [ "askpass", "clap", "client", - "futures 0.3.31", + "futures 0.3.32", "gpui", "gpui_platform", "http_client", @@ -13213,7 +13284,7 @@ version = "0.1.0" dependencies = [ "anyhow", "editor", - "futures 0.3.31", + "futures 0.3.32", "fuzzy", "gpui", "language", @@ -13255,7 +13326,7 @@ dependencies = [ "chrono", "collections", "fs", - "futures 0.3.31", + "futures 0.3.32", "fuzzy", "gpui", "handlebars 4.5.0", @@ -14010,7 +14081,7 @@ dependencies = [ "extension", "extension_host", "fs", - "futures 0.3.31", + "futures 0.3.32", "fuzzy", "gpui", "http_client", @@ -14194,7 +14265,7 @@ dependencies = [ "base64 0.22.1", "collections", "fs", - "futures 0.3.31", + "futures 0.3.32", "gpui", "log", "parking_lot", @@ -14222,7 +14293,7 @@ dependencies = [ "anyhow", "askpass", "auto_update", - "futures 0.3.31", + "futures 0.3.32", "gpui", "log", "markdown", @@ -14260,7 +14331,7 @@ dependencies = [ "extension_host", "fork", "fs", - "futures 0.3.31", + "futures 0.3.32", "git", "git2", "git_hosting_providers", @@ -14342,7 +14413,7 @@ dependencies = [ "editor", "feature_flags", "file_icons", - "futures 0.3.31", + "futures 0.3.32", "gpui", "html_to_markdown", "http_client", @@ -14467,7 +14538,7 @@ version = "0.1.0" dependencies = [ "anyhow", "bytes 1.11.1", - "futures 0.3.31", + "futures 0.3.32", "gpui_util", "http_client", "http_client_tls", @@ -14558,6 +14629,41 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "rmcp" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2231b2c085b371c01bc90c0e6c1cab8834711b6394533375bdbf870b0166d419" +dependencies = [ + "async-trait", + "base64 0.22.1", + "chrono", + "futures 0.3.32", + "pastey", + "pin-project-lite", + "rmcp-macros", + "schemars", + "serde", + "serde_json", + "thiserror 2.0.17", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "rmcp-macros" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36ea0e100fadf81be85d7ff70f86cd805c7572601d4ab2946207f36540854b43" +dependencies = [ + "darling 0.23.0", + "proc-macro2", + "quote", + "serde_json", + "syn 2.0.117", +] + [[package]] name = "rmp" version = "0.8.14" @@ -14639,7 +14745,7 @@ dependencies = [ "async-tungstenite", "base64 0.22.1", "collections", - "futures 0.3.31", + "futures 0.3.32", "gpui", "parking_lot", "proto", @@ -14732,7 +14838,7 @@ dependencies = [ "chrono", "data-encoding", "dirs 6.0.0", - "futures 0.3.31", + "futures 0.3.32", "glob", "jupyter-protocol", "serde", @@ -15106,7 +15212,7 @@ dependencies = [ "backtrace", "chrono", "flume", - "futures 0.3.31", + "futures 0.3.32", "parking_lot", "rand 0.9.2", "web-time", @@ -15133,6 +15239,7 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "82d20c4491bc164fa2f6c5d44565947a52ad80b9505d8e36f8d54c27c739fcd0" dependencies = [ + "chrono", "dyn-clone", "indexmap", "ref-cast", @@ -15334,7 +15441,7 @@ dependencies = [ "collections", "editor", "fs", - "futures 0.3.31", + "futures 0.3.32", "gpui", "itertools 0.14.0", "language", @@ -15613,7 +15720,7 @@ dependencies = [ "collections", "ec4rs", "fs", - "futures 0.3.31", + "futures 0.3.32", "gpui", "indoc", "inventory", @@ -15717,7 +15824,7 @@ dependencies = [ "editor", "feature_flags", "fs", - "futures 0.3.31", + "futures 0.3.32", "fuzzy", "gpui", "heck 0.5.0", @@ -15858,7 +15965,7 @@ dependencies = [ "acp_thread", "action_log", "agent", - "agent-client-protocol", + "agent-client-protocol-core", "agent_settings", "agent_ui", "anyhow", @@ -16093,7 +16200,7 @@ dependencies = [ "collections", "extension", "fs", - "futures 0.3.31", + "futures 0.3.32", "gpui", "indoc", "parking_lot", @@ -16205,7 +16312,7 @@ version = "0.1.0" dependencies = [ "anyhow", "collections", - "futures 0.3.31", + "futures 0.3.32", "indoc", "libsqlite3-sys", "log", @@ -17251,7 +17358,7 @@ version = "0.1.0" dependencies = [ "anyhow", "collections", - "futures 0.3.31", + "futures 0.3.32", "gpui", "hex", "log", @@ -17298,7 +17405,7 @@ dependencies = [ name = "telemetry" version = "0.1.0" dependencies = [ - "futures 0.3.31", + "futures 0.3.32", "serde", "serde_json", "telemetry_events", @@ -17353,7 +17460,7 @@ dependencies = [ "alacritty_terminal", "anyhow", "collections", - "futures 0.3.31", + "futures 0.3.32", "gpui", "itertools 0.14.0", "libc", @@ -17399,7 +17506,7 @@ dependencies = [ "db", "dirs 4.0.0", "editor", - "futures 0.3.31", + "futures 0.3.32", "gpui", "itertools 0.14.0", "language", @@ -18035,7 +18142,7 @@ dependencies = [ "anyhow", "convert_case 0.8.0", "editor", - "futures 0.3.31", + "futures 0.3.32", "fuzzy", "gpui", "language", @@ -18911,7 +19018,7 @@ dependencies = [ "command-fds", "dirs 4.0.0", "dunce", - "futures 0.3.31", + "futures 0.3.32", "futures-lite 1.13.0", "git2", "globset", @@ -19068,7 +19175,7 @@ dependencies = [ "db", "editor", "env_logger 0.11.8", - "futures 0.3.31", + "futures 0.3.32", "fuzzy", "git_ui", "gpui", @@ -19432,7 +19539,7 @@ version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7516db7f32decdadb1c3b8deb1b7d78b9df7606c5cc2f6241737c2ab3a0258e" dependencies = [ - "futures 0.3.31", + "futures 0.3.32", "js-sys", "wasm-bindgen", "web-sys", @@ -19788,7 +19895,7 @@ dependencies = [ "cap-std", "cap-time-ext", "fs-set-times", - "futures 0.3.31", + "futures 0.3.32", "io-extras", "io-lifetimes", "rustix 1.1.2", @@ -19812,7 +19919,7 @@ dependencies = [ "anyhow", "async-trait", "bytes 1.11.1", - "futures 0.3.31", + "futures 0.3.32", "wasmtime", ] @@ -19830,7 +19937,7 @@ name = "watch" version = "0.1.0" dependencies = [ "ctor", - "futures 0.3.31", + "futures 0.3.32", "gpui", "parking_lot", "zlog", @@ -20000,7 +20107,7 @@ dependencies = [ "client", "cloud_api_types", "cloud_llm_client", - "futures 0.3.31", + "futures 0.3.32", "gpui", "http_client", "language_model", @@ -21194,7 +21301,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c4db52a11d4dfb0a59f194c064055794ee6564eb1ced88c25da2cf76e50c5621" dependencies = [ "bitflags 2.10.0", - "futures 0.3.31", + "futures 0.3.32", "once_cell", ] @@ -21445,7 +21552,7 @@ dependencies = [ "db", "feature_flags", "fs", - "futures 0.3.31", + "futures 0.3.32", "git", "gpui", "http_client", @@ -21493,7 +21600,7 @@ dependencies = [ "collections", "encoding_rs", "fs", - "futures 0.3.31", + "futures 0.3.32", "fuzzy", "git", "gpui", @@ -21745,7 +21852,7 @@ dependencies = [ "base64 0.22.1", "bytes 1.11.1", "flate2", - "futures 0.3.31", + "futures 0.3.32", "http-body-util", "hyper 1.7.0", "hyper-util", @@ -21900,7 +22007,7 @@ dependencies = [ "action_log", "activity_indicator", "agent", - "agent-client-protocol", + "agent-client-protocol-core", "agent_servers", "agent_settings", "agent_ui", @@ -21950,7 +22057,7 @@ dependencies = [ "feedback", "file_finder", "fs", - "futures 0.3.31", + "futures 0.3.32", "git", "git_graph", "git_hosting_providers", @@ -22326,7 +22433,7 @@ dependencies = [ "asynchronous-codec", "bytes 1.11.1", "crossbeam-queue", - "futures 0.3.31", + "futures 0.3.32", "log", "num-traits", "once_cell", diff --git a/Cargo.toml b/Cargo.toml index 3a393237ab9f5a..1c5b124981f998 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -477,7 +477,7 @@ ztracing_macro = { path = "crates/ztracing_macro" } # External crates # -agent-client-protocol = { version = "=0.10.2", features = ["unstable"] } +agent-client-protocol-core = { path = "../acp-rust-sdk/src/agent-client-protocol-core", features = ["unstable"] } aho-corasick = "1.1" alacritty_terminal = { git = "https://github.com/zed-industries/alacritty", rev = "9d9640d4" } any_vec = "0.14" diff --git a/crates/acp_thread/Cargo.toml b/crates/acp_thread/Cargo.toml index 7ef53bc5227086..9b1e0a9b64855c 100644 --- a/crates/acp_thread/Cargo.toml +++ b/crates/acp_thread/Cargo.toml @@ -17,7 +17,7 @@ test-support = ["gpui/test-support", "project/test-support", "dep:parking_lot", [dependencies] action_log.workspace = true -agent-client-protocol.workspace = true +agent-client-protocol-core.workspace = true base64.workspace = true anyhow.workspace = true buffer_diff.workspace = true diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs index 0bcb8254c8b812..5746ca14bb9623 100644 --- a/crates/acp_thread/src/acp_thread.rs +++ b/crates/acp_thread/src/acp_thread.rs @@ -3,7 +3,7 @@ mod diff; mod mention; mod terminal; use action_log::{ActionLog, ActionLogTelemetry}; -use agent_client_protocol::{self as acp}; +use agent_client_protocol_core::schema as acp; use anyhow::{Context as _, Result, anyhow}; use collections::HashSet; pub use connection::*; diff --git a/crates/acp_thread/src/connection.rs b/crates/acp_thread/src/connection.rs index 58a8aa33830f12..0835a05d6cb07e 100644 --- a/crates/acp_thread/src/connection.rs +++ b/crates/acp_thread/src/connection.rs @@ -1,5 +1,5 @@ use crate::AcpThread; -use agent_client_protocol::{self as acp}; +use agent_client_protocol_core::schema as acp; use anyhow::Result; use chrono::{DateTime, Utc}; use collections::{HashMap, IndexMap}; @@ -939,7 +939,7 @@ mod test_support { fn truncate( &self, - _session_id: &agent_client_protocol::SessionId, + _session_id: &acp::SessionId, _cx: &App, ) -> Option> { Some(Rc::new(StubAgentSessionEditor)) diff --git a/crates/acp_thread/src/mention.rs b/crates/acp_thread/src/mention.rs index 753838d3b98ed6..b4928eb5edc102 100644 --- a/crates/acp_thread/src/mention.rs +++ b/crates/acp_thread/src/mention.rs @@ -1,4 +1,4 @@ -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use anyhow::{Context as _, Result, bail}; use file_icons::FileIcons; use prompt_store::{PromptId, UserPromptId}; diff --git a/crates/acp_thread/src/terminal.rs b/crates/acp_thread/src/terminal.rs index fceb816f7f1471..08fcf32e0d3da8 100644 --- a/crates/acp_thread/src/terminal.rs +++ b/crates/acp_thread/src/terminal.rs @@ -1,4 +1,4 @@ -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use anyhow::Result; use futures::{FutureExt as _, future::Shared}; use gpui::{App, AppContext, AsyncApp, Context, Entity, Task}; diff --git a/crates/acp_tools/Cargo.toml b/crates/acp_tools/Cargo.toml index 8f14b1f93b32c6..43963b4034411c 100644 --- a/crates/acp_tools/Cargo.toml +++ b/crates/acp_tools/Cargo.toml @@ -14,7 +14,7 @@ path = "src/acp_tools.rs" doctest = false [dependencies] -agent-client-protocol.workspace = true +agent-client-protocol-core.workspace = true collections.workspace = true gpui.workspace = true language.workspace= true diff --git a/crates/acp_tools/src/acp_tools.rs b/crates/acp_tools/src/acp_tools.rs index ae8a39c8df4f73..dfeaab42e14e80 100644 --- a/crates/acp_tools/src/acp_tools.rs +++ b/crates/acp_tools/src/acp_tools.rs @@ -1,12 +1,6 @@ -use std::{ - cell::RefCell, - collections::HashSet, - fmt::Display, - rc::{Rc, Weak}, - sync::Arc, -}; +use std::{cell::RefCell, collections::HashSet, fmt::Display, sync::Arc}; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use collections::HashMap; use gpui::{ App, Empty, Entity, EventEmitter, FocusHandle, Focusable, Global, ListAlignment, ListState, @@ -23,6 +17,42 @@ use workspace::{ Item, ItemHandle, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView, Workspace, }; +// Stub types for the old streaming API which is not available in agent-client-protocol-core. +// These allow the ACP debug panel code to compile but the streaming won't be active. +#[allow(dead_code)] +type RequestId = String; + +#[derive(Clone)] +#[allow(dead_code)] +enum StreamMessageDirection { + Incoming, + Outgoing, +} + +#[derive(Clone)] +#[allow(dead_code)] +enum StreamMessageContent { + Request { + id: RequestId, + method: Arc, + params: Option, + }, + Response { + id: RequestId, + result: Result, acp::Error>, + }, + Notification { + method: Arc, + params: Option, + }, +} + +#[allow(dead_code)] +struct StreamMessage { + direction: StreamMessageDirection, + message: StreamMessageContent, +} + actions!(dev, [OpenAcpLogs]); pub fn init(cx: &mut App) { @@ -49,7 +79,6 @@ pub struct AcpConnectionRegistry { struct ActiveConnection { agent_id: AgentId, - connection: Weak, } impl AcpConnectionRegistry { @@ -63,16 +92,9 @@ impl AcpConnectionRegistry { } } - pub fn set_active_connection( - &self, - agent_id: AgentId, - connection: &Rc, - cx: &mut Context, - ) { - self.active_connection.replace(Some(ActiveConnection { - agent_id, - connection: Rc::downgrade(connection), - })); + pub fn set_active_connection(&self, agent_id: AgentId, cx: &mut Context) { + self.active_connection + .replace(Some(ActiveConnection { agent_id })); cx.notify(); } } @@ -90,9 +112,10 @@ struct WatchedConnection { agent_id: AgentId, messages: Vec, list_state: ListState, - connection: Weak, - incoming_request_methods: HashMap>, - outgoing_request_methods: HashMap>, + #[allow(dead_code)] + incoming_request_methods: HashMap>, + #[allow(dead_code)] + outgoing_request_methods: HashMap>, _task: Task<()>, } @@ -124,38 +147,23 @@ impl AcpTools { }; if let Some(watched_connection) = self.watched_connection.as_ref() { - if Weak::ptr_eq( - &watched_connection.connection, - &active_connection.connection, - ) { + if watched_connection.agent_id == active_connection.agent_id { return; } } - if let Some(connection) = active_connection.connection.upgrade() { - let mut receiver = connection.subscribe(); - let task = cx.spawn(async move |this, cx| { - while let Ok(message) = receiver.recv().await { - this.update(cx, |this, cx| { - this.push_stream_message(message, cx); - }) - .ok(); - } - }); - - self.watched_connection = Some(WatchedConnection { - agent_id: active_connection.agent_id.clone(), - messages: vec![], - list_state: ListState::new(0, ListAlignment::Bottom, px(2048.)), - connection: active_connection.connection.clone(), - incoming_request_methods: HashMap::default(), - outgoing_request_methods: HashMap::default(), - _task: task, - }); - } + self.watched_connection = Some(WatchedConnection { + agent_id: active_connection.agent_id.clone(), + messages: vec![], + list_state: ListState::new(0, ListAlignment::Bottom, px(2048.)), + incoming_request_methods: HashMap::default(), + outgoing_request_methods: HashMap::default(), + _task: Task::ready(()), + }); } - fn push_stream_message(&mut self, stream_message: acp::StreamMessage, cx: &mut Context) { + #[allow(dead_code)] + fn push_stream_message(&mut self, stream_message: StreamMessage, cx: &mut Context) { let Some(connection) = self.watched_connection.as_mut() else { return; }; @@ -163,27 +171,19 @@ impl AcpTools { let index = connection.messages.len(); let (request_id, method, message_type, params) = match stream_message.message { - acp::StreamMessageContent::Request { id, method, params } => { + StreamMessageContent::Request { id, method, params } => { let method_map = match stream_message.direction { - acp::StreamMessageDirection::Incoming => { - &mut connection.incoming_request_methods - } - acp::StreamMessageDirection::Outgoing => { - &mut connection.outgoing_request_methods - } + StreamMessageDirection::Incoming => &mut connection.incoming_request_methods, + StreamMessageDirection::Outgoing => &mut connection.outgoing_request_methods, }; method_map.insert(id.clone(), method.clone()); (Some(id), method.into(), MessageType::Request, Ok(params)) } - acp::StreamMessageContent::Response { id, result } => { + StreamMessageContent::Response { id, result } => { let method_map = match stream_message.direction { - acp::StreamMessageDirection::Incoming => { - &mut connection.outgoing_request_methods - } - acp::StreamMessageDirection::Outgoing => { - &mut connection.incoming_request_methods - } + StreamMessageDirection::Incoming => &mut connection.outgoing_request_methods, + StreamMessageDirection::Outgoing => &mut connection.incoming_request_methods, }; if let Some(method) = method_map.remove(&id) { @@ -197,7 +197,7 @@ impl AcpTools { ) } } - acp::StreamMessageContent::Notification { method, params } => { + StreamMessageContent::Notification { method, params } => { (None, method.into(), MessageType::Notification, Ok(params)) } }; @@ -243,8 +243,8 @@ impl AcpTools { }; Some(serde_json::json!({ "_direction": match message.direction { - acp::StreamMessageDirection::Incoming => "incoming", - acp::StreamMessageDirection::Outgoing => "outgoing", + StreamMessageDirection::Incoming => "incoming", + StreamMessageDirection::Outgoing => "outgoing", }, "_type": message.message_type.to_string().to_lowercase(), "id": message.request_id, @@ -326,10 +326,10 @@ impl AcpTools { cx.notify() })) .child(match message.direction { - acp::StreamMessageDirection::Incoming => Icon::new(IconName::ArrowDown) + StreamMessageDirection::Incoming => Icon::new(IconName::ArrowDown) .color(Color::Error) .size(IconSize::Small), - acp::StreamMessageDirection::Outgoing => Icon::new(IconName::ArrowUp) + StreamMessageDirection::Outgoing => Icon::new(IconName::ArrowUp) .color(Color::Success) .size(IconSize::Small), }) @@ -402,8 +402,8 @@ impl AcpTools { struct WatchedConnectionMessage { name: SharedString, - request_id: Option, - direction: acp::StreamMessageDirection, + request_id: Option, + direction: StreamMessageDirection, message_type: MessageType, params: Result, acp::Error>, collapsed_params_md: Option>, @@ -427,6 +427,7 @@ impl WatchedConnectionMessage { } } +#[allow(dead_code)] fn collapsed_params_md( params: &serde_json::Value, language_registry: &Arc, @@ -459,6 +460,7 @@ fn expanded_params_md( cx.new(|cx| Markdown::new(params_md.into(), Some(language_registry.clone()), None, cx)) } +#[allow(dead_code)] enum MessageType { Request, Response, diff --git a/crates/agent/Cargo.toml b/crates/agent/Cargo.toml index a5a4c2742a444b..84e72c089628c3 100644 --- a/crates/agent/Cargo.toml +++ b/crates/agent/Cargo.toml @@ -19,7 +19,7 @@ workspace = true [dependencies] acp_thread.workspace = true action_log.workspace = true -agent-client-protocol.workspace = true +agent-client-protocol-core.workspace = true agent_servers.workspace = true agent_settings.workspace = true anyhow.workspace = true diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rs index b7aa9d1e311016..5d87f88e8ab4bd 100644 --- a/crates/agent/src/agent.rs +++ b/crates/agent/src/agent.rs @@ -28,7 +28,7 @@ use acp_thread::{ AcpThread, AgentModelSelector, AgentSessionInfo, AgentSessionList, AgentSessionListRequest, AgentSessionListResponse, TokenUsageRatio, UserMessageId, }; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use anyhow::{Context as _, Result, anyhow}; use chrono::{DateTime, Utc}; use collections::{HashMap, HashSet, IndexMap}; diff --git a/crates/agent/src/db.rs b/crates/agent/src/db.rs index bde07a040869bf..e8b0383addf09f 100644 --- a/crates/agent/src/db.rs +++ b/crates/agent/src/db.rs @@ -1,6 +1,6 @@ use crate::{AgentMessage, AgentMessageContent, UserMessage, UserMessageContent}; use acp_thread::UserMessageId; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use agent_settings::AgentProfileId; use anyhow::{Result, anyhow}; use chrono::{DateTime, Utc}; diff --git a/crates/agent/src/native_agent_server.rs b/crates/agent/src/native_agent_server.rs index 7f19f9005e3ff5..a9b89fc518ddaa 100644 --- a/crates/agent/src/native_agent_server.rs +++ b/crates/agent/src/native_agent_server.rs @@ -1,6 +1,6 @@ use std::{any::Any, rc::Rc, sync::Arc}; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use agent_servers::{AgentServer, AgentServerDelegate}; use agent_settings::AgentSettings; use anyhow::Result; diff --git a/crates/agent/src/tests/mod.rs b/crates/agent/src/tests/mod.rs index 036a6f1030c43b..54f3d5a5b0ae55 100644 --- a/crates/agent/src/tests/mod.rs +++ b/crates/agent/src/tests/mod.rs @@ -3,7 +3,7 @@ use acp_thread::{ AgentConnection, AgentModelGroupName, AgentModelList, PermissionOptions, ThreadStatus, UserMessageId, }; -use agent_client_protocol::{self as acp}; +use agent_client_protocol_core::schema as acp; use agent_settings::AgentProfileId; use anyhow::Result; use client::{Client, UserStore}; @@ -5228,7 +5228,7 @@ async fn test_max_subagent_depth_prevents_tool_registration(cx: &mut TestAppCont cx, ); thread.set_subagent_context(SubagentContext { - parent_thread_id: agent_client_protocol::SessionId::new("parent-id"), + parent_thread_id: acp::SessionId::new("parent-id"), depth: MAX_SUBAGENT_DEPTH - 1, }); thread diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rs index b61df1b8af84d3..1d11372accc090 100644 --- a/crates/agent/src/thread.rs +++ b/crates/agent/src/thread.rs @@ -12,7 +12,7 @@ use feature_flags::{ FeatureFlagAppExt as _, StreamingEditFileToolFeatureFlag, UpdatePlanToolFeatureFlag, }; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use agent_settings::{ AgentProfileId, AgentSettings, SUMMARIZE_THREAD_DETAILED_PROMPT, SUMMARIZE_THREAD_PROMPT, }; @@ -3341,7 +3341,7 @@ where T::description() } - fn kind(&self) -> agent_client_protocol::ToolKind { + fn kind(&self) -> agent_client_protocol_core::schema::ToolKind { T::kind() } diff --git a/crates/agent/src/thread_store.rs b/crates/agent/src/thread_store.rs index e62ff78871c653..a4aac074c48ca1 100644 --- a/crates/agent/src/thread_store.rs +++ b/crates/agent/src/thread_store.rs @@ -1,5 +1,5 @@ use crate::{DbThread, DbThreadMetadata, ThreadsDatabase}; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use anyhow::{Result, anyhow}; use gpui::{App, Context, Entity, Global, Task, prelude::*}; use util::path_list::PathList; diff --git a/crates/agent/src/tools/context_server_registry.rs b/crates/agent/src/tools/context_server_registry.rs index df4cc313036b55..b4d65189c0a6c2 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::ToolKind; +use agent_client_protocol_core::schema::ToolKind; use anyhow::Result; use collections::{BTreeMap, HashMap}; use context_server::{ContextServerId, client::NotificationSubscription}; diff --git a/crates/agent/src/tools/copy_path_tool.rs b/crates/agent/src/tools/copy_path_tool.rs index 95688f27dcd8ca..5e9d72b43fcd1c 100644 --- a/crates/agent/src/tools/copy_path_tool.rs +++ b/crates/agent/src/tools/copy_path_tool.rs @@ -5,7 +5,7 @@ use super::tool_permissions::{ use crate::{ AgentTool, ToolCallEventStream, ToolInput, ToolPermissionDecision, decide_permission_for_paths, }; -use agent_client_protocol::ToolKind; +use agent_client_protocol_core::schema::ToolKind; use agent_settings::AgentSettings; use futures::FutureExt as _; use gpui::{App, Entity, Task}; @@ -198,7 +198,7 @@ impl AgentTool for CopyPathTool { #[cfg(test)] mod tests { use super::*; - use agent_client_protocol as acp; + use agent_client_protocol_core::schema as acp; use fs::Fs as _; use gpui::TestAppContext; use project::{FakeFs, Project}; diff --git a/crates/agent/src/tools/create_directory_tool.rs b/crates/agent/src/tools/create_directory_tool.rs index d6c59bcce30ab2..eb918dabeb4bcb 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::{ SensitiveSettingsKind, authorize_symlink_access, canonicalize_worktree_roots, detect_symlink_escape, sensitive_settings_kind, }; -use agent_client_protocol::ToolKind; +use agent_client_protocol_core::schema::ToolKind; use agent_settings::AgentSettings; use futures::FutureExt as _; use gpui::{App, Entity, SharedString, Task}; @@ -169,7 +169,7 @@ impl AgentTool for CreateDirectoryTool { #[cfg(test)] mod tests { use super::*; - use agent_client_protocol as acp; + use agent_client_protocol_core::schema as acp; use fs::Fs as _; use gpui::TestAppContext; use project::{FakeFs, Project}; diff --git a/crates/agent/src/tools/delete_path_tool.rs b/crates/agent/src/tools/delete_path_tool.rs index 7433975c7b782a..59a2c67cce7164 100644 --- a/crates/agent/src/tools/delete_path_tool.rs +++ b/crates/agent/src/tools/delete_path_tool.rs @@ -6,7 +6,7 @@ use crate::{ AgentTool, ToolCallEventStream, ToolInput, ToolPermissionDecision, decide_permission_for_path, }; use action_log::ActionLog; -use agent_client_protocol::ToolKind; +use agent_client_protocol_core::schema::ToolKind; use agent_settings::AgentSettings; use futures::{FutureExt as _, SinkExt, StreamExt, channel::mpsc}; use gpui::{App, AppContext, Entity, SharedString, Task}; @@ -228,7 +228,7 @@ impl AgentTool for DeletePathTool { #[cfg(test)] mod tests { use super::*; - use agent_client_protocol as acp; + use agent_client_protocol_core::schema as acp; use fs::Fs as _; use gpui::TestAppContext; use project::{FakeFs, Project}; diff --git a/crates/agent/src/tools/diagnostics_tool.rs b/crates/agent/src/tools/diagnostics_tool.rs index 5889f66c2edbe0..7f995e3f2f18d9 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 as acp; +use agent_client_protocol_core::schema as acp; use anyhow::Result; use futures::FutureExt as _; use gpui::{App, Entity, Task}; diff --git a/crates/agent/src/tools/edit_file_tool.rs b/crates/agent/src/tools/edit_file_tool.rs index 763efd6724a719..f3b67cad2b993c 100644 --- a/crates/agent/src/tools/edit_file_tool.rs +++ b/crates/agent/src/tools/edit_file_tool.rs @@ -6,7 +6,7 @@ use crate::{ edit_agent::{EditAgent, EditAgentOutputEvent, EditFormat}, }; use acp_thread::Diff; -use agent_client_protocol::{self as acp, ToolCallLocation, ToolCallUpdateFields}; +use agent_client_protocol_core::schema::{self as acp, ToolCallLocation, ToolCallUpdateFields}; use anyhow::{Context as _, Result}; use collections::HashSet; use futures::{FutureExt as _, StreamExt as _}; diff --git a/crates/agent/src/tools/fetch_tool.rs b/crates/agent/src/tools/fetch_tool.rs index 75880801595ad0..9fbd538ebaa4e2 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 as acp; +use agent_client_protocol_core::schema as acp; use agent_settings::AgentSettings; use anyhow::{Context as _, Result, bail}; use futures::{AsyncReadExt as _, FutureExt as _}; diff --git a/crates/agent/src/tools/find_path_tool.rs b/crates/agent/src/tools/find_path_tool.rs index 9c654615032251..8afc9dab09e9d4 100644 --- a/crates/agent/src/tools/find_path_tool.rs +++ b/crates/agent/src/tools/find_path_tool.rs @@ -1,5 +1,5 @@ use crate::{AgentTool, ToolCallEventStream, ToolInput}; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use anyhow::{Result, anyhow}; use futures::FutureExt as _; use gpui::{App, AppContext, Entity, SharedString, Task}; diff --git a/crates/agent/src/tools/grep_tool.rs b/crates/agent/src/tools/grep_tool.rs index fbfdc18585b822..050e67e8241feb 100644 --- a/crates/agent/src/tools/grep_tool.rs +++ b/crates/agent/src/tools/grep_tool.rs @@ -1,5 +1,5 @@ use crate::{AgentTool, ToolCallEventStream, ToolInput}; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use anyhow::Result; use futures::{FutureExt as _, StreamExt}; use gpui::{App, Entity, SharedString, Task}; diff --git a/crates/agent/src/tools/list_directory_tool.rs b/crates/agent/src/tools/list_directory_tool.rs index 7abbe1ed4c4882..218412fe111152 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_project_path, }; use crate::{AgentTool, ToolCallEventStream, ToolInput}; -use agent_client_protocol::ToolKind; +use agent_client_protocol_core::schema::ToolKind; use anyhow::{Context as _, Result, anyhow}; use gpui::{App, Entity, SharedString, Task}; use project::{Project, ProjectPath, WorktreeSettings}; @@ -267,7 +267,7 @@ impl AgentTool for ListDirectoryTool { #[cfg(test)] mod tests { use super::*; - use agent_client_protocol as acp; + use agent_client_protocol_core::schema as acp; use fs::Fs as _; use gpui::{TestAppContext, UpdateGlobal}; use indoc::indoc; diff --git a/crates/agent/src/tools/move_path_tool.rs b/crates/agent/src/tools/move_path_tool.rs index 147947bb67ec64..d88e529081e805 100644 --- a/crates/agent/src/tools/move_path_tool.rs +++ b/crates/agent/src/tools/move_path_tool.rs @@ -5,7 +5,7 @@ use super::tool_permissions::{ use crate::{ AgentTool, ToolCallEventStream, ToolInput, ToolPermissionDecision, decide_permission_for_paths, }; -use agent_client_protocol::ToolKind; +use agent_client_protocol_core::schema::ToolKind; use agent_settings::AgentSettings; use futures::FutureExt as _; use gpui::{App, Entity, SharedString, Task}; @@ -205,7 +205,7 @@ impl AgentTool for MovePathTool { #[cfg(test)] mod tests { use super::*; - use agent_client_protocol as acp; + use agent_client_protocol_core::schema as acp; use fs::Fs as _; use gpui::TestAppContext; use project::{FakeFs, Project}; diff --git a/crates/agent/src/tools/now_tool.rs b/crates/agent/src/tools/now_tool.rs index fe1cafe5881d14..1deeb6861802b8 100644 --- a/crates/agent/src/tools/now_tool.rs +++ b/crates/agent/src/tools/now_tool.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use chrono::{Local, Utc}; use gpui::{App, SharedString, Task}; use schemars::JsonSchema; diff --git a/crates/agent/src/tools/open_tool.rs b/crates/agent/src/tools/open_tool.rs index 344a513d10c2d6..bae306c75898ac 100644 --- a/crates/agent/src/tools/open_tool.rs +++ b/crates/agent/src/tools/open_tool.rs @@ -3,7 +3,7 @@ use super::tool_permissions::{ resolve_project_path, }; use crate::{AgentTool, ToolInput}; -use agent_client_protocol::ToolKind; +use agent_client_protocol_core::schema::ToolKind; use futures::FutureExt as _; use gpui::{App, AppContext as _, Entity, SharedString, Task}; use project::Project; diff --git a/crates/agent/src/tools/read_file_tool.rs b/crates/agent/src/tools/read_file_tool.rs index 093a8580892cfc..96a44c443b63eb 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::{self as acp, ToolCallUpdateFields}; +use agent_client_protocol_core::schema::{self as acp, ToolCallUpdateFields}; use anyhow::{Context as _, Result, anyhow}; use futures::FutureExt as _; use gpui::{App, Entity, SharedString, Task}; @@ -347,7 +347,7 @@ impl AgentTool for ReadFileTool { #[cfg(test)] mod test { use super::*; - use agent_client_protocol as acp; + use agent_client_protocol_core::schema as acp; use fs::Fs as _; use gpui::{AppContext, TestAppContext, UpdateGlobal as _}; use project::{FakeFs, Project}; diff --git a/crates/agent/src/tools/restore_file_from_disk_tool.rs b/crates/agent/src/tools/restore_file_from_disk_tool.rs index 9273ea5b8bb041..1c9f398029eb5b 100644 --- a/crates/agent/src/tools/restore_file_from_disk_tool.rs +++ b/crates/agent/src/tools/restore_file_from_disk_tool.rs @@ -3,7 +3,7 @@ use super::tool_permissions::{ canonicalize_worktree_roots, path_has_symlink_escape, resolve_project_path, sensitive_settings_kind, }; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use agent_settings::AgentSettings; use collections::FxHashSet; use futures::FutureExt as _; diff --git a/crates/agent/src/tools/save_file_tool.rs b/crates/agent/src/tools/save_file_tool.rs index c6a1cd79db6512..833f74e02fd448 100644 --- a/crates/agent/src/tools/save_file_tool.rs +++ b/crates/agent/src/tools/save_file_tool.rs @@ -1,4 +1,4 @@ -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use agent_settings::AgentSettings; use collections::FxHashSet; use futures::FutureExt as _; diff --git a/crates/agent/src/tools/spawn_agent_tool.rs b/crates/agent/src/tools/spawn_agent_tool.rs index 27afbbdc3ea05d..0639e2fa11b4de 100644 --- a/crates/agent/src/tools/spawn_agent_tool.rs +++ b/crates/agent/src/tools/spawn_agent_tool.rs @@ -1,5 +1,5 @@ use acp_thread::{SUBAGENT_SESSION_INFO_META_KEY, SubagentSessionInfo}; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use anyhow::Result; use gpui::{App, SharedString, Task}; use language_model::LanguageModelToolResultContent; diff --git a/crates/agent/src/tools/streaming_edit_file_tool.rs b/crates/agent/src/tools/streaming_edit_file_tool.rs index c0c29bfc43d9c5..c185295d713ddd 100644 --- a/crates/agent/src/tools/streaming_edit_file_tool.rs +++ b/crates/agent/src/tools/streaming_edit_file_tool.rs @@ -11,7 +11,7 @@ use crate::{ }; use acp_thread::Diff; use action_log::ActionLog; -use agent_client_protocol::{self as acp, ToolCallLocation, ToolCallUpdateFields}; +use agent_client_protocol_core::schema::{self as acp, ToolCallLocation, ToolCallUpdateFields}; use anyhow::{Context as _, Result}; use collections::HashSet; use futures::FutureExt as _; diff --git a/crates/agent/src/tools/terminal_tool.rs b/crates/agent/src/tools/terminal_tool.rs index 82bf9a06480bb7..b19323da2b6990 100644 --- a/crates/agent/src/tools/terminal_tool.rs +++ b/crates/agent/src/tools/terminal_tool.rs @@ -1,4 +1,4 @@ -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use agent_settings::AgentSettings; use anyhow::Result; use futures::FutureExt as _; diff --git a/crates/agent/src/tools/update_plan_tool.rs b/crates/agent/src/tools/update_plan_tool.rs index 8d45f8aad42a8c..af18f6409d0b19 100644 --- a/crates/agent/src/tools/update_plan_tool.rs +++ b/crates/agent/src/tools/update_plan_tool.rs @@ -1,5 +1,5 @@ use crate::{AgentTool, ToolCallEventStream, ToolInput}; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use gpui::{App, SharedString, Task}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; diff --git a/crates/agent/src/tools/web_search_tool.rs b/crates/agent/src/tools/web_search_tool.rs index c697a5b78f1fe8..7d0a50a8c9c2d7 100644 --- a/crates/agent/src/tools/web_search_tool.rs +++ b/crates/agent/src/tools/web_search_tool.rs @@ -4,7 +4,7 @@ use crate::{ AgentTool, ToolCallEventStream, ToolInput, ToolPermissionDecision, decide_permission_from_settings, }; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use agent_settings::AgentSettings; use anyhow::Result; use cloud_llm_client::WebSearchResponse; diff --git a/crates/agent_servers/Cargo.toml b/crates/agent_servers/Cargo.toml index 1542466be35bbc..4caf08c7c0bb9d 100644 --- a/crates/agent_servers/Cargo.toml +++ b/crates/agent_servers/Cargo.toml @@ -20,7 +20,7 @@ doctest = false acp_tools.workspace = true acp_thread.workspace = true action_log.workspace = true -agent-client-protocol.workspace = true +agent-client-protocol-core.workspace = true anyhow.workspace = true async-trait.workspace = true chrono.workspace = true diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs index 5f452bc9c0e2e9..2ef69c0fb0f3ab 100644 --- a/crates/agent_servers/src/acp.rs +++ b/crates/agent_servers/src/acp.rs @@ -2,14 +2,15 @@ use acp_thread::{ AgentConnection, AgentSessionInfo, AgentSessionList, AgentSessionListRequest, AgentSessionListResponse, }; -use acp_tools::AcpConnectionRegistry; use action_log::ActionLog; -use agent_client_protocol::{self as acp, Agent as _, ErrorCode}; +use agent_client_protocol_core::schema::{self as acp, ErrorCode}; +use agent_client_protocol_core::{ByteStreams, ConnectionTo}; use anyhow::anyhow; use collections::HashMap; use feature_flags::{AcpBetaFeatureFlag, FeatureFlagAppExt as _}; -use futures::AsyncBufReadExt as _; +use futures::channel::mpsc; use futures::io::BufReader; +use futures::{AsyncBufReadExt as _, StreamExt as _}; use project::agent_server_store::AgentServerCommand; use project::{AgentId, Project}; use serde::Deserialize; @@ -40,10 +41,19 @@ pub const GEMINI_TERMINAL_AUTH_METHOD_ID: &str = "spawn-gemini-cli"; #[error("Unsupported version")] pub struct UnsupportedVersion; +/// Holds state needed by foreground work dispatched from background handler closures. +struct ClientContext { + sessions: Rc>>, + session_list: Rc>>>, +} + +/// Work items sent from `Send` handler closures to the `!Send` foreground thread. +type ForegroundWork = Box; + pub struct AcpConnection { id: AgentId, telemetry_id: SharedString, - connection: Rc, + connection: ConnectionTo, sessions: Rc>>, auth_methods: Vec, command: AgentServerCommand, @@ -53,7 +63,8 @@ pub struct AcpConnection { default_config_options: HashMap, child: Child, session_list: Option>, - _io_task: Task>, + _io_task: Task<()>, + _dispatch_task: Task<()>, _wait_task: Task>, _stderr_task: Task>, } @@ -84,13 +95,13 @@ pub struct AcpSession { } pub struct AcpSessionList { - connection: Rc, + connection: ConnectionTo, updates_tx: smol::channel::Sender, updates_rx: smol::channel::Receiver, } impl AcpSessionList { - fn new(connection: Rc) -> Self { + fn new(connection: ConnectionTo) -> Self { let (tx, rx) = smol::channel::unbounded(); Self { connection, @@ -123,7 +134,11 @@ impl AgentSessionList for AcpSessionList { let acp_request = acp::ListSessionsRequest::new() .cwd(request.cwd) .cursor(request.cursor); - let response = conn.list_sessions(acp_request).await?; + let response = conn + .send_request(acp_request) + .block_task() + .await + .map_err(map_acp_error)?; Ok(AgentSessionListResponse { sessions: response .sessions @@ -240,20 +255,225 @@ impl AcpConnection { let client_session_list: Rc>>> = Rc::new(RefCell::new(None)); - let client = ClientDelegate { + // Set up the foreground dispatch channel for bridging Send handler + // closures to the !Send foreground thread. + let (dispatch_tx, dispatch_rx) = mpsc::unbounded::(); + + // Build the transport from child stdio + let transport = ByteStreams::new(stdin, stdout); + + // Use a oneshot channel to extract the ConnectionTo from the + // connect_with closure. + let (connection_tx, connection_rx) = futures::channel::oneshot::channel(); + + // Build the connection with handler closures. + // All handlers forward work to the foreground dispatch channel. + let connection_future = { + let dispatch_tx = dispatch_tx.clone(); + agent_client_protocol_core::Client + .builder() + .name("zed") + // --- Request handlers (agent→client) --- + .on_receive_request( + { + let dispatch_tx = dispatch_tx.clone(); + async move |args: acp::RequestPermissionRequest, + responder: agent_client_protocol_core::Responder< + acp::RequestPermissionResponse, + >, + _connection: ConnectionTo< + agent_client_protocol_core::Agent, + >| { + dispatch_tx + .unbounded_send(Box::new(move |cx, ctx| { + handle_request_permission(args, responder, cx, ctx); + })) + .ok(); + Ok(()) + } + }, + agent_client_protocol_core::on_receive_request!(), + ) + .on_receive_request( + { + let dispatch_tx = dispatch_tx.clone(); + async move |args: acp::WriteTextFileRequest, + responder: agent_client_protocol_core::Responder< + acp::WriteTextFileResponse, + >, + _connection| { + dispatch_tx + .unbounded_send(Box::new(move |cx, ctx| { + handle_write_text_file(args, responder, cx, ctx); + })) + .ok(); + Ok(()) + } + }, + agent_client_protocol_core::on_receive_request!(), + ) + .on_receive_request( + { + let dispatch_tx = dispatch_tx.clone(); + async move |args: acp::ReadTextFileRequest, + responder: agent_client_protocol_core::Responder< + acp::ReadTextFileResponse, + >, + _connection| { + dispatch_tx + .unbounded_send(Box::new(move |cx, ctx| { + handle_read_text_file(args, responder, cx, ctx); + })) + .ok(); + Ok(()) + } + }, + agent_client_protocol_core::on_receive_request!(), + ) + .on_receive_request( + { + let dispatch_tx = dispatch_tx.clone(); + async move |args: acp::CreateTerminalRequest, + responder: agent_client_protocol_core::Responder< + acp::CreateTerminalResponse, + >, + _connection| { + dispatch_tx + .unbounded_send(Box::new(move |cx, ctx| { + handle_create_terminal(args, responder, cx, ctx); + })) + .ok(); + Ok(()) + } + }, + agent_client_protocol_core::on_receive_request!(), + ) + .on_receive_request( + { + let dispatch_tx = dispatch_tx.clone(); + async move |args: acp::KillTerminalRequest, + responder: agent_client_protocol_core::Responder< + acp::KillTerminalResponse, + >, + _connection| { + dispatch_tx + .unbounded_send(Box::new(move |cx, ctx| { + handle_kill_terminal(args, responder, cx, ctx); + })) + .ok(); + Ok(()) + } + }, + agent_client_protocol_core::on_receive_request!(), + ) + .on_receive_request( + { + let dispatch_tx = dispatch_tx.clone(); + async move |args: acp::ReleaseTerminalRequest, + responder: agent_client_protocol_core::Responder< + acp::ReleaseTerminalResponse, + >, + _connection| { + dispatch_tx + .unbounded_send(Box::new(move |cx, ctx| { + handle_release_terminal(args, responder, cx, ctx); + })) + .ok(); + Ok(()) + } + }, + agent_client_protocol_core::on_receive_request!(), + ) + .on_receive_request( + { + let dispatch_tx = dispatch_tx.clone(); + async move |args: acp::TerminalOutputRequest, + responder: agent_client_protocol_core::Responder< + acp::TerminalOutputResponse, + >, + _connection| { + dispatch_tx + .unbounded_send(Box::new(move |cx, ctx| { + handle_terminal_output(args, responder, cx, ctx); + })) + .ok(); + Ok(()) + } + }, + agent_client_protocol_core::on_receive_request!(), + ) + .on_receive_request( + { + let dispatch_tx = dispatch_tx.clone(); + async move |args: acp::WaitForTerminalExitRequest, + responder: agent_client_protocol_core::Responder< + acp::WaitForTerminalExitResponse, + >, + _connection| { + dispatch_tx + .unbounded_send(Box::new(move |cx, ctx| { + handle_wait_for_terminal_exit(args, responder, cx, ctx); + })) + .ok(); + Ok(()) + } + }, + agent_client_protocol_core::on_receive_request!(), + ) + // --- Notification handlers (agent→client) --- + .on_receive_notification( + { + let dispatch_tx = dispatch_tx.clone(); + async move |notification: acp::SessionNotification, + _connection: ConnectionTo< + agent_client_protocol_core::Agent, + >| { + dispatch_tx + .unbounded_send(Box::new(move |cx, ctx| { + handle_session_notification(notification, cx, ctx); + })) + .ok(); + Ok(()) + } + }, + agent_client_protocol_core::on_receive_notification!(), + ) + .connect_with( + transport, + move |connection: ConnectionTo| async move { + connection_tx.send(connection.clone()).ok(); + // Keep the connection alive until the transport closes. + futures::future::pending::>().await + }, + ) + }; + + // Spawn the connection loop on a background thread. + let io_task = cx.background_spawn(async move { + if let Err(err) = connection_future.await { + log::error!("ACP connection error: {err}"); + } + }); + + // Wait for the ConnectionTo handle. + let connection: ConnectionTo = connection_rx + .await + .context("Failed to receive ACP connection handle")?; + + // Set up the foreground dispatch loop to process work items from handlers. + let dispatch_context = ClientContext { sessions: sessions.clone(), session_list: client_session_list.clone(), - cx: cx.clone(), }; - let (connection, io_task) = acp::ClientSideConnection::new(client, stdin, stdout, { - let foreground_executor = cx.foreground_executor().clone(); - move |fut| { - foreground_executor.spawn(fut).detach(); + let dispatch_task = cx.spawn({ + let mut dispatch_rx = dispatch_rx; + async move |cx| { + while let Some(work) = dispatch_rx.next().await { + work(cx, &dispatch_context); + } } }); - let io_task = cx.background_spawn(io_task); - let stderr_task = cx.background_spawn(async move { let mut stderr = BufReader::new(stderr); let mut line = String::new(); @@ -285,16 +505,16 @@ impl AcpConnection { } }); - let connection = Rc::new(connection); - - cx.update(|cx| { - AcpConnectionRegistry::default_global(cx).update(cx, |registry, cx| { - registry.set_active_connection(agent_id.clone(), &connection, cx) - }); - }); + // TODO: Update AcpConnectionRegistry to support ConnectionTo + // The old streaming/subscribe API is not available in agent-client-protocol-core. + // cx.update(|cx| { + // AcpConnectionRegistry::default_global(cx).update(cx, |registry, cx| { + // registry.set_active_connection(agent_id.clone(), &connection, cx) + // }); + // }); let response = connection - .initialize( + .send_request( acp::InitializeRequest::new(acp::ProtocolVersion::V1) .client_capabilities( acp::ClientCapabilities::new() @@ -303,7 +523,6 @@ impl AcpConnection { .write_text_file(true)) .terminal(true) .auth(acp::AuthCapabilities::new().terminal(true)) - // Experimental: Allow for rendering terminal output from the agents .meta(acp::Meta::from_iter([ ("terminal_output".into(), true.into()), ("terminal-auth".into(), true.into()), @@ -314,6 +533,7 @@ impl AcpConnection { .title(release_channel.map(ToOwned::to_owned)), ), ) + .block_task() .await?; if response.protocol_version < MINIMUM_SUPPORTED_VERSION { @@ -322,9 +542,7 @@ impl AcpConnection { let telemetry_id = response .agent_info - // Use the one the agent provides if we have one .map(|info| info.name.into()) - // Otherwise, just use the name .unwrap_or_else(|| agent_id.0.to_string().into()); let session_list = if response @@ -372,6 +590,7 @@ impl AcpConnection { default_config_options, session_list, _io_task: io_task, + _dispatch_task: dispatch_task, _wait_task: wait_task, _stderr_task: stderr_task, child, @@ -447,11 +666,12 @@ impl AcpConnection { let conn = self.connection.clone(); async move |_| { let result = conn - .set_session_config_option(acp::SetSessionConfigOptionRequest::new( + .send_request(acp::SetSessionConfigOptionRequest::new( session_id, config_id_clone.clone(), default_value_id, )) + .block_task() .await .log_err(); @@ -566,17 +786,25 @@ impl AgentConnection for AcpConnection { let mcp_servers = mcp_servers_for_project(&project, cx); cx.spawn(async move |cx| { - let response = self.connection - .new_session(acp::NewSessionRequest::new(cwd.clone()).mcp_servers(mcp_servers)) + let response = self + .connection + .send_request( + acp::NewSessionRequest::new(cwd.clone()).mcp_servers(mcp_servers), + ) + .block_task() .await .map_err(map_acp_error)?; - let (modes, models, config_options) = config_state(response.modes, response.models, response.config_options); + let (modes, models, config_options) = + config_state(response.modes, response.models, response.config_options); if let Some(default_mode) = self.default_mode.clone() { if let Some(modes) = modes.as_ref() { let mut modes_ref = modes.borrow_mut(); - let has_mode = modes_ref.available_modes.iter().any(|mode| mode.id == default_mode); + let has_mode = modes_ref + .available_modes + .iter() + .any(|mode| mode.id == default_mode); if has_mode { let initial_mode_id = modes_ref.current_mode_id.clone(); @@ -587,14 +815,21 @@ impl AgentConnection for AcpConnection { let modes = modes.clone(); let conn = self.connection.clone(); async move |_| { - let result = conn.set_session_mode(acp::SetSessionModeRequest::new(session_id, default_mode)) - .await.log_err(); + let result = conn + .send_request(acp::SetSessionModeRequest::new( + session_id, + default_mode, + )) + .block_task() + .await + .log_err(); if result.is_none() { modes.borrow_mut().current_mode_id = initial_mode_id; } } - }).detach(); + }) + .detach(); modes_ref.current_mode_id = default_mode; } else { @@ -615,7 +850,10 @@ impl AgentConnection for AcpConnection { if let Some(default_model) = self.default_model.clone() { if let Some(models) = models.as_ref() { let mut models_ref = models.borrow_mut(); - let has_model = models_ref.available_models.iter().any(|model| model.model_id == default_model); + let has_model = models_ref + .available_models + .iter() + .any(|model| model.model_id == default_model); if has_model { let initial_model_id = models_ref.current_model_id.clone(); @@ -626,14 +864,21 @@ impl AgentConnection for AcpConnection { let models = models.clone(); let conn = self.connection.clone(); async move |_| { - let result = conn.set_session_model(acp::SetSessionModelRequest::new(session_id, default_model)) - .await.log_err(); + let result = conn + .send_request(acp::SetSessionModelRequest::new( + session_id, + default_model, + )) + .block_task() + .await + .log_err(); if result.is_none() { models.borrow_mut().current_model_id = initial_model_id; } } - }).detach(); + }) + .detach(); models_ref.current_model_id = default_model; } else { @@ -665,8 +910,9 @@ impl AgentConnection for AcpConnection { project, action_log, response.session_id.clone(), - // ACP doesn't currently support per-session prompt capabilities or changing capabilities dynamically. - watch::Receiver::constant(self.agent_capabilities.prompt_capabilities.clone()), + watch::Receiver::constant( + self.agent_capabilities.prompt_capabilities.clone(), + ), cx, ) }); @@ -745,9 +991,10 @@ impl AgentConnection for AcpConnection { cx.spawn(async move |cx| { let response = match self .connection - .load_session( + .send_request( acp::LoadSessionRequest::new(session_id.clone(), cwd).mcp_servers(mcp_servers), ) + .block_task() .await { Ok(response) => response, @@ -827,10 +1074,11 @@ impl AgentConnection for AcpConnection { cx.spawn(async move |cx| { let response = match self .connection - .resume_session( + .send_request( acp::ResumeSessionRequest::new(session_id.clone(), cwd) .mcp_servers(mcp_servers), ) + .block_task() .await { Ok(response) => response, @@ -875,7 +1123,8 @@ impl AgentConnection for AcpConnection { let conn = self.connection.clone(); let session_id = session_id.clone(); cx.foreground_executor().spawn(async move { - conn.close_session(acp::CloseSessionRequest::new(session_id.clone())) + conn.send_request(acp::CloseSessionRequest::new(session_id.clone())) + .block_task() .await?; self.sessions.borrow_mut().remove(&session_id); Ok(()) @@ -907,7 +1156,8 @@ impl AgentConnection for AcpConnection { fn authenticate(&self, method_id: acp::AuthMethodId, cx: &mut App) -> Task> { let conn = self.connection.clone(); cx.foreground_executor().spawn(async move { - conn.authenticate(acp::AuthenticateRequest::new(method_id)) + conn.send_request(acp::AuthenticateRequest::new(method_id)) + .block_task() .await?; Ok(()) }) @@ -923,7 +1173,7 @@ impl AgentConnection for AcpConnection { let sessions = self.sessions.clone(); let session_id = params.session_id.clone(); cx.foreground_executor().spawn(async move { - let result = conn.prompt(params).await; + let result = conn.send_request(params).block_task().await; let mut suppress_abort_err = false; @@ -974,15 +1224,12 @@ impl AgentConnection for AcpConnection { }) } - fn cancel(&self, session_id: &acp::SessionId, cx: &mut App) { + fn cancel(&self, session_id: &acp::SessionId, _cx: &mut App) { if let Some(session) = self.sessions.borrow_mut().get_mut(session_id) { session.suppress_abort_err = true; } - let conn = self.connection.clone(); let params = acp::CancelNotification::new(session_id.clone()); - cx.foreground_executor() - .spawn(async move { conn.cancel(params).await }) - .detach(); + self.connection.send_notification(params).log_err(); } fn session_modes( @@ -1280,7 +1527,7 @@ fn config_state( struct AcpSessionModes { session_id: acp::SessionId, - connection: Rc, + connection: ConnectionTo, state: Rc>, } @@ -1305,7 +1552,8 @@ impl acp_thread::AgentSessionModes for AcpSessionModes { let state = self.state.clone(); cx.foreground_executor().spawn(async move { let result = connection - .set_session_mode(acp::SetSessionModeRequest::new(session_id, mode_id)) + .send_request(acp::SetSessionModeRequest::new(session_id, mode_id)) + .block_task() .await; if result.is_err() { @@ -1321,14 +1569,14 @@ impl acp_thread::AgentSessionModes for AcpSessionModes { struct AcpModelSelector { session_id: acp::SessionId, - connection: Rc, + connection: ConnectionTo, state: Rc>, } impl AcpModelSelector { fn new( session_id: acp::SessionId, - connection: Rc, + connection: ConnectionTo, state: Rc>, ) -> Self { Self { @@ -1364,7 +1612,8 @@ impl acp_thread::AgentModelSelector for AcpModelSelector { let state = self.state.clone(); cx.foreground_executor().spawn(async move { let result = connection - .set_session_model(acp::SetSessionModelRequest::new(session_id, model_id)) + .send_request(acp::SetSessionModelRequest::new(session_id, model_id)) + .block_task() .await; if result.is_err() { @@ -1393,7 +1642,7 @@ impl acp_thread::AgentModelSelector for AcpModelSelector { struct AcpSessionConfigOptions { session_id: acp::SessionId, - connection: Rc, + connection: ConnectionTo, state: Rc>>, watch_tx: Rc>>, watch_rx: watch::Receiver<()>, @@ -1418,9 +1667,10 @@ impl acp_thread::AgentSessionConfigOptions for AcpSessionConfigOptions { cx.foreground_executor().spawn(async move { let response = connection - .set_session_config_option(acp::SetSessionConfigOptionRequest::new( + .send_request(acp::SetSessionConfigOptionRequest::new( session_id, config_id, value, )) + .block_task() .await?; *state.borrow_mut() = response.config_options.clone(); @@ -1434,312 +1684,457 @@ impl acp_thread::AgentSessionConfigOptions for AcpSessionConfigOptions { } } -struct ClientDelegate { - sessions: Rc>>, - session_list: Rc>>>, - cx: AsyncApp, +// --------------------------------------------------------------------------- +// Handler functions dispatched from background handler closures to the +// foreground thread via the ForegroundWork channel. +// --------------------------------------------------------------------------- + +fn session_thread( + ctx: &ClientContext, + session_id: &acp::SessionId, +) -> Result, acp::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}"))) } -#[async_trait::async_trait(?Send)] -impl acp::Client for ClientDelegate { - async fn request_permission( - &self, - arguments: acp::RequestPermissionRequest, - ) -> Result { - let thread; - { - let sessions_ref = self.sessions.borrow(); - let session = sessions_ref - .get(&arguments.session_id) - .context("Failed to get session")?; - thread = session.thread.clone(); - } - - let cx = &mut self.cx.clone(); - - let task = thread.update(cx, |thread, cx| { - thread.request_tool_call_authorization( - arguments.tool_call, - acp_thread::PermissionOptions::Flat(arguments.options), - cx, - ) - })??; - - let outcome = task.await; +fn respond_err( + responder: agent_client_protocol_core::Responder, + err: acp::Error, +) { + responder.respond_with_error(err).log_err(); +} - Ok(acp::RequestPermissionResponse::new(outcome.into())) - } +fn handle_request_permission( + args: acp::RequestPermissionRequest, + responder: agent_client_protocol_core::Responder, + cx: &mut AsyncApp, + ctx: &ClientContext, +) { + let thread = match session_thread(ctx, &args.session_id) { + Ok(t) => t, + Err(e) => return respond_err(responder, e), + }; + + cx.spawn(async move |cx| { + let result: Result<_, acp::Error> = async { + let task = thread + .update(cx, |thread, cx| { + thread.request_tool_call_authorization( + args.tool_call, + acp_thread::PermissionOptions::Flat(args.options), + cx, + ) + }) + .map_err(acp::Error::from)? + .map_err(acp::Error::from)?; + Ok(task.await) + } + .await; - async fn write_text_file( - &self, - arguments: acp::WriteTextFileRequest, - ) -> Result { - let cx = &mut self.cx.clone(); - let task = self - .session_thread(&arguments.session_id)? - .update(cx, |thread, cx| { - thread.write_text_file(arguments.path, arguments.content, cx) - })?; - - task.await?; - - Ok(Default::default()) - } + match result { + Ok(outcome) => { + responder + .respond(acp::RequestPermissionResponse::new(outcome.into())) + .log_err(); + } + Err(e) => respond_err(responder, e), + } + }) + .detach(); +} - async fn read_text_file( - &self, - arguments: acp::ReadTextFileRequest, - ) -> Result { - let task = self.session_thread(&arguments.session_id)?.update( - &mut self.cx.clone(), - |thread, cx| { - thread.read_text_file(arguments.path, arguments.line, arguments.limit, false, cx) - }, - )?; +fn handle_write_text_file( + args: acp::WriteTextFileRequest, + responder: agent_client_protocol_core::Responder, + cx: &mut AsyncApp, + ctx: &ClientContext, +) { + let thread = match session_thread(ctx, &args.session_id) { + Ok(t) => t, + Err(e) => return respond_err(responder, e), + }; + + cx.spawn(async move |cx| { + let result: Result<_, acp::Error> = async { + let task = thread + .update(cx, |thread, cx| { + thread.write_text_file(args.path, args.content, cx) + }) + .map_err(acp::Error::from)?; + task.await.map_err(acp::Error::from)?; + Ok(()) + } + .await; - let content = task.await?; + match result { + Ok(()) => { + responder + .respond(acp::WriteTextFileResponse::default()) + .log_err(); + } + Err(e) => respond_err(responder, e), + } + }) + .detach(); +} - Ok(acp::ReadTextFileResponse::new(content)) - } +fn handle_read_text_file( + args: acp::ReadTextFileRequest, + responder: agent_client_protocol_core::Responder, + cx: &mut AsyncApp, + ctx: &ClientContext, +) { + let thread = match session_thread(ctx, &args.session_id) { + Ok(t) => t, + Err(e) => return respond_err(responder, e), + }; + + cx.spawn(async move |cx| { + let result: Result<_, acp::Error> = async { + thread + .update(cx, |thread, cx| { + thread.read_text_file(args.path, args.line, args.limit, false, cx) + }) + .map_err(acp::Error::from)? + .await + } + .await; - async fn session_notification( - &self, - notification: acp::SessionNotification, - ) -> Result<(), acp::Error> { - let sessions = self.sessions.borrow(); - let session = sessions - .get(¬ification.session_id) - .context("Failed to get session")?; - - if let acp::SessionUpdate::CurrentModeUpdate(acp::CurrentModeUpdate { - current_mode_id, - .. - }) = ¬ification.update - { - if let Some(session_modes) = &session.session_modes { - session_modes.borrow_mut().current_mode_id = current_mode_id.clone(); + match result { + Ok(content) => { + responder + .respond(acp::ReadTextFileResponse::new(content)) + .log_err(); } + Err(e) => respond_err(responder, e), } + }) + .detach(); +} - if let acp::SessionUpdate::ConfigOptionUpdate(acp::ConfigOptionUpdate { - config_options, - .. - }) = ¬ification.update - { - if let Some(opts) = &session.config_options { - *opts.config_options.borrow_mut() = config_options.clone(); - opts.tx.borrow_mut().send(()).ok(); - } +fn handle_session_notification( + notification: acp::SessionNotification, + cx: &mut AsyncApp, + ctx: &ClientContext, +) { + let sessions = ctx.sessions.borrow(); + let Some(session) = sessions.get(¬ification.session_id) else { + log::warn!( + "Received session notification for unknown session: {:?}", + notification.session_id + ); + return; + }; + + if let acp::SessionUpdate::CurrentModeUpdate(acp::CurrentModeUpdate { + current_mode_id, .. + }) = ¬ification.update + { + if let Some(session_modes) = &session.session_modes { + session_modes.borrow_mut().current_mode_id = current_mode_id.clone(); } + } - if let acp::SessionUpdate::SessionInfoUpdate(info_update) = ¬ification.update - && let Some(session_list) = self.session_list.borrow().as_ref() - { - session_list.send_info_update(notification.session_id.clone(), info_update.clone()); + if let acp::SessionUpdate::ConfigOptionUpdate(acp::ConfigOptionUpdate { + config_options, .. + }) = ¬ification.update + { + if let Some(opts) = &session.config_options { + *opts.config_options.borrow_mut() = config_options.clone(); + opts.tx.borrow_mut().send(()).ok(); } + } - // Clone so we can inspect meta both before and after handing off to the thread - let update_clone = notification.update.clone(); + if let acp::SessionUpdate::SessionInfoUpdate(info_update) = ¬ification.update + && let Some(session_list) = ctx.session_list.borrow().as_ref() + { + session_list.send_info_update(notification.session_id.clone(), info_update.clone()); + } - // Pre-handle: if a ToolCall carries terminal_info, create/register a display-only terminal. - if let acp::SessionUpdate::ToolCall(tc) = &update_clone { - if let Some(meta) = &tc.meta { - if let Some(terminal_info) = meta.get("terminal_info") { - if let Some(id_str) = terminal_info.get("terminal_id").and_then(|v| v.as_str()) - { - let terminal_id = acp::TerminalId::new(id_str); - let cwd = terminal_info - .get("cwd") - .and_then(|v| v.as_str().map(PathBuf::from)); - - // Create a minimal display-only lower-level terminal and register it. - let _ = session.thread.update(&mut self.cx.clone(), |thread, cx| { - let builder = TerminalBuilder::new_display_only( - CursorShape::default(), - AlternateScroll::On, - None, - 0, - cx.background_executor(), - thread.project().read(cx).path_style(cx), - )?; - let lower = cx.new(|cx| builder.subscribe(cx)); - thread.on_terminal_provider_event( - TerminalProviderEvent::Created { - terminal_id, - label: tc.title.clone(), - cwd, - output_byte_limit: None, - terminal: lower, - }, - cx, - ); - anyhow::Ok(()) - }); - } + let update_clone = notification.update.clone(); + let thread = session.thread.clone(); + + // Pre-handle: if a ToolCall carries terminal_info, create/register a display-only terminal. + if let acp::SessionUpdate::ToolCall(tc) = &update_clone { + if let Some(meta) = &tc.meta { + if let Some(terminal_info) = meta.get("terminal_info") { + if let Some(id_str) = terminal_info.get("terminal_id").and_then(|v| v.as_str()) { + let terminal_id = acp::TerminalId::new(id_str); + let cwd = terminal_info + .get("cwd") + .and_then(|v| v.as_str().map(PathBuf::from)); + + let _ = thread.update(cx, |thread, cx| { + let builder = TerminalBuilder::new_display_only( + CursorShape::default(), + AlternateScroll::On, + None, + 0, + cx.background_executor(), + thread.project().read(cx).path_style(cx), + )?; + let lower = cx.new(|cx| builder.subscribe(cx)); + thread.on_terminal_provider_event( + TerminalProviderEvent::Created { + terminal_id, + label: tc.title.clone(), + cwd, + output_byte_limit: None, + terminal: lower, + }, + cx, + ); + anyhow::Ok(()) + }); } } } + } - // Forward the update to the acp_thread as usual. - session.thread.update(&mut self.cx.clone(), |thread, cx| { - thread.handle_session_update(notification.update.clone(), cx) - })??; - - // Post-handle: stream terminal output/exit if present on ToolCallUpdate meta. - if let acp::SessionUpdate::ToolCallUpdate(tcu) = &update_clone { - if let Some(meta) = &tcu.meta { - if let Some(term_out) = meta.get("terminal_output") { - if let Some(id_str) = term_out.get("terminal_id").and_then(|v| v.as_str()) { - let terminal_id = acp::TerminalId::new(id_str); - if let Some(s) = term_out.get("data").and_then(|v| v.as_str()) { - let data = s.as_bytes().to_vec(); - let _ = session.thread.update(&mut self.cx.clone(), |thread, cx| { - thread.on_terminal_provider_event( - TerminalProviderEvent::Output { terminal_id, data }, - cx, - ); - }); - } - } - } + // Drop sessions borrow before updating the thread, which may re-borrow. + drop(sessions); - // terminal_exit - if let Some(term_exit) = meta.get("terminal_exit") { - if let Some(id_str) = term_exit.get("terminal_id").and_then(|v| v.as_str()) { - let terminal_id = acp::TerminalId::new(id_str); - let status = acp::TerminalExitStatus::new() - .exit_code( - term_exit - .get("exit_code") - .and_then(|v| v.as_u64()) - .map(|i| i as u32), - ) - .signal( - term_exit - .get("signal") - .and_then(|v| v.as_str().map(|s| s.to_string())), - ); + // Forward the update to the acp_thread as usual. + if let Err(err) = thread + .update(cx, |thread, cx| { + thread.handle_session_update(notification.update.clone(), cx) + }) + .and_then(|inner| inner.map_err(anyhow::Error::from)) + { + log::error!( + "Failed to handle session update for {:?}: {err:?}", + notification.session_id + ); + } - let _ = session.thread.update(&mut self.cx.clone(), |thread, cx| { + // Post-handle: stream terminal output/exit if present on ToolCallUpdate meta. + if let acp::SessionUpdate::ToolCallUpdate(tcu) = &update_clone { + if let Some(meta) = &tcu.meta { + if let Some(term_out) = meta.get("terminal_output") { + if let Some(id_str) = term_out.get("terminal_id").and_then(|v| v.as_str()) { + let terminal_id = acp::TerminalId::new(id_str); + if let Some(s) = term_out.get("data").and_then(|v| v.as_str()) { + let data = s.as_bytes().to_vec(); + let _ = thread.update(cx, |thread, cx| { thread.on_terminal_provider_event( - TerminalProviderEvent::Exit { - terminal_id, - status, - }, + TerminalProviderEvent::Output { terminal_id, data }, cx, ); }); } } } - } - Ok(()) - } + if let Some(term_exit) = meta.get("terminal_exit") { + if let Some(id_str) = term_exit.get("terminal_id").and_then(|v| v.as_str()) { + let terminal_id = acp::TerminalId::new(id_str); + let status = acp::TerminalExitStatus::new() + .exit_code( + term_exit + .get("exit_code") + .and_then(|v| v.as_u64()) + .map(|i| i as u32), + ) + .signal( + term_exit + .get("signal") + .and_then(|v| v.as_str().map(|s| s.to_string())), + ); - async fn create_terminal( - &self, - args: acp::CreateTerminalRequest, - ) -> Result { - let thread = self.session_thread(&args.session_id)?; - let project = thread.read_with(&self.cx, |thread, _cx| thread.project().clone())?; - - let terminal_entity = acp_thread::create_terminal_entity( - args.command.clone(), - &args.args, - args.env - .into_iter() - .map(|env| (env.name, env.value)) - .collect(), - args.cwd.clone(), - &project, - &mut self.cx.clone(), - ) - .await?; + let _ = thread.update(cx, |thread, cx| { + thread.on_terminal_provider_event( + TerminalProviderEvent::Exit { + terminal_id, + status, + }, + cx, + ); + }); + } + } + } + } +} - // Register with renderer - let terminal_entity = thread.update(&mut self.cx.clone(), |thread, cx| { - thread.register_terminal_created( - acp::TerminalId::new(uuid::Uuid::new_v4().to_string()), - format!("{} {}", args.command, args.args.join(" ")), +fn handle_create_terminal( + args: acp::CreateTerminalRequest, + responder: agent_client_protocol_core::Responder, + cx: &mut AsyncApp, + ctx: &ClientContext, +) { + let thread = match session_thread(ctx, &args.session_id) { + Ok(t) => t, + Err(e) => return respond_err(responder, e), + }; + let project = match thread + .read_with(cx, |thread, _cx| thread.project().clone()) + .map_err(acp::Error::from) + { + Ok(p) => p, + Err(e) => return respond_err(responder, e), + }; + + cx.spawn(async move |cx| { + let result: Result<_, acp::Error> = async { + let terminal_entity = acp_thread::create_terminal_entity( + args.command.clone(), + &args.args, + args.env + .into_iter() + .map(|env| (env.name, env.value)) + .collect(), args.cwd.clone(), - args.output_byte_limit, - terminal_entity, + &project, cx, ) - })?; - let terminal_id = terminal_entity.read_with(&self.cx, |terminal, _| terminal.id().clone()); - Ok(acp::CreateTerminalResponse::new(terminal_id)) - } - - async fn kill_terminal( - &self, - args: acp::KillTerminalRequest, - ) -> Result { - self.session_thread(&args.session_id)? - .update(&mut self.cx.clone(), |thread, cx| { - thread.kill_terminal(args.terminal_id, cx) - })??; - - Ok(Default::default()) - } - - async fn ext_method(&self, _args: acp::ExtRequest) -> Result { - Err(acp::Error::method_not_found()) - } + .await + .map_err(acp::Error::from)?; + + let terminal_entity = thread + .update(cx, |thread, cx| { + thread.register_terminal_created( + acp::TerminalId::new(uuid::Uuid::new_v4().to_string()), + format!("{} {}", args.command, args.args.join(" ")), + args.cwd.clone(), + args.output_byte_limit, + terminal_entity, + cx, + ) + }) + .map_err(acp::Error::from)?; + let terminal_id = terminal_entity.read_with(cx, |terminal, _| terminal.id().clone()); + Ok(terminal_id) + } + .await; - async fn ext_notification(&self, _args: acp::ExtNotification) -> Result<(), acp::Error> { - Err(acp::Error::method_not_found()) - } + match result { + Ok(terminal_id) => { + responder + .respond(acp::CreateTerminalResponse::new(terminal_id)) + .log_err(); + } + Err(e) => respond_err(responder, e), + } + }) + .detach(); +} - async fn release_terminal( - &self, - args: acp::ReleaseTerminalRequest, - ) -> Result { - self.session_thread(&args.session_id)? - .update(&mut self.cx.clone(), |thread, cx| { - thread.release_terminal(args.terminal_id, cx) - })??; - - Ok(Default::default()) +fn handle_kill_terminal( + args: acp::KillTerminalRequest, + responder: agent_client_protocol_core::Responder, + cx: &mut AsyncApp, + ctx: &ClientContext, +) { + let thread = match session_thread(ctx, &args.session_id) { + Ok(t) => t, + Err(e) => return respond_err(responder, e), + }; + + match thread + .update(cx, |thread, cx| thread.kill_terminal(args.terminal_id, cx)) + .map_err(acp::Error::from) + .and_then(|r| r.map_err(acp::Error::from)) + { + Ok(()) => { + responder + .respond(acp::KillTerminalResponse::default()) + .log_err(); + } + Err(e) => respond_err(responder, e), } +} - async fn terminal_output( - &self, - args: acp::TerminalOutputRequest, - ) -> Result { - self.session_thread(&args.session_id)? - .read_with(&mut self.cx.clone(), |thread, cx| { - let out = thread - .terminal(args.terminal_id)? - .read(cx) - .current_output(cx); - - Ok(out) - })? +fn handle_release_terminal( + args: acp::ReleaseTerminalRequest, + responder: agent_client_protocol_core::Responder, + cx: &mut AsyncApp, + ctx: &ClientContext, +) { + let thread = match session_thread(ctx, &args.session_id) { + Ok(t) => t, + Err(e) => return respond_err(responder, e), + }; + + match thread + .update(cx, |thread, cx| { + thread.release_terminal(args.terminal_id, cx) + }) + .map_err(acp::Error::from) + .and_then(|r| r.map_err(acp::Error::from)) + { + Ok(()) => { + responder + .respond(acp::ReleaseTerminalResponse::default()) + .log_err(); + } + Err(e) => respond_err(responder, e), } +} - async fn wait_for_terminal_exit( - &self, - args: acp::WaitForTerminalExitRequest, - ) -> Result { - let exit_status = self - .session_thread(&args.session_id)? - .update(&mut self.cx.clone(), |thread, cx| { - anyhow::Ok(thread.terminal(args.terminal_id)?.read(cx).wait_for_exit()) - })?? - .await; - - Ok(acp::WaitForTerminalExitResponse::new(exit_status)) +fn handle_terminal_output( + args: acp::TerminalOutputRequest, + responder: agent_client_protocol_core::Responder, + cx: &mut AsyncApp, + ctx: &ClientContext, +) { + let thread = match session_thread(ctx, &args.session_id) { + Ok(t) => t, + Err(e) => return respond_err(responder, e), + }; + + match thread + .read_with(cx, |thread, cx| -> Result<_, anyhow::Error> { + let out = thread + .terminal(args.terminal_id)? + .read(cx) + .current_output(cx); + Ok(out) + }) + .map_err(acp::Error::from) + .and_then(|r| r.map_err(acp::Error::from)) + { + Ok(output) => { + responder.respond(output).log_err(); + } + Err(e) => respond_err(responder, e), } } -impl ClientDelegate { - fn session_thread(&self, session_id: &acp::SessionId) -> Result> { - let sessions = self.sessions.borrow(); - sessions - .get(session_id) - .context("Failed to get session") - .map(|session| session.thread.clone()) - } +fn handle_wait_for_terminal_exit( + args: acp::WaitForTerminalExitRequest, + responder: agent_client_protocol_core::Responder, + cx: &mut AsyncApp, + ctx: &ClientContext, +) { + let thread = match session_thread(ctx, &args.session_id) { + Ok(t) => t, + Err(e) => return respond_err(responder, e), + }; + + cx.spawn(async move |cx| { + let result: Result<_, acp::Error> = async { + let exit_status = thread + .update(cx, |thread, cx| { + anyhow::Ok(thread.terminal(args.terminal_id)?.read(cx).wait_for_exit()) + }) + .map_err(acp::Error::from)? + .map_err(acp::Error::from)? + .await; + Ok(exit_status) + } + .await; + + match result { + Ok(exit_status) => { + responder + .respond(acp::WaitForTerminalExitResponse::new(exit_status)) + .log_err(); + } + Err(e) => respond_err(responder, e), + } + }) + .detach(); } diff --git a/crates/agent_servers/src/agent_servers.rs b/crates/agent_servers/src/agent_servers.rs index 2016e5aaaa27b6..8ebc1c652d993f 100644 --- a/crates/agent_servers/src/agent_servers.rs +++ b/crates/agent_servers/src/agent_servers.rs @@ -48,31 +48,34 @@ pub trait AgentServer: Send { fn into_any(self: Rc) -> Rc; - fn default_mode(&self, _cx: &App) -> Option { + fn default_mode(&self, _cx: &App) -> Option { None } fn set_default_mode( &self, - _mode_id: Option, + _mode_id: Option, _fs: Arc, _cx: &mut App, ) { } - fn default_model(&self, _cx: &App) -> Option { + fn default_model(&self, _cx: &App) -> Option { None } fn set_default_model( &self, - _model_id: Option, + _model_id: Option, _fs: Arc, _cx: &mut App, ) { } - fn favorite_model_ids(&self, _cx: &mut App) -> HashSet { + fn favorite_model_ids( + &self, + _cx: &mut App, + ) -> HashSet { HashSet::default() } @@ -91,16 +94,16 @@ pub trait AgentServer: Send { fn favorite_config_option_value_ids( &self, - _config_id: &agent_client_protocol::SessionConfigId, + _config_id: &agent_client_protocol_core::schema::SessionConfigId, _cx: &mut App, - ) -> HashSet { + ) -> HashSet { HashSet::default() } fn toggle_favorite_config_option_value( &self, - _config_id: agent_client_protocol::SessionConfigId, - _value_id: agent_client_protocol::SessionConfigValueId, + _config_id: agent_client_protocol_core::schema::SessionConfigId, + _value_id: agent_client_protocol_core::schema::SessionConfigValueId, _should_be_favorite: bool, _fs: Arc, _cx: &App, @@ -109,7 +112,7 @@ pub trait AgentServer: Send { fn toggle_favorite_model( &self, - _model_id: agent_client_protocol::ModelId, + _model_id: agent_client_protocol_core::schema::ModelId, _should_be_favorite: bool, _fs: Arc, _cx: &App, diff --git a/crates/agent_servers/src/custom.rs b/crates/agent_servers/src/custom.rs index 0dcd2240d6ecf6..91f39b25b8cb7a 100644 --- a/crates/agent_servers/src/custom.rs +++ b/crates/agent_servers/src/custom.rs @@ -1,6 +1,6 @@ use crate::{AgentServer, AgentServerDelegate, load_proxy_env}; use acp_thread::AgentConnection; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use anyhow::{Context as _, Result}; use collections::HashSet; use credentials_provider::CredentialsProvider; diff --git a/crates/agent_servers/src/e2e_tests.rs b/crates/agent_servers/src/e2e_tests.rs index 956d106df2a260..3f3c77f740eb4c 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, ToolCall, ToolCallStatus}; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use futures::{FutureExt, StreamExt, channel::mpsc, select}; use gpui::AppContext; use gpui::{Entity, TestAppContext}; @@ -378,7 +378,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::PermissionOptionId::new($allow_option_id), + ::agent_client_protocol_core::schema::PermissionOptionId::new($allow_option_id), cx, ) .await; diff --git a/crates/agent_settings/Cargo.toml b/crates/agent_settings/Cargo.toml index b2db5677dcfdc0..942e54c37b97b4 100644 --- a/crates/agent_settings/Cargo.toml +++ b/crates/agent_settings/Cargo.toml @@ -12,7 +12,7 @@ workspace = true path = "src/agent_settings.rs" [dependencies] -agent-client-protocol.workspace = true +agent-client-protocol-core.workspace = true anyhow.workspace = true collections.workspace = true convert_case.workspace = true diff --git a/crates/agent_settings/src/agent_settings.rs b/crates/agent_settings/src/agent_settings.rs index f0730d39eee17c..9b2a8673bb5454 100644 --- a/crates/agent_settings/src/agent_settings.rs +++ b/crates/agent_settings/src/agent_settings.rs @@ -3,7 +3,7 @@ mod agent_profile; use std::path::{Component, Path}; use std::sync::{Arc, LazyLock}; -use agent_client_protocol::ModelId; +use agent_client_protocol_core::schema::ModelId; use collections::{HashSet, IndexMap}; use fs::Fs; use gpui::{App, Pixels, px}; diff --git a/crates/agent_ui/Cargo.toml b/crates/agent_ui/Cargo.toml index e505a124b68989..ce03c3ddc67add 100644 --- a/crates/agent_ui/Cargo.toml +++ b/crates/agent_ui/Cargo.toml @@ -28,7 +28,7 @@ unit-eval = [] [dependencies] acp_thread.workspace = true action_log.workspace = true -agent-client-protocol.workspace = true +agent-client-protocol-core.workspace = true agent.workspace = true agent_servers.workspace = true agent_settings.workspace = true diff --git a/crates/agent_ui/src/agent_panel.rs b/crates/agent_ui/src/agent_panel.rs index 118f0dce6cb53c..dd1594430c7ce5 100644 --- a/crates/agent_ui/src/agent_panel.rs +++ b/crates/agent_ui/src/agent_panel.rs @@ -10,7 +10,7 @@ use std::{ use acp_thread::{AcpThread, MentionUri, ThreadStatus}; use agent::{ContextServerRegistry, SharedThread, ThreadStore}; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use agent_servers::AgentServer; use collections::HashSet; use db::kvp::{Dismissable, KeyValueStore}; diff --git a/crates/agent_ui/src/agent_ui.rs b/crates/agent_ui/src/agent_ui.rs index 185a54825d3af1..45620b4c26a17a 100644 --- a/crates/agent_ui/src/agent_ui.rs +++ b/crates/agent_ui/src/agent_ui.rs @@ -39,7 +39,7 @@ use std::rc::Rc; use std::sync::Arc; use ::ui::IconName; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use agent_settings::{AgentProfileId, AgentSettings}; use command_palette_hooks::CommandPaletteFilter; use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt as _}; @@ -232,7 +232,7 @@ pub struct NewExternalAgentThread { #[action(namespace = agent)] #[serde(deny_unknown_fields)] pub struct NewNativeAgentThreadFromSummary { - from_session_id: agent_client_protocol::SessionId, + from_session_id: agent_client_protocol_core::schema::SessionId, } #[derive(Debug, Default, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)] @@ -317,7 +317,7 @@ pub enum AgentInitialContent { title: Option, }, ContentBlock { - blocks: Vec, + blocks: Vec, auto_submit: bool, }, FromExternalSource(ExternalSourcePrompt), diff --git a/crates/agent_ui/src/completion_provider.rs b/crates/agent_ui/src/completion_provider.rs index a72b352375ef9b..7ee3b60f95c1c0 100644 --- a/crates/agent_ui/src/completion_provider.rs +++ b/crates/agent_ui/src/completion_provider.rs @@ -7,7 +7,7 @@ use std::sync::atomic::AtomicBool; use crate::DEFAULT_THREAD_TITLE; use crate::ThreadHistory; use acp_thread::MentionUri; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use anyhow::Result; use editor::{CompletionProvider, Editor, code_context_menus::COMPLETION_MENU_MAX_WIDTH}; use futures::FutureExt as _; diff --git a/crates/agent_ui/src/config_options.rs b/crates/agent_ui/src/config_options.rs index 44c0baa232222c..a1d1158e8e1c23 100644 --- a/crates/agent_ui/src/config_options.rs +++ b/crates/agent_ui/src/config_options.rs @@ -1,7 +1,7 @@ use std::{cmp::Reverse, rc::Rc, sync::Arc}; use acp_thread::AgentSessionConfigOptions; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use agent_servers::AgentServer; use agent_settings::AgentSettings; use collections::HashSet; diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs index 83a0c158a11c54..c3a17a06c958a8 100644 --- a/crates/agent_ui/src/conversation_view.rs +++ b/crates/agent_ui/src/conversation_view.rs @@ -7,7 +7,7 @@ use acp_thread::{ use acp_thread::{AgentConnection, Plan}; use action_log::{ActionLog, ActionLogTelemetry, DiffStats}; use agent::{NativeAgentServer, NativeAgentSessionList, SharedThread, ThreadStore}; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; #[cfg(test)] use agent_servers::AgentServerDelegate; use agent_servers::{AgentServer, GEMINI_TERMINAL_AUTH_METHOD_ID}; @@ -2750,7 +2750,7 @@ pub(crate) mod tests { }; use action_log::ActionLog; use agent::{AgentTool, EditFileTool, FetchTool, TerminalTool, ToolPermissionContext}; - use agent_client_protocol::SessionId; + use agent_client_protocol_core::schema::SessionId; use editor::MultiBufferOffset; use fs::FakeFs; use gpui::{EventEmitter, TestAppContext, VisualTestContext}; diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs index c065c3de3d83c0..4926a7337431c7 100644 --- a/crates/agent_ui/src/conversation_view/thread_view.rs +++ b/crates/agent_ui/src/conversation_view/thread_view.rs @@ -249,12 +249,13 @@ pub struct ThreadView { pub session_capabilities: SharedSessionCapabilities, /// Tracks which tool calls have their content/output expanded. /// Used for showing/hiding tool call results, terminal output, etc. - pub expanded_tool_calls: HashSet, - pub expanded_tool_call_raw_inputs: HashSet, + pub expanded_tool_calls: HashSet, + pub expanded_tool_call_raw_inputs: HashSet, pub expanded_thinking_blocks: HashSet<(usize, usize)>, auto_expanded_thinking_block: Option<(usize, usize)>, user_toggled_thinking_blocks: HashSet<(usize, usize)>, - pub subagent_scroll_handles: RefCell>, + pub subagent_scroll_handles: + RefCell>, pub edits_expanded: bool, pub plan_expanded: bool, pub queue_expanded: bool, @@ -266,12 +267,12 @@ pub struct ThreadView { pub queued_message_editor_subscriptions: Vec, pub last_synced_queue_length: usize, pub turn_fields: TurnFields, - pub discarded_partial_edits: HashSet, + pub discarded_partial_edits: HashSet, pub is_loading_contents: bool, pub new_server_version_available: Option, pub resumed_without_history: bool, pub(crate) permission_selections: - HashMap, + HashMap, pub resume_thread_metadata: Option, pub _cancel_task: Option>, _save_task: Option>, diff --git a/crates/agent_ui/src/entry_view_state.rs b/crates/agent_ui/src/entry_view_state.rs index eeaf8f6935a229..4cd34ceb38af52 100644 --- a/crates/agent_ui/src/entry_view_state.rs +++ b/crates/agent_ui/src/entry_view_state.rs @@ -3,7 +3,7 @@ use std::ops::Range; use super::thread_history::ThreadHistory; use acp_thread::{AcpThread, AgentThreadEntry}; use agent::ThreadStore; -use agent_client_protocol::ToolCallId; +use agent_client_protocol_core::schema::ToolCallId; use collections::HashMap; use editor::{Editor, EditorEvent, EditorMode, MinimapVisibility, SizingBehavior}; use gpui::{ @@ -465,7 +465,7 @@ mod tests { use std::sync::Arc; use acp_thread::{AgentConnection, StubAgentConnection}; - use agent_client_protocol as acp; + use agent_client_protocol_core::schema as acp; use buffer_diff::{DiffHunkStatus, DiffHunkStatusKind}; use editor::RowInfo; use fs::FakeFs; diff --git a/crates/agent_ui/src/mention_set.rs b/crates/agent_ui/src/mention_set.rs index 4db856f9dd1e51..2e150527e01a84 100644 --- a/crates/agent_ui/src/mention_set.rs +++ b/crates/agent_ui/src/mention_set.rs @@ -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 as acp; +use agent_client_protocol_core::schema as acp; use agent_servers::{AgentServer, AgentServerDelegate}; use anyhow::{Context as _, Result, anyhow}; use collections::{HashMap, HashSet}; diff --git a/crates/agent_ui/src/message_editor.rs b/crates/agent_ui/src/message_editor.rs index 8660e792cd23bc..a925553a2ef0c9 100644 --- a/crates/agent_ui/src/message_editor.rs +++ b/crates/agent_ui/src/message_editor.rs @@ -11,7 +11,7 @@ use crate::{ }; use acp_thread::MentionUri; use agent::ThreadStore; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use anyhow::{Result, anyhow}; use editor::{ Addon, AnchorRangeExt, ContextMenuOptions, Editor, EditorElement, EditorEvent, EditorMode, @@ -1905,7 +1905,7 @@ mod tests { use acp_thread::MentionUri; use agent::{ThreadStore, outline}; - use agent_client_protocol as acp; + use agent_client_protocol_core::schema as acp; use base64::Engine as _; use editor::{ AnchorRangeExt as _, Editor, EditorMode, MultiBufferOffset, SelectionEffects, diff --git a/crates/agent_ui/src/mode_selector.rs b/crates/agent_ui/src/mode_selector.rs index 60c9b878709238..c619940387b9fc 100644 --- a/crates/agent_ui/src/mode_selector.rs +++ b/crates/agent_ui/src/mode_selector.rs @@ -1,5 +1,5 @@ use acp_thread::AgentSessionModes; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use agent_servers::AgentServer; use agent_settings::AgentSettings; use fs::Fs; diff --git a/crates/agent_ui/src/model_selector.rs b/crates/agent_ui/src/model_selector.rs index 89ed3e490b33ca..805c1b7188d1c8 100644 --- a/crates/agent_ui/src/model_selector.rs +++ b/crates/agent_ui/src/model_selector.rs @@ -1,7 +1,7 @@ use std::{cmp::Reverse, rc::Rc, sync::Arc}; use acp_thread::{AgentModelIcon, AgentModelInfo, AgentModelList, AgentModelSelector}; -use agent_client_protocol::ModelId; +use agent_client_protocol_core::schema::ModelId; use agent_servers::AgentServer; use agent_settings::AgentSettings; use anyhow::Result; @@ -533,7 +533,7 @@ async fn fuzzy_search( #[cfg(test)] mod tests { - use agent_client_protocol as acp; + use agent_client_protocol_core::schema as acp; use gpui::TestAppContext; use super::*; diff --git a/crates/agent_ui/src/test_support.rs b/crates/agent_ui/src/test_support.rs index 94502485b1f3a2..2ffac1635836b2 100644 --- a/crates/agent_ui/src/test_support.rs +++ b/crates/agent_ui/src/test_support.rs @@ -1,5 +1,5 @@ use acp_thread::{AgentConnection, StubAgentConnection}; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use agent_servers::{AgentServer, AgentServerDelegate}; use gpui::{Entity, Task, TestAppContext, VisualTestContext}; use project::AgentId; diff --git a/crates/agent_ui/src/thread_history.rs b/crates/agent_ui/src/thread_history.rs index 7b7a3e60211896..29e8cdd94c7da3 100644 --- a/crates/agent_ui/src/thread_history.rs +++ b/crates/agent_ui/src/thread_history.rs @@ -1,5 +1,5 @@ use acp_thread::{AgentSessionInfo, AgentSessionList, AgentSessionListRequest, SessionListUpdate}; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use gpui::{App, Task}; use std::rc::Rc; use ui::prelude::*; diff --git a/crates/agent_ui/src/thread_import.rs b/crates/agent_ui/src/thread_import.rs index 5402b1c74353b7..4e5c4f7131ac41 100644 --- a/crates/agent_ui/src/thread_import.rs +++ b/crates/agent_ui/src/thread_import.rs @@ -1,6 +1,6 @@ use acp_thread::AgentSessionListRequest; use agent::ThreadStore; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use chrono::Utc; use collections::HashSet; use db::kvp::Dismissable; diff --git a/crates/agent_ui/src/thread_metadata_store.rs b/crates/agent_ui/src/thread_metadata_store.rs index fcd9665c52451d..9696e09d7d969e 100644 --- a/crates/agent_ui/src/thread_metadata_store.rs +++ b/crates/agent_ui/src/thread_metadata_store.rs @@ -2,7 +2,7 @@ use std::{path::Path, sync::Arc}; use acp_thread::AcpThreadEvent; use agent::{ThreadStore, ZED_AGENT_ID}; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use anyhow::Context as _; use chrono::{DateTime, Utc}; use collections::{HashMap, HashSet}; @@ -791,7 +791,7 @@ mod tests { use acp_thread::{AgentConnection, StubAgentConnection}; use action_log::ActionLog; use agent::DbThread; - use agent_client_protocol as acp; + use agent_client_protocol_core::schema as acp; use feature_flags::FeatureFlagAppExt; use gpui::TestAppContext; use project::FakeFs; diff --git a/crates/agent_ui/src/threads_archive_view.rs b/crates/agent_ui/src/threads_archive_view.rs index 9aca31e1edbe72..cd43d6627ce401 100644 --- a/crates/agent_ui/src/threads_archive_view.rs +++ b/crates/agent_ui/src/threads_archive_view.rs @@ -7,7 +7,7 @@ use crate::thread_metadata_store::{ThreadMetadata, ThreadMetadataStore}; use crate::{Agent, RemoveSelectedThread}; use agent::ThreadStore; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use agent_settings::AgentSettings; use chrono::{DateTime, Datelike as _, Local, NaiveDate, TimeDelta, Utc}; use editor::Editor; diff --git a/crates/agent_ui/src/ui/mention_crease.rs b/crates/agent_ui/src/ui/mention_crease.rs index 6e99647304d93f..3b58b04f2d46f1 100644 --- a/crates/agent_ui/src/ui/mention_crease.rs +++ b/crates/agent_ui/src/ui/mention_crease.rs @@ -1,7 +1,7 @@ use std::{ops::RangeInclusive, path::PathBuf, time::Duration}; use acp_thread::MentionUri; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use editor::{Editor, SelectionEffects, scroll::Autoscroll}; use gpui::{ Animation, AnimationExt, AnyView, Context, IntoElement, WeakEntity, Window, pulsating_between, diff --git a/crates/eval_cli/Cargo.toml b/crates/eval_cli/Cargo.toml index cac5dc6aa28fa9..b68ebfdd0ffb8c 100644 --- a/crates/eval_cli/Cargo.toml +++ b/crates/eval_cli/Cargo.toml @@ -15,7 +15,7 @@ path = "src/main.rs" [dependencies] acp_thread.workspace = true agent.workspace = true -agent-client-protocol.workspace = true +agent-client-protocol-core.workspace = true agent_ui.workspace = true anyhow.workspace = true clap.workspace = true diff --git a/crates/eval_cli/src/main.rs b/crates/eval_cli/src/main.rs index f9ab1835f94327..1c2d4b7e863578 100644 --- a/crates/eval_cli/src/main.rs +++ b/crates/eval_cli/src/main.rs @@ -40,7 +40,7 @@ use std::time::{Duration, Instant}; use acp_thread::AgentConnection as _; use agent::{NativeAgent, NativeAgentConnection, Templates, ThreadStore}; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use anyhow::{Context, Result}; use clap::Parser; use feature_flags::FeatureFlagAppExt as _; diff --git a/crates/sidebar/Cargo.toml b/crates/sidebar/Cargo.toml index 04ed8808a14d4c..c40ee1cf802e45 100644 --- a/crates/sidebar/Cargo.toml +++ b/crates/sidebar/Cargo.toml @@ -18,7 +18,7 @@ default = [] acp_thread.workspace = true action_log.workspace = true agent.workspace = true -agent-client-protocol.workspace = true +agent-client-protocol-core.workspace = true agent_settings.workspace = true agent_ui = { workspace = true, features = ["audio"] } anyhow.workspace = true diff --git a/crates/sidebar/src/sidebar.rs b/crates/sidebar/src/sidebar.rs index a9664a04812325..78e305df4c55a4 100644 --- a/crates/sidebar/src/sidebar.rs +++ b/crates/sidebar/src/sidebar.rs @@ -2,7 +2,7 @@ mod thread_switcher; use acp_thread::ThreadStatus; use action_log::DiffStats; -use agent_client_protocol::{self as acp}; +use agent_client_protocol_core::schema as acp; use agent_settings::AgentSettings; use agent_ui::thread_metadata_store::{ThreadMetadata, ThreadMetadataStore}; use agent_ui::threads_archive_view::{ diff --git a/crates/sidebar/src/thread_switcher.rs b/crates/sidebar/src/thread_switcher.rs index 86e2aeba38b9ee..2794d3417a10cb 100644 --- a/crates/sidebar/src/thread_switcher.rs +++ b/crates/sidebar/src/thread_switcher.rs @@ -1,5 +1,5 @@ use action_log::DiffStats; -use agent_client_protocol as acp; +use agent_client_protocol_core::schema as acp; use agent_ui::thread_metadata_store::ThreadMetadata; use gpui::{ Action as _, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, Modifiers, diff --git a/crates/zed/Cargo.toml b/crates/zed/Cargo.toml index 9feaa59c976220..49d7698b8d0bb3 100644 --- a/crates/zed/Cargo.toml +++ b/crates/zed/Cargo.toml @@ -66,7 +66,7 @@ required-features = ["visual-tests"] acp_tools.workspace = true activity_indicator.workspace = true agent.workspace = true -agent-client-protocol.workspace = true +agent-client-protocol-core.workspace = true agent_settings.workspace = true agent_ui = { workspace = true, features = ["audio"] } anyhow.workspace = true diff --git a/crates/zed/src/main.rs b/crates/zed/src/main.rs index 303f21b8ffa62f..5f809ade7fb564 100644 --- a/crates/zed/src/main.rs +++ b/crates/zed/src/main.rs @@ -5,7 +5,6 @@ mod reliability; mod zed; use agent::{SharedThread, ThreadStore}; -use agent_client_protocol; use agent_ui::AgentPanel; use anyhow::{Context as _, Error, Result}; use clap::Parser; @@ -978,7 +977,7 @@ fn handle_open_request(request: OpenRequest, app_state: Arc, cx: &mut let shared_thread = SharedThread::from_bytes(&response.thread_data)?; let db_thread = shared_thread.to_db_thread(); - let session_id = agent_client_protocol::SessionId::new(session_id); + let session_id = agent_client_protocol_core::schema::SessionId::new(session_id); let save_session_id = session_id.clone(); diff --git a/crates/zed/src/visual_test_runner.rs b/crates/zed/src/visual_test_runner.rs index 7e081c15a564cb..6d89da27c3945f 100644 --- a/crates/zed/src/visual_test_runner.rs +++ b/crates/zed/src/visual_test_runner.rs @@ -95,7 +95,7 @@ fn main() { #[cfg(target_os = "macos")] use { acp_thread::{AgentConnection, StubAgentConnection}, - agent_client_protocol as acp, + agent_client_protocol_core::schema as acp, agent_servers::{AgentServer, AgentServerDelegate}, anyhow::{Context as _, Result}, assets::Assets, From 07070d98b1a45e3984a6cc07628990809e4f2663 Mon Sep 17 00:00:00 2001 From: Ben Brandt Date: Thu, 2 Apr 2026 14:30:27 +0200 Subject: [PATCH 02/20] Fix acp logs --- Cargo.lock | 1 + crates/acp_tools/Cargo.toml | 1 + crates/acp_tools/src/acp_tools.rs | 89 +++++++++++++++++++++++-------- crates/agent_servers/src/acp.rs | 57 ++++++++++++++++---- 4 files changed, 117 insertions(+), 31 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 849129850d7df2..2bc256c9adbe5f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -59,6 +59,7 @@ dependencies = [ "serde", "serde_json", "settings", + "smol", "theme_settings", "ui", "util", diff --git a/crates/acp_tools/Cargo.toml b/crates/acp_tools/Cargo.toml index 43963b4034411c..9124e0aa5503dd 100644 --- a/crates/acp_tools/Cargo.toml +++ b/crates/acp_tools/Cargo.toml @@ -22,6 +22,7 @@ markdown.workspace = true project.workspace = true serde.workspace = true serde_json.workspace = true +smol.workspace = true settings.workspace = true theme_settings.workspace = true ui.workspace = true diff --git a/crates/acp_tools/src/acp_tools.rs b/crates/acp_tools/src/acp_tools.rs index dfeaab42e14e80..debc04d41b0447 100644 --- a/crates/acp_tools/src/acp_tools.rs +++ b/crates/acp_tools/src/acp_tools.rs @@ -17,21 +17,16 @@ use workspace::{ Item, ItemHandle, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView, Workspace, }; -// Stub types for the old streaming API which is not available in agent-client-protocol-core. -// These allow the ACP debug panel code to compile but the streaming won't be active. -#[allow(dead_code)] -type RequestId = String; +pub type RequestId = String; #[derive(Clone)] -#[allow(dead_code)] -enum StreamMessageDirection { +pub enum StreamMessageDirection { Incoming, Outgoing, } #[derive(Clone)] -#[allow(dead_code)] -enum StreamMessageContent { +pub enum StreamMessageContent { Request { id: RequestId, method: Arc, @@ -47,10 +42,49 @@ enum StreamMessageContent { }, } -#[allow(dead_code)] -struct StreamMessage { - direction: StreamMessageDirection, - message: StreamMessageContent, +pub struct StreamMessage { + pub direction: StreamMessageDirection, + pub message: StreamMessageContent, +} + +impl StreamMessage { + pub fn from_json_line(direction: StreamMessageDirection, line: &str) -> Option { + let value: serde_json::Value = serde_json::from_str(line).ok()?; + let obj = value.as_object()?; + + let message = if let Some(method) = obj.get("method").and_then(|m| m.as_str()) { + if let Some(id) = obj.get("id") { + StreamMessageContent::Request { + id: id.to_string(), + method: method.into(), + params: obj.get("params").cloned(), + } + } else { + StreamMessageContent::Notification { + method: method.into(), + params: obj.get("params").cloned(), + } + } + } else if let Some(id) = obj.get("id") { + if let Some(error) = obj.get("error") { + let acp_err = serde_json::from_value::(error.clone()) + .unwrap_or_else(|_| acp::Error::internal_error()); + StreamMessageContent::Response { + id: id.to_string(), + result: Err(acp_err), + } + } else { + StreamMessageContent::Response { + id: id.to_string(), + result: Ok(obj.get("result").cloned()), + } + } + } else { + return None; + }; + + Some(StreamMessage { direction, message }) + } } actions!(dev, [OpenAcpLogs]); @@ -79,6 +113,7 @@ pub struct AcpConnectionRegistry { struct ActiveConnection { agent_id: AgentId, + messages_rx: smol::channel::Receiver, } impl AcpConnectionRegistry { @@ -92,9 +127,16 @@ impl AcpConnectionRegistry { } } - pub fn set_active_connection(&self, agent_id: AgentId, cx: &mut Context) { - self.active_connection - .replace(Some(ActiveConnection { agent_id })); + pub fn set_active_connection( + &self, + agent_id: AgentId, + messages_rx: smol::channel::Receiver, + cx: &mut Context, + ) { + self.active_connection.replace(Some(ActiveConnection { + agent_id, + messages_rx, + })); cx.notify(); } } @@ -112,9 +154,7 @@ struct WatchedConnection { agent_id: AgentId, messages: Vec, list_state: ListState, - #[allow(dead_code)] incoming_request_methods: HashMap>, - #[allow(dead_code)] outgoing_request_methods: HashMap>, _task: Task<()>, } @@ -152,17 +192,26 @@ impl AcpTools { } } + let messages_rx = active_connection.messages_rx.clone(); + let task = cx.spawn(async move |this, cx| { + while let Ok(message) = messages_rx.recv().await { + this.update(cx, |this, cx| { + this.push_stream_message(message, cx); + }) + .ok(); + } + }); + self.watched_connection = Some(WatchedConnection { agent_id: active_connection.agent_id.clone(), messages: vec![], list_state: ListState::new(0, ListAlignment::Bottom, px(2048.)), incoming_request_methods: HashMap::default(), outgoing_request_methods: HashMap::default(), - _task: Task::ready(()), + _task: task, }); } - #[allow(dead_code)] fn push_stream_message(&mut self, stream_message: StreamMessage, cx: &mut Context) { let Some(connection) = self.watched_connection.as_mut() else { return; @@ -427,7 +476,6 @@ impl WatchedConnectionMessage { } } -#[allow(dead_code)] fn collapsed_params_md( params: &serde_json::Value, language_registry: &Arc, @@ -460,7 +508,6 @@ fn expanded_params_md( cx.new(|cx| Markdown::new(params_md.into(), Some(language_registry.clone()), None, cx)) } -#[allow(dead_code)] enum MessageType { Request, Response, diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs index 2ef69c0fb0f3ab..80a037a7e89146 100644 --- a/crates/agent_servers/src/acp.rs +++ b/crates/agent_servers/src/acp.rs @@ -2,9 +2,10 @@ use acp_thread::{ AgentConnection, AgentSessionInfo, AgentSessionList, AgentSessionListRequest, AgentSessionListResponse, }; +use acp_tools::{AcpConnectionRegistry, StreamMessage, StreamMessageDirection}; use action_log::ActionLog; use agent_client_protocol_core::schema::{self as acp, ErrorCode}; -use agent_client_protocol_core::{ByteStreams, ConnectionTo}; +use agent_client_protocol_core::{ConnectionTo, Lines}; use anyhow::anyhow; use collections::HashMap; use feature_flags::{AcpBetaFeatureFlag, FeatureFlagAppExt as _}; @@ -259,8 +260,46 @@ impl AcpConnection { // closures to the !Send foreground thread. let (dispatch_tx, dispatch_rx) = mpsc::unbounded::(); - // Build the transport from child stdio - let transport = ByteStreams::new(stdin, stdout); + // Build a tapped transport that intercepts raw JSON-RPC lines for + // the ACP logs panel. We replicate the ByteStreams→Lines conversion + // manually so we can wrap the stream and sink with inspection. + let (stream_tap_tx, stream_tap_rx) = smol::channel::unbounded::(); + + let incoming_lines = futures::io::BufReader::new(stdout).lines(); + let tapped_incoming = incoming_lines.inspect({ + let tap_tx = stream_tap_tx.clone(); + move |result| { + if let Ok(line) = result { + if let Some(msg) = + StreamMessage::from_json_line(StreamMessageDirection::Incoming, line) + { + tap_tx.try_send(msg).ok(); + } + } + } + }); + + let outgoing_sink = + futures::sink::unfold(Box::pin(stdin), async move |mut writer, line: String| { + use futures::AsyncWriteExt; + let mut bytes = line.into_bytes(); + bytes.push(b'\n'); + writer.write_all(&bytes).await?; + Ok::<_, std::io::Error>(writer) + }); + let tapped_outgoing = futures::SinkExt::with(outgoing_sink, { + let tap_tx = stream_tap_tx; + move |line: String| { + if let Some(msg) = + StreamMessage::from_json_line(StreamMessageDirection::Outgoing, &line) + { + tap_tx.try_send(msg).ok(); + } + futures::future::ok::(line) + } + }); + + let transport = Lines::new(tapped_outgoing, tapped_incoming); // Use a oneshot channel to extract the ConnectionTo from the // connect_with closure. @@ -505,13 +544,11 @@ impl AcpConnection { } }); - // TODO: Update AcpConnectionRegistry to support ConnectionTo - // The old streaming/subscribe API is not available in agent-client-protocol-core. - // cx.update(|cx| { - // AcpConnectionRegistry::default_global(cx).update(cx, |registry, cx| { - // registry.set_active_connection(agent_id.clone(), &connection, cx) - // }); - // }); + cx.update(|cx| { + AcpConnectionRegistry::default_global(cx).update(cx, |registry, cx| { + registry.set_active_connection(agent_id.clone(), stream_tap_rx, cx) + }); + }); let response = connection .send_request( From 6fcad1d1332c4fae039ebb4782fa0c13bd6b965d Mon Sep 17 00:00:00 2001 From: Ben Brandt Date: Thu, 2 Apr 2026 14:51:35 +0200 Subject: [PATCH 03/20] cleanup --- Cargo.lock | 2 + Cargo.toml | 2 +- crates/acp_tools/src/acp_tools.rs | 58 ++-- crates/agent_servers/src/acp.rs | 307 ++++++++-------------- crates/agent_servers/src/agent_servers.rs | 38 +-- 5 files changed, 163 insertions(+), 244 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2bc256c9adbe5f..4f52f444867c7a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -220,6 +220,7 @@ dependencies = [ [[package]] name = "agent-client-protocol-core" version = "0.1.0" +source = "git+https://github.com/agentclientprotocol/rust-sdk?rev=9fa32bb04e301f4be968a372eb5085dc3a86ef3c#9fa32bb04e301f4be968a372eb5085dc3a86ef3c" dependencies = [ "agent-client-protocol-derive", "agent-client-protocol-schema", @@ -243,6 +244,7 @@ dependencies = [ [[package]] name = "agent-client-protocol-derive" version = "0.1.0" +source = "git+https://github.com/agentclientprotocol/rust-sdk?rev=9fa32bb04e301f4be968a372eb5085dc3a86ef3c#9fa32bb04e301f4be968a372eb5085dc3a86ef3c" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index 1c5b124981f998..2474178be5f7a9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -477,7 +477,7 @@ ztracing_macro = { path = "crates/ztracing_macro" } # External crates # -agent-client-protocol-core = { path = "../acp-rust-sdk/src/agent-client-protocol-core", features = ["unstable"] } +agent-client-protocol-core = { git = "https://github.com/agentclientprotocol/rust-sdk", rev = "9fa32bb04e301f4be968a372eb5085dc3a86ef3c", features = ["unstable"] } aho-corasick = "1.1" alacritty_terminal = { git = "https://github.com/zed-industries/alacritty", rev = "9d9640d4" } any_vec = "0.14" diff --git a/crates/acp_tools/src/acp_tools.rs b/crates/acp_tools/src/acp_tools.rs index debc04d41b0447..201750709e9524 100644 --- a/crates/acp_tools/src/acp_tools.rs +++ b/crates/acp_tools/src/acp_tools.rs @@ -1,4 +1,4 @@ -use std::{cell::RefCell, collections::HashSet, fmt::Display, sync::Arc}; +use std::{collections::HashSet, fmt::Display, sync::Arc}; use agent_client_protocol_core::schema as acp; use collections::HashMap; @@ -42,6 +42,7 @@ pub enum StreamMessageContent { }, } +#[derive(Clone)] pub struct StreamMessage { pub direction: StreamMessageDirection, pub message: StreamMessageContent, @@ -108,12 +109,10 @@ impl Global for GlobalAcpConnectionRegistry {} #[derive(Default)] pub struct AcpConnectionRegistry { - active_connection: RefCell>, -} - -struct ActiveConnection { - agent_id: AgentId, - messages_rx: smol::channel::Receiver, + active_agent_id: Option, + generation: u64, + subscribers: Vec>, + _broadcast_task: Option>, } impl AcpConnectionRegistry { @@ -128,17 +127,33 @@ impl AcpConnectionRegistry { } pub fn set_active_connection( - &self, + &mut self, agent_id: AgentId, messages_rx: smol::channel::Receiver, cx: &mut Context, ) { - self.active_connection.replace(Some(ActiveConnection { - agent_id, - messages_rx, + self.active_agent_id = Some(agent_id); + self.generation += 1; + self.subscribers.clear(); + + self._broadcast_task = Some(cx.spawn(async move |this, cx| { + while let Ok(message) = messages_rx.recv().await { + this.update(cx, |this, _cx| { + this.subscribers + .retain(|sender| sender.try_send(message.clone()).is_ok()); + }) + .ok(); + } })); + cx.notify(); } + + pub fn subscribe(&mut self) -> smol::channel::Receiver { + let (sender, receiver) = smol::channel::bounded(4096); + self.subscribers.push(sender); + receiver + } } struct AcpTools { @@ -152,6 +167,7 @@ struct AcpTools { struct WatchedConnection { agent_id: AgentId, + generation: u64, messages: Vec, list_state: ListState, incoming_request_methods: HashMap>, @@ -181,18 +197,25 @@ impl AcpTools { } fn update_connection(&mut self, cx: &mut Context) { - let active_connection = self.connection_registry.read(cx).active_connection.borrow(); - let Some(active_connection) = active_connection.as_ref() else { + let (generation, agent_id) = { + let registry = self.connection_registry.read(cx); + (registry.generation, registry.active_agent_id.clone()) + }; + + let Some(agent_id) = agent_id else { return; }; - if let Some(watched_connection) = self.watched_connection.as_ref() { - if watched_connection.agent_id == active_connection.agent_id { + if let Some(watched) = self.watched_connection.as_ref() { + if watched.generation == generation { return; } } - let messages_rx = active_connection.messages_rx.clone(); + let messages_rx = self + .connection_registry + .update(cx, |registry, _cx| registry.subscribe()); + let task = cx.spawn(async move |this, cx| { while let Ok(message) = messages_rx.recv().await { this.update(cx, |this, cx| { @@ -203,7 +226,8 @@ impl AcpTools { }); self.watched_connection = Some(WatchedConnection { - agent_id: active_connection.agent_id.clone(), + agent_id, + generation, messages: vec![], list_state: ListState::new(0, ListAlignment::Bottom, px(2048.)), incoming_request_methods: HashMap::default(), diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs index 80a037a7e89146..5e8b7aa59e189c 100644 --- a/crates/agent_servers/src/acp.rs +++ b/crates/agent_servers/src/acp.rs @@ -203,6 +203,34 @@ pub async fn connect( const MINIMUM_SUPPORTED_VERSION: acp::ProtocolVersion = acp::ProtocolVersion::V1; +macro_rules! dispatch_request_handler { + ($dispatch_tx:expr, $handler:expr) => {{ + let dispatch_tx = $dispatch_tx.clone(); + async move |args, responder, _connection| { + dispatch_tx + .unbounded_send(Box::new(move |cx, ctx| { + $handler(args, responder, cx, ctx); + })) + .log_err(); + Ok(()) + } + }}; +} + +macro_rules! dispatch_notification_handler { + ($dispatch_tx:expr, $handler:expr) => {{ + let dispatch_tx = $dispatch_tx.clone(); + async move |notification, _connection| { + dispatch_tx + .unbounded_send(Box::new(move |cx, ctx| { + $handler(notification, cx, ctx); + })) + .log_err(); + Ok(()) + } + }}; +} + impl AcpConnection { pub async fn stdio( agent_id: AgentId, @@ -263,7 +291,7 @@ impl AcpConnection { // Build a tapped transport that intercepts raw JSON-RPC lines for // the ACP logs panel. We replicate the ByteStreams→Lines conversion // manually so we can wrap the stream and sink with inspection. - let (stream_tap_tx, stream_tap_rx) = smol::channel::unbounded::(); + let (stream_tap_tx, stream_tap_rx) = smol::channel::bounded::(4096); let incoming_lines = futures::io::BufReader::new(stdout).lines(); let tapped_incoming = incoming_lines.inspect({ @@ -314,167 +342,40 @@ impl AcpConnection { .name("zed") // --- Request handlers (agent→client) --- .on_receive_request( - { - let dispatch_tx = dispatch_tx.clone(); - async move |args: acp::RequestPermissionRequest, - responder: agent_client_protocol_core::Responder< - acp::RequestPermissionResponse, - >, - _connection: ConnectionTo< - agent_client_protocol_core::Agent, - >| { - dispatch_tx - .unbounded_send(Box::new(move |cx, ctx| { - handle_request_permission(args, responder, cx, ctx); - })) - .ok(); - Ok(()) - } - }, + dispatch_request_handler!(dispatch_tx, handle_request_permission), agent_client_protocol_core::on_receive_request!(), ) .on_receive_request( - { - let dispatch_tx = dispatch_tx.clone(); - async move |args: acp::WriteTextFileRequest, - responder: agent_client_protocol_core::Responder< - acp::WriteTextFileResponse, - >, - _connection| { - dispatch_tx - .unbounded_send(Box::new(move |cx, ctx| { - handle_write_text_file(args, responder, cx, ctx); - })) - .ok(); - Ok(()) - } - }, + dispatch_request_handler!(dispatch_tx, handle_write_text_file), agent_client_protocol_core::on_receive_request!(), ) .on_receive_request( - { - let dispatch_tx = dispatch_tx.clone(); - async move |args: acp::ReadTextFileRequest, - responder: agent_client_protocol_core::Responder< - acp::ReadTextFileResponse, - >, - _connection| { - dispatch_tx - .unbounded_send(Box::new(move |cx, ctx| { - handle_read_text_file(args, responder, cx, ctx); - })) - .ok(); - Ok(()) - } - }, + dispatch_request_handler!(dispatch_tx, handle_read_text_file), agent_client_protocol_core::on_receive_request!(), ) .on_receive_request( - { - let dispatch_tx = dispatch_tx.clone(); - async move |args: acp::CreateTerminalRequest, - responder: agent_client_protocol_core::Responder< - acp::CreateTerminalResponse, - >, - _connection| { - dispatch_tx - .unbounded_send(Box::new(move |cx, ctx| { - handle_create_terminal(args, responder, cx, ctx); - })) - .ok(); - Ok(()) - } - }, + dispatch_request_handler!(dispatch_tx, handle_create_terminal), agent_client_protocol_core::on_receive_request!(), ) .on_receive_request( - { - let dispatch_tx = dispatch_tx.clone(); - async move |args: acp::KillTerminalRequest, - responder: agent_client_protocol_core::Responder< - acp::KillTerminalResponse, - >, - _connection| { - dispatch_tx - .unbounded_send(Box::new(move |cx, ctx| { - handle_kill_terminal(args, responder, cx, ctx); - })) - .ok(); - Ok(()) - } - }, + dispatch_request_handler!(dispatch_tx, handle_kill_terminal), agent_client_protocol_core::on_receive_request!(), ) .on_receive_request( - { - let dispatch_tx = dispatch_tx.clone(); - async move |args: acp::ReleaseTerminalRequest, - responder: agent_client_protocol_core::Responder< - acp::ReleaseTerminalResponse, - >, - _connection| { - dispatch_tx - .unbounded_send(Box::new(move |cx, ctx| { - handle_release_terminal(args, responder, cx, ctx); - })) - .ok(); - Ok(()) - } - }, + dispatch_request_handler!(dispatch_tx, handle_release_terminal), agent_client_protocol_core::on_receive_request!(), ) .on_receive_request( - { - let dispatch_tx = dispatch_tx.clone(); - async move |args: acp::TerminalOutputRequest, - responder: agent_client_protocol_core::Responder< - acp::TerminalOutputResponse, - >, - _connection| { - dispatch_tx - .unbounded_send(Box::new(move |cx, ctx| { - handle_terminal_output(args, responder, cx, ctx); - })) - .ok(); - Ok(()) - } - }, + dispatch_request_handler!(dispatch_tx, handle_terminal_output), agent_client_protocol_core::on_receive_request!(), ) .on_receive_request( - { - let dispatch_tx = dispatch_tx.clone(); - async move |args: acp::WaitForTerminalExitRequest, - responder: agent_client_protocol_core::Responder< - acp::WaitForTerminalExitResponse, - >, - _connection| { - dispatch_tx - .unbounded_send(Box::new(move |cx, ctx| { - handle_wait_for_terminal_exit(args, responder, cx, ctx); - })) - .ok(); - Ok(()) - } - }, + dispatch_request_handler!(dispatch_tx, handle_wait_for_terminal_exit), agent_client_protocol_core::on_receive_request!(), ) // --- Notification handlers (agent→client) --- .on_receive_notification( - { - let dispatch_tx = dispatch_tx.clone(); - async move |notification: acp::SessionNotification, - _connection: ConnectionTo< - agent_client_protocol_core::Agent, - >| { - dispatch_tx - .unbounded_send(Box::new(move |cx, ctx| { - handle_session_notification(notification, cx, ctx); - })) - .ok(); - Ok(()) - } - }, + dispatch_notification_handler!(dispatch_tx, handle_session_notification), agent_client_protocol_core::on_receive_notification!(), ) .connect_with( @@ -1857,82 +1758,86 @@ fn handle_session_notification( cx: &mut AsyncApp, ctx: &ClientContext, ) { - let sessions = ctx.sessions.borrow(); - let Some(session) = sessions.get(¬ification.session_id) else { - log::warn!( - "Received session notification for unknown session: {:?}", - notification.session_id - ); - return; - }; + let (thread, update_clone) = { + let sessions = ctx.sessions.borrow(); + let Some(session) = sessions.get(¬ification.session_id) else { + log::warn!( + "Received session notification for unknown session: {:?}", + notification.session_id + ); + return; + }; - if let acp::SessionUpdate::CurrentModeUpdate(acp::CurrentModeUpdate { - current_mode_id, .. - }) = ¬ification.update - { - if let Some(session_modes) = &session.session_modes { - session_modes.borrow_mut().current_mode_id = current_mode_id.clone(); + if let acp::SessionUpdate::CurrentModeUpdate(acp::CurrentModeUpdate { + current_mode_id, + .. + }) = ¬ification.update + { + if let Some(session_modes) = &session.session_modes { + session_modes.borrow_mut().current_mode_id = current_mode_id.clone(); + } } - } - if let acp::SessionUpdate::ConfigOptionUpdate(acp::ConfigOptionUpdate { - config_options, .. - }) = ¬ification.update - { - if let Some(opts) = &session.config_options { - *opts.config_options.borrow_mut() = config_options.clone(); - opts.tx.borrow_mut().send(()).ok(); + if let acp::SessionUpdate::ConfigOptionUpdate(acp::ConfigOptionUpdate { + config_options, + .. + }) = ¬ification.update + { + if let Some(opts) = &session.config_options { + *opts.config_options.borrow_mut() = config_options.clone(); + opts.tx.borrow_mut().send(()).ok(); + } } - } - if let acp::SessionUpdate::SessionInfoUpdate(info_update) = ¬ification.update - && let Some(session_list) = ctx.session_list.borrow().as_ref() - { - session_list.send_info_update(notification.session_id.clone(), info_update.clone()); - } + if let acp::SessionUpdate::SessionInfoUpdate(info_update) = ¬ification.update + && let Some(session_list) = ctx.session_list.borrow().as_ref() + { + session_list.send_info_update(notification.session_id.clone(), info_update.clone()); + } - let update_clone = notification.update.clone(); - let thread = session.thread.clone(); + let update_clone = notification.update.clone(); + let thread = session.thread.clone(); - // Pre-handle: if a ToolCall carries terminal_info, create/register a display-only terminal. - if let acp::SessionUpdate::ToolCall(tc) = &update_clone { - if let Some(meta) = &tc.meta { - if let Some(terminal_info) = meta.get("terminal_info") { - if let Some(id_str) = terminal_info.get("terminal_id").and_then(|v| v.as_str()) { - let terminal_id = acp::TerminalId::new(id_str); - let cwd = terminal_info - .get("cwd") - .and_then(|v| v.as_str().map(PathBuf::from)); + // Pre-handle: if a ToolCall carries terminal_info, create/register a display-only terminal. + if let acp::SessionUpdate::ToolCall(tc) = &update_clone { + if let Some(meta) = &tc.meta { + if let Some(terminal_info) = meta.get("terminal_info") { + if let Some(id_str) = terminal_info.get("terminal_id").and_then(|v| v.as_str()) + { + let terminal_id = acp::TerminalId::new(id_str); + let cwd = terminal_info + .get("cwd") + .and_then(|v| v.as_str().map(PathBuf::from)); - let _ = thread.update(cx, |thread, cx| { - let builder = TerminalBuilder::new_display_only( - CursorShape::default(), - AlternateScroll::On, - None, - 0, - cx.background_executor(), - thread.project().read(cx).path_style(cx), - )?; - let lower = cx.new(|cx| builder.subscribe(cx)); - thread.on_terminal_provider_event( - TerminalProviderEvent::Created { - terminal_id, - label: tc.title.clone(), - cwd, - output_byte_limit: None, - terminal: lower, - }, - cx, - ); - anyhow::Ok(()) - }); + let _ = thread.update(cx, |thread, cx| { + let builder = TerminalBuilder::new_display_only( + CursorShape::default(), + AlternateScroll::On, + None, + 0, + cx.background_executor(), + thread.project().read(cx).path_style(cx), + )?; + let lower = cx.new(|cx| builder.subscribe(cx)); + thread.on_terminal_provider_event( + TerminalProviderEvent::Created { + terminal_id, + label: tc.title.clone(), + cwd, + output_byte_limit: None, + terminal: lower, + }, + cx, + ); + anyhow::Ok(()) + }); + } } } } - } - // Drop sessions borrow before updating the thread, which may re-borrow. - drop(sessions); + (thread, update_clone) + }; // Forward the update to the acp_thread as usual. if let Err(err) = thread diff --git a/crates/agent_servers/src/agent_servers.rs b/crates/agent_servers/src/agent_servers.rs index 8ebc1c652d993f..9bba14dea302b3 100644 --- a/crates/agent_servers/src/agent_servers.rs +++ b/crates/agent_servers/src/agent_servers.rs @@ -12,6 +12,9 @@ use http_client::read_no_proxy_from_env; use project::{AgentId, Project, agent_server_store::AgentServerStore}; use acp_thread::AgentConnection; +use agent_client_protocol_core::schema::{ + ModelId, SessionConfigId, SessionConfigValueId, SessionModeId, +}; use anyhow::Result; use gpui::{App, AppContext, Entity, Task}; use settings::SettingsStore; @@ -48,34 +51,19 @@ pub trait AgentServer: Send { fn into_any(self: Rc) -> Rc; - fn default_mode(&self, _cx: &App) -> Option { + fn default_mode(&self, _cx: &App) -> Option { None } - fn set_default_mode( - &self, - _mode_id: Option, - _fs: Arc, - _cx: &mut App, - ) { - } + fn set_default_mode(&self, _mode_id: Option, _fs: Arc, _cx: &mut App) {} - fn default_model(&self, _cx: &App) -> Option { + fn default_model(&self, _cx: &App) -> Option { None } - fn set_default_model( - &self, - _model_id: Option, - _fs: Arc, - _cx: &mut App, - ) { - } + fn set_default_model(&self, _model_id: Option, _fs: Arc, _cx: &mut App) {} - fn favorite_model_ids( - &self, - _cx: &mut App, - ) -> HashSet { + fn favorite_model_ids(&self, _cx: &mut App) -> HashSet { HashSet::default() } @@ -94,16 +82,16 @@ pub trait AgentServer: Send { fn favorite_config_option_value_ids( &self, - _config_id: &agent_client_protocol_core::schema::SessionConfigId, + _config_id: &SessionConfigId, _cx: &mut App, - ) -> HashSet { + ) -> HashSet { HashSet::default() } fn toggle_favorite_config_option_value( &self, - _config_id: agent_client_protocol_core::schema::SessionConfigId, - _value_id: agent_client_protocol_core::schema::SessionConfigValueId, + _config_id: SessionConfigId, + _value_id: SessionConfigValueId, _should_be_favorite: bool, _fs: Arc, _cx: &App, @@ -112,7 +100,7 @@ pub trait AgentServer: Send { fn toggle_favorite_model( &self, - _model_id: agent_client_protocol_core::schema::ModelId, + _model_id: ModelId, _should_be_favorite: bool, _fs: Arc, _cx: &App, From 2fa45f5e74b5a10e7ecb80841db1761cafe43e21 Mon Sep 17 00:00:00 2001 From: Ben Brandt Date: Thu, 2 Apr 2026 15:02:36 +0200 Subject: [PATCH 04/20] clean up imports --- Cargo.toml | 2 +- crates/acp_thread/Cargo.toml | 2 +- crates/acp_thread/src/acp_thread.rs | 2 +- crates/acp_thread/src/connection.rs | 2 +- crates/acp_thread/src/mention.rs | 2 +- crates/acp_thread/src/terminal.rs | 2 +- crates/acp_tools/Cargo.toml | 2 +- crates/acp_tools/src/acp_tools.rs | 2 +- crates/agent/Cargo.toml | 2 +- crates/agent/src/agent.rs | 2 +- crates/agent/src/db.rs | 2 +- crates/agent/src/native_agent_server.rs | 2 +- crates/agent/src/tests/mod.rs | 2 +- crates/agent/src/thread.rs | 4 +- crates/agent/src/thread_store.rs | 2 +- .../src/tools/context_server_registry.rs | 6 +- crates/agent/src/tools/copy_path_tool.rs | 7 +-- .../agent/src/tools/create_directory_tool.rs | 7 +-- crates/agent/src/tools/delete_path_tool.rs | 7 +-- crates/agent/src/tools/diagnostics_tool.rs | 2 +- crates/agent/src/tools/edit_file_tool.rs | 2 +- crates/agent/src/tools/fetch_tool.rs | 2 +- crates/agent/src/tools/find_path_tool.rs | 2 +- crates/agent/src/tools/grep_tool.rs | 2 +- crates/agent/src/tools/list_directory_tool.rs | 7 +-- crates/agent/src/tools/move_path_tool.rs | 7 +-- crates/agent/src/tools/now_tool.rs | 2 +- crates/agent/src/tools/open_tool.rs | 6 +- crates/agent/src/tools/read_file_tool.rs | 4 +- .../src/tools/restore_file_from_disk_tool.rs | 2 +- crates/agent/src/tools/save_file_tool.rs | 2 +- crates/agent/src/tools/spawn_agent_tool.rs | 2 +- .../src/tools/streaming_edit_file_tool.rs | 2 +- crates/agent/src/tools/terminal_tool.rs | 2 +- crates/agent/src/tools/update_plan_tool.rs | 2 +- crates/agent/src/tools/web_search_tool.rs | 2 +- crates/agent_servers/Cargo.toml | 2 +- crates/agent_servers/src/acp.rs | 63 +++++++++---------- crates/agent_servers/src/agent_servers.rs | 2 +- crates/agent_servers/src/custom.rs | 2 +- crates/agent_servers/src/e2e_tests.rs | 4 +- crates/agent_settings/Cargo.toml | 2 +- crates/agent_settings/src/agent_settings.rs | 6 +- crates/agent_ui/Cargo.toml | 2 +- crates/agent_ui/src/agent_panel.rs | 2 +- crates/agent_ui/src/agent_ui.rs | 6 +- crates/agent_ui/src/completion_provider.rs | 2 +- crates/agent_ui/src/config_options.rs | 2 +- crates/agent_ui/src/conversation_view.rs | 4 +- .../src/conversation_view/thread_view.rs | 13 ++-- crates/agent_ui/src/entry_view_state.rs | 10 +-- crates/agent_ui/src/mention_set.rs | 2 +- crates/agent_ui/src/message_editor.rs | 4 +- crates/agent_ui/src/mode_selector.rs | 2 +- crates/agent_ui/src/model_selector.rs | 13 ++-- crates/agent_ui/src/test_support.rs | 2 +- crates/agent_ui/src/thread_history.rs | 2 +- crates/agent_ui/src/thread_import.rs | 2 +- crates/agent_ui/src/thread_metadata_store.rs | 4 +- crates/agent_ui/src/threads_archive_view.rs | 2 +- crates/agent_ui/src/ui/mention_crease.rs | 2 +- crates/eval_cli/Cargo.toml | 2 +- crates/eval_cli/src/main.rs | 2 +- crates/sidebar/Cargo.toml | 2 +- crates/sidebar/src/sidebar.rs | 2 +- crates/sidebar/src/thread_switcher.rs | 2 +- crates/zed/Cargo.toml | 2 +- crates/zed/src/main.rs | 3 +- crates/zed/src/visual_test_runner.rs | 2 +- 69 files changed, 137 insertions(+), 146 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 2474178be5f7a9..efbbd9f7f3f631 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -477,7 +477,7 @@ ztracing_macro = { path = "crates/ztracing_macro" } # External crates # -agent-client-protocol-core = { git = "https://github.com/agentclientprotocol/rust-sdk", rev = "9fa32bb04e301f4be968a372eb5085dc3a86ef3c", features = ["unstable"] } +agent-client-protocol = { package = "agent-client-protocol-core", git = "https://github.com/agentclientprotocol/rust-sdk", rev = "9fa32bb04e301f4be968a372eb5085dc3a86ef3c", features = ["unstable"] } aho-corasick = "1.1" alacritty_terminal = { git = "https://github.com/zed-industries/alacritty", rev = "9d9640d4" } any_vec = "0.14" diff --git a/crates/acp_thread/Cargo.toml b/crates/acp_thread/Cargo.toml index 9b1e0a9b64855c..7ef53bc5227086 100644 --- a/crates/acp_thread/Cargo.toml +++ b/crates/acp_thread/Cargo.toml @@ -17,7 +17,7 @@ test-support = ["gpui/test-support", "project/test-support", "dep:parking_lot", [dependencies] action_log.workspace = true -agent-client-protocol-core.workspace = true +agent-client-protocol.workspace = true base64.workspace = true anyhow.workspace = true buffer_diff.workspace = true diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs index 5746ca14bb9623..0d84196598bf7a 100644 --- a/crates/acp_thread/src/acp_thread.rs +++ b/crates/acp_thread/src/acp_thread.rs @@ -3,7 +3,7 @@ mod diff; mod mention; mod terminal; use action_log::{ActionLog, ActionLogTelemetry}; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use anyhow::{Context as _, Result, anyhow}; use collections::HashSet; pub use connection::*; diff --git a/crates/acp_thread/src/connection.rs b/crates/acp_thread/src/connection.rs index 0835a05d6cb07e..c365a36c203f08 100644 --- a/crates/acp_thread/src/connection.rs +++ b/crates/acp_thread/src/connection.rs @@ -1,5 +1,5 @@ use crate::AcpThread; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use anyhow::Result; use chrono::{DateTime, Utc}; use collections::{HashMap, IndexMap}; diff --git a/crates/acp_thread/src/mention.rs b/crates/acp_thread/src/mention.rs index b4928eb5edc102..b1eb42996af29c 100644 --- a/crates/acp_thread/src/mention.rs +++ b/crates/acp_thread/src/mention.rs @@ -1,4 +1,4 @@ -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use anyhow::{Context as _, Result, bail}; use file_icons::FileIcons; use prompt_store::{PromptId, UserPromptId}; diff --git a/crates/acp_thread/src/terminal.rs b/crates/acp_thread/src/terminal.rs index 08fcf32e0d3da8..2fe769cb737b71 100644 --- a/crates/acp_thread/src/terminal.rs +++ b/crates/acp_thread/src/terminal.rs @@ -1,4 +1,4 @@ -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use anyhow::Result; use futures::{FutureExt as _, future::Shared}; use gpui::{App, AppContext, AsyncApp, Context, Entity, Task}; diff --git a/crates/acp_tools/Cargo.toml b/crates/acp_tools/Cargo.toml index 9124e0aa5503dd..15d928b664fd26 100644 --- a/crates/acp_tools/Cargo.toml +++ b/crates/acp_tools/Cargo.toml @@ -14,7 +14,7 @@ path = "src/acp_tools.rs" doctest = false [dependencies] -agent-client-protocol-core.workspace = true +agent-client-protocol.workspace = true collections.workspace = true gpui.workspace = true language.workspace= true diff --git a/crates/acp_tools/src/acp_tools.rs b/crates/acp_tools/src/acp_tools.rs index 201750709e9524..d17b8346aa1733 100644 --- a/crates/acp_tools/src/acp_tools.rs +++ b/crates/acp_tools/src/acp_tools.rs @@ -1,6 +1,6 @@ use std::{collections::HashSet, fmt::Display, sync::Arc}; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use collections::HashMap; use gpui::{ App, Empty, Entity, EventEmitter, FocusHandle, Focusable, Global, ListAlignment, ListState, diff --git a/crates/agent/Cargo.toml b/crates/agent/Cargo.toml index 84e72c089628c3..a5a4c2742a444b 100644 --- a/crates/agent/Cargo.toml +++ b/crates/agent/Cargo.toml @@ -19,7 +19,7 @@ workspace = true [dependencies] acp_thread.workspace = true action_log.workspace = true -agent-client-protocol-core.workspace = true +agent-client-protocol.workspace = true agent_servers.workspace = true agent_settings.workspace = true anyhow.workspace = true diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rs index 5d87f88e8ab4bd..3b88504e016327 100644 --- a/crates/agent/src/agent.rs +++ b/crates/agent/src/agent.rs @@ -28,7 +28,7 @@ use acp_thread::{ AcpThread, AgentModelSelector, AgentSessionInfo, AgentSessionList, AgentSessionListRequest, AgentSessionListResponse, TokenUsageRatio, UserMessageId, }; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use anyhow::{Context as _, Result, anyhow}; use chrono::{DateTime, Utc}; use collections::{HashMap, HashSet, IndexMap}; diff --git a/crates/agent/src/db.rs b/crates/agent/src/db.rs index e8b0383addf09f..0ed03ed51703b0 100644 --- a/crates/agent/src/db.rs +++ b/crates/agent/src/db.rs @@ -1,6 +1,6 @@ use crate::{AgentMessage, AgentMessageContent, UserMessage, UserMessageContent}; use acp_thread::UserMessageId; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use agent_settings::AgentProfileId; use anyhow::{Result, anyhow}; use chrono::{DateTime, Utc}; diff --git a/crates/agent/src/native_agent_server.rs b/crates/agent/src/native_agent_server.rs index a9b89fc518ddaa..c1c995b06babae 100644 --- a/crates/agent/src/native_agent_server.rs +++ b/crates/agent/src/native_agent_server.rs @@ -1,6 +1,6 @@ use std::{any::Any, rc::Rc, sync::Arc}; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use agent_servers::{AgentServer, AgentServerDelegate}; use agent_settings::AgentSettings; use anyhow::Result; diff --git a/crates/agent/src/tests/mod.rs b/crates/agent/src/tests/mod.rs index 54f3d5a5b0ae55..49d2d050611e29 100644 --- a/crates/agent/src/tests/mod.rs +++ b/crates/agent/src/tests/mod.rs @@ -3,7 +3,7 @@ use acp_thread::{ AgentConnection, AgentModelGroupName, AgentModelList, PermissionOptions, ThreadStatus, UserMessageId, }; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use agent_settings::AgentProfileId; use anyhow::Result; use client::{Client, UserStore}; diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rs index 1d11372accc090..479dcfc01b6991 100644 --- a/crates/agent/src/thread.rs +++ b/crates/agent/src/thread.rs @@ -12,7 +12,7 @@ use feature_flags::{ FeatureFlagAppExt as _, StreamingEditFileToolFeatureFlag, UpdatePlanToolFeatureFlag, }; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use agent_settings::{ AgentProfileId, AgentSettings, SUMMARIZE_THREAD_DETAILED_PROMPT, SUMMARIZE_THREAD_PROMPT, }; @@ -3341,7 +3341,7 @@ where T::description() } - fn kind(&self) -> agent_client_protocol_core::schema::ToolKind { + fn kind(&self) -> acp::ToolKind { T::kind() } diff --git a/crates/agent/src/thread_store.rs b/crates/agent/src/thread_store.rs index a4aac074c48ca1..f1367457d327d6 100644 --- a/crates/agent/src/thread_store.rs +++ b/crates/agent/src/thread_store.rs @@ -1,5 +1,5 @@ use crate::{DbThread, DbThreadMetadata, ThreadsDatabase}; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use anyhow::{Result, anyhow}; use gpui::{App, Context, Entity, Global, Task, prelude::*}; use util::path_list::PathList; diff --git a/crates/agent/src/tools/context_server_registry.rs b/crates/agent/src/tools/context_server_registry.rs index b4d65189c0a6c2..65b5df8abfe1c0 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_core::schema::ToolKind; +use agent_client_protocol::schema as acp; use anyhow::Result; use collections::{BTreeMap, HashMap}; use context_server::{ContextServerId, client::NotificationSubscription}; @@ -304,8 +304,8 @@ impl AnyAgentTool for ContextServerTool { self.tool.description.clone().unwrap_or_default().into() } - fn kind(&self) -> ToolKind { - ToolKind::Other + fn kind(&self) -> acp::ToolKind { + acp::ToolKind::Other } fn initial_title(&self, _input: serde_json::Value, _cx: &mut App) -> SharedString { diff --git a/crates/agent/src/tools/copy_path_tool.rs b/crates/agent/src/tools/copy_path_tool.rs index 5e9d72b43fcd1c..32d48d2e1435b6 100644 --- a/crates/agent/src/tools/copy_path_tool.rs +++ b/crates/agent/src/tools/copy_path_tool.rs @@ -5,7 +5,7 @@ use super::tool_permissions::{ use crate::{ AgentTool, ToolCallEventStream, ToolInput, ToolPermissionDecision, decide_permission_for_paths, }; -use agent_client_protocol_core::schema::ToolKind; +use agent_client_protocol::schema as acp; use agent_settings::AgentSettings; use futures::FutureExt as _; use gpui::{App, Entity, Task}; @@ -61,8 +61,8 @@ impl AgentTool for CopyPathTool { const NAME: &'static str = "copy_path"; - fn kind() -> ToolKind { - ToolKind::Move + fn kind() -> acp::ToolKind { + acp::ToolKind::Move } fn initial_title( @@ -198,7 +198,6 @@ impl AgentTool for CopyPathTool { #[cfg(test)] mod tests { use super::*; - use agent_client_protocol_core::schema as acp; use fs::Fs as _; use gpui::TestAppContext; use project::{FakeFs, Project}; diff --git a/crates/agent/src/tools/create_directory_tool.rs b/crates/agent/src/tools/create_directory_tool.rs index eb918dabeb4bcb..631870b4236af2 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::{ SensitiveSettingsKind, authorize_symlink_access, canonicalize_worktree_roots, detect_symlink_escape, sensitive_settings_kind, }; -use agent_client_protocol_core::schema::ToolKind; +use agent_client_protocol::schema as acp; use agent_settings::AgentSettings; use futures::FutureExt as _; use gpui::{App, Entity, SharedString, Task}; @@ -52,8 +52,8 @@ impl AgentTool for CreateDirectoryTool { const NAME: &'static str = "create_directory"; - fn kind() -> ToolKind { - ToolKind::Read + fn kind() -> acp::ToolKind { + acp::ToolKind::Read } fn initial_title( @@ -169,7 +169,6 @@ impl AgentTool for CreateDirectoryTool { #[cfg(test)] mod tests { use super::*; - use agent_client_protocol_core::schema as acp; use fs::Fs as _; use gpui::TestAppContext; use project::{FakeFs, Project}; diff --git a/crates/agent/src/tools/delete_path_tool.rs b/crates/agent/src/tools/delete_path_tool.rs index 59a2c67cce7164..3051ffc29eba8e 100644 --- a/crates/agent/src/tools/delete_path_tool.rs +++ b/crates/agent/src/tools/delete_path_tool.rs @@ -6,7 +6,7 @@ use crate::{ AgentTool, ToolCallEventStream, ToolInput, ToolPermissionDecision, decide_permission_for_path, }; use action_log::ActionLog; -use agent_client_protocol_core::schema::ToolKind; +use agent_client_protocol::schema as acp; use agent_settings::AgentSettings; use futures::{FutureExt as _, SinkExt, StreamExt, channel::mpsc}; use gpui::{App, AppContext, Entity, SharedString, Task}; @@ -55,8 +55,8 @@ impl AgentTool for DeletePathTool { const NAME: &'static str = "delete_path"; - fn kind() -> ToolKind { - ToolKind::Delete + fn kind() -> acp::ToolKind { + acp::ToolKind::Delete } fn initial_title( @@ -228,7 +228,6 @@ impl AgentTool for DeletePathTool { #[cfg(test)] mod tests { use super::*; - use agent_client_protocol_core::schema as acp; use fs::Fs as _; use gpui::TestAppContext; use project::{FakeFs, Project}; diff --git a/crates/agent/src/tools/diagnostics_tool.rs b/crates/agent/src/tools/diagnostics_tool.rs index 7f995e3f2f18d9..a59f61ae97a187 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_core::schema as acp; +use agent_client_protocol::schema as acp; use anyhow::Result; use futures::FutureExt as _; use gpui::{App, Entity, Task}; diff --git a/crates/agent/src/tools/edit_file_tool.rs b/crates/agent/src/tools/edit_file_tool.rs index f3b67cad2b993c..a43241a407bef9 100644 --- a/crates/agent/src/tools/edit_file_tool.rs +++ b/crates/agent/src/tools/edit_file_tool.rs @@ -6,7 +6,7 @@ use crate::{ edit_agent::{EditAgent, EditAgentOutputEvent, EditFormat}, }; use acp_thread::Diff; -use agent_client_protocol_core::schema::{self as acp, ToolCallLocation, ToolCallUpdateFields}; +use agent_client_protocol::schema::{self as acp, ToolCallLocation, ToolCallUpdateFields}; use anyhow::{Context as _, Result}; use collections::HashSet; use futures::{FutureExt as _, StreamExt as _}; diff --git a/crates/agent/src/tools/fetch_tool.rs b/crates/agent/src/tools/fetch_tool.rs index 9fbd538ebaa4e2..8723a6d9882df2 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_core::schema as acp; +use agent_client_protocol::schema as acp; use agent_settings::AgentSettings; use anyhow::{Context as _, Result, bail}; use futures::{AsyncReadExt as _, FutureExt as _}; diff --git a/crates/agent/src/tools/find_path_tool.rs b/crates/agent/src/tools/find_path_tool.rs index 8afc9dab09e9d4..66d127e756ca83 100644 --- a/crates/agent/src/tools/find_path_tool.rs +++ b/crates/agent/src/tools/find_path_tool.rs @@ -1,5 +1,5 @@ use crate::{AgentTool, ToolCallEventStream, ToolInput}; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use anyhow::{Result, anyhow}; use futures::FutureExt as _; use gpui::{App, AppContext, Entity, SharedString, Task}; diff --git a/crates/agent/src/tools/grep_tool.rs b/crates/agent/src/tools/grep_tool.rs index 050e67e8241feb..a56c793bb856b7 100644 --- a/crates/agent/src/tools/grep_tool.rs +++ b/crates/agent/src/tools/grep_tool.rs @@ -1,5 +1,5 @@ use crate::{AgentTool, ToolCallEventStream, ToolInput}; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use anyhow::Result; use futures::{FutureExt as _, StreamExt}; use gpui::{App, Entity, SharedString, Task}; diff --git a/crates/agent/src/tools/list_directory_tool.rs b/crates/agent/src/tools/list_directory_tool.rs index 218412fe111152..be51fcf9188308 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_project_path, }; use crate::{AgentTool, ToolCallEventStream, ToolInput}; -use agent_client_protocol_core::schema::ToolKind; +use agent_client_protocol::schema as acp; use anyhow::{Context as _, Result, anyhow}; use gpui::{App, Entity, SharedString, Task}; use project::{Project, ProjectPath, WorktreeSettings}; @@ -127,8 +127,8 @@ impl AgentTool for ListDirectoryTool { const NAME: &'static str = "list_directory"; - fn kind() -> ToolKind { - ToolKind::Read + fn kind() -> acp::ToolKind { + acp::ToolKind::Read } fn initial_title( @@ -267,7 +267,6 @@ impl AgentTool for ListDirectoryTool { #[cfg(test)] mod tests { use super::*; - use agent_client_protocol_core::schema as acp; use fs::Fs as _; use gpui::{TestAppContext, UpdateGlobal}; use indoc::indoc; diff --git a/crates/agent/src/tools/move_path_tool.rs b/crates/agent/src/tools/move_path_tool.rs index d88e529081e805..fcdbd3c59406c3 100644 --- a/crates/agent/src/tools/move_path_tool.rs +++ b/crates/agent/src/tools/move_path_tool.rs @@ -5,7 +5,7 @@ use super::tool_permissions::{ use crate::{ AgentTool, ToolCallEventStream, ToolInput, ToolPermissionDecision, decide_permission_for_paths, }; -use agent_client_protocol_core::schema::ToolKind; +use agent_client_protocol::schema as acp; use agent_settings::AgentSettings; use futures::FutureExt as _; use gpui::{App, Entity, SharedString, Task}; @@ -62,8 +62,8 @@ impl AgentTool for MovePathTool { const NAME: &'static str = "move_path"; - fn kind() -> ToolKind { - ToolKind::Move + fn kind() -> acp::ToolKind { + acp::ToolKind::Move } fn initial_title( @@ -205,7 +205,6 @@ impl AgentTool for MovePathTool { #[cfg(test)] mod tests { use super::*; - use agent_client_protocol_core::schema as acp; use fs::Fs as _; use gpui::TestAppContext; use project::{FakeFs, Project}; diff --git a/crates/agent/src/tools/now_tool.rs b/crates/agent/src/tools/now_tool.rs index 1deeb6861802b8..04aba44ff3a1f4 100644 --- a/crates/agent/src/tools/now_tool.rs +++ b/crates/agent/src/tools/now_tool.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use chrono::{Local, Utc}; use gpui::{App, SharedString, Task}; use schemars::JsonSchema; diff --git a/crates/agent/src/tools/open_tool.rs b/crates/agent/src/tools/open_tool.rs index bae306c75898ac..dc72c758e36b04 100644 --- a/crates/agent/src/tools/open_tool.rs +++ b/crates/agent/src/tools/open_tool.rs @@ -3,7 +3,7 @@ use super::tool_permissions::{ resolve_project_path, }; use crate::{AgentTool, ToolInput}; -use agent_client_protocol_core::schema::ToolKind; +use agent_client_protocol::schema as acp; use futures::FutureExt as _; use gpui::{App, AppContext as _, Entity, SharedString, Task}; use project::Project; @@ -43,8 +43,8 @@ impl AgentTool for OpenTool { const NAME: &'static str = "open"; - fn kind() -> ToolKind { - ToolKind::Execute + fn kind() -> acp::ToolKind { + acp::ToolKind::Execute } fn initial_title( diff --git a/crates/agent/src/tools/read_file_tool.rs b/crates/agent/src/tools/read_file_tool.rs index 96a44c443b63eb..e59e2e4db3a4ed 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_core::schema::{self as acp, ToolCallUpdateFields}; +use agent_client_protocol::schema::{self as acp, ToolCallUpdateFields}; use anyhow::{Context as _, Result, anyhow}; use futures::FutureExt as _; use gpui::{App, Entity, SharedString, Task}; @@ -347,7 +347,7 @@ impl AgentTool for ReadFileTool { #[cfg(test)] mod test { use super::*; - use agent_client_protocol_core::schema as acp; + use agent_client_protocol::schema as acp; use fs::Fs as _; use gpui::{AppContext, TestAppContext, UpdateGlobal as _}; use project::{FakeFs, Project}; diff --git a/crates/agent/src/tools/restore_file_from_disk_tool.rs b/crates/agent/src/tools/restore_file_from_disk_tool.rs index 1c9f398029eb5b..311ca664333453 100644 --- a/crates/agent/src/tools/restore_file_from_disk_tool.rs +++ b/crates/agent/src/tools/restore_file_from_disk_tool.rs @@ -3,7 +3,7 @@ use super::tool_permissions::{ canonicalize_worktree_roots, path_has_symlink_escape, resolve_project_path, sensitive_settings_kind, }; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use agent_settings::AgentSettings; use collections::FxHashSet; use futures::FutureExt as _; diff --git a/crates/agent/src/tools/save_file_tool.rs b/crates/agent/src/tools/save_file_tool.rs index 833f74e02fd448..7eeeea961f6e50 100644 --- a/crates/agent/src/tools/save_file_tool.rs +++ b/crates/agent/src/tools/save_file_tool.rs @@ -1,4 +1,4 @@ -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use agent_settings::AgentSettings; use collections::FxHashSet; use futures::FutureExt as _; diff --git a/crates/agent/src/tools/spawn_agent_tool.rs b/crates/agent/src/tools/spawn_agent_tool.rs index 0639e2fa11b4de..cdb36126f5763d 100644 --- a/crates/agent/src/tools/spawn_agent_tool.rs +++ b/crates/agent/src/tools/spawn_agent_tool.rs @@ -1,5 +1,5 @@ use acp_thread::{SUBAGENT_SESSION_INFO_META_KEY, SubagentSessionInfo}; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use anyhow::Result; use gpui::{App, SharedString, Task}; use language_model::LanguageModelToolResultContent; diff --git a/crates/agent/src/tools/streaming_edit_file_tool.rs b/crates/agent/src/tools/streaming_edit_file_tool.rs index c185295d713ddd..dfd3310f143d2a 100644 --- a/crates/agent/src/tools/streaming_edit_file_tool.rs +++ b/crates/agent/src/tools/streaming_edit_file_tool.rs @@ -11,7 +11,7 @@ use crate::{ }; use acp_thread::Diff; use action_log::ActionLog; -use agent_client_protocol_core::schema::{self as acp, ToolCallLocation, ToolCallUpdateFields}; +use agent_client_protocol::schema::{self as acp, ToolCallLocation, ToolCallUpdateFields}; use anyhow::{Context as _, Result}; use collections::HashSet; use futures::FutureExt as _; diff --git a/crates/agent/src/tools/terminal_tool.rs b/crates/agent/src/tools/terminal_tool.rs index b19323da2b6990..4d17c0d91dc4d1 100644 --- a/crates/agent/src/tools/terminal_tool.rs +++ b/crates/agent/src/tools/terminal_tool.rs @@ -1,4 +1,4 @@ -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use agent_settings::AgentSettings; use anyhow::Result; use futures::FutureExt as _; diff --git a/crates/agent/src/tools/update_plan_tool.rs b/crates/agent/src/tools/update_plan_tool.rs index af18f6409d0b19..39e88590b1872a 100644 --- a/crates/agent/src/tools/update_plan_tool.rs +++ b/crates/agent/src/tools/update_plan_tool.rs @@ -1,5 +1,5 @@ use crate::{AgentTool, ToolCallEventStream, ToolInput}; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use gpui::{App, SharedString, Task}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; diff --git a/crates/agent/src/tools/web_search_tool.rs b/crates/agent/src/tools/web_search_tool.rs index 7d0a50a8c9c2d7..8efff5ae52bc78 100644 --- a/crates/agent/src/tools/web_search_tool.rs +++ b/crates/agent/src/tools/web_search_tool.rs @@ -4,7 +4,7 @@ use crate::{ AgentTool, ToolCallEventStream, ToolInput, ToolPermissionDecision, decide_permission_from_settings, }; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use agent_settings::AgentSettings; use anyhow::Result; use cloud_llm_client::WebSearchResponse; diff --git a/crates/agent_servers/Cargo.toml b/crates/agent_servers/Cargo.toml index 4caf08c7c0bb9d..1542466be35bbc 100644 --- a/crates/agent_servers/Cargo.toml +++ b/crates/agent_servers/Cargo.toml @@ -20,7 +20,7 @@ doctest = false acp_tools.workspace = true acp_thread.workspace = true action_log.workspace = true -agent-client-protocol-core.workspace = true +agent-client-protocol.workspace = true anyhow.workspace = true async-trait.workspace = true chrono.workspace = true diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs index 5e8b7aa59e189c..b81de679982649 100644 --- a/crates/agent_servers/src/acp.rs +++ b/crates/agent_servers/src/acp.rs @@ -4,8 +4,8 @@ use acp_thread::{ }; use acp_tools::{AcpConnectionRegistry, StreamMessage, StreamMessageDirection}; use action_log::ActionLog; -use agent_client_protocol_core::schema::{self as acp, ErrorCode}; -use agent_client_protocol_core::{ConnectionTo, Lines}; +use agent_client_protocol::schema::{self as acp, ErrorCode}; +use agent_client_protocol::{Agent, Client, ConnectionTo, JsonRpcResponse, Lines, Responder}; use anyhow::anyhow; use collections::HashMap; use feature_flags::{AcpBetaFeatureFlag, FeatureFlagAppExt as _}; @@ -54,7 +54,7 @@ type ForegroundWork = Box; pub struct AcpConnection { id: AgentId, telemetry_id: SharedString, - connection: ConnectionTo, + connection: ConnectionTo, sessions: Rc>>, auth_methods: Vec, command: AgentServerCommand, @@ -96,13 +96,13 @@ pub struct AcpSession { } pub struct AcpSessionList { - connection: ConnectionTo, + connection: ConnectionTo, updates_tx: smol::channel::Sender, updates_rx: smol::channel::Receiver, } impl AcpSessionList { - fn new(connection: ConnectionTo) -> Self { + fn new(connection: ConnectionTo) -> Self { let (tx, rx) = smol::channel::unbounded(); Self { connection, @@ -337,50 +337,50 @@ impl AcpConnection { // All handlers forward work to the foreground dispatch channel. let connection_future = { let dispatch_tx = dispatch_tx.clone(); - agent_client_protocol_core::Client + Client .builder() .name("zed") // --- Request handlers (agent→client) --- .on_receive_request( dispatch_request_handler!(dispatch_tx, handle_request_permission), - agent_client_protocol_core::on_receive_request!(), + agent_client_protocol::on_receive_request!(), ) .on_receive_request( dispatch_request_handler!(dispatch_tx, handle_write_text_file), - agent_client_protocol_core::on_receive_request!(), + agent_client_protocol::on_receive_request!(), ) .on_receive_request( dispatch_request_handler!(dispatch_tx, handle_read_text_file), - agent_client_protocol_core::on_receive_request!(), + agent_client_protocol::on_receive_request!(), ) .on_receive_request( dispatch_request_handler!(dispatch_tx, handle_create_terminal), - agent_client_protocol_core::on_receive_request!(), + agent_client_protocol::on_receive_request!(), ) .on_receive_request( dispatch_request_handler!(dispatch_tx, handle_kill_terminal), - agent_client_protocol_core::on_receive_request!(), + agent_client_protocol::on_receive_request!(), ) .on_receive_request( dispatch_request_handler!(dispatch_tx, handle_release_terminal), - agent_client_protocol_core::on_receive_request!(), + agent_client_protocol::on_receive_request!(), ) .on_receive_request( dispatch_request_handler!(dispatch_tx, handle_terminal_output), - agent_client_protocol_core::on_receive_request!(), + agent_client_protocol::on_receive_request!(), ) .on_receive_request( dispatch_request_handler!(dispatch_tx, handle_wait_for_terminal_exit), - agent_client_protocol_core::on_receive_request!(), + agent_client_protocol::on_receive_request!(), ) // --- Notification handlers (agent→client) --- .on_receive_notification( dispatch_notification_handler!(dispatch_tx, handle_session_notification), - agent_client_protocol_core::on_receive_notification!(), + agent_client_protocol::on_receive_notification!(), ) .connect_with( transport, - move |connection: ConnectionTo| async move { + move |connection: ConnectionTo| async move { connection_tx.send(connection.clone()).ok(); // Keep the connection alive until the transport closes. futures::future::pending::>().await @@ -396,7 +396,7 @@ impl AcpConnection { }); // Wait for the ConnectionTo handle. - let connection: ConnectionTo = connection_rx + let connection: ConnectionTo = connection_rx .await .context("Failed to receive ACP connection handle")?; @@ -1465,7 +1465,7 @@ fn config_state( struct AcpSessionModes { session_id: acp::SessionId, - connection: ConnectionTo, + connection: ConnectionTo, state: Rc>, } @@ -1507,14 +1507,14 @@ impl acp_thread::AgentSessionModes for AcpSessionModes { struct AcpModelSelector { session_id: acp::SessionId, - connection: ConnectionTo, + connection: ConnectionTo, state: Rc>, } impl AcpModelSelector { fn new( session_id: acp::SessionId, - connection: ConnectionTo, + connection: ConnectionTo, state: Rc>, ) -> Self { Self { @@ -1580,7 +1580,7 @@ impl acp_thread::AgentModelSelector for AcpModelSelector { struct AcpSessionConfigOptions { session_id: acp::SessionId, - connection: ConnectionTo, + connection: ConnectionTo, state: Rc>>, watch_tx: Rc>>, watch_rx: watch::Receiver<()>, @@ -1638,16 +1638,13 @@ fn session_thread( .ok_or_else(|| acp::Error::internal_error().data(format!("unknown session: {session_id}"))) } -fn respond_err( - responder: agent_client_protocol_core::Responder, - err: acp::Error, -) { +fn respond_err(responder: Responder, err: acp::Error) { responder.respond_with_error(err).log_err(); } fn handle_request_permission( args: acp::RequestPermissionRequest, - responder: agent_client_protocol_core::Responder, + responder: Responder, cx: &mut AsyncApp, ctx: &ClientContext, ) { @@ -1686,7 +1683,7 @@ fn handle_request_permission( fn handle_write_text_file( args: acp::WriteTextFileRequest, - responder: agent_client_protocol_core::Responder, + responder: Responder, cx: &mut AsyncApp, ctx: &ClientContext, ) { @@ -1721,7 +1718,7 @@ fn handle_write_text_file( fn handle_read_text_file( args: acp::ReadTextFileRequest, - responder: agent_client_protocol_core::Responder, + responder: Responder, cx: &mut AsyncApp, ctx: &ClientContext, ) { @@ -1903,7 +1900,7 @@ fn handle_session_notification( fn handle_create_terminal( args: acp::CreateTerminalRequest, - responder: agent_client_protocol_core::Responder, + responder: Responder, cx: &mut AsyncApp, ctx: &ClientContext, ) { @@ -1966,7 +1963,7 @@ fn handle_create_terminal( fn handle_kill_terminal( args: acp::KillTerminalRequest, - responder: agent_client_protocol_core::Responder, + responder: Responder, cx: &mut AsyncApp, ctx: &ClientContext, ) { @@ -1991,7 +1988,7 @@ fn handle_kill_terminal( fn handle_release_terminal( args: acp::ReleaseTerminalRequest, - responder: agent_client_protocol_core::Responder, + responder: Responder, cx: &mut AsyncApp, ctx: &ClientContext, ) { @@ -2018,7 +2015,7 @@ fn handle_release_terminal( fn handle_terminal_output( args: acp::TerminalOutputRequest, - responder: agent_client_protocol_core::Responder, + responder: Responder, cx: &mut AsyncApp, ctx: &ClientContext, ) { @@ -2047,7 +2044,7 @@ fn handle_terminal_output( fn handle_wait_for_terminal_exit( args: acp::WaitForTerminalExitRequest, - responder: agent_client_protocol_core::Responder, + responder: Responder, cx: &mut AsyncApp, ctx: &ClientContext, ) { diff --git a/crates/agent_servers/src/agent_servers.rs b/crates/agent_servers/src/agent_servers.rs index 9bba14dea302b3..37e77c80c79683 100644 --- a/crates/agent_servers/src/agent_servers.rs +++ b/crates/agent_servers/src/agent_servers.rs @@ -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_core::schema::{ +use agent_client_protocol::schema::{ ModelId, SessionConfigId, SessionConfigValueId, SessionModeId, }; use anyhow::Result; diff --git a/crates/agent_servers/src/custom.rs b/crates/agent_servers/src/custom.rs index 91f39b25b8cb7a..b07bd4a09a2e8d 100644 --- a/crates/agent_servers/src/custom.rs +++ b/crates/agent_servers/src/custom.rs @@ -1,6 +1,6 @@ use crate::{AgentServer, AgentServerDelegate, load_proxy_env}; use acp_thread::AgentConnection; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use anyhow::{Context as _, Result}; use collections::HashSet; use credentials_provider::CredentialsProvider; diff --git a/crates/agent_servers/src/e2e_tests.rs b/crates/agent_servers/src/e2e_tests.rs index 3f3c77f740eb4c..c388569a2c705b 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, ToolCall, ToolCallStatus}; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use futures::{FutureExt, StreamExt, channel::mpsc, select}; use gpui::AppContext; use gpui::{Entity, TestAppContext}; @@ -378,7 +378,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_core::schema::PermissionOptionId::new($allow_option_id), + ::agent_client_protocol::schema::PermissionOptionId::new($allow_option_id), cx, ) .await; diff --git a/crates/agent_settings/Cargo.toml b/crates/agent_settings/Cargo.toml index 942e54c37b97b4..b2db5677dcfdc0 100644 --- a/crates/agent_settings/Cargo.toml +++ b/crates/agent_settings/Cargo.toml @@ -12,7 +12,7 @@ workspace = true path = "src/agent_settings.rs" [dependencies] -agent-client-protocol-core.workspace = true +agent-client-protocol.workspace = true anyhow.workspace = true collections.workspace = true convert_case.workspace = true diff --git a/crates/agent_settings/src/agent_settings.rs b/crates/agent_settings/src/agent_settings.rs index 9b2a8673bb5454..c131a686ce10df 100644 --- a/crates/agent_settings/src/agent_settings.rs +++ b/crates/agent_settings/src/agent_settings.rs @@ -3,7 +3,7 @@ mod agent_profile; use std::path::{Component, Path}; use std::sync::{Arc, LazyLock}; -use agent_client_protocol_core::schema::ModelId; +use agent_client_protocol::schema as acp; use collections::{HashSet, IndexMap}; use fs::Fs; use gpui::{App, Pixels, px}; @@ -214,10 +214,10 @@ impl AgentSettings { self.message_editor_min_lines * 2 } - pub fn favorite_model_ids(&self) -> HashSet { + pub fn favorite_model_ids(&self) -> HashSet { self.favorite_models .iter() - .map(|sel| ModelId::new(format!("{}/{}", sel.provider.0, sel.model))) + .map(|sel| acp::ModelId::new(format!("{}/{}", sel.provider.0, sel.model))) .collect() } diff --git a/crates/agent_ui/Cargo.toml b/crates/agent_ui/Cargo.toml index ce03c3ddc67add..e505a124b68989 100644 --- a/crates/agent_ui/Cargo.toml +++ b/crates/agent_ui/Cargo.toml @@ -28,7 +28,7 @@ unit-eval = [] [dependencies] acp_thread.workspace = true action_log.workspace = true -agent-client-protocol-core.workspace = true +agent-client-protocol.workspace = true agent.workspace = true agent_servers.workspace = true agent_settings.workspace = true diff --git a/crates/agent_ui/src/agent_panel.rs b/crates/agent_ui/src/agent_panel.rs index dd1594430c7ce5..4792e0dfebb7e8 100644 --- a/crates/agent_ui/src/agent_panel.rs +++ b/crates/agent_ui/src/agent_panel.rs @@ -10,7 +10,7 @@ use std::{ use acp_thread::{AcpThread, MentionUri, ThreadStatus}; use agent::{ContextServerRegistry, SharedThread, ThreadStore}; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use agent_servers::AgentServer; use collections::HashSet; use db::kvp::{Dismissable, KeyValueStore}; diff --git a/crates/agent_ui/src/agent_ui.rs b/crates/agent_ui/src/agent_ui.rs index 45620b4c26a17a..0c831b04a98540 100644 --- a/crates/agent_ui/src/agent_ui.rs +++ b/crates/agent_ui/src/agent_ui.rs @@ -39,7 +39,7 @@ use std::rc::Rc; use std::sync::Arc; use ::ui::IconName; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use agent_settings::{AgentProfileId, AgentSettings}; use command_palette_hooks::CommandPaletteFilter; use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt as _}; @@ -232,7 +232,7 @@ pub struct NewExternalAgentThread { #[action(namespace = agent)] #[serde(deny_unknown_fields)] pub struct NewNativeAgentThreadFromSummary { - from_session_id: agent_client_protocol_core::schema::SessionId, + from_session_id: acp::SessionId, } #[derive(Debug, Default, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)] @@ -317,7 +317,7 @@ pub enum AgentInitialContent { title: Option, }, ContentBlock { - blocks: Vec, + blocks: Vec, auto_submit: bool, }, FromExternalSource(ExternalSourcePrompt), diff --git a/crates/agent_ui/src/completion_provider.rs b/crates/agent_ui/src/completion_provider.rs index 7ee3b60f95c1c0..d618cd2369f4d5 100644 --- a/crates/agent_ui/src/completion_provider.rs +++ b/crates/agent_ui/src/completion_provider.rs @@ -7,7 +7,7 @@ use std::sync::atomic::AtomicBool; use crate::DEFAULT_THREAD_TITLE; use crate::ThreadHistory; use acp_thread::MentionUri; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use anyhow::Result; use editor::{CompletionProvider, Editor, code_context_menus::COMPLETION_MENU_MAX_WIDTH}; use futures::FutureExt as _; diff --git a/crates/agent_ui/src/config_options.rs b/crates/agent_ui/src/config_options.rs index a1d1158e8e1c23..7945a76e1994cd 100644 --- a/crates/agent_ui/src/config_options.rs +++ b/crates/agent_ui/src/config_options.rs @@ -1,7 +1,7 @@ use std::{cmp::Reverse, rc::Rc, sync::Arc}; use acp_thread::AgentSessionConfigOptions; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use agent_servers::AgentServer; use agent_settings::AgentSettings; use collections::HashSet; diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs index c3a17a06c958a8..73196e8c01a919 100644 --- a/crates/agent_ui/src/conversation_view.rs +++ b/crates/agent_ui/src/conversation_view.rs @@ -7,7 +7,7 @@ use acp_thread::{ use acp_thread::{AgentConnection, Plan}; use action_log::{ActionLog, ActionLogTelemetry, DiffStats}; use agent::{NativeAgentServer, NativeAgentSessionList, SharedThread, ThreadStore}; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; #[cfg(test)] use agent_servers::AgentServerDelegate; use agent_servers::{AgentServer, GEMINI_TERMINAL_AUTH_METHOD_ID}; @@ -2745,12 +2745,12 @@ fn plan_label_markdown_style( #[cfg(test)] pub(crate) mod tests { + use acp::SessionId; use acp_thread::{ AgentSessionList, AgentSessionListRequest, AgentSessionListResponse, StubAgentConnection, }; use action_log::ActionLog; use agent::{AgentTool, EditFileTool, FetchTool, TerminalTool, ToolPermissionContext}; - use agent_client_protocol_core::schema::SessionId; use editor::MultiBufferOffset; use fs::FakeFs; use gpui::{EventEmitter, TestAppContext, VisualTestContext}; diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs index 4926a7337431c7..e6fdb9a381c05c 100644 --- a/crates/agent_ui/src/conversation_view/thread_view.rs +++ b/crates/agent_ui/src/conversation_view/thread_view.rs @@ -2,6 +2,7 @@ use crate::{ DEFAULT_THREAD_TITLE, SelectPermissionGranularity, agent_configuration::configure_context_server_modal::default_markdown_style, }; +use agent_client_protocol::schema as acp; use std::cell::RefCell; use acp_thread::{ContentBlock, PlanEntry}; @@ -249,13 +250,12 @@ pub struct ThreadView { pub session_capabilities: SharedSessionCapabilities, /// Tracks which tool calls have their content/output expanded. /// Used for showing/hiding tool call results, terminal output, etc. - pub expanded_tool_calls: HashSet, - pub expanded_tool_call_raw_inputs: HashSet, + pub expanded_tool_calls: HashSet, + pub expanded_tool_call_raw_inputs: HashSet, pub expanded_thinking_blocks: HashSet<(usize, usize)>, auto_expanded_thinking_block: Option<(usize, usize)>, user_toggled_thinking_blocks: HashSet<(usize, usize)>, - pub subagent_scroll_handles: - RefCell>, + pub subagent_scroll_handles: RefCell>, pub edits_expanded: bool, pub plan_expanded: bool, pub queue_expanded: bool, @@ -267,12 +267,11 @@ pub struct ThreadView { pub queued_message_editor_subscriptions: Vec, pub last_synced_queue_length: usize, pub turn_fields: TurnFields, - pub discarded_partial_edits: HashSet, + pub discarded_partial_edits: HashSet, pub is_loading_contents: bool, pub new_server_version_available: Option, pub resumed_without_history: bool, - pub(crate) permission_selections: - HashMap, + pub(crate) permission_selections: HashMap, pub resume_thread_metadata: Option, pub _cancel_task: Option>, _save_task: Option>, diff --git a/crates/agent_ui/src/entry_view_state.rs b/crates/agent_ui/src/entry_view_state.rs index 4cd34ceb38af52..584776eb613503 100644 --- a/crates/agent_ui/src/entry_view_state.rs +++ b/crates/agent_ui/src/entry_view_state.rs @@ -3,7 +3,7 @@ use std::ops::Range; use super::thread_history::ThreadHistory; use acp_thread::{AcpThread, AgentThreadEntry}; use agent::ThreadStore; -use agent_client_protocol_core::schema::ToolCallId; +use agent_client_protocol::schema as acp; use collections::HashMap; use editor::{Editor, EditorEvent, EditorMode, MinimapVisibility, SizingBehavior}; use gpui::{ @@ -286,9 +286,9 @@ pub struct EntryViewEvent { } pub enum ViewEvent { - NewDiff(ToolCallId), - NewTerminal(ToolCallId), - TerminalMovedToBackground(ToolCallId), + NewDiff(acp::ToolCallId), + NewTerminal(acp::ToolCallId), + TerminalMovedToBackground(acp::ToolCallId), MessageEditorEvent(Entity, MessageEditorEvent), OpenDiffLocation { path: String, @@ -465,7 +465,7 @@ mod tests { use std::sync::Arc; use acp_thread::{AgentConnection, StubAgentConnection}; - use agent_client_protocol_core::schema as acp; + use agent_client_protocol::schema as acp; use buffer_diff::{DiffHunkStatus, DiffHunkStatusKind}; use editor::RowInfo; use fs::FakeFs; diff --git a/crates/agent_ui/src/mention_set.rs b/crates/agent_ui/src/mention_set.rs index 2e150527e01a84..1bf524c454ecbc 100644 --- a/crates/agent_ui/src/mention_set.rs +++ b/crates/agent_ui/src/mention_set.rs @@ -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_core::schema as acp; +use agent_client_protocol::schema as acp; use agent_servers::{AgentServer, AgentServerDelegate}; use anyhow::{Context as _, Result, anyhow}; use collections::{HashMap, HashSet}; diff --git a/crates/agent_ui/src/message_editor.rs b/crates/agent_ui/src/message_editor.rs index a925553a2ef0c9..0edca0ad52b984 100644 --- a/crates/agent_ui/src/message_editor.rs +++ b/crates/agent_ui/src/message_editor.rs @@ -11,7 +11,7 @@ use crate::{ }; use acp_thread::MentionUri; use agent::ThreadStore; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use anyhow::{Result, anyhow}; use editor::{ Addon, AnchorRangeExt, ContextMenuOptions, Editor, EditorElement, EditorEvent, EditorMode, @@ -1905,7 +1905,7 @@ mod tests { use acp_thread::MentionUri; use agent::{ThreadStore, outline}; - use agent_client_protocol_core::schema as acp; + use agent_client_protocol::schema as acp; use base64::Engine as _; use editor::{ AnchorRangeExt as _, Editor, EditorMode, MultiBufferOffset, SelectionEffects, diff --git a/crates/agent_ui/src/mode_selector.rs b/crates/agent_ui/src/mode_selector.rs index c619940387b9fc..c45e368739c05e 100644 --- a/crates/agent_ui/src/mode_selector.rs +++ b/crates/agent_ui/src/mode_selector.rs @@ -1,5 +1,5 @@ use acp_thread::AgentSessionModes; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use agent_servers::AgentServer; use agent_settings::AgentSettings; use fs::Fs; diff --git a/crates/agent_ui/src/model_selector.rs b/crates/agent_ui/src/model_selector.rs index 805c1b7188d1c8..1e65cc6992dee0 100644 --- a/crates/agent_ui/src/model_selector.rs +++ b/crates/agent_ui/src/model_selector.rs @@ -1,7 +1,7 @@ use std::{cmp::Reverse, rc::Rc, sync::Arc}; use acp_thread::{AgentModelIcon, AgentModelInfo, AgentModelList, AgentModelSelector}; -use agent_client_protocol_core::schema::ModelId; +use agent_client_protocol::schema as acp; use agent_servers::AgentServer; use agent_settings::AgentSettings; use anyhow::Result; @@ -54,7 +54,7 @@ pub struct ModelPickerDelegate { selected_index: usize, selected_description: Option<(usize, SharedString, bool)>, selected_model: Option, - favorites: HashSet, + favorites: HashSet, _refresh_models_task: Task<()>, _settings_subscription: Subscription, focus_handle: FocusHandle, @@ -427,7 +427,7 @@ impl PickerDelegate for ModelPickerDelegate { fn info_list_to_picker_entries( model_list: AgentModelList, - favorites: &HashSet, + favorites: &HashSet, ) -> Vec { let mut entries = Vec::new(); @@ -533,7 +533,6 @@ async fn fuzzy_search( #[cfg(test)] mod tests { - use agent_client_protocol_core::schema as acp; use gpui::TestAppContext; use super::*; @@ -595,10 +594,10 @@ mod tests { } } - fn create_favorites(models: Vec<&str>) -> HashSet { + fn create_favorites(models: Vec<&str>) -> HashSet { models .into_iter() - .map(|m| ModelId::new(m.to_string())) + .map(|m| acp::ModelId::new(m.to_string())) .collect() } @@ -794,7 +793,7 @@ mod tests { #[gpui::test] fn test_favorites_count_returns_correct_count(_cx: &mut TestAppContext) { - let empty_favorites: HashSet = HashSet::default(); + let empty_favorites: HashSet = HashSet::default(); assert_eq!(empty_favorites.len(), 0); let one_favorite = create_favorites(vec!["model-a"]); diff --git a/crates/agent_ui/src/test_support.rs b/crates/agent_ui/src/test_support.rs index 2ffac1635836b2..f151d23c88f0f6 100644 --- a/crates/agent_ui/src/test_support.rs +++ b/crates/agent_ui/src/test_support.rs @@ -1,5 +1,5 @@ use acp_thread::{AgentConnection, StubAgentConnection}; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use agent_servers::{AgentServer, AgentServerDelegate}; use gpui::{Entity, Task, TestAppContext, VisualTestContext}; use project::AgentId; diff --git a/crates/agent_ui/src/thread_history.rs b/crates/agent_ui/src/thread_history.rs index 29e8cdd94c7da3..58b954eab6b8ed 100644 --- a/crates/agent_ui/src/thread_history.rs +++ b/crates/agent_ui/src/thread_history.rs @@ -1,5 +1,5 @@ use acp_thread::{AgentSessionInfo, AgentSessionList, AgentSessionListRequest, SessionListUpdate}; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use gpui::{App, Task}; use std::rc::Rc; use ui::prelude::*; diff --git a/crates/agent_ui/src/thread_import.rs b/crates/agent_ui/src/thread_import.rs index 4e5c4f7131ac41..d1d488164c2451 100644 --- a/crates/agent_ui/src/thread_import.rs +++ b/crates/agent_ui/src/thread_import.rs @@ -1,6 +1,6 @@ use acp_thread::AgentSessionListRequest; use agent::ThreadStore; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use chrono::Utc; use collections::HashSet; use db::kvp::Dismissable; diff --git a/crates/agent_ui/src/thread_metadata_store.rs b/crates/agent_ui/src/thread_metadata_store.rs index 9696e09d7d969e..0adfc8014b9bec 100644 --- a/crates/agent_ui/src/thread_metadata_store.rs +++ b/crates/agent_ui/src/thread_metadata_store.rs @@ -2,7 +2,7 @@ use std::{path::Path, sync::Arc}; use acp_thread::AcpThreadEvent; use agent::{ThreadStore, ZED_AGENT_ID}; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use anyhow::Context as _; use chrono::{DateTime, Utc}; use collections::{HashMap, HashSet}; @@ -791,7 +791,7 @@ mod tests { use acp_thread::{AgentConnection, StubAgentConnection}; use action_log::ActionLog; use agent::DbThread; - use agent_client_protocol_core::schema as acp; + use agent_client_protocol::schema as acp; use feature_flags::FeatureFlagAppExt; use gpui::TestAppContext; use project::FakeFs; diff --git a/crates/agent_ui/src/threads_archive_view.rs b/crates/agent_ui/src/threads_archive_view.rs index cd43d6627ce401..c67049d4d58e62 100644 --- a/crates/agent_ui/src/threads_archive_view.rs +++ b/crates/agent_ui/src/threads_archive_view.rs @@ -7,7 +7,7 @@ use crate::thread_metadata_store::{ThreadMetadata, ThreadMetadataStore}; use crate::{Agent, RemoveSelectedThread}; use agent::ThreadStore; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use agent_settings::AgentSettings; use chrono::{DateTime, Datelike as _, Local, NaiveDate, TimeDelta, Utc}; use editor::Editor; diff --git a/crates/agent_ui/src/ui/mention_crease.rs b/crates/agent_ui/src/ui/mention_crease.rs index 3b58b04f2d46f1..b13f8b6395dc19 100644 --- a/crates/agent_ui/src/ui/mention_crease.rs +++ b/crates/agent_ui/src/ui/mention_crease.rs @@ -1,7 +1,7 @@ use std::{ops::RangeInclusive, path::PathBuf, time::Duration}; use acp_thread::MentionUri; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use editor::{Editor, SelectionEffects, scroll::Autoscroll}; use gpui::{ Animation, AnimationExt, AnyView, Context, IntoElement, WeakEntity, Window, pulsating_between, diff --git a/crates/eval_cli/Cargo.toml b/crates/eval_cli/Cargo.toml index b68ebfdd0ffb8c..cac5dc6aa28fa9 100644 --- a/crates/eval_cli/Cargo.toml +++ b/crates/eval_cli/Cargo.toml @@ -15,7 +15,7 @@ path = "src/main.rs" [dependencies] acp_thread.workspace = true agent.workspace = true -agent-client-protocol-core.workspace = true +agent-client-protocol.workspace = true agent_ui.workspace = true anyhow.workspace = true clap.workspace = true diff --git a/crates/eval_cli/src/main.rs b/crates/eval_cli/src/main.rs index 1c2d4b7e863578..bb6cbc883e1b6d 100644 --- a/crates/eval_cli/src/main.rs +++ b/crates/eval_cli/src/main.rs @@ -40,7 +40,7 @@ use std::time::{Duration, Instant}; use acp_thread::AgentConnection as _; use agent::{NativeAgent, NativeAgentConnection, Templates, ThreadStore}; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use anyhow::{Context, Result}; use clap::Parser; use feature_flags::FeatureFlagAppExt as _; diff --git a/crates/sidebar/Cargo.toml b/crates/sidebar/Cargo.toml index c40ee1cf802e45..04ed8808a14d4c 100644 --- a/crates/sidebar/Cargo.toml +++ b/crates/sidebar/Cargo.toml @@ -18,7 +18,7 @@ default = [] acp_thread.workspace = true action_log.workspace = true agent.workspace = true -agent-client-protocol-core.workspace = true +agent-client-protocol.workspace = true agent_settings.workspace = true agent_ui = { workspace = true, features = ["audio"] } anyhow.workspace = true diff --git a/crates/sidebar/src/sidebar.rs b/crates/sidebar/src/sidebar.rs index 78e305df4c55a4..515da09c843f23 100644 --- a/crates/sidebar/src/sidebar.rs +++ b/crates/sidebar/src/sidebar.rs @@ -2,7 +2,7 @@ mod thread_switcher; use acp_thread::ThreadStatus; use action_log::DiffStats; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use agent_settings::AgentSettings; use agent_ui::thread_metadata_store::{ThreadMetadata, ThreadMetadataStore}; use agent_ui::threads_archive_view::{ diff --git a/crates/sidebar/src/thread_switcher.rs b/crates/sidebar/src/thread_switcher.rs index 2794d3417a10cb..19f982edaabf25 100644 --- a/crates/sidebar/src/thread_switcher.rs +++ b/crates/sidebar/src/thread_switcher.rs @@ -1,5 +1,5 @@ use action_log::DiffStats; -use agent_client_protocol_core::schema as acp; +use agent_client_protocol::schema as acp; use agent_ui::thread_metadata_store::ThreadMetadata; use gpui::{ Action as _, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, Modifiers, diff --git a/crates/zed/Cargo.toml b/crates/zed/Cargo.toml index 49d7698b8d0bb3..9feaa59c976220 100644 --- a/crates/zed/Cargo.toml +++ b/crates/zed/Cargo.toml @@ -66,7 +66,7 @@ required-features = ["visual-tests"] acp_tools.workspace = true activity_indicator.workspace = true agent.workspace = true -agent-client-protocol-core.workspace = true +agent-client-protocol.workspace = true agent_settings.workspace = true agent_ui = { workspace = true, features = ["audio"] } anyhow.workspace = true diff --git a/crates/zed/src/main.rs b/crates/zed/src/main.rs index 5f809ade7fb564..f29e1dd4feecb4 100644 --- a/crates/zed/src/main.rs +++ b/crates/zed/src/main.rs @@ -5,6 +5,7 @@ mod reliability; mod zed; use agent::{SharedThread, ThreadStore}; +use agent_client_protocol::schema as acp; use agent_ui::AgentPanel; use anyhow::{Context as _, Error, Result}; use clap::Parser; @@ -977,7 +978,7 @@ fn handle_open_request(request: OpenRequest, app_state: Arc, cx: &mut let shared_thread = SharedThread::from_bytes(&response.thread_data)?; let db_thread = shared_thread.to_db_thread(); - let session_id = agent_client_protocol_core::schema::SessionId::new(session_id); + let session_id = acp::SessionId::new(session_id); let save_session_id = session_id.clone(); diff --git a/crates/zed/src/visual_test_runner.rs b/crates/zed/src/visual_test_runner.rs index 6d89da27c3945f..3cb384b87abc83 100644 --- a/crates/zed/src/visual_test_runner.rs +++ b/crates/zed/src/visual_test_runner.rs @@ -95,7 +95,7 @@ fn main() { #[cfg(target_os = "macos")] use { acp_thread::{AgentConnection, StubAgentConnection}, - agent_client_protocol_core::schema as acp, + agent_client_protocol::schema as acp, agent_servers::{AgentServer, AgentServerDelegate}, anyhow::{Context as _, Result}, assets::Assets, From 90043a69eb8390ecb095286a1974be11f4159d67 Mon Sep 17 00:00:00 2001 From: Ben Brandt Date: Thu, 2 Apr 2026 15:46:28 +0200 Subject: [PATCH 05/20] Fix ACP requests on the foreground thread Bridge `SentRequest` results through a oneshot-backed future so ACP requests can be safely awaited from GPUI foreground tasks instead of using `block_task` outside `ConnectionTo::spawn`. --- crates/agent/src/tools/edit_file_tool.rs | 6 +- crates/agent/src/tools/read_file_tool.rs | 9 +- crates/agent_servers/src/acp.rs | 155 ++++++++++++----------- 3 files changed, 91 insertions(+), 79 deletions(-) diff --git a/crates/agent/src/tools/edit_file_tool.rs b/crates/agent/src/tools/edit_file_tool.rs index a43241a407bef9..8f9d23f0007391 100644 --- a/crates/agent/src/tools/edit_file_tool.rs +++ b/crates/agent/src/tools/edit_file_tool.rs @@ -6,7 +6,7 @@ use crate::{ edit_agent::{EditAgent, EditAgentOutputEvent, EditFormat}, }; use acp_thread::Diff; -use agent_client_protocol::schema::{self as acp, ToolCallLocation, ToolCallUpdateFields}; +use agent_client_protocol::schema as acp; use anyhow::{Context as _, Result}; use collections::HashSet; use futures::{FutureExt as _, StreamExt as _}; @@ -260,7 +260,7 @@ impl AgentTool for EditFileTool { let abs_path = project.read(cx).absolute_path(&project_path, cx); if let Some(abs_path) = abs_path.clone() { event_stream.update_fields( - ToolCallUpdateFields::new() + acp::ToolCallUpdateFields::new() .locations(vec![acp::ToolCallLocation::new(abs_path)]), ); } @@ -409,7 +409,7 @@ impl AgentTool for EditFileTool { range.start.to_point(&buffer.snapshot()).row })); if let Some(abs_path) = abs_path.clone() { - event_stream.update_fields(ToolCallUpdateFields::new().locations(vec![ToolCallLocation::new(abs_path).line(line)])); + event_stream.update_fields(acp::ToolCallUpdateFields::new().locations(vec![acp::ToolCallLocation::new(abs_path).line(line)])); } emitted_location = true; } diff --git a/crates/agent/src/tools/read_file_tool.rs b/crates/agent/src/tools/read_file_tool.rs index e59e2e4db3a4ed..5b5f9ca1af6ece 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::{self as acp, ToolCallUpdateFields}; +use agent_client_protocol::schema as acp; use anyhow::{Context as _, Result, anyhow}; use futures::FutureExt as _; use gpui::{App, Entity, SharedString, Task}; @@ -200,7 +200,7 @@ impl AgentTool for ReadFileTool { let file_path = input.path.clone(); cx.update(|_cx| { - event_stream.update_fields(ToolCallUpdateFields::new().locations(vec![ + event_stream.update_fields(acp::ToolCallUpdateFields::new().locations(vec![ acp::ToolCallLocation::new(&abs_path) .line(input.start_line.map(|line| line.saturating_sub(1))), ])); @@ -228,7 +228,7 @@ impl AgentTool for ReadFileTool { .context("processing image") .map_err(tool_content_err)?; - event_stream.update_fields(ToolCallUpdateFields::new().content(vec![ + 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"), ))), @@ -333,7 +333,7 @@ impl AgentTool for ReadFileTool { text, } .to_string(); - event_stream.update_fields(ToolCallUpdateFields::new().content(vec![ + event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![ acp::ToolCallContent::Content(acp::Content::new(markdown)), ])); } @@ -347,7 +347,6 @@ impl AgentTool for ReadFileTool { #[cfg(test)] mod test { use super::*; - use agent_client_protocol::schema as acp; use fs::Fs as _; use gpui::{AppContext, TestAppContext, UpdateGlobal as _}; use project::{FakeFs, Project}; diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs index b81de679982649..99c49da208fd73 100644 --- a/crates/agent_servers/src/acp.rs +++ b/crates/agent_servers/src/acp.rs @@ -5,13 +5,15 @@ use acp_thread::{ use acp_tools::{AcpConnectionRegistry, StreamMessage, StreamMessageDirection}; use action_log::ActionLog; use agent_client_protocol::schema::{self as acp, ErrorCode}; -use agent_client_protocol::{Agent, Client, ConnectionTo, JsonRpcResponse, Lines, Responder}; +use agent_client_protocol::{ + Agent, Client, ConnectionTo, JsonRpcResponse, Lines, Responder, SentRequest, +}; use anyhow::anyhow; use collections::HashMap; use feature_flags::{AcpBetaFeatureFlag, FeatureFlagAppExt as _}; use futures::channel::mpsc; use futures::io::BufReader; -use futures::{AsyncBufReadExt as _, StreamExt as _}; +use futures::{AsyncBufReadExt as _, Future, StreamExt as _}; use project::agent_server_store::AgentServerCommand; use project::{AgentId, Project}; use serde::Deserialize; @@ -38,6 +40,27 @@ use crate::GEMINI_ID; pub const GEMINI_TERMINAL_AUTH_METHOD_ID: &str = "spawn-gemini-cli"; +/// Converts a [`SentRequest`] into a `Future` that can be safely awaited from +/// the GPUI foreground thread. +/// +/// Unlike [`SentRequest::block_task`], which is only safe inside +/// [`ConnectionTo::spawn`] tasks, this uses [`SentRequest::on_receiving_result`] +/// to bridge the response through a oneshot channel. The SDK callback is trivial +/// (just a channel send), so it doesn't meaningfully block the dispatch loop. +fn into_foreground_future( + sent: SentRequest, +) -> impl Future> { + let (tx, rx) = futures::channel::oneshot::channel(); + let spawn_result = sent.on_receiving_result(async move |result| { + tx.send(result).ok(); + Ok(()) + }); + async move { + spawn_result?; + rx.await.map_err(|_| acp::Error::internal_error())? + } +} + #[derive(Debug, Error)] #[error("Unsupported version")] pub struct UnsupportedVersion; @@ -135,9 +158,7 @@ impl AgentSessionList for AcpSessionList { let acp_request = acp::ListSessionsRequest::new() .cwd(request.cwd) .cursor(request.cursor); - let response = conn - .send_request(acp_request) - .block_task() + let response = into_foreground_future(conn.send_request(acp_request)) .await .map_err(map_acp_error)?; Ok(AgentSessionListResponse { @@ -451,8 +472,8 @@ impl AcpConnection { }); }); - let response = connection - .send_request( + let response = into_foreground_future( + connection.send_request( acp::InitializeRequest::new(acp::ProtocolVersion::V1) .client_capabilities( acp::ClientCapabilities::new() @@ -470,9 +491,9 @@ impl AcpConnection { acp::Implementation::new("zed", version) .title(release_channel.map(ToOwned::to_owned)), ), - ) - .block_task() - .await?; + ), + ) + .await?; if response.protocol_version < MINIMUM_SUPPORTED_VERSION { return Err(UnsupportedVersion.into()); @@ -480,7 +501,9 @@ impl AcpConnection { let telemetry_id = response .agent_info + // Use the one the agent provides if we have one .map(|info| info.name.into()) + // Otherwise, just use the name .unwrap_or_else(|| agent_id.0.to_string().into()); let session_list = if response @@ -603,15 +626,15 @@ impl AcpConnection { let config_opts = config_options.clone(); let conn = self.connection.clone(); async move |_| { - let result = conn - .send_request(acp::SetSessionConfigOptionRequest::new( + let result = into_foreground_future(conn.send_request( + acp::SetSessionConfigOptionRequest::new( session_id, config_id_clone.clone(), default_value_id, - )) - .block_task() - .await - .log_err(); + ), + )) + .await + .log_err(); if result.is_none() { if let Some(initial) = initial_value { @@ -724,14 +747,12 @@ impl AgentConnection for AcpConnection { let mcp_servers = mcp_servers_for_project(&project, cx); cx.spawn(async move |cx| { - let response = self - .connection - .send_request( - acp::NewSessionRequest::new(cwd.clone()).mcp_servers(mcp_servers), - ) - .block_task() - .await - .map_err(map_acp_error)?; + let response = into_foreground_future( + self.connection + .send_request(acp::NewSessionRequest::new(cwd.clone()).mcp_servers(mcp_servers)), + ) + .await + .map_err(map_acp_error)?; let (modes, models, config_options) = config_state(response.modes, response.models, response.config_options); @@ -753,14 +774,14 @@ impl AgentConnection for AcpConnection { let modes = modes.clone(); let conn = self.connection.clone(); async move |_| { - let result = conn - .send_request(acp::SetSessionModeRequest::new( + let result = into_foreground_future( + conn.send_request(acp::SetSessionModeRequest::new( session_id, default_mode, - )) - .block_task() - .await - .log_err(); + )), + ) + .await + .log_err(); if result.is_none() { modes.borrow_mut().current_mode_id = initial_mode_id; @@ -802,14 +823,14 @@ impl AgentConnection for AcpConnection { let models = models.clone(); let conn = self.connection.clone(); async move |_| { - let result = conn - .send_request(acp::SetSessionModelRequest::new( + let result = into_foreground_future( + conn.send_request(acp::SetSessionModelRequest::new( session_id, default_model, - )) - .block_task() - .await - .log_err(); + )), + ) + .await + .log_err(); if result.is_none() { models.borrow_mut().current_model_id = initial_model_id; @@ -848,6 +869,7 @@ impl AgentConnection for AcpConnection { project, action_log, response.session_id.clone(), + // ACP doesn't currently support per-session prompt capabilities or changing capabilities dynamically. watch::Receiver::constant( self.agent_capabilities.prompt_capabilities.clone(), ), @@ -927,13 +949,10 @@ impl AgentConnection for AcpConnection { ); cx.spawn(async move |cx| { - let response = match self - .connection - .send_request( - acp::LoadSessionRequest::new(session_id.clone(), cwd).mcp_servers(mcp_servers), - ) - .block_task() - .await + let response = match into_foreground_future(self.connection.send_request( + acp::LoadSessionRequest::new(session_id.clone(), cwd).mcp_servers(mcp_servers), + )) + .await { Ok(response) => response, Err(err) => { @@ -1010,14 +1029,10 @@ impl AgentConnection for AcpConnection { ); cx.spawn(async move |cx| { - let response = match self - .connection - .send_request( - acp::ResumeSessionRequest::new(session_id.clone(), cwd) - .mcp_servers(mcp_servers), - ) - .block_task() - .await + let response = match into_foreground_future(self.connection.send_request( + acp::ResumeSessionRequest::new(session_id.clone(), cwd).mcp_servers(mcp_servers), + )) + .await { Ok(response) => response, Err(err) => { @@ -1061,9 +1076,10 @@ impl AgentConnection for AcpConnection { let conn = self.connection.clone(); let session_id = session_id.clone(); cx.foreground_executor().spawn(async move { - conn.send_request(acp::CloseSessionRequest::new(session_id.clone())) - .block_task() - .await?; + into_foreground_future( + conn.send_request(acp::CloseSessionRequest::new(session_id.clone())), + ) + .await?; self.sessions.borrow_mut().remove(&session_id); Ok(()) }) @@ -1094,8 +1110,7 @@ impl AgentConnection for AcpConnection { fn authenticate(&self, method_id: acp::AuthMethodId, cx: &mut App) -> Task> { let conn = self.connection.clone(); cx.foreground_executor().spawn(async move { - conn.send_request(acp::AuthenticateRequest::new(method_id)) - .block_task() + into_foreground_future(conn.send_request(acp::AuthenticateRequest::new(method_id))) .await?; Ok(()) }) @@ -1111,7 +1126,7 @@ impl AgentConnection for AcpConnection { let sessions = self.sessions.clone(); let session_id = params.session_id.clone(); cx.foreground_executor().spawn(async move { - let result = conn.send_request(params).block_task().await; + let result = into_foreground_future(conn.send_request(params)).await; let mut suppress_abort_err = false; @@ -1489,10 +1504,10 @@ impl acp_thread::AgentSessionModes for AcpSessionModes { }; let state = self.state.clone(); cx.foreground_executor().spawn(async move { - let result = connection - .send_request(acp::SetSessionModeRequest::new(session_id, mode_id)) - .block_task() - .await; + let result = into_foreground_future( + connection.send_request(acp::SetSessionModeRequest::new(session_id, mode_id)), + ) + .await; if result.is_err() { state.borrow_mut().current_mode_id = old_mode_id; @@ -1549,10 +1564,10 @@ impl acp_thread::AgentModelSelector for AcpModelSelector { }; let state = self.state.clone(); cx.foreground_executor().spawn(async move { - let result = connection - .send_request(acp::SetSessionModelRequest::new(session_id, model_id)) - .block_task() - .await; + let result = into_foreground_future( + connection.send_request(acp::SetSessionModelRequest::new(session_id, model_id)), + ) + .await; if result.is_err() { state.borrow_mut().current_model_id = old_model_id; @@ -1604,12 +1619,10 @@ impl acp_thread::AgentSessionConfigOptions for AcpSessionConfigOptions { let watch_tx = self.watch_tx.clone(); cx.foreground_executor().spawn(async move { - let response = connection - .send_request(acp::SetSessionConfigOptionRequest::new( - session_id, config_id, value, - )) - .block_task() - .await?; + let response = into_foreground_future(connection.send_request( + acp::SetSessionConfigOptionRequest::new(session_id, config_id, value), + )) + .await?; *state.borrow_mut() = response.config_options.clone(); watch_tx.borrow_mut().send(()).ok(); From 46a927d9db22dd8207585a079edb5a283695abab Mon Sep 17 00:00:00 2001 From: Ben Brandt Date: Thu, 2 Apr 2026 15:59:58 +0200 Subject: [PATCH 06/20] clean up --- Cargo.lock | 1 + crates/acp_tools/Cargo.toml | 1 + crates/acp_tools/src/acp_tools.rs | 43 +++++-- crates/agent_servers/src/acp.rs | 203 ++++++++++++++++-------------- 4 files changed, 142 insertions(+), 106 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4f52f444867c7a..bd82df022a65d6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -54,6 +54,7 @@ dependencies = [ "collections", "gpui", "language", + "log", "markdown", "project", "serde", diff --git a/crates/acp_tools/Cargo.toml b/crates/acp_tools/Cargo.toml index 15d928b664fd26..7f341008f5e523 100644 --- a/crates/acp_tools/Cargo.toml +++ b/crates/acp_tools/Cargo.toml @@ -18,6 +18,7 @@ agent-client-protocol.workspace = true collections.workspace = true gpui.workspace = true language.workspace= true +log.workspace = true markdown.workspace = true project.workspace = true serde.workspace = true diff --git a/crates/acp_tools/src/acp_tools.rs b/crates/acp_tools/src/acp_tools.rs index d17b8346aa1733..4876456fcbcecc 100644 --- a/crates/acp_tools/src/acp_tools.rs +++ b/crates/acp_tools/src/acp_tools.rs @@ -17,7 +17,7 @@ use workspace::{ Item, ItemHandle, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView, Workspace, }; -pub type RequestId = String; +pub type RequestId = serde_json::Value; #[derive(Clone)] pub enum StreamMessageDirection { @@ -56,7 +56,7 @@ impl StreamMessage { let message = if let Some(method) = obj.get("method").and_then(|m| m.as_str()) { if let Some(id) = obj.get("id") { StreamMessageContent::Request { - id: id.to_string(), + id: id.clone(), method: method.into(), params: obj.get("params").cloned(), } @@ -68,15 +68,18 @@ impl StreamMessage { } } else if let Some(id) = obj.get("id") { if let Some(error) = obj.get("error") { - let acp_err = serde_json::from_value::(error.clone()) - .unwrap_or_else(|_| acp::Error::internal_error()); + let acp_err = + serde_json::from_value::(error.clone()).unwrap_or_else(|err| { + log::warn!("Failed to deserialize ACP error: {err}"); + acp::Error::internal_error() + }); StreamMessageContent::Response { - id: id.to_string(), + id: id.clone(), result: Err(acp_err), } } else { StreamMessageContent::Response { - id: id.to_string(), + id: id.clone(), result: Ok(obj.get("result").cloned()), } } @@ -107,6 +110,13 @@ struct GlobalAcpConnectionRegistry(Entity); impl Global for GlobalAcpConnectionRegistry {} +/// A raw JSON-RPC line captured from the transport, tagged with direction. +/// Deserialization into [`StreamMessage`] is deferred until a subscriber is listening. +pub struct RawStreamLine { + pub direction: StreamMessageDirection, + pub line: Arc, +} + #[derive(Default)] pub struct AcpConnectionRegistry { active_agent_id: Option, @@ -129,7 +139,7 @@ impl AcpConnectionRegistry { pub fn set_active_connection( &mut self, agent_id: AgentId, - messages_rx: smol::channel::Receiver, + raw_rx: smol::channel::Receiver, cx: &mut Context, ) { self.active_agent_id = Some(agent_id); @@ -137,10 +147,21 @@ impl AcpConnectionRegistry { self.subscribers.clear(); self._broadcast_task = Some(cx.spawn(async move |this, cx| { - while let Ok(message) = messages_rx.recv().await { + while let Ok(raw) = raw_rx.recv().await { this.update(cx, |this, _cx| { - this.subscribers - .retain(|sender| sender.try_send(message.clone()).is_ok()); + if this.subscribers.is_empty() { + return; + } + + let Some(message) = StreamMessage::from_json_line(raw.direction, &raw.line) + else { + return; + }; + + this.subscribers.retain(|sender| !sender.is_closed()); + for sender in &this.subscribers { + sender.try_send(message.clone()).ok(); + } }) .ok(); } @@ -150,7 +171,7 @@ impl AcpConnectionRegistry { } pub fn subscribe(&mut self) -> smol::channel::Receiver { - let (sender, receiver) = smol::channel::bounded(4096); + let (sender, receiver) = smol::channel::unbounded(); self.subscribers.push(sender); receiver } diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs index 99c49da208fd73..830d74546eeed0 100644 --- a/crates/agent_servers/src/acp.rs +++ b/crates/agent_servers/src/acp.rs @@ -2,7 +2,7 @@ use acp_thread::{ AgentConnection, AgentSessionInfo, AgentSessionList, AgentSessionListRequest, AgentSessionListResponse, }; -use acp_tools::{AcpConnectionRegistry, StreamMessage, StreamMessageDirection}; +use acp_tools::{AcpConnectionRegistry, RawStreamLine, StreamMessageDirection}; use action_log::ActionLog; use agent_client_protocol::schema::{self as acp, ErrorCode}; use agent_client_protocol::{ @@ -26,6 +26,7 @@ use util::process::Child; use std::path::PathBuf; use std::process::Stdio; use std::rc::Rc; +use std::sync::Arc; use std::{any::Any, cell::RefCell}; use thiserror::Error; @@ -228,11 +229,18 @@ macro_rules! dispatch_request_handler { ($dispatch_tx:expr, $handler:expr) => {{ let dispatch_tx = $dispatch_tx.clone(); async move |args, responder, _connection| { - dispatch_tx - .unbounded_send(Box::new(move |cx, ctx| { - $handler(args, responder, cx, ctx); - })) - .log_err(); + if dispatch_tx.is_closed() { + log::error!("dispatch channel closed, cannot handle request"); + responder + .respond_with_error(acp::Error::internal_error()) + .log_err(); + } else { + dispatch_tx + .unbounded_send(Box::new(move |cx, ctx| { + $handler(args, responder, cx, ctx); + })) + .log_err(); + } Ok(()) } }}; @@ -310,43 +318,40 @@ impl AcpConnection { let (dispatch_tx, dispatch_rx) = mpsc::unbounded::(); // Build a tapped transport that intercepts raw JSON-RPC lines for - // the ACP logs panel. We replicate the ByteStreams→Lines conversion - // manually so we can wrap the stream and sink with inspection. - let (stream_tap_tx, stream_tap_rx) = smol::channel::bounded::(4096); + // the ACP logs panel. Raw lines are sent without parsing — deserialization + // is deferred until a subscriber is actually listening. + let (stream_tap_tx, stream_tap_rx) = smol::channel::unbounded::(); let incoming_lines = futures::io::BufReader::new(stdout).lines(); let tapped_incoming = incoming_lines.inspect({ let tap_tx = stream_tap_tx.clone(); move |result| { if let Ok(line) = result { - if let Some(msg) = - StreamMessage::from_json_line(StreamMessageDirection::Incoming, line) - { - tap_tx.try_send(msg).ok(); - } + tap_tx + .try_send(RawStreamLine { + direction: StreamMessageDirection::Incoming, + line: Arc::from(line.as_str()), + }) + .ok(); } } }); - let outgoing_sink = - futures::sink::unfold(Box::pin(stdin), async move |mut writer, line: String| { + let tapped_outgoing = futures::sink::unfold( + (Box::pin(stdin), stream_tap_tx), + async move |(mut writer, tap_tx), line: String| { use futures::AsyncWriteExt; - let mut bytes = line.into_bytes(); - bytes.push(b'\n'); - writer.write_all(&bytes).await?; - Ok::<_, std::io::Error>(writer) - }); - let tapped_outgoing = futures::SinkExt::with(outgoing_sink, { - let tap_tx = stream_tap_tx; - move |line: String| { - if let Some(msg) = - StreamMessage::from_json_line(StreamMessageDirection::Outgoing, &line) - { - tap_tx.try_send(msg).ok(); - } - futures::future::ok::(line) - } - }); + writer.write_all(line.as_bytes()).await?; + writer.write_all(b"\n").await?; + tap_tx + .try_send(RawStreamLine { + direction: StreamMessageDirection::Outgoing, + line: Arc::from(line.as_str()), + }) + .ok(); + Ok::<_, std::io::Error>((writer, tap_tx)) + }, + ); let transport = Lines::new(tapped_outgoing, tapped_incoming); @@ -402,7 +407,11 @@ impl AcpConnection { .connect_with( transport, move |connection: ConnectionTo| async move { - connection_tx.send(connection.clone()).ok(); + if connection_tx.send(connection.clone()).is_err() { + log::error!( + "failed to send ACP connection handle — receiver was dropped" + ); + } // Keep the connection alive until the transport closes. futures::future::pending::>().await }, @@ -1768,7 +1777,8 @@ fn handle_session_notification( cx: &mut AsyncApp, ctx: &ClientContext, ) { - let (thread, update_clone) = { + // Extract everything we need from the session while briefly borrowing. + let (thread, session_modes, config_opts_data, update_clone) = { let sessions = ctx.sessions.borrow(); let Some(session) = sessions.get(¬ification.session_id) else { log::warn!( @@ -1777,77 +1787,80 @@ fn handle_session_notification( ); return; }; + ( + session.thread.clone(), + session.session_modes.clone(), + session + .config_options + .as_ref() + .map(|opts| (opts.config_options.clone(), opts.tx.clone())), + notification.update.clone(), + ) + }; + // Borrow is dropped here. - if let acp::SessionUpdate::CurrentModeUpdate(acp::CurrentModeUpdate { - current_mode_id, - .. - }) = ¬ification.update - { - if let Some(session_modes) = &session.session_modes { - session_modes.borrow_mut().current_mode_id = current_mode_id.clone(); - } - } - - if let acp::SessionUpdate::ConfigOptionUpdate(acp::ConfigOptionUpdate { - config_options, - .. - }) = ¬ification.update - { - if let Some(opts) = &session.config_options { - *opts.config_options.borrow_mut() = config_options.clone(); - opts.tx.borrow_mut().send(()).ok(); - } + // Apply mode/config/session_list updates without holding the borrow. + if let acp::SessionUpdate::CurrentModeUpdate(acp::CurrentModeUpdate { + current_mode_id, .. + }) = ¬ification.update + { + if let Some(session_modes) = &session_modes { + session_modes.borrow_mut().current_mode_id = current_mode_id.clone(); } + } - if let acp::SessionUpdate::SessionInfoUpdate(info_update) = ¬ification.update - && let Some(session_list) = ctx.session_list.borrow().as_ref() - { - session_list.send_info_update(notification.session_id.clone(), info_update.clone()); + if let acp::SessionUpdate::ConfigOptionUpdate(acp::ConfigOptionUpdate { + config_options, .. + }) = ¬ification.update + { + if let Some((config_opts_cell, tx_cell)) = &config_opts_data { + *config_opts_cell.borrow_mut() = config_options.clone(); + tx_cell.borrow_mut().send(()).ok(); } + } - let update_clone = notification.update.clone(); - let thread = session.thread.clone(); + if let acp::SessionUpdate::SessionInfoUpdate(info_update) = ¬ification.update + && let Some(session_list) = ctx.session_list.borrow().as_ref() + { + session_list.send_info_update(notification.session_id.clone(), info_update.clone()); + } - // Pre-handle: if a ToolCall carries terminal_info, create/register a display-only terminal. - if let acp::SessionUpdate::ToolCall(tc) = &update_clone { - if let Some(meta) = &tc.meta { - if let Some(terminal_info) = meta.get("terminal_info") { - if let Some(id_str) = terminal_info.get("terminal_id").and_then(|v| v.as_str()) - { - let terminal_id = acp::TerminalId::new(id_str); - let cwd = terminal_info - .get("cwd") - .and_then(|v| v.as_str().map(PathBuf::from)); + // Pre-handle: if a ToolCall carries terminal_info, create/register a display-only terminal. + if let acp::SessionUpdate::ToolCall(tc) = &update_clone { + if let Some(meta) = &tc.meta { + if let Some(terminal_info) = meta.get("terminal_info") { + if let Some(id_str) = terminal_info.get("terminal_id").and_then(|v| v.as_str()) { + let terminal_id = acp::TerminalId::new(id_str); + let cwd = terminal_info + .get("cwd") + .and_then(|v| v.as_str().map(PathBuf::from)); - let _ = thread.update(cx, |thread, cx| { - let builder = TerminalBuilder::new_display_only( - CursorShape::default(), - AlternateScroll::On, - None, - 0, - cx.background_executor(), - thread.project().read(cx).path_style(cx), - )?; - let lower = cx.new(|cx| builder.subscribe(cx)); - thread.on_terminal_provider_event( - TerminalProviderEvent::Created { - terminal_id, - label: tc.title.clone(), - cwd, - output_byte_limit: None, - terminal: lower, - }, - cx, - ); - anyhow::Ok(()) - }); - } + let _ = thread.update(cx, |thread, cx| { + let builder = TerminalBuilder::new_display_only( + CursorShape::default(), + AlternateScroll::On, + None, + 0, + cx.background_executor(), + thread.project().read(cx).path_style(cx), + )?; + let lower = cx.new(|cx| builder.subscribe(cx)); + thread.on_terminal_provider_event( + TerminalProviderEvent::Created { + terminal_id, + label: tc.title.clone(), + cwd, + output_byte_limit: None, + terminal: lower, + }, + cx, + ); + anyhow::Ok(()) + }); } } } - - (thread, update_clone) - }; + } // Forward the update to the acp_thread as usual. if let Err(err) = thread From c340c44e6c85fc338663cbb90c86fda22ceb9951 Mon Sep 17 00:00:00 2001 From: Ben Brandt Date: Thu, 2 Apr 2026 17:10:02 +0200 Subject: [PATCH 07/20] more cleanup --- crates/acp_tools/src/acp_tools.rs | 12 +++- crates/agent_servers/src/acp.rs | 97 ++++++++++++++++--------------- 2 files changed, 61 insertions(+), 48 deletions(-) diff --git a/crates/acp_tools/src/acp_tools.rs b/crates/acp_tools/src/acp_tools.rs index 4876456fcbcecc..94d8cff0c8d4d3 100644 --- a/crates/acp_tools/src/acp_tools.rs +++ b/crates/acp_tools/src/acp_tools.rs @@ -71,7 +71,7 @@ impl StreamMessage { let acp_err = serde_json::from_value::(error.clone()).unwrap_or_else(|err| { log::warn!("Failed to deserialize ACP error: {err}"); - acp::Error::internal_error() + acp::Error::internal_error().data(error.to_string()) }); StreamMessageContent::Response { id: id.clone(), @@ -165,6 +165,15 @@ impl AcpConnectionRegistry { }) .ok(); } + + // The transport closed — clear state so observers (e.g. the ACP + // logs tab) can transition back to the disconnected state. + this.update(cx, |this, cx| { + this.active_agent_id = None; + this.subscribers.clear(); + cx.notify(); + }) + .ok(); })); cx.notify(); @@ -224,6 +233,7 @@ impl AcpTools { }; let Some(agent_id) = agent_id else { + self.watched_connection = None; return; }; diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs index 830d74546eeed0..7fc6855d19a8f4 100644 --- a/crates/agent_servers/src/acp.rs +++ b/crates/agent_servers/src/acp.rs @@ -229,17 +229,14 @@ macro_rules! dispatch_request_handler { ($dispatch_tx:expr, $handler:expr) => {{ let dispatch_tx = $dispatch_tx.clone(); async move |args, responder, _connection| { - if dispatch_tx.is_closed() { + if let Err(_) = dispatch_tx.unbounded_send(Box::new(move |cx, ctx| { + $handler(args, responder, cx, ctx); + })) { + // The dispatch channel is closed — the AcpConnection is being + // torn down and the child process is being killed. The responder + // inside the work item drops without responding; the agent won't + // be around to notice since the transport is also closing. log::error!("dispatch channel closed, cannot handle request"); - responder - .respond_with_error(acp::Error::internal_error()) - .log_err(); - } else { - dispatch_tx - .unbounded_send(Box::new(move |cx, ctx| { - $handler(args, responder, cx, ctx); - })) - .log_err(); } Ok(()) } @@ -1835,28 +1832,30 @@ fn handle_session_notification( .get("cwd") .and_then(|v| v.as_str().map(PathBuf::from)); - let _ = thread.update(cx, |thread, cx| { - let builder = TerminalBuilder::new_display_only( - CursorShape::default(), - AlternateScroll::On, - None, - 0, - cx.background_executor(), - thread.project().read(cx).path_style(cx), - )?; - let lower = cx.new(|cx| builder.subscribe(cx)); - thread.on_terminal_provider_event( - TerminalProviderEvent::Created { - terminal_id, - label: tc.title.clone(), - cwd, - output_byte_limit: None, - terminal: lower, - }, - cx, - ); - anyhow::Ok(()) - }); + thread + .update(cx, |thread, cx| { + let builder = TerminalBuilder::new_display_only( + CursorShape::default(), + AlternateScroll::On, + None, + 0, + cx.background_executor(), + thread.project().read(cx).path_style(cx), + )?; + let lower = cx.new(|cx| builder.subscribe(cx)); + thread.on_terminal_provider_event( + TerminalProviderEvent::Created { + terminal_id, + label: tc.title.clone(), + cwd, + output_byte_limit: None, + terminal: lower, + }, + cx, + ); + anyhow::Ok(()) + }) + .log_err(); } } } @@ -1883,12 +1882,14 @@ fn handle_session_notification( let terminal_id = acp::TerminalId::new(id_str); if let Some(s) = term_out.get("data").and_then(|v| v.as_str()) { let data = s.as_bytes().to_vec(); - let _ = thread.update(cx, |thread, cx| { - thread.on_terminal_provider_event( - TerminalProviderEvent::Output { terminal_id, data }, - cx, - ); - }); + thread + .update(cx, |thread, cx| { + thread.on_terminal_provider_event( + TerminalProviderEvent::Output { terminal_id, data }, + cx, + ); + }) + .log_err(); } } } @@ -1909,15 +1910,17 @@ fn handle_session_notification( .and_then(|v| v.as_str().map(|s| s.to_string())), ); - let _ = thread.update(cx, |thread, cx| { - thread.on_terminal_provider_event( - TerminalProviderEvent::Exit { - terminal_id, - status, - }, - cx, - ); - }); + thread + .update(cx, |thread, cx| { + thread.on_terminal_provider_event( + TerminalProviderEvent::Exit { + terminal_id, + status, + }, + cx, + ); + }) + .log_err(); } } } From f49365dd4cae27fdd4e57c3423b3fe695ebfe4f6 Mon Sep 17 00:00:00 2001 From: Ben Brandt Date: Thu, 2 Apr 2026 17:13:01 +0200 Subject: [PATCH 08/20] Unused dep --- Cargo.lock | 1 - crates/agent_servers/Cargo.toml | 1 - 2 files changed, 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bd82df022a65d6..e40189c3fc0a95 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -275,7 +275,6 @@ dependencies = [ "action_log", "agent-client-protocol-core", "anyhow", - "async-trait", "chrono", "client", "collections", diff --git a/crates/agent_servers/Cargo.toml b/crates/agent_servers/Cargo.toml index 1542466be35bbc..1afd0aa902ed58 100644 --- a/crates/agent_servers/Cargo.toml +++ b/crates/agent_servers/Cargo.toml @@ -22,7 +22,6 @@ acp_thread.workspace = true action_log.workspace = true agent-client-protocol.workspace = true anyhow.workspace = true -async-trait.workspace = true chrono.workspace = true client.workspace = true collections.workspace = true From d4fb440ffce90e52bebf29b6aa96a85435109de1 Mon Sep 17 00:00:00 2001 From: Ben Brandt Date: Thu, 2 Apr 2026 19:07:48 +0200 Subject: [PATCH 09/20] clean up --- crates/acp_tools/src/acp_tools.rs | 8 +++---- crates/agent_servers/src/acp.rs | 37 ++++++++++++++++--------------- 2 files changed, 23 insertions(+), 22 deletions(-) diff --git a/crates/acp_tools/src/acp_tools.rs b/crates/acp_tools/src/acp_tools.rs index 94d8cff0c8d4d3..c048c1cf5fda20 100644 --- a/crates/acp_tools/src/acp_tools.rs +++ b/crates/acp_tools/src/acp_tools.rs @@ -160,10 +160,10 @@ impl AcpConnectionRegistry { this.subscribers.retain(|sender| !sender.is_closed()); for sender in &this.subscribers { - sender.try_send(message.clone()).ok(); + sender.try_send(message.clone()).log_err(); } }) - .ok(); + .log_err(); } // The transport closed — clear state so observers (e.g. the ACP @@ -173,7 +173,7 @@ impl AcpConnectionRegistry { this.subscribers.clear(); cx.notify(); }) - .ok(); + .log_err(); })); cx.notify(); @@ -252,7 +252,7 @@ impl AcpTools { this.update(cx, |this, cx| { this.push_stream_message(message, cx); }) - .ok(); + .log_err(); } }); diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs index 7fc6855d19a8f4..0eb047fe2592be 100644 --- a/crates/agent_servers/src/acp.rs +++ b/crates/agent_servers/src/acp.rs @@ -229,14 +229,14 @@ macro_rules! dispatch_request_handler { ($dispatch_tx:expr, $handler:expr) => {{ let dispatch_tx = $dispatch_tx.clone(); async move |args, responder, _connection| { - if let Err(_) = dispatch_tx.unbounded_send(Box::new(move |cx, ctx| { - $handler(args, responder, cx, ctx); - })) { - // The dispatch channel is closed — the AcpConnection is being - // torn down and the child process is being killed. The responder - // inside the work item drops without responding; the agent won't - // be around to notice since the transport is also closing. - log::error!("dispatch channel closed, cannot handle request"); + if dispatch_tx.is_closed() { + respond_err(responder, acp::Error::internal_error()); + } else { + dispatch_tx + .unbounded_send(Box::new(move |cx, ctx| { + $handler(args, responder, cx, ctx); + })) + .log_err(); } Ok(()) } @@ -329,7 +329,7 @@ impl AcpConnection { direction: StreamMessageDirection::Incoming, line: Arc::from(line.as_str()), }) - .ok(); + .log_err(); } } }); @@ -338,14 +338,15 @@ impl AcpConnection { (Box::pin(stdin), stream_tap_tx), async move |(mut writer, tap_tx), line: String| { use futures::AsyncWriteExt; - writer.write_all(line.as_bytes()).await?; - writer.write_all(b"\n").await?; tap_tx .try_send(RawStreamLine { direction: StreamMessageDirection::Outgoing, line: Arc::from(line.as_str()), }) - .ok(); + .log_err(); + let mut bytes = line.into_bytes(); + bytes.push(b'\n'); + writer.write_all(&bytes).await?; Ok::<_, std::io::Error>((writer, tap_tx)) }, ); @@ -1713,12 +1714,13 @@ fn handle_write_text_file( cx.spawn(async move |cx| { let result: Result<_, acp::Error> = async { - let task = thread + thread .update(cx, |thread, cx| { thread.write_text_file(args.path, args.content, cx) }) + .map_err(acp::Error::from)? + .await .map_err(acp::Error::from)?; - task.await.map_err(acp::Error::from)?; Ok(()) } .await; @@ -1775,7 +1777,7 @@ fn handle_session_notification( ctx: &ClientContext, ) { // Extract everything we need from the session while briefly borrowing. - let (thread, session_modes, config_opts_data, update_clone) = { + let (thread, session_modes, config_opts_data) = { let sessions = ctx.sessions.borrow(); let Some(session) = sessions.get(¬ification.session_id) else { log::warn!( @@ -1791,7 +1793,6 @@ fn handle_session_notification( .config_options .as_ref() .map(|opts| (opts.config_options.clone(), opts.tx.clone())), - notification.update.clone(), ) }; // Borrow is dropped here. @@ -1823,7 +1824,7 @@ fn handle_session_notification( } // Pre-handle: if a ToolCall carries terminal_info, create/register a display-only terminal. - if let acp::SessionUpdate::ToolCall(tc) = &update_clone { + if let acp::SessionUpdate::ToolCall(tc) = ¬ification.update { if let Some(meta) = &tc.meta { if let Some(terminal_info) = meta.get("terminal_info") { if let Some(id_str) = terminal_info.get("terminal_id").and_then(|v| v.as_str()) { @@ -1875,7 +1876,7 @@ fn handle_session_notification( } // Post-handle: stream terminal output/exit if present on ToolCallUpdate meta. - if let acp::SessionUpdate::ToolCallUpdate(tcu) = &update_clone { + if let acp::SessionUpdate::ToolCallUpdate(tcu) = ¬ification.update { if let Some(meta) = &tcu.meta { if let Some(term_out) = meta.get("terminal_output") { if let Some(id_str) = term_out.get("terminal_id").and_then(|v| v.as_str()) { From 9ad785b4bbec1574e8b9d7a3928013481226e529 Mon Sep 17 00:00:00 2001 From: Ben Brandt Date: Thu, 2 Apr 2026 19:17:11 +0200 Subject: [PATCH 10/20] more --- crates/agent_servers/src/acp.rs | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs index 0eb047fe2592be..236558e8870cea 100644 --- a/crates/agent_servers/src/acp.rs +++ b/crates/agent_servers/src/acp.rs @@ -58,7 +58,10 @@ fn into_foreground_future( }); async move { spawn_result?; - rx.await.map_err(|_| acp::Error::internal_error())? + rx.await.map_err(|_| { + acp::Error::internal_error() + .data("response channel cancelled — connection may have dropped") + })? } } @@ -229,15 +232,11 @@ macro_rules! dispatch_request_handler { ($dispatch_tx:expr, $handler:expr) => {{ let dispatch_tx = $dispatch_tx.clone(); async move |args, responder, _connection| { - if dispatch_tx.is_closed() { - respond_err(responder, acp::Error::internal_error()); - } else { - dispatch_tx - .unbounded_send(Box::new(move |cx, ctx| { - $handler(args, responder, cx, ctx); - })) - .log_err(); - } + dispatch_tx + .unbounded_send(Box::new(move |cx, ctx| { + $handler(args, responder, cx, ctx); + })) + .log_err(); Ok(()) } }}; From 561b141902b632abaa17859394713aba52120e81 Mon Sep 17 00:00:00 2001 From: Ben Brandt Date: Thu, 16 Apr 2026 22:29:42 +0200 Subject: [PATCH 11/20] Update test helper --- Cargo.lock | 5 +- Cargo.toml | 2 +- crates/agent_servers/Cargo.toml | 1 - crates/agent_servers/src/acp.rs | 187 +++++++++++++++----------------- 4 files changed, 90 insertions(+), 105 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2e9c50542b6e21..e12b1483ed4801 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -223,7 +223,7 @@ dependencies = [ [[package]] name = "agent-client-protocol-core" version = "0.1.0" -source = "git+https://github.com/agentclientprotocol/rust-sdk?rev=9fa32bb04e301f4be968a372eb5085dc3a86ef3c#9fa32bb04e301f4be968a372eb5085dc3a86ef3c" +source = "git+https://github.com/agentclientprotocol/rust-sdk?rev=4444454f6c7735bf224ee5d7d2193b2ebeaeeb60#4444454f6c7735bf224ee5d7d2193b2ebeaeeb60" dependencies = [ "agent-client-protocol-derive", "agent-client-protocol-schema", @@ -247,7 +247,7 @@ dependencies = [ [[package]] name = "agent-client-protocol-derive" version = "0.1.0" -source = "git+https://github.com/agentclientprotocol/rust-sdk?rev=9fa32bb04e301f4be968a372eb5085dc3a86ef3c#9fa32bb04e301f4be968a372eb5085dc3a86ef3c" +source = "git+https://github.com/agentclientprotocol/rust-sdk?rev=4444454f6c7735bf224ee5d7d2193b2ebeaeeb60#4444454f6c7735bf224ee5d7d2193b2ebeaeeb60" dependencies = [ "proc-macro2", "quote", @@ -293,7 +293,6 @@ dependencies = [ "libc", "log", "nix 0.29.0", - "piper", "project", "release_channel", "remote", diff --git a/Cargo.toml b/Cargo.toml index bc8041248da80c..76da8f22d22d70 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -494,7 +494,7 @@ ztracing_macro = { path = "crates/ztracing_macro" } # External crates # -agent-client-protocol = { package = "agent-client-protocol-core", git = "https://github.com/agentclientprotocol/rust-sdk", rev = "9fa32bb04e301f4be968a372eb5085dc3a86ef3c", features = ["unstable"] } +agent-client-protocol = { package = "agent-client-protocol-core", git = "https://github.com/agentclientprotocol/rust-sdk", rev = "4444454f6c7735bf224ee5d7d2193b2ebeaeeb60", features = ["unstable"] } aho-corasick = "1.1" alacritty_terminal = { git = "https://github.com/zed-industries/alacritty", rev = "9d9640d4" } any_vec = "0.14" diff --git a/crates/agent_servers/Cargo.toml b/crates/agent_servers/Cargo.toml index cb7237a0313af1..d279e613c6f6e4 100644 --- a/crates/agent_servers/Cargo.toml +++ b/crates/agent_servers/Cargo.toml @@ -67,7 +67,6 @@ indoc.workspace = true acp_thread = { workspace = true, features = ["test-support"] } gpui = { workspace = true, features = ["test-support"] } gpui_tokio.workspace = true -piper = "0.2" project = { workspace = true, features = ["test-support"] } reqwest_client = { workspace = true, features = ["test-support"] } settings = { workspace = true, features = ["test-support"] } diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs index ae83b8374aaaa2..311011ac205e38 100644 --- a/crates/agent_servers/src/acp.rs +++ b/crates/agent_servers/src/acp.rs @@ -617,7 +617,6 @@ impl AcpConnection { agent_capabilities: acp::AgentCapabilities, agent_server_store: WeakEntity, io_task: Task<()>, - dispatch_task: Task<()>, _cx: &mut App, ) -> Self { Self { @@ -635,7 +634,7 @@ impl AcpConnection { child: None, session_list: None, _io_task: io_task, - _dispatch_task: dispatch_task, + _dispatch_task: Task::ready(()), _wait_task: Task::ready(Ok(())), _stderr_task: Task::ready(Ok(())), } @@ -1550,68 +1549,6 @@ mod tests { assert_eq!(task.label, "Login"); } - struct FakeAcpAgent { - load_session_count: Arc, - close_session_count: Arc, - } - - #[async_trait::async_trait(?Send)] - impl acp::Agent for FakeAcpAgent { - async fn initialize( - &self, - args: acp::InitializeRequest, - ) -> acp::Result { - Ok( - acp::InitializeResponse::new(args.protocol_version).agent_capabilities( - acp::AgentCapabilities::default() - .load_session(true) - .session_capabilities( - acp::SessionCapabilities::default() - .close(acp::SessionCloseCapabilities::new()), - ), - ), - ) - } - - async fn authenticate( - &self, - _: acp::AuthenticateRequest, - ) -> acp::Result { - Ok(Default::default()) - } - - async fn new_session( - &self, - _: acp::NewSessionRequest, - ) -> acp::Result { - Ok(acp::NewSessionResponse::new(acp::SessionId::new("unused"))) - } - - async fn prompt(&self, _: acp::PromptRequest) -> acp::Result { - Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)) - } - - async fn cancel(&self, _: acp::CancelNotification) -> acp::Result<()> { - Ok(()) - } - - async fn load_session( - &self, - _: acp::LoadSessionRequest, - ) -> acp::Result { - self.load_session_count.fetch_add(1, Ordering::SeqCst); - Ok(acp::LoadSessionResponse::new()) - } - - async fn close_session( - &self, - _: acp::CloseSessionRequest, - ) -> acp::Result { - self.close_session_count.fetch_add(1, Ordering::SeqCst); - Ok(acp::CloseSessionResponse::new()) - } - } - async fn connect_fake_agent( cx: &mut gpui::TestAppContext, ) -> ( @@ -1633,50 +1570,100 @@ mod tests { let load_count = Arc::new(AtomicUsize::new(0)); let close_count = Arc::new(AtomicUsize::new(0)); - let (c2a_reader, c2a_writer) = piper::pipe(4096); - let (a2c_reader, a2c_writer) = piper::pipe(4096); + let (client_transport, agent_transport) = agent_client_protocol::Channel::duplex(); let sessions: Rc>> = Rc::new(RefCell::new(HashMap::default())); - let session_list_container: Rc>>> = - Rc::new(RefCell::new(None)); - - let foreground = cx.foreground_executor().clone(); - let client_delegate = ClientDelegate { - sessions: sessions.clone(), - session_list: session_list_container, - cx: cx.to_async(), - }; - - let (client_conn, client_io_task) = - acp::ClientSideConnection::new(client_delegate, c2a_writer, a2c_reader, { - let foreground = foreground.clone(); - move |fut| { - foreground.spawn(fut).detach(); - } - }); + // 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() + .name("fake-agent") + .on_receive_request( + async move |req: acp::InitializeRequest, responder, _cx| { + responder.respond( + acp::InitializeResponse::new(req.protocol_version).agent_capabilities( + acp::AgentCapabilities::default() + .load_session(true) + .session_capabilities( + acp::SessionCapabilities::default() + .close(acp::SessionCloseCapabilities::new()), + ), + ), + ) + }, + agent_client_protocol::on_receive_request!(), + ) + .on_receive_request( + async move |_req: acp::AuthenticateRequest, responder, _cx| { + responder.respond(Default::default()) + }, + agent_client_protocol::on_receive_request!(), + ) + .on_receive_request( + async move |_req: acp::NewSessionRequest, responder, _cx| { + responder.respond(acp::NewSessionResponse::new(acp::SessionId::new("unused"))) + }, + agent_client_protocol::on_receive_request!(), + ) + .on_receive_request( + async move |_req: acp::PromptRequest, responder, _cx| { + responder.respond(acp::PromptResponse::new(acp::StopReason::EndTurn)) + }, + agent_client_protocol::on_receive_request!(), + ) + .on_receive_request( + { + let load_count = load_count.clone(); + async move |_req: acp::LoadSessionRequest, responder, _cx| { + load_count.fetch_add(1, Ordering::SeqCst); + responder.respond(acp::LoadSessionResponse::new()) + } + }, + agent_client_protocol::on_receive_request!(), + ) + .on_receive_request( + { + let close_count = close_count.clone(); + async move |_req: acp::CloseSessionRequest, responder, _cx| { + close_count.fetch_add(1, Ordering::SeqCst); + responder.respond(acp::CloseSessionResponse::new()) + } + }, + agent_client_protocol::on_receive_request!(), + ) + .on_receive_notification( + async move |_notif: acp::CancelNotification, _cx| Ok(()), + agent_client_protocol::on_receive_notification!(), + ) + .connect_to(agent_transport); - let fake_agent = FakeAcpAgent { - load_session_count: load_count.clone(), - close_session_count: close_count.clone(), - }; + let agent_io_task = cx.background_spawn(agent_future); - let (_, agent_io_task) = - acp::AgentSideConnection::new(fake_agent, a2c_writer, c2a_reader, { - let foreground = foreground.clone(); - move |fut| { - foreground.spawn(fut).detach(); - } - }); + // Build the client side and capture the `ConnectionTo` handle. + let (connection_tx, connection_rx) = futures::channel::oneshot::channel(); + let client_future = Client.builder().name("zed-test").connect_with( + client_transport, + move |connection: ConnectionTo| async move { + connection_tx.send(connection).ok(); + futures::future::pending::>().await + }, + ); - let client_io_task = cx.background_spawn(client_io_task); - let agent_io_task = cx.background_spawn(agent_io_task); + let client_io_task = cx.background_spawn(async move { + client_future.await.ok(); + }); - let response = client_conn - .initialize(acp::InitializeRequest::new(acp::ProtocolVersion::V1)) + let client_conn: ConnectionTo = connection_rx .await - .expect("failed to initialize ACP connection"); + .expect("failed to receive ACP connection handle"); + + let response = into_foreground_future( + client_conn.send_request(acp::InitializeRequest::new(acp::ProtocolVersion::V1)), + ) + .await + .expect("failed to initialize ACP connection"); let agent_capabilities = response.agent_capabilities; @@ -1685,7 +1672,7 @@ mod tests { let connection = cx.update(|cx| { AcpConnection::new_for_test( - Rc::new(client_conn), + client_conn, sessions, agent_capabilities, agent_server_store, From 37688049caaff467402db6a2ac8442a157433679 Mon Sep 17 00:00:00 2001 From: Ben Brandt Date: Thu, 16 Apr 2026 22:35:04 +0200 Subject: [PATCH 12/20] Clean up imports --- crates/agent_servers/src/agent_servers.rs | 30 +++++++++++++++-------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/crates/agent_servers/src/agent_servers.rs b/crates/agent_servers/src/agent_servers.rs index 37e77c80c79683..d910add67eb817 100644 --- a/crates/agent_servers/src/agent_servers.rs +++ b/crates/agent_servers/src/agent_servers.rs @@ -12,9 +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::{ - ModelId, SessionConfigId, SessionConfigValueId, SessionModeId, -}; +use agent_client_protocol::schema as acp_schema; use anyhow::Result; use gpui::{App, AppContext, Entity, Task}; use settings::SettingsStore; @@ -51,19 +49,31 @@ pub trait AgentServer: Send { fn into_any(self: Rc) -> Rc; - fn default_mode(&self, _cx: &App) -> Option { + fn default_mode(&self, _cx: &App) -> Option { None } - fn set_default_mode(&self, _mode_id: Option, _fs: Arc, _cx: &mut App) {} + fn set_default_mode( + &self, + _mode_id: Option, + _fs: Arc, + _cx: &mut App, + ) { + } - fn default_model(&self, _cx: &App) -> Option { + fn default_model(&self, _cx: &App) -> Option { None } - fn set_default_model(&self, _model_id: Option, _fs: Arc, _cx: &mut App) {} + fn set_default_model( + &self, + _model_id: Option, + _fs: Arc, + _cx: &mut App, + ) { + } - fn favorite_model_ids(&self, _cx: &mut App) -> HashSet { + fn favorite_model_ids(&self, _cx: &mut App) -> HashSet { HashSet::default() } @@ -84,7 +94,7 @@ pub trait AgentServer: Send { &self, _config_id: &SessionConfigId, _cx: &mut App, - ) -> HashSet { + ) -> HashSet { HashSet::default() } @@ -100,7 +110,7 @@ pub trait AgentServer: Send { fn toggle_favorite_model( &self, - _model_id: ModelId, + _model_id: acp_schema::ModelId, _should_be_favorite: bool, _fs: Arc, _cx: &App, From a9e0ec5216792c178cb1901d246e21e69774cd6c Mon Sep 17 00:00:00 2001 From: Ben Brandt Date: Thu, 16 Apr 2026 22:40:17 +0200 Subject: [PATCH 13/20] More imports --- crates/agent_servers/src/agent_servers.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/agent_servers/src/agent_servers.rs b/crates/agent_servers/src/agent_servers.rs index d910add67eb817..2dc8141a6dd56c 100644 --- a/crates/agent_servers/src/agent_servers.rs +++ b/crates/agent_servers/src/agent_servers.rs @@ -92,7 +92,7 @@ pub trait AgentServer: Send { fn favorite_config_option_value_ids( &self, - _config_id: &SessionConfigId, + _config_id: &acp_schema::SessionConfigId, _cx: &mut App, ) -> HashSet { HashSet::default() @@ -100,8 +100,8 @@ pub trait AgentServer: Send { fn toggle_favorite_config_option_value( &self, - _config_id: SessionConfigId, - _value_id: SessionConfigValueId, + _config_id: acp_schema::SessionConfigId, + _value_id: acp_schema::SessionConfigValueId, _should_be_favorite: bool, _fs: Arc, _cx: &App, From fe3816041b614bfcab07cfa70411456a41c7ecb9 Mon Sep 17 00:00:00 2001 From: Ben Brandt Date: Thu, 16 Apr 2026 23:31:14 +0200 Subject: [PATCH 14/20] Preserve more logs --- crates/acp_tools/src/acp_tools.rs | 93 ++++++++++++++++++++++++++----- crates/agent_servers/src/acp.rs | 45 ++++++++++----- 2 files changed, 110 insertions(+), 28 deletions(-) diff --git a/crates/acp_tools/src/acp_tools.rs b/crates/acp_tools/src/acp_tools.rs index c048c1cf5fda20..5aad9f3a169da0 100644 --- a/crates/acp_tools/src/acp_tools.rs +++ b/crates/acp_tools/src/acp_tools.rs @@ -1,4 +1,8 @@ -use std::{collections::HashSet, fmt::Display, sync::Arc}; +use std::{ + collections::{HashSet, VecDeque}, + fmt::Display, + sync::Arc, +}; use agent_client_protocol::schema as acp; use collections::HashMap; @@ -19,10 +23,13 @@ use workspace::{ pub type RequestId = serde_json::Value; -#[derive(Clone)] +#[derive(Clone, Copy, PartialEq, Eq)] pub enum StreamMessageDirection { Incoming, Outgoing, + /// Lines captured from the agent's stderr. These are not part of the + /// JSON-RPC protocol, but agents often emit useful diagnostics there. + Stderr, } #[derive(Clone)] @@ -40,6 +47,8 @@ pub enum StreamMessageContent { method: Arc, params: Option, }, + /// A raw stderr line from the agent process. + Stderr { line: Arc }, } #[derive(Clone)] @@ -49,7 +58,21 @@ pub struct StreamMessage { } impl StreamMessage { - pub fn from_json_line(direction: StreamMessageDirection, line: &str) -> Option { + /// Build a `StreamMessage` from a raw line captured off the transport. + /// + /// For `Stderr`, the line is wrapped as-is (no JSON parsing). For + /// `Incoming`/`Outgoing`, the line is parsed as JSON-RPC; returns `None` + /// if it doesn't look like a valid JSON-RPC message. + pub fn from_raw_line(direction: StreamMessageDirection, line: &str) -> Option { + if direction == StreamMessageDirection::Stderr { + return Some(StreamMessage { + direction, + message: StreamMessageContent::Stderr { + line: Arc::from(line), + }, + }); + } + let value: serde_json::Value = serde_json::from_str(line).ok()?; let obj = value.as_object()?; @@ -110,17 +133,28 @@ struct GlobalAcpConnectionRegistry(Entity); impl Global for GlobalAcpConnectionRegistry {} -/// A raw JSON-RPC line captured from the transport, tagged with direction. -/// Deserialization into [`StreamMessage`] is deferred until a subscriber is listening. +/// A raw line captured from the transport (or from stderr), tagged with direction. +/// Deserialization into [`StreamMessage`] happens eagerly on arrival so that +/// the registry's ring buffer can be replayed to late subscribers. pub struct RawStreamLine { pub direction: StreamMessageDirection, pub line: Arc, } +/// Maximum number of messages retained in the registry's backlog. +/// +/// Mirrors `MAX_STORED_LOG_ENTRIES` in the LSP log store, so that opening the +/// ACP logs panel after a session has been running for a while still shows +/// meaningful history. +const MAX_BACKLOG_MESSAGES: usize = 2000; + #[derive(Default)] pub struct AcpConnectionRegistry { active_agent_id: Option, generation: u64, + /// Bounded ring buffer of every message observed on the current connection. + /// When a new connection is set, this is cleared. + backlog: VecDeque, subscribers: Vec>, _broadcast_task: Option>, } @@ -144,20 +178,22 @@ impl AcpConnectionRegistry { ) { self.active_agent_id = Some(agent_id); self.generation += 1; + self.backlog.clear(); self.subscribers.clear(); self._broadcast_task = Some(cx.spawn(async move |this, cx| { while let Ok(raw) = raw_rx.recv().await { this.update(cx, |this, _cx| { - if this.subscribers.is_empty() { - return; - } - - let Some(message) = StreamMessage::from_json_line(raw.direction, &raw.line) + let Some(message) = StreamMessage::from_raw_line(raw.direction, &raw.line) else { return; }; + if this.backlog.len() == MAX_BACKLOG_MESSAGES { + this.backlog.pop_front(); + } + this.backlog.push_back(message.clone()); + this.subscribers.retain(|sender| !sender.is_closed()); for sender in &this.subscribers { sender.try_send(message.clone()).log_err(); @@ -179,10 +215,17 @@ impl AcpConnectionRegistry { cx.notify(); } - pub fn subscribe(&mut self) -> smol::channel::Receiver { + /// Subscribe to messages on the current connection. + /// + /// Returns the existing backlog (already-observed messages) together with + /// a receiver for new messages. The caller is responsible for flushing the + /// backlog into its local state before draining the receiver, so that no + /// messages are dropped between the snapshot and live subscription. + pub fn subscribe(&mut self) -> (Vec, smol::channel::Receiver) { + let backlog = self.backlog.iter().cloned().collect(); let (sender, receiver) = smol::channel::unbounded(); self.subscribers.push(sender); - receiver + (backlog, receiver) } } @@ -243,7 +286,7 @@ impl AcpTools { } } - let messages_rx = self + let (backlog, messages_rx) = self .connection_registry .update(cx, |registry, _cx| registry.subscribe()); @@ -265,6 +308,10 @@ impl AcpTools { outgoing_request_methods: HashMap::default(), _task: task, }); + + for message in backlog { + self.push_stream_message(message, cx); + } } fn push_stream_message(&mut self, stream_message: StreamMessage, cx: &mut Context) { @@ -279,6 +326,8 @@ impl AcpTools { let method_map = match stream_message.direction { StreamMessageDirection::Incoming => &mut connection.incoming_request_methods, StreamMessageDirection::Outgoing => &mut connection.outgoing_request_methods, + // Stderr lines never carry request/response correlation. + StreamMessageDirection::Stderr => return, }; method_map.insert(id.clone(), method.clone()); @@ -288,6 +337,7 @@ impl AcpTools { let method_map = match stream_message.direction { StreamMessageDirection::Incoming => &mut connection.outgoing_request_methods, StreamMessageDirection::Outgoing => &mut connection.incoming_request_methods, + StreamMessageDirection::Stderr => return, }; if let Some(method) = method_map.remove(&id) { @@ -304,6 +354,17 @@ impl AcpTools { StreamMessageContent::Notification { method, params } => { (None, method.into(), MessageType::Notification, Ok(params)) } + StreamMessageContent::Stderr { line } => { + // Stderr is rendered as plain text inline with JSON-RPC traffic, + // using `stderr` as the pseudo-method name so it shows up in the + // header the same way real methods do. + ( + None, + "stderr".into(), + MessageType::Stderr, + Ok(Some(serde_json::Value::String(line.to_string()))), + ) + } }; let message = WatchedConnectionMessage { @@ -349,6 +410,7 @@ impl AcpTools { "_direction": match message.direction { StreamMessageDirection::Incoming => "incoming", StreamMessageDirection::Outgoing => "outgoing", + StreamMessageDirection::Stderr => "stderr", }, "_type": message.message_type.to_string().to_lowercase(), "id": message.request_id, @@ -436,6 +498,9 @@ impl AcpTools { StreamMessageDirection::Outgoing => Icon::new(IconName::ArrowUp) .color(Color::Success) .size(IconSize::Small), + StreamMessageDirection::Stderr => Icon::new(IconName::Warning) + .color(Color::Warning) + .size(IconSize::Small), }) .child( Label::new(message.name.clone()) @@ -567,6 +632,7 @@ enum MessageType { Request, Response, Notification, + Stderr, } impl Display for MessageType { @@ -575,6 +641,7 @@ impl Display for MessageType { MessageType::Request => write!(f, "Request"), MessageType::Response => write!(f, "Response"), MessageType::Notification => write!(f, "Notification"), + MessageType::Stderr => write!(f, "Stderr"), } } } diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs index 311011ac205e38..7b5e53e2fdbfb9 100644 --- a/crates/agent_servers/src/acp.rs +++ b/crates/agent_servers/src/acp.rs @@ -354,16 +354,15 @@ impl AcpConnection { // closures to the !Send foreground thread. let (dispatch_tx, dispatch_rx) = mpsc::unbounded::(); - // Build a tapped transport that intercepts raw JSON-RPC lines for - // the ACP logs panel. Raw lines are sent without parsing — deserialization - // is deferred until a subscriber is actually listening. + // Build a tapped transport that intercepts raw JSON-RPC lines, plus + // stderr lines, for the ACP logs panel. let (stream_tap_tx, stream_tap_rx) = smol::channel::unbounded::(); let incoming_lines = futures::io::BufReader::new(stdout).lines(); let tapped_incoming = incoming_lines.inspect({ let tap_tx = stream_tap_tx.clone(); - move |result| { - if let Ok(line) = result { + move |result| match result { + Ok(line) => { tap_tx .try_send(RawStreamLine { direction: StreamMessageDirection::Incoming, @@ -371,11 +370,17 @@ impl AcpConnection { }) .log_err(); } + Err(err) => { + // I/O errors on the transport are fatal for the SDK, but + // without logging them the ACP logs panel shows no trace + // of why the connection died. + log::warn!("ACP transport read error: {err}"); + } } }); let tapped_outgoing = futures::sink::unfold( - (Box::pin(stdin), stream_tap_tx), + (Box::pin(stdin), stream_tap_tx.clone()), async move |(mut writer, tap_tx), line: String| { use futures::AsyncWriteExt; tap_tx @@ -482,16 +487,26 @@ impl AcpConnection { } }); - let stderr_task = cx.background_spawn(async move { - let mut stderr = BufReader::new(stderr); - let mut line = String::new(); - while let Ok(n) = stderr.read_line(&mut line).await - && n > 0 - { - log::warn!("agent stderr: {}", line.trim()); - line.clear(); + let stderr_task = cx.background_spawn({ + let tap_tx = stream_tap_tx.clone(); + async move { + let mut stderr = BufReader::new(stderr); + let mut line = String::new(); + while let Ok(n) = stderr.read_line(&mut line).await + && n > 0 + { + let trimmed = line.trim_end_matches(['\n', '\r']); + log::warn!("agent stderr: {trimmed}"); + tap_tx + .try_send(RawStreamLine { + direction: StreamMessageDirection::Stderr, + line: Arc::from(trimmed), + }) + .log_err(); + line.clear(); + } + Ok(()) } - Ok(()) }); let wait_task = cx.spawn({ From 2cd672c54053fd08c5d42714226825cce6eb626f Mon Sep 17 00:00:00 2001 From: Ben Brandt Date: Tue, 21 Apr 2026 11:22:19 +0000 Subject: [PATCH 15/20] Update to latest version Co-authored-by: Ben Brandt --- Cargo.lock | 316 +++++++++++++++++++------------- Cargo.toml | 2 +- crates/agent_servers/src/acp.rs | 194 +++++++++----------- 3 files changed, 279 insertions(+), 233 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 08cd5b08356f7d..e5449ee408a1cc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7,7 +7,7 @@ name = "acp_thread" version = "0.1.0" dependencies = [ "action_log", - "agent-client-protocol-core", + "agent-client-protocol", "anyhow", "base64 0.22.1", "buffer_diff", @@ -51,7 +51,7 @@ dependencies = [ name = "acp_tools" version = "0.1.0" dependencies = [ - "agent-client-protocol-core", + "agent-client-protocol", "collections", "gpui", "language", @@ -148,7 +148,7 @@ version = "0.1.0" dependencies = [ "acp_thread", "action_log", - "agent-client-protocol-core", + "agent-client-protocol", "agent_servers", "agent_settings", "anyhow", @@ -192,7 +192,7 @@ dependencies = [ "regex", "reqwest_client", "rust-embed", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "settings", @@ -221,9 +221,10 @@ dependencies = [ ] [[package]] -name = "agent-client-protocol-core" -version = "0.1.0" -source = "git+https://github.com/agentclientprotocol/rust-sdk?rev=4444454f6c7735bf224ee5d7d2193b2ebeaeeb60#4444454f6c7735bf224ee5d7d2193b2ebeaeeb60" +name = "agent-client-protocol" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "598d0408bb054b4fc40c3f9f69da6fa0cab2d4afa9011e0227eed558857afaae" dependencies = [ "agent-client-protocol-derive", "agent-client-protocol-schema", @@ -234,7 +235,7 @@ dependencies = [ "jsonrpcmsg", "rmcp", "rustc-hash 2.1.1", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "thiserror 2.0.17", @@ -246,8 +247,9 @@ dependencies = [ [[package]] name = "agent-client-protocol-derive" -version = "0.1.0" -source = "git+https://github.com/agentclientprotocol/rust-sdk?rev=4444454f6c7735bf224ee5d7d2193b2ebeaeeb60#4444454f6c7735bf224ee5d7d2193b2ebeaeeb60" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce42c2d3c048c12897eef2e577dfff1e3355c632c9f1625cc953b9df48b44631" dependencies = [ "proc-macro2", "quote", @@ -256,16 +258,18 @@ dependencies = [ [[package]] name = "agent-client-protocol-schema" -version = "0.11.4" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca68e7e55681ce56546c0cecc6bc8f20493d24b44c6d93ec46174f310730bba2" +checksum = "49bae57dad1c28a362fbdcf7bab0583316a02b45a70792109fced55780a3b63c" dependencies = [ "anyhow", "derive_more", - "schemars", + "schemars 1.0.4", "serde", "serde_json", + "serde_with", "strum 0.28.0", + "tracing", ] [[package]] @@ -275,7 +279,7 @@ dependencies = [ "acp_thread", "acp_tools", "action_log", - "agent-client-protocol-core", + "agent-client-protocol", "anyhow", "async-pipe", "async-trait", @@ -318,7 +322,7 @@ dependencies = [ name = "agent_settings" version = "0.1.0" dependencies = [ - "agent-client-protocol-core", + "agent-client-protocol", "anyhow", "collections", "convert_case 0.8.0", @@ -330,7 +334,7 @@ dependencies = [ "paths", "project", "regex", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "serde_json_lenient", @@ -345,7 +349,7 @@ dependencies = [ "acp_thread", "action_log", "agent", - "agent-client-protocol-core", + "agent-client-protocol", "agent_servers", "agent_settings", "ai_onboarding", @@ -410,7 +414,7 @@ dependencies = [ "reqwest_client", "rope", "rules_library", - "schemars", + "schemars 1.0.4", "search", "semver", "serde", @@ -676,7 +680,7 @@ dependencies = [ "http_client", "language_model_core", "log", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "strum 0.27.2", @@ -1953,7 +1957,7 @@ dependencies = [ "aws-sdk-bedrockruntime", "aws-smithy-types", "futures 0.3.32", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "strum 0.27.2", @@ -1992,7 +1996,7 @@ dependencies = [ "bitflags 2.10.0", "cexpr", "clang-sys", - "itertools 0.10.5", + "itertools 0.11.0", "log", "prettyplease", "proc-macro2", @@ -2012,7 +2016,7 @@ dependencies = [ "bitflags 2.10.0", "cexpr", "clang-sys", - "itertools 0.10.5", + "itertools 0.11.0", "proc-macro2", "quote", "regex", @@ -2699,7 +2703,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eadd868a2ce9ca38de7eeafdcec9c7065ef89b42b32f0839278d55f35c54d1ff" dependencies = [ "heck 0.4.1", - "indexmap", + "indexmap 2.11.4", "log", "proc-macro2", "quote", @@ -3319,7 +3323,7 @@ dependencies = [ name = "collections" version = "0.1.0" dependencies = [ - "indexmap", + "indexmap 2.11.4", "rustc-hash 2.1.1", ] @@ -3575,7 +3579,7 @@ dependencies = [ "parking_lot", "postage", "rand 0.9.3", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "settings", @@ -4404,7 +4408,7 @@ checksum = "d74b6bcf49ebbd91f1b1875b706ea46545032a14003b5557b7dfa4bbeba6766e" dependencies = [ "cc", "codespan-reporting", - "indexmap", + "indexmap 2.11.4", "proc-macro2", "quote", "scratch", @@ -4419,7 +4423,7 @@ checksum = "94ca2ad69673c4b35585edfa379617ac364bccd0ba0adf319811ba3a74ffa48a" dependencies = [ "clap", "codespan-reporting", - "indexmap", + "indexmap 2.11.4", "proc-macro2", "quote", "syn 2.0.117", @@ -4437,7 +4441,7 @@ version = "1.0.187" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a8ebf0b6138325af3ec73324cb3a48b64d57721f17291b151206782e61f66cd" dependencies = [ - "indexmap", + "indexmap 2.11.4", "proc-macro2", "quote", "syn 2.0.117", @@ -4466,7 +4470,7 @@ dependencies = [ "parking_lot", "paths", "proto", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "settings", @@ -4483,7 +4487,7 @@ name = "dap-types" version = "0.0.1" source = "git+https://github.com/zed-industries/dap-types?rev=1b461b310481d01e02b2603c16d7144b926339f8#1b461b310481d01e02b2603c16d7144b926339f8" dependencies = [ - "schemars", + "schemars 1.0.4", "serde", "serde_json", ] @@ -4747,7 +4751,7 @@ dependencies = [ "pretty_assertions", "project", "rpc", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "serde_json_lenient", @@ -4787,7 +4791,7 @@ dependencies = [ "anyhow", "futures 0.3.32", "http_client", - "schemars", + "schemars 1.0.4", "serde", "serde_json", ] @@ -5066,7 +5070,7 @@ dependencies = [ "jsonschema", "mdbook", "regex", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "settings", @@ -5502,7 +5506,7 @@ dependencies = [ "release_channel", "rope", "rpc", - "schemars", + "schemars 1.0.4", "semver", "serde", "serde_json", @@ -5879,7 +5883,7 @@ version = "0.1.0" dependencies = [ "acp_thread", "agent", - "agent-client-protocol-core", + "agent-client-protocol", "agent_ui", "anyhow", "clap", @@ -6246,7 +6250,7 @@ dependencies = [ "fs", "gpui", "inventory", - "schemars", + "schemars 1.0.4", "serde_json", "settings", ] @@ -7199,7 +7203,7 @@ dependencies = [ "derive_more", "derive_setters", "gh-workflow-macros", - "indexmap", + "indexmap 2.11.4", "merge", "serde", "serde_json", @@ -7244,7 +7248,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" dependencies = [ "fallible-iterator", - "indexmap", + "indexmap 2.11.4", "stable_deref_trait", ] @@ -7281,7 +7285,7 @@ dependencies = [ "rand 0.9.3", "regex", "rope", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "smallvec", @@ -7403,7 +7407,7 @@ dependencies = [ "rand 0.9.3", "remote", "remote_connection", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "settings", @@ -7589,7 +7593,7 @@ dependencies = [ "http_client", "language_model_core", "log", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "strum 0.27.2", @@ -7695,7 +7699,7 @@ dependencies = [ "reqwest_client", "resvg", "scheduler", - "schemars", + "schemars 1.0.4", "seahash", "serde", "serde_json", @@ -7840,7 +7844,7 @@ version = "0.1.0" dependencies = [ "derive_more", "gpui_util", - "schemars", + "schemars 1.0.4", "serde", ] @@ -7995,7 +7999,7 @@ dependencies = [ "futures-sink", "futures-util", "http 0.2.12", - "indexmap", + "indexmap 2.11.4", "slab", "tokio", "tokio-util", @@ -8014,7 +8018,7 @@ dependencies = [ "futures-core", "futures-sink", "http 1.3.1", - "indexmap", + "indexmap 2.11.4", "slab", "tokio", "tokio-util", @@ -8841,6 +8845,17 @@ version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "964de6e86d545b246d84badc0fef527924ace5134f30641c203ef52ba83f58d5" +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "serde", +] + [[package]] name = "indexmap" version = "2.11.4" @@ -8848,7 +8863,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4b0f83760fb341a774ed326568e19f5a863af4a952def8c39f9ab92fd95b88e5" dependencies = [ "equivalent", - "hashbrown 0.15.5", + "hashbrown 0.16.1", "serde", "serde_core", ] @@ -9251,7 +9266,7 @@ dependencies = [ "parking_lot", "paths", "project", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "settings", @@ -9522,7 +9537,7 @@ dependencies = [ "lsp", "parking_lot", "regex", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "toml 0.8.23", @@ -9585,7 +9600,7 @@ dependencies = [ "gpui_shared_string", "http_client", "partial-json-fixer", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "smol", @@ -9637,7 +9652,7 @@ dependencies = [ "opencode", "pretty_assertions", "release_channel", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "settings", @@ -9665,7 +9680,7 @@ dependencies = [ "http_client", "language_model", "open_ai", - "schemars", + "schemars 1.0.4", "semver", "serde", "serde_json", @@ -10185,7 +10200,7 @@ dependencies = [ "anyhow", "futures 0.3.32", "http_client", - "schemars", + "schemars 1.0.4", "serde", "serde_json", ] @@ -10262,7 +10277,7 @@ dependencies = [ "parking_lot", "postage", "release_channel", - "schemars", + "schemars 1.0.4", "semver", "serde", "serde_json", @@ -10844,7 +10859,7 @@ dependencies = [ "anyhow", "futures 0.3.32", "http_client", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "strum 0.27.2", @@ -10941,7 +10956,7 @@ dependencies = [ "half", "hashbrown 0.16.1", "hexf-parse", - "indexmap", + "indexmap 2.11.4", "libm", "log", "num-traits", @@ -10965,7 +10980,7 @@ dependencies = [ "half", "hashbrown 0.16.1", "hexf-parse", - "indexmap", + "indexmap 2.11.4", "libm", "log", "num-traits", @@ -11663,7 +11678,7 @@ checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe" dependencies = [ "crc32fast", "hashbrown 0.15.5", - "indexmap", + "indexmap 2.11.4", "memchr", ] @@ -11716,7 +11731,7 @@ dependencies = [ "anyhow", "futures 0.3.32", "http_client", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "settings", @@ -11740,7 +11755,7 @@ dependencies = [ "notifications", "picker", "project", - "schemars", + "schemars 1.0.4", "serde", "settings", "telemetry", @@ -11830,7 +11845,7 @@ dependencies = [ "log", "pretty_assertions", "rand 0.9.3", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "strum 0.27.2", @@ -11849,7 +11864,7 @@ dependencies = [ "gpui", "picker", "project", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "settings", @@ -11868,7 +11883,7 @@ dependencies = [ "futures 0.3.32", "http_client", "language_model_core", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "settings", @@ -11884,7 +11899,7 @@ dependencies = [ "futures 0.3.32", "google_ai", "http_client", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "strum 0.27.2", @@ -12827,7 +12842,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db" dependencies = [ "fixedbitset 0.4.2", - "indexmap", + "indexmap 2.11.4", ] [[package]] @@ -12941,7 +12956,7 @@ dependencies = [ "editor", "gpui", "menu", - "schemars", + "schemars 1.0.4", "serde", "settings", "theme", @@ -13067,7 +13082,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "740ebea15c5d1428f910cd1a5f52cebf8d25006245ed8ade92702f4943d91e07" dependencies = [ "base64 0.22.1", - "indexmap", + "indexmap 2.11.4", "quick-xml 0.38.3", "serde", "time", @@ -13449,7 +13464,7 @@ dependencies = [ "gpui", "http_client", "image", - "indexmap", + "indexmap 2.11.4", "itertools 0.14.0", "language", "log", @@ -13468,7 +13483,7 @@ dependencies = [ "release_channel", "remote", "rpc", - "schemars", + "schemars 1.0.4", "semver", "serde", "serde_json", @@ -13547,7 +13562,7 @@ dependencies = [ "project", "rayon", "remote_connection", - "schemars", + "schemars 1.0.4", "search", "serde", "serde_json", @@ -13718,8 +13733,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "22505a5c94da8e3b7c2996394d1c933236c4d743e81a410bcca4e6989fc066a4" dependencies = [ "bytes 1.11.1", - "heck 0.4.1", - "itertools 0.10.5", + "heck 0.5.0", + "itertools 0.11.0", "log", "multimap", "once_cell", @@ -13752,7 +13767,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "81bddcdb20abf9501610992b6759a4c888aef7d1a7247ef75e2404275ac24af1" dependencies = [ "anyhow", - "itertools 0.10.5", + "itertools 0.11.0", "proc-macro2", "quote", "syn 2.0.117", @@ -14548,7 +14563,7 @@ dependencies = [ "prost 0.9.0", "release_channel", "rpc", - "schemars", + "schemars 1.0.4", "semver", "serde", "serde_json", @@ -14917,7 +14932,7 @@ dependencies = [ "pastey 0.2.1", "pin-project-lite", "rmcp-macros", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "thiserror 2.0.17", @@ -15500,7 +15515,7 @@ dependencies = [ "anyhow", "clap", "env_logger 0.11.8", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "settings", @@ -15508,6 +15523,18 @@ dependencies = [ "theme_settings", ] +[[package]] +name = "schemars" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + [[package]] name = "schemars" version = "1.0.4" @@ -15516,7 +15543,7 @@ checksum = "82d20c4491bc164fa2f6c5d44565947a52ad80b9505d8e36f8d54c27c739fcd0" dependencies = [ "chrono", "dyn-clone", - "indexmap", + "indexmap 2.11.4", "ref-cast", "schemars_derive", "serde", @@ -15888,7 +15915,7 @@ version = "1.0.145" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c" dependencies = [ - "indexmap", + "indexmap 2.11.4", "itoa", "memchr", "ryu", @@ -15902,7 +15929,7 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e033097bf0d2b59a62b42c18ebbb797503839b26afdda2c4e1415cb6c813540" dependencies = [ - "indexmap", + "indexmap 2.11.4", "itoa", "memchr", "ryu", @@ -15961,13 +15988,44 @@ dependencies = [ "serde", ] +[[package]] +name = "serde_with" +version = "3.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd5414fad8e6907dbdd5bc441a50ae8d6e26151a03b1de04d89a5576de61d01f" +dependencies = [ + "base64 0.22.1", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.11.4", + "schemars 0.9.0", + "schemars 1.0.4", + "serde_core", + "serde_json", + "serde_with_macros", + "time", +] + +[[package]] +name = "serde_with_macros" +version = "3.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3db8978e608f1fe7357e211969fd9abdcae80bac1ba7a3369bb7eb6b404eb65" +dependencies = [ + "darling 0.23.0", + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "serde_yaml" version = "0.9.34+deprecated" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" dependencies = [ - "indexmap", + "indexmap 2.11.4", "itoa", "ryu", "serde", @@ -16014,7 +16072,7 @@ dependencies = [ "pretty_assertions", "release_channel", "rust-embed", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "serde_json_lenient", @@ -16037,7 +16095,7 @@ dependencies = [ "gpui", "language_model_core", "log", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "serde_json_lenient", @@ -16125,7 +16183,7 @@ dependencies = [ "regex", "release_channel", "rodio", - "schemars", + "schemars 1.0.4", "search", "serde", "serde_json", @@ -16242,7 +16300,7 @@ dependencies = [ "acp_thread", "action_log", "agent", - "agent-client-protocol-core", + "agent-client-protocol", "agent_settings", "agent_ui", "anyhow", @@ -16489,7 +16547,7 @@ version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1c97747dbf44bb1ca44a561ece23508e99cb592e862f22222dcf42f51d1e451" dependencies = [ - "heck 0.4.1", + "heck 0.5.0", "proc-macro2", "quote", "syn 2.0.117", @@ -16516,7 +16574,7 @@ dependencies = [ "indoc", "parking_lot", "paths", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "serde_json_lenient", @@ -16687,7 +16745,7 @@ dependencies = [ "futures-util", "hashbrown 0.15.5", "hashlink 0.10.0", - "indexmap", + "indexmap 2.11.4", "log", "memchr", "once_cell", @@ -17545,7 +17603,7 @@ dependencies = [ "menu", "picker", "project", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "settings", @@ -17618,7 +17676,7 @@ dependencies = [ "parking_lot", "pretty_assertions", "proto", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "serde_json_lenient", @@ -17722,7 +17780,7 @@ dependencies = [ "rand 0.9.3", "regex", "release_channel", - "schemars", + "schemars 1.0.4", "serde", "settings", "smol", @@ -17771,7 +17829,7 @@ dependencies = [ "release_channel", "remote", "rpc", - "schemars", + "schemars 1.0.4", "semver", "serde", "serde_json", @@ -17818,7 +17876,7 @@ dependencies = [ "palette", "parking_lot", "refineable", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "serde_json_lenient", @@ -17848,7 +17906,7 @@ dependencies = [ "clap", "collections", "gpui", - "indexmap", + "indexmap 2.11.4", "log", "palette", "serde", @@ -17895,7 +17953,7 @@ dependencies = [ "log", "palette", "refineable", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "serde_json_lenient", @@ -18132,7 +18190,7 @@ dependencies = [ "remote", "remote_connection", "rpc", - "schemars", + "schemars 1.0.4", "semver", "serde", "settings", @@ -18320,7 +18378,7 @@ version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0dc8b1fb61449e27716ec0e1bdf0f6b8f3e8f6b05391e8497b8b6d7804ea6d8" dependencies = [ - "indexmap", + "indexmap 2.11.4", "serde_core", "serde_spanned 1.0.3", "toml_datetime 0.7.3", @@ -18353,7 +18411,7 @@ version = "0.22.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" dependencies = [ - "indexmap", + "indexmap 2.11.4", "serde", "serde_spanned 0.6.9", "toml_datetime 0.6.11", @@ -18367,7 +18425,7 @@ version = "0.23.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6485ef6d0d9b5d0ec17244ff7eb05310113c3f316f2d14200d4de56b3cb98f8d" dependencies = [ - "indexmap", + "indexmap 2.11.4", "toml_datetime 0.7.3", "toml_parser", "winnow", @@ -19050,7 +19108,7 @@ dependencies = [ "icons", "itertools 0.14.0", "menu", - "schemars", + "schemars 1.0.4", "serde", "smallvec", "strum 0.27.2", @@ -19312,7 +19370,7 @@ dependencies = [ "rand 0.9.3", "regex", "rust-embed", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "serde_json_lenient", @@ -19424,7 +19482,7 @@ name = "vercel" version = "0.1.0" dependencies = [ "anyhow", - "schemars", + "schemars 1.0.4", "serde", "strum 0.27.2", ] @@ -19475,7 +19533,7 @@ dependencies = [ "project_panel", "regex", "release_channel", - "schemars", + "schemars 1.0.4", "search", "semver", "serde", @@ -19759,7 +19817,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fd83062c17b9f4985d438603cde0a5e8c5c8198201a6937f778b607924c7da2" dependencies = [ "anyhow", - "indexmap", + "indexmap 2.11.4", "serde", "serde_derive", "serde_json", @@ -19777,7 +19835,7 @@ dependencies = [ "anyhow", "auditable-serde", "flate2", - "indexmap", + "indexmap 2.11.4", "serde", "serde_derive", "serde_json", @@ -19794,7 +19852,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" dependencies = [ "anyhow", - "indexmap", + "indexmap 2.11.4", "wasm-encoder 0.244.0", "wasmparser 0.244.0", ] @@ -19831,7 +19889,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "84e5df6dba6c0d7fafc63a450f1738451ed7a0b52295d83e868218fa286bf708" dependencies = [ "bitflags 2.10.0", - "indexmap", + "indexmap 2.11.4", "semver", ] @@ -19843,7 +19901,7 @@ checksum = "d06bfa36ab3ac2be0dee563380147a5b81ba10dd8885d7fbbc9eb574be67d185" dependencies = [ "bitflags 2.10.0", "hashbrown 0.15.5", - "indexmap", + "indexmap 2.11.4", "semver", "serde", ] @@ -19856,7 +19914,7 @@ checksum = "0f51cad774fb3c9461ab9bccc9c62dfb7388397b5deda31bf40e8108ccd678b2" dependencies = [ "bitflags 2.10.0", "hashbrown 0.15.5", - "indexmap", + "indexmap 2.11.4", "semver", ] @@ -19868,7 +19926,7 @@ checksum = "a9b1e81f3eb254cf7404a82cee6926a4a3ccc5aad80cc3d43608a070c67aa1d7" dependencies = [ "bitflags 2.10.0", "hashbrown 0.15.5", - "indexmap", + "indexmap 2.11.4", "semver", "serde", ] @@ -19881,7 +19939,7 @@ checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" dependencies = [ "bitflags 2.10.0", "hashbrown 0.15.5", - "indexmap", + "indexmap 2.11.4", "semver", ] @@ -19911,7 +19969,7 @@ dependencies = [ "cfg-if", "encoding_rs", "hashbrown 0.15.5", - "indexmap", + "indexmap 2.11.4", "libc", "log", "mach2 0.4.3", @@ -19968,7 +20026,7 @@ dependencies = [ "cranelift-bitset", "cranelift-entity", "gimli", - "indexmap", + "indexmap 2.11.4", "log", "object", "postcard", @@ -20154,7 +20212,7 @@ dependencies = [ "anyhow", "bitflags 2.10.0", "heck 0.5.0", - "indexmap", + "indexmap 2.11.4", "wit-parser 0.236.1", ] @@ -20491,7 +20549,7 @@ dependencies = [ "cfg_aliases 0.2.1", "document-features", "hashbrown 0.16.1", - "indexmap", + "indexmap 2.11.4", "log", "naga 29.0.0 (git+https://github.com/zed-industries/wgpu.git?branch=v29)", "once_cell", @@ -21638,7 +21696,7 @@ checksum = "d8a39a15d1ae2077688213611209849cad40e9e5cccf6e61951a425850677ff3" dependencies = [ "anyhow", "heck 0.4.1", - "indexmap", + "indexmap 2.11.4", "wasm-metadata 0.201.0", "wit-bindgen-core 0.22.0", "wit-component 0.201.0", @@ -21652,7 +21710,7 @@ checksum = "9d0809dc5ba19e2e98661bf32fc0addc5a3ca5bf3a6a7083aa6ba484085ff3ce" dependencies = [ "anyhow", "heck 0.5.0", - "indexmap", + "indexmap 2.11.4", "prettyplease", "syn 2.0.117", "wasm-metadata 0.227.1", @@ -21668,7 +21726,7 @@ checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" dependencies = [ "anyhow", "heck 0.5.0", - "indexmap", + "indexmap 2.11.4", "prettyplease", "syn 2.0.117", "wasm-metadata 0.244.0", @@ -21728,7 +21786,7 @@ checksum = "421c0c848a0660a8c22e2fd217929a0191f14476b68962afd2af89fd22e39825" dependencies = [ "anyhow", "bitflags 2.10.0", - "indexmap", + "indexmap 2.11.4", "log", "serde", "serde_derive", @@ -21747,7 +21805,7 @@ checksum = "635c3adc595422cbf2341a17fb73a319669cc8d33deed3a48368a841df86b676" dependencies = [ "anyhow", "bitflags 2.10.0", - "indexmap", + "indexmap 2.11.4", "log", "serde", "serde_derive", @@ -21766,7 +21824,7 @@ checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" dependencies = [ "anyhow", "bitflags 2.10.0", - "indexmap", + "indexmap 2.11.4", "log", "serde", "serde_derive", @@ -21785,7 +21843,7 @@ checksum = "196d3ecfc4b759a8573bf86a9b3f8996b304b3732e4c7de81655f875f6efdca6" dependencies = [ "anyhow", "id-arena", - "indexmap", + "indexmap 2.11.4", "log", "semver", "serde", @@ -21803,7 +21861,7 @@ checksum = "ddf445ed5157046e4baf56f9138c124a0824d4d1657e7204d71886ad8ce2fc11" dependencies = [ "anyhow", "id-arena", - "indexmap", + "indexmap 2.11.4", "log", "semver", "serde", @@ -21821,7 +21879,7 @@ checksum = "16e4833a20cd6e85d6abfea0e63a399472d6f88c6262957c17f546879a80ba15" dependencies = [ "anyhow", "id-arena", - "indexmap", + "indexmap 2.11.4", "log", "semver", "serde", @@ -21839,7 +21897,7 @@ checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" dependencies = [ "anyhow", "id-arena", - "indexmap", + "indexmap 2.11.4", "log", "semver", "serde", @@ -21892,7 +21950,7 @@ dependencies = [ "project", "release_channel", "remote", - "schemars", + "schemars 1.0.4", "serde", "serde_json", "session", @@ -22034,7 +22092,7 @@ version = "0.1.0" dependencies = [ "anyhow", "language_model_core", - "schemars", + "schemars 1.0.4", "serde", "strum 0.27.2", "tiktoken-rs", @@ -22142,7 +22200,7 @@ dependencies = [ "clap", "compliance", "gh-workflow", - "indexmap", + "indexmap 2.11.4", "indoc", "itertools 0.14.0", "regex", @@ -22342,7 +22400,7 @@ dependencies = [ "action_log", "activity_indicator", "agent", - "agent-client-protocol-core", + "agent-client-protocol", "agent_servers", "agent_settings", "agent_ui", @@ -22618,7 +22676,7 @@ name = "zed_actions" version = "0.1.0" dependencies = [ "gpui", - "schemars", + "schemars 1.0.4", "serde", "util", "uuid", @@ -22869,7 +22927,7 @@ dependencies = [ "crc32fast", "crossbeam-utils", "displaydoc", - "indexmap", + "indexmap 2.11.4", "num_enum", "thiserror 1.0.69", ] diff --git a/Cargo.toml b/Cargo.toml index 36ad5271c439a4..2216437872723e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -496,7 +496,7 @@ ztracing_macro = { path = "crates/ztracing_macro" } # External crates # -agent-client-protocol = { package = "agent-client-protocol-core", git = "https://github.com/agentclientprotocol/rust-sdk", rev = "4444454f6c7735bf224ee5d7d2193b2ebeaeeb60", features = ["unstable"] } +agent-client-protocol = { version = "=0.11.0", features = ["unstable"] } aho-corasick = "1.1" alacritty_terminal = { git = "https://github.com/zed-industries/alacritty", rev = "9d9640d4" } any_vec = "0.14" diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs index df1743e711efcf..0d7253a2b77341 100644 --- a/crates/agent_servers/src/acp.rs +++ b/crates/agent_servers/src/acp.rs @@ -1663,7 +1663,7 @@ pub mod test_support { &self, session_id: &acp::SessionId, cx: &App, - ) -> Option> { + ) -> Option> { self.inner.truncate(session_id, cx) } @@ -1711,73 +1711,6 @@ pub mod test_support { } } - struct FakeAcpAgent { - load_session_count: Arc, - close_session_count: Arc, - fail_next_prompt: Arc, - } - - #[async_trait::async_trait(?Send)] - impl acp::Agent for FakeAcpAgent { - async fn initialize( - &self, - args: acp::InitializeRequest, - ) -> acp::Result { - Ok( - acp::InitializeResponse::new(args.protocol_version).agent_capabilities( - acp::AgentCapabilities::default() - .load_session(true) - .session_capabilities( - acp::SessionCapabilities::default() - .close(acp::SessionCloseCapabilities::new()), - ), - ), - ) - } - - async fn authenticate( - &self, - _: acp::AuthenticateRequest, - ) -> acp::Result { - Ok(Default::default()) - } - - async fn new_session( - &self, - _: acp::NewSessionRequest, - ) -> acp::Result { - Ok(acp::NewSessionResponse::new(acp::SessionId::new("unused"))) - } - - async fn prompt(&self, _: acp::PromptRequest) -> acp::Result { - if self.fail_next_prompt.swap(false, Ordering::SeqCst) { - Err(acp::ErrorCode::InternalError.into()) - } else { - Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)) - } - } - - async fn cancel(&self, _: acp::CancelNotification) -> acp::Result<()> { - Ok(()) - } - - async fn load_session( - &self, - _: acp::LoadSessionRequest, - ) -> acp::Result { - self.load_session_count.fetch_add(1, Ordering::SeqCst); - Ok(acp::LoadSessionResponse::new()) - } - - async fn close_session( - &self, - _: acp::CloseSessionRequest, - ) -> acp::Result { - self.close_session_count.fetch_add(1, Ordering::SeqCst); - Ok(acp::CloseSessionResponse::new()) - } - } - async fn build_fake_acp_connection( project: Entity, load_session_count: Arc, @@ -1785,50 +1718,105 @@ pub mod test_support { fail_next_prompt: Arc, cx: &mut AsyncApp, ) -> Result { - let (c2a_writer, c2a_reader) = async_pipe::pipe(); - let (a2c_writer, a2c_reader) = async_pipe::pipe(); + let (client_transport, agent_transport) = agent_client_protocol::Channel::duplex(); let sessions: Rc>> = Rc::new(RefCell::new(HashMap::default())); - let session_list_container: Rc>>> = - Rc::new(RefCell::new(None)); - let foreground = cx.foreground_executor().clone(); + let agent_future = Agent + .builder() + .name("fake-agent") + .on_receive_request( + async move |req: acp::InitializeRequest, responder, _cx| { + responder.respond( + acp::InitializeResponse::new(req.protocol_version).agent_capabilities( + acp::AgentCapabilities::default() + .load_session(true) + .session_capabilities( + acp::SessionCapabilities::default() + .close(acp::SessionCloseCapabilities::new()), + ), + ), + ) + }, + agent_client_protocol::on_receive_request!(), + ) + .on_receive_request( + async move |_req: acp::AuthenticateRequest, responder, _cx| { + responder.respond(Default::default()) + }, + agent_client_protocol::on_receive_request!(), + ) + .on_receive_request( + async move |_req: acp::NewSessionRequest, responder, _cx| { + responder.respond(acp::NewSessionResponse::new(acp::SessionId::new("unused"))) + }, + agent_client_protocol::on_receive_request!(), + ) + .on_receive_request( + { + 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()) + } else { + responder.respond(acp::PromptResponse::new(acp::StopReason::EndTurn)) + } + } + }, + agent_client_protocol::on_receive_request!(), + ) + .on_receive_request( + { + let load_session_count = load_session_count.clone(); + async move |_req: acp::LoadSessionRequest, responder, _cx| { + load_session_count.fetch_add(1, Ordering::SeqCst); + responder.respond(acp::LoadSessionResponse::new()) + } + }, + agent_client_protocol::on_receive_request!(), + ) + .on_receive_request( + { + let close_session_count = close_session_count.clone(); + async move |_req: acp::CloseSessionRequest, responder, _cx| { + close_session_count.fetch_add(1, Ordering::SeqCst); + responder.respond(acp::CloseSessionResponse::new()) + } + }, + agent_client_protocol::on_receive_request!(), + ) + .on_receive_notification( + async move |_notif: acp::CancelNotification, _cx| Ok(()), + agent_client_protocol::on_receive_notification!(), + ) + .connect_to(agent_transport); - let client_delegate = ClientDelegate { - sessions: sessions.clone(), - session_list: session_list_container, - cx: cx.clone(), - }; + let agent_io_task = cx.background_spawn(agent_future); - let (client_conn, client_io_task) = - acp::ClientSideConnection::new(client_delegate, c2a_writer, a2c_reader, { - let foreground = foreground.clone(); - move |fut| { - foreground.spawn(fut).detach(); + let (connection_tx, connection_rx) = futures::channel::oneshot::channel(); + let client_future = Client.builder().name("zed-test").connect_with( + client_transport, + move |connection: ConnectionTo| async move { + if connection_tx.send(connection).is_err() { + log::error!("failed to send fake ACP connection handle"); } - }); - - let fake_agent = FakeAcpAgent { - load_session_count: load_session_count.clone(), - close_session_count: close_session_count.clone(), - fail_next_prompt, - }; + futures::future::pending::>().await + }, + ); - let (_, agent_io_task) = - acp::AgentSideConnection::new(fake_agent, a2c_writer, c2a_reader, { - let foreground = foreground.clone(); - move |fut| { - foreground.spawn(fut).detach(); - } - }); + let client_io_task = cx.background_spawn(async move { + client_future.await.ok(); + }); - let client_io_task = cx.background_spawn(client_io_task); - let agent_io_task = cx.background_spawn(agent_io_task); + let client_conn: ConnectionTo = connection_rx + .await + .context("failed to receive fake ACP connection handle")?; - let response = client_conn - .initialize(acp::InitializeRequest::new(acp::ProtocolVersion::V1)) - .await?; + let response = into_foreground_future( + client_conn.send_request(acp::InitializeRequest::new(acp::ProtocolVersion::V1)), + ) + .await?; let agent_capabilities = response.agent_capabilities; @@ -1837,7 +1825,7 @@ pub mod test_support { let connection = cx.update(|cx| { AcpConnection::new_for_test( - Rc::new(client_conn), + client_conn, sessions, agent_capabilities, agent_server_store, From e89d93169c62cd34da42e8428e161ffc1825b609 Mon Sep 17 00:00:00 2001 From: Ben Brandt Date: Tue, 21 Apr 2026 11:49:40 +0000 Subject: [PATCH 16/20] Better error handling --- crates/acp_tools/Cargo.toml | 3 + crates/agent_servers/Cargo.toml | 2 +- crates/agent_servers/src/acp.rs | 128 ++++++++++++++++++++--- crates/agent_ui/src/conversation_view.rs | 1 - 4 files changed, 119 insertions(+), 15 deletions(-) diff --git a/crates/acp_tools/Cargo.toml b/crates/acp_tools/Cargo.toml index 7f341008f5e523..2d7162b9dec538 100644 --- a/crates/acp_tools/Cargo.toml +++ b/crates/acp_tools/Cargo.toml @@ -13,6 +13,9 @@ workspace = true path = "src/acp_tools.rs" doctest = false +[features] +test-support = ["workspace/test-support"] + [dependencies] agent-client-protocol.workspace = true collections.workspace = true diff --git a/crates/agent_servers/Cargo.toml b/crates/agent_servers/Cargo.toml index 0b547e8a0af797..dc13541831c4e0 100644 --- a/crates/agent_servers/Cargo.toml +++ b/crates/agent_servers/Cargo.toml @@ -6,7 +6,7 @@ publish.workspace = true license = "GPL-3.0-or-later" [features] -test-support = ["acp_thread/test-support", "gpui/test-support", "project/test-support", "dep:async-pipe", "dep:env_logger", "client/test-support", "dep:gpui_tokio", "reqwest_client/test-support"] +test-support = ["acp_tools/test-support", "acp_thread/test-support", "gpui/test-support", "project/test-support", "dep:async-pipe", "dep:env_logger", "client/test-support", "dep:gpui_tokio", "reqwest_client/test-support"] e2e = [] [lints] diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs index 0d7253a2b77341..0292cd3b7b439e 100644 --- a/crates/agent_servers/src/acp.rs +++ b/crates/agent_servers/src/acp.rs @@ -75,8 +75,118 @@ struct ClientContext { session_list: Rc>>>, } +fn dispatch_queue_closed_error() -> acp::Error { + acp::Error::internal_error().data("ACP foreground dispatch queue closed") +} + /// Work items sent from `Send` handler closures to the `!Send` foreground thread. -type ForegroundWork = Box; +trait ForegroundWorkItem: Send { + fn run(self: Box, cx: &mut AsyncApp, ctx: &ClientContext); + fn reject(self: Box); +} + +type ForegroundWork = Box; + +struct RequestForegroundWork +where + Req: Send + 'static, + Res: JsonRpcResponse + Send + 'static, +{ + request: Req, + responder: Responder, + handler: fn(Req, Responder, &mut AsyncApp, &ClientContext), +} + +impl ForegroundWorkItem for RequestForegroundWork +where + Req: Send + 'static, + Res: JsonRpcResponse + Send + 'static, +{ + fn run(self: Box, cx: &mut AsyncApp, ctx: &ClientContext) { + let Self { + request, + responder, + handler, + } = *self; + handler(request, responder, cx, ctx); + } + + fn reject(self: Box) { + let Self { responder, .. } = *self; + log::error!("ACP foreground dispatch queue closed while handling inbound request"); + responder + .respond_with_error(dispatch_queue_closed_error()) + .log_err(); + } +} + +struct NotificationForegroundWork +where + Notif: Send + 'static, +{ + notification: Notif, + connection: ConnectionTo, + handler: fn(Notif, &mut AsyncApp, &ClientContext), +} + +impl ForegroundWorkItem for NotificationForegroundWork +where + Notif: Send + 'static, +{ + fn run(self: Box, cx: &mut AsyncApp, ctx: &ClientContext) { + let Self { + notification, + handler, + .. + } = *self; + handler(notification, cx, ctx); + } + + fn reject(self: Box) { + let Self { connection, .. } = *self; + log::error!("ACP foreground dispatch queue closed while handling inbound notification"); + connection + .send_error_notification(dispatch_queue_closed_error()) + .log_err(); + } +} + +fn enqueue_request( + dispatch_tx: &mpsc::UnboundedSender, + request: Req, + responder: Responder, + handler: fn(Req, Responder, &mut AsyncApp, &ClientContext), +) where + Req: Send + 'static, + Res: JsonRpcResponse + Send + 'static, +{ + let work: ForegroundWork = Box::new(RequestForegroundWork { + request, + responder, + handler, + }); + if let Err(err) = dispatch_tx.unbounded_send(work) { + err.into_inner().reject(); + } +} + +fn enqueue_notification( + dispatch_tx: &mpsc::UnboundedSender, + notification: Notif, + connection: ConnectionTo, + handler: fn(Notif, &mut AsyncApp, &ClientContext), +) where + Notif: Send + 'static, +{ + let work: ForegroundWork = Box::new(NotificationForegroundWork { + notification, + connection, + handler, + }); + if let Err(err) = dispatch_tx.unbounded_send(work) { + err.into_inner().reject(); + } +} pub struct AcpConnection { id: AgentId, @@ -248,11 +358,7 @@ macro_rules! dispatch_request_handler { ($dispatch_tx:expr, $handler:expr) => {{ let dispatch_tx = $dispatch_tx.clone(); async move |args, responder, _connection| { - dispatch_tx - .unbounded_send(Box::new(move |cx, ctx| { - $handler(args, responder, cx, ctx); - })) - .log_err(); + enqueue_request(&dispatch_tx, args, responder, $handler); Ok(()) } }}; @@ -261,12 +367,8 @@ macro_rules! dispatch_request_handler { macro_rules! dispatch_notification_handler { ($dispatch_tx:expr, $handler:expr) => {{ let dispatch_tx = $dispatch_tx.clone(); - async move |notification, _connection| { - dispatch_tx - .unbounded_send(Box::new(move |cx, ctx| { - $handler(notification, cx, ctx); - })) - .log_err(); + async move |notification, connection| { + enqueue_notification(&dispatch_tx, notification, connection, $handler); Ok(()) } }}; @@ -481,7 +583,7 @@ impl AcpConnection { let mut dispatch_rx = dispatch_rx; async move |cx| { while let Some(work) = dispatch_rx.next().await { - work(cx, &dispatch_context); + work.run(cx, &dispatch_context); } } }); diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs index 50cfcddd658285..60da951cde3eee 100644 --- a/crates/agent_ui/src/conversation_view.rs +++ b/crates/agent_ui/src/conversation_view.rs @@ -2868,7 +2868,6 @@ pub(crate) mod tests { }; use action_log::ActionLog; use agent::{AgentTool, EditFileTool, FetchTool, TerminalTool, ToolPermissionContext}; - use agent_client_protocol::schema::SessionId; use agent_servers::FakeAcpAgentServer; use editor::MultiBufferOffset; use fs::FakeFs; From d29ccf9e4621b4904714822b7497207b965b12ff Mon Sep 17 00:00:00 2001 From: Ben Brandt Date: Tue, 21 Apr 2026 12:04:46 +0000 Subject: [PATCH 17/20] Fixes --- crates/acp_tools/src/acp_tools.rs | 18 ++++++++++++++++ crates/agent_ui/src/conversation_view.rs | 27 ++++++++++++------------ 2 files changed, 31 insertions(+), 14 deletions(-) diff --git a/crates/acp_tools/src/acp_tools.rs b/crates/acp_tools/src/acp_tools.rs index 5aad9f3a169da0..69b667df302ce2 100644 --- a/crates/acp_tools/src/acp_tools.rs +++ b/crates/acp_tools/src/acp_tools.rs @@ -215,6 +215,15 @@ impl AcpConnectionRegistry { cx.notify(); } + /// Clear the retained message history for the current connection and force + /// watchers to resubscribe so their local correlation state is reset too. + pub fn clear_messages(&mut self, cx: &mut Context) { + self.backlog.clear(); + self.generation += 1; + self.subscribers.clear(); + cx.notify(); + } + /// Subscribe to messages on the current connection. /// /// Returns the existing backlog (already-observed messages) together with @@ -277,6 +286,7 @@ impl AcpTools { let Some(agent_id) = agent_id else { self.watched_connection = None; + self.expanded.clear(); return; }; @@ -286,6 +296,8 @@ impl AcpTools { } } + self.expanded.clear(); + let (backlog, messages_rx) = self .connection_registry .update(cx, |registry, _cx| registry.subscribe()); @@ -427,6 +439,8 @@ impl AcpTools { if let Some(connection) = self.watched_connection.as_mut() { connection.messages.clear(); connection.list_state.reset(0); + connection.incoming_request_methods.clear(); + connection.outgoing_request_methods.clear(); self.expanded.clear(); cx.notify(); } @@ -732,6 +746,7 @@ impl Render for AcpToolsToolbarItemView { }; let acp_tools = acp_tools.clone(); + let connection_registry = acp_tools.read(cx).connection_registry.clone(); let has_messages = acp_tools .read(cx) .watched_connection @@ -756,6 +771,9 @@ impl Render for AcpToolsToolbarItemView { .tooltip(Tooltip::text("Clear Messages")) .disabled(!has_messages) .on_click(cx.listener(move |_this, _, _window, cx| { + connection_registry.update(cx, |registry, cx| { + registry.clear_messages(cx); + }); acp_tools.update(cx, |acp_tools, cx| { acp_tools.clear_messages(cx); }); diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs index 60da951cde3eee..0a176a4f84fbd7 100644 --- a/crates/agent_ui/src/conversation_view.rs +++ b/crates/agent_ui/src/conversation_view.rs @@ -2862,7 +2862,6 @@ fn plan_label_markdown_style( #[cfg(test)] pub(crate) mod tests { - use acp::SessionId; use acp_thread::{ AgentSessionList, AgentSessionListRequest, AgentSessionListResponse, StubAgentConnection, }; @@ -3033,8 +3032,8 @@ pub(crate) mod tests { async fn test_recent_history_refreshes_when_history_cache_updated(cx: &mut TestAppContext) { init_test(cx); - let session_a = AgentSessionInfo::new(SessionId::new("session-a")); - let session_b = AgentSessionInfo::new(SessionId::new("session-b")); + let session_a = AgentSessionInfo::new(acp::SessionId::new("session-a")); + let session_b = AgentSessionInfo::new(acp::SessionId::new("session-b")); // Use a connection that provides a session list so ThreadHistory is created let (conversation_view, history, cx) = setup_thread_view_with_history( @@ -3073,7 +3072,7 @@ pub(crate) mod tests { async fn test_new_thread_creation_triggers_session_list_refresh(cx: &mut TestAppContext) { init_test(cx); - let session = AgentSessionInfo::new(SessionId::new("history-session")); + let session = AgentSessionInfo::new(acp::SessionId::new("history-session")); let (conversation_view, _history, cx) = setup_thread_view_with_history( StubAgentServer::new(SessionHistoryConnection::new(vec![session.clone()])), cx, @@ -3109,7 +3108,7 @@ pub(crate) mod tests { Rc::new(StubAgentServer::new(ResumeOnlyAgentConnection)), connection_store, Agent::Custom { id: "Test".into() }, - Some(SessionId::new("resume-session")), + Some(acp::SessionId::new("resume-session")), None, None, None, @@ -3156,7 +3155,7 @@ pub(crate) mod tests { self, project, "RestoredAvailableCommandsConnection", - SessionId::new("new-session"), + acp::SessionId::new("new-session"), cx, ); Task::ready(Ok(thread)) @@ -3246,7 +3245,7 @@ pub(crate) mod tests { Rc::new(StubAgentServer::new(RestoredAvailableCommandsConnection)), connection_store, Agent::Custom { id: "Test".into() }, - Some(SessionId::new("restored-session")), + Some(acp::SessionId::new("restored-session")), None, None, None, @@ -3328,7 +3327,7 @@ pub(crate) mod tests { Rc::new(StubAgentServer::new(connection)), connection_store, Agent::Custom { id: "Test".into() }, - Some(SessionId::new("session-1")), + Some(acp::SessionId::new("session-1")), None, Some(PathList::new(&[PathBuf::from("/project/subdir")])), None, @@ -4296,7 +4295,7 @@ pub(crate) mod tests { connection: Rc, project: Entity, name: &'static str, - session_id: SessionId, + session_id: acp::SessionId, cx: &mut App, ) -> Entity { let action_log = cx.new(|_| ActionLog::new(project.clone())); @@ -4339,7 +4338,7 @@ pub(crate) mod tests { self, project, "SessionHistoryConnection", - SessionId::new("history-session"), + acp::SessionId::new("history-session"), cx, ); Task::ready(Ok(thread)) @@ -4403,7 +4402,7 @@ pub(crate) mod tests { self, project, "ResumeOnlyAgentConnection", - SessionId::new("new-session"), + acp::SessionId::new("new-session"), cx, ); Task::ready(Ok(thread)) @@ -4583,7 +4582,7 @@ pub(crate) mod tests { self, project, action_log, - SessionId::new("test"), + acp::SessionId::new("test"), watch::Receiver::constant( acp::PromptCapabilities::new() .image(true) @@ -4663,7 +4662,7 @@ pub(crate) mod tests { self.clone(), project, action_log, - SessionId::new("new-session"), + acp::SessionId::new("new-session"), watch::Receiver::constant( acp::PromptCapabilities::new() .image(true) @@ -7289,7 +7288,7 @@ pub(crate) mod tests { self, project, action_log, - SessionId::new("close-capable-session"), + acp::SessionId::new("close-capable-session"), watch::Receiver::constant( acp::PromptCapabilities::new() .image(true) From 1c382e0a398c493cb3aa1db093445523248028f4 Mon Sep 17 00:00:00 2001 From: Ben Brandt Date: Tue, 21 Apr 2026 12:42:02 +0000 Subject: [PATCH 18/20] unused deps --- crates/agent_servers/Cargo.toml | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/crates/agent_servers/Cargo.toml b/crates/agent_servers/Cargo.toml index dc13541831c4e0..c8970ec57a9050 100644 --- a/crates/agent_servers/Cargo.toml +++ b/crates/agent_servers/Cargo.toml @@ -6,7 +6,7 @@ publish.workspace = true license = "GPL-3.0-or-later" [features] -test-support = ["acp_tools/test-support", "acp_thread/test-support", "gpui/test-support", "project/test-support", "dep:async-pipe", "dep:env_logger", "client/test-support", "dep:gpui_tokio", "reqwest_client/test-support"] +test-support = ["acp_tools/test-support", "acp_thread/test-support", "gpui/test-support", "project/test-support", "dep:env_logger", "client/test-support", "dep:gpui_tokio", "reqwest_client/test-support"] e2e = [] [lints] @@ -22,8 +22,6 @@ acp_thread.workspace = true action_log.workspace = true agent-client-protocol.workspace = true anyhow.workspace = true -async-pipe = { workspace = true, optional = true } -async-trait.workspace = true chrono.workspace = true client.workspace = true collections.workspace = true @@ -67,7 +65,6 @@ fs.workspace = true indoc.workspace = true acp_thread = { workspace = true, features = ["test-support"] } -async-pipe.workspace = true gpui = { workspace = true, features = ["test-support"] } gpui_tokio.workspace = true project = { workspace = true, features = ["test-support"] } From 6ef6e506df8a544291feecdff895c5025d223e42 Mon Sep 17 00:00:00 2001 From: Ben Brandt Date: Wed, 22 Apr 2026 13:03:48 +0200 Subject: [PATCH 19/20] Final cleanups --- Cargo.lock | 11 ++--------- Cargo.toml | 2 +- crates/agent_ui/src/conversation_view.rs | 2 +- 3 files changed, 4 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3fe593c3e3b5bd..cb1f34b565180b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -222,14 +222,13 @@ dependencies = [ [[package]] name = "agent-client-protocol" -version = "0.11.0" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "598d0408bb054b4fc40c3f9f69da6fa0cab2d4afa9011e0227eed558857afaae" +checksum = "2af62fb84df2af0f933d8f5fd78b843fa5eb0ec5a48fa1b528c41951d0bbe36c" dependencies = [ "agent-client-protocol-derive", "agent-client-protocol-schema", "anyhow", - "boxfnonce", "futures 0.3.32", "futures-concurrency", "jsonrpcmsg", @@ -2204,12 +2203,6 @@ dependencies = [ "syn 2.0.117", ] -[[package]] -name = "boxfnonce" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5988cb1d626264ac94100be357308f29ff7cbdd3b36bda27f450a4ee3f713426" - [[package]] name = "breadcrumbs" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index f3eb0011225561..9d42559927744f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -496,7 +496,7 @@ ztracing_macro = { path = "crates/ztracing_macro" } # External crates # -agent-client-protocol = { version = "=0.11.0", features = ["unstable"] } +agent-client-protocol = { version = "=0.11.1", features = ["unstable"] } aho-corasick = "1.1" alacritty_terminal = { git = "https://github.com/zed-industries/alacritty", rev = "9d9640d4" } any_vec = "0.14" diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs index 615138e34983b3..6577496965a2b2 100644 --- a/crates/agent_ui/src/conversation_view.rs +++ b/crates/agent_ui/src/conversation_view.rs @@ -3359,7 +3359,7 @@ pub(crate) mod tests { cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx))); // Simulate a previous run that persisted metadata for this session. - let resume_session_id = SessionId::new("persistent-session"); + let resume_session_id = acp::SessionId::new("persistent-session"); let stored_title: SharedString = "Persistent chat".into(); cx.update(|_window, cx| { ThreadMetadataStore::global(cx).update(cx, |store, cx| { From dbb118ada1d3541e5668ceae46d1390aa73ec23e Mon Sep 17 00:00:00 2001 From: Ben Brandt Date: Wed, 22 Apr 2026 15:05:25 +0200 Subject: [PATCH 20/20] Cleanup --- crates/acp_tools/src/acp_tools.rs | 145 ++++- crates/agent_servers/src/acp.rs | 408 ++++++++------ crates/agent_ui/src/thread_history.rs | 772 -------------------------- 3 files changed, 360 insertions(+), 965 deletions(-) delete mode 100644 crates/agent_ui/src/thread_history.rs diff --git a/crates/acp_tools/src/acp_tools.rs b/crates/acp_tools/src/acp_tools.rs index 69b667df302ce2..ea6de9f7d606be 100644 --- a/crates/acp_tools/src/acp_tools.rs +++ b/crates/acp_tools/src/acp_tools.rs @@ -1,7 +1,10 @@ use std::{ collections::{HashSet, VecDeque}, fmt::Display, - sync::Arc, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, }; use agent_client_protocol::schema as acp; @@ -21,8 +24,6 @@ use workspace::{ Item, ItemHandle, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView, Workspace, }; -pub type RequestId = serde_json::Value; - #[derive(Clone, Copy, PartialEq, Eq)] pub enum StreamMessageDirection { Incoming, @@ -35,12 +36,12 @@ pub enum StreamMessageDirection { #[derive(Clone)] pub enum StreamMessageContent { Request { - id: RequestId, + id: acp::RequestId, method: Arc, params: Option, }, Response { - id: RequestId, + id: acp::RequestId, result: Result, acp::Error>, }, Notification { @@ -76,20 +77,34 @@ impl StreamMessage { let value: serde_json::Value = serde_json::from_str(line).ok()?; let obj = value.as_object()?; + let parsed_id = obj + .get("id") + .map(|raw| serde_json::from_value::(raw.clone())); + let message = if let Some(method) = obj.get("method").and_then(|m| m.as_str()) { - if let Some(id) = obj.get("id") { - StreamMessageContent::Request { - id: id.clone(), + match parsed_id { + Some(Ok(id)) => StreamMessageContent::Request { + id, method: method.into(), params: obj.get("params").cloned(), + }, + Some(Err(err)) => { + log::warn!("Skipping JSON-RPC message with unparsable id: {err}"); + return None; } - } else { - StreamMessageContent::Notification { + None => StreamMessageContent::Notification { method: method.into(), params: obj.get("params").cloned(), - } + }, } - } else if let Some(id) = obj.get("id") { + } else if let Some(parsed_id) = parsed_id { + let id = match parsed_id { + Ok(id) => id, + Err(err) => { + log::warn!("Skipping JSON-RPC response with unparsable id: {err}"); + return None; + } + }; if let Some(error) = obj.get("error") { let acp_err = serde_json::from_value::(error.clone()).unwrap_or_else(|err| { @@ -97,12 +112,12 @@ impl StreamMessage { acp::Error::internal_error().data(error.to_string()) }); StreamMessageContent::Response { - id: id.clone(), + id, result: Err(acp_err), } } else { StreamMessageContent::Response { - id: id.clone(), + id, result: Ok(obj.get("result").cloned()), } } @@ -133,12 +148,66 @@ struct GlobalAcpConnectionRegistry(Entity); impl Global for GlobalAcpConnectionRegistry {} -/// A raw line captured from the transport (or from stderr), tagged with direction. -/// Deserialization into [`StreamMessage`] happens eagerly on arrival so that -/// the registry's ring buffer can be replayed to late subscribers. -pub struct RawStreamLine { - pub direction: StreamMessageDirection, - pub line: Arc, +/// A raw line captured from the transport (or from stderr), tagged with +/// direction. Deserialization into [`StreamMessage`] happens on the +/// registry's foreground task so the ring buffer can be replayed to late +/// subscribers. +struct RawStreamLine { + direction: StreamMessageDirection, + line: Arc, +} + +/// Handle to an ACP connection's log tap. Passed back by +/// [`AcpConnectionRegistry::set_active_connection`] so that the connection +/// can publish transport and stderr lines without knowing anything about +/// the logs panel's channel. +/// +/// The tap carries a shared `enabled` flag that the registry flips on when +/// the first observer subscribes. Until then, `emit_*` methods are +/// effectively free: they check an atomic and return. This keeps the +/// logs panel's memory footprint opt-in — if no one ever opens it, the +/// transport never allocates a line or pushes a channel item. +#[derive(Clone)] +pub struct AcpLogTap { + enabled: Arc, + sender: smol::channel::Sender, +} + +impl AcpLogTap { + fn is_enabled(&self) -> bool { + self.enabled.load(Ordering::Relaxed) + } + + fn enable(&self) { + self.enabled.store(true, Ordering::Relaxed); + } + + fn emit(&self, direction: StreamMessageDirection, line: &str) { + if !self.is_enabled() { + return; + } + self.sender + .try_send(RawStreamLine { + direction, + line: Arc::from(line), + }) + .log_err(); + } + + /// Record a line read from the agent's stdout. + pub fn emit_incoming(&self, line: &str) { + self.emit(StreamMessageDirection::Incoming, line); + } + + /// Record a line written to the agent's stdin. + pub fn emit_outgoing(&self, line: &str) { + self.emit(StreamMessageDirection::Outgoing, line); + } + + /// Record a line read from the agent's stderr. + pub fn emit_stderr(&self, line: &str) { + self.emit(StreamMessageDirection::Stderr, line); + } } /// Maximum number of messages retained in the registry's backlog. @@ -156,6 +225,9 @@ pub struct AcpConnectionRegistry { /// When a new connection is set, this is cleared. backlog: VecDeque, subscribers: Vec>, + /// The tap handed to the currently active connection, so the registry + /// can flip its `enabled` flag the first time someone subscribes. + active_tap: Option, _broadcast_task: Option>, } @@ -170,16 +242,29 @@ impl AcpConnectionRegistry { } } + /// Register a new active connection and return an [`AcpLogTap`] that + /// the connection should hand to its transport + stderr readers. + /// + /// The tap starts out disabled: transport lines are dropped cheaply + /// until someone subscribes via [`Self::subscribe`], at which point + /// the tap is flipped on and subsequent lines are broadcast to all + /// current and future subscribers. pub fn set_active_connection( &mut self, agent_id: AgentId, - raw_rx: smol::channel::Receiver, cx: &mut Context, - ) { + ) -> AcpLogTap { + let (sender, raw_rx) = smol::channel::unbounded::(); + let tap = AcpLogTap { + enabled: Arc::new(AtomicBool::new(false)), + sender, + }; + self.active_agent_id = Some(agent_id); self.generation += 1; self.backlog.clear(); self.subscribers.clear(); + self.active_tap = Some(tap.clone()); self._broadcast_task = Some(cx.spawn(async move |this, cx| { while let Ok(raw) = raw_rx.recv().await { @@ -207,12 +292,14 @@ impl AcpConnectionRegistry { this.update(cx, |this, cx| { this.active_agent_id = None; this.subscribers.clear(); + this.active_tap = None; cx.notify(); }) .log_err(); })); cx.notify(); + tap } /// Clear the retained message history for the current connection and force @@ -230,7 +317,15 @@ impl AcpConnectionRegistry { /// a receiver for new messages. The caller is responsible for flushing the /// backlog into its local state before draining the receiver, so that no /// messages are dropped between the snapshot and live subscription. + /// + /// The first subscription enables the connection's log tap; prior + /// messages are therefore not available. This is intentional: the tap + /// is opt-in so that the default case (no one ever opens the ACP logs + /// panel) performs zero per-message bookkeeping. pub fn subscribe(&mut self) -> (Vec, smol::channel::Receiver) { + if let Some(tap) = &self.active_tap { + tap.enable(); + } let backlog = self.backlog.iter().cloned().collect(); let (sender, receiver) = smol::channel::unbounded(); self.subscribers.push(sender); @@ -252,8 +347,8 @@ struct WatchedConnection { generation: u64, messages: Vec, list_state: ListState, - incoming_request_methods: HashMap>, - outgoing_request_methods: HashMap>, + incoming_request_methods: HashMap>, + outgoing_request_methods: HashMap>, _task: Task<()>, } @@ -585,7 +680,7 @@ impl AcpTools { struct WatchedConnectionMessage { name: SharedString, - request_id: Option, + request_id: Option, direction: StreamMessageDirection, message_type: MessageType, params: Result, acp::Error>, diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs index 96b77d0f785cbf..28ec60e404314a 100644 --- a/crates/agent_servers/src/acp.rs +++ b/crates/agent_servers/src/acp.rs @@ -2,7 +2,7 @@ use acp_thread::{ AgentConnection, AgentSessionInfo, AgentSessionList, AgentSessionListRequest, AgentSessionListResponse, }; -use acp_tools::{AcpConnectionRegistry, RawStreamLine, StreamMessageDirection}; +use acp_tools::AcpConnectionRegistry; use action_log::ActionLog; use agent_client_protocol::schema::{self as acp, ErrorCode}; use agent_client_protocol::{ @@ -41,14 +41,21 @@ use crate::GEMINI_ID; pub const GEMINI_TERMINAL_AUTH_METHOD_ID: &str = "spawn-gemini-cli"; -/// Converts a [`SentRequest`] into a `Future` that can be safely awaited from -/// the GPUI foreground thread. +/// Awaits the response to an ACP request from a GPUI foreground task. /// -/// Unlike [`SentRequest::block_task`], which is only safe inside -/// [`ConnectionTo::spawn`] tasks, this uses [`SentRequest::on_receiving_result`] -/// to bridge the response through a oneshot channel. The SDK callback is trivial -/// (just a channel send), so it doesn't meaningfully block the dispatch loop. -fn into_foreground_future( +/// The ACP SDK offers two ways to consume a [`SentRequest`]: +/// - [`SentRequest::block_task`]: linear `.await` inside a spawned task. +/// - [`SentRequest::on_receiving_result`]: a callback invoked when the +/// response arrives, with the guarantee that no other inbound messages +/// are processed while the callback runs. This is the recommended form +/// inside SDK handler callbacks, where [`block_task`] would deadlock. +/// +/// We use `on_receiving_result` with a oneshot bridge here (rather than +/// [`block_task`]) so that our handler-side code paths can share a single +/// request-awaiting helper. The SDK callback itself is trivial (one channel +/// send) so the extra ordering guarantee it imposes on the dispatch loop is +/// negligible. +fn into_foreground_future( sent: SentRequest, ) -> impl Future> { let (tx, rx) = futures::channel::oneshot::channel(); @@ -69,6 +76,37 @@ fn into_foreground_future( #[error("Unsupported version")] pub struct UnsupportedVersion; +/// Helper for flattening the nested `Result` shapes that come out of +/// `entity.update(cx, |_, cx| fallible_op(cx))` into a single `Result`. +/// +/// `anyhow::Error` values get converted via `acp::Error::from`, which +/// downcasts an `acp::Error` back out of `anyhow` when present, so typed +/// errors like auth-required survive the trip. +trait FlattenAcpResult { + fn flatten_acp(self) -> Result; +} + +impl FlattenAcpResult for Result, anyhow::Error> { + fn flatten_acp(self) -> Result { + match self { + Ok(Ok(value)) => Ok(value), + Ok(Err(err)) => Err(err.into()), + Err(err) => Err(err.into()), + } + } +} + +impl FlattenAcpResult for Result, anyhow::Error> { + fn flatten_acp(self) -> Result { + 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>>, @@ -354,24 +392,95 @@ pub async fn connect( const MINIMUM_SUPPORTED_VERSION: acp::ProtocolVersion = acp::ProtocolVersion::V1; -macro_rules! dispatch_request_handler { - ($dispatch_tx:expr, $handler:expr) => {{ - let dispatch_tx = $dispatch_tx.clone(); - async move |args, responder, _connection| { - enqueue_request(&dispatch_tx, args, responder, $handler); - Ok(()) - } - }}; -} +/// Build a `Client` connection over `transport` with Zed's full +/// agent→client handler set wired up. +/// +/// All incoming requests and notifications are forwarded to the foreground +/// dispatch queue via `dispatch_tx`, where they are handled by the +/// `handle_*` functions on a GPUI context. The returned future drives the +/// connection and completes when the transport closes; callers are expected +/// to spawn it on a background executor and hold the task for the lifetime +/// of the connection. The `connection_tx` oneshot receives the +/// `ConnectionTo` handle as soon as the builder runs its `main_fn`. +fn connect_client_future( + name: &'static str, + transport: impl agent_client_protocol::ConnectTo + 'static, + dispatch_tx: mpsc::UnboundedSender, + connection_tx: futures::channel::oneshot::Sender>, +) -> impl Future> { + // Each handler forwards its inputs onto the foreground dispatch queue. + // The SDK requires the closure to be `Send`, so we move a clone of + // `dispatch_tx` into each one. + macro_rules! on_request { + ($handler:ident) => {{ + let dispatch_tx = dispatch_tx.clone(); + async move |req, responder, _connection| { + enqueue_request(&dispatch_tx, req, responder, $handler); + Ok(()) + } + }}; + } + macro_rules! on_notification { + ($handler:ident) => {{ + let dispatch_tx = dispatch_tx.clone(); + async move |notif, connection| { + enqueue_notification(&dispatch_tx, notif, connection, $handler); + Ok(()) + } + }}; + } -macro_rules! dispatch_notification_handler { - ($dispatch_tx:expr, $handler:expr) => {{ - let dispatch_tx = $dispatch_tx.clone(); - async move |notification, connection| { - enqueue_notification(&dispatch_tx, notification, connection, $handler); - Ok(()) - } - }}; + Client + .builder() + .name(name) + // --- Request handlers (agent→client) --- + .on_receive_request( + on_request!(handle_request_permission), + agent_client_protocol::on_receive_request!(), + ) + .on_receive_request( + on_request!(handle_write_text_file), + agent_client_protocol::on_receive_request!(), + ) + .on_receive_request( + on_request!(handle_read_text_file), + agent_client_protocol::on_receive_request!(), + ) + .on_receive_request( + on_request!(handle_create_terminal), + agent_client_protocol::on_receive_request!(), + ) + .on_receive_request( + on_request!(handle_kill_terminal), + agent_client_protocol::on_receive_request!(), + ) + .on_receive_request( + on_request!(handle_release_terminal), + agent_client_protocol::on_receive_request!(), + ) + .on_receive_request( + on_request!(handle_terminal_output), + agent_client_protocol::on_receive_request!(), + ) + .on_receive_request( + on_request!(handle_wait_for_terminal_exit), + agent_client_protocol::on_receive_request!(), + ) + // --- Notification handlers (agent→client) --- + .on_receive_notification( + on_notification!(handle_session_notification), + agent_client_protocol::on_receive_notification!(), + ) + .connect_with( + transport, + move |connection: ConnectionTo| async move { + if connection_tx.send(connection).is_err() { + log::error!("failed to send ACP connection handle — receiver was dropped"); + } + // Keep the connection alive until the transport closes. + futures::future::pending::>().await + }, + ) } impl AcpConnection { @@ -455,22 +564,20 @@ impl AcpConnection { // closures to the !Send foreground thread. let (dispatch_tx, dispatch_rx) = mpsc::unbounded::(); - // Build a tapped transport that intercepts raw JSON-RPC lines, plus - // stderr lines, for the ACP logs panel. - let (stream_tap_tx, stream_tap_rx) = smol::channel::unbounded::(); + // Register this connection with the logs panel registry. The + // returned tap is opt-in: until someone subscribes to the ACP logs + // panel, `emit_*` calls below are ~free (atomic load + return). + let log_tap = cx.update(|cx| { + AcpConnectionRegistry::default_global(cx).update(cx, |registry, cx| { + registry.set_active_connection(agent_id.clone(), cx) + }) + }); let incoming_lines = futures::io::BufReader::new(stdout).lines(); let tapped_incoming = incoming_lines.inspect({ - let tap_tx = stream_tap_tx.clone(); + let log_tap = log_tap.clone(); move |result| match result { - Ok(line) => { - tap_tx - .try_send(RawStreamLine { - direction: StreamMessageDirection::Incoming, - line: Arc::from(line.as_str()), - }) - .log_err(); - } + Ok(line) => log_tap.emit_incoming(line), Err(err) => { // I/O errors on the transport are fatal for the SDK, but // without logging them the ACP logs panel shows no trace @@ -481,95 +588,32 @@ impl AcpConnection { }); let tapped_outgoing = futures::sink::unfold( - (Box::pin(stdin), stream_tap_tx.clone()), - async move |(mut writer, tap_tx), line: String| { + (Box::pin(stdin), log_tap.clone()), + async move |(mut writer, log_tap), line: String| { use futures::AsyncWriteExt; - tap_tx - .try_send(RawStreamLine { - direction: StreamMessageDirection::Outgoing, - line: Arc::from(line.as_str()), - }) - .log_err(); + log_tap.emit_outgoing(&line); let mut bytes = line.into_bytes(); bytes.push(b'\n'); writer.write_all(&bytes).await?; - Ok::<_, std::io::Error>((writer, tap_tx)) + Ok::<_, std::io::Error>((writer, log_tap)) }, ); let transport = Lines::new(tapped_outgoing, tapped_incoming); - // Use a oneshot channel to extract the ConnectionTo from the - // connect_with closure. + // `connect_client_future` installs the production handler set and + // hands us back both the connection-future (to run on a background + // executor) and a oneshot receiver that produces the + // `ConnectionTo` once the transport handshake is ready. let (connection_tx, connection_rx) = futures::channel::oneshot::channel(); - - // Build the connection with handler closures. - // All handlers forward work to the foreground dispatch channel. - let connection_future = { - let dispatch_tx = dispatch_tx.clone(); - Client - .builder() - .name("zed") - // --- Request handlers (agent→client) --- - .on_receive_request( - dispatch_request_handler!(dispatch_tx, handle_request_permission), - agent_client_protocol::on_receive_request!(), - ) - .on_receive_request( - dispatch_request_handler!(dispatch_tx, handle_write_text_file), - agent_client_protocol::on_receive_request!(), - ) - .on_receive_request( - dispatch_request_handler!(dispatch_tx, handle_read_text_file), - agent_client_protocol::on_receive_request!(), - ) - .on_receive_request( - dispatch_request_handler!(dispatch_tx, handle_create_terminal), - agent_client_protocol::on_receive_request!(), - ) - .on_receive_request( - dispatch_request_handler!(dispatch_tx, handle_kill_terminal), - agent_client_protocol::on_receive_request!(), - ) - .on_receive_request( - dispatch_request_handler!(dispatch_tx, handle_release_terminal), - agent_client_protocol::on_receive_request!(), - ) - .on_receive_request( - dispatch_request_handler!(dispatch_tx, handle_terminal_output), - agent_client_protocol::on_receive_request!(), - ) - .on_receive_request( - dispatch_request_handler!(dispatch_tx, handle_wait_for_terminal_exit), - agent_client_protocol::on_receive_request!(), - ) - // --- Notification handlers (agent→client) --- - .on_receive_notification( - dispatch_notification_handler!(dispatch_tx, handle_session_notification), - agent_client_protocol::on_receive_notification!(), - ) - .connect_with( - transport, - move |connection: ConnectionTo| async move { - if connection_tx.send(connection.clone()).is_err() { - log::error!( - "failed to send ACP connection handle — receiver was dropped" - ); - } - // Keep the connection alive until the transport closes. - futures::future::pending::>().await - }, - ) - }; - - // Spawn the connection loop on a background thread. + let connection_future = + connect_client_future("zed", transport, dispatch_tx.clone(), connection_tx); let io_task = cx.background_spawn(async move { if let Err(err) = connection_future.await { log::error!("ACP connection error: {err}"); } }); - // Wait for the ConnectionTo handle. let connection: ConnectionTo = connection_rx .await .context("Failed to receive ACP connection handle")?; @@ -589,7 +633,7 @@ impl AcpConnection { }); let stderr_task = cx.background_spawn({ - let tap_tx = stream_tap_tx.clone(); + let log_tap = log_tap.clone(); async move { let mut stderr = BufReader::new(stderr); let mut line = String::new(); @@ -598,12 +642,7 @@ impl AcpConnection { { let trimmed = line.trim_end_matches(['\n', '\r']); log::warn!("agent stderr: {trimmed}"); - tap_tx - .try_send(RawStreamLine { - direction: StreamMessageDirection::Stderr, - line: Arc::from(trimmed), - }) - .log_err(); + log_tap.emit_stderr(trimmed); line.clear(); } Ok(()) @@ -620,12 +659,6 @@ impl AcpConnection { } }); - cx.update(|cx| { - AcpConnectionRegistry::default_global(cx).update(cx, |registry, cx| { - registry.set_active_connection(agent_id.clone(), stream_tap_rx, cx) - }); - }); - let response = into_foreground_future( connection.send_request( acp::InitializeRequest::new(acp::ProtocolVersion::V1) @@ -724,6 +757,7 @@ impl AcpConnection { agent_capabilities: acp::AgentCapabilities, agent_server_store: WeakEntity, io_task: Task<()>, + dispatch_task: Task<()>, _cx: &mut App, ) -> Self { Self { @@ -741,7 +775,7 @@ impl AcpConnection { child: None, session_list: None, _io_task: io_task, - _dispatch_task: Task::ready(()), + _dispatch_task: dispatch_task, _wait_task: Task::ready(Ok(())), _stderr_task: Task::ready(Ok(())), } @@ -1886,6 +1920,8 @@ pub mod test_support { let sessions: Rc>> = Rc::new(RefCell::new(HashMap::default())); + let client_session_list: Rc>>> = + Rc::new(RefCell::new(None)); let agent_future = Agent .builder() @@ -1958,17 +1994,18 @@ pub mod test_support { let agent_io_task = cx.background_spawn(agent_future); + // Wire the production handler set into the fake client so inbound + // requests/notifications from the fake agent are dispatched the + // same way the real `stdio` path does. + let (dispatch_tx, dispatch_rx) = mpsc::unbounded::(); + let (connection_tx, connection_rx) = futures::channel::oneshot::channel(); - let client_future = Client.builder().name("zed-test").connect_with( + let client_future = connect_client_future( + "zed-test", client_transport, - move |connection: ConnectionTo| async move { - if connection_tx.send(connection).is_err() { - log::error!("failed to send fake ACP connection handle"); - } - futures::future::pending::>().await - }, + dispatch_tx.clone(), + connection_tx, ); - let client_io_task = cx.background_spawn(async move { client_future.await.ok(); }); @@ -1984,6 +2021,19 @@ pub mod test_support { let agent_capabilities = response.agent_capabilities; + let dispatch_context = ClientContext { + sessions: sessions.clone(), + session_list: client_session_list.clone(), + }; + let dispatch_task = cx.spawn({ + let mut dispatch_rx = dispatch_rx; + async move |cx| { + while let Some(work) = dispatch_rx.next().await { + work.run(cx, &dispatch_context); + } + } + }); + let agent_server_store = project.read_with(cx, |project, _| project.agent_server_store().downgrade()); @@ -1994,6 +2044,7 @@ pub mod test_support { agent_capabilities, agent_server_store, client_io_task, + dispatch_task, cx, ) }); @@ -2196,6 +2247,8 @@ mod tests { let sessions: Rc>> = Rc::new(RefCell::new(HashMap::default())); + let client_session_list: Rc>>> = + Rc::new(RefCell::new(None)); // Build the fake agent side. It handles the requests issued by // `AcpConnection` during the test and tracks load/close counts. @@ -2292,16 +2345,18 @@ mod tests { let agent_io_task = cx.background_spawn(agent_future); - // Build the client side and capture the `ConnectionTo` handle. + // Wire the production handler set into the fake client so inbound + // requests/notifications from the fake agent reach the same + // dispatcher that the real `stdio` path uses. + let (dispatch_tx, dispatch_rx) = mpsc::unbounded::(); + let (connection_tx, connection_rx) = futures::channel::oneshot::channel(); - let client_future = Client.builder().name("zed-test").connect_with( + let client_future = connect_client_future( + "zed-test", client_transport, - move |connection: ConnectionTo| async move { - connection_tx.send(connection).ok(); - futures::future::pending::>().await - }, + dispatch_tx.clone(), + connection_tx, ); - let client_io_task = cx.background_spawn(async move { client_future.await.ok(); }); @@ -2318,6 +2373,24 @@ mod tests { let agent_capabilities = response.agent_capabilities; + let dispatch_context = ClientContext { + sessions: sessions.clone(), + session_list: client_session_list.clone(), + }; + // `TestAppContext::spawn` hands out an `AsyncApp` by value, whereas the + // production path uses `Context::spawn` which hands out `&mut AsyncApp`. + // Bind the value-form to a local and take `&mut` of it to reuse the + // same dispatch loop shape. + let dispatch_task = cx.spawn({ + let mut dispatch_rx = dispatch_rx; + move |cx| async move { + let mut cx = cx; + while let Some(work) = dispatch_rx.next().await { + work.run(&mut cx, &dispatch_context); + } + } + }); + let agent_server_store = project.read_with(cx, |project, _| project.agent_server_store().downgrade()); @@ -2328,6 +2401,7 @@ mod tests { agent_capabilities, agent_server_store, client_io_task, + dispatch_task, cx, ) }); @@ -2944,7 +3018,14 @@ fn session_thread( .ok_or_else(|| acp::Error::internal_error().data(format!("unknown session: {session_id}"))) } -fn respond_err(responder: Responder, err: acp::Error) { +fn respond_err(responder: Responder, err: acp::Error) { + // 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. + log::warn!( + "Responding to ACP request `{method}` with error: {err:?}", + method = responder.method() + ); responder.respond_with_error(err).log_err(); } @@ -2969,8 +3050,7 @@ fn handle_request_permission( cx, ) }) - .map_err(acp::Error::from)? - .map_err(acp::Error::from)?; + .flatten_acp()?; Ok(task.await) } .await; @@ -3005,8 +3085,7 @@ fn handle_write_text_file( thread.write_text_file(args.path, args.content, cx) }) .map_err(acp::Error::from)? - .await - .map_err(acp::Error::from)?; + .await?; Ok(()) } .await; @@ -3153,7 +3232,7 @@ fn handle_session_notification( .update(cx, |thread, cx| { thread.handle_session_update(notification.update.clone(), cx) }) - .and_then(|inner| inner.map_err(anyhow::Error::from)) + .flatten_acp() { log::error!( "Failed to handle session update for {:?}: {err:?}", @@ -3245,21 +3324,18 @@ fn handle_create_terminal( &project, cx, ) - .await - .map_err(acp::Error::from)?; + .await?; - let terminal_entity = thread - .update(cx, |thread, cx| { - thread.register_terminal_created( - acp::TerminalId::new(uuid::Uuid::new_v4().to_string()), - format!("{} {}", args.command, args.args.join(" ")), - args.cwd.clone(), - args.output_byte_limit, - terminal_entity, - cx, - ) - }) - .map_err(acp::Error::from)?; + let terminal_entity = thread.update(cx, |thread, cx| { + thread.register_terminal_created( + acp::TerminalId::new(uuid::Uuid::new_v4().to_string()), + format!("{} {}", args.command, args.args.join(" ")), + args.cwd.clone(), + args.output_byte_limit, + terminal_entity, + cx, + ) + })?; let terminal_id = terminal_entity.read_with(cx, |terminal, _| terminal.id().clone()); Ok(terminal_id) } @@ -3290,8 +3366,7 @@ fn handle_kill_terminal( match thread .update(cx, |thread, cx| thread.kill_terminal(args.terminal_id, cx)) - .map_err(acp::Error::from) - .and_then(|r| r.map_err(acp::Error::from)) + .flatten_acp() { Ok(()) => { responder @@ -3317,8 +3392,7 @@ fn handle_release_terminal( .update(cx, |thread, cx| { thread.release_terminal(args.terminal_id, cx) }) - .map_err(acp::Error::from) - .and_then(|r| r.map_err(acp::Error::from)) + .flatten_acp() { Ok(()) => { responder @@ -3341,15 +3415,14 @@ fn handle_terminal_output( }; match thread - .read_with(cx, |thread, cx| -> Result<_, anyhow::Error> { + .read_with(cx, |thread, cx| -> anyhow::Result<_> { let out = thread .terminal(args.terminal_id)? .read(cx) .current_output(cx); Ok(out) }) - .map_err(acp::Error::from) - .and_then(|r| r.map_err(acp::Error::from)) + .flatten_acp() { Ok(output) => { responder.respond(output).log_err(); @@ -3375,8 +3448,7 @@ fn handle_wait_for_terminal_exit( .update(cx, |thread, cx| { anyhow::Ok(thread.terminal(args.terminal_id)?.read(cx).wait_for_exit()) }) - .map_err(acp::Error::from)? - .map_err(acp::Error::from)? + .flatten_acp()? .await; Ok(exit_status) } diff --git a/crates/agent_ui/src/thread_history.rs b/crates/agent_ui/src/thread_history.rs deleted file mode 100644 index 58b954eab6b8ed..00000000000000 --- a/crates/agent_ui/src/thread_history.rs +++ /dev/null @@ -1,772 +0,0 @@ -use acp_thread::{AgentSessionInfo, AgentSessionList, AgentSessionListRequest, SessionListUpdate}; -use agent_client_protocol::schema as acp; -use gpui::{App, Task}; -use std::rc::Rc; -use ui::prelude::*; - -pub struct ThreadHistory { - session_list: Rc, - sessions: Vec, - _refresh_task: Task<()>, - _watch_task: Option>, -} - -impl ThreadHistory { - pub fn new(session_list: Rc, cx: &mut Context) -> Self { - let mut this = Self { - session_list, - sessions: Vec::new(), - _refresh_task: Task::ready(()), - _watch_task: None, - }; - - this.start_watching(cx); - this - } - - #[cfg(any(test, feature = "test-support"))] - pub fn set_session_list( - &mut self, - session_list: Rc, - cx: &mut Context, - ) { - if Rc::ptr_eq(&self.session_list, &session_list) { - return; - } - - self.session_list = session_list; - self.sessions.clear(); - self._refresh_task = Task::ready(()); - self.start_watching(cx); - } - - fn start_watching(&mut self, cx: &mut Context) { - let Some(rx) = self.session_list.watch(cx) else { - self._watch_task = None; - self.refresh_sessions(false, cx); - return; - }; - self.session_list.notify_refresh(); - - self._watch_task = Some(cx.spawn(async move |this, cx| { - while let Ok(first_update) = rx.recv().await { - let mut updates = vec![first_update]; - while let Ok(update) = rx.try_recv() { - updates.push(update); - } - - this.update(cx, |this, cx| { - let needs_refresh = updates - .iter() - .any(|u| matches!(u, SessionListUpdate::Refresh)); - - if needs_refresh { - this.refresh_sessions(false, cx); - } else { - for update in updates { - if let SessionListUpdate::SessionInfo { session_id, update } = update { - this.apply_info_update(session_id, update, cx); - } - } - } - }) - .ok(); - } - })); - } - - pub(crate) fn refresh_full_history(&mut self, cx: &mut Context) { - self.refresh_sessions(true, cx); - } - - fn apply_info_update( - &mut self, - session_id: acp::SessionId, - info_update: acp::SessionInfoUpdate, - cx: &mut Context, - ) { - let Some(session) = self - .sessions - .iter_mut() - .find(|s| s.session_id == session_id) - else { - return; - }; - - match info_update.title { - acp::MaybeUndefined::Value(title) => { - session.title = Some(title.into()); - } - acp::MaybeUndefined::Null => { - session.title = None; - } - acp::MaybeUndefined::Undefined => {} - } - match info_update.updated_at { - acp::MaybeUndefined::Value(date_str) => { - if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(&date_str) { - session.updated_at = Some(dt.with_timezone(&chrono::Utc)); - } - } - acp::MaybeUndefined::Null => { - session.updated_at = None; - } - acp::MaybeUndefined::Undefined => {} - } - if let Some(meta) = info_update.meta { - session.meta = Some(meta); - } - - cx.notify(); - } - - fn refresh_sessions(&mut self, load_all_pages: bool, cx: &mut Context) { - let session_list = self.session_list.clone(); - - self._refresh_task = cx.spawn(async move |this, cx| { - let mut cursor: Option = None; - let mut is_first_page = true; - - loop { - let request = AgentSessionListRequest { - cursor: cursor.clone(), - ..Default::default() - }; - let task = cx.update(|cx| session_list.list_sessions(request, cx)); - let response = match task.await { - Ok(response) => response, - Err(error) => { - log::error!("Failed to load session history: {error:#}"); - return; - } - }; - - let acp_thread::AgentSessionListResponse { - sessions: page_sessions, - next_cursor, - .. - } = response; - - this.update(cx, |this, cx| { - if is_first_page { - this.sessions = page_sessions; - } else { - this.sessions.extend(page_sessions); - } - cx.notify(); - }) - .ok(); - - is_first_page = false; - if !load_all_pages { - break; - } - - match next_cursor { - Some(next_cursor) => { - if cursor.as_ref() == Some(&next_cursor) { - log::warn!( - "Session list pagination returned the same cursor; stopping to avoid a loop." - ); - break; - } - cursor = Some(next_cursor); - } - None => break, - } - } - }); - } - - pub(crate) fn is_empty(&self) -> bool { - self.sessions.is_empty() - } - - pub fn refresh(&mut self, _cx: &mut Context) { - self.session_list.notify_refresh(); - } - - pub fn session_for_id(&self, session_id: &acp::SessionId) -> Option { - self.sessions - .iter() - .find(|entry| &entry.session_id == session_id) - .cloned() - } - - pub(crate) fn sessions(&self) -> &[AgentSessionInfo] { - &self.sessions - } - - pub(crate) fn get_recent_sessions(&self, limit: usize) -> Vec { - self.sessions.iter().take(limit).cloned().collect() - } - - pub fn supports_delete(&self) -> bool { - self.session_list.supports_delete() - } - - pub(crate) fn delete_session( - &self, - session_id: &acp::SessionId, - cx: &mut App, - ) -> Task> { - self.session_list.delete_session(session_id, cx) - } - - pub(crate) fn delete_sessions(&self, cx: &mut App) -> Task> { - self.session_list.delete_sessions(cx) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use acp_thread::AgentSessionListResponse; - use gpui::TestAppContext; - use std::{ - any::Any, - sync::{Arc, Mutex}, - }; - - fn init_test(cx: &mut TestAppContext) { - cx.update(|cx| { - let settings_store = settings::SettingsStore::test(cx); - cx.set_global(settings_store); - theme_settings::init(theme::LoadThemes::JustBase, cx); - }); - } - - #[derive(Clone)] - struct TestSessionList { - sessions: Vec, - updates_tx: smol::channel::Sender, - updates_rx: smol::channel::Receiver, - } - - impl TestSessionList { - fn new(sessions: Vec) -> Self { - let (tx, rx) = smol::channel::unbounded(); - Self { - sessions, - updates_tx: tx, - updates_rx: rx, - } - } - - fn send_update(&self, update: SessionListUpdate) { - self.updates_tx.try_send(update).ok(); - } - } - - impl AgentSessionList for TestSessionList { - fn list_sessions( - &self, - _request: AgentSessionListRequest, - _cx: &mut App, - ) -> Task> { - Task::ready(Ok(AgentSessionListResponse::new(self.sessions.clone()))) - } - - fn watch(&self, _cx: &mut App) -> Option> { - Some(self.updates_rx.clone()) - } - - fn notify_refresh(&self) { - self.send_update(SessionListUpdate::Refresh); - } - - fn into_any(self: Rc) -> Rc { - self - } - } - - #[derive(Clone)] - struct PaginatedTestSessionList { - first_page_sessions: Vec, - second_page_sessions: Vec, - requested_cursors: Arc>>>, - async_responses: bool, - updates_tx: smol::channel::Sender, - updates_rx: smol::channel::Receiver, - } - - impl PaginatedTestSessionList { - fn new( - first_page_sessions: Vec, - second_page_sessions: Vec, - ) -> Self { - let (tx, rx) = smol::channel::unbounded(); - Self { - first_page_sessions, - second_page_sessions, - requested_cursors: Arc::new(Mutex::new(Vec::new())), - async_responses: false, - updates_tx: tx, - updates_rx: rx, - } - } - - fn with_async_responses(mut self) -> Self { - self.async_responses = true; - self - } - - fn requested_cursors(&self) -> Vec> { - self.requested_cursors.lock().unwrap().clone() - } - - fn clear_requested_cursors(&self) { - self.requested_cursors.lock().unwrap().clear() - } - - fn send_update(&self, update: SessionListUpdate) { - self.updates_tx.try_send(update).ok(); - } - } - - impl AgentSessionList for PaginatedTestSessionList { - fn list_sessions( - &self, - request: AgentSessionListRequest, - cx: &mut App, - ) -> Task> { - let requested_cursors = self.requested_cursors.clone(); - let first_page_sessions = self.first_page_sessions.clone(); - let second_page_sessions = self.second_page_sessions.clone(); - - let respond = move || { - requested_cursors - .lock() - .unwrap() - .push(request.cursor.clone()); - - match request.cursor.as_deref() { - None => AgentSessionListResponse { - sessions: first_page_sessions, - next_cursor: Some("page-2".to_string()), - meta: None, - }, - Some("page-2") => AgentSessionListResponse::new(second_page_sessions), - _ => AgentSessionListResponse::new(Vec::new()), - } - }; - - if self.async_responses { - cx.foreground_executor().spawn(async move { - smol::future::yield_now().await; - Ok(respond()) - }) - } else { - Task::ready(Ok(respond())) - } - } - - fn watch(&self, _cx: &mut App) -> Option> { - Some(self.updates_rx.clone()) - } - - fn notify_refresh(&self) { - self.send_update(SessionListUpdate::Refresh); - } - - fn into_any(self: Rc) -> Rc { - self - } - } - - fn test_session(session_id: &str, title: &str) -> AgentSessionInfo { - AgentSessionInfo { - session_id: acp::SessionId::new(session_id), - work_dirs: None, - title: Some(title.to_string().into()), - updated_at: None, - created_at: None, - meta: None, - } - } - - #[gpui::test] - async fn test_refresh_only_loads_first_page_by_default(cx: &mut TestAppContext) { - init_test(cx); - - let session_list = Rc::new(PaginatedTestSessionList::new( - vec![test_session("session-1", "First")], - vec![test_session("session-2", "Second")], - )); - - let history = cx.new(|cx| ThreadHistory::new(session_list.clone(), cx)); - cx.run_until_parked(); - - history.update(cx, |history, _cx| { - assert_eq!(history.sessions.len(), 1); - assert_eq!( - history.sessions[0].session_id, - acp::SessionId::new("session-1") - ); - }); - assert_eq!(session_list.requested_cursors(), vec![None]); - } - - #[gpui::test] - async fn test_enabling_full_pagination_loads_all_pages(cx: &mut TestAppContext) { - init_test(cx); - - let session_list = Rc::new(PaginatedTestSessionList::new( - vec![test_session("session-1", "First")], - vec![test_session("session-2", "Second")], - )); - - let history = cx.new(|cx| ThreadHistory::new(session_list.clone(), cx)); - cx.run_until_parked(); - session_list.clear_requested_cursors(); - - history.update(cx, |history, cx| history.refresh_full_history(cx)); - cx.run_until_parked(); - - history.update(cx, |history, _cx| { - assert_eq!(history.sessions.len(), 2); - assert_eq!( - history.sessions[0].session_id, - acp::SessionId::new("session-1") - ); - assert_eq!( - history.sessions[1].session_id, - acp::SessionId::new("session-2") - ); - }); - assert_eq!( - session_list.requested_cursors(), - vec![None, Some("page-2".to_string())] - ); - } - - #[gpui::test] - async fn test_standard_refresh_replaces_with_first_page_after_full_history_refresh( - cx: &mut TestAppContext, - ) { - init_test(cx); - - let session_list = Rc::new(PaginatedTestSessionList::new( - vec![test_session("session-1", "First")], - vec![test_session("session-2", "Second")], - )); - - let history = cx.new(|cx| ThreadHistory::new(session_list.clone(), cx)); - cx.run_until_parked(); - - history.update(cx, |history, cx| history.refresh_full_history(cx)); - cx.run_until_parked(); - session_list.clear_requested_cursors(); - - history.update(cx, |history, cx| { - history.refresh(cx); - }); - cx.run_until_parked(); - - history.update(cx, |history, _cx| { - assert_eq!(history.sessions.len(), 1); - assert_eq!( - history.sessions[0].session_id, - acp::SessionId::new("session-1") - ); - }); - assert_eq!(session_list.requested_cursors(), vec![None]); - } - - #[gpui::test] - async fn test_re_entering_full_pagination_reloads_all_pages(cx: &mut TestAppContext) { - init_test(cx); - - let session_list = Rc::new(PaginatedTestSessionList::new( - vec![test_session("session-1", "First")], - vec![test_session("session-2", "Second")], - )); - - let history = cx.new(|cx| ThreadHistory::new(session_list.clone(), cx)); - cx.run_until_parked(); - - history.update(cx, |history, cx| history.refresh_full_history(cx)); - cx.run_until_parked(); - session_list.clear_requested_cursors(); - - history.update(cx, |history, cx| history.refresh_full_history(cx)); - cx.run_until_parked(); - - history.update(cx, |history, _cx| { - assert_eq!(history.sessions.len(), 2); - }); - assert_eq!( - session_list.requested_cursors(), - vec![None, Some("page-2".to_string())] - ); - } - - #[gpui::test] - async fn test_partial_refresh_batch_drops_non_first_page_sessions(cx: &mut TestAppContext) { - init_test(cx); - - let second_page_session_id = acp::SessionId::new("session-2"); - let session_list = Rc::new(PaginatedTestSessionList::new( - vec![test_session("session-1", "First")], - vec![test_session("session-2", "Second")], - )); - - let history = cx.new(|cx| ThreadHistory::new(session_list.clone(), cx)); - cx.run_until_parked(); - - history.update(cx, |history, cx| history.refresh_full_history(cx)); - cx.run_until_parked(); - - session_list.clear_requested_cursors(); - - session_list.send_update(SessionListUpdate::SessionInfo { - session_id: second_page_session_id.clone(), - update: acp::SessionInfoUpdate::new().title("Updated Second"), - }); - session_list.send_update(SessionListUpdate::Refresh); - cx.run_until_parked(); - - history.update(cx, |history, _cx| { - assert_eq!(history.sessions.len(), 1); - assert_eq!( - history.sessions[0].session_id, - acp::SessionId::new("session-1") - ); - assert!( - history - .sessions - .iter() - .all(|session| session.session_id != second_page_session_id) - ); - }); - assert_eq!(session_list.requested_cursors(), vec![None]); - } - - #[gpui::test] - async fn test_full_pagination_works_with_async_page_fetches(cx: &mut TestAppContext) { - init_test(cx); - - let session_list = Rc::new( - PaginatedTestSessionList::new( - vec![test_session("session-1", "First")], - vec![test_session("session-2", "Second")], - ) - .with_async_responses(), - ); - - let history = cx.new(|cx| ThreadHistory::new(session_list.clone(), cx)); - cx.run_until_parked(); - session_list.clear_requested_cursors(); - - history.update(cx, |history, cx| history.refresh_full_history(cx)); - cx.run_until_parked(); - - history.update(cx, |history, _cx| { - assert_eq!(history.sessions.len(), 2); - }); - assert_eq!( - session_list.requested_cursors(), - vec![None, Some("page-2".to_string())] - ); - } - - #[gpui::test] - async fn test_apply_info_update_title(cx: &mut TestAppContext) { - init_test(cx); - - let session_id = acp::SessionId::new("test-session"); - let sessions = vec![AgentSessionInfo { - session_id: session_id.clone(), - work_dirs: None, - title: Some("Original Title".into()), - updated_at: None, - created_at: None, - meta: None, - }]; - let session_list = Rc::new(TestSessionList::new(sessions)); - - let history = cx.new(|cx| ThreadHistory::new(session_list.clone(), cx)); - cx.run_until_parked(); - - session_list.send_update(SessionListUpdate::SessionInfo { - session_id: session_id.clone(), - update: acp::SessionInfoUpdate::new().title("New Title"), - }); - cx.run_until_parked(); - - history.update(cx, |history, _cx| { - let session = history.sessions.iter().find(|s| s.session_id == session_id); - assert_eq!( - session.unwrap().title.as_ref().map(|s| s.as_ref()), - Some("New Title") - ); - }); - } - - #[gpui::test] - async fn test_apply_info_update_clears_title_with_null(cx: &mut TestAppContext) { - init_test(cx); - - let session_id = acp::SessionId::new("test-session"); - let sessions = vec![AgentSessionInfo { - session_id: session_id.clone(), - work_dirs: None, - title: Some("Original Title".into()), - updated_at: None, - created_at: None, - meta: None, - }]; - let session_list = Rc::new(TestSessionList::new(sessions)); - - let history = cx.new(|cx| ThreadHistory::new(session_list.clone(), cx)); - cx.run_until_parked(); - - session_list.send_update(SessionListUpdate::SessionInfo { - session_id: session_id.clone(), - update: acp::SessionInfoUpdate::new().title(None::), - }); - cx.run_until_parked(); - - history.update(cx, |history, _cx| { - let session = history.sessions.iter().find(|s| s.session_id == session_id); - assert_eq!(session.unwrap().title, None); - }); - } - - #[gpui::test] - async fn test_apply_info_update_ignores_undefined_fields(cx: &mut TestAppContext) { - init_test(cx); - - let session_id = acp::SessionId::new("test-session"); - let sessions = vec![AgentSessionInfo { - session_id: session_id.clone(), - work_dirs: None, - title: Some("Original Title".into()), - updated_at: None, - created_at: None, - meta: None, - }]; - let session_list = Rc::new(TestSessionList::new(sessions)); - - let history = cx.new(|cx| ThreadHistory::new(session_list.clone(), cx)); - cx.run_until_parked(); - - session_list.send_update(SessionListUpdate::SessionInfo { - session_id: session_id.clone(), - update: acp::SessionInfoUpdate::new(), - }); - cx.run_until_parked(); - - history.update(cx, |history, _cx| { - let session = history.sessions.iter().find(|s| s.session_id == session_id); - assert_eq!( - session.unwrap().title.as_ref().map(|s| s.as_ref()), - Some("Original Title") - ); - }); - } - - #[gpui::test] - async fn test_multiple_info_updates_applied_in_order(cx: &mut TestAppContext) { - init_test(cx); - - let session_id = acp::SessionId::new("test-session"); - let sessions = vec![AgentSessionInfo { - session_id: session_id.clone(), - work_dirs: None, - title: None, - updated_at: None, - created_at: None, - meta: None, - }]; - let session_list = Rc::new(TestSessionList::new(sessions)); - - let history = cx.new(|cx| ThreadHistory::new(session_list.clone(), cx)); - cx.run_until_parked(); - - session_list.send_update(SessionListUpdate::SessionInfo { - session_id: session_id.clone(), - update: acp::SessionInfoUpdate::new().title("First Title"), - }); - session_list.send_update(SessionListUpdate::SessionInfo { - session_id: session_id.clone(), - update: acp::SessionInfoUpdate::new().title("Second Title"), - }); - cx.run_until_parked(); - - history.update(cx, |history, _cx| { - let session = history.sessions.iter().find(|s| s.session_id == session_id); - assert_eq!( - session.unwrap().title.as_ref().map(|s| s.as_ref()), - Some("Second Title") - ); - }); - } - - #[gpui::test] - async fn test_refresh_supersedes_info_updates(cx: &mut TestAppContext) { - init_test(cx); - - let session_id = acp::SessionId::new("test-session"); - let sessions = vec![AgentSessionInfo { - session_id: session_id.clone(), - work_dirs: None, - title: Some("Server Title".into()), - updated_at: None, - created_at: None, - meta: None, - }]; - let session_list = Rc::new(TestSessionList::new(sessions)); - - let history = cx.new(|cx| ThreadHistory::new(session_list.clone(), cx)); - cx.run_until_parked(); - - session_list.send_update(SessionListUpdate::SessionInfo { - session_id: session_id.clone(), - update: acp::SessionInfoUpdate::new().title("Local Update"), - }); - session_list.send_update(SessionListUpdate::Refresh); - cx.run_until_parked(); - - history.update(cx, |history, _cx| { - let session = history.sessions.iter().find(|s| s.session_id == session_id); - assert_eq!( - session.unwrap().title.as_ref().map(|s| s.as_ref()), - Some("Server Title") - ); - }); - } - - #[gpui::test] - async fn test_info_update_for_unknown_session_is_ignored(cx: &mut TestAppContext) { - init_test(cx); - - let session_id = acp::SessionId::new("known-session"); - let sessions = vec![AgentSessionInfo { - session_id, - work_dirs: None, - title: Some("Original".into()), - updated_at: None, - created_at: None, - meta: None, - }]; - let session_list = Rc::new(TestSessionList::new(sessions)); - - let history = cx.new(|cx| ThreadHistory::new(session_list.clone(), cx)); - cx.run_until_parked(); - - session_list.send_update(SessionListUpdate::SessionInfo { - session_id: acp::SessionId::new("unknown-session"), - update: acp::SessionInfoUpdate::new().title("Should Be Ignored"), - }); - cx.run_until_parked(); - - history.update(cx, |history, _cx| { - assert_eq!(history.sessions.len(), 1); - assert_eq!( - history.sessions[0].title.as_ref().map(|s| s.as_ref()), - Some("Original") - ); - }); - } -}